diff --git a/docs/database/catalog.md b/docs/database/catalog.md new file mode 100644 index 0000000..523b3b2 --- /dev/null +++ b/docs/database/catalog.md @@ -0,0 +1,58 @@ +# Food catalog + +The catalog is the list of foods Moisson Montréal can receive. Each row is one kind of food. A donation of that food points at the row, and the price grid stores the price of one unit over time. Accounting matches the row through its Business Central code. + +food_items is one donation: the donor, the quantity and the date. catalog_items is the food itself. + +## Diagram + +![Food catalog diagram](images/catalog.png) + +The columns in this picture are the catalog item. The quality class column is a link to the quality_classes table: it stores the class code, such as A, B or C. The full database diagram in [schema.md](schema.md) shows that link together with the price grid. + +## Tables + +### catalog_items + +One row per kind of food. The table was created for the price grid, and these columns complete it. + +- **id**: code that identifies the catalog item, assigned automatically +- **name**: name of the food, for example Pain +- **category**: group the food belongs to, for example Boulangerie +- **business_central_code**: code of this food in Business Central. Two catalog items cannot share a code +- **unit**: unit used to count the food, such as kg or caisse. Free text for now, until issue #28 decides how the price of one unit works +- **quality_class**: quality class of this food. It must be a class that exists, such as A, B or C. The class is stored on the catalog item +- **created_at**: date and time the item was added, stored in UTC +- **updated_at**: date and time of the last change, stored in UTC. Empty until the item is edited + +## Quality class + +The quality class belongs to the catalog item, so every donation of that food can use the same class. The classes and their percentages live in the quality_classes table. A catalog item can only use a class that is already there. + +A donation still keeps the quality class it was given, on food_items. That value is what a receipt uses. + +## Business Central code + +The code is how the catalog item is matched with the accounting system. The database rejects a second item with the same code. The comparison is exact, so `BC-PAIN` and `bc-pain` are two different codes. + +## Rules enforced by the database + +1. A name, a category, a Business Central code and a unit cannot be empty. +2. A Business Central code can belong to only one catalog item. +3. The quality class must be a quality class that exists. +4. A quality class cannot be deleted while a catalog item uses it. + +## API + +List, create and edit are available at `api/catalog-items`. Any signed-in employee can list the catalog. Creating or editing an item requires the ManagePriceGrid permission, so only an Admin can do it. Creating or editing an item with a Business Central code that is already used returns a conflict. A quality class that does not exist is refused. + +## Migration + +- Entity Framework migration: [20261117040905_AddCatalogItemDetails](../../src/MoissonMontreal.Api/Data/Migrations/20261117040905_AddCatalogItemDetails.cs) +- Equivalent SQL script: [0006_add_catalog_item_details.sql](sql/0006_add_catalog_item_details.sql) +- Table settings: [CatalogItemConfiguration.cs](../../src/MoissonMontreal.Api/Data/Configurations/CatalogItemConfiguration.cs) +- API: [CatalogItemsController.cs](../../src/MoissonMontreal.Api/Controllers/CatalogItemsController.cs) + +Catalog items that existed before this migration get placeholder values, so the new rules can be added: category `To classify`, Business Central code `TO-FIX-` followed by the item id, unit `unit` and quality class A. Fix these items by hand after the migration. + +The SQL script must be run after [0005_create_quality_classes.sql](sql/0005_create_quality_classes.sql). It records itself in the migration history, so Entity Framework will not apply it a second time. diff --git a/docs/database/images/catalog.png b/docs/database/images/catalog.png new file mode 100644 index 0000000..97d720e Binary files /dev/null and b/docs/database/images/catalog.png differ diff --git a/docs/database/prices.dbml b/docs/database/prices.dbml index 1769b88..c352757 100644 --- a/docs/database/prices.dbml +++ b/docs/database/prices.dbml @@ -8,17 +8,27 @@ Table catalog_items { id uuid [not null, default: `gen_random_uuid()`] name varchar(255) [not null] + category varchar(100) [not null] + business_central_code varchar(50) [not null, note: 'Unique code used to match the item in Business Central'] + unit varchar(20) [not null, note: 'Free text until the price of one unit is decided'] + quality_class varchar(1) [not null, note: 'Code of the quality class. The class lives on the catalog item'] created_at timestamptz [not null, default: `now()`, note: 'Stored in UTC'] + updated_at timestamptz [null, note: 'Stored in UTC, empty if never changed'] indexes { id [pk, name: 'pk_catalog_items'] + business_central_code [unique, name: 'ix_catalog_items_business_central_code'] + quality_class [name: 'ix_catalog_items_quality_class'] } checks { `length(name) > 0` [name: 'ck_catalog_items_name_not_empty'] + `length(category) > 0` [name: 'ck_catalog_items_category_not_empty'] + `length(business_central_code) > 0` [name: 'ck_catalog_items_business_central_code_not_empty'] + `length(unit) > 0` [name: 'ck_catalog_items_unit_not_empty'] } - Note: 'Types of food recognized by the app. Category, Business Central code, unit and quality come with #27' + Note: 'Types of food recognized by the app, with the Business Central code and the quality class' } Table prices { @@ -115,4 +125,6 @@ Ref fk_food_items_catalog_items_catalog_item_id: food_items.catalog_item_id > ca Ref fk_food_items_quality_classes_quality: food_items.quality > quality_classes.code [delete: restrict] +Ref fk_catalog_items_quality_classes_quality_class: catalog_items.quality_class > quality_classes.code [delete: restrict] + Ref fk_prices_catalog_items_catalog_item_id: prices.catalog_item_id > catalog_items.id [delete: restrict] diff --git a/docs/database/prices.md b/docs/database/prices.md index 9de707d..fc61dea 100644 --- a/docs/database/prices.md +++ b/docs/database/prices.md @@ -16,13 +16,16 @@ The donors and food_items tables come from an earlier step. They are shown in th One row per type of food, such as bread or apples. A donation of bread and the next donation of bread are two different rows in food_items, but they share one catalog item, and so one price history. -| Column | Meaning | -| --- | --- | -| id | Code that identifies the catalog item, assigned automatically | -| name | Name of the food. It cannot be empty. | -| created_at | Date and time the item was added, stored in UTC | +- **id**: code that identifies the catalog item, assigned automatically +- **name**: name of the food. It cannot be empty. +- **category**: group the food belongs to, for example Boulangerie +- **business_central_code**: code of this food in Business Central. Two catalog items cannot share a code +- **unit**: unit used to count the food, such as kg or caisse +- **quality_class**: quality class of this food. It must be a class that exists +- **created_at**: date and time the item was added, stored in UTC +- **updated_at**: date and time of the last change, stored in UTC. Empty until the item is edited -This is the smallest catalog the price grid needs. Issue #27 adds the category, the Business Central code (which will be unique), the unit and the quality to this same table. Until then, two catalog items can have the same name. +The category, the Business Central code, the unit and the quality class are described in [Food catalog](catalog.md). ### prices @@ -80,7 +83,7 @@ Adding a new price to the grid therefore never changes a receipt that already ex ## Units and precision -- A price is for one unit of the catalog item, for example 1 kg or 1 case. The unit itself is added to catalog_items in issue #27, following the decision of issue #28. +- A price is for one unit of the catalog item, for example 1 kg or 1 case. The unit is stored on the catalog item as free text until issue #28 decides how the price of one unit is defined. - unit_price keeps 4 decimal places, the same as receipt_items.unit_price, so a price can be copied onto a receipt without losing anything. - A price with more than 4 decimals is rounded half away from zero by the database. For example, $0.12345 is stored as $0.1235. - The largest price allowed is $99,999,999.9999. A larger value is refused. diff --git a/docs/database/quality-classes.dbml b/docs/database/quality-classes.dbml index 8016bc9..56f1ec3 100644 --- a/docs/database/quality-classes.dbml +++ b/docs/database/quality-classes.dbml @@ -77,17 +77,27 @@ Table food_items { Table catalog_items { id uuid [not null, default: `gen_random_uuid()`] name varchar(255) [not null] + category varchar(100) [not null] + business_central_code varchar(50) [not null, note: 'Unique code used to match the item in Business Central'] + unit varchar(20) [not null, note: 'Free text until the price of one unit is decided'] + quality_class varchar(1) [not null, note: 'Code of the quality class. The class lives on the catalog item'] created_at timestamptz [not null, default: `now()`, note: 'Stored in UTC'] + updated_at timestamptz [null, note: 'Stored in UTC, empty if never changed'] indexes { id [pk, name: 'pk_catalog_items'] + business_central_code [unique, name: 'ix_catalog_items_business_central_code'] + quality_class [name: 'ix_catalog_items_quality_class'] } checks { `length(name) > 0` [name: 'ck_catalog_items_name_not_empty'] + `length(category) > 0` [name: 'ck_catalog_items_category_not_empty'] + `length(business_central_code) > 0` [name: 'ck_catalog_items_business_central_code_not_empty'] + `length(unit) > 0` [name: 'ck_catalog_items_unit_not_empty'] } - Note: 'Types of food recognized by the app. Category, Business Central code, unit and quality come with #27' + Note: 'Types of food recognized by the app, with the Business Central code and the quality class' } Ref fk_food_items_donors_donor_id: food_items.donor_id > donors.id [delete: restrict] @@ -96,6 +106,8 @@ Ref fk_food_items_catalog_items_catalog_item_id: food_items.catalog_item_id > ca Ref fk_food_items_quality_classes_quality: food_items.quality > quality_classes.code [delete: restrict] +Ref fk_catalog_items_quality_classes_quality_class: catalog_items.quality_class > quality_classes.code [delete: restrict] + Records quality_classes(code, name, percentage, min_percentage, max_percentage) { 'A', 'Grocery quality', 100.00, 100.00, 100.00 'B', 'Imperfect', 50.00, 50.00, 75.00 diff --git a/docs/database/receipts.dbml b/docs/database/receipts.dbml index d09a3b9..6f40ae1 100644 --- a/docs/database/receipts.dbml +++ b/docs/database/receipts.dbml @@ -77,17 +77,27 @@ Table quality_classes { Table catalog_items { id uuid [not null, default: `gen_random_uuid()`] name varchar(255) [not null] + category varchar(100) [not null] + business_central_code varchar(50) [not null, note: 'Unique code used to match the item in Business Central'] + unit varchar(20) [not null, note: 'Free text until the price of one unit is decided'] + quality_class varchar(1) [not null, note: 'Code of the quality class. The class lives on the catalog item'] created_at timestamptz [not null, default: `now()`, note: 'Stored in UTC'] + updated_at timestamptz [null, note: 'Stored in UTC, empty if never changed'] indexes { id [pk, name: 'pk_catalog_items'] + business_central_code [unique, name: 'ix_catalog_items_business_central_code'] + quality_class [name: 'ix_catalog_items_quality_class'] } checks { `length(name) > 0` [name: 'ck_catalog_items_name_not_empty'] + `length(category) > 0` [name: 'ck_catalog_items_category_not_empty'] + `length(business_central_code) > 0` [name: 'ck_catalog_items_business_central_code_not_empty'] + `length(unit) > 0` [name: 'ck_catalog_items_unit_not_empty'] } - Note: 'Types of food recognized by the app. Category, Business Central code, unit and quality come with #27' + Note: 'Types of food recognized by the app, with the Business Central code and the quality class' } Table receipts { @@ -142,6 +152,8 @@ Ref fk_food_items_catalog_items_catalog_item_id: food_items.catalog_item_id > ca Ref fk_food_items_quality_classes_quality: food_items.quality > quality_classes.code [delete: restrict] +Ref fk_catalog_items_quality_classes_quality_class: catalog_items.quality_class > quality_classes.code [delete: restrict] + Ref fk_receipts_donors_donor_id: receipts.donor_id > donors.id [delete: restrict] Ref fk_receipt_items_receipts_receipt_id_donor_id: receipt_items.(receipt_id, donor_id) > receipts.(id, donor_id) [delete: cascade] diff --git a/docs/database/schema.dbml b/docs/database/schema.dbml index f826f64..18afbc7 100644 --- a/docs/database/schema.dbml +++ b/docs/database/schema.dbml @@ -1,7 +1,8 @@ // Full database schema of the Moisson Montreal receipt app // Paste this file into https://dbdiagram.io to render the diagram. // Matches the migrations 20261103000127_CreateUsersAndRoles, 20261105163138_CreateDonorsAndFoodItems, -// 20261107041912_CreateReceipts, 20261110175320_CreateCatalogItemsAndPrices and 20261112060008_CreateQualityClasses. +// 20261107041912_CreateReceipts, 20261110175320_CreateCatalogItemsAndPrices, +// 20261112060008_CreateQualityClasses and 20261117040905_AddCatalogItemDetails. Project moisson_montreal { database_type: 'PostgreSQL' @@ -164,17 +165,27 @@ Table receipt_items { Table catalog_items { id uuid [not null, default: `gen_random_uuid()`] name varchar(255) [not null] + category varchar(100) [not null] + business_central_code varchar(50) [not null, note: 'Unique code used to match the item in Business Central'] + unit varchar(20) [not null, note: 'Free text until the price of one unit is decided'] + quality_class varchar(1) [not null, note: 'Code of the quality class. The class lives on the catalog item'] created_at timestamptz [not null, default: `now()`, note: 'Stored in UTC'] + updated_at timestamptz [null, note: 'Stored in UTC, empty if never changed'] indexes { id [pk, name: 'pk_catalog_items'] + business_central_code [unique, name: 'ix_catalog_items_business_central_code'] + quality_class [name: 'ix_catalog_items_quality_class'] } checks { `length(name) > 0` [name: 'ck_catalog_items_name_not_empty'] + `length(category) > 0` [name: 'ck_catalog_items_category_not_empty'] + `length(business_central_code) > 0` [name: 'ck_catalog_items_business_central_code_not_empty'] + `length(unit) > 0` [name: 'ck_catalog_items_unit_not_empty'] } - Note: 'Types of food recognized by the app. Category, Business Central code, unit and quality come with #27' + Note: 'Types of food recognized by the app, with the Business Central code and the quality class' } Table prices { @@ -212,6 +223,8 @@ Ref fk_receipt_items_food_items_food_item_id_donor_id: receipt_items.(food_item_ Ref fk_prices_catalog_items_catalog_item_id: prices.catalog_item_id > catalog_items.id [delete: restrict] +Ref fk_catalog_items_quality_classes_quality_class: catalog_items.quality_class > quality_classes.code [delete: restrict] + TableGroup accounts { roles users diff --git a/docs/database/schema.md b/docs/database/schema.md index 19d6ddd..0e108f1 100644 --- a/docs/database/schema.md +++ b/docs/database/schema.md @@ -73,9 +73,9 @@ More detail: [Receipts and their prices](receipts.md). ### catalog_items -The types of food the app knows, such as bread or apples. A donation of bread and the next donation of bread are two different food items, but they share the same catalog item, and so the same price. For now a catalog item only has a name. Its category, Business Central code, unit and quality come with issue #27. +The types of food the app knows, such as bread or apples. A donation of bread and the next donation of bread are two different food items, but they share the same catalog item, and so the same price. Each catalog item has a name, a category, a unique Business Central code, a unit and a quality class. -More detail: [Price grid](prices.md). +More detail: [Food catalog](catalog.md) and [Price grid](prices.md). ### prices @@ -119,7 +119,7 @@ The database itself refuses anything that would break these rules, even if there - A food item cannot be deleted while it is on a receipt. - A role cannot be deleted while someone has it. - A catalog item cannot be deleted while it has prices or while a donation points to it. -- A quality class cannot be deleted while a food item uses it. +- A quality class cannot be deleted while a food item or a catalog item uses it. **Exact amounts** - All amounts are stored as exact decimal numbers, so no cent is lost along the way. @@ -130,11 +130,12 @@ The database itself refuses anything that would break these rules, even if there **Valid values** - A quantity and a price must be greater than zero. - A quality percentage must be between 0 and 100. -- A food item must have a quality class that exists. +- A food item and a catalog item must have a quality class that exists. - A quality class keeps a default percentage within its own range, and the range stays between 0 % and 100 %. - Two quality classes cannot have the same code or the same name, and a code is one capital letter from A to Z. - A receipt total cannot be negative. -- Donor names, food names, catalog item names and units cannot be empty. +- Donor names, food names, catalog item names, categories, Business Central codes and units cannot be empty. +- Two catalog items cannot have the same Business Central code. **Accounts** - Two employees cannot have the same email or the same Microsoft account. @@ -153,7 +154,6 @@ These parts of the project are planned in their own issues and will add tables l | Feature | Issue | | --- | --- | | Price lookup by date | #25 | -| Food catalog details: category, Business Central code, unit and quality | #27 | | Calculation of a donation's value | #30 | | Receipt statuses: prepared, approved at two levels, issued, cancelled and replaced | #31 | | Receipt numbering, unique and with no gaps | #32 | @@ -181,6 +181,7 @@ Each table comes from one of these migrations: | receipts, receipt_items | [20261107041912_CreateReceipts](../../src/MoissonMontreal.Api/Data/Migrations/20261107041912_CreateReceipts.cs) | [0003_create_receipts.sql](sql/0003_create_receipts.sql) | [receipts.md](receipts.md) | | catalog_items, prices | [20261110175320_CreateCatalogItemsAndPrices](../../src/MoissonMontreal.Api/Data/Migrations/20261110175320_CreateCatalogItemsAndPrices.cs) | [0004_create_catalog_items_and_prices.sql](sql/0004_create_catalog_items_and_prices.sql) | [prices.md](prices.md) | | quality_classes | [20261112060008_CreateQualityClasses](../../src/MoissonMontreal.Api/Data/Migrations/20261112060008_CreateQualityClasses.cs) | [0005_create_quality_classes.sql](sql/0005_create_quality_classes.sql) | [quality-classes.md](quality-classes.md) | +| catalog item details | [20261117040905_AddCatalogItemDetails](../../src/MoissonMontreal.Api/Data/Migrations/20261117040905_AddCatalogItemDetails.cs) | [0006_add_catalog_item_details.sql](sql/0006_add_catalog_item_details.sql) | [catalog.md](catalog.md) | The SQL scripts must be run in order on an empty database. diff --git a/docs/database/sql/0006_add_catalog_item_details.sql b/docs/database/sql/0006_add_catalog_item_details.sql new file mode 100644 index 0000000..a98fc55 --- /dev/null +++ b/docs/database/sql/0006_add_catalog_item_details.sql @@ -0,0 +1,41 @@ +START TRANSACTION; +ALTER TABLE catalog_items ADD category character varying(100) NOT NULL DEFAULT ''; + +ALTER TABLE catalog_items ADD business_central_code character varying(50) NOT NULL DEFAULT ''; + +ALTER TABLE catalog_items ADD unit character varying(20) NOT NULL DEFAULT ''; + +ALTER TABLE catalog_items ADD quality_class character varying(1) NOT NULL DEFAULT ''; + +ALTER TABLE catalog_items ADD updated_at timestamp with time zone; + +UPDATE catalog_items +SET category = 'To classify', + business_central_code = 'TO-FIX-' || id::text, + unit = 'unit', + quality_class = 'A'; + +ALTER TABLE catalog_items ALTER COLUMN category DROP DEFAULT; + +ALTER TABLE catalog_items ALTER COLUMN business_central_code DROP DEFAULT; + +ALTER TABLE catalog_items ALTER COLUMN unit DROP DEFAULT; + +ALTER TABLE catalog_items ALTER COLUMN quality_class DROP DEFAULT; + +CREATE UNIQUE INDEX ix_catalog_items_business_central_code ON catalog_items (business_central_code); + +CREATE INDEX ix_catalog_items_quality_class ON catalog_items (quality_class); + +ALTER TABLE catalog_items ADD CONSTRAINT ck_catalog_items_category_not_empty CHECK (length(category) > 0); + +ALTER TABLE catalog_items ADD CONSTRAINT ck_catalog_items_business_central_code_not_empty CHECK (length(business_central_code) > 0); + +ALTER TABLE catalog_items ADD CONSTRAINT ck_catalog_items_unit_not_empty CHECK (length(unit) > 0); + +ALTER TABLE catalog_items ADD CONSTRAINT fk_catalog_items_quality_classes_quality_class FOREIGN KEY (quality_class) REFERENCES quality_classes (code) ON DELETE RESTRICT; + +INSERT INTO "__EFMigrationsHistory" (migration_id, product_version) +VALUES ('20261117040905_AddCatalogItemDetails', '10.0.13'); + +COMMIT; diff --git a/src/MoissonMontreal.Api/Catalog/CatalogItemValidator.cs b/src/MoissonMontreal.Api/Catalog/CatalogItemValidator.cs new file mode 100644 index 0000000..77f1b79 --- /dev/null +++ b/src/MoissonMontreal.Api/Catalog/CatalogItemValidator.cs @@ -0,0 +1,68 @@ +using System.Text.RegularExpressions; +using MoissonMontreal.Core.Dtos; +using MoissonMontreal.Core.Entities; + +namespace MoissonMontreal.Api.Catalog; + +/// +/// Checks a catalog item request and returns the values ready to store. +/// +public static partial class CatalogItemValidator +{ + /// + /// Trims each field and reports every problem. A true result means can be saved. + /// The quality class must also exist in the quality_classes table; this method only checks its shape. + /// + public static bool TryNormalize(CatalogItemRequest request, out CatalogItemFields fields, out Dictionary errors) + { + var found = new Dictionary(); + var name = Required(request.Name, nameof(CatalogItemRequest.Name), CatalogItem.NameMaxLength, found); + var category = Required(request.Category, nameof(CatalogItemRequest.Category), CatalogItem.CategoryMaxLength, found); + var code = Required(request.BusinessCentralCode, nameof(CatalogItemRequest.BusinessCentralCode), CatalogItem.BusinessCentralCodeMaxLength, found); + var unit = Required(request.Unit, nameof(CatalogItemRequest.Unit), CatalogItem.UnitMaxLength, found); + var qualityClass = Quality(request.QualityClass, found); + + fields = new CatalogItemFields(name, category, code, unit, qualityClass); + errors = found; + return found.Count == 0; + } + + private static string Required(string? value, string field, int maxLength, Dictionary errors) + { + var trimmed = value?.Trim() ?? string.Empty; + if (trimmed.Length == 0) + { + errors[field] = [$"{field} is required."]; + } + else if (trimmed.Length > maxLength) + { + errors[field] = [$"{field} must be {maxLength} characters or fewer."]; + } + + return trimmed; + } + + private static string Quality(string? value, Dictionary errors) + { + var trimmed = value?.Trim() ?? string.Empty; + if (!QualityClassCode().IsMatch(trimmed)) + { + errors[nameof(CatalogItemRequest.QualityClass)] = ["QualityClass must be one capital letter, such as A, B or C."]; + } + + return trimmed; + } + + [GeneratedRegex("^[A-Z]$")] + private static partial Regex QualityClassCode(); +} + +/// +/// Trimmed catalog fields that passed validation. +/// +public readonly record struct CatalogItemFields( + string Name, + string Category, + string BusinessCentralCode, + string Unit, + string QualityClass); diff --git a/src/MoissonMontreal.Api/Controllers/CatalogItemsController.cs b/src/MoissonMontreal.Api/Controllers/CatalogItemsController.cs new file mode 100644 index 0000000..91b8dcf --- /dev/null +++ b/src/MoissonMontreal.Api/Controllers/CatalogItemsController.cs @@ -0,0 +1,174 @@ +using System.Linq.Expressions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using MoissonMontreal.Api.Catalog; +using MoissonMontreal.Api.Data; +using MoissonMontreal.Api.Data.Configurations; +using MoissonMontreal.Core.Authorization; +using MoissonMontreal.Core.Dtos; +using MoissonMontreal.Core.Entities; +using Npgsql; + +namespace MoissonMontreal.Api.Controllers; + +/// +/// Lists, creates and edits the foods in the catalog. +/// Any signed-in employee can read the catalog. Creating and editing an item requires . +/// +[ApiController] +[Route("api/catalog-items")] +public class CatalogItemsController(MoissonDbContext db) : ControllerBase +{ + private const string QualityClassMissing = "QualityClass must be a quality class that exists."; + + private static readonly Expression> AsDto = item => new CatalogItemDto( + item.Id, + item.Name, + item.Category, + item.BusinessCentralCode, + item.Unit, + item.QualityClassCode, + item.CreatedAt, + item.UpdatedAt); + + private static readonly Func ToDto = AsDto.Compile(); + + /// + /// Returns every catalog item, ordered by name. + /// + [HttpGet] + public async Task>> List(CancellationToken cancellationToken) + { + var items = await db.CatalogItems + .OrderBy(item => item.Name) + .ThenBy(item => item.BusinessCentralCode) + .Select(AsDto) + .ToListAsync(cancellationToken); + + return items; + } + + /// + /// Returns one catalog item. + /// + [HttpGet("{id:guid}")] + public async Task> Get(Guid id, CancellationToken cancellationToken) + { + var item = await db.CatalogItems.SingleOrDefaultAsync(item => item.Id == id, cancellationToken); + return item is null ? NotFound() : ToDto(item); + } + + /// + /// Adds a catalog item. The Business Central code must be new, and the quality class must exist. + /// + [HttpPost] + [Authorize(Policy = Permissions.ManagePriceGrid)] + public async Task> Create(CatalogItemRequest request, CancellationToken cancellationToken) + { + var (fields, errors) = await TryReadAsync(request, cancellationToken); + if (errors is not null) + { + return ValidationProblem(new ValidationProblemDetails(errors)); + } + + var item = new CatalogItem + { + Name = fields.Name, + Category = fields.Category, + BusinessCentralCode = fields.BusinessCentralCode, + Unit = fields.Unit, + QualityClassCode = fields.QualityClass, + }; + db.CatalogItems.Add(item); + + if (await TrySaveAsync(cancellationToken) is { } conflict) + { + return conflict; + } + + return CreatedAtAction(nameof(Get), new { id = item.Id }, ToDto(item)); + } + + /// + /// Replaces the fields of a catalog item. The Business Central code must stay unique. + /// + [HttpPut("{id:guid}")] + [Authorize(Policy = Permissions.ManagePriceGrid)] + public async Task> Update(Guid id, CatalogItemRequest request, CancellationToken cancellationToken) + { + var (fields, errors) = await TryReadAsync(request, cancellationToken); + if (errors is not null) + { + return ValidationProblem(new ValidationProblemDetails(errors)); + } + + var item = await db.CatalogItems.SingleOrDefaultAsync(item => item.Id == id, cancellationToken); + if (item is null) + { + return NotFound(); + } + + item.Name = fields.Name; + item.Category = fields.Category; + item.BusinessCentralCode = fields.BusinessCentralCode; + item.Unit = fields.Unit; + item.QualityClassCode = fields.QualityClass; + item.UpdatedAt = DateTimeOffset.UtcNow; + + if (await TrySaveAsync(cancellationToken) is { } conflict) + { + return conflict; + } + + return ToDto(item); + } + + private async Task<(CatalogItemFields Fields, Dictionary? Errors)> TryReadAsync( + CatalogItemRequest request, + CancellationToken cancellationToken) + { + if (!CatalogItemValidator.TryNormalize(request, out var fields, out var errors)) + { + return (fields, errors); + } + + var qualityExists = await db.QualityClasses.AnyAsync(quality => quality.Code == fields.QualityClass, cancellationToken); + if (!qualityExists) + { + return (fields, QualityClassErrors()); + } + + return (fields, null); + } + + private static Dictionary QualityClassErrors() => new() + { + [nameof(CatalogItemRequest.QualityClass)] = [QualityClassMissing], + }; + + private async Task TrySaveAsync(CancellationToken cancellationToken) + { + try + { + await db.SaveChangesAsync(cancellationToken); + return null; + } + catch (DbUpdateException exception) when (exception.InnerException is PostgresException postgres + && postgres.ConstraintName == CatalogItemConfiguration.BusinessCentralCodeIndex) + { + return Conflict(new ProblemDetails + { + Status = StatusCodes.Status409Conflict, + Title = "Business Central code already used", + Detail = "A catalog item with this Business Central code already exists.", + }); + } + catch (DbUpdateException exception) when (exception.InnerException is PostgresException postgres + && postgres.ConstraintName == CatalogItemConfiguration.QualityClassForeignKey) + { + // The quality class was deleted after TryReadAsync checked it. + return ValidationProblem(new ValidationProblemDetails(QualityClassErrors())); + } + } +} diff --git a/src/MoissonMontreal.Api/Data/Configurations/CatalogItemConfiguration.cs b/src/MoissonMontreal.Api/Data/Configurations/CatalogItemConfiguration.cs index 095f0df..e61d3f3 100644 --- a/src/MoissonMontreal.Api/Data/Configurations/CatalogItemConfiguration.cs +++ b/src/MoissonMontreal.Api/Data/Configurations/CatalogItemConfiguration.cs @@ -10,16 +10,55 @@ namespace MoissonMontreal.Api.Data.Configurations; public class CatalogItemConfiguration : IEntityTypeConfiguration { /// - /// Configures the columns and constraint of the catalog_items table. + /// Name of the unique index on the Business Central code. + /// + public const string BusinessCentralCodeIndex = "ix_catalog_items_business_central_code"; + + /// + /// Name of the foreign key from the catalog item to its quality class. + /// + public const string QualityClassForeignKey = "fk_catalog_items_quality_classes_quality_class"; + + /// + /// Configures the columns, the unique Business Central code and the link to the quality class. /// /// Builder used to configure the catalog item entity. public void Configure(EntityTypeBuilder builder) { - builder.ToTable(t => t.HasCheckConstraint("ck_catalog_items_name_not_empty", "length(name) > 0")); + builder.ToTable(t => + { + t.HasCheckConstraint("ck_catalog_items_name_not_empty", "length(name) > 0"); + t.HasCheckConstraint("ck_catalog_items_category_not_empty", "length(category) > 0"); + t.HasCheckConstraint("ck_catalog_items_business_central_code_not_empty", "length(business_central_code) > 0"); + t.HasCheckConstraint("ck_catalog_items_unit_not_empty", "length(unit) > 0"); + }); builder.Property(c => c.Id).HasDefaultValueSql("gen_random_uuid()"); - builder.Property(c => c.Name).HasMaxLength(255); + builder.Property(c => c.Name).HasMaxLength(CatalogItem.NameMaxLength); + + builder.Property(c => c.Category).HasMaxLength(CatalogItem.CategoryMaxLength); + + builder.Property(c => c.BusinessCentralCode).HasMaxLength(CatalogItem.BusinessCentralCodeMaxLength); + + builder.HasIndex(c => c.BusinessCentralCode) + .IsUnique() + .HasDatabaseName(BusinessCentralCodeIndex); + + builder.Property(c => c.Unit).HasMaxLength(CatalogItem.UnitMaxLength); + + builder.Property(c => c.QualityClassCode) + .HasColumnName("quality_class") + .HasMaxLength(1); + + builder.HasIndex(c => c.QualityClassCode) + .HasDatabaseName("ix_catalog_items_quality_class"); + + builder.HasOne(c => c.QualityClass) + .WithMany() + .HasForeignKey(c => c.QualityClassCode) + .OnDelete(DeleteBehavior.Restrict) + .HasConstraintName(QualityClassForeignKey); builder.Property(c => c.CreatedAt).HasDefaultValueSql("now()"); } diff --git a/src/MoissonMontreal.Api/Data/Migrations/20261117040905_AddCatalogItemDetails.Designer.cs b/src/MoissonMontreal.Api/Data/Migrations/20261117040905_AddCatalogItemDetails.Designer.cs new file mode 100644 index 0000000..3c149a9 --- /dev/null +++ b/src/MoissonMontreal.Api/Data/Migrations/20261117040905_AddCatalogItemDetails.Designer.cs @@ -0,0 +1,651 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using MoissonMontreal.Api.Data; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace MoissonMontreal.Api.Data.Migrations +{ + [DbContext(typeof(MoissonDbContext))] + [Migration("20261117040905_AddCatalogItemDetails")] + partial class AddCatalogItemDetails + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.CatalogItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("BusinessCentralCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("business_central_code"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("QualityClassCode") + .IsRequired() + .HasMaxLength(1) + .HasColumnType("character varying(1)") + .HasColumnName("quality_class"); + + b.Property("Unit") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("unit"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.HasKey("Id") + .HasName("pk_catalog_items"); + + b.HasIndex("BusinessCentralCode") + .IsUnique() + .HasDatabaseName("ix_catalog_items_business_central_code"); + + b.HasIndex("QualityClassCode") + .HasDatabaseName("ix_catalog_items_quality_class"); + + b.ToTable("catalog_items", null, t => + { + t.HasCheckConstraint("ck_catalog_items_business_central_code_not_empty", "length(business_central_code) > 0"); + + t.HasCheckConstraint("ck_catalog_items_category_not_empty", "length(category) > 0"); + + t.HasCheckConstraint("ck_catalog_items_name_not_empty", "length(name) > 0"); + + t.HasCheckConstraint("ck_catalog_items_unit_not_empty", "length(unit) > 0"); + }); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.Donor", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Address") + .HasColumnType("text") + .HasColumnName("address"); + + b.Property("ContactPerson") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("contact_person"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("PostalCode") + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("postal_code"); + + b.HasKey("Id") + .HasName("pk_donors"); + + b.ToTable("donors", null, t => + { + t.HasCheckConstraint("ck_donors_name_not_empty", "length(name) > 0"); + }); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.FoodItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CatalogItemId") + .HasColumnType("uuid") + .HasColumnName("catalog_item_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("DonationDate") + .HasColumnType("date") + .HasColumnName("donation_date"); + + b.Property("DonorId") + .HasColumnType("uuid") + .HasColumnName("donor_id"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("Quality") + .IsRequired() + .HasMaxLength(1) + .HasColumnType("character varying(1)") + .HasColumnName("quality"); + + b.Property("Quantity") + .HasPrecision(12, 2) + .HasColumnType("numeric(12,2)") + .HasColumnName("quantity"); + + b.Property("Unit") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("unit"); + + b.HasKey("Id") + .HasName("pk_food_items"); + + b.HasAlternateKey("Id", "DonorId") + .HasName("ak_food_items_id_donor_id"); + + b.HasIndex("CatalogItemId") + .HasDatabaseName("ix_food_items_catalog_item_id"); + + b.HasIndex("DonorId") + .HasDatabaseName("ix_food_items_donor_id"); + + b.HasIndex("Quality") + .HasDatabaseName("ix_food_items_quality"); + + b.ToTable("food_items", null, t => + { + t.HasCheckConstraint("ck_food_items_name_not_empty", "length(name) > 0"); + + t.HasCheckConstraint("ck_food_items_quantity_positive", "quantity > 0"); + + t.HasCheckConstraint("ck_food_items_unit_not_empty", "length(unit) > 0"); + }); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.Price", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CatalogItemId") + .HasColumnType("uuid") + .HasColumnName("catalog_item_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("EffectiveDate") + .HasColumnType("date") + .HasColumnName("effective_date"); + + b.Property("UnitPrice") + .HasPrecision(12, 4) + .HasColumnType("numeric(12,4)") + .HasColumnName("unit_price"); + + b.HasKey("Id") + .HasName("pk_prices"); + + b.HasIndex("CatalogItemId", "EffectiveDate") + .IsUnique() + .HasDatabaseName("ix_prices_catalog_item_id_effective_date"); + + b.ToTable("prices", null, t => + { + t.HasCheckConstraint("ck_prices_unit_price_positive", "unit_price > 0"); + }); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.QualityClass", b => + { + b.Property("Code") + .HasMaxLength(1) + .HasColumnType("character varying(1)") + .HasColumnName("code"); + + b.Property("MaxPercentage") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)") + .HasColumnName("max_percentage"); + + b.Property("MinPercentage") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)") + .HasColumnName("min_percentage"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("name"); + + b.Property("Percentage") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)") + .HasColumnName("percentage"); + + b.HasKey("Code") + .HasName("pk_quality_classes"); + + b.HasIndex("Name") + .IsUnique() + .HasDatabaseName("ix_quality_classes_name"); + + b.ToTable("quality_classes", null, t => + { + t.HasCheckConstraint("ck_quality_classes_code_format", "code ~ '^[A-Z]$'"); + + t.HasCheckConstraint("ck_quality_classes_name_not_empty", "length(name) > 0"); + + t.HasCheckConstraint("ck_quality_classes_percentage_in_range", "percentage BETWEEN min_percentage AND max_percentage"); + + t.HasCheckConstraint("ck_quality_classes_range_valid", "min_percentage >= 0 AND min_percentage <= max_percentage AND max_percentage <= 100"); + }); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.Receipt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("DonorId") + .HasColumnType("uuid") + .HasColumnName("donor_id"); + + b.Property("ReceiptDate") + .ValueGeneratedOnAdd() + .HasColumnType("date") + .HasColumnName("receipt_date") + .HasDefaultValueSql("(now() AT TIME ZONE 'America/Montreal')::date"); + + b.Property("TotalAmount") + .HasPrecision(12, 2) + .HasColumnType("numeric(12,2)") + .HasColumnName("total_amount"); + + b.HasKey("Id") + .HasName("pk_receipts"); + + b.HasAlternateKey("Id", "DonorId") + .HasName("ak_receipts_id_donor_id"); + + b.HasIndex("DonorId") + .HasDatabaseName("ix_receipts_donor_id"); + + b.ToTable("receipts", null, t => + { + t.HasCheckConstraint("ck_receipts_total_amount_not_negative", "total_amount >= 0"); + }); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.ReceiptItem", b => + { + b.Property("ReceiptId") + .HasColumnType("uuid") + .HasColumnName("receipt_id"); + + b.Property("FoodItemId") + .HasColumnType("uuid") + .HasColumnName("food_item_id"); + + b.Property("DonorId") + .HasColumnType("uuid") + .HasColumnName("donor_id"); + + b.Property("QualityPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)") + .HasColumnName("quality_percent"); + + b.Property("Quantity") + .HasPrecision(12, 2) + .HasColumnType("numeric(12,2)") + .HasColumnName("quantity"); + + b.Property("Unit") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("unit"); + + b.Property("UnitPrice") + .HasPrecision(12, 4) + .HasColumnType("numeric(12,4)") + .HasColumnName("unit_price"); + + b.HasKey("ReceiptId", "FoodItemId") + .HasName("pk_receipt_items"); + + b.HasIndex("FoodItemId") + .IsUnique() + .HasDatabaseName("ix_receipt_items_food_item_id"); + + b.HasIndex("FoodItemId", "DonorId") + .HasDatabaseName("ix_receipt_items_food_item_id_donor_id"); + + b.HasIndex("ReceiptId", "DonorId") + .HasDatabaseName("ix_receipt_items_receipt_id_donor_id"); + + b.ToTable("receipt_items", null, t => + { + t.HasCheckConstraint("ck_receipt_items_quality_percent_range", "quality_percent BETWEEN 0 AND 100"); + + t.HasCheckConstraint("ck_receipt_items_quantity_positive", "quantity > 0"); + + t.HasCheckConstraint("ck_receipt_items_unit_not_empty", "length(unit) > 0"); + + t.HasCheckConstraint("ck_receipt_items_unit_price_positive", "unit_price > 0"); + }); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.Role", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("code"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("name"); + + b.HasKey("Id") + .HasName("pk_roles"); + + b.HasIndex("Code") + .IsUnique() + .HasDatabaseName("ix_roles_code"); + + b.HasIndex("Name") + .IsUnique() + .HasDatabaseName("ix_roles_name"); + + b.ToTable("roles", (string)null); + + b.HasData( + new + { + Id = 1, + Code = "Supply", + Name = "Supply" + }, + new + { + Id = 2, + Code = "SupplyDirector", + Name = "Supply Director" + }, + new + { + Id = 3, + Code = "Finance", + Name = "Finance" + }, + new + { + Id = 4, + Code = "Admin", + Name = "Admin" + }); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("display_name"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)") + .HasColumnName("email"); + + b.Property("EntraObjectId") + .HasColumnType("uuid") + .HasColumnName("entra_object_id"); + + b.Property("IsActive") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("is_active"); + + b.Property("RoleId") + .HasColumnType("integer") + .HasColumnName("role_id"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Email") + .IsUnique() + .HasDatabaseName("ix_users_email"); + + b.HasIndex("EntraObjectId") + .IsUnique() + .HasDatabaseName("ix_users_entra_object_id"); + + b.HasIndex("RoleId") + .HasDatabaseName("ix_users_role_id"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_email_lowercase", "email = lower(email)"); + }); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.CatalogItem", b => + { + b.HasOne("MoissonMontreal.Core.Entities.QualityClass", "QualityClass") + .WithMany() + .HasForeignKey("QualityClassCode") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_catalog_items_quality_classes_quality_class"); + + b.Navigation("QualityClass"); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.FoodItem", b => + { + b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", "CatalogItem") + .WithMany() + .HasForeignKey("CatalogItemId") + .OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_food_items_catalog_items_catalog_item_id"); + + b.HasOne("MoissonMontreal.Core.Entities.Donor", "Donor") + .WithMany("FoodItems") + .HasForeignKey("DonorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_food_items_donors_donor_id"); + + b.HasOne("MoissonMontreal.Core.Entities.QualityClass", "QualityClass") + .WithMany() + .HasForeignKey("Quality") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_food_items_quality_classes_quality"); + + b.Navigation("CatalogItem"); + + b.Navigation("Donor"); + + b.Navigation("QualityClass"); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.Price", b => + { + b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", "CatalogItem") + .WithMany("Prices") + .HasForeignKey("CatalogItemId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_prices_catalog_items_catalog_item_id"); + + b.Navigation("CatalogItem"); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.Receipt", b => + { + b.HasOne("MoissonMontreal.Core.Entities.Donor", "Donor") + .WithMany() + .HasForeignKey("DonorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_receipts_donors_donor_id"); + + b.Navigation("Donor"); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.ReceiptItem", b => + { + b.HasOne("MoissonMontreal.Core.Entities.FoodItem", "FoodItem") + .WithMany() + .HasForeignKey("FoodItemId", "DonorId") + .HasPrincipalKey("Id", "DonorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_receipt_items_food_items_food_item_id_donor_id"); + + b.HasOne("MoissonMontreal.Core.Entities.Receipt", "Receipt") + .WithMany("Items") + .HasForeignKey("ReceiptId", "DonorId") + .HasPrincipalKey("Id", "DonorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_receipt_items_receipts_receipt_id_donor_id"); + + b.Navigation("FoodItem"); + + b.Navigation("Receipt"); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.User", b => + { + b.HasOne("MoissonMontreal.Core.Entities.Role", "Role") + .WithMany("Users") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_users_roles_role_id"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.CatalogItem", b => + { + b.Navigation("Prices"); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.Donor", b => + { + b.Navigation("FoodItems"); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.Receipt", b => + { + b.Navigation("Items"); + }); + + modelBuilder.Entity("MoissonMontreal.Core.Entities.Role", b => + { + b.Navigation("Users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/MoissonMontreal.Api/Data/Migrations/20261117040905_AddCatalogItemDetails.cs b/src/MoissonMontreal.Api/Data/Migrations/20261117040905_AddCatalogItemDetails.cs new file mode 100644 index 0000000..d8239e0 --- /dev/null +++ b/src/MoissonMontreal.Api/Data/Migrations/20261117040905_AddCatalogItemDetails.cs @@ -0,0 +1,193 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace MoissonMontreal.Api.Data.Migrations +{ + /// + public partial class AddCatalogItemDetails : Migration + { + /// + /// Adds the catalog item details. The UPDATE that fills existing rows is written by hand, not generated: + /// without it, rows that already exist would keep empty values and fail the checks, the unique index and the + /// foreign key added below. Keep it if this migration is regenerated. + /// + /// Builder used to describe the operations. + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "business_central_code", + table: "catalog_items", + type: "character varying(50)", + maxLength: 50, + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "category", + table: "catalog_items", + type: "character varying(100)", + maxLength: 100, + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "quality_class", + table: "catalog_items", + type: "character varying(1)", + maxLength: 1, + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "unit", + table: "catalog_items", + type: "character varying(20)", + maxLength: 20, + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "updated_at", + table: "catalog_items", + type: "timestamp with time zone", + nullable: true); + + // Items created before this migration get placeholder values to fix by hand. The id keeps each code unique. + migrationBuilder.Sql(""" + UPDATE catalog_items + SET category = 'To classify', + business_central_code = 'TO-FIX-' || id::text, + unit = 'unit', + quality_class = 'A'; + """); + + migrationBuilder.AlterColumn( + name: "business_central_code", + table: "catalog_items", + type: "character varying(50)", + maxLength: 50, + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(50)", + oldMaxLength: 50, + oldDefaultValue: ""); + + migrationBuilder.AlterColumn( + name: "category", + table: "catalog_items", + type: "character varying(100)", + maxLength: 100, + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(100)", + oldMaxLength: 100, + oldDefaultValue: ""); + + migrationBuilder.AlterColumn( + name: "quality_class", + table: "catalog_items", + type: "character varying(1)", + maxLength: 1, + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(1)", + oldMaxLength: 1, + oldDefaultValue: ""); + + migrationBuilder.AlterColumn( + name: "unit", + table: "catalog_items", + type: "character varying(20)", + maxLength: 20, + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(20)", + oldMaxLength: 20, + oldDefaultValue: ""); + + migrationBuilder.CreateIndex( + name: "ix_catalog_items_business_central_code", + table: "catalog_items", + column: "business_central_code", + unique: true); + + migrationBuilder.CreateIndex( + name: "ix_catalog_items_quality_class", + table: "catalog_items", + column: "quality_class"); + + migrationBuilder.AddCheckConstraint( + name: "ck_catalog_items_business_central_code_not_empty", + table: "catalog_items", + sql: "length(business_central_code) > 0"); + + migrationBuilder.AddCheckConstraint( + name: "ck_catalog_items_category_not_empty", + table: "catalog_items", + sql: "length(category) > 0"); + + migrationBuilder.AddCheckConstraint( + name: "ck_catalog_items_unit_not_empty", + table: "catalog_items", + sql: "length(unit) > 0"); + + migrationBuilder.AddForeignKey( + name: "fk_catalog_items_quality_classes_quality_class", + table: "catalog_items", + column: "quality_class", + principalTable: "quality_classes", + principalColumn: "code", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "fk_catalog_items_quality_classes_quality_class", + table: "catalog_items"); + + migrationBuilder.DropIndex( + name: "ix_catalog_items_business_central_code", + table: "catalog_items"); + + migrationBuilder.DropIndex( + name: "ix_catalog_items_quality_class", + table: "catalog_items"); + + migrationBuilder.DropCheckConstraint( + name: "ck_catalog_items_business_central_code_not_empty", + table: "catalog_items"); + + migrationBuilder.DropCheckConstraint( + name: "ck_catalog_items_category_not_empty", + table: "catalog_items"); + + migrationBuilder.DropCheckConstraint( + name: "ck_catalog_items_unit_not_empty", + table: "catalog_items"); + + migrationBuilder.DropColumn( + name: "business_central_code", + table: "catalog_items"); + + migrationBuilder.DropColumn( + name: "category", + table: "catalog_items"); + + migrationBuilder.DropColumn( + name: "quality_class", + table: "catalog_items"); + + migrationBuilder.DropColumn( + name: "unit", + table: "catalog_items"); + + migrationBuilder.DropColumn( + name: "updated_at", + table: "catalog_items"); + } + } +} diff --git a/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs b/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs index 30f0202..2cf2555 100644 --- a/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs +++ b/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs @@ -30,6 +30,18 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnName("id") .HasDefaultValueSql("gen_random_uuid()"); + b.Property("BusinessCentralCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("business_central_code"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + b.Property("CreatedAt") .ValueGeneratedOnAdd() .HasColumnType("timestamp with time zone") @@ -42,12 +54,41 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("character varying(255)") .HasColumnName("name"); + b.Property("QualityClassCode") + .IsRequired() + .HasMaxLength(1) + .HasColumnType("character varying(1)") + .HasColumnName("quality_class"); + + b.Property("Unit") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("unit"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + b.HasKey("Id") .HasName("pk_catalog_items"); + b.HasIndex("BusinessCentralCode") + .IsUnique() + .HasDatabaseName("ix_catalog_items_business_central_code"); + + b.HasIndex("QualityClassCode") + .HasDatabaseName("ix_catalog_items_quality_class"); + b.ToTable("catalog_items", null, t => { + t.HasCheckConstraint("ck_catalog_items_business_central_code_not_empty", "length(business_central_code) > 0"); + + t.HasCheckConstraint("ck_catalog_items_category_not_empty", "length(category) > 0"); + t.HasCheckConstraint("ck_catalog_items_name_not_empty", "length(name) > 0"); + + t.HasCheckConstraint("ck_catalog_items_unit_not_empty", "length(unit) > 0"); }); }); @@ -482,6 +523,18 @@ protected override void BuildModel(ModelBuilder modelBuilder) }); }); + modelBuilder.Entity("MoissonMontreal.Core.Entities.CatalogItem", b => + { + b.HasOne("MoissonMontreal.Core.Entities.QualityClass", "QualityClass") + .WithMany() + .HasForeignKey("QualityClassCode") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_catalog_items_quality_classes_quality_class"); + + b.Navigation("QualityClass"); + }); + modelBuilder.Entity("MoissonMontreal.Core.Entities.FoodItem", b => { b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", "CatalogItem") diff --git a/src/MoissonMontreal.Core/Dtos/CatalogItemDto.cs b/src/MoissonMontreal.Core/Dtos/CatalogItemDto.cs new file mode 100644 index 0000000..ec0f047 --- /dev/null +++ b/src/MoissonMontreal.Core/Dtos/CatalogItemDto.cs @@ -0,0 +1,14 @@ +namespace MoissonMontreal.Core.Dtos; + +/// +/// A catalog item returned by the API. +/// +public record CatalogItemDto( + Guid Id, + string Name, + string Category, + string BusinessCentralCode, + string Unit, + string QualityClass, + DateTimeOffset CreatedAt, + DateTimeOffset? UpdatedAt); diff --git a/src/MoissonMontreal.Core/Dtos/CatalogItemRequest.cs b/src/MoissonMontreal.Core/Dtos/CatalogItemRequest.cs new file mode 100644 index 0000000..fec60d7 --- /dev/null +++ b/src/MoissonMontreal.Core/Dtos/CatalogItemRequest.cs @@ -0,0 +1,11 @@ +namespace MoissonMontreal.Core.Dtos; + +/// +/// Fields sent when a catalog item is created or edited. +/// +public record CatalogItemRequest( + string? Name, + string? Category, + string? BusinessCentralCode, + string? Unit, + string? QualityClass); diff --git a/src/MoissonMontreal.Core/Entities/CatalogItem.cs b/src/MoissonMontreal.Core/Entities/CatalogItem.cs index fe00b92..ed97341 100644 --- a/src/MoissonMontreal.Core/Entities/CatalogItem.cs +++ b/src/MoissonMontreal.Core/Entities/CatalogItem.cs @@ -6,6 +6,26 @@ namespace MoissonMontreal.Core.Entities; /// public class CatalogItem { + /// + /// Longest name stored for a catalog item. + /// + public const int NameMaxLength = 255; + + /// + /// Longest category stored for a catalog item. + /// + public const int CategoryMaxLength = 100; + + /// + /// Longest Business Central code stored for a catalog item. + /// + public const int BusinessCentralCodeMaxLength = 50; + + /// + /// Longest unit stored for a catalog item. The unit is free text until the price-per-unit decision in issue 28. + /// + public const int UnitMaxLength = 20; + /// /// Identifier of the catalog item, assigned by the database. /// @@ -16,11 +36,41 @@ public class CatalogItem /// public string Name { get; set; } = string.Empty; + /// + /// Group the food belongs to, such as Bakery. Cannot be empty. + /// + public string Category { get; set; } = string.Empty; + + /// + /// Code of this food in Business Central. Two catalog items cannot share a code. + /// + public string BusinessCentralCode { get; set; } = string.Empty; + + /// + /// Unit used to count this food, as free text for now (for example kg or caisse). + /// + public string Unit { get; set; } = string.Empty; + + /// + /// Code of the quality class of this food. It must match an existing quality class. + /// + public string QualityClassCode { get; set; } = string.Empty; + + /// + /// Quality class of this food. The class lives on the catalog item. + /// + public QualityClass QualityClass { get; set; } = null!; + /// /// Date and time the catalog item was created, set by the database. /// public DateTimeOffset CreatedAt { get; set; } + /// + /// Date and time of the last change, or null if the item was never changed. + /// + public DateTimeOffset? UpdatedAt { get; set; } + /// /// Every price this item has had, one per effective date. /// diff --git a/tests/MoissonMontreal.Tests/Api/CatalogEndpointTests.cs b/tests/MoissonMontreal.Tests/Api/CatalogEndpointTests.cs new file mode 100644 index 0000000..6013e9f --- /dev/null +++ b/tests/MoissonMontreal.Tests/Api/CatalogEndpointTests.cs @@ -0,0 +1,232 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using MoissonMontreal.Api.Data; +using MoissonMontreal.Core.Authorization; +using MoissonMontreal.Core.Dtos; +using MoissonMontreal.Tests.Fixtures; + +namespace MoissonMontreal.Tests.Api; + +[Trait("Category", "Integration")] +public class CatalogEndpointTests(CatalogApiFactory factory) : IClassFixture +{ + [Fact] + public async Task List_ReturnsUnauthorized_WhenTokenIsMissing() + { + using var client = factory.CreateClient(); + + var response = await client.GetAsync("/api/catalog-items"); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task List_ReturnsTheCatalogOrderedByName() + { + await ClearAsync(); + using var client = await CreateClientAsync(); + await CreateAsync(client, Request(name: "Pommes", code: "BC-APPLES")); + await CreateAsync(client, Request(name: "Pain", code: "BC-BREAD")); + + var response = await client.GetAsync("/api/catalog-items"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var items = await response.Content.ReadFromJsonAsync>(); + Assert.Equal(["Pain", "Pommes"], items!.Select(item => item.Name)); + } + + [Fact] + public async Task Create_ReturnsTheSavedItem() + { + using var client = await CreateClientAsync(); + + var response = await client.PostAsJsonAsync("/api/catalog-items", Request()); + + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + var item = await response.Content.ReadFromJsonAsync(); + Assert.Equal("Pain", item!.Name); + Assert.Equal("Boulangerie", item.Category); + Assert.Equal("BC-001", item.BusinessCentralCode); + Assert.Equal("kg", item.Unit); + Assert.Equal("A", item.QualityClass); + Assert.NotEqual(Guid.Empty, item.Id); + Assert.NotEqual(default, item.CreatedAt); + Assert.Null(item.UpdatedAt); + Assert.Equal($"/api/catalog-items/{item.Id}", response.Headers.Location?.AbsolutePath); + } + + [Fact] + public async Task Get_ReturnsTheItem() + { + using var client = await CreateClientAsync(); + var created = await CreateAsync(client, Request(code: "BC-GET")); + + var response = await client.GetAsync($"/api/catalog-items/{created.Id}"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var item = await response.Content.ReadFromJsonAsync(); + Assert.Equal(created.Id, item!.Id); + } + + [Fact] + public async Task Get_ReturnsNotFound_WhenTheItemDoesNotExist() + { + using var client = await CreateClientAsync(); + + var response = await client.GetAsync($"/api/catalog-items/{Guid.NewGuid()}"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task Update_ReplacesTheFields() + { + using var client = await CreateClientAsync(); + var created = await CreateAsync(client, Request(code: "BC-EDIT")); + + var response = await client.PutAsJsonAsync( + $"/api/catalog-items/{created.Id}", + Request(name: "Pain complet", category: "Boulangerie", code: "BC-EDIT-2", unit: "caisse", qualityClass: "B")); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var item = await response.Content.ReadFromJsonAsync(); + Assert.Equal("Pain complet", item!.Name); + Assert.Equal("BC-EDIT-2", item.BusinessCentralCode); + Assert.Equal("caisse", item.Unit); + Assert.Equal("B", item.QualityClass); + Assert.NotNull(item.UpdatedAt); + } + + [Fact] + public async Task Update_KeepsTheSameBusinessCentralCode() + { + using var client = await CreateClientAsync(); + var created = await CreateAsync(client, Request(code: "BC-SAME")); + + var response = await client.PutAsJsonAsync($"/api/catalog-items/{created.Id}", Request(name: "Pain bio", code: "BC-SAME")); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Update_ReturnsNotFound_WhenTheItemDoesNotExist() + { + using var client = await CreateClientAsync(); + + var response = await client.PutAsJsonAsync($"/api/catalog-items/{Guid.NewGuid()}", Request(code: "BC-MISSING")); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task Create_ReturnsConflict_WhenTheBusinessCentralCodeExists() + { + using var client = await CreateClientAsync(); + await CreateAsync(client, Request(code: "BC-DUP")); + + var response = await client.PostAsJsonAsync("/api/catalog-items", Request(name: "Riz", code: "BC-DUP")); + + Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); + } + + [Fact] + public async Task Update_ReturnsConflict_WhenTheBusinessCentralCodeBelongsToAnotherItem() + { + using var client = await CreateClientAsync(); + await CreateAsync(client, Request(name: "Riz", code: "BC-RICE")); + var bread = await CreateAsync(client, Request(code: "BC-BREAD-2")); + + var response = await client.PutAsJsonAsync($"/api/catalog-items/{bread.Id}", Request(code: "BC-RICE")); + + Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); + } + + [Fact] + public async Task Create_ReturnsBadRequest_WhenTheQualityClassDoesNotExist() + { + using var client = await CreateClientAsync(); + + var response = await client.PostAsJsonAsync("/api/catalog-items", Request(qualityClass: "Z", code: "BC-BAD")); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + var problem = await response.Content.ReadFromJsonAsync(); + Assert.Contains(nameof(CatalogItemRequest.QualityClass), problem!.Errors.Keys); + } + + [Theory] + [InlineData(RoleCodes.Supply)] + [InlineData(RoleCodes.SupplyDirector)] + [InlineData(RoleCodes.Finance)] + public async Task Create_ReturnsForbidden_WhenRoleCannotManageThePriceGrid(string role) + { + using var client = await CreateClientAsync(role); + + var response = await client.PostAsJsonAsync("/api/catalog-items", Request(code: $"BC-FORBIDDEN-{role}")); + + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task Update_ReturnsForbidden_WhenRoleCannotManageThePriceGrid() + { + using var adminClient = await CreateClientAsync(); + var created = await CreateAsync(adminClient, Request(code: "BC-NO-EDIT")); + using var client = await CreateClientAsync(RoleCodes.Supply); + + var response = await client.PutAsJsonAsync($"/api/catalog-items/{created.Id}", Request(name: "Pain bio", code: "BC-NO-EDIT")); + + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task List_ReturnsOk_WhenRoleCannotManageThePriceGrid() + { + using var client = await CreateClientAsync(RoleCodes.Supply); + + var response = await client.GetAsync("/api/catalog-items"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Create_ReturnsBadRequest_WhenTheNameIsBlank() + { + using var client = await CreateClientAsync(); + + var response = await client.PostAsJsonAsync("/api/catalog-items", Request(name: " ", code: "BC-BLANK")); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + private async Task CreateClientAsync(string role = RoleCodes.Admin) + { + await factory.SignInAsAsync(role); + var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", factory.CreateToken()); + return client; + } + + private static CatalogItemRequest Request( + string name = "Pain", + string category = "Boulangerie", + string code = "BC-001", + string unit = "kg", + string qualityClass = "A") => new(name, category, code, unit, qualityClass); + + private static async Task CreateAsync(HttpClient client, CatalogItemRequest request) + { + var response = await client.PostAsJsonAsync("/api/catalog-items", request); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + return (await response.Content.ReadFromJsonAsync())!; + } + + private async Task ClearAsync() + { + await using var context = new MoissonDbContext( + new DbContextOptionsBuilder().UseNpgsql(factory.ConnectionString).Options); + await context.CatalogItems.ExecuteDeleteAsync(); + } +} diff --git a/tests/MoissonMontreal.Tests/Api/CatalogItemValidatorTests.cs b/tests/MoissonMontreal.Tests/Api/CatalogItemValidatorTests.cs new file mode 100644 index 0000000..6dc5687 --- /dev/null +++ b/tests/MoissonMontreal.Tests/Api/CatalogItemValidatorTests.cs @@ -0,0 +1,107 @@ +using MoissonMontreal.Api.Catalog; +using MoissonMontreal.Core.Dtos; +using MoissonMontreal.Core.Entities; + +namespace MoissonMontreal.Tests.Api; + +public class CatalogItemValidatorTests +{ + [Fact] + public void TryNormalize_TrimsEachField() + { + var request = new CatalogItemRequest(" Pain ", " Boulangerie ", " BC-001 ", " kg ", " A "); + + var ok = CatalogItemValidator.TryNormalize(request, out var fields, out var errors); + + Assert.True(ok); + Assert.Empty(errors); + Assert.Equal(new CatalogItemFields("Pain", "Boulangerie", "BC-001", "kg", "A"), fields); + } + + [Theory] + [InlineData("A")] + [InlineData("B")] + [InlineData("Z")] + public void TryNormalize_AcceptsASingleCapitalLetter(string qualityClass) + { + var ok = CatalogItemValidator.TryNormalize(Valid() with { QualityClass = qualityClass }, out var fields, out _); + + Assert.True(ok); + Assert.Equal(qualityClass, fields.QualityClass); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void TryNormalize_RejectsABlankName(string? name) + { + var ok = CatalogItemValidator.TryNormalize(Valid() with { Name = name }, out _, out var errors); + + Assert.False(ok); + Assert.Contains(nameof(CatalogItemRequest.Name), errors.Keys); + } + + [Fact] + public void TryNormalize_RejectsANameThatIsTooLong() + { + var ok = CatalogItemValidator.TryNormalize( + Valid() with { Name = new string('a', CatalogItem.NameMaxLength + 1) }, + out _, + out var errors); + + Assert.False(ok); + Assert.Contains(nameof(CatalogItemRequest.Name), errors.Keys); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void TryNormalize_RejectsABlankCategory(string? category) + { + var ok = CatalogItemValidator.TryNormalize(Valid() with { Category = category }, out _, out var errors); + + Assert.False(ok); + Assert.Contains(nameof(CatalogItemRequest.Category), errors.Keys); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void TryNormalize_RejectsABlankBusinessCentralCode(string? code) + { + var ok = CatalogItemValidator.TryNormalize(Valid() with { BusinessCentralCode = code }, out _, out var errors); + + Assert.False(ok); + Assert.Contains(nameof(CatalogItemRequest.BusinessCentralCode), errors.Keys); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void TryNormalize_RejectsABlankUnit(string? unit) + { + var ok = CatalogItemValidator.TryNormalize(Valid() with { Unit = unit }, out _, out var errors); + + Assert.False(ok); + Assert.Contains(nameof(CatalogItemRequest.Unit), errors.Keys); + } + + [Theory] + [InlineData("a")] + [InlineData("AB")] + [InlineData("")] + [InlineData(null)] + public void TryNormalize_RejectsAQualityClassThatIsNotOneCapitalLetter(string? qualityClass) + { + var ok = CatalogItemValidator.TryNormalize(Valid() with { QualityClass = qualityClass }, out _, out var errors); + + Assert.False(ok); + Assert.Contains(nameof(CatalogItemRequest.QualityClass), errors.Keys); + } + + private static CatalogItemRequest Valid() => new("Pain", "Boulangerie", "BC-001", "kg", "A"); +} diff --git a/tests/MoissonMontreal.Tests/Api/CatalogItemsMigrationTests.cs b/tests/MoissonMontreal.Tests/Api/CatalogItemsMigrationTests.cs new file mode 100644 index 0000000..6690955 --- /dev/null +++ b/tests/MoissonMontreal.Tests/Api/CatalogItemsMigrationTests.cs @@ -0,0 +1,160 @@ +using System.Data.Common; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using MoissonMontreal.Api.Data; +using MoissonMontreal.Api.Data.Configurations; +using MoissonMontreal.Core.Entities; +using MoissonMontreal.Tests.Fixtures; + +namespace MoissonMontreal.Tests.Api; + +[Trait("Category", "Integration")] +public class CatalogItemsMigrationTests(PostgresFixture postgres) : IClassFixture +{ + private const string MigrationBeforeCatalogItemDetails = "20261112060008_CreateQualityClasses"; + + [Fact] + public async Task Migrate_FillsExistingCatalogItems_WithPlaceholderValues() + { + await using var context = CreateContext("catalog_upgrade"); + await context.GetService().MigrateAsync(MigrationBeforeCatalogItemDetails); + await context.Database.ExecuteSqlRawAsync(""" + INSERT INTO catalog_items (id, name) VALUES + ('00000000-0000-0000-0000-0000000000c1', 'Pain'), + ('00000000-0000-0000-0000-0000000000c2', 'Pommes'); + """); + + await context.Database.MigrateAsync(); + + var items = await context.CatalogItems.OrderBy(item => item.Name).ToListAsync(); + Assert.Equal(["Pain", "Pommes"], items.Select(item => item.Name)); + Assert.All(items, item => + { + Assert.Equal("To classify", item.Category); + Assert.Equal($"TO-FIX-{item.Id}", item.BusinessCentralCode); + Assert.Equal("unit", item.Unit); + Assert.Equal("A", item.QualityClassCode); + }); + } + + [Fact] + public async Task CatalogItem_StoresCategoryBusinessCentralCodeUnitAndQualityClass() + { + var seed = await SeedAsync(); + + await using var context = CreateContext(); + var saved = await context.CatalogItems.Include(item => item.QualityClass).SingleAsync(item => item.Id == seed.Id); + + Assert.Equal("Boulangerie", saved.Category); + Assert.Equal(seed.Code, saved.BusinessCentralCode); + Assert.Equal("kg", saved.Unit); + Assert.Equal("A", saved.QualityClassCode); + Assert.Equal("A", saved.QualityClass.Code); + Assert.Null(saved.UpdatedAt); + } + + [Fact] + public async Task SaveChanges_Throws_WhenBusinessCentralCodeIsDuplicated() + { + var seed = await SeedAsync(); + + await using var context = CreateContext(); + context.CatalogItems.Add(Item(code: seed.Code, name: "Pain blanc")); + + await PostgresConstraintAssertions.AssertViolatesConstraintAsync(context, CatalogItemConfiguration.BusinessCentralCodeIndex); + } + + [Fact] + public async Task SaveChanges_Throws_WhenCategoryIsEmpty() + { + await using var context = CreateContext(); + await context.Database.MigrateAsync(); + context.CatalogItems.Add(Item(category: "")); + + await PostgresConstraintAssertions.AssertViolatesConstraintAsync(context, "ck_catalog_items_category_not_empty"); + } + + [Fact] + public async Task SaveChanges_Throws_WhenBusinessCentralCodeIsEmpty() + { + await using var context = CreateContext(); + await context.Database.MigrateAsync(); + context.CatalogItems.Add(Item(code: "")); + + await PostgresConstraintAssertions.AssertViolatesConstraintAsync(context, "ck_catalog_items_business_central_code_not_empty"); + } + + [Fact] + public async Task SaveChanges_Throws_WhenUnitIsEmpty() + { + await using var context = CreateContext(); + await context.Database.MigrateAsync(); + context.CatalogItems.Add(Item(unit: "")); + + await PostgresConstraintAssertions.AssertViolatesConstraintAsync(context, "ck_catalog_items_unit_not_empty"); + } + + [Fact] + public async Task SaveChanges_Throws_WhenQualityClassDoesNotExist() + { + await using var context = CreateContext(); + await context.Database.MigrateAsync(); + context.CatalogItems.Add(Item(qualityClass: "Z")); + + await PostgresConstraintAssertions.AssertViolatesConstraintAsync(context, "fk_catalog_items_quality_classes_quality_class"); + } + + [Fact] + public async Task DeleteQualityClass_Throws_WhenACatalogItemUsesIt() + { + await SeedAsync(); + + await using var context = CreateContext(); + var quality = await context.QualityClasses.SingleAsync(q => q.Code == "A"); + context.QualityClasses.Remove(quality); + + await PostgresConstraintAssertions.AssertViolatesConstraintAsync(context, "fk_catalog_items_quality_classes_quality_class"); + } + + private async Task SeedAsync() + { + await using var context = CreateContext(); + await context.Database.MigrateAsync(); + + var code = "BC-" + Guid.NewGuid().ToString("N")[..12]; + var item = Item(code: code); + context.CatalogItems.Add(item); + await context.SaveChangesAsync(); + return new Seed(item.Id, code); + } + + private static CatalogItem Item( + string name = "Pain", + string category = "Boulangerie", + string code = "BC-PAIN", + string unit = "kg", + string qualityClass = "A") => new() + { + Name = name, + Category = category, + BusinessCentralCode = code, + Unit = unit, + QualityClassCode = qualityClass, + }; + + private MoissonDbContext CreateContext(string? database = null) + { + var connectionString = postgres.ConnectionString; + if (database is not null) + { + var builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; + builder["Database"] = database; + connectionString = builder.ConnectionString; + } + + return new MoissonDbContext(new DbContextOptionsBuilder().UseNpgsql(connectionString).Options); + } + + private sealed record Seed(Guid Id, string Code); +} diff --git a/tests/MoissonMontreal.Tests/Api/PricesMigrationTests.cs b/tests/MoissonMontreal.Tests/Api/PricesMigrationTests.cs index d91fd6b..7b4f9c6 100644 --- a/tests/MoissonMontreal.Tests/Api/PricesMigrationTests.cs +++ b/tests/MoissonMontreal.Tests/Api/PricesMigrationTests.cs @@ -211,7 +211,14 @@ public async Task SaveChanges_Throws_WhenCatalogItemNameIsEmpty() await using var context = CreateContext(); await context.Database.MigrateAsync(); - context.CatalogItems.Add(new CatalogItem { Name = "" }); + context.CatalogItems.Add(new CatalogItem + { + Name = "", + Category = "Boulangerie", + BusinessCentralCode = "BC-EMPTY", + Unit = "kg", + QualityClassCode = "A", + }); await PostgresConstraintAssertions.AssertViolatesConstraintAsync(context, "ck_catalog_items_name_not_empty"); } @@ -359,7 +366,14 @@ private async Task AddCatalogItemAsync(string name) await using var context = CreateContext(); await context.Database.MigrateAsync(); - var item = new CatalogItem { Name = name }; + var item = new CatalogItem + { + Name = name, + Category = "Boulangerie", + BusinessCentralCode = "BC-" + Guid.NewGuid().ToString("N")[..12], + Unit = "kg", + QualityClassCode = "A", + }; context.CatalogItems.Add(item); await context.SaveChangesAsync(); diff --git a/tests/MoissonMontreal.Tests/Fixtures/CatalogApiFactory.cs b/tests/MoissonMontreal.Tests/Fixtures/CatalogApiFactory.cs new file mode 100644 index 0000000..5bdf9dc --- /dev/null +++ b/tests/MoissonMontreal.Tests/Fixtures/CatalogApiFactory.cs @@ -0,0 +1,58 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.EntityFrameworkCore; +using MoissonMontreal.Api.Data; +using MoissonMontreal.Core.Entities; +using Testcontainers.PostgreSql; + +namespace MoissonMontreal.Tests.Fixtures; + +/// +/// API host signed in with a test token and backed by a disposable PostgreSQL database. +/// +public sealed class CatalogApiFactory : AuthenticatedApiFactory, IAsyncLifetime +{ + private readonly PostgreSqlContainer _container = new PostgreSqlBuilder("postgres:17").Build(); + + public string ConnectionString => _container.GetConnectionString(); + + public async Task InitializeAsync() + { + await _container.StartAsync(); + + var options = new DbContextOptionsBuilder().UseNpgsql(ConnectionString).Options; + await using var context = new MoissonDbContext(options); + await context.Database.MigrateAsync(); + } + + /// + /// Makes the signed-in test employee the only user, with the given role. + /// + public async Task SignInAsAsync(string roleCode) + { + await using var context = new MoissonDbContext( + new DbContextOptionsBuilder().UseNpgsql(ConnectionString).Options); + await context.Users.ExecuteDeleteAsync(); + var roleId = await context.Roles.Where(r => r.Code == roleCode).Select(r => r.Id).SingleAsync(); + context.Users.Add(new User + { + Email = Email, + DisplayName = Name, + RoleId = roleId, + IsActive = true, + EntraObjectId = Guid.Parse(ObjectId), + }); + await context.SaveChangesAsync(); + } + + async Task IAsyncLifetime.DisposeAsync() + { + await _container.DisposeAsync(); + await base.DisposeAsync(); + } + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + builder.UseSetting("ConnectionStrings:Moisson", ConnectionString); + } +}