From b8d36655b6c623ee429975fd1e0603efd584a35f Mon Sep 17 00:00:00 2001 From: jspngl Date: Mon, 16 Nov 2026 23:43:50 -0500 Subject: [PATCH 1/3] feat(api): add price lookup by date and price history endpoint --- .../CatalogItemPricesController.cs | 83 +++++++++++++++++++ .../MoissonMontreal.Api.http | 10 +++ .../Pricing/PriceService.cs | 49 +++++++++++ src/MoissonMontreal.Api/Program.cs | 2 + src/MoissonMontreal.Core/Dtos/PriceDto.cs | 18 ++++ .../Pricing/CatalogItemNotFoundException.cs | 14 ++++ .../Pricing/PriceHistory.cs | 25 ++++++ .../Pricing/PriceNotFoundException.cs | 47 +++++++++++ 8 files changed, 248 insertions(+) create mode 100644 src/MoissonMontreal.Api/Controllers/CatalogItemPricesController.cs create mode 100644 src/MoissonMontreal.Api/Pricing/PriceService.cs create mode 100644 src/MoissonMontreal.Core/Dtos/PriceDto.cs create mode 100644 src/MoissonMontreal.Core/Pricing/CatalogItemNotFoundException.cs create mode 100644 src/MoissonMontreal.Core/Pricing/PriceHistory.cs create mode 100644 src/MoissonMontreal.Core/Pricing/PriceNotFoundException.cs diff --git a/src/MoissonMontreal.Api/Controllers/CatalogItemPricesController.cs b/src/MoissonMontreal.Api/Controllers/CatalogItemPricesController.cs new file mode 100644 index 0000000..adc3bb1 --- /dev/null +++ b/src/MoissonMontreal.Api/Controllers/CatalogItemPricesController.cs @@ -0,0 +1,83 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; + +using MoissonMontreal.Api.Pricing; +using MoissonMontreal.Core.Dtos; +using MoissonMontreal.Core.Entities; +using MoissonMontreal.Core.Pricing; + +namespace MoissonMontreal.Api.Controllers; + +/// +/// Reads the price history of a catalog item and the price in effect on a given day. +/// +/// Service that reads the price grid. +[ApiController] +[Route("api/catalog-items/{catalogItemId:guid}/prices")] +public class CatalogItemPricesController(PriceService prices) : ControllerBase +{ + /// + /// Returns every price the catalog item has had, oldest effective date first. + /// + /// Identifier of the catalog item. + /// Token cancelled when the client aborts the request. + /// 200 with the price history (an empty list when the item has no price yet), or 404 when the item does not exist. + [HttpGet] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task> GetHistory(Guid catalogItemId, CancellationToken cancellationToken) + { + try + { + var item = await prices.GetPriceHistoryAsync(catalogItemId, cancellationToken); + return new PriceHistoryDto(item.Id, item.Name, item.Prices.Select(ToDto).ToList()); + } + catch (CatalogItemNotFoundException e) + { + return CatalogItemNotFound(e); + } + } + + /// + /// Returns the price of the catalog item in effect on a day: the one with the latest effective date on or before that day. + /// + /// Identifier of the catalog item. + /// Day to find the price for, in the format yyyy-MM-dd. + /// Token cancelled when the client aborts the request. + /// + /// 200 with the price, 404 when the item does not exist or has no price on that day, or 400 when the date is missing or invalid. + /// + [HttpGet("in-effect")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task> GetPriceInEffect( + Guid catalogItemId, + [FromQuery, BindRequired] DateOnly date, + CancellationToken cancellationToken) + { + try + { + return ToDto(await prices.GetPriceInEffectAsync(catalogItemId, date, cancellationToken)); + } + catch (CatalogItemNotFoundException e) + { + return CatalogItemNotFound(e); + } + catch (PriceNotFoundException e) + { + var problem = ProblemDetailsFactory.CreateProblemDetails( + HttpContext, StatusCodes.Status404NotFound, title: "No price on this date", detail: e.Message); + problem.Extensions["catalogItemId"] = e.CatalogItemId; + problem.Extensions["date"] = e.Date; + problem.Extensions["firstEffectiveDate"] = e.FirstEffectiveDate; + return NotFound(problem); + } + } + + private static PriceDto ToDto(Price price) => new(price.Id, price.UnitPrice, price.EffectiveDate, price.CreatedAt); + + private NotFoundObjectResult CatalogItemNotFound(CatalogItemNotFoundException e) => + NotFound(ProblemDetailsFactory.CreateProblemDetails( + HttpContext, StatusCodes.Status404NotFound, title: "Catalog item not found", detail: e.Message)); +} \ No newline at end of file diff --git a/src/MoissonMontreal.Api/MoissonMontreal.Api.http b/src/MoissonMontreal.Api/MoissonMontreal.Api.http index ed734ad..e346d38 100644 --- a/src/MoissonMontreal.Api/MoissonMontreal.Api.http +++ b/src/MoissonMontreal.Api/MoissonMontreal.Api.http @@ -2,3 +2,13 @@ GET {{MoissonMontreal.Api_HostAddress}}/health ### + +### Price history of a catalog item (replace the id; requires a bearer token) +GET {{MoissonMontreal.Api_HostAddress}}/api/catalog-items/00000000-0000-0000-0000-000000000000/prices +Authorization: Bearer {{token}} +### + +### Price of a catalog item in effect on a day +GET {{MoissonMontreal.Api_HostAddress}}/api/catalog-items/00000000-0000-0000-0000-000000000000/prices/in-effect?date=2026-11-15 +Authorization: Bearer {{token}} +### diff --git a/src/MoissonMontreal.Api/Pricing/PriceService.cs b/src/MoissonMontreal.Api/Pricing/PriceService.cs new file mode 100644 index 0000000..bc7688c --- /dev/null +++ b/src/MoissonMontreal.Api/Pricing/PriceService.cs @@ -0,0 +1,49 @@ +using Microsoft.EntityFrameworkCore; + +using MoissonMontreal.Api.Data; +using MoissonMontreal.Core.Entities; +using MoissonMontreal.Core.Pricing; + +namespace MoissonMontreal.Api.Pricing; + +/// +/// Reads the price grid: the price history of a catalog item and the price in effect on a given day. +/// The donation value calculation relies on . +/// +/// Database context of the request. +public class PriceService(MoissonDbContext db) +{ + /// + /// Returns the price of a catalog item in effect on a given day: the price with the latest effective date on or before that day. + /// + /// Identifier of the catalog item. + /// Day to find the price for, such as the date a donation was received. + /// Token that cancels the database query. + /// The price in effect on that day. + /// The catalog item does not exist. + /// The day is before the item's first price, or the item has no price. + public async Task GetPriceInEffectAsync(Guid catalogItemId, DateOnly date, CancellationToken cancellationToken = default) + { + var item = await LoadWithPricesAsync(catalogItemId, cancellationToken); + + return PriceHistory.FindPriceInEffect(item.Prices, date) + ?? throw new PriceNotFoundException(catalogItemId, date, item.Prices.FirstOrDefault()?.EffectiveDate); + } + + /// + /// Returns a catalog item with every price it has had, oldest effective date first. + /// + /// Identifier of the catalog item. + /// Token that cancels the database query. + /// The catalog item, with its prices sorted by effective date. The list is empty when the item has no price yet. + /// The catalog item does not exist. + public Task GetPriceHistoryAsync(Guid catalogItemId, CancellationToken cancellationToken = default) => + LoadWithPricesAsync(catalogItemId, cancellationToken); + + private async Task LoadWithPricesAsync(Guid catalogItemId, CancellationToken cancellationToken) => + await db.CatalogItems + .AsNoTracking() + .Include(c => c.Prices.OrderBy(p => p.EffectiveDate)) + .SingleOrDefaultAsync(c => c.Id == catalogItemId, cancellationToken) + ?? throw new CatalogItemNotFoundException(catalogItemId); +} \ No newline at end of file diff --git a/src/MoissonMontreal.Api/Program.cs b/src/MoissonMontreal.Api/Program.cs index e1733e8..d014690 100644 --- a/src/MoissonMontreal.Api/Program.cs +++ b/src/MoissonMontreal.Api/Program.cs @@ -4,6 +4,7 @@ using Microsoft.Identity.Web; using MoissonMontreal.Api.Data; using MoissonMontreal.Api.Authorization; +using MoissonMontreal.Api.Pricing; var builder = WebApplication.CreateBuilder(args); @@ -37,6 +38,7 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddControllers(); // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi diff --git a/src/MoissonMontreal.Core/Dtos/PriceDto.cs b/src/MoissonMontreal.Core/Dtos/PriceDto.cs new file mode 100644 index 0000000..e86e8ad --- /dev/null +++ b/src/MoissonMontreal.Core/Dtos/PriceDto.cs @@ -0,0 +1,18 @@ +namespace MoissonMontreal.Core.Dtos; + +/// +/// One price of a catalog item, as returned by the API. +/// +/// Identifier of the price. +/// Price of one unit, in dollars, with up to four decimal places. +/// First day the price applies. +/// Date and time the price was entered, in UTC. +public record PriceDto(Guid Id, decimal UnitPrice, DateOnly EffectiveDate, DateTimeOffset CreatedAt); + +/// +/// Every price a catalog item has had, oldest effective date first. +/// +/// Identifier of the catalog item. +/// Name of the catalog item, such as Bread. +/// Prices of the item, sorted by effective date. Empty when the item has no price yet. +public record PriceHistoryDto(Guid CatalogItemId, string CatalogItemName, IReadOnlyList Prices); \ No newline at end of file diff --git a/src/MoissonMontreal.Core/Pricing/CatalogItemNotFoundException.cs b/src/MoissonMontreal.Core/Pricing/CatalogItemNotFoundException.cs new file mode 100644 index 0000000..45cc48f --- /dev/null +++ b/src/MoissonMontreal.Core/Pricing/CatalogItemNotFoundException.cs @@ -0,0 +1,14 @@ +namespace MoissonMontreal.Core.Pricing; + +/// +/// Thrown when a price or a price history is asked for a catalog item that does not exist. +/// +/// Identifier that matches no catalog item. +public class CatalogItemNotFoundException(Guid catalogItemId) + : Exception($"Catalog item {catalogItemId} does not exist.") +{ + /// + /// Identifier that matches no catalog item. + /// + public Guid CatalogItemId { get; } = catalogItemId; +} \ No newline at end of file diff --git a/src/MoissonMontreal.Core/Pricing/PriceHistory.cs b/src/MoissonMontreal.Core/Pricing/PriceHistory.cs new file mode 100644 index 0000000..e636d55 --- /dev/null +++ b/src/MoissonMontreal.Core/Pricing/PriceHistory.cs @@ -0,0 +1,25 @@ +using MoissonMontreal.Core.Entities; + +namespace MoissonMontreal.Core.Pricing; + +/// +/// Rule that picks, in the price history of one catalog item, the price in effect on a given day. +/// +public static class PriceHistory +{ + /// + /// Returns the price with the latest effective date on or before . + /// A price applies from its effective date itself until the day before the next price starts. + /// + /// Every price of one catalog item, in any order. + /// Day to find the price for, such as the date a donation was received. + /// The price in effect on that day, or null when the day is before the first price or the item has no price. + public static Price? FindPriceInEffect(IEnumerable prices, DateOnly date) + { + ArgumentNullException.ThrowIfNull(prices); + + return prices + .Where(p => p.EffectiveDate <= date) + .MaxBy(p => p.EffectiveDate); + } +} \ No newline at end of file diff --git a/src/MoissonMontreal.Core/Pricing/PriceNotFoundException.cs b/src/MoissonMontreal.Core/Pricing/PriceNotFoundException.cs new file mode 100644 index 0000000..36cd778 --- /dev/null +++ b/src/MoissonMontreal.Core/Pricing/PriceNotFoundException.cs @@ -0,0 +1,47 @@ +using System.Globalization; + +namespace MoissonMontreal.Core.Pricing; + +/// +/// Thrown when a catalog item has no price in effect on the requested day, because the day is before its first price +/// or because the item has no price at all. The value of a donation must never be guessed in that case. +/// +public class PriceNotFoundException : Exception +{ + /// + /// Creates the error for a catalog item and a day. + /// + /// Identifier of the catalog item that has no price on that day. + /// Day a price was asked for. + /// Effective date of the item's first price, or null when the item has no price. + public PriceNotFoundException(Guid catalogItemId, DateOnly date, DateOnly? firstEffectiveDate) + : base(BuildMessage(catalogItemId, date, firstEffectiveDate)) + { + CatalogItemId = catalogItemId; + Date = date; + FirstEffectiveDate = firstEffectiveDate; + } + + /// + /// Identifier of the catalog item that has no price on that day. + /// + public Guid CatalogItemId { get; } + + /// + /// Day a price was asked for. + /// + public DateOnly Date { get; } + + /// + /// Effective date of the item's first price, or null when the item has no price at all. + /// + public DateOnly? FirstEffectiveDate { get; } + + private static string BuildMessage(Guid catalogItemId, DateOnly date, DateOnly? firstEffectiveDate) + { + var day = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + return firstEffectiveDate is { } first + ? $"Catalog item {catalogItemId} has no price on {day}: its first price starts on {first.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}." + : $"Catalog item {catalogItemId} has no price on {day}: it has no price at all."; + } +} \ No newline at end of file From 7fc99ff7131453b0161801a7b7369c8cbfe92691 Mon Sep 17 00:00:00 2001 From: jspngl Date: Mon, 16 Nov 2026 23:45:41 -0500 Subject: [PATCH 2/3] test(api): cover price lookup edge cases and the price history endpoint --- .../Api/CatalogItemPricesEndpointTests.cs | 163 +++++++++++++++++ .../Api/PriceServiceTests.cs | 169 ++++++++++++++++++ .../Pricing/PriceHistoryTests.cs | 103 +++++++++++ 3 files changed, 435 insertions(+) create mode 100644 tests/MoissonMontreal.Tests/Api/CatalogItemPricesEndpointTests.cs create mode 100644 tests/MoissonMontreal.Tests/Api/PriceServiceTests.cs create mode 100644 tests/MoissonMontreal.Tests/Pricing/PriceHistoryTests.cs diff --git a/tests/MoissonMontreal.Tests/Api/CatalogItemPricesEndpointTests.cs b/tests/MoissonMontreal.Tests/Api/CatalogItemPricesEndpointTests.cs new file mode 100644 index 0000000..7628d27 --- /dev/null +++ b/tests/MoissonMontreal.Tests/Api/CatalogItemPricesEndpointTests.cs @@ -0,0 +1,163 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; + +using MoissonMontreal.Core.Dtos; +using MoissonMontreal.Core.Entities; +using MoissonMontreal.Tests.Fixtures; + +namespace MoissonMontreal.Tests.Api; + +[Trait("Category", "Integration")] +public class CatalogItemPricesEndpointTests(PermissionsApiFactory factory) : IClassFixture +{ + private static readonly DateOnly November = new(2026, 11, 1); + private static readonly DateOnly December = new(2026, 12, 1); + + [Fact] + public async Task GetHistory_ReturnsEveryPrice_OldestFirst() + { + var breadId = await AddCatalogItemAsync("Pain", (4.25m, December), (4.00m, November)); + + var response = await GetAsync($"/api/catalog-items/{breadId}/prices"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var history = await response.Content.ReadFromJsonAsync(); + Assert.NotNull(history); + Assert.Equal((breadId, "Pain"), (history.CatalogItemId, history.CatalogItemName)); + Assert.Equal([November, December], history.Prices.Select(p => p.EffectiveDate)); + Assert.Equal([4.00m, 4.25m], history.Prices.Select(p => p.UnitPrice)); + Assert.All(history.Prices, p => Assert.NotEqual(Guid.Empty, p.Id)); + } + + [Fact] + public async Task GetHistory_ReturnsAnEmptyList_WhenTheItemHasNoPrice() + { + var applesId = await AddCatalogItemAsync("Pommes"); + + var history = await (await GetAsync($"/api/catalog-items/{applesId}/prices")).Content.ReadFromJsonAsync(); + + Assert.NotNull(history); + Assert.Empty(history.Prices); + } + + [Fact] + public async Task GetHistory_ReturnsNotFound_WhenTheItemDoesNotExist() + { + var response = await GetAsync($"/api/catalog-items/{Guid.NewGuid()}/prices"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Equal("Catalog item not found", (await ReadProblemAsync(response)).GetProperty("title").GetString()); + } + + [Fact] + public async Task GetHistory_ReturnsUnauthorized_WhenTokenIsMissing() + { + var breadId = await AddCatalogItemAsync("Pain", (4.00m, November)); + + var response = await GetAsync($"/api/catalog-items/{breadId}/prices", token: null); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Theory] + [InlineData("2026-11-01", 4.00)] + [InlineData("2026-11-30", 4.00)] + [InlineData("2026-12-01", 4.25)] + [InlineData("2027-03-10", 4.25)] + public async Task GetPriceInEffect_ReturnsThePriceThatAppliesOnTheDate(string date, decimal expected) + { + var breadId = await AddCatalogItemAsync("Pain", (4.00m, November), (4.25m, December)); + + var response = await GetAsync($"/api/catalog-items/{breadId}/prices/in-effect?date={date}"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var price = await response.Content.ReadFromJsonAsync(); + Assert.Equal(expected, price!.UnitPrice); + } + + [Fact] + public async Task GetPriceInEffect_ReturnsAClearError_WhenTheDateIsBeforeTheFirstPrice() + { + var breadId = await AddCatalogItemAsync("Pain", (4.00m, November)); + + var response = await GetAsync($"/api/catalog-items/{breadId}/prices/in-effect?date=2026-10-20"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + var problem = await ReadProblemAsync(response); + Assert.Equal("No price on this date", problem.GetProperty("title").GetString()); + Assert.Equal( + $"Catalog item {breadId} has no price on 2026-10-20: its first price starts on 2026-11-01.", + problem.GetProperty("detail").GetString()); + Assert.Equal("2026-11-01", problem.GetProperty("firstEffectiveDate").GetString()); + Assert.False(problem.TryGetProperty("unitPrice", out _)); + } + + [Fact] + public async Task GetPriceInEffect_ReturnsAClearError_WhenTheItemHasNoPrice() + { + var applesId = await AddCatalogItemAsync("Pommes"); + + var response = await GetAsync($"/api/catalog-items/{applesId}/prices/in-effect?date=2026-11-15"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + var problem = await ReadProblemAsync(response); + Assert.Equal(JsonValueKind.Null, problem.GetProperty("firstEffectiveDate").ValueKind); + } + + [Fact] + public async Task GetPriceInEffect_ReturnsNotFound_WhenTheItemDoesNotExist() + { + var response = await GetAsync($"/api/catalog-items/{Guid.NewGuid()}/prices/in-effect?date=2026-11-15"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Equal("Catalog item not found", (await ReadProblemAsync(response)).GetProperty("title").GetString()); + } + + [Theory] + [InlineData("")] + [InlineData("?date=")] + [InlineData("?date=not-a-date")] + [InlineData("?date=2026-13-01")] + public async Task GetPriceInEffect_ReturnsBadRequest_WhenTheDateIsMissingOrInvalid(string query) + { + var breadId = await AddCatalogItemAsync("Pain", (4.00m, November)); + + var response = await GetAsync($"/api/catalog-items/{breadId}/prices/in-effect{query}"); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + private async Task GetAsync(string path, string? token = "") + { + using var client = factory.CreateClient(); + using var request = new HttpRequestMessage(HttpMethod.Get, path); + if (token is not null) + { + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token == "" ? factory.CreateToken() : token); + } + + return await client.SendAsync(request); + } + + private static async Task ReadProblemAsync(HttpResponseMessage response) + { + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + return await response.Content.ReadFromJsonAsync(); + } + + private async Task AddCatalogItemAsync(string name, params (decimal UnitPrice, DateOnly EffectiveDate)[] prices) + { + await using var context = factory.CreateDbContext(); + var item = new CatalogItem { Name = name }; + foreach (var (unitPrice, effectiveDate) in prices) + { + item.Prices.Add(new Price { UnitPrice = unitPrice, EffectiveDate = effectiveDate }); + } + + context.CatalogItems.Add(item); + await context.SaveChangesAsync(); + return item.Id; + } +} \ No newline at end of file diff --git a/tests/MoissonMontreal.Tests/Api/PriceServiceTests.cs b/tests/MoissonMontreal.Tests/Api/PriceServiceTests.cs new file mode 100644 index 0000000..b3e66a0 --- /dev/null +++ b/tests/MoissonMontreal.Tests/Api/PriceServiceTests.cs @@ -0,0 +1,169 @@ +using Microsoft.EntityFrameworkCore; + +using MoissonMontreal.Api.Data; +using MoissonMontreal.Api.Pricing; +using MoissonMontreal.Core.Entities; +using MoissonMontreal.Core.Pricing; +using MoissonMontreal.Tests.Fixtures; + +namespace MoissonMontreal.Tests.Api; + +[Trait("Category", "Integration")] +public class PriceServiceTests(PostgresFixture postgres) : IClassFixture, IAsyncLifetime +{ + private static readonly DateOnly November = new(2026, 11, 1); + private static readonly DateOnly December = new(2026, 12, 1); + private static readonly DateOnly January = new(2027, 1, 1); + + public async Task InitializeAsync() + { + await using var context = CreateContext(); + await context.Database.MigrateAsync(); + } + + public Task DisposeAsync() => Task.CompletedTask; + + [Theory] + [InlineData("2026-11-01", 4.00)] + [InlineData("2026-11-15", 4.00)] + [InlineData("2026-11-30", 4.00)] + [InlineData("2026-12-01", 4.25)] + [InlineData("2027-01-01", 3.90)] + [InlineData("2027-03-10", 3.90)] + public async Task GetPriceInEffect_ReturnsThePriceThatAppliesOnTheDate(string date, decimal expected) + { + var breadId = await AddBreadWithHistoryAsync(); + + await using var context = CreateContext(); + var price = await new PriceService(context).GetPriceInEffectAsync(breadId, DateOnly.Parse(date)); + + Assert.Equal(expected, price.UnitPrice); + Assert.Equal(breadId, price.CatalogItemId); + } + + [Fact] + public async Task GetPriceInEffect_ReturnsThePrice_OnItsExactEffectiveDate() + { + var breadId = await AddBreadWithHistoryAsync(); + + await using var context = CreateContext(); + var price = await new PriceService(context).GetPriceInEffectAsync(breadId, December); + + Assert.Equal((4.25m, December), (price.UnitPrice, price.EffectiveDate)); + } + + [Fact] + public async Task GetPriceInEffect_Throws_WhenTheDateIsBeforeTheFirstPrice() + { + var breadId = await AddBreadWithHistoryAsync(); + var dayBefore = November.AddDays(-1); + + await using var context = CreateContext(); + var e = await Assert.ThrowsAsync( + () => new PriceService(context).GetPriceInEffectAsync(breadId, dayBefore)); + + Assert.Equal((breadId, dayBefore, November), (e.CatalogItemId, e.Date, e.FirstEffectiveDate)); + } + + [Fact] + public async Task GetPriceInEffect_Throws_WhenTheItemHasNoPrice() + { + var applesId = await AddCatalogItemAsync("Pommes"); + + await using var context = CreateContext(); + var e = await Assert.ThrowsAsync( + () => new PriceService(context).GetPriceInEffectAsync(applesId, December)); + + Assert.Null(e.FirstEffectiveDate); + } + + [Fact] + public async Task GetPriceInEffect_Throws_WhenTheItemDoesNotExist() + { + var unknownId = Guid.NewGuid(); + + await using var context = CreateContext(); + var e = await Assert.ThrowsAsync( + () => new PriceService(context).GetPriceInEffectAsync(unknownId, December)); + + Assert.Equal(unknownId, e.CatalogItemId); + } + + [Fact] + public async Task GetPriceInEffect_IgnoresThePricesOfOtherItems() + { + var breadId = await AddBreadWithHistoryAsync(); + var applesId = await AddCatalogItemAsync("Pommes"); + await AddPriceAsync(applesId, 2.49m, December); + + await using var context = CreateContext(); + var service = new PriceService(context); + + Assert.Equal(4.00m, (await service.GetPriceInEffectAsync(breadId, December.AddDays(-1))).UnitPrice); + await Assert.ThrowsAsync(() => service.GetPriceInEffectAsync(applesId, November)); + } + + [Fact] + public async Task GetPriceHistory_ReturnsEveryPrice_OldestFirst() + { + var itemId = await AddCatalogItemAsync("Pain"); + await AddPriceAsync(itemId, 3.90m, January); + await AddPriceAsync(itemId, 4.00m, November); + await AddPriceAsync(itemId, 4.25m, December); + + await using var context = CreateContext(); + var item = await new PriceService(context).GetPriceHistoryAsync(itemId); + + Assert.Equal("Pain", item.Name); + Assert.Equal([November, December, January], item.Prices.Select(p => p.EffectiveDate)); + Assert.Equal([4.00m, 4.25m, 3.90m], item.Prices.Select(p => p.UnitPrice)); + } + + [Fact] + public async Task GetPriceHistory_ReturnsAnEmptyList_WhenTheItemHasNoPrice() + { + var applesId = await AddCatalogItemAsync("Pommes"); + + await using var context = CreateContext(); + var item = await new PriceService(context).GetPriceHistoryAsync(applesId); + + Assert.Empty(item.Prices); + } + + [Fact] + public async Task GetPriceHistory_Throws_WhenTheItemDoesNotExist() + { + await using var context = CreateContext(); + + await Assert.ThrowsAsync( + () => new PriceService(context).GetPriceHistoryAsync(Guid.NewGuid())); + } + + private async Task AddBreadWithHistoryAsync() + { + var breadId = await AddCatalogItemAsync("Pain"); + await AddPriceAsync(breadId, 4.00m, November); + await AddPriceAsync(breadId, 4.25m, December); + await AddPriceAsync(breadId, 3.90m, January); + return breadId; + } + + private async Task AddCatalogItemAsync(string name) + { + await using var context = CreateContext(); + var item = new CatalogItem { Name = name }; + context.CatalogItems.Add(item); + await context.SaveChangesAsync(); + return item.Id; + } + + private async Task AddPriceAsync(Guid catalogItemId, decimal unitPrice, DateOnly effectiveDate) + { + await using var context = CreateContext(); + context.Prices.Add(new Price { CatalogItemId = catalogItemId, UnitPrice = unitPrice, EffectiveDate = effectiveDate }); + await context.SaveChangesAsync(); + } + + private MoissonDbContext CreateContext() => + new(new DbContextOptionsBuilder().UseNpgsql(postgres.ConnectionString).Options); +} \ No newline at end of file diff --git a/tests/MoissonMontreal.Tests/Pricing/PriceHistoryTests.cs b/tests/MoissonMontreal.Tests/Pricing/PriceHistoryTests.cs new file mode 100644 index 0000000..d454ac0 --- /dev/null +++ b/tests/MoissonMontreal.Tests/Pricing/PriceHistoryTests.cs @@ -0,0 +1,103 @@ +using MoissonMontreal.Core.Entities; +using MoissonMontreal.Core.Pricing; + +namespace MoissonMontreal.Tests.Pricing; + +public class PriceHistoryTests +{ + // Bread history from docs/database/prices.md. + private static readonly Price November = NewPrice(4.00m, new DateOnly(2026, 11, 1)); + private static readonly Price December = NewPrice(4.25m, new DateOnly(2026, 12, 1)); + private static readonly Price January = NewPrice(3.90m, new DateOnly(2027, 1, 1)); + private static readonly Price[] Bread = [November, December, January]; + + public static TheoryData DatesAndExpectedPrices() => new() + { + { new DateOnly(2026, 11, 1), 4.00m }, // exact effective date of the first price + { new DateOnly(2026, 11, 15), 4.00m }, // between two prices + { new DateOnly(2026, 11, 30), 4.00m }, // last day before the next price + { new DateOnly(2026, 12, 1), 4.25m }, // exact effective date of a later price + { new DateOnly(2026, 12, 31), 4.25m }, + { new DateOnly(2027, 1, 1), 3.90m }, // exact effective date of the latest price + { new DateOnly(2027, 3, 10), 3.90m }, // after the latest price + { new DateOnly(2099, 12, 31), 3.90m }, // far in the future + }; + + [Theory] + [MemberData(nameof(DatesAndExpectedPrices))] + public void FindPriceInEffect_ReturnsTheLatestPriceOnOrBeforeTheDate(DateOnly date, decimal expected) + { + var price = PriceHistory.FindPriceInEffect(Bread, date); + + Assert.NotNull(price); + Assert.Equal(expected, price.UnitPrice); + } + + [Theory] + [InlineData(2026, 10, 31)] // the day before the first price + [InlineData(2026, 10, 20)] + [InlineData(1, 1, 1)] + public void FindPriceInEffect_ReturnsNull_WhenTheDateIsBeforeTheFirstPrice(int year, int month, int day) + { + Assert.Null(PriceHistory.FindPriceInEffect(Bread, new DateOnly(year, month, day))); + } + + [Fact] + public void FindPriceInEffect_ReturnsNull_WhenThereIsNoPrice() + { + Assert.Null(PriceHistory.FindPriceInEffect([], new DateOnly(2026, 11, 15))); + } + + [Fact] + public void FindPriceInEffect_DoesNotDependOnTheOrderOfThePrices() + { + Price[] shuffled = [January, November, December]; + + Assert.Same(December, PriceHistory.FindPriceInEffect(shuffled, new DateOnly(2026, 12, 15))); + Assert.Same(November, PriceHistory.FindPriceInEffect(shuffled, new DateOnly(2026, 11, 15))); + } + + [Fact] + public void FindPriceInEffect_ReturnsTheOnlyPrice_FromItsEffectiveDate() + { + Price[] single = [November]; + + Assert.Same(November, PriceHistory.FindPriceInEffect(single, new DateOnly(2026, 11, 1))); + Assert.Null(PriceHistory.FindPriceInEffect(single, new DateOnly(2026, 10, 31))); + } + + [Fact] + public void FindPriceInEffect_Throws_WhenPricesIsNull() + { + Assert.Throws(() => PriceHistory.FindPriceInEffect(null!, new DateOnly(2026, 11, 15))); + } + + [Fact] + public void PriceNotFoundException_NamesTheFirstEffectiveDate() + { + var id = Guid.NewGuid(); + + var e = new PriceNotFoundException(id, new DateOnly(2026, 10, 20), new DateOnly(2026, 11, 1)); + + Assert.Equal($"Catalog item {id} has no price on 2026-10-20: its first price starts on 2026-11-01.", e.Message); + Assert.Equal((id, new DateOnly(2026, 10, 20), new DateOnly(2026, 11, 1)), (e.CatalogItemId, e.Date, e.FirstEffectiveDate)); + } + + [Fact] + public void PriceNotFoundException_SaysWhenTheItemHasNoPrice() + { + var id = Guid.NewGuid(); + + var e = new PriceNotFoundException(id, new DateOnly(2026, 11, 15), null); + + Assert.Equal($"Catalog item {id} has no price on 2026-11-15: it has no price at all.", e.Message); + Assert.Null(e.FirstEffectiveDate); + } + + private static Price NewPrice(decimal unitPrice, DateOnly effectiveDate) => new() + { + Id = Guid.NewGuid(), + UnitPrice = unitPrice, + EffectiveDate = effectiveDate, + }; +} \ No newline at end of file From ec1a038fc982b3bab0e50b74a174766ebfb303ec Mon Sep 17 00:00:00 2001 From: jspngl Date: Mon, 16 Nov 2026 23:46:01 -0500 Subject: [PATCH 3/3] docs(api): explain how a price is looked up for a date --- docs/database/prices.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/docs/database/prices.md b/docs/database/prices.md index 9de707d..e265164 100644 --- a/docs/database/prices.md +++ b/docs/database/prices.md @@ -67,7 +67,27 @@ The price that applies on a given day is the one with the latest effective date | 2027-03-10 | $3.90 | | 2026-10-20 | None, since it is before the first price. The app must show a clear error instead of guessing. | -Looking up the price for a date is done by the app, in issue #25. +### Looking up a price in the app + +The app looks up the price for a date with `PriceService.GetPriceInEffectAsync` ([PriceService.cs](../../src/MoissonMontreal.Api/Pricing/PriceService.cs)). The rule itself is in `PriceHistory.FindPriceInEffect` ([PriceHistory.cs](../../src/MoissonMontreal.Core/Pricing/PriceHistory.cs)), so it is written in one place only. + +| Situation | What the app does | +| --- | --- | +| A price applies on that day | Returns that price | +| The day is before the first price | Throws `PriceNotFoundException`, which gives the first effective date of the item | +| The item has no price at all | Throws `PriceNotFoundException`, with no first effective date | +| The catalog item does not exist | Throws `CatalogItemNotFoundException` | + +The app never falls back to another price, such as the first or the closest one, so a donation is never valued with a wrong price. + +The API exposes the same information: + +| Request | Answer | +| --- | --- | +| `GET /api/catalog-items/{id}/prices` | 200 with every price of the item, oldest effective date first. The list is empty when the item has no price yet. 404 when the item does not exist. | +| `GET /api/catalog-items/{id}/prices/in-effect?date=2026-11-15` | 200 with the price in effect on that day. 404 with a clear message when the item does not exist or has no price on that day (the answer then includes `firstEffectiveDate`). 400 when the date is missing or is not a valid `yyyy-MM-dd` date. | + +Both requests need a signed-in employee (a valid token with the `access_as_user` scope), like every other request of the API. ## Prices on the grid and prices on receipts