Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion docs/database/prices.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,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. |

Any user of the tenant with a valid token (with the `access_as_user` scope) can read prices. No permission is checked, so the person does not need to have been added to the app.

## Prices on the grid and prices on receipts

Expand Down
83 changes: 83 additions & 0 deletions src/MoissonMontreal.Api/Controllers/CatalogItemPricesController.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Reads the price history of a catalog item and the price in effect on a given day.
/// </summary>
/// <param name="prices">Service that reads the price grid.</param>
[ApiController]
[Route("api/catalog-items/{catalogItemId:guid}/prices")]
public class CatalogItemPricesController(PriceService prices) : ControllerBase
{
/// <summary>
/// Returns every price the catalog item has had, oldest effective date first.
/// </summary>
/// <param name="catalogItemId">Identifier of the catalog item.</param>
/// <param name="cancellationToken">Token cancelled when the client aborts the request.</param>
/// <returns>200 with the price history (an empty list when the item has no price yet), or 404 when the item does not exist.</returns>
[HttpGet]
[ProducesResponseType<PriceHistoryDto>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<ActionResult<PriceHistoryDto>> 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);
}
}

/// <summary>
/// Returns the price of the catalog item in effect on a day: the one with the latest effective date on or before that day.
/// </summary>
/// <param name="catalogItemId">Identifier of the catalog item.</param>
/// <param name="date">Day to find the price for, in the format yyyy-MM-dd.</param>
/// <param name="cancellationToken">Token cancelled when the client aborts the request.</param>
/// <returns>
/// 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.
/// </returns>
[HttpGet("in-effect")]
[ProducesResponseType<PriceDto>(StatusCodes.Status200OK)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<ActionResult<PriceDto>> 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));
}
10 changes: 10 additions & 0 deletions src/MoissonMontreal.Api/MoissonMontreal.Api.http
Original file line number Diff line number Diff line change
Expand Up @@ -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}}
###
49 changes: 49 additions & 0 deletions src/MoissonMontreal.Api/Pricing/PriceService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using Microsoft.EntityFrameworkCore;

using MoissonMontreal.Api.Data;
using MoissonMontreal.Core.Entities;
using MoissonMontreal.Core.Pricing;

namespace MoissonMontreal.Api.Pricing;

/// <summary>
/// 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 <see cref="GetPriceInEffectAsync"/>.
/// </summary>
/// <param name="db">Database context of the request.</param>
public class PriceService(MoissonDbContext db)
{
/// <summary>
/// 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.
/// </summary>
/// <param name="catalogItemId">Identifier of the catalog item.</param>
/// <param name="date">Day to find the price for, such as the date a donation was received.</param>
/// <param name="cancellationToken">Token that cancels the database query.</param>
/// <returns>The price in effect on that day.</returns>
/// <exception cref="CatalogItemNotFoundException">The catalog item does not exist.</exception>
/// <exception cref="PriceNotFoundException">The day is before the item's first price, or the item has no price.</exception>
public async Task<Price> GetPriceInEffectAsync(Guid catalogItemId, DateOnly date, CancellationToken cancellationToken = default)
Comment thread
lauriechammah marked this conversation as resolved.
Resolved
{
var item = await LoadWithPricesAsync(catalogItemId, cancellationToken);

return PriceHistory.FindPriceInEffect(item.Prices, date)
?? throw new PriceNotFoundException(catalogItemId, date, PriceHistory.FindFirstEffectiveDate(item.Prices));
}

/// <summary>
/// Returns a catalog item with every price it has had, oldest effective date first.
/// </summary>
/// <param name="catalogItemId">Identifier of the catalog item.</param>
/// <param name="cancellationToken">Token that cancels the database query.</param>
/// <returns>The catalog item, with its prices sorted by effective date. The list is empty when the item has no price yet.</returns>
/// <exception cref="CatalogItemNotFoundException">The catalog item does not exist.</exception>
public Task<CatalogItem> GetPriceHistoryAsync(Guid catalogItemId, CancellationToken cancellationToken = default) =>
LoadWithPricesAsync(catalogItemId, cancellationToken);

private async Task<CatalogItem> 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);
}
2 changes: 2 additions & 0 deletions src/MoissonMontreal.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -37,6 +38,7 @@

builder.Services.AddScoped<UserLookupService>();
builder.Services.AddScoped<IAuthorizationHandler, PermissionHandler>();
builder.Services.AddScoped<PriceService>();

builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
Expand Down
18 changes: 18 additions & 0 deletions src/MoissonMontreal.Core/Dtos/PriceDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace MoissonMontreal.Core.Dtos;

/// <summary>
/// One price of a catalog item, as returned by the API.
/// </summary>
/// <param name="Id">Identifier of the price.</param>
/// <param name="UnitPrice">Price of one unit, in dollars, with up to four decimal places.</param>
/// <param name="EffectiveDate">First day the price applies.</param>
/// <param name="CreatedAt">Date and time the price was entered, in UTC.</param>
public record PriceDto(Guid Id, decimal UnitPrice, DateOnly EffectiveDate, DateTimeOffset CreatedAt);

/// <summary>
/// Every price a catalog item has had, oldest effective date first.
/// </summary>
/// <param name="CatalogItemId">Identifier of the catalog item.</param>
/// <param name="CatalogItemName">Name of the catalog item, such as Bread.</param>
/// <param name="Prices">Prices of the item, sorted by effective date. Empty when the item has no price yet.</param>
public record PriceHistoryDto(Guid CatalogItemId, string CatalogItemName, IReadOnlyList<PriceDto> Prices);
14 changes: 14 additions & 0 deletions src/MoissonMontreal.Core/Pricing/CatalogItemNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace MoissonMontreal.Core.Pricing;

/// <summary>
/// Thrown when a price or a price history is asked for a catalog item that does not exist.
/// </summary>
/// <param name="catalogItemId">Identifier that matches no catalog item.</param>
public class CatalogItemNotFoundException(Guid catalogItemId)
: Exception($"Catalog item {catalogItemId} does not exist.")
{
/// <summary>
/// Identifier that matches no catalog item.
/// </summary>
public Guid CatalogItemId { get; } = catalogItemId;
}
37 changes: 37 additions & 0 deletions src/MoissonMontreal.Core/Pricing/PriceHistory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using MoissonMontreal.Core.Entities;

namespace MoissonMontreal.Core.Pricing;

/// <summary>
/// Rule that picks, in the price history of one catalog item, the price in effect on a given day.
/// </summary>
public static class PriceHistory
{
/// <summary>
/// Returns the price with the latest effective date on or before <paramref name="date"/>.
/// A price applies from its effective date itself until the day before the next price starts.
/// </summary>
/// <param name="prices">Every price of one catalog item, in any order.</param>
/// <param name="date">Day to find the price for, such as the date a donation was received.</param>
/// <returns>The price in effect on that day, or <c>null</c> when the day is before the first price or the item has no price.</returns>
public static Price? FindPriceInEffect(IEnumerable<Price> prices, DateOnly date)
{
ArgumentNullException.ThrowIfNull(prices);

return prices
.Where(p => p.EffectiveDate <= date)
.MaxBy(p => p.EffectiveDate);
}

/// <summary>
/// Returns the earliest effective date in the price history of one catalog item.
/// </summary>
/// <param name="prices">Every price of one catalog item, in any order.</param>
/// <returns>The first effective date, or <c>null</c> when the item has no price.</returns>
public static DateOnly? FindFirstEffectiveDate(IEnumerable<Price> prices)
{
ArgumentNullException.ThrowIfNull(prices);

return prices.Min(p => (DateOnly?)p.EffectiveDate);
}
}
47 changes: 47 additions & 0 deletions src/MoissonMontreal.Core/Pricing/PriceNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System.Globalization;

namespace MoissonMontreal.Core.Pricing;

/// <summary>
/// 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.
/// </summary>
public class PriceNotFoundException : Exception
{
/// <summary>
/// Creates the error for a catalog item and a day.
/// </summary>
/// <param name="catalogItemId">Identifier of the catalog item that has no price on that day.</param>
/// <param name="date">Day a price was asked for.</param>
/// <param name="firstEffectiveDate">Effective date of the item's first price, or <c>null</c> when the item has no price.</param>
public PriceNotFoundException(Guid catalogItemId, DateOnly date, DateOnly? firstEffectiveDate)
: base(BuildMessage(catalogItemId, date, firstEffectiveDate))
{
CatalogItemId = catalogItemId;
Date = date;
FirstEffectiveDate = firstEffectiveDate;
}

/// <summary>
/// Identifier of the catalog item that has no price on that day.
/// </summary>
public Guid CatalogItemId { get; }

/// <summary>
/// Day a price was asked for.
/// </summary>
public DateOnly Date { get; }

/// <summary>
/// Effective date of the item's first price, or <c>null</c> when the item has no price at all.
/// </summary>
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.";
}
}
Loading
Loading