diff --git a/.gitignore b/.gitignore
index b962736..3eba7bf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -483,4 +483,7 @@ $RECYCLE.BIN/
# PRD
PRD*.pdf
-PRD*.docx
\ No newline at end of file
+PRD*.docx
+
+# Real Business Central exports contain personal data (Loi 25): never commit them
+data/private/
diff --git a/docs/database/donation-imports.md b/docs/database/donation-imports.md
new file mode 100644
index 0000000..5a92222
--- /dev/null
+++ b/docs/database/donation-imports.md
@@ -0,0 +1,203 @@
+# Donation imports from Business Central
+
+When Moisson Montréal receives food, the operations team records it in Business Central as a purchase order. The import reads the lines of that purchase order from an Excel export, values each line with the price grid, and records the donations in the app, so nobody types them a second time. After each import, the team gets a report of what was imported, what was rejected and why.
+
+## The Business Central export
+
+The format below comes from a real purchase order exported from Business Central (purchase order COMA-000295). It is still to confirm with Moisson Montréal that this is the export the operations team will use for every donation (see Open points).
+
+| Item | Value |
+| --- | --- |
+| File | Excel workbook (.xlsx), 10 MB at most |
+| Sheet | `Lignes`, one row per line of the purchase order, headers on the first row |
+| Encoding and separators | None to handle: an .xlsx file is a zipped set of XML files in UTF-8, so accents such as in `Qualité` are always read correctly. A CSV or text file renamed to .xlsx is refused |
+| Columns read | `Type`, `N°`, `Description`, `Quantité`, `Code d'unité de mesure`, `Qualité du test`, and `N° ligne` when the export has it. Columns are found by their header, so their order does not matter and other columns, such as `Code d'emplacement`, are ignored. The straight and curly apostrophes are the same |
+| Numbers | A quantity saved as a number, or as text with a comma or a dot (`48,5` or `48.5`). At most 2 decimals |
+| Dates | The export has no date on its lines. The date of the donation is entered with the file (see Running an import) |
+| Donor | The export has no donor on its lines. The donor's Business Central code is entered with the file |
+| Formulas | Never calculated. Only the value Excel saved with the file is read, so a cell cannot run code |
+
+### Example
+
+| Type | N° | Description | Quantité | Code d'unité de mesure | Qualité du test |
+| --- | --- | --- | --- | --- | --- |
+| Article | 1000094 | Citron lime | 48 | CA | Bon |
+| Article | 1000112 | Poivron | 100 | CA | Moyen |
+| Commentaire | | Livraison reçue en deux fois | | | |
+
+### Quality
+
+The operations team writes the quality of each line in `Qualité du test`. It is turned into a quality class:
+
+| Qualité du test | Quality class | Share of the price kept |
+| --- | --- | --- |
+| Bon | A | 100 % |
+| Moyen | B | the default percentage of class B (50 %) |
+| Mauvais | C | 0 % |
+
+This correspondence is still to confirm with Moisson Montréal. It is written in one place, [BusinessCentralQuality.cs](../../src/MoissonMontreal.Core/Donations/BusinessCentralQuality.cs).
+
+### Edge cases
+
+| Case | What happens |
+| --- | --- |
+| A line that is not an article, such as `Commentaire` | Rejected with `NotAnItemLine` |
+| An empty row | Skipped, not counted |
+| A negative or zero quantity, such as a return | Rejected with `NegativeQuantity`. A return is not a donation |
+| The same item on several lines, such as 8 lines of Poivron | Each line is a separate donation |
+| A cell with an Excel error, such as `#DIV/0!` | Rejected with `ExcelError` |
+| A line that is not in kg, such as `CA` | Rejected with `UnitMismatch`. Prices are per kg (issue #28), and how to turn a case into kg is still open |
+| Total rows | None in the real export. A total row would have an empty or non-article type and be rejected |
+
+### Uniqueness key of a line
+
+Each line gets a key, stored in `food_items.source_key`, that never changes when the same purchase order is exported again:
+
+- `COMA-000295/line-20000` when the export has the Business Central line number (`N° ligne`), which is the safest key;
+- otherwise `COMA-000295/1000112#2`: the purchase order number, the item code and the position of the row among the rows of that item (the second Poivron row). Rejected rows count too, so when a rejected row is fixed and the file imported again, the rows after it keep their key. Comment lines do not change it.
+
+The key is unique in the database, so a line can become only one donation.
+
+## Running an import
+
+`POST api/donation-imports` with a form (`multipart/form-data`), for the Supply, Supply Director and Admin roles (ManageDonations permission):
+
+| Field | Example |
+| --- | --- |
+| `file` | the .xlsx export |
+| `donorCode` | `F-100`, the donor's Business Central code (see [donors.md](donors.md)) |
+| `documentNumber` | `COMA-000295` |
+| `donationDate` | `2026-11-15` |
+| `confirmDuplicate` | `true` only to import again a file that was already imported |
+
+The import then:
+
+1. checks the file: not empty, at most 10 MB, an .xlsx file, a `Lignes` sheet with the required columns and at least one row;
+2. reads every row and checks it without stopping at the first problem;
+3. finds the catalog item of each line through its confirmed mapping (see [catalog.md](catalog.md));
+4. values each line with the price in effect on the donation date and the percentage of its quality class, with the calculation and rounding of [receipts.md](receipts.md);
+5. saves the import, its donations and its errors in one transaction.
+
+Valid lines are imported and invalid lines are rejected with their reason. If anything fails while saving, for example if the server stops, nothing is kept: there is never half an import.
+
+### Errors of a line
+
+| Code | Meaning |
+| --- | --- |
+| ExcelError | A cell contains an Excel error |
+| NotAnItemLine | The line is not an article |
+| MissingItemCode | The `N°` cell is empty |
+| MissingQuantity | The quantity is empty |
+| InvalidQuantity | The quantity is not a number with at most 2 decimals |
+| NegativeQuantity | The quantity is zero or negative |
+| MissingUnit | The unit is empty |
+| MissingQuality | The quality is empty |
+| UnknownQuality | The quality is not Bon, Moyen or Mauvais |
+| UnknownDonor | No donor has the Business Central code entered |
+| UnmappedItem | The item code has no confirmed mapping to a catalog item |
+| InactiveCatalogItem | The item is mapped to a catalog item that is no longer in the price grid |
+| UnitMismatch | The line is not in kg, the unit of every price, or its unit differs from the unit of the catalog item |
+| NoPriceOnDate | The catalog item has no price on the donation date |
+
+### The report and its endpoints
+
+| Endpoint | Returns |
+| --- | --- |
+| `POST api/donation-imports` | 201 with the report: rows read, imported, rejected and already imported, total value, who imported it and when, the unmapped items and the unknown donors |
+| `GET api/donation-imports?page=1&pageSize=20` | The history of imports, newest first |
+| `GET api/donation-imports/{id}` | The report of one import |
+| `GET api/donation-imports/{id}/errors?page=1&pageSize=50` | The rejected rows with their row number, code and message, in row order |
+| `GET api/donation-imports/{id}/lines?page=1&pageSize=50` | The imported donations with their frozen price, percentage and value |
+
+A file problem returns 400 with a clear message. A role that cannot manage donations gets 403.
+
+### Importing the same file twice
+
+The import stores the SHA-256 checksum of each file. If the same file is imported again, the API answers 409 with the date and the author of the first import, and asks for `confirmDuplicate=true`. Even then, a line already imported is skipped and counted as already imported, never recorded twice. Two files that overlap, such as the same purchase order exported again with one more line, only import the new line.
+
+## Hand-checked values
+
+These values were calculated by hand and are checked by `Import_ValuesEachLineAsCheckedByHand_AndFreezesThePriceAndPercentage`. Prices are in effect from 2026-11-01, and the donation date is 2026-11-15.
+
+| Item | Quantity | Price per kg | Quality | Calculation | Value |
+| --- | --- | --- | --- | --- | --- |
+| Citron lime | 48 KG | $12.50 | Bon, A 100 % | 48 × 12.50 × 1 = 600.00 | $600.00 |
+| Poivron | 100 KG | $18.75 | Moyen, B 50 % | 100 × 18.75 × 0.5 = 937.50 | $937.50 |
+| Tomate | 56 KG | $9.99 | Bon, A 100 % | 56 × 9.99 × 1 = 559.44 | $559.44 |
+| Brocoli | 32 KG | $14.333 | Moyen, B 50 % | 32 × 14.333 × 0.5 = 229.328 | $229.33 |
+| Fruits et Légumes variés | 46 KG | $7.1235 | Bon, A 100 % | 46 × 7.1235 × 1 = 327.681 | $327.68 |
+| Pomme | 1 KG | $0.45 | Moyen, B 50 % | 1 × 0.45 × 0.5 = 0.225, halfway rounded up | $0.23 |
+| Laitue | 20 KG | $3.00 | Mauvais, C 0 % | 20 × 3.00 × 0 = 0 | $0.00 |
+| Total | | | | | $2,654.18 |
+
+## Tables
+
+### donation_imports
+
+| Column | Meaning |
+| --- | --- |
+| id | Code that identifies the import |
+| file_name | Name of the file imported |
+| file_sha256 | SHA-256 checksum of the file |
+| document_number | Purchase order number, such as COMA-000295 |
+| donor_code | Business Central code of the donor, as entered |
+| donor_id | The donor with that code, empty if no donor has it |
+| donation_date | Date of the donation |
+| status | Imported, ImportedWithErrors (some rows rejected) or NothingImported |
+| rows_read, rows_imported, rows_rejected, rows_already_imported | Counts of the report |
+| total_value | Sum of the values imported, in dollars and cents |
+| imported_by_user_id | The employee who ran the import |
+| imported_at | Date and time of the import, stored in UTC |
+
+### donation_import_errors
+
+One row per rejected row: the import, the row number, the error code, the message and the item code when there is one. The errors are deleted with their import.
+
+### New columns of food_items
+
+| Column | Meaning |
+| --- | --- |
+| business_central_code | Item code in Business Central |
+| unit_price, price_effective_date | Price of one unit used, and the date it started to apply |
+| quality_percent | Percentage of the price kept |
+| value | quantity × unit_price × quality_percent / 100, rounded to the cent |
+| donation_import_id | The import that created the donation, empty for a donation entered by hand |
+| source_key | The Business Central line it comes from, unique |
+
+Amounts, quantities and percentages are exact decimal numbers, never floating-point numbers.
+
+## Rules enforced by the database
+
+1. A source line can be imported only once: `source_key` is unique.
+2. An imported donation has a source key, and a donation entered by hand has none.
+3. The price, its date, the percentage and the value are all set or all empty.
+4. A price is greater than 0, a percentage is between 0 and 100, and a value is not negative.
+5. The counts of an import add up, and its checksum is 64 lowercase hexadecimal characters.
+6. An import cannot be deleted while it has donations, and an employee or a donor cannot be deleted while an import points to them.
+
+## Real files and personal data
+
+A real export can contain personal data, such as the name and address of a donor who is a person (Loi 25).
+
+- A real export is never committed. Keep it in the restricted folder of Moisson Montréal agreed with the team, or locally in `data/private/`, which Git ignores.
+- Only the anonymized sample [samples/purchase-order-lines-anonymized.xlsx](samples/purchase-order-lines-anonymized.xlsx) is versioned. It keeps the structure and the awkward cases of the real export (repeated items, a comment line, an empty row, a return, a missing quality, a quantity written with a comma) but contains no donor nor any personal data. `Read_ReadsTheAnonymizedSampleOfTheRealExport_WithoutABlockingError` reads it.
+
+## Migration
+
+| Item | Location |
+| --- | --- |
+| Entity Framework migration | [20261204063259_AddDonationImports](../../src/MoissonMontreal.Api/Data/Migrations/20261204063259_AddDonationImports.cs) |
+| Equivalent SQL script | [0014_add_donation_imports.sql](sql/0014_add_donation_imports.sql) |
+| Code | [DonationExportReader.cs](../../src/MoissonMontreal.Api/Donations/DonationExportReader.cs), [DonationImporter.cs](../../src/MoissonMontreal.Api/Donations/DonationImporter.cs) and [DonationImportsController.cs](../../src/MoissonMontreal.Api/Controllers/DonationImportsController.cs) |
+
+The SQL script is generated with `dotnet ef migrations script AddUserAccountChanges AddDonationImports --project src/MoissonMontreal.Api --output docs/database/sql/0014_add_donation_imports.sql`, and its byte order mark is removed. Donations that existed before the migration keep empty values in the new columns.
+
+## Open points
+
+To confirm with Moisson Montréal:
+
+- That the purchase order lines are the export to use for every donation, and whether it can include the line number (`N° ligne`).
+- The correspondence between `Qualité du test` and the quality classes, and how a class B percentage other than the default is chosen.
+- How to turn a line counted in cases (`CA`) into kg, so it can be valued. Until then it is rejected.
+- Whether a single invalid row should cancel the whole import. For now the valid rows are imported and the others are rejected, which is the usual practice.
+- Whether an unknown donor should be created automatically. For now the lines are rejected and the donor is listed in the report, to avoid duplicate donors.
diff --git a/docs/database/images/prices.png b/docs/database/images/prices.png
index f2783fc..3fc868a 100644
Binary files a/docs/database/images/prices.png and b/docs/database/images/prices.png differ
diff --git a/docs/database/images/quality-classes.png b/docs/database/images/quality-classes.png
index a4a8407..bbcdb92 100644
Binary files a/docs/database/images/quality-classes.png and b/docs/database/images/quality-classes.png differ
diff --git a/docs/database/images/receipts.png b/docs/database/images/receipts.png
index 6d4d36f..753a1df 100644
Binary files a/docs/database/images/receipts.png and b/docs/database/images/receipts.png differ
diff --git a/docs/database/images/schema.png b/docs/database/images/schema.png
index c11ea35..763e0af 100644
Binary files a/docs/database/images/schema.png and b/docs/database/images/schema.png differ
diff --git a/docs/database/prices.dbml b/docs/database/prices.dbml
index a7d1ac7..7fd6743 100644
--- a/docs/database/prices.dbml
+++ b/docs/database/prices.dbml
@@ -3,6 +3,8 @@
// Matches the migration 20261110175320_CreateCatalogItemsAndPrices.
// donors and food_items come from the migration 20261105163138_CreateDonorsAndFoodItems (donor profile columns from 20261128005314_AddDonorProfile, active flag and search name from 20261128222105_AddDonorListSearch)
// and are shown here because each donation links to its catalog item.
+// roles, users and donation_imports (20261103000127_CreateUsersAndRoles and 20261204063259_AddDonationImports)
+// are shown because an imported donation links to its import.
// quality_classes comes from 20261112060008_CreateQualityClasses and is shown because each donation links to its quality class.
Table catalog_items {
@@ -94,6 +96,13 @@ Table food_items {
quality varchar(1) [not null, note: 'Code of the quality class']
catalog_item_id uuid [null, note: 'Catalog item of the donation, which gives its price. Empty until it is matched to the catalog']
created_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
+ business_central_code varchar(50) [null, note: 'Business Central item code, for an imported donation']
+ unit_price numeric(12,4) [null, note: 'Price of one unit copied from the price grid when the donation was imported']
+ price_effective_date date [null, note: 'Date that price started to apply']
+ quality_percent numeric(5,2) [null, note: 'Percentage of the price kept, copied when the donation was imported']
+ value numeric(12,2) [null, note: 'quantity x unit_price x quality_percent / 100, rounded to the cent']
+ donation_import_id uuid [null, note: 'Import that created the donation, empty for a donation entered by hand']
+ source_key varchar(120) [null, note: 'Business Central line the donation comes from, such as COMA-000295/1000112#2']
indexes {
id [pk, name: 'pk_food_items']
@@ -101,12 +110,19 @@ Table food_items {
donor_id [name: 'ix_food_items_donor_id']
catalog_item_id [name: 'ix_food_items_catalog_item_id']
quality [name: 'ix_food_items_quality']
+ donation_import_id [name: 'ix_food_items_donation_import_id']
+ source_key [unique, name: 'ix_food_items_source_key']
}
checks {
`length(name) > 0` [name: 'ck_food_items_name_not_empty']
`quantity > 0` [name: 'ck_food_items_quantity_positive']
`length(unit) > 0` [name: 'ck_food_items_unit_not_empty']
+ `unit_price > 0` [name: 'ck_food_items_unit_price_positive']
+ `quality_percent BETWEEN 0 AND 100` [name: 'ck_food_items_quality_percent_range']
+ `value >= 0` [name: 'ck_food_items_value_not_negative']
+ `(unit_price IS NULL) = (price_effective_date IS NULL) AND (unit_price IS NULL) = (quality_percent IS NULL) AND (unit_price IS NULL) = (value IS NULL)` [name: 'ck_food_items_frozen_value_complete']
+ `(donation_import_id IS NULL) = (source_key IS NULL)` [name: 'ck_food_items_imported_has_source_key']
}
Note: 'Food donated by a donor, with its date and quality'
@@ -134,6 +150,82 @@ Table quality_classes {
Note: 'Quality classes of donated food. Initial values follow the PRD and are to be confirmed with Nafissa'
}
+Table roles {
+ id integer [not null, note: 'Fixed values, inserted by the migration']
+ code varchar(50) [not null, note: 'Stable identifier used by the permission checks']
+ name varchar(100) [not null, note: 'Label shown in the app']
+
+ indexes {
+ id [pk, name: 'pk_roles']
+ code [unique, name: 'ix_roles_code']
+ name [unique, name: 'ix_roles_name']
+ }
+
+ Note: 'Department-based roles that determine what a user can see and do'
+}
+
+Table users {
+ id integer [not null, increment]
+ email varchar(256) [not null, note: 'Work email, always lowercase']
+ entra_object_id uuid [null, note: 'Microsoft Entra id, filled on the first permission check']
+ display_name varchar(200) [not null]
+ role_id integer [not null]
+ is_active boolean [not null, default: true, note: 'False once the admin removes access']
+ 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_users']
+ email [unique, name: 'ix_users_email']
+ entra_object_id [unique, name: 'ix_users_entra_object_id']
+ role_id [name: 'ix_users_role_id']
+ }
+
+ checks {
+ `email = lower(email)` [name: 'ck_users_email_lowercase']
+ }
+
+ Note: 'Employees allowed to use the app'
+}
+
+Table donation_imports {
+ id uuid [not null, default: `gen_random_uuid()`]
+ file_name varchar(255) [not null]
+ file_sha256 character(64) [not null, note: 'SHA-256 checksum of the file, to detect a second import of the same file']
+ document_number varchar(50) [not null, note: 'Business Central purchase order number, such as COMA-000295']
+ donor_code varchar(50) [not null, note: 'Business Central code of the donor, as entered for the import']
+ donor_id uuid [null, note: 'Donor that has this code, empty when no donor has it']
+ donation_date date [not null]
+ status varchar(30) [not null, note: 'Imported, ImportedWithErrors or NothingImported']
+ rows_read integer [not null]
+ rows_imported integer [not null]
+ rows_rejected integer [not null]
+ rows_already_imported integer [not null, note: 'Lines skipped because an earlier import already created them']
+ total_value numeric(14,2) [not null, note: 'Sum of the values of the imported lines, in dollars']
+ imported_by_user_id integer [not null]
+ imported_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
+
+ indexes {
+ id [pk, name: 'pk_donation_imports']
+ file_sha256 [name: 'ix_donation_imports_file_sha256']
+ imported_at [name: 'ix_donation_imports_imported_at']
+ donor_id [name: 'ix_donation_imports_donor_id']
+ imported_by_user_id [name: 'ix_donation_imports_imported_by_user_id']
+ }
+
+ checks {
+ `length(file_name) > 0` [name: 'ck_donation_imports_file_name_not_empty']
+ `file_sha256 ~ '^[0-9a-f]{64}$'` [name: 'ck_donation_imports_file_sha256_format']
+ `length(document_number) > 0` [name: 'ck_donation_imports_document_number_not_empty']
+ `length(donor_code) > 0` [name: 'ck_donation_imports_donor_code_not_empty']
+ `status IN ('Imported', 'ImportedWithErrors', 'NothingImported')` [name: 'ck_donation_imports_status_valid']
+ `rows_imported >= 0 AND rows_rejected >= 0 AND rows_already_imported >= 0 AND rows_read = rows_imported + rows_rejected + rows_already_imported` [name: 'ck_donation_imports_counts_add_up']
+ `total_value >= 0` [name: 'ck_donation_imports_total_value_not_negative']
+ }
+
+ Note: 'One row per import of a Business Central export: the file, who imported it, when, and the counts of the report'
+}
+
Ref fk_food_items_donors_donor_id: food_items.donor_id > donors.id [delete: restrict]
Ref fk_food_items_catalog_items_catalog_item_id: food_items.catalog_item_id > catalog_items.id [delete: restrict]
@@ -143,3 +235,11 @@ Ref fk_food_items_quality_classes_quality: food_items.quality > quality_classes.
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]
+
+Ref fk_food_items_donation_imports_donation_import_id: food_items.donation_import_id > donation_imports.id [delete: restrict]
+
+Ref fk_donation_imports_donors_donor_id: donation_imports.donor_id > donors.id [delete: restrict]
+
+Ref fk_donation_imports_users_imported_by_user_id: donation_imports.imported_by_user_id > users.id [delete: restrict]
+
+Ref fk_users_roles_role_id: users.role_id > roles.id [delete: restrict]
diff --git a/docs/database/quality-classes.dbml b/docs/database/quality-classes.dbml
index c2cb0c7..70484ff 100644
--- a/docs/database/quality-classes.dbml
+++ b/docs/database/quality-classes.dbml
@@ -3,6 +3,8 @@
// Matches the migration 20261112060008_CreateQualityClasses.
// donors and food_items come from the migration 20261105163138_CreateDonorsAndFoodItems (donor profile columns from 20261128005314_AddDonorProfile, active flag and search name from 20261128222105_AddDonorListSearch)
// and are shown here because food items link to their quality class.
+// roles, users and donation_imports (20261103000127_CreateUsersAndRoles and 20261204063259_AddDonationImports)
+// are shown because an imported donation links to its import.
// catalog_items comes from 20261110175320_CreateCatalogItemsAndPrices and is shown because food items link to it.
Table quality_classes {
@@ -70,6 +72,13 @@ Table food_items {
quality varchar(1) [not null, note: 'Code of the quality class']
catalog_item_id uuid [null, note: 'Catalog item of the donation, which gives its price. Empty until it is matched to the catalog']
created_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
+ business_central_code varchar(50) [null, note: 'Business Central item code, for an imported donation']
+ unit_price numeric(12,4) [null, note: 'Price of one unit copied from the price grid when the donation was imported']
+ price_effective_date date [null, note: 'Date that price started to apply']
+ quality_percent numeric(5,2) [null, note: 'Percentage of the price kept, copied when the donation was imported']
+ value numeric(12,2) [null, note: 'quantity x unit_price x quality_percent / 100, rounded to the cent']
+ donation_import_id uuid [null, note: 'Import that created the donation, empty for a donation entered by hand']
+ source_key varchar(120) [null, note: 'Business Central line the donation comes from, such as COMA-000295/1000112#2']
indexes {
id [pk, name: 'pk_food_items']
@@ -77,12 +86,19 @@ Table food_items {
donor_id [name: 'ix_food_items_donor_id']
catalog_item_id [name: 'ix_food_items_catalog_item_id']
quality [name: 'ix_food_items_quality']
+ donation_import_id [name: 'ix_food_items_donation_import_id']
+ source_key [unique, name: 'ix_food_items_source_key']
}
checks {
`length(name) > 0` [name: 'ck_food_items_name_not_empty']
`quantity > 0` [name: 'ck_food_items_quantity_positive']
`length(unit) > 0` [name: 'ck_food_items_unit_not_empty']
+ `unit_price > 0` [name: 'ck_food_items_unit_price_positive']
+ `quality_percent BETWEEN 0 AND 100` [name: 'ck_food_items_quality_percent_range']
+ `value >= 0` [name: 'ck_food_items_value_not_negative']
+ `(unit_price IS NULL) = (price_effective_date IS NULL) AND (unit_price IS NULL) = (quality_percent IS NULL) AND (unit_price IS NULL) = (value IS NULL)` [name: 'ck_food_items_frozen_value_complete']
+ `(donation_import_id IS NULL) = (source_key IS NULL)` [name: 'ck_food_items_imported_has_source_key']
}
Note: 'Food donated by a donor, with its date and quality'
@@ -115,6 +131,82 @@ Table catalog_items {
Note: 'Types of food recognized by the app, with the Business Central code and the quality class'
}
+Table roles {
+ id integer [not null, note: 'Fixed values, inserted by the migration']
+ code varchar(50) [not null, note: 'Stable identifier used by the permission checks']
+ name varchar(100) [not null, note: 'Label shown in the app']
+
+ indexes {
+ id [pk, name: 'pk_roles']
+ code [unique, name: 'ix_roles_code']
+ name [unique, name: 'ix_roles_name']
+ }
+
+ Note: 'Department-based roles that determine what a user can see and do'
+}
+
+Table users {
+ id integer [not null, increment]
+ email varchar(256) [not null, note: 'Work email, always lowercase']
+ entra_object_id uuid [null, note: 'Microsoft Entra id, filled on the first permission check']
+ display_name varchar(200) [not null]
+ role_id integer [not null]
+ is_active boolean [not null, default: true, note: 'False once the admin removes access']
+ 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_users']
+ email [unique, name: 'ix_users_email']
+ entra_object_id [unique, name: 'ix_users_entra_object_id']
+ role_id [name: 'ix_users_role_id']
+ }
+
+ checks {
+ `email = lower(email)` [name: 'ck_users_email_lowercase']
+ }
+
+ Note: 'Employees allowed to use the app'
+}
+
+Table donation_imports {
+ id uuid [not null, default: `gen_random_uuid()`]
+ file_name varchar(255) [not null]
+ file_sha256 character(64) [not null, note: 'SHA-256 checksum of the file, to detect a second import of the same file']
+ document_number varchar(50) [not null, note: 'Business Central purchase order number, such as COMA-000295']
+ donor_code varchar(50) [not null, note: 'Business Central code of the donor, as entered for the import']
+ donor_id uuid [null, note: 'Donor that has this code, empty when no donor has it']
+ donation_date date [not null]
+ status varchar(30) [not null, note: 'Imported, ImportedWithErrors or NothingImported']
+ rows_read integer [not null]
+ rows_imported integer [not null]
+ rows_rejected integer [not null]
+ rows_already_imported integer [not null, note: 'Lines skipped because an earlier import already created them']
+ total_value numeric(14,2) [not null, note: 'Sum of the values of the imported lines, in dollars']
+ imported_by_user_id integer [not null]
+ imported_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
+
+ indexes {
+ id [pk, name: 'pk_donation_imports']
+ file_sha256 [name: 'ix_donation_imports_file_sha256']
+ imported_at [name: 'ix_donation_imports_imported_at']
+ donor_id [name: 'ix_donation_imports_donor_id']
+ imported_by_user_id [name: 'ix_donation_imports_imported_by_user_id']
+ }
+
+ checks {
+ `length(file_name) > 0` [name: 'ck_donation_imports_file_name_not_empty']
+ `file_sha256 ~ '^[0-9a-f]{64}$'` [name: 'ck_donation_imports_file_sha256_format']
+ `length(document_number) > 0` [name: 'ck_donation_imports_document_number_not_empty']
+ `length(donor_code) > 0` [name: 'ck_donation_imports_donor_code_not_empty']
+ `status IN ('Imported', 'ImportedWithErrors', 'NothingImported')` [name: 'ck_donation_imports_status_valid']
+ `rows_imported >= 0 AND rows_rejected >= 0 AND rows_already_imported >= 0 AND rows_read = rows_imported + rows_rejected + rows_already_imported` [name: 'ck_donation_imports_counts_add_up']
+ `total_value >= 0` [name: 'ck_donation_imports_total_value_not_negative']
+ }
+
+ Note: 'One row per import of a Business Central export: the file, who imported it, when, and the counts of the report'
+}
+
Ref fk_food_items_donors_donor_id: food_items.donor_id > donors.id [delete: restrict]
Ref fk_food_items_catalog_items_catalog_item_id: food_items.catalog_item_id > catalog_items.id [delete: restrict]
@@ -128,3 +220,11 @@ Records quality_classes(code, name, percentage, min_percentage, max_percentage)
'B', 'Imperfect', 50.00, 50.00, 75.00
'C', 'Near expiry', 0.00, 0.00, 0.00
}
+
+Ref fk_food_items_donation_imports_donation_import_id: food_items.donation_import_id > donation_imports.id [delete: restrict]
+
+Ref fk_donation_imports_donors_donor_id: donation_imports.donor_id > donors.id [delete: restrict]
+
+Ref fk_donation_imports_users_imported_by_user_id: donation_imports.imported_by_user_id > users.id [delete: restrict]
+
+Ref fk_users_roles_role_id: users.role_id > roles.id [delete: restrict]
diff --git a/docs/database/receipts.dbml b/docs/database/receipts.dbml
index 648436c..8fce4ec 100644
--- a/docs/database/receipts.dbml
+++ b/docs/database/receipts.dbml
@@ -5,6 +5,8 @@
// donors and food_items come from the migration 20261105163138_CreateDonorsAndFoodItems (donor profile columns from 20261128005314_AddDonorProfile, active flag and search name from 20261128222105_AddDonorListSearch),
// catalog_items from 20261110175320_CreateCatalogItemsAndPrices and quality_classes from 20261112060008_CreateQualityClasses.
// They are shown here because receipts link to them.
+// roles, users and donation_imports (20261103000127_CreateUsersAndRoles and 20261204063259_AddDonationImports)
+// are shown because an imported donation links to its import.
Table donors {
id uuid [not null, default: `gen_random_uuid()`]
@@ -49,6 +51,13 @@ Table food_items {
quality varchar(1) [not null, note: 'Code of the quality class']
catalog_item_id uuid [null, note: 'Catalog item of the donation, which gives its price. Empty until it is matched to the catalog']
created_at timestamptz [not null, default: `now()`]
+ business_central_code varchar(50) [null, note: 'Business Central item code, for an imported donation']
+ unit_price numeric(12,4) [null, note: 'Price of one unit copied from the price grid when the donation was imported']
+ price_effective_date date [null, note: 'Date that price started to apply']
+ quality_percent numeric(5,2) [null, note: 'Percentage of the price kept, copied when the donation was imported']
+ value numeric(12,2) [null, note: 'quantity x unit_price x quality_percent / 100, rounded to the cent']
+ donation_import_id uuid [null, note: 'Import that created the donation, empty for a donation entered by hand']
+ source_key varchar(120) [null, note: 'Business Central line the donation comes from, such as COMA-000295/1000112#2']
indexes {
id [pk, name: 'pk_food_items']
@@ -56,12 +65,19 @@ Table food_items {
donor_id [name: 'ix_food_items_donor_id']
catalog_item_id [name: 'ix_food_items_catalog_item_id']
quality [name: 'ix_food_items_quality']
+ donation_import_id [name: 'ix_food_items_donation_import_id']
+ source_key [unique, name: 'ix_food_items_source_key']
}
checks {
`length(name) > 0` [name: 'ck_food_items_name_not_empty']
`quantity > 0` [name: 'ck_food_items_quantity_positive']
`length(unit) > 0` [name: 'ck_food_items_unit_not_empty']
+ `unit_price > 0` [name: 'ck_food_items_unit_price_positive']
+ `quality_percent BETWEEN 0 AND 100` [name: 'ck_food_items_quality_percent_range']
+ `value >= 0` [name: 'ck_food_items_value_not_negative']
+ `(unit_price IS NULL) = (price_effective_date IS NULL) AND (unit_price IS NULL) = (quality_percent IS NULL) AND (unit_price IS NULL) = (value IS NULL)` [name: 'ck_food_items_frozen_value_complete']
+ `(donation_import_id IS NULL) = (source_key IS NULL)` [name: 'ck_food_items_imported_has_source_key']
}
Note: 'Food donated by a donor, with its date and quality'
@@ -170,6 +186,82 @@ Table receipt_items {
Note: 'Food items on a receipt. Line value = round(quantity x unit_price x quality_percent / 100, 2), half away from zero'
}
+Table roles {
+ id integer [not null, note: 'Fixed values, inserted by the migration']
+ code varchar(50) [not null, note: 'Stable identifier used by the permission checks']
+ name varchar(100) [not null, note: 'Label shown in the app']
+
+ indexes {
+ id [pk, name: 'pk_roles']
+ code [unique, name: 'ix_roles_code']
+ name [unique, name: 'ix_roles_name']
+ }
+
+ Note: 'Department-based roles that determine what a user can see and do'
+}
+
+Table users {
+ id integer [not null, increment]
+ email varchar(256) [not null, note: 'Work email, always lowercase']
+ entra_object_id uuid [null, note: 'Microsoft Entra id, filled on the first permission check']
+ display_name varchar(200) [not null]
+ role_id integer [not null]
+ is_active boolean [not null, default: true, note: 'False once the admin removes access']
+ 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_users']
+ email [unique, name: 'ix_users_email']
+ entra_object_id [unique, name: 'ix_users_entra_object_id']
+ role_id [name: 'ix_users_role_id']
+ }
+
+ checks {
+ `email = lower(email)` [name: 'ck_users_email_lowercase']
+ }
+
+ Note: 'Employees allowed to use the app'
+}
+
+Table donation_imports {
+ id uuid [not null, default: `gen_random_uuid()`]
+ file_name varchar(255) [not null]
+ file_sha256 character(64) [not null, note: 'SHA-256 checksum of the file, to detect a second import of the same file']
+ document_number varchar(50) [not null, note: 'Business Central purchase order number, such as COMA-000295']
+ donor_code varchar(50) [not null, note: 'Business Central code of the donor, as entered for the import']
+ donor_id uuid [null, note: 'Donor that has this code, empty when no donor has it']
+ donation_date date [not null]
+ status varchar(30) [not null, note: 'Imported, ImportedWithErrors or NothingImported']
+ rows_read integer [not null]
+ rows_imported integer [not null]
+ rows_rejected integer [not null]
+ rows_already_imported integer [not null, note: 'Lines skipped because an earlier import already created them']
+ total_value numeric(14,2) [not null, note: 'Sum of the values of the imported lines, in dollars']
+ imported_by_user_id integer [not null]
+ imported_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
+
+ indexes {
+ id [pk, name: 'pk_donation_imports']
+ file_sha256 [name: 'ix_donation_imports_file_sha256']
+ imported_at [name: 'ix_donation_imports_imported_at']
+ donor_id [name: 'ix_donation_imports_donor_id']
+ imported_by_user_id [name: 'ix_donation_imports_imported_by_user_id']
+ }
+
+ checks {
+ `length(file_name) > 0` [name: 'ck_donation_imports_file_name_not_empty']
+ `file_sha256 ~ '^[0-9a-f]{64}$'` [name: 'ck_donation_imports_file_sha256_format']
+ `length(document_number) > 0` [name: 'ck_donation_imports_document_number_not_empty']
+ `length(donor_code) > 0` [name: 'ck_donation_imports_donor_code_not_empty']
+ `status IN ('Imported', 'ImportedWithErrors', 'NothingImported')` [name: 'ck_donation_imports_status_valid']
+ `rows_imported >= 0 AND rows_rejected >= 0 AND rows_already_imported >= 0 AND rows_read = rows_imported + rows_rejected + rows_already_imported` [name: 'ck_donation_imports_counts_add_up']
+ `total_value >= 0` [name: 'ck_donation_imports_total_value_not_negative']
+ }
+
+ Note: 'One row per import of a Business Central export: the file, who imported it, when, and the counts of the report'
+}
+
Ref fk_food_items_donors_donor_id: food_items.donor_id > donors.id [delete: restrict]
Ref fk_food_items_catalog_items_catalog_item_id: food_items.catalog_item_id > catalog_items.id [delete: restrict]
@@ -183,3 +275,11 @@ 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]
Ref fk_receipt_items_food_items_food_item_id_donor_id: receipt_items.(food_item_id, donor_id) > food_items.(id, donor_id) [delete: restrict]
+
+Ref fk_food_items_donation_imports_donation_import_id: food_items.donation_import_id > donation_imports.id [delete: restrict]
+
+Ref fk_donation_imports_donors_donor_id: donation_imports.donor_id > donors.id [delete: restrict]
+
+Ref fk_donation_imports_users_imported_by_user_id: donation_imports.imported_by_user_id > users.id [delete: restrict]
+
+Ref fk_users_roles_role_id: users.role_id > roles.id [delete: restrict]
diff --git a/docs/database/samples/purchase-order-lines-anonymized.xlsx b/docs/database/samples/purchase-order-lines-anonymized.xlsx
new file mode 100644
index 0000000..a84c124
Binary files /dev/null and b/docs/database/samples/purchase-order-lines-anonymized.xlsx differ
diff --git a/docs/database/schema.dbml b/docs/database/schema.dbml
index e43ae08..64369ad 100644
--- a/docs/database/schema.dbml
+++ b/docs/database/schema.dbml
@@ -4,8 +4,8 @@
// 20261107041912_CreateReceipts, 20261110175320_CreateCatalogItemsAndPrices,
// 20261112060008_CreateQualityClasses, 20261117040905_AddCatalogItemDetails,
// 20261120031640_MakeCatalogItemQualityClassOptional, 20261124214039_AddBcItemMappings, 20261127052039_AddReceiptStatus,
-// 20261127053347_AddReceiptNumbers, 20261128005314_AddDonorProfile, 20261128222105_AddDonorListSearch
-// and 20261204061822_AddUserAccountChanges.
+// 20261127053347_AddReceiptNumbers, 20261128005314_AddDonorProfile, 20261128222105_AddDonorListSearch,
+// 20261204061822_AddUserAccountChanges and 20261204063259_AddDonationImports.
Project moisson_montreal {
database_type: 'PostgreSQL'
@@ -119,6 +119,13 @@ Table food_items {
quality varchar(1) [not null, note: 'Code of the quality class']
catalog_item_id uuid [null, note: 'Catalog item of the donation, which gives its price. Empty until it is matched to the catalog']
created_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
+ business_central_code varchar(50) [null, note: 'Business Central item code, for an imported donation']
+ unit_price numeric(12,4) [null, note: 'Price of one unit copied from the price grid when the donation was imported']
+ price_effective_date date [null, note: 'Date that price started to apply']
+ quality_percent numeric(5,2) [null, note: 'Percentage of the price kept, copied when the donation was imported']
+ value numeric(12,2) [null, note: 'quantity x unit_price x quality_percent / 100, rounded to the cent']
+ donation_import_id uuid [null, note: 'Import that created the donation, empty for a donation entered by hand']
+ source_key varchar(120) [null, note: 'Business Central line the donation comes from, such as COMA-000295/1000112#2']
indexes {
id [pk, name: 'pk_food_items']
@@ -126,17 +133,84 @@ Table food_items {
donor_id [name: 'ix_food_items_donor_id']
catalog_item_id [name: 'ix_food_items_catalog_item_id']
quality [name: 'ix_food_items_quality']
+ donation_import_id [name: 'ix_food_items_donation_import_id']
+ source_key [unique, name: 'ix_food_items_source_key']
}
checks {
`length(name) > 0` [name: 'ck_food_items_name_not_empty']
`quantity > 0` [name: 'ck_food_items_quantity_positive']
`length(unit) > 0` [name: 'ck_food_items_unit_not_empty']
+ `unit_price > 0` [name: 'ck_food_items_unit_price_positive']
+ `quality_percent BETWEEN 0 AND 100` [name: 'ck_food_items_quality_percent_range']
+ `value >= 0` [name: 'ck_food_items_value_not_negative']
+ `(unit_price IS NULL) = (price_effective_date IS NULL) AND (unit_price IS NULL) = (quality_percent IS NULL) AND (unit_price IS NULL) = (value IS NULL)` [name: 'ck_food_items_frozen_value_complete']
+ `(donation_import_id IS NULL) = (source_key IS NULL)` [name: 'ck_food_items_imported_has_source_key']
}
Note: 'Food donated by a donor, with its date and quality'
}
+Table donation_imports {
+ id uuid [not null, default: `gen_random_uuid()`]
+ file_name varchar(255) [not null]
+ file_sha256 character(64) [not null, note: 'SHA-256 checksum of the file, to detect a second import of the same file']
+ document_number varchar(50) [not null, note: 'Business Central purchase order number, such as COMA-000295']
+ donor_code varchar(50) [not null, note: 'Business Central code of the donor, as entered for the import']
+ donor_id uuid [null, note: 'Donor that has this code, empty when no donor has it']
+ donation_date date [not null]
+ status varchar(30) [not null, note: 'Imported, ImportedWithErrors or NothingImported']
+ rows_read integer [not null]
+ rows_imported integer [not null]
+ rows_rejected integer [not null]
+ rows_already_imported integer [not null, note: 'Lines skipped because an earlier import already created them']
+ total_value numeric(14,2) [not null, note: 'Sum of the values of the imported lines, in dollars']
+ imported_by_user_id integer [not null]
+ imported_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
+
+ indexes {
+ id [pk, name: 'pk_donation_imports']
+ file_sha256 [name: 'ix_donation_imports_file_sha256']
+ imported_at [name: 'ix_donation_imports_imported_at']
+ donor_id [name: 'ix_donation_imports_donor_id']
+ imported_by_user_id [name: 'ix_donation_imports_imported_by_user_id']
+ }
+
+ checks {
+ `length(file_name) > 0` [name: 'ck_donation_imports_file_name_not_empty']
+ `file_sha256 ~ '^[0-9a-f]{64}$'` [name: 'ck_donation_imports_file_sha256_format']
+ `length(document_number) > 0` [name: 'ck_donation_imports_document_number_not_empty']
+ `length(donor_code) > 0` [name: 'ck_donation_imports_donor_code_not_empty']
+ `status IN ('Imported', 'ImportedWithErrors', 'NothingImported')` [name: 'ck_donation_imports_status_valid']
+ `rows_imported >= 0 AND rows_rejected >= 0 AND rows_already_imported >= 0 AND rows_read = rows_imported + rows_rejected + rows_already_imported` [name: 'ck_donation_imports_counts_add_up']
+ `total_value >= 0` [name: 'ck_donation_imports_total_value_not_negative']
+ }
+
+ Note: 'One row per import of a Business Central export: the file, who imported it, when, and the counts of the report'
+}
+
+Table donation_import_errors {
+ id uuid [not null, default: `gen_random_uuid()`]
+ donation_import_id uuid [not null]
+ row_number integer [not null, note: 'Row of the Excel file']
+ code varchar(30) [not null, note: 'Error code, such as UnmappedItem']
+ message varchar(500) [not null, note: 'What is wrong and how to fix it']
+ business_central_code varchar(50) [null, note: 'Business Central item code of the row, when there is one']
+
+ indexes {
+ id [pk, name: 'pk_donation_import_errors']
+ (donation_import_id, row_number) [name: 'ix_donation_import_errors_donation_import_id_row_number']
+ }
+
+ checks {
+ `row_number >= 1` [name: 'ck_donation_import_errors_row_number_positive']
+ `code IN ('ExcelError', 'NotAnItemLine', 'MissingItemCode', 'MissingQuantity', 'InvalidQuantity', 'NegativeQuantity', 'MissingUnit', 'MissingQuality', 'UnknownQuality', 'UnknownDonor', 'UnmappedItem', 'InactiveCatalogItem', 'UnitMismatch', 'NoPriceOnDate')` [name: 'ck_donation_import_errors_code_valid']
+ `length(message) > 0` [name: 'ck_donation_import_errors_message_not_empty']
+ }
+
+ Note: 'Rows of an import that were rejected, with the reason'
+}
+
Table quality_classes {
code varchar(1) [not null, note: 'One capital letter from A to Z, such as A, B or C']
name varchar(100) [not null]
@@ -341,6 +415,14 @@ Table bc_item_mapping_changes {
Note: 'History of every change made to a mapping, with its author'
}
+Ref fk_food_items_donation_imports_donation_import_id: food_items.donation_import_id > donation_imports.id [delete: restrict]
+
+Ref fk_donation_imports_donors_donor_id: donation_imports.donor_id > donors.id [delete: restrict]
+
+Ref fk_donation_imports_users_imported_by_user_id: donation_imports.imported_by_user_id > users.id [delete: restrict]
+
+Ref fk_donation_import_errors_donation_imports_donation_import_id: donation_import_errors.donation_import_id > donation_imports.id [delete: cascade]
+
Ref fk_users_roles_role_id: users.role_id > roles.id [delete: restrict]
Ref fk_user_account_changes_users_user_id: user_account_changes.user_id > users.id [delete: restrict]
@@ -391,6 +473,8 @@ TableGroup donations {
donors
food_items
quality_classes
+ donation_imports
+ donation_import_errors
}
TableGroup tax_receipts {
diff --git a/docs/database/schema.md b/docs/database/schema.md
index a165050..03b79e3 100644
--- a/docs/database/schema.md
+++ b/docs/database/schema.md
@@ -7,7 +7,7 @@ The database has four parts:
| Part | Tables | What it holds |
| --- | --- | --- |
| Accounts | roles, users, user_account_changes | Who can use the app, what each person is allowed to do, and every change made to their access |
-| Donations | donors, food_items, quality_classes | Who gave food, what they gave, when, and in what condition |
+| Donations | donors, food_items, quality_classes, donation_imports, donation_import_errors | Who gave food, what they gave, when, in what condition, and which Business Central import brought it in |
| Tax receipts | receipts, receipt_items, receipt_status_changes, receipt_number_counters | The receipts given to donors, the value of each food item on them, every change of their status, and their numbers |
| Price grid | catalog_items, prices, bc_item_mappings, bc_item_mapping_changes | The types of food the app knows, the price of each one over time, and which Business Central item each one values |
@@ -51,7 +51,23 @@ More detail: [Donor profiles](donors.md).
The food given by a donor. Each row holds what the food is, the quantity and its unit (for example 12.50 kg), the date it was received, and its quality class (see quality_classes).
-Every food item belongs to one donor and has one quality class. It can also point to its catalog item (see catalog_items), which gives its price. That link stays empty until the donation is matched to the catalog, which is still to come.
+Every food item belongs to one donor and has one quality class. It can also point to its catalog item (see catalog_items), which gives its price. That link stays empty until the donation is matched to the catalog.
+
+A donation imported from Business Central also keeps the price of one unit, the percentage and the value used when it was imported, so its value never changes if the price grid changes later, and the Business Central line it comes from, so the same line is never imported twice.
+
+More detail: [Donation imports from Business Central](donation-imports.md).
+
+### donation_imports
+
+One row per import of a Business Central export: the file name and its checksum, the purchase order number, the donor, the date of the donation, who imported it and when, and the counts of the report (rows read, imported, rejected and already imported) with the total value imported.
+
+More detail: [Donation imports from Business Central](donation-imports.md).
+
+### donation_import_errors
+
+The rows of an import that were rejected, each with its row number in the Excel file, an error code and a message that says what to fix.
+
+More detail: [Donation imports from Business Central](donation-imports.md).
### quality_classes
@@ -171,6 +187,11 @@ The database itself refuses anything that would break these rules, even if there
- A donor is an individual or an organization.
- Two donors cannot have the same Business Central code, and a donor's code cannot be empty when it is set.
+**Donation imports**
+- A line of a Business Central export can become only one donation, even if the file is imported twice or two files overlap.
+- An imported donation keeps its price, percentage and value together: all of them or none.
+- The counts of an import always add up: rows read = imported + rejected + already imported.
+
**Receipt numbers**
- Two receipts cannot have the same number.
- An issued receipt always has a number, and a receipt that was never issued has none.
@@ -230,6 +251,7 @@ Each table comes from one of these migrations:
| donor profile | [20261128005314_AddDonorProfile](../../src/MoissonMontreal.Api/Data/Migrations/20261128005314_AddDonorProfile.cs) | [0011_add_donor_profile.sql](sql/0011_add_donor_profile.sql) | [donors.md](donors.md) |
| donor list and search | [20261128222105_AddDonorListSearch](../../src/MoissonMontreal.Api/Data/Migrations/20261128222105_AddDonorListSearch.cs) | [0012_add_donor_list_search.sql](sql/0012_add_donor_list_search.sql) | [donors.md](donors.md) |
| user_account_changes | [20261204061822_AddUserAccountChanges](../../src/MoissonMontreal.Api/Data/Migrations/20261204061822_AddUserAccountChanges.cs) | [0013_add_user_account_changes.sql](sql/0013_add_user_account_changes.sql) | [users-roles.md](users-roles.md) |
+| donation_imports, donation_import_errors, frozen value of food_items | [20261204063259_AddDonationImports](../../src/MoissonMontreal.Api/Data/Migrations/20261204063259_AddDonationImports.cs) | [0014_add_donation_imports.sql](sql/0014_add_donation_imports.sql) | [donation-imports.md](donation-imports.md) |
The SQL scripts must be run in order on an empty database.
diff --git a/docs/database/sql/0014_add_donation_imports.sql b/docs/database/sql/0014_add_donation_imports.sql
new file mode 100644
index 0000000..1f0b0b4
--- /dev/null
+++ b/docs/database/sql/0014_add_donation_imports.sql
@@ -0,0 +1,88 @@
+START TRANSACTION;
+ALTER TABLE food_items ADD business_central_code character varying(50);
+
+ALTER TABLE food_items ADD donation_import_id uuid;
+
+ALTER TABLE food_items ADD price_effective_date date;
+
+ALTER TABLE food_items ADD quality_percent numeric(5,2);
+
+ALTER TABLE food_items ADD source_key character varying(120);
+
+ALTER TABLE food_items ADD unit_price numeric(12,4);
+
+ALTER TABLE food_items ADD value numeric(12,2);
+
+CREATE TABLE donation_imports (
+ id uuid NOT NULL DEFAULT (gen_random_uuid()),
+ file_name character varying(255) NOT NULL,
+ file_sha256 character(64) NOT NULL,
+ document_number character varying(50) NOT NULL,
+ donor_code character varying(50) NOT NULL,
+ donor_id uuid,
+ donation_date date NOT NULL,
+ status character varying(30) NOT NULL,
+ rows_read integer NOT NULL,
+ rows_imported integer NOT NULL,
+ rows_rejected integer NOT NULL,
+ rows_already_imported integer NOT NULL,
+ total_value numeric(14,2) NOT NULL,
+ imported_by_user_id integer NOT NULL,
+ imported_at timestamp with time zone NOT NULL DEFAULT (now()),
+ CONSTRAINT pk_donation_imports PRIMARY KEY (id),
+ CONSTRAINT ck_donation_imports_counts_add_up CHECK (rows_imported >= 0 AND rows_rejected >= 0 AND rows_already_imported >= 0 AND rows_read = rows_imported + rows_rejected + rows_already_imported),
+ CONSTRAINT ck_donation_imports_document_number_not_empty CHECK (length(document_number) > 0),
+ CONSTRAINT ck_donation_imports_donor_code_not_empty CHECK (length(donor_code) > 0),
+ CONSTRAINT ck_donation_imports_file_name_not_empty CHECK (length(file_name) > 0),
+ CONSTRAINT ck_donation_imports_file_sha256_format CHECK (file_sha256 ~ '^[0-9a-f]{64}$'),
+ CONSTRAINT ck_donation_imports_status_valid CHECK (status IN ('Imported', 'ImportedWithErrors', 'NothingImported')),
+ CONSTRAINT ck_donation_imports_total_value_not_negative CHECK (total_value >= 0),
+ CONSTRAINT fk_donation_imports_donors_donor_id FOREIGN KEY (donor_id) REFERENCES donors (id) ON DELETE RESTRICT,
+ CONSTRAINT fk_donation_imports_users_imported_by_user_id FOREIGN KEY (imported_by_user_id) REFERENCES users (id) ON DELETE RESTRICT
+);
+
+CREATE TABLE donation_import_errors (
+ id uuid NOT NULL DEFAULT (gen_random_uuid()),
+ donation_import_id uuid NOT NULL,
+ row_number integer NOT NULL,
+ code character varying(30) NOT NULL,
+ message character varying(500) NOT NULL,
+ business_central_code character varying(50),
+ CONSTRAINT pk_donation_import_errors PRIMARY KEY (id),
+ CONSTRAINT ck_donation_import_errors_code_valid CHECK (code IN ('ExcelError', 'NotAnItemLine', 'MissingItemCode', 'MissingQuantity', 'InvalidQuantity', 'NegativeQuantity', 'MissingUnit', 'MissingQuality', 'UnknownQuality', 'UnknownDonor', 'UnmappedItem', 'InactiveCatalogItem', 'UnitMismatch', 'NoPriceOnDate')),
+ CONSTRAINT ck_donation_import_errors_message_not_empty CHECK (length(message) > 0),
+ CONSTRAINT ck_donation_import_errors_row_number_positive CHECK (row_number >= 1),
+ CONSTRAINT fk_donation_import_errors_donation_imports_donation_import_id FOREIGN KEY (donation_import_id) REFERENCES donation_imports (id) ON DELETE CASCADE
+);
+
+CREATE INDEX ix_food_items_donation_import_id ON food_items (donation_import_id);
+
+CREATE UNIQUE INDEX ix_food_items_source_key ON food_items (source_key);
+
+ALTER TABLE food_items ADD CONSTRAINT ck_food_items_frozen_value_complete CHECK ((unit_price IS NULL) = (price_effective_date IS NULL) AND (unit_price IS NULL) = (quality_percent IS NULL) AND (unit_price IS NULL) = (value IS NULL));
+
+ALTER TABLE food_items ADD CONSTRAINT ck_food_items_imported_has_source_key CHECK ((donation_import_id IS NULL) = (source_key IS NULL));
+
+ALTER TABLE food_items ADD CONSTRAINT ck_food_items_quality_percent_range CHECK (quality_percent BETWEEN 0 AND 100);
+
+ALTER TABLE food_items ADD CONSTRAINT ck_food_items_unit_price_positive CHECK (unit_price > 0);
+
+ALTER TABLE food_items ADD CONSTRAINT ck_food_items_value_not_negative CHECK (value >= 0);
+
+CREATE INDEX ix_donation_import_errors_donation_import_id_row_number ON donation_import_errors (donation_import_id, row_number);
+
+CREATE INDEX ix_donation_imports_donor_id ON donation_imports (donor_id);
+
+CREATE INDEX ix_donation_imports_file_sha256 ON donation_imports (file_sha256);
+
+CREATE INDEX ix_donation_imports_imported_at ON donation_imports (imported_at);
+
+CREATE INDEX ix_donation_imports_imported_by_user_id ON donation_imports (imported_by_user_id);
+
+ALTER TABLE food_items ADD CONSTRAINT fk_food_items_donation_imports_donation_import_id FOREIGN KEY (donation_import_id) REFERENCES donation_imports (id) ON DELETE RESTRICT;
+
+INSERT INTO "__EFMigrationsHistory" (migration_id, product_version)
+VALUES ('20261204063259_AddDonationImports', '10.0.13');
+
+COMMIT;
+
diff --git a/src/MoissonMontreal.Api/Catalog/BusinessCentralExportReader.cs b/src/MoissonMontreal.Api/Catalog/BusinessCentralExportReader.cs
index f814522..be71ca1 100644
--- a/src/MoissonMontreal.Api/Catalog/BusinessCentralExportReader.cs
+++ b/src/MoissonMontreal.Api/Catalog/BusinessCentralExportReader.cs
@@ -58,14 +58,14 @@ public static class BusinessCentralExportReader
/// The file is not an Excel file, has no Articles sheet, or misses a required column.
public static BusinessCentralExport Read(Stream file)
{
- using var workbook = OpenWorkbook(file);
-
- if (!workbook.TryGetWorksheet(SheetName, out var sheet))
- {
- throw new BusinessCentralExportException($"The file does not have a sheet named {SheetName}.");
- }
-
- var columns = FindColumns(sheet.Row(1));
+ using var workbook = BusinessCentralWorkbook.Open(file);
+ var sheet = BusinessCentralWorkbook.Sheet(workbook, SheetName);
+ var positions = BusinessCentralWorkbook.FindColumns(sheet, [TypeHeader, CodeHeader, NameHeader, UnitHeader]);
+ var columns = new ExportColumns(
+ Type: positions[TypeHeader],
+ Code: positions[CodeHeader],
+ Name: positions[NameHeader],
+ Unit: positions[UnitHeader]);
var rows = new List();
var errors = new List();
var lastRow = sheet.LastRowUsed()?.RowNumber() ?? 1;
@@ -81,7 +81,7 @@ public static BusinessCentralExport Read(Stream file)
var excelErrors = FindExcelErrors(line, columns);
if (excelErrors.Count > 0)
{
- var shownCode = SavedValue(line.Cell(columns.Code)).IsError ? string.Empty : code;
+ var shownCode = BusinessCentralWorkbook.SavedValue(line.Cell(columns.Code)).IsError ? string.Empty : code;
errors.Add(new CatalogImportError(rowNumber, shownCode, string.Join(" ", excelErrors)));
continue;
}
@@ -106,74 +106,7 @@ public static BusinessCentralExport Read(Stream file)
return new BusinessCentralExport(rows, errors);
}
- ///
- /// Opens the stream as an Excel workbook.
- ///
- /// Content of the file.
- /// The opened workbook. The caller disposes it.
- /// The file is not a valid .xlsx file.
- private static XLWorkbook OpenWorkbook(Stream file)
- {
- try
- {
- return new XLWorkbook(file);
- }
- // ClosedXML throws several exception types for a damaged or non-Excel file, so they are all turned into one clear message.
- catch (Exception exception) when (exception is not OperationCanceledException)
- {
- throw new BusinessCentralExportException("The file is not a valid Excel (.xlsx) file.", exception);
- }
- }
-
- ///
- /// Finds the position of each required column in the header row.
- ///
- /// First row of the sheet.
- /// The column number of each required column.
- /// One or more required columns are missing.
- private static ExportColumns FindColumns(IXLRow header)
- {
- var positions = new Dictionary(StringComparer.OrdinalIgnoreCase);
- foreach (var cell in header.CellsUsed())
- {
- positions.TryAdd(NormalizeHeader(ReadText(cell)), cell.Address.ColumnNumber);
- }
-
- string[] required = [TypeHeader, CodeHeader, NameHeader, UnitHeader];
- var missing = required.Where(name => !positions.ContainsKey(NormalizeHeader(name))).ToList();
- if (missing.Count > 0)
- {
- throw new BusinessCentralExportException($"The {SheetName} sheet is missing these columns: {string.Join(", ", missing)}.");
- }
-
- return new ExportColumns(
- Type: positions[NormalizeHeader(TypeHeader)],
- Code: positions[NormalizeHeader(CodeHeader)],
- Name: positions[NormalizeHeader(NameHeader)],
- Unit: positions[NormalizeHeader(UnitHeader)]);
- }
-
- ///
- /// Makes two spellings of the same header equal. Business Central writes some headers with a curly apostrophe (’) and others with a straight one (').
- ///
- /// Header as written in the file.
- /// The header without surrounding spaces and with straight apostrophes.
- private static string NormalizeHeader(string header) => header.Replace('’', '\'').Trim();
-
- ///
- /// Reads a cell as text. For a formula cell, the value saved in the file is read and the formula is never calculated.
- ///
- /// Cell to read.
- /// The text of the cell without surrounding spaces, or an empty string for an empty cell.
- private static string ReadText(IXLCell cell) =>
- SavedValue(cell).ToString(CultureInfo.InvariantCulture).Trim();
-
- ///
- /// Returns the value saved in a cell. For a formula cell, it is the result Excel saved with the file, and the formula is never calculated.
- ///
- /// Cell to read.
- /// The saved value, which can be text, a number, a date, empty or an Excel error.
- private static XLCellValue SavedValue(IXLCell cell) => cell.HasFormula ? cell.CachedValue : cell.Value;
+ private static string ReadText(IXLCell cell) => BusinessCentralWorkbook.ReadText(cell);
///
/// Lists the required cells of a line that contain an Excel error, such as #REF! or #N/A, so the line is reported instead of
@@ -193,19 +126,11 @@ private static List FindExcelErrors(IXLRow line, ExportColumns columns)
];
return requiredCells
- .Select(cell => (cell.Header, Value: SavedValue(line.Cell(cell.Column))))
- .Where(cell => cell.Value.IsError)
- .Select(cell => $"The {cell.Header} cell contains the Excel error {cell.Value.ToString(CultureInfo.InvariantCulture)}.")
+ .Select(cell => BusinessCentralWorkbook.ExcelError(line.Cell(cell.Column), cell.Header))
+ .OfType()
.ToList();
}
- ///
- /// Column number of each required column in the sheet.
- ///
- /// Column of the line type.
- /// Column of the Business Central code.
- /// Column of the item name.
- /// Column of the unit.
private readonly record struct ExportColumns(int Type, int Code, int Name, int Unit);
}
diff --git a/src/MoissonMontreal.Api/Catalog/BusinessCentralWorkbook.cs b/src/MoissonMontreal.Api/Catalog/BusinessCentralWorkbook.cs
new file mode 100644
index 0000000..5a0b6a5
--- /dev/null
+++ b/src/MoissonMontreal.Api/Catalog/BusinessCentralWorkbook.cs
@@ -0,0 +1,65 @@
+using System.Globalization;
+
+using ClosedXML.Excel;
+
+namespace MoissonMontreal.Api.Catalog;
+
+///
+/// Reading helpers shared by every Business Central export: opening the file, finding columns by their header and reading
+/// cells. A formula is never calculated: only the value Excel saved with the file is read, so a cell can never run code.
+///
+public static class BusinessCentralWorkbook
+{
+ public static XLWorkbook Open(Stream file)
+ {
+ try
+ {
+ return new XLWorkbook(file);
+ }
+ // ClosedXML throws several exception types for a damaged or non-Excel file, so they are all turned into one clear message.
+ catch (Exception exception) when (exception is not OperationCanceledException)
+ {
+ throw new BusinessCentralExportException("The file is not a valid Excel (.xlsx) file.", exception);
+ }
+ }
+
+ public static IXLWorksheet Sheet(XLWorkbook workbook, string sheetName) =>
+ workbook.TryGetWorksheet(sheetName, out var sheet)
+ ? sheet
+ : throw new BusinessCentralExportException($"The file does not have a sheet named {sheetName}.");
+
+ ///
+ /// Finds each required column by its header in the first row, so the import keeps working if Business Central adds or
+ /// moves columns. The straight and curly apostrophes are treated as the same character, since Business Central uses both.
+ ///
+ /// A required column is missing.
+ public static IReadOnlyDictionary FindColumns(IXLWorksheet sheet, IReadOnlyList requiredHeaders)
+ {
+ var positions = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var cell in sheet.Row(1).CellsUsed())
+ {
+ positions.TryAdd(NormalizeHeader(ReadText(cell)), cell.Address.ColumnNumber);
+ }
+
+ var missing = requiredHeaders.Where(header => !positions.ContainsKey(NormalizeHeader(header))).ToList();
+ if (missing.Count > 0)
+ {
+ throw new BusinessCentralExportException($"The {sheet.Name} sheet is missing these columns: {string.Join(", ", missing)}.");
+ }
+
+ return requiredHeaders.ToDictionary(header => header, header => positions[NormalizeHeader(header)]);
+ }
+
+ public static string ReadText(IXLCell cell) =>
+ SavedValue(cell).ToString(CultureInfo.InvariantCulture).Trim();
+
+ public static XLCellValue SavedValue(IXLCell cell) => cell.HasFormula ? cell.CachedValue : cell.Value;
+
+ public static string? ExcelError(IXLCell cell, string header)
+ {
+ var value = SavedValue(cell);
+ return value.IsError ? $"The {header} cell contains the Excel error {value.ToString(CultureInfo.InvariantCulture)}." : null;
+ }
+
+ private static string NormalizeHeader(string header) => header.Replace('’', '\'').Trim();
+}
diff --git a/src/MoissonMontreal.Api/Controllers/DonationImportsController.cs b/src/MoissonMontreal.Api/Controllers/DonationImportsController.cs
new file mode 100644
index 0000000..c6a38b3
--- /dev/null
+++ b/src/MoissonMontreal.Api/Controllers/DonationImportsController.cs
@@ -0,0 +1,296 @@
+using System.Linq.Expressions;
+using System.Security.Cryptography;
+
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+using MoissonMontreal.Api.Catalog;
+using MoissonMontreal.Api.Data;
+using MoissonMontreal.Api.Donations;
+using MoissonMontreal.Core.Authorization;
+using MoissonMontreal.Core.Donations;
+using MoissonMontreal.Core.Dtos;
+using MoissonMontreal.Core.Entities;
+
+namespace MoissonMontreal.Api.Controllers;
+
+[ApiController]
+[Route("api/donation-imports")]
+[Authorize(Policy = Permissions.ManageDonations)]
+public class DonationImportsController(DonationImporter importer, MoissonDbContext db) : ControllerBase
+{
+ public const long MaxFileBytes = 10 * 1024 * 1024;
+
+ public const int MaxPageSize = 100;
+
+ private const long MaxRequestBytes = MaxFileBytes + 1024 * 1024;
+
+ private const string ExcelExtension = ".xlsx";
+
+ private static readonly Expression> AsDto = i => new DonationImportDto(
+ i.Id,
+ i.FileName,
+ i.DocumentNumber,
+ i.DonorCode,
+ i.Donor == null ? null : i.Donor.Name,
+ i.DonationDate,
+ i.Status,
+ i.RowsRead,
+ i.RowsImported,
+ i.RowsRejected,
+ i.RowsAlreadyImported,
+ i.TotalValue,
+ i.ImportedBy.DisplayName,
+ i.ImportedAt);
+
+ [HttpPost]
+ [Consumes("multipart/form-data")]
+ [RequestSizeLimit(MaxRequestBytes)]
+ [RequestFormLimits(MultipartBodyLengthLimit = MaxRequestBytes)]
+ public async Task> Import(
+ IFormFile? file,
+ [FromForm] string? donorCode,
+ [FromForm] string? documentNumber,
+ [FromForm] DateOnly? donationDate,
+ [FromForm] bool confirmDuplicate,
+ CancellationToken cancellationToken)
+ {
+ var fieldErrors = CheckFields(donorCode, documentNumber, donationDate);
+ if (fieldErrors.Count > 0)
+ {
+ return ValidationProblem(new ValidationProblemDetails(fieldErrors));
+ }
+
+ if (file is null || file.Length == 0)
+ {
+ return FileProblem("No file was sent, or the file is empty. Send the Business Central export in a form field named file.");
+ }
+
+ if (file.Length > MaxFileBytes)
+ {
+ return FileProblem($"The file is too large. The limit is {MaxFileBytes / (1024 * 1024)} MB.");
+ }
+
+ if (!string.Equals(Path.GetExtension(file.FileName), ExcelExtension, StringComparison.OrdinalIgnoreCase))
+ {
+ return FileProblem($"The file must be an Excel file ({ExcelExtension}).");
+ }
+
+ using var content = new MemoryStream();
+ await using (var upload = file.OpenReadStream())
+ {
+ await upload.CopyToAsync(content, cancellationToken);
+ }
+
+ var checksum = Convert.ToHexStringLower(SHA256.HashData(content.GetBuffer().AsSpan(0, (int)content.Length)));
+ content.Position = 0;
+
+ DonationExport export;
+ try
+ {
+ export = DonationExportReader.Read(content);
+ }
+ catch (BusinessCentralExportException exception)
+ {
+ return FileProblem(exception.Message);
+ }
+
+ if (export.RowsRead == 0)
+ {
+ return FileProblem($"The {DonationExportReader.SheetName} sheet has no donation line.");
+ }
+
+ var request = new DonationImportRequest(
+ Path.GetFileName(file.FileName),
+ checksum,
+ documentNumber!,
+ donorCode!,
+ donationDate!.Value,
+ confirmDuplicate,
+ export);
+
+ DonationImport import;
+ try
+ {
+ import = await importer.ImportAsync(request, User, cancellationToken);
+ }
+ catch (DuplicateDonationImportException exception)
+ {
+ var problem = new ProblemDetails
+ {
+ Status = StatusCodes.Status409Conflict,
+ Title = "This file was already imported",
+ Detail = exception.Message,
+ };
+ problem.Extensions["previousImportId"] = exception.PreviousImportId;
+ problem.Extensions["importedAt"] = exception.ImportedAt;
+ problem.Extensions["importedBy"] = exception.ImportedBy;
+ return Conflict(problem);
+ }
+ catch (ConcurrentDonationImportException exception)
+ {
+ return Conflict(new ProblemDetails
+ {
+ Status = StatusCodes.Status409Conflict,
+ Title = "Lines imported at the same time",
+ Detail = exception.Message,
+ });
+ }
+
+ var report = await FindReportAsync(import.Id, cancellationToken);
+ return CreatedAtAction(nameof(Get), new { id = import.Id }, report);
+ }
+
+ [HttpGet]
+ public async Task>> List(
+ [FromQuery] int page = 1,
+ [FromQuery] int pageSize = 20,
+ CancellationToken cancellationToken = default)
+ {
+ if (PageProblem(page, pageSize) is { } problem)
+ {
+ return problem;
+ }
+
+ var imports = db.DonationImports.OrderByDescending(i => i.ImportedAt).ThenBy(i => i.Id);
+ return Page(
+ await imports.Skip((page - 1) * pageSize).Take(pageSize).Select(AsDto).ToListAsync(cancellationToken),
+ page,
+ pageSize,
+ await imports.CountAsync(cancellationToken));
+ }
+
+ [HttpGet("{id:guid}")]
+ public async Task> Get(Guid id, CancellationToken cancellationToken) =>
+ await FindReportAsync(id, cancellationToken) is { } report ? report : NotFound();
+
+ [HttpGet("{id:guid}/errors")]
+ public async Task>> Errors(
+ Guid id,
+ [FromQuery] int page = 1,
+ [FromQuery] int pageSize = 50,
+ CancellationToken cancellationToken = default)
+ {
+ if (PageProblem(page, pageSize) is { } problem)
+ {
+ return problem;
+ }
+
+ if (!await db.DonationImports.AnyAsync(i => i.Id == id, cancellationToken))
+ {
+ return NotFound();
+ }
+
+ var errors = db.DonationImportErrors.Where(e => e.DonationImportId == id).OrderBy(e => e.RowNumber).ThenBy(e => e.Id);
+ return Page(
+ await errors
+ .Skip((page - 1) * pageSize)
+ .Take(pageSize)
+ .Select(e => new DonationImportErrorDto(e.RowNumber, e.Code, e.Message, e.BusinessCentralCode))
+ .ToListAsync(cancellationToken),
+ page,
+ pageSize,
+ await errors.CountAsync(cancellationToken));
+ }
+
+ [HttpGet("{id:guid}/lines")]
+ public async Task>> Lines(
+ Guid id,
+ [FromQuery] int page = 1,
+ [FromQuery] int pageSize = 50,
+ CancellationToken cancellationToken = default)
+ {
+ if (PageProblem(page, pageSize) is { } problem)
+ {
+ return problem;
+ }
+
+ if (!await db.DonationImports.AnyAsync(i => i.Id == id, cancellationToken))
+ {
+ return NotFound();
+ }
+
+ var lines = db.FoodItems.Where(f => f.DonationImportId == id).OrderBy(f => f.SourceKey);
+ return Page(
+ await lines
+ .Skip((page - 1) * pageSize)
+ .Take(pageSize)
+ .Select(f => new DonationImportLineDto(
+ f.SourceKey!, f.BusinessCentralCode, f.Name, f.Quantity, f.Unit, f.Quality, f.QualityPercent, f.UnitPrice, f.PriceEffectiveDate, f.Value))
+ .ToListAsync(cancellationToken),
+ page,
+ pageSize,
+ await lines.CountAsync(cancellationToken));
+ }
+
+ private async Task FindReportAsync(Guid id, CancellationToken cancellationToken)
+ {
+ var import = await db.DonationImports.Where(i => i.Id == id).Select(AsDto).SingleOrDefaultAsync(cancellationToken);
+ if (import is null)
+ {
+ return null;
+ }
+
+ var unmapped = await db.DonationImportErrors
+ .Where(e => e.DonationImportId == id && e.Code == DonationImportErrorCode.UnmappedItem && e.BusinessCentralCode != null)
+ .Select(e => e.BusinessCentralCode!)
+ .Distinct()
+ .OrderBy(code => code)
+ .ToListAsync(cancellationToken);
+ var unknownDonors = await db.DonationImportErrors.AnyAsync(e => e.DonationImportId == id && e.Code == DonationImportErrorCode.UnknownDonor, cancellationToken)
+ ? [import.DonorCode]
+ : new List();
+
+ return new DonationImportReport(import, unmapped, unknownDonors);
+ }
+
+ private static Dictionary CheckFields(string? donorCode, string? documentNumber, DateOnly? donationDate)
+ {
+ var errors = new Dictionary();
+ if (string.IsNullOrWhiteSpace(donorCode))
+ {
+ errors["donorCode"] = ["The Business Central code of the donor is required."];
+ }
+ else if (donorCode.Trim().Length > DonationImport.DonorCodeMaxLength)
+ {
+ errors["donorCode"] = [$"The donor code must be {DonationImport.DonorCodeMaxLength} characters or fewer."];
+ }
+
+ if (string.IsNullOrWhiteSpace(documentNumber))
+ {
+ errors["documentNumber"] = ["The Business Central document number, such as COMA-000295, is required."];
+ }
+ else if (documentNumber.Trim().Length > DonationImport.DocumentNumberMaxLength)
+ {
+ errors["documentNumber"] = [$"The document number must be {DonationImport.DocumentNumberMaxLength} characters or fewer."];
+ }
+
+ if (donationDate is null)
+ {
+ errors["donationDate"] = ["The donation date is required, in the format yyyy-MM-dd."];
+ }
+
+ return errors;
+ }
+
+ private static PagedResult Page(IReadOnlyList items, int page, int pageSize, int totalCount) =>
+ new(items, page, pageSize, totalCount, (totalCount + pageSize - 1) / pageSize);
+
+ private BadRequestObjectResult? PageProblem(int page, int pageSize) =>
+ page < 1 || pageSize < 1 || pageSize > MaxPageSize
+ ? BadRequest(new ProblemDetails
+ {
+ Status = StatusCodes.Status400BadRequest,
+ Title = "Invalid page",
+ Detail = $"page must be 1 or more, and pageSize between 1 and {MaxPageSize}.",
+ })
+ : null;
+
+ private BadRequestObjectResult FileProblem(string detail) => BadRequest(new ProblemDetails
+ {
+ Status = StatusCodes.Status400BadRequest,
+ Title = "The file cannot be imported",
+ Detail = detail,
+ });
+}
diff --git a/src/MoissonMontreal.Api/Data/Configurations/DonationImportConfiguration.cs b/src/MoissonMontreal.Api/Data/Configurations/DonationImportConfiguration.cs
new file mode 100644
index 0000000..b244fe2
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Configurations/DonationImportConfiguration.cs
@@ -0,0 +1,55 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+using MoissonMontreal.Core.Donations;
+using MoissonMontreal.Core.Entities;
+
+namespace MoissonMontreal.Api.Data.Configurations;
+
+public class DonationImportConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable(t =>
+ {
+ t.HasCheckConstraint("ck_donation_imports_file_name_not_empty", "length(file_name) > 0");
+ t.HasCheckConstraint("ck_donation_imports_file_sha256_format", "file_sha256 ~ '^[0-9a-f]{64}$'");
+ t.HasCheckConstraint("ck_donation_imports_document_number_not_empty", "length(document_number) > 0");
+ t.HasCheckConstraint("ck_donation_imports_donor_code_not_empty", "length(donor_code) > 0");
+ t.HasCheckConstraint("ck_donation_imports_status_valid", EnumColumn.IsValid("status"));
+ t.HasCheckConstraint(
+ "ck_donation_imports_counts_add_up",
+ "rows_imported >= 0 AND rows_rejected >= 0 AND rows_already_imported >= 0 AND rows_read = rows_imported + rows_rejected + rows_already_imported");
+ t.HasCheckConstraint("ck_donation_imports_total_value_not_negative", "total_value >= 0");
+ });
+
+ builder.Property(i => i.Id).HasDefaultValueSql("gen_random_uuid()");
+
+ builder.Property(i => i.FileName).HasMaxLength(DonationImport.FileNameMaxLength);
+
+ builder.Property(i => i.FileSha256).HasMaxLength(64).IsFixedLength();
+
+ builder.HasIndex(i => i.FileSha256);
+
+ builder.Property(i => i.DocumentNumber).HasMaxLength(DonationImport.DocumentNumberMaxLength);
+
+ builder.Property(i => i.DonorCode).HasMaxLength(DonationImport.DonorCodeMaxLength);
+
+ builder.Property(i => i.Status).HasConversion().HasMaxLength(30);
+
+ builder.Property(i => i.TotalValue).HasPrecision(14, 2);
+
+ builder.Property(i => i.ImportedAt).HasDefaultValueSql("now()");
+
+ builder.HasIndex(i => i.ImportedAt);
+
+ builder.HasOne(i => i.Donor)
+ .WithMany()
+ .HasForeignKey(i => i.DonorId)
+ .OnDelete(DeleteBehavior.Restrict);
+
+ builder.HasOne(i => i.ImportedBy)
+ .WithMany()
+ .HasForeignKey(i => i.ImportedByUserId)
+ .OnDelete(DeleteBehavior.Restrict);
+ }
+}
diff --git a/src/MoissonMontreal.Api/Data/Configurations/DonationImportErrorConfiguration.cs b/src/MoissonMontreal.Api/Data/Configurations/DonationImportErrorConfiguration.cs
new file mode 100644
index 0000000..01ac20e
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Configurations/DonationImportErrorConfiguration.cs
@@ -0,0 +1,34 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+using MoissonMontreal.Core.Donations;
+using MoissonMontreal.Core.Entities;
+
+namespace MoissonMontreal.Api.Data.Configurations;
+
+public class DonationImportErrorConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable(t =>
+ {
+ t.HasCheckConstraint("ck_donation_import_errors_row_number_positive", "row_number >= 1");
+ t.HasCheckConstraint("ck_donation_import_errors_code_valid", EnumColumn.IsValid("code"));
+ t.HasCheckConstraint("ck_donation_import_errors_message_not_empty", "length(message) > 0");
+ });
+
+ builder.Property(e => e.Id).HasDefaultValueSql("gen_random_uuid()");
+
+ builder.Property(e => e.Code).HasConversion().HasMaxLength(30);
+
+ builder.Property(e => e.Message).HasMaxLength(DonationImportError.MessageMaxLength);
+
+ builder.Property(e => e.BusinessCentralCode).HasMaxLength(50);
+
+ builder.HasIndex(e => new { e.DonationImportId, e.RowNumber });
+
+ builder.HasOne(e => e.DonationImport)
+ .WithMany(i => i.Errors)
+ .HasForeignKey(e => e.DonationImportId)
+ .OnDelete(DeleteBehavior.Cascade);
+ }
+}
diff --git a/src/MoissonMontreal.Api/Data/Configurations/EnumColumn.cs b/src/MoissonMontreal.Api/Data/Configurations/EnumColumn.cs
new file mode 100644
index 0000000..2bde2d4
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Configurations/EnumColumn.cs
@@ -0,0 +1,7 @@
+namespace MoissonMontreal.Api.Data.Configurations;
+
+public static class EnumColumn
+{
+ public static string IsValid(string column) where TEnum : struct, Enum =>
+ $"{column} IN ({string.Join(", ", Enum.GetNames().Select(name => $"'{name}'"))})";
+}
diff --git a/src/MoissonMontreal.Api/Data/Configurations/FoodItemConfiguration.cs b/src/MoissonMontreal.Api/Data/Configurations/FoodItemConfiguration.cs
index 04b27b9..f9cce94 100644
--- a/src/MoissonMontreal.Api/Data/Configurations/FoodItemConfiguration.cs
+++ b/src/MoissonMontreal.Api/Data/Configurations/FoodItemConfiguration.cs
@@ -9,6 +9,10 @@ namespace MoissonMontreal.Api.Data.Configurations;
///
public class FoodItemConfiguration : IEntityTypeConfiguration
{
+ public const string SourceKeyIndex = "ix_food_items_source_key";
+
+ public const int SourceKeyMaxLength = 120;
+
///
public void Configure(EntityTypeBuilder builder)
{
@@ -17,6 +21,13 @@ public void Configure(EntityTypeBuilder builder)
t.HasCheckConstraint("ck_food_items_quantity_positive", "quantity > 0");
t.HasCheckConstraint("ck_food_items_name_not_empty", "length(name) > 0");
t.HasCheckConstraint("ck_food_items_unit_not_empty", "length(unit) > 0");
+ t.HasCheckConstraint("ck_food_items_unit_price_positive", "unit_price > 0");
+ t.HasCheckConstraint("ck_food_items_quality_percent_range", "quality_percent BETWEEN 0 AND 100");
+ t.HasCheckConstraint("ck_food_items_value_not_negative", "value >= 0");
+ t.HasCheckConstraint(
+ "ck_food_items_frozen_value_complete",
+ "(unit_price IS NULL) = (price_effective_date IS NULL) AND (unit_price IS NULL) = (quality_percent IS NULL) AND (unit_price IS NULL) = (value IS NULL)");
+ t.HasCheckConstraint("ck_food_items_imported_has_source_key", "(donation_import_id IS NULL) = (source_key IS NULL)");
});
builder.Property(f => f.Id).HasDefaultValueSql("gen_random_uuid()");
@@ -31,6 +42,25 @@ public void Configure(EntityTypeBuilder builder)
builder.Property(f => f.CreatedAt).HasDefaultValueSql("now()");
+ builder.Property(f => f.BusinessCentralCode).HasMaxLength(50);
+
+ builder.Property(f => f.UnitPrice).HasPrecision(12, 4);
+
+ builder.Property(f => f.QualityPercent).HasPrecision(5, 2);
+
+ builder.Property(f => f.Value).HasPrecision(12, 2);
+
+ builder.Property(f => f.SourceKey).HasMaxLength(SourceKeyMaxLength);
+
+ builder.HasIndex(f => f.SourceKey)
+ .IsUnique()
+ .HasDatabaseName(SourceKeyIndex);
+
+ builder.HasOne(f => f.DonationImport)
+ .WithMany(i => i.FoodItems)
+ .HasForeignKey(f => f.DonationImportId)
+ .OnDelete(DeleteBehavior.Restrict);
+
builder.HasOne(f => f.Donor)
.WithMany(d => d.FoodItems)
.HasForeignKey(f => f.DonorId)
diff --git a/src/MoissonMontreal.Api/Data/Migrations/20261204063259_AddDonationImports.Designer.cs b/src/MoissonMontreal.Api/Data/Migrations/20261204063259_AddDonationImports.Designer.cs
new file mode 100644
index 0000000..42ebb35
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Migrations/20261204063259_AddDonationImports.Designer.cs
@@ -0,0 +1,1389 @@
+//
+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("20261204063259_AddDonationImports")]
+ partial class AddDonationImports
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "10.0.13")
+ .HasAnnotation("Relational:MaxIdentifierLength", 63);
+
+ NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "pg_trgm");
+ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.BcItemMapping", 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("CatalogItemId")
+ .HasColumnType("uuid")
+ .HasColumnName("catalog_item_id");
+
+ b.Property("ConfirmedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("confirmed_at");
+
+ b.Property("ConfirmedByUserId")
+ .HasColumnType("integer")
+ .HasColumnName("confirmed_by_user_id");
+
+ b.HasKey("Id")
+ .HasName("pk_bc_item_mappings");
+
+ b.HasIndex("BusinessCentralCode")
+ .IsUnique()
+ .HasDatabaseName("ix_bc_item_mappings_business_central_code");
+
+ b.HasIndex("CatalogItemId")
+ .HasDatabaseName("ix_bc_item_mappings_catalog_item_id");
+
+ b.HasIndex("ConfirmedByUserId")
+ .HasDatabaseName("ix_bc_item_mappings_confirmed_by_user_id");
+
+ b.ToTable("bc_item_mappings", null, t =>
+ {
+ t.HasCheckConstraint("ck_bc_item_mappings_business_central_code_not_empty", "length(business_central_code) > 0");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.BcItemMappingChange", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("Action")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasColumnName("action");
+
+ b.Property("BusinessCentralCode")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("business_central_code");
+
+ b.Property("ChangedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("changed_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("ChangedByUserId")
+ .HasColumnType("integer")
+ .HasColumnName("changed_by_user_id");
+
+ b.Property("NewCatalogItemId")
+ .HasColumnType("uuid")
+ .HasColumnName("new_catalog_item_id");
+
+ b.Property("OldCatalogItemId")
+ .HasColumnType("uuid")
+ .HasColumnName("old_catalog_item_id");
+
+ b.HasKey("Id")
+ .HasName("pk_bc_item_mapping_changes");
+
+ b.HasIndex("BusinessCentralCode")
+ .HasDatabaseName("ix_bc_item_mapping_changes_business_central_code");
+
+ b.HasIndex("ChangedByUserId")
+ .HasDatabaseName("ix_bc_item_mapping_changes_changed_by_user_id");
+
+ b.HasIndex("NewCatalogItemId")
+ .HasDatabaseName("ix_bc_item_mapping_changes_new_catalog_item_id");
+
+ b.HasIndex("OldCatalogItemId")
+ .HasDatabaseName("ix_bc_item_mapping_changes_old_catalog_item_id");
+
+ b.ToTable("bc_item_mapping_changes", (string)null);
+ });
+
+ 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("IsActive")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(true)
+ .HasColumnName("is_active");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("name");
+
+ b.Property("QualityClassCode")
+ .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.DonationImport", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("DocumentNumber")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("document_number");
+
+ b.Property("DonationDate")
+ .HasColumnType("date")
+ .HasColumnName("donation_date");
+
+ b.Property("DonorCode")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("donor_code");
+
+ b.Property("DonorId")
+ .HasColumnType("uuid")
+ .HasColumnName("donor_id");
+
+ b.Property("FileName")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("file_name");
+
+ b.Property("FileSha256")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("character(64)")
+ .HasColumnName("file_sha256")
+ .IsFixedLength();
+
+ b.Property("ImportedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("imported_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("ImportedByUserId")
+ .HasColumnType("integer")
+ .HasColumnName("imported_by_user_id");
+
+ b.Property("RowsAlreadyImported")
+ .HasColumnType("integer")
+ .HasColumnName("rows_already_imported");
+
+ b.Property("RowsImported")
+ .HasColumnType("integer")
+ .HasColumnName("rows_imported");
+
+ b.Property("RowsRead")
+ .HasColumnType("integer")
+ .HasColumnName("rows_read");
+
+ b.Property("RowsRejected")
+ .HasColumnType("integer")
+ .HasColumnName("rows_rejected");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasColumnName("status");
+
+ b.Property("TotalValue")
+ .HasPrecision(14, 2)
+ .HasColumnType("numeric(14,2)")
+ .HasColumnName("total_value");
+
+ b.HasKey("Id")
+ .HasName("pk_donation_imports");
+
+ b.HasIndex("DonorId")
+ .HasDatabaseName("ix_donation_imports_donor_id");
+
+ b.HasIndex("FileSha256")
+ .HasDatabaseName("ix_donation_imports_file_sha256");
+
+ b.HasIndex("ImportedAt")
+ .HasDatabaseName("ix_donation_imports_imported_at");
+
+ b.HasIndex("ImportedByUserId")
+ .HasDatabaseName("ix_donation_imports_imported_by_user_id");
+
+ b.ToTable("donation_imports", null, t =>
+ {
+ t.HasCheckConstraint("ck_donation_imports_counts_add_up", "rows_imported >= 0 AND rows_rejected >= 0 AND rows_already_imported >= 0 AND rows_read = rows_imported + rows_rejected + rows_already_imported");
+
+ t.HasCheckConstraint("ck_donation_imports_document_number_not_empty", "length(document_number) > 0");
+
+ t.HasCheckConstraint("ck_donation_imports_donor_code_not_empty", "length(donor_code) > 0");
+
+ t.HasCheckConstraint("ck_donation_imports_file_name_not_empty", "length(file_name) > 0");
+
+ t.HasCheckConstraint("ck_donation_imports_file_sha256_format", "file_sha256 ~ '^[0-9a-f]{64}$'");
+
+ t.HasCheckConstraint("ck_donation_imports_status_valid", "status IN ('Imported', 'ImportedWithErrors', 'NothingImported')");
+
+ t.HasCheckConstraint("ck_donation_imports_total_value_not_negative", "total_value >= 0");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.DonationImportError", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("BusinessCentralCode")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("business_central_code");
+
+ b.Property("Code")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasColumnName("code");
+
+ b.Property("DonationImportId")
+ .HasColumnType("uuid")
+ .HasColumnName("donation_import_id");
+
+ b.Property("Message")
+ .IsRequired()
+ .HasMaxLength(500)
+ .HasColumnType("character varying(500)")
+ .HasColumnName("message");
+
+ b.Property("RowNumber")
+ .HasColumnType("integer")
+ .HasColumnName("row_number");
+
+ b.HasKey("Id")
+ .HasName("pk_donation_import_errors");
+
+ b.HasIndex("DonationImportId", "RowNumber")
+ .HasDatabaseName("ix_donation_import_errors_donation_import_id_row_number");
+
+ b.ToTable("donation_import_errors", null, t =>
+ {
+ t.HasCheckConstraint("ck_donation_import_errors_code_valid", "code IN ('ExcelError', 'NotAnItemLine', 'MissingItemCode', 'MissingQuantity', 'InvalidQuantity', 'NegativeQuantity', 'MissingUnit', 'MissingQuality', 'UnknownQuality', 'UnknownDonor', 'UnmappedItem', 'InactiveCatalogItem', 'UnitMismatch', 'NoPriceOnDate')");
+
+ t.HasCheckConstraint("ck_donation_import_errors_message_not_empty", "length(message) > 0");
+
+ t.HasCheckConstraint("ck_donation_import_errors_row_number_positive", "row_number >= 1");
+ });
+ });
+
+ 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("BusinessCentralCode")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("business_central_code");
+
+ b.Property("City")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)")
+ .HasColumnName("city");
+
+ 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("Email")
+ .HasMaxLength(254)
+ .HasColumnType("character varying(254)")
+ .HasColumnName("email");
+
+ b.Property("IsActive")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(true)
+ .HasColumnName("is_active");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("name");
+
+ b.Property("Notes")
+ .HasColumnType("text")
+ .HasColumnName("notes");
+
+ b.Property("Phone")
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasColumnName("phone");
+
+ b.Property("PostalCode")
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasColumnName("postal_code");
+
+ b.Property("Province")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("province");
+
+ b.Property("SearchName")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("search_name");
+
+ b.Property("Type")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasColumnName("type");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.HasKey("Id")
+ .HasName("pk_donors");
+
+ b.HasIndex("BusinessCentralCode")
+ .IsUnique()
+ .HasDatabaseName("ix_donors_business_central_code");
+
+ b.HasIndex("SearchName")
+ .HasDatabaseName("ix_donors_search_name");
+
+ NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("SearchName"), "gin");
+ NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("SearchName"), new[] { "gin_trgm_ops" });
+
+ b.ToTable("donors", null, t =>
+ {
+ t.HasCheckConstraint("ck_donors_business_central_code_not_empty", "length(business_central_code) > 0");
+
+ t.HasCheckConstraint("ck_donors_name_not_empty", "length(name) > 0");
+
+ t.HasCheckConstraint("ck_donors_type", "type IN ('individual', 'organization')");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.FoodItem", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("BusinessCentralCode")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("business_central_code");
+
+ 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("DonationImportId")
+ .HasColumnType("uuid")
+ .HasColumnName("donation_import_id");
+
+ b.Property("DonorId")
+ .HasColumnType("uuid")
+ .HasColumnName("donor_id");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("name");
+
+ b.Property("PriceEffectiveDate")
+ .HasColumnType("date")
+ .HasColumnName("price_effective_date");
+
+ b.Property("Quality")
+ .IsRequired()
+ .HasMaxLength(1)
+ .HasColumnType("character varying(1)")
+ .HasColumnName("quality");
+
+ 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("SourceKey")
+ .HasMaxLength(120)
+ .HasColumnType("character varying(120)")
+ .HasColumnName("source_key");
+
+ 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.Property("Value")
+ .HasPrecision(12, 2)
+ .HasColumnType("numeric(12,2)")
+ .HasColumnName("value");
+
+ 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("DonationImportId")
+ .HasDatabaseName("ix_food_items_donation_import_id");
+
+ b.HasIndex("DonorId")
+ .HasDatabaseName("ix_food_items_donor_id");
+
+ b.HasIndex("Quality")
+ .HasDatabaseName("ix_food_items_quality");
+
+ b.HasIndex("SourceKey")
+ .IsUnique()
+ .HasDatabaseName("ix_food_items_source_key");
+
+ b.ToTable("food_items", null, t =>
+ {
+ t.HasCheckConstraint("ck_food_items_frozen_value_complete", "(unit_price IS NULL) = (price_effective_date IS NULL) AND (unit_price IS NULL) = (quality_percent IS NULL) AND (unit_price IS NULL) = (value IS NULL)");
+
+ t.HasCheckConstraint("ck_food_items_imported_has_source_key", "(donation_import_id IS NULL) = (source_key IS NULL)");
+
+ t.HasCheckConstraint("ck_food_items_name_not_empty", "length(name) > 0");
+
+ t.HasCheckConstraint("ck_food_items_quality_percent_range", "quality_percent BETWEEN 0 AND 100");
+
+ t.HasCheckConstraint("ck_food_items_quantity_positive", "quantity > 0");
+
+ t.HasCheckConstraint("ck_food_items_unit_not_empty", "length(unit) > 0");
+
+ t.HasCheckConstraint("ck_food_items_unit_price_positive", "unit_price > 0");
+
+ t.HasCheckConstraint("ck_food_items_value_not_negative", "value >= 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("ReceiptNumber")
+ .HasMaxLength(10)
+ .HasColumnType("character varying(10)")
+ .HasColumnName("receipt_number");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasDefaultValue("Draft")
+ .HasColumnName("status");
+
+ 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.HasIndex("ReceiptNumber")
+ .IsUnique()
+ .HasDatabaseName("ix_receipts_receipt_number");
+
+ b.ToTable("receipts", null, t =>
+ {
+ t.HasCheckConstraint("ck_receipts_issued_has_receipt_number", "status <> 'Issued' OR receipt_number IS NOT NULL");
+
+ t.HasCheckConstraint("ck_receipts_receipt_number_format", "receipt_number ~ '^DEN_[0-9]{6}$'");
+
+ t.HasCheckConstraint("ck_receipts_receipt_number_only_once_issued", "status IN ('Issued', 'Cancelled') OR receipt_number IS NULL");
+
+ t.HasCheckConstraint("ck_receipts_status_valid", "status IN ('Draft', 'PendingSupplyApproval', 'PendingFinanceApproval', 'Approved', 'Issued', 'Cancelled')");
+
+ 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("ReceiptCancelled")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(false)
+ .HasColumnName("receipt_cancelled");
+
+ 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")
+ .HasFilter("NOT receipt_cancelled");
+
+ 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.ReceiptNumberCounter", b =>
+ {
+ b.Property("Series")
+ .HasMaxLength(10)
+ .HasColumnType("character varying(10)")
+ .HasColumnName("series");
+
+ b.Property("LastNumber")
+ .HasColumnType("integer")
+ .HasColumnName("last_number");
+
+ b.HasKey("Series")
+ .HasName("pk_receipt_number_counters");
+
+ b.ToTable("receipt_number_counters", null, t =>
+ {
+ t.HasCheckConstraint("ck_receipt_number_counters_last_number_in_range", "last_number BETWEEN 0 AND 999999");
+ });
+
+ b.HasData(
+ new
+ {
+ Series = "DEN",
+ LastNumber = 0
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.ReceiptStatusChange", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("ChangedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("changed_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("ChangedByUserId")
+ .HasColumnType("integer")
+ .HasColumnName("changed_by_user_id");
+
+ b.Property("FromStatus")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasColumnName("from_status");
+
+ b.Property("Reason")
+ .HasMaxLength(1000)
+ .HasColumnType("character varying(1000)")
+ .HasColumnName("reason");
+
+ b.Property("ReceiptId")
+ .HasColumnType("uuid")
+ .HasColumnName("receipt_id");
+
+ b.Property("ToStatus")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasColumnName("to_status");
+
+ b.HasKey("Id")
+ .HasName("pk_receipt_status_changes");
+
+ b.HasIndex("ChangedByUserId")
+ .HasDatabaseName("ix_receipt_status_changes_changed_by_user_id");
+
+ b.HasIndex("ReceiptId", "ChangedAt")
+ .HasDatabaseName("ix_receipt_status_changes_receipt_id_changed_at");
+
+ b.ToTable("receipt_status_changes", null, t =>
+ {
+ t.HasCheckConstraint("ck_receipt_status_changes_from_status_valid", "from_status IN ('Draft', 'PendingSupplyApproval', 'PendingFinanceApproval', 'Approved', 'Issued', 'Cancelled')");
+
+ t.HasCheckConstraint("ck_receipt_status_changes_reason_not_empty", "length(reason) > 0");
+
+ t.HasCheckConstraint("ck_receipt_status_changes_reason_required", "to_status NOT IN ('Draft', 'Cancelled') OR reason IS NOT NULL");
+
+ t.HasCheckConstraint("ck_receipt_status_changes_status_differs", "from_status <> to_status");
+
+ t.HasCheckConstraint("ck_receipt_status_changes_to_status_valid", "to_status IN ('Draft', 'PendingSupplyApproval', 'PendingFinanceApproval', 'Approved', 'Issued', 'Cancelled')");
+ });
+ });
+
+ 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.Property("Version")
+ .IsConcurrencyToken()
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("xid")
+ .HasColumnName("xmin");
+
+ 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.UserAccountChange", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("Action")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasColumnName("action");
+
+ b.Property("ChangedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("changed_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("ChangedByUserId")
+ .HasColumnType("integer")
+ .HasColumnName("changed_by_user_id");
+
+ b.Property("NewDisplayName")
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("new_display_name");
+
+ b.Property("NewEmail")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)")
+ .HasColumnName("new_email");
+
+ b.Property("NewIsActive")
+ .HasColumnType("boolean")
+ .HasColumnName("new_is_active");
+
+ b.Property("NewRoleId")
+ .HasColumnType("integer")
+ .HasColumnName("new_role_id");
+
+ b.Property("OldDisplayName")
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("old_display_name");
+
+ b.Property("OldEmail")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)")
+ .HasColumnName("old_email");
+
+ b.Property("OldIsActive")
+ .HasColumnType("boolean")
+ .HasColumnName("old_is_active");
+
+ b.Property("OldRoleId")
+ .HasColumnType("integer")
+ .HasColumnName("old_role_id");
+
+ b.Property("UserId")
+ .HasColumnType("integer")
+ .HasColumnName("user_id");
+
+ b.HasKey("Id")
+ .HasName("pk_user_account_changes");
+
+ b.HasIndex("ChangedByUserId")
+ .HasDatabaseName("ix_user_account_changes_changed_by_user_id");
+
+ b.HasIndex("NewRoleId")
+ .HasDatabaseName("ix_user_account_changes_new_role_id");
+
+ b.HasIndex("OldRoleId")
+ .HasDatabaseName("ix_user_account_changes_old_role_id");
+
+ b.HasIndex("UserId")
+ .HasDatabaseName("ix_user_account_changes_user_id");
+
+ b.ToTable("user_account_changes", (string)null);
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.BcItemMapping", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", "CatalogItem")
+ .WithMany()
+ .HasForeignKey("CatalogItemId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_bc_item_mappings_catalog_items_catalog_item_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.User", "ConfirmedBy")
+ .WithMany()
+ .HasForeignKey("ConfirmedByUserId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_bc_item_mappings_users_confirmed_by_user_id");
+
+ b.Navigation("CatalogItem");
+
+ b.Navigation("ConfirmedBy");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.BcItemMappingChange", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.User", "ChangedBy")
+ .WithMany()
+ .HasForeignKey("ChangedByUserId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_bc_item_mapping_changes_users_changed_by_user_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", null)
+ .WithMany()
+ .HasForeignKey("NewCatalogItemId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_bc_item_mapping_changes_catalog_items_new_catalog_item_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", null)
+ .WithMany()
+ .HasForeignKey("OldCatalogItemId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_bc_item_mapping_changes_catalog_items_old_catalog_item_id");
+
+ b.Navigation("ChangedBy");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.CatalogItem", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.QualityClass", "QualityClass")
+ .WithMany()
+ .HasForeignKey("QualityClassCode")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_catalog_items_quality_classes_quality_class");
+
+ b.Navigation("QualityClass");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.DonationImport", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.Donor", "Donor")
+ .WithMany()
+ .HasForeignKey("DonorId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_donation_imports_donors_donor_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.User", "ImportedBy")
+ .WithMany()
+ .HasForeignKey("ImportedByUserId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_donation_imports_users_imported_by_user_id");
+
+ b.Navigation("Donor");
+
+ b.Navigation("ImportedBy");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.DonationImportError", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.DonationImport", "DonationImport")
+ .WithMany("Errors")
+ .HasForeignKey("DonationImportId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired()
+ .HasConstraintName("fk_donation_import_errors_donation_imports_donation_import_id");
+
+ b.Navigation("DonationImport");
+ });
+
+ 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.DonationImport", "DonationImport")
+ .WithMany("FoodItems")
+ .HasForeignKey("DonationImportId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_food_items_donation_imports_donation_import_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("DonationImport");
+
+ 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.ReceiptStatusChange", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.User", "ChangedBy")
+ .WithMany()
+ .HasForeignKey("ChangedByUserId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_receipt_status_changes_users_changed_by_user_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.Receipt", "Receipt")
+ .WithMany("StatusChanges")
+ .HasForeignKey("ReceiptId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_receipt_status_changes_receipts_receipt_id");
+
+ b.Navigation("ChangedBy");
+
+ 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.UserAccountChange", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.User", "ChangedBy")
+ .WithMany()
+ .HasForeignKey("ChangedByUserId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_user_account_changes_users_changed_by_user_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.Role", null)
+ .WithMany()
+ .HasForeignKey("NewRoleId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_user_account_changes_roles_new_role_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.Role", null)
+ .WithMany()
+ .HasForeignKey("OldRoleId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_user_account_changes_roles_old_role_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.User", "User")
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_user_account_changes_users_user_id");
+
+ b.Navigation("ChangedBy");
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.CatalogItem", b =>
+ {
+ b.Navigation("Prices");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.DonationImport", b =>
+ {
+ b.Navigation("Errors");
+
+ b.Navigation("FoodItems");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.Donor", b =>
+ {
+ b.Navigation("FoodItems");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.Receipt", b =>
+ {
+ b.Navigation("Items");
+
+ b.Navigation("StatusChanges");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.Role", b =>
+ {
+ b.Navigation("Users");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/MoissonMontreal.Api/Data/Migrations/20261204063259_AddDonationImports.cs b/src/MoissonMontreal.Api/Data/Migrations/20261204063259_AddDonationImports.cs
new file mode 100644
index 0000000..3261cf6
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Migrations/20261204063259_AddDonationImports.cs
@@ -0,0 +1,273 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace MoissonMontreal.Api.Data.Migrations
+{
+ ///
+ public partial class AddDonationImports : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "business_central_code",
+ table: "food_items",
+ type: "character varying(50)",
+ maxLength: 50,
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "donation_import_id",
+ table: "food_items",
+ type: "uuid",
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "price_effective_date",
+ table: "food_items",
+ type: "date",
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "quality_percent",
+ table: "food_items",
+ type: "numeric(5,2)",
+ precision: 5,
+ scale: 2,
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "source_key",
+ table: "food_items",
+ type: "character varying(120)",
+ maxLength: 120,
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "unit_price",
+ table: "food_items",
+ type: "numeric(12,4)",
+ precision: 12,
+ scale: 4,
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "value",
+ table: "food_items",
+ type: "numeric(12,2)",
+ precision: 12,
+ scale: 2,
+ nullable: true);
+
+ migrationBuilder.CreateTable(
+ name: "donation_imports",
+ columns: table => new
+ {
+ id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
+ file_name = table.Column(type: "character varying(255)", maxLength: 255, nullable: false),
+ file_sha256 = table.Column(type: "character(64)", fixedLength: true, maxLength: 64, nullable: false),
+ document_number = table.Column(type: "character varying(50)", maxLength: 50, nullable: false),
+ donor_code = table.Column(type: "character varying(50)", maxLength: 50, nullable: false),
+ donor_id = table.Column(type: "uuid", nullable: true),
+ donation_date = table.Column(type: "date", nullable: false),
+ status = table.Column(type: "character varying(30)", maxLength: 30, nullable: false),
+ rows_read = table.Column(type: "integer", nullable: false),
+ rows_imported = table.Column(type: "integer", nullable: false),
+ rows_rejected = table.Column(type: "integer", nullable: false),
+ rows_already_imported = table.Column(type: "integer", nullable: false),
+ total_value = table.Column(type: "numeric(14,2)", precision: 14, scale: 2, nullable: false),
+ imported_by_user_id = table.Column(type: "integer", nullable: false),
+ imported_at = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("pk_donation_imports", x => x.id);
+ table.CheckConstraint("ck_donation_imports_counts_add_up", "rows_imported >= 0 AND rows_rejected >= 0 AND rows_already_imported >= 0 AND rows_read = rows_imported + rows_rejected + rows_already_imported");
+ table.CheckConstraint("ck_donation_imports_document_number_not_empty", "length(document_number) > 0");
+ table.CheckConstraint("ck_donation_imports_donor_code_not_empty", "length(donor_code) > 0");
+ table.CheckConstraint("ck_donation_imports_file_name_not_empty", "length(file_name) > 0");
+ table.CheckConstraint("ck_donation_imports_file_sha256_format", "file_sha256 ~ '^[0-9a-f]{64}$'");
+ table.CheckConstraint("ck_donation_imports_status_valid", "status IN ('Imported', 'ImportedWithErrors', 'NothingImported')");
+ table.CheckConstraint("ck_donation_imports_total_value_not_negative", "total_value >= 0");
+ table.ForeignKey(
+ name: "fk_donation_imports_donors_donor_id",
+ column: x => x.donor_id,
+ principalTable: "donors",
+ principalColumn: "id",
+ onDelete: ReferentialAction.Restrict);
+ table.ForeignKey(
+ name: "fk_donation_imports_users_imported_by_user_id",
+ column: x => x.imported_by_user_id,
+ principalTable: "users",
+ principalColumn: "id",
+ onDelete: ReferentialAction.Restrict);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "donation_import_errors",
+ columns: table => new
+ {
+ id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
+ donation_import_id = table.Column(type: "uuid", nullable: false),
+ row_number = table.Column(type: "integer", nullable: false),
+ code = table.Column(type: "character varying(30)", maxLength: 30, nullable: false),
+ message = table.Column(type: "character varying(500)", maxLength: 500, nullable: false),
+ business_central_code = table.Column(type: "character varying(50)", maxLength: 50, nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("pk_donation_import_errors", x => x.id);
+ table.CheckConstraint("ck_donation_import_errors_code_valid", "code IN ('ExcelError', 'NotAnItemLine', 'MissingItemCode', 'MissingQuantity', 'InvalidQuantity', 'NegativeQuantity', 'MissingUnit', 'MissingQuality', 'UnknownQuality', 'UnknownDonor', 'UnmappedItem', 'InactiveCatalogItem', 'UnitMismatch', 'NoPriceOnDate')");
+ table.CheckConstraint("ck_donation_import_errors_message_not_empty", "length(message) > 0");
+ table.CheckConstraint("ck_donation_import_errors_row_number_positive", "row_number >= 1");
+ table.ForeignKey(
+ name: "fk_donation_import_errors_donation_imports_donation_import_id",
+ column: x => x.donation_import_id,
+ principalTable: "donation_imports",
+ principalColumn: "id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "ix_food_items_donation_import_id",
+ table: "food_items",
+ column: "donation_import_id");
+
+ migrationBuilder.CreateIndex(
+ name: "ix_food_items_source_key",
+ table: "food_items",
+ column: "source_key",
+ unique: true);
+
+ migrationBuilder.AddCheckConstraint(
+ name: "ck_food_items_frozen_value_complete",
+ table: "food_items",
+ sql: "(unit_price IS NULL) = (price_effective_date IS NULL) AND (unit_price IS NULL) = (quality_percent IS NULL) AND (unit_price IS NULL) = (value IS NULL)");
+
+ migrationBuilder.AddCheckConstraint(
+ name: "ck_food_items_imported_has_source_key",
+ table: "food_items",
+ sql: "(donation_import_id IS NULL) = (source_key IS NULL)");
+
+ migrationBuilder.AddCheckConstraint(
+ name: "ck_food_items_quality_percent_range",
+ table: "food_items",
+ sql: "quality_percent BETWEEN 0 AND 100");
+
+ migrationBuilder.AddCheckConstraint(
+ name: "ck_food_items_unit_price_positive",
+ table: "food_items",
+ sql: "unit_price > 0");
+
+ migrationBuilder.AddCheckConstraint(
+ name: "ck_food_items_value_not_negative",
+ table: "food_items",
+ sql: "value >= 0");
+
+ migrationBuilder.CreateIndex(
+ name: "ix_donation_import_errors_donation_import_id_row_number",
+ table: "donation_import_errors",
+ columns: new[] { "donation_import_id", "row_number" });
+
+ migrationBuilder.CreateIndex(
+ name: "ix_donation_imports_donor_id",
+ table: "donation_imports",
+ column: "donor_id");
+
+ migrationBuilder.CreateIndex(
+ name: "ix_donation_imports_file_sha256",
+ table: "donation_imports",
+ column: "file_sha256");
+
+ migrationBuilder.CreateIndex(
+ name: "ix_donation_imports_imported_at",
+ table: "donation_imports",
+ column: "imported_at");
+
+ migrationBuilder.CreateIndex(
+ name: "ix_donation_imports_imported_by_user_id",
+ table: "donation_imports",
+ column: "imported_by_user_id");
+
+ migrationBuilder.AddForeignKey(
+ name: "fk_food_items_donation_imports_donation_import_id",
+ table: "food_items",
+ column: "donation_import_id",
+ principalTable: "donation_imports",
+ principalColumn: "id",
+ onDelete: ReferentialAction.Restrict);
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropForeignKey(
+ name: "fk_food_items_donation_imports_donation_import_id",
+ table: "food_items");
+
+ migrationBuilder.DropTable(
+ name: "donation_import_errors");
+
+ migrationBuilder.DropTable(
+ name: "donation_imports");
+
+ migrationBuilder.DropIndex(
+ name: "ix_food_items_donation_import_id",
+ table: "food_items");
+
+ migrationBuilder.DropIndex(
+ name: "ix_food_items_source_key",
+ table: "food_items");
+
+ migrationBuilder.DropCheckConstraint(
+ name: "ck_food_items_frozen_value_complete",
+ table: "food_items");
+
+ migrationBuilder.DropCheckConstraint(
+ name: "ck_food_items_imported_has_source_key",
+ table: "food_items");
+
+ migrationBuilder.DropCheckConstraint(
+ name: "ck_food_items_quality_percent_range",
+ table: "food_items");
+
+ migrationBuilder.DropCheckConstraint(
+ name: "ck_food_items_unit_price_positive",
+ table: "food_items");
+
+ migrationBuilder.DropCheckConstraint(
+ name: "ck_food_items_value_not_negative",
+ table: "food_items");
+
+ migrationBuilder.DropColumn(
+ name: "business_central_code",
+ table: "food_items");
+
+ migrationBuilder.DropColumn(
+ name: "donation_import_id",
+ table: "food_items");
+
+ migrationBuilder.DropColumn(
+ name: "price_effective_date",
+ table: "food_items");
+
+ migrationBuilder.DropColumn(
+ name: "quality_percent",
+ table: "food_items");
+
+ migrationBuilder.DropColumn(
+ name: "source_key",
+ table: "food_items");
+
+ migrationBuilder.DropColumn(
+ name: "unit_price",
+ table: "food_items");
+
+ migrationBuilder.DropColumn(
+ name: "value",
+ table: "food_items");
+ }
+ }
+}
diff --git a/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs b/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs
index 4963600..ad78058 100644
--- a/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs
+++ b/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs
@@ -199,6 +199,166 @@ protected override void BuildModel(ModelBuilder modelBuilder)
});
});
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.DonationImport", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("DocumentNumber")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("document_number");
+
+ b.Property("DonationDate")
+ .HasColumnType("date")
+ .HasColumnName("donation_date");
+
+ b.Property("DonorCode")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("donor_code");
+
+ b.Property("DonorId")
+ .HasColumnType("uuid")
+ .HasColumnName("donor_id");
+
+ b.Property("FileName")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("file_name");
+
+ b.Property("FileSha256")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("character(64)")
+ .HasColumnName("file_sha256")
+ .IsFixedLength();
+
+ b.Property("ImportedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("imported_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("ImportedByUserId")
+ .HasColumnType("integer")
+ .HasColumnName("imported_by_user_id");
+
+ b.Property("RowsAlreadyImported")
+ .HasColumnType("integer")
+ .HasColumnName("rows_already_imported");
+
+ b.Property("RowsImported")
+ .HasColumnType("integer")
+ .HasColumnName("rows_imported");
+
+ b.Property("RowsRead")
+ .HasColumnType("integer")
+ .HasColumnName("rows_read");
+
+ b.Property("RowsRejected")
+ .HasColumnType("integer")
+ .HasColumnName("rows_rejected");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasColumnName("status");
+
+ b.Property("TotalValue")
+ .HasPrecision(14, 2)
+ .HasColumnType("numeric(14,2)")
+ .HasColumnName("total_value");
+
+ b.HasKey("Id")
+ .HasName("pk_donation_imports");
+
+ b.HasIndex("DonorId")
+ .HasDatabaseName("ix_donation_imports_donor_id");
+
+ b.HasIndex("FileSha256")
+ .HasDatabaseName("ix_donation_imports_file_sha256");
+
+ b.HasIndex("ImportedAt")
+ .HasDatabaseName("ix_donation_imports_imported_at");
+
+ b.HasIndex("ImportedByUserId")
+ .HasDatabaseName("ix_donation_imports_imported_by_user_id");
+
+ b.ToTable("donation_imports", null, t =>
+ {
+ t.HasCheckConstraint("ck_donation_imports_counts_add_up", "rows_imported >= 0 AND rows_rejected >= 0 AND rows_already_imported >= 0 AND rows_read = rows_imported + rows_rejected + rows_already_imported");
+
+ t.HasCheckConstraint("ck_donation_imports_document_number_not_empty", "length(document_number) > 0");
+
+ t.HasCheckConstraint("ck_donation_imports_donor_code_not_empty", "length(donor_code) > 0");
+
+ t.HasCheckConstraint("ck_donation_imports_file_name_not_empty", "length(file_name) > 0");
+
+ t.HasCheckConstraint("ck_donation_imports_file_sha256_format", "file_sha256 ~ '^[0-9a-f]{64}$'");
+
+ t.HasCheckConstraint("ck_donation_imports_status_valid", "status IN ('Imported', 'ImportedWithErrors', 'NothingImported')");
+
+ t.HasCheckConstraint("ck_donation_imports_total_value_not_negative", "total_value >= 0");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.DonationImportError", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("BusinessCentralCode")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("business_central_code");
+
+ b.Property("Code")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasColumnName("code");
+
+ b.Property("DonationImportId")
+ .HasColumnType("uuid")
+ .HasColumnName("donation_import_id");
+
+ b.Property("Message")
+ .IsRequired()
+ .HasMaxLength(500)
+ .HasColumnType("character varying(500)")
+ .HasColumnName("message");
+
+ b.Property("RowNumber")
+ .HasColumnType("integer")
+ .HasColumnName("row_number");
+
+ b.HasKey("Id")
+ .HasName("pk_donation_import_errors");
+
+ b.HasIndex("DonationImportId", "RowNumber")
+ .HasDatabaseName("ix_donation_import_errors_donation_import_id_row_number");
+
+ b.ToTable("donation_import_errors", null, t =>
+ {
+ t.HasCheckConstraint("ck_donation_import_errors_code_valid", "code IN ('ExcelError', 'NotAnItemLine', 'MissingItemCode', 'MissingQuantity', 'InvalidQuantity', 'NegativeQuantity', 'MissingUnit', 'MissingQuality', 'UnknownQuality', 'UnknownDonor', 'UnmappedItem', 'InactiveCatalogItem', 'UnitMismatch', 'NoPriceOnDate')");
+
+ t.HasCheckConstraint("ck_donation_import_errors_message_not_empty", "length(message) > 0");
+
+ t.HasCheckConstraint("ck_donation_import_errors_row_number_positive", "row_number >= 1");
+ });
+ });
+
modelBuilder.Entity("MoissonMontreal.Core.Entities.Donor", b =>
{
b.Property("Id")
@@ -315,6 +475,11 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
+ b.Property("BusinessCentralCode")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("business_central_code");
+
b.Property("CatalogItemId")
.HasColumnType("uuid")
.HasColumnName("catalog_item_id");
@@ -329,6 +494,10 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.HasColumnType("date")
.HasColumnName("donation_date");
+ b.Property("DonationImportId")
+ .HasColumnType("uuid")
+ .HasColumnName("donation_import_id");
+
b.Property("DonorId")
.HasColumnType("uuid")
.HasColumnName("donor_id");
@@ -339,23 +508,47 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.HasColumnType("character varying(255)")
.HasColumnName("name");
+ b.Property("PriceEffectiveDate")
+ .HasColumnType("date")
+ .HasColumnName("price_effective_date");
+
b.Property("Quality")
.IsRequired()
.HasMaxLength(1)
.HasColumnType("character varying(1)")
.HasColumnName("quality");
+ 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("SourceKey")
+ .HasMaxLength(120)
+ .HasColumnType("character varying(120)")
+ .HasColumnName("source_key");
+
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.Property("Value")
+ .HasPrecision(12, 2)
+ .HasColumnType("numeric(12,2)")
+ .HasColumnName("value");
+
b.HasKey("Id")
.HasName("pk_food_items");
@@ -365,19 +558,36 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.HasIndex("CatalogItemId")
.HasDatabaseName("ix_food_items_catalog_item_id");
+ b.HasIndex("DonationImportId")
+ .HasDatabaseName("ix_food_items_donation_import_id");
+
b.HasIndex("DonorId")
.HasDatabaseName("ix_food_items_donor_id");
b.HasIndex("Quality")
.HasDatabaseName("ix_food_items_quality");
+ b.HasIndex("SourceKey")
+ .IsUnique()
+ .HasDatabaseName("ix_food_items_source_key");
+
b.ToTable("food_items", null, t =>
{
+ t.HasCheckConstraint("ck_food_items_frozen_value_complete", "(unit_price IS NULL) = (price_effective_date IS NULL) AND (unit_price IS NULL) = (quality_percent IS NULL) AND (unit_price IS NULL) = (value IS NULL)");
+
+ t.HasCheckConstraint("ck_food_items_imported_has_source_key", "(donation_import_id IS NULL) = (source_key IS NULL)");
+
t.HasCheckConstraint("ck_food_items_name_not_empty", "length(name) > 0");
+ t.HasCheckConstraint("ck_food_items_quality_percent_range", "quality_percent BETWEEN 0 AND 100");
+
t.HasCheckConstraint("ck_food_items_quantity_positive", "quantity > 0");
t.HasCheckConstraint("ck_food_items_unit_not_empty", "length(unit) > 0");
+
+ t.HasCheckConstraint("ck_food_items_unit_price_positive", "unit_price > 0");
+
+ t.HasCheckConstraint("ck_food_items_value_not_negative", "value >= 0");
});
});
@@ -960,6 +1170,38 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Navigation("QualityClass");
});
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.DonationImport", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.Donor", "Donor")
+ .WithMany()
+ .HasForeignKey("DonorId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_donation_imports_donors_donor_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.User", "ImportedBy")
+ .WithMany()
+ .HasForeignKey("ImportedByUserId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_donation_imports_users_imported_by_user_id");
+
+ b.Navigation("Donor");
+
+ b.Navigation("ImportedBy");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.DonationImportError", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.DonationImport", "DonationImport")
+ .WithMany("Errors")
+ .HasForeignKey("DonationImportId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired()
+ .HasConstraintName("fk_donation_import_errors_donation_imports_donation_import_id");
+
+ b.Navigation("DonationImport");
+ });
+
modelBuilder.Entity("MoissonMontreal.Core.Entities.FoodItem", b =>
{
b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", "CatalogItem")
@@ -968,6 +1210,12 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("fk_food_items_catalog_items_catalog_item_id");
+ b.HasOne("MoissonMontreal.Core.Entities.DonationImport", "DonationImport")
+ .WithMany("FoodItems")
+ .HasForeignKey("DonationImportId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_food_items_donation_imports_donation_import_id");
+
b.HasOne("MoissonMontreal.Core.Entities.Donor", "Donor")
.WithMany("FoodItems")
.HasForeignKey("DonorId")
@@ -984,6 +1232,8 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Navigation("CatalogItem");
+ b.Navigation("DonationImport");
+
b.Navigation("Donor");
b.Navigation("QualityClass");
@@ -1107,6 +1357,13 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Navigation("Prices");
});
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.DonationImport", b =>
+ {
+ b.Navigation("Errors");
+
+ b.Navigation("FoodItems");
+ });
+
modelBuilder.Entity("MoissonMontreal.Core.Entities.Donor", b =>
{
b.Navigation("FoodItems");
diff --git a/src/MoissonMontreal.Api/Data/MoissonDbContext.cs b/src/MoissonMontreal.Api/Data/MoissonDbContext.cs
index 746f6c7..725c266 100644
--- a/src/MoissonMontreal.Api/Data/MoissonDbContext.cs
+++ b/src/MoissonMontreal.Api/Data/MoissonDbContext.cs
@@ -29,6 +29,10 @@ public class MoissonDbContext(DbContextOptions options) : DbCo
///
public DbSet FoodItems => Set();
+ public DbSet DonationImports => Set();
+
+ public DbSet DonationImportErrors => Set();
+
///
/// Tax receipts given to donors.
///
diff --git a/src/MoissonMontreal.Api/Donations/DonationExportReader.cs b/src/MoissonMontreal.Api/Donations/DonationExportReader.cs
new file mode 100644
index 0000000..91de62a
--- /dev/null
+++ b/src/MoissonMontreal.Api/Donations/DonationExportReader.cs
@@ -0,0 +1,214 @@
+using System.Globalization;
+
+using ClosedXML.Excel;
+
+using MoissonMontreal.Api.Catalog;
+using MoissonMontreal.Core.Donations;
+using MoissonMontreal.Core.Dtos;
+
+namespace MoissonMontreal.Api.Donations;
+
+///
+/// Reads the lines of a purchase order exported from Business Central to Excel (sheet Lignes), the format of the real export
+/// described in docs/database/donation-imports.md. Every row is checked and every problem is reported with its row number;
+/// the reader never stops at the first bad row. Cells are read as text through , so a
+/// formula is never calculated.
+///
+public static class DonationExportReader
+{
+ public const string SheetName = "Lignes";
+
+ public const string TypeHeader = "Type";
+
+ public const string CodeHeader = "N°";
+
+ public const string NameHeader = "Description";
+
+ public const string QuantityHeader = "Quantité";
+
+ public const string UnitHeader = "Code d'unité de mesure";
+
+ public const string QualityHeader = "Qualité du test";
+
+ public const string LineNumberHeader = "N° ligne";
+
+ private const string ItemType = "Article";
+
+ private const int QuantityDecimals = 2;
+
+ private const decimal LargestQuantity = 9_999_999_999.99m;
+
+ public static DonationExport Read(Stream file)
+ {
+ using var workbook = BusinessCentralWorkbook.Open(file);
+ var sheet = BusinessCentralWorkbook.Sheet(workbook, SheetName);
+ var columns = BusinessCentralWorkbook.FindColumns(
+ sheet, [TypeHeader, CodeHeader, NameHeader, QuantityHeader, UnitHeader, QualityHeader]);
+ var lineNumberColumn = FindOptionalColumn(sheet, LineNumberHeader);
+
+ var lines = new List();
+ var errors = new List();
+ var occurrences = new Dictionary(StringComparer.Ordinal);
+ var rowsRead = 0;
+ var lastRow = sheet.LastRowUsed()?.RowNumber() ?? 1;
+
+ for (var rowNumber = 2; rowNumber <= lastRow; rowNumber++)
+ {
+ var row = sheet.Row(rowNumber);
+ if (row.CellsUsed().All(cell => BusinessCentralWorkbook.ReadText(cell).Length == 0))
+ {
+ continue;
+ }
+
+ rowsRead++;
+ var code = Text(row, columns[CodeHeader]);
+
+ // Counted before the checks, so a rejected row keeps its place: once it is fixed and the file imported again,
+ // the rows of the same item after it keep the key they had.
+ var position = occurrences[code] = occurrences.GetValueOrDefault(code) + 1;
+ var excelErrors = columns
+ .Select(column => BusinessCentralWorkbook.ExcelError(row.Cell(column.Value), column.Key))
+ .OfType()
+ .ToList();
+ if (excelErrors.Count > 0)
+ {
+ errors.Add(Error(rowNumber, DonationImportErrorCode.ExcelError, string.Join(" ", excelErrors), null));
+ continue;
+ }
+
+ var type = Text(row, columns[TypeHeader]);
+ if (!string.Equals(type, ItemType, StringComparison.OrdinalIgnoreCase))
+ {
+ var shownType = type.Length == 0 ? "empty" : type;
+ errors.Add(Error(rowNumber, DonationImportErrorCode.NotAnItemLine, $"The line type is {shownType}, not {ItemType}, so it is not a donated item.", code));
+ continue;
+ }
+
+ var lineError = CheckLine(row, rowNumber, columns, code, out var quantity);
+ if (lineError is not null)
+ {
+ errors.Add(lineError);
+ continue;
+ }
+
+ var lineKey = lineNumberColumn is { } column && Text(row, column) is { Length: > 0 } lineNumber
+ ? $"line-{lineNumber}"
+ : $"{code}#{position}";
+
+ lines.Add(new DonationExportLine(
+ rowNumber,
+ lineKey,
+ code,
+ Text(row, columns[NameHeader]),
+ quantity,
+ Text(row, columns[UnitHeader]),
+ Text(row, columns[QualityHeader])));
+ }
+
+ return new DonationExport(rowsRead, lines, errors);
+ }
+
+ private static DonationImportErrorDto? CheckLine(
+ IXLRow row, int rowNumber, IReadOnlyDictionary columns, string code, out decimal quantity)
+ {
+ quantity = 0;
+ if (code.Length == 0)
+ {
+ return Error(rowNumber, DonationImportErrorCode.MissingItemCode, $"The {CodeHeader} cell is empty, so the item cannot be found.", null);
+ }
+
+ var quantityCell = BusinessCentralWorkbook.SavedValue(row.Cell(columns[QuantityHeader]));
+ if (quantityCell.IsBlank || Text(row, columns[QuantityHeader]).Length == 0)
+ {
+ return Error(rowNumber, DonationImportErrorCode.MissingQuantity, "The quantity is empty.", code);
+ }
+
+ if (!TryReadQuantity(quantityCell, out quantity))
+ {
+ return Error(rowNumber, DonationImportErrorCode.InvalidQuantity, $"The quantity {Text(row, columns[QuantityHeader])} is not a number with at most {QuantityDecimals} decimals.", code);
+ }
+
+ if (quantity <= 0)
+ {
+ return Error(rowNumber, DonationImportErrorCode.NegativeQuantity, $"The quantity is {quantity.ToString(CultureInfo.InvariantCulture)}. A return or an empty line cannot be imported as a donation.", code);
+ }
+
+ if (Text(row, columns[UnitHeader]).Length == 0)
+ {
+ return Error(rowNumber, DonationImportErrorCode.MissingUnit, "The unit is empty.", code);
+ }
+
+ var quality = Text(row, columns[QualityHeader]);
+ if (quality.Length == 0)
+ {
+ return Error(rowNumber, DonationImportErrorCode.MissingQuality, "The quality is empty, so the value cannot be calculated.", code);
+ }
+
+ if (!BusinessCentralQuality.TryGetQualityClass(quality, out _))
+ {
+ return Error(rowNumber, DonationImportErrorCode.UnknownQuality, $"The quality {quality} is not one of {string.Join(", ", BusinessCentralQuality.KnownValues)}.", code);
+ }
+
+ return null;
+ }
+
+ ///
+ /// Reads a quantity saved as a number, or as text with a dot or a comma as decimal separator (48.5 or 48,5).
+ /// A number Excel saved in binary is rounded to 10 decimals first, so 0.1 + 0.2 saved as 0.30000000000000004 reads as 0.3.
+ ///
+ private static bool TryReadQuantity(XLCellValue cell, out decimal quantity)
+ {
+ quantity = 0;
+ if (cell.IsNumber)
+ {
+ var number = cell.GetNumber();
+ if (double.IsNaN(number) || Math.Abs(number) > (double)LargestQuantity)
+ {
+ return false;
+ }
+
+ quantity = Math.Round((decimal)number, 10);
+ }
+ else
+ {
+ var text = cell.ToString(CultureInfo.InvariantCulture).Trim().Replace(',', '.');
+ if (!decimal.TryParse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out quantity))
+ {
+ return false;
+ }
+ }
+
+ return Math.Abs(quantity) <= LargestQuantity && quantity == Math.Round(quantity, QuantityDecimals);
+ }
+
+ private static int? FindOptionalColumn(IXLWorksheet sheet, string header)
+ {
+ try
+ {
+ return BusinessCentralWorkbook.FindColumns(sheet, [header])[header];
+ }
+ catch (BusinessCentralExportException)
+ {
+ return null;
+ }
+ }
+
+ private static string Text(IXLRow row, int column) => BusinessCentralWorkbook.ReadText(row.Cell(column));
+
+ private static DonationImportErrorDto Error(int rowNumber, DonationImportErrorCode code, string message, string? itemCode) =>
+ new(rowNumber, code, message, string.IsNullOrEmpty(itemCode) ? null : itemCode);
+}
+
+public record DonationExport(int RowsRead, IReadOnlyList Lines, IReadOnlyList Errors);
+
+/// Identifies the line within its purchase order: the Business Central line number when the export
+/// has one, otherwise the item code and its position among the rows with that code, rejected rows included (1000112#2 is
+/// the second Poivron row).
+public record DonationExportLine(
+ int RowNumber,
+ string LineKey,
+ string ItemCode,
+ string Description,
+ decimal Quantity,
+ string Unit,
+ string Quality);
diff --git a/src/MoissonMontreal.Api/Donations/DonationImportRequest.cs b/src/MoissonMontreal.Api/Donations/DonationImportRequest.cs
new file mode 100644
index 0000000..f592afe
--- /dev/null
+++ b/src/MoissonMontreal.Api/Donations/DonationImportRequest.cs
@@ -0,0 +1,10 @@
+namespace MoissonMontreal.Api.Donations;
+
+public record DonationImportRequest(
+ string FileName,
+ string FileSha256,
+ string DocumentNumber,
+ string DonorCode,
+ DateOnly DonationDate,
+ bool ConfirmDuplicate,
+ DonationExport Export);
diff --git a/src/MoissonMontreal.Api/Donations/DonationImporter.cs b/src/MoissonMontreal.Api/Donations/DonationImporter.cs
new file mode 100644
index 0000000..15be802
--- /dev/null
+++ b/src/MoissonMontreal.Api/Donations/DonationImporter.cs
@@ -0,0 +1,211 @@
+using System.Security.Claims;
+
+using Microsoft.EntityFrameworkCore;
+
+using MoissonMontreal.Api.Authorization;
+using MoissonMontreal.Api.Catalog;
+using MoissonMontreal.Api.Data;
+using MoissonMontreal.Api.Data.Configurations;
+using MoissonMontreal.Core.Donations;
+using MoissonMontreal.Core.Dtos;
+using MoissonMontreal.Core.Entities;
+using MoissonMontreal.Core.Pricing;
+
+using Npgsql;
+
+namespace MoissonMontreal.Api.Donations;
+
+public class DonationImporter(MoissonDbContext db, UserLookupService users, BcItemMappingService mappings)
+{
+ ///
+ /// Unit of every price in the grid (issue #28). A line counted in another unit, such as CA (case), cannot be valued
+ /// until we know how to turn it into kg, so it is rejected instead of being valued with a price per kg.
+ ///
+ public const string PriceUnit = "KG";
+
+ ///
+ /// Turns the valid lines of a Business Central export into donations and records the import with its errors.
+ /// Each line is resolved through its confirmed mapping and valued with at the price in effect
+ /// on the donation date; the price and percentage used are copied into the line. A line that is already imported (same
+ /// source key) is skipped, so overlapping files never create a donation twice. Invalid lines are rejected and reported,
+ /// the valid ones are imported. Everything is saved in one transaction: if anything fails, nothing is kept.
+ ///
+ /// The same file was already imported and the import is not confirmed.
+ /// Someone imported the same lines at the same time.
+ public async Task ImportAsync(
+ DonationImportRequest request,
+ ClaimsPrincipal employee,
+ CancellationToken cancellationToken = default)
+ {
+ var user = await users.FindActiveUserAsync(employee, cancellationToken)
+ ?? throw new InvalidOperationException("Only an employee with an active account can import donations.");
+
+ if (!request.ConfirmDuplicate)
+ {
+ var previous = await db.DonationImports
+ .Where(i => i.FileSha256 == request.FileSha256)
+ .OrderBy(i => i.ImportedAt)
+ .Select(i => new { i.Id, i.ImportedAt, i.ImportedBy.DisplayName })
+ .FirstOrDefaultAsync(cancellationToken);
+ if (previous is not null)
+ {
+ throw new DuplicateDonationImportException(previous.Id, previous.ImportedAt, previous.DisplayName);
+ }
+ }
+
+ var donorCode = request.DonorCode.Trim();
+ var documentNumber = request.DocumentNumber.Trim();
+ var donor = await db.Donors.SingleOrDefaultAsync(d => d.BusinessCentralCode == donorCode, cancellationToken);
+ var lines = request.Export.Lines;
+
+ var itemMappings = await mappings.ResolveAsync(lines.Select(l => l.ItemCode), cancellationToken);
+ var qualityClasses = await db.QualityClasses.ToDictionaryAsync(q => q.Code, cancellationToken);
+ var catalogItemIds = itemMappings.Values.Select(m => m.CatalogItemId).Distinct().ToList();
+ var prices = (await db.Prices
+ .AsNoTracking()
+ .Where(p => catalogItemIds.Contains(p.CatalogItemId))
+ .ToListAsync(cancellationToken))
+ .ToLookup(p => p.CatalogItemId);
+ var sourceKeys = lines.Select(l => SourceKey(documentNumber, l)).ToList();
+ var alreadyImported = (await db.FoodItems
+ .Where(f => f.SourceKey != null && sourceKeys.Contains(f.SourceKey))
+ .Select(f => f.SourceKey!)
+ .ToListAsync(cancellationToken))
+ .ToHashSet(StringComparer.Ordinal);
+
+ var import = new DonationImport
+ {
+ FileName = request.FileName,
+ FileSha256 = request.FileSha256,
+ DocumentNumber = documentNumber,
+ DonorCode = donorCode,
+ DonorId = donor?.Id,
+ DonationDate = request.DonationDate,
+ ImportedByUserId = user.Id,
+ RowsRead = request.Export.RowsRead,
+ };
+
+ var errors = request.Export.Errors.ToList();
+ foreach (var line in lines)
+ {
+ var sourceKey = SourceKey(documentNumber, line);
+ if (alreadyImported.Contains(sourceKey))
+ {
+ import.RowsAlreadyImported++;
+ continue;
+ }
+
+ if (donor is null)
+ {
+ errors.Add(Error(line, DonationImportErrorCode.UnknownDonor, $"No donor has the Business Central code {donorCode}. Add the code to the donor's profile, then import the file again."));
+ continue;
+ }
+
+ var lineError = Value(line, itemMappings, qualityClasses, prices, request.DonationDate, out var foodItem);
+ if (lineError is not null)
+ {
+ errors.Add(lineError);
+ continue;
+ }
+
+ foodItem!.DonorId = donor.Id;
+ foodItem.SourceKey = sourceKey;
+ import.FoodItems.Add(foodItem);
+ alreadyImported.Add(sourceKey);
+ }
+
+ import.RowsImported = import.FoodItems.Count;
+ import.RowsRejected = errors.Count;
+ import.TotalValue = import.FoodItems.Sum(f => f.Value ?? 0m);
+ import.Status = import.RowsImported == 0
+ ? DonationImportStatus.NothingImported
+ : errors.Count == 0 ? DonationImportStatus.Imported : DonationImportStatus.ImportedWithErrors;
+ foreach (var error in errors.OrderBy(e => e.RowNumber))
+ {
+ import.Errors.Add(new DonationImportError
+ {
+ RowNumber = error.RowNumber,
+ Code = error.Code,
+ Message = Truncate(error.Message, DonationImportError.MessageMaxLength),
+ BusinessCentralCode = error.BusinessCentralCode,
+ });
+ }
+
+ db.DonationImports.Add(import);
+ await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
+ try
+ {
+ await db.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException exception) when (exception.InnerException is PostgresException { ConstraintName: FoodItemConfiguration.SourceKeyIndex })
+ {
+ throw new ConcurrentDonationImportException(exception);
+ }
+
+ await transaction.CommitAsync(cancellationToken);
+ return import;
+ }
+
+ private static DonationImportErrorDto? Value(
+ DonationExportLine line,
+ IReadOnlyDictionary itemMappings,
+ IReadOnlyDictionary qualityClasses,
+ ILookup prices,
+ DateOnly donationDate,
+ out FoodItem? foodItem)
+ {
+ foodItem = null;
+ if (!itemMappings.TryGetValue(line.ItemCode, out var mapping))
+ {
+ return Error(line, DonationImportErrorCode.UnmappedItem, $"The Business Central item {line.ItemCode} is not matched to a catalog item yet. Confirm its mapping, then import the file again.");
+ }
+
+ var catalogItem = mapping.CatalogItem;
+ if (!catalogItem.IsActive)
+ {
+ return Error(line, DonationImportErrorCode.InactiveCatalogItem, $"The Business Central item {line.ItemCode} is matched to {catalogItem.Name}, which is no longer in the price grid. Review its mapping.");
+ }
+
+ if (!string.Equals(line.Unit.Trim(), PriceUnit, StringComparison.OrdinalIgnoreCase))
+ {
+ return Error(line, DonationImportErrorCode.UnitMismatch, $"The line is in {line.Unit}, but prices are per kg. A line in another unit cannot be valued yet.");
+ }
+
+ if (!string.Equals(line.Unit.Trim(), catalogItem.Unit.Trim(), StringComparison.OrdinalIgnoreCase))
+ {
+ return Error(line, DonationImportErrorCode.UnitMismatch, $"The line is in {line.Unit}, but the price of {catalogItem.Name} is per {catalogItem.Unit}.");
+ }
+
+ BusinessCentralQuality.TryGetQualityClass(line.Quality, out var qualityCode);
+ var qualityClass = qualityClasses[qualityCode];
+ var price = PriceHistory.FindPriceInEffect(prices[catalogItem.Id], donationDate);
+ if (price is null)
+ {
+ return Error(line, DonationImportErrorCode.NoPriceOnDate, $"{catalogItem.Name} has no price on {donationDate:yyyy-MM-dd}, so the donation cannot be valued.");
+ }
+
+ foodItem = new FoodItem
+ {
+ Name = line.Description.Length > 0 ? line.Description : catalogItem.Name,
+ Quantity = line.Quantity,
+ Unit = line.Unit,
+ DonationDate = donationDate,
+ Quality = qualityClass.Code,
+ CatalogItemId = catalogItem.Id,
+ BusinessCentralCode = line.ItemCode,
+ UnitPrice = price.UnitPrice,
+ PriceEffectiveDate = price.EffectiveDate,
+ QualityPercent = qualityClass.Percentage,
+ Value = DonationValue.CalculateLine(line.Quantity, price.UnitPrice, qualityClass.Percentage),
+ };
+ return null;
+ }
+
+ private static string SourceKey(string documentNumber, DonationExportLine line) =>
+ Truncate($"{documentNumber}/{line.LineKey}", FoodItemConfiguration.SourceKeyMaxLength);
+
+ private static DonationImportErrorDto Error(DonationExportLine line, DonationImportErrorCode code, string message) =>
+ new(line.RowNumber, code, message, line.ItemCode);
+
+ private static string Truncate(string text, int maxLength) => text.Length <= maxLength ? text : text[..maxLength];
+}
diff --git a/src/MoissonMontreal.Api/Program.cs b/src/MoissonMontreal.Api/Program.cs
index d9bd275..a5095b1 100644
--- a/src/MoissonMontreal.Api/Program.cs
+++ b/src/MoissonMontreal.Api/Program.cs
@@ -4,6 +4,7 @@
using Microsoft.Identity.Web;
using MoissonMontreal.Api.Accounts;
using MoissonMontreal.Api.Data;
+using MoissonMontreal.Api.Donations;
using MoissonMontreal.Api.Authorization;
using MoissonMontreal.Api.Catalog;
using MoissonMontreal.Api.Pricing;
@@ -51,6 +52,7 @@
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
+builder.Services.AddScoped();
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
diff --git a/src/MoissonMontreal.Core/Donations/BusinessCentralQuality.cs b/src/MoissonMontreal.Core/Donations/BusinessCentralQuality.cs
new file mode 100644
index 0000000..fc36fcb
--- /dev/null
+++ b/src/MoissonMontreal.Core/Donations/BusinessCentralQuality.cs
@@ -0,0 +1,20 @@
+namespace MoissonMontreal.Core.Donations;
+
+///
+/// Turns the quality written by the operations team in Business Central (column "Qualité du test") into a quality class.
+/// To confirm with Moisson Montréal: Bon is read as A, Moyen as B and Mauvais as C.
+///
+public static class BusinessCentralQuality
+{
+ private static readonly Dictionary Classes = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["Bon"] = "A",
+ ["Moyen"] = "B",
+ ["Mauvais"] = "C",
+ };
+
+ public static IReadOnlyCollection KnownValues => Classes.Keys;
+
+ public static bool TryGetQualityClass(string businessCentralQuality, out string qualityClass) =>
+ Classes.TryGetValue(businessCentralQuality.Trim(), out qualityClass!);
+}
diff --git a/src/MoissonMontreal.Core/Donations/ConcurrentDonationImportException.cs b/src/MoissonMontreal.Core/Donations/ConcurrentDonationImportException.cs
new file mode 100644
index 0000000..b18925a
--- /dev/null
+++ b/src/MoissonMontreal.Core/Donations/ConcurrentDonationImportException.cs
@@ -0,0 +1,4 @@
+namespace MoissonMontreal.Core.Donations;
+
+public class ConcurrentDonationImportException(Exception innerException)
+ : Exception("Some of these lines were imported by someone else at the same time. Nothing was saved: start the import again.", innerException);
diff --git a/src/MoissonMontreal.Core/Donations/DonationImportErrorCode.cs b/src/MoissonMontreal.Core/Donations/DonationImportErrorCode.cs
new file mode 100644
index 0000000..138cdb1
--- /dev/null
+++ b/src/MoissonMontreal.Core/Donations/DonationImportErrorCode.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace MoissonMontreal.Core.Donations;
+
+[JsonConverter(typeof(JsonStringEnumConverter))]
+public enum DonationImportErrorCode
+{
+ ExcelError,
+ NotAnItemLine,
+ MissingItemCode,
+ MissingQuantity,
+ InvalidQuantity,
+ NegativeQuantity,
+ MissingUnit,
+ MissingQuality,
+ UnknownQuality,
+ UnknownDonor,
+ UnmappedItem,
+ InactiveCatalogItem,
+ UnitMismatch,
+ NoPriceOnDate,
+}
diff --git a/src/MoissonMontreal.Core/Donations/DonationImportStatus.cs b/src/MoissonMontreal.Core/Donations/DonationImportStatus.cs
new file mode 100644
index 0000000..0dada51
--- /dev/null
+++ b/src/MoissonMontreal.Core/Donations/DonationImportStatus.cs
@@ -0,0 +1,11 @@
+using System.Text.Json.Serialization;
+
+namespace MoissonMontreal.Core.Donations;
+
+[JsonConverter(typeof(JsonStringEnumConverter))]
+public enum DonationImportStatus
+{
+ Imported,
+ ImportedWithErrors,
+ NothingImported,
+}
diff --git a/src/MoissonMontreal.Core/Donations/DuplicateDonationImportException.cs b/src/MoissonMontreal.Core/Donations/DuplicateDonationImportException.cs
new file mode 100644
index 0000000..11a016a
--- /dev/null
+++ b/src/MoissonMontreal.Core/Donations/DuplicateDonationImportException.cs
@@ -0,0 +1,11 @@
+namespace MoissonMontreal.Core.Donations;
+
+public class DuplicateDonationImportException(Guid previousImportId, DateTimeOffset importedAt, string importedBy)
+ : Exception($"This file was already imported on {importedAt:yyyy-MM-dd HH:mm} UTC by {importedBy}. Send confirmDuplicate=true to import it again: lines already imported are skipped, so no donation is created twice.")
+{
+ public Guid PreviousImportId { get; } = previousImportId;
+
+ public DateTimeOffset ImportedAt { get; } = importedAt;
+
+ public string ImportedBy { get; } = importedBy;
+}
diff --git a/src/MoissonMontreal.Core/Dtos/DonationImportDto.cs b/src/MoissonMontreal.Core/Dtos/DonationImportDto.cs
new file mode 100644
index 0000000..f7b0c58
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/DonationImportDto.cs
@@ -0,0 +1,36 @@
+using MoissonMontreal.Core.Donations;
+
+namespace MoissonMontreal.Core.Dtos;
+
+public record DonationImportDto(
+ Guid Id,
+ string FileName,
+ string DocumentNumber,
+ string DonorCode,
+ string? DonorName,
+ DateOnly DonationDate,
+ DonationImportStatus Status,
+ int RowsRead,
+ int RowsImported,
+ int RowsRejected,
+ int RowsAlreadyImported,
+ decimal TotalValue,
+ string ImportedBy,
+ DateTimeOffset ImportedAt);
+
+public record DonationImportReport(
+ DonationImportDto Import,
+ IReadOnlyList UnmappedItems,
+ IReadOnlyList UnknownDonors);
+
+public record DonationImportLineDto(
+ string SourceKey,
+ string? BusinessCentralCode,
+ string Name,
+ decimal Quantity,
+ string Unit,
+ string QualityClass,
+ decimal? QualityPercent,
+ decimal? UnitPrice,
+ DateOnly? PriceEffectiveDate,
+ decimal? Value);
diff --git a/src/MoissonMontreal.Core/Dtos/DonationImportErrorDto.cs b/src/MoissonMontreal.Core/Dtos/DonationImportErrorDto.cs
new file mode 100644
index 0000000..9dc9a45
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/DonationImportErrorDto.cs
@@ -0,0 +1,5 @@
+using MoissonMontreal.Core.Donations;
+
+namespace MoissonMontreal.Core.Dtos;
+
+public record DonationImportErrorDto(int RowNumber, DonationImportErrorCode Code, string Message, string? BusinessCentralCode);
diff --git a/src/MoissonMontreal.Core/Entities/DonationImport.cs b/src/MoissonMontreal.Core/Entities/DonationImport.cs
new file mode 100644
index 0000000..c727f1a
--- /dev/null
+++ b/src/MoissonMontreal.Core/Entities/DonationImport.cs
@@ -0,0 +1,57 @@
+using MoissonMontreal.Core.Donations;
+
+namespace MoissonMontreal.Core.Entities;
+
+public class DonationImport
+{
+ public const int FileNameMaxLength = 255;
+
+ public const int DocumentNumberMaxLength = 50;
+
+ public const int DonorCodeMaxLength = Donor.BusinessCentralCodeMaxLength;
+
+ public Guid Id { get; set; }
+
+ public string FileName { get; set; } = string.Empty;
+
+ ///
+ /// SHA-256 checksum of the file, in lowercase hexadecimal. Two identical files have the same checksum, which is how a
+ /// second import of the same file is detected.
+ ///
+ public string FileSha256 { get; set; } = string.Empty;
+
+ public string DocumentNumber { get; set; } = string.Empty;
+
+ public string DonorCode { get; set; } = string.Empty;
+
+ ///
+ /// Donor found from , or empty when no donor has that Business Central code.
+ ///
+ public Guid? DonorId { get; set; }
+
+ public Donor? Donor { get; set; }
+
+ public DateOnly DonationDate { get; set; }
+
+ public DonationImportStatus Status { get; set; }
+
+ public int RowsRead { get; set; }
+
+ public int RowsImported { get; set; }
+
+ public int RowsRejected { get; set; }
+
+ public int RowsAlreadyImported { get; set; }
+
+ public decimal TotalValue { get; set; }
+
+ public int ImportedByUserId { get; set; }
+
+ public User ImportedBy { get; set; } = null!;
+
+ public DateTimeOffset ImportedAt { get; set; }
+
+ public ICollection Errors { get; set; } = [];
+
+ public ICollection FoodItems { get; set; } = [];
+}
diff --git a/src/MoissonMontreal.Core/Entities/DonationImportError.cs b/src/MoissonMontreal.Core/Entities/DonationImportError.cs
new file mode 100644
index 0000000..584a4f8
--- /dev/null
+++ b/src/MoissonMontreal.Core/Entities/DonationImportError.cs
@@ -0,0 +1,22 @@
+using MoissonMontreal.Core.Donations;
+
+namespace MoissonMontreal.Core.Entities;
+
+public class DonationImportError
+{
+ public const int MessageMaxLength = 500;
+
+ public Guid Id { get; set; }
+
+ public Guid DonationImportId { get; set; }
+
+ public DonationImport DonationImport { get; set; } = null!;
+
+ public int RowNumber { get; set; }
+
+ public DonationImportErrorCode Code { get; set; }
+
+ public string Message { get; set; } = string.Empty;
+
+ public string? BusinessCentralCode { get; set; }
+}
diff --git a/src/MoissonMontreal.Core/Entities/FoodItem.cs b/src/MoissonMontreal.Core/Entities/FoodItem.cs
index 5373611..557a090 100644
--- a/src/MoissonMontreal.Core/Entities/FoodItem.cs
+++ b/src/MoissonMontreal.Core/Entities/FoodItem.cs
@@ -65,4 +65,46 @@ public class FoodItem
/// Date and time the item was added, set by the database.
///
public DateTimeOffset CreatedAt { get; set; }
+
+ ///
+ /// Code of the item in Business Central, for a donation imported from Business Central. Empty otherwise.
+ ///
+ public string? BusinessCentralCode { get; set; }
+
+ ///
+ /// Price of one unit used to value the donation when it was imported, copied from the price grid so the value can be
+ /// recalculated the same way even if the grid changes later. Empty for a donation that was not valued at import.
+ ///
+ public decimal? UnitPrice { get; set; }
+
+ ///
+ /// Date the copied price started to apply in the price grid.
+ ///
+ public DateOnly? PriceEffectiveDate { get; set; }
+
+ ///
+ /// Percentage of the price kept for the quality class when the donation was valued, copied like the price.
+ ///
+ public decimal? QualityPercent { get; set; }
+
+ ///
+ /// Value of the donation in dollars when it was imported: quantity × unit price × quality percentage, rounded to the cent.
+ ///
+ public decimal? Value { get; set; }
+
+ ///
+ /// Import that created this donation, or empty for a donation entered by hand.
+ ///
+ public Guid? DonationImportId { get; set; }
+
+ ///
+ /// Import that created this donation.
+ ///
+ public DonationImport? DonationImport { get; set; }
+
+ ///
+ /// Identifies the Business Central line this donation comes from, such as COMA-000295/1000112#2. Unique, so importing a
+ /// line twice, from the same file or from two files that overlap, never creates a second donation.
+ ///
+ public string? SourceKey { get; set; }
}
diff --git a/tests/MoissonMontreal.Tests/Api/BusinessCentralExportReaderTests.cs b/tests/MoissonMontreal.Tests/Api/BusinessCentralExportReaderTests.cs
index 37e3be2..caee1e2 100644
--- a/tests/MoissonMontreal.Tests/Api/BusinessCentralExportReaderTests.cs
+++ b/tests/MoissonMontreal.Tests/Api/BusinessCentralExportReaderTests.cs
@@ -1,9 +1,8 @@
-using System.IO.Compression;
-
using ClosedXML.Excel;
using MoissonMontreal.Api.Catalog;
using MoissonMontreal.Core.Dtos;
+using MoissonMontreal.Tests.Fixtures;
namespace MoissonMontreal.Tests.Api;
@@ -116,7 +115,7 @@ public void Read_ReadsTheSavedValue_OfAFormulaCell_WithoutCalculatingTheFormula(
using var saved = Save(workbook);
// The saved value differs from what the formula gives, so reading "Citron lime" would mean the formula was calculated.
- using var file = WithSavedFormulaValue(saved, "D2", "Nom enregistré");
+ using var file = ExcelTestFiles.WithSavedFormulaValue(saved, "D2", "Nom enregistré");
var row = Assert.Single(BusinessCentralExportReader.Read(file).Rows);
@@ -162,7 +161,7 @@ public void Read_ReportsAFormulaCell_WhoseSavedResultIsAnExcelError()
sheet.Cell(2, 4).FormulaA1 = "VLOOKUP(B2, Articles!A:B, 2, FALSE)";
sheet.Cell(2, 7).Value = "CA";
using var saved = Save(workbook);
- using var file = WithSavedFormulaValue(saved, "D2", "#N/A", valueType: "e");
+ using var file = ExcelTestFiles.WithSavedFormulaValue(saved, "D2", "#N/A", valueType: "e");
var export = BusinessCentralExportReader.Read(file);
@@ -252,35 +251,4 @@ private static MemoryStream Save(XLWorkbook workbook)
stream.Position = 0;
return stream;
}
-
- // ClosedXML saves a formula without its result, so the result Excel would have saved is written into the sheet XML by hand.
- private static MemoryStream WithSavedFormulaValue(MemoryStream workbook, string cell, string savedValue, string valueType = "str")
- {
- var copy = new MemoryStream();
- workbook.CopyTo(copy);
-
- using (var zip = new ZipArchive(copy, ZipArchiveMode.Update, leaveOpen: true))
- {
- var entry = zip.GetEntry("xl/worksheets/sheet1.xml")!;
- string xml;
- using (var reader = new StreamReader(entry.Open()))
- {
- xml = reader.ReadToEnd();
- }
-
- var cellStart = $"";
- Assert.Contains(cellStart, xml);
- var cellIndex = xml.IndexOf(cellStart, StringComparison.Ordinal);
- var formulaEnd = xml.IndexOf("", cellIndex, StringComparison.Ordinal) + "".Length;
- xml = xml[..formulaEnd] + $"{savedValue}" + xml[formulaEnd..];
- xml = xml.Replace(cellStart, $"");
-
- entry.Delete();
- using var writer = new StreamWriter(zip.CreateEntry("xl/worksheets/sheet1.xml").Open());
- writer.Write(xml);
- }
-
- copy.Position = 0;
- return copy;
- }
}
diff --git a/tests/MoissonMontreal.Tests/Api/DonationExportReaderTests.cs b/tests/MoissonMontreal.Tests/Api/DonationExportReaderTests.cs
new file mode 100644
index 0000000..7a074f3
--- /dev/null
+++ b/tests/MoissonMontreal.Tests/Api/DonationExportReaderTests.cs
@@ -0,0 +1,301 @@
+using System.Text;
+
+using ClosedXML.Excel;
+
+using MoissonMontreal.Api.Catalog;
+using MoissonMontreal.Api.Donations;
+using MoissonMontreal.Core.Donations;
+using MoissonMontreal.Tests.Docs;
+using MoissonMontreal.Tests.Fixtures;
+
+namespace MoissonMontreal.Tests.Api;
+
+public class DonationExportReaderTests
+{
+ private static readonly object[] RealHeaders =
+ ["Type", "N°", "Withholding Tax Prod. Post. Group", "Description", "Code d'emplacement", "Quantité", "Code d’unité de mesure", "Qualité du test"];
+
+ [Fact]
+ public void Read_ReadsTheItemLines_OfARealPurchaseOrderExport()
+ {
+ using var file = BuildExport(
+ ["Article", "1000094", "", "Citron lime", "CDL", 48, "CA", "Bon"],
+ ["Article", "1000112", "", "Poivron", "CDL", 100, "CA", "Moyen"],
+ ["Article", "1000112", "", "Poivron", "CDL", 90, "CA", "Bon"]);
+
+ var export = DonationExportReader.Read(file);
+
+ Assert.Equal(3, export.RowsRead);
+ Assert.Empty(export.Errors);
+ Assert.Equal(
+ [
+ new DonationExportLine(2, "1000094#1", "1000094", "Citron lime", 48m, "CA", "Bon"),
+ new DonationExportLine(3, "1000112#1", "1000112", "Poivron", 100m, "CA", "Moyen"),
+ new DonationExportLine(4, "1000112#2", "1000112", "Poivron", 90m, "CA", "Bon"),
+ ],
+ export.Lines);
+ }
+
+ [Fact]
+ public void Read_ReadsTheAnonymizedSampleOfTheRealExport_WithoutABlockingError()
+ {
+ using var file = File.OpenRead(Path.Combine(RepositoryPaths.DatabaseDocs, "samples", "purchase-order-lines-anonymized.xlsx"));
+
+ var export = DonationExportReader.Read(file);
+
+ Assert.Equal(17, export.RowsRead);
+ Assert.Equal(14, export.Lines.Count);
+ Assert.Equal(
+ Enumerable.Range(1, 8).Select(n => $"1000112#{n}"),
+ export.Lines.Where(l => l.ItemCode == "1000112").Select(l => l.LineKey));
+ Assert.Equal(
+ [
+ (16, DonationImportErrorCode.NotAnItemLine),
+ (18, DonationImportErrorCode.NegativeQuantity),
+ (19, DonationImportErrorCode.MissingQuality),
+ ],
+ export.Errors.Select(e => (e.RowNumber, e.Code)));
+ }
+
+ [Fact]
+ public void Read_FindsTheColumnsByName_InAnyOrder()
+ {
+ using var workbook = new XLWorkbook();
+ var sheet = workbook.AddWorksheet("Lignes");
+ object[] headers = ["Qualité du test", "Code d'unité de mesure", "Quantité", "Description", "N°", "Type"];
+ object[] values = ["Bon", "CA", 56, "Tomate", "1000110", "Article"];
+ for (var column = 0; column < headers.Length; column++)
+ {
+ sheet.Cell(1, column + 1).Value = XLCellValue.FromObject(headers[column]);
+ sheet.Cell(2, column + 1).Value = XLCellValue.FromObject(values[column]);
+ }
+
+ var line = Assert.Single(DonationExportReader.Read(Save(workbook)).Lines);
+
+ Assert.Equal(("1000110", "Tomate", 56m, "CA", "Bon"), (line.ItemCode, line.Description, line.Quantity, line.Unit, line.Quality));
+ }
+
+ [Fact]
+ public void Read_UsesTheBusinessCentralLineNumber_WhenTheExportHasIt()
+ {
+ using var workbook = new XLWorkbook();
+ var sheet = workbook.AddWorksheet("Lignes");
+ object[][] rows =
+ [
+ ["N° ligne", "Type", "N°", "Description", "Quantité", "Code d'unité de mesure", "Qualité du test"],
+ [20000, "Article", "1000112", "Poivron", 22, "CA", "Bon"],
+ ];
+ for (var row = 0; row < rows.Length; row++)
+ {
+ for (var column = 0; column < rows[row].Length; column++)
+ {
+ sheet.Cell(row + 1, column + 1).Value = XLCellValue.FromObject(rows[row][column]);
+ }
+ }
+
+ var line = Assert.Single(DonationExportReader.Read(Save(workbook)).Lines);
+
+ Assert.Equal("line-20000", line.LineKey);
+ }
+
+ [Fact]
+ public void Read_KeepsTheKeyOfTheNextLines_WhenARejectedRowOfTheSameItemIsFixed()
+ {
+ using var withRejectedRow = BuildExport(
+ ["Article", "1000112", "", "Poivron", "CDL", 100, "CA", ""],
+ ["Article", "1000112", "", "Poivron", "CDL", 90, "CA", "Bon"]);
+ using var withFixedRow = BuildExport(
+ ["Article", "1000112", "", "Poivron", "CDL", 100, "CA", "Moyen"],
+ ["Article", "1000112", "", "Poivron", "CDL", 90, "CA", "Bon"]);
+
+ var before = DonationExportReader.Read(withRejectedRow);
+ var after = DonationExportReader.Read(withFixedRow);
+
+ Assert.Equal(["1000112#2"], before.Lines.Select(l => l.LineKey));
+ Assert.Equal(["1000112#1", "1000112#2"], after.Lines.Select(l => l.LineKey));
+ }
+
+ [Fact]
+ public void Read_ReportsEveryInvalidRow_WithItsRowNumberAndCode_AndKeepsTheValidRows()
+ {
+ using var file = BuildExport(
+ ["Article", "1000094", "", "Citron lime", "CDL", 48, "CA", "Bon"],
+ ["Article", "", "", "Sans code", "CDL", 10, "CA", "Bon"],
+ ["Article", "1000112", "", "Poivron", "CDL", "", "CA", "Bon"],
+ ["Article", "1000112", "", "Poivron", "CDL", "beaucoup", "CA", "Bon"],
+ ["Article", "1000110", "", "Tomate", "CDL", -5, "CA", "Bon"],
+ ["Article", "1000110", "", "Tomate", "CDL", 1.234, "CA", "Bon"],
+ ["Article", "1000106", "", "Brocoli", "CDL", 32, "", "Bon"],
+ ["Article", "1000106", "", "Brocoli", "CDL", 32, "CA", ""],
+ ["Article", "1000106", "", "Brocoli", "CDL", 32, "CA", "Excellent"],
+ ["Commentaire", "", "", "Livraison en retard", "", "", "", ""],
+ ["Article", "1000071", "", "Fruits et Légumes variés", "CDL", 46, "CA", "Moyen"]);
+
+ var export = DonationExportReader.Read(file);
+
+ Assert.Equal(11, export.RowsRead);
+ Assert.Equal(["1000094", "1000071"], export.Lines.Select(l => l.ItemCode));
+ Assert.Equal(
+ [
+ (3, DonationImportErrorCode.MissingItemCode),
+ (4, DonationImportErrorCode.MissingQuantity),
+ (5, DonationImportErrorCode.InvalidQuantity),
+ (6, DonationImportErrorCode.NegativeQuantity),
+ (7, DonationImportErrorCode.InvalidQuantity),
+ (8, DonationImportErrorCode.MissingUnit),
+ (9, DonationImportErrorCode.MissingQuality),
+ (10, DonationImportErrorCode.UnknownQuality),
+ (11, DonationImportErrorCode.NotAnItemLine),
+ ],
+ export.Errors.Select(e => (e.RowNumber, e.Code)));
+ Assert.All(export.Errors, e => Assert.False(string.IsNullOrWhiteSpace(e.Message)));
+ }
+
+ [Theory]
+ [InlineData("48,5")]
+ [InlineData("48.5")]
+ [InlineData(" 48,50 ")]
+ public void Read_AcceptsAQuantityWrittenWithACommaOrADot(string quantity)
+ {
+ using var file = BuildExport(["Article", "1000094", "", "Citron lime", "CDL", quantity, "CA", "Bon"]);
+
+ Assert.Equal(48.5m, Assert.Single(DonationExportReader.Read(file).Lines).Quantity);
+ }
+
+ [Fact]
+ public void Read_ReadsAQuantitySavedAsABinaryNumber_Exactly()
+ {
+ using var file = BuildExport(["Article", "1000094", "", "Citron lime", "CDL", 0.1 + 0.2, "CA", "Bon"]);
+
+ Assert.Equal(0.3m, Assert.Single(DonationExportReader.Read(file).Lines).Quantity);
+ }
+
+ [Fact]
+ public void Read_ReadsTheSavedValueOfAFormula_WithoutCalculatingIt()
+ {
+ using var workbook = new XLWorkbook();
+ var sheet = workbook.AddWorksheet("Lignes");
+ for (var column = 0; column < RealHeaders.Length; column++)
+ {
+ sheet.Cell(1, column + 1).Value = XLCellValue.FromObject(RealHeaders[column]);
+ }
+
+ object[] values = ["Article", "1000094", "", null!, "CDL", 48, "CA", "Bon"];
+ for (var column = 0; column < values.Length; column++)
+ {
+ if (values[column] is not null)
+ {
+ sheet.Cell(2, column + 1).Value = XLCellValue.FromObject(values[column]);
+ }
+ }
+
+ sheet.Cell(2, 4).FormulaA1 = "\"Citron\" & \" lime\"";
+ using var saved = Save(workbook);
+ using var file = ExcelTestFiles.WithSavedFormulaValue(saved, "D2", "Nom enregistré");
+
+ Assert.Equal("Nom enregistré", Assert.Single(DonationExportReader.Read(file).Lines).Description);
+ }
+
+ [Fact]
+ public void Read_ReportsACellThatContainsAnExcelError()
+ {
+ using var file = BuildExport(["Article", "1000094", "", "Citron lime", "CDL", XLError.DivisionByZero, "CA", "Bon"]);
+
+ var error = Assert.Single(DonationExportReader.Read(file).Errors);
+
+ Assert.Equal((2, DonationImportErrorCode.ExcelError), (error.RowNumber, error.Code));
+ Assert.Contains("#DIV/0!", error.Message);
+ }
+
+ [Fact]
+ public void Read_SkipsEmptyRows()
+ {
+ using var file = BuildExport(
+ ["Article", "1000094", "", "Citron lime", "CDL", 48, "CA", "Bon"],
+ ["", "", "", "", "", "", "", ""],
+ ["Article", "1000106", "", "Brocoli", "CDL", 32, "CA", "Bon"]);
+
+ var export = DonationExportReader.Read(file);
+
+ Assert.Equal(2, export.RowsRead);
+ Assert.Equal([2, 4], export.Lines.Select(l => l.RowNumber));
+ }
+
+ [Fact]
+ public void Read_ReturnsNoRows_WhenTheSheetOnlyHasItsHeaders()
+ {
+ using var file = BuildExport();
+
+ var export = DonationExportReader.Read(file);
+
+ Assert.Equal(0, export.RowsRead);
+ Assert.Empty(export.Lines);
+ }
+
+ [Theory]
+ [InlineData("Type;N°;Description;Quantité\nArticle;1000094;Citron lime;48")]
+ [InlineData("This is not a spreadsheet")]
+ public void Read_Throws_WhenTheFileIsNotAnExcelFile(string content)
+ {
+ using var file = new MemoryStream(Encoding.Latin1.GetBytes(content));
+
+ var error = Assert.Throws(() => DonationExportReader.Read(file));
+
+ Assert.Equal("The file is not a valid Excel (.xlsx) file.", error.Message);
+ }
+
+ [Fact]
+ public void Read_Throws_WhenTheLinesSheetIsMissing()
+ {
+ using var workbook = new XLWorkbook();
+ workbook.AddWorksheet("Articles").Cell(1, 1).Value = "Type";
+
+ var error = Assert.Throws(() => DonationExportReader.Read(Save(workbook)));
+
+ Assert.Equal("The file does not have a sheet named Lignes.", error.Message);
+ }
+
+ [Fact]
+ public void Read_Throws_WhenAColumnIsMissing()
+ {
+ using var workbook = new XLWorkbook();
+ var sheet = workbook.AddWorksheet("Lignes");
+ object[] headers = ["Type", "N°", "Description", "Code d'unité de mesure"];
+ for (var column = 0; column < headers.Length; column++)
+ {
+ sheet.Cell(1, column + 1).Value = XLCellValue.FromObject(headers[column]);
+ }
+
+ var error = Assert.Throws(() => DonationExportReader.Read(Save(workbook)));
+
+ Assert.Equal("The Lignes sheet is missing these columns: Quantité, Qualité du test.", error.Message);
+ }
+
+ private static MemoryStream BuildExport(params object[][] rows)
+ {
+ using var workbook = new XLWorkbook();
+ var sheet = workbook.AddWorksheet("Lignes");
+ for (var column = 0; column < RealHeaders.Length; column++)
+ {
+ sheet.Cell(1, column + 1).Value = XLCellValue.FromObject(RealHeaders[column]);
+ }
+
+ for (var row = 0; row < rows.Length; row++)
+ {
+ for (var column = 0; column < rows[row].Length; column++)
+ {
+ sheet.Cell(row + 2, column + 1).Value = XLCellValue.FromObject(rows[row][column]);
+ }
+ }
+
+ return Save(workbook);
+ }
+
+ private static MemoryStream Save(XLWorkbook workbook)
+ {
+ var stream = new MemoryStream();
+ workbook.SaveAs(stream);
+ stream.Position = 0;
+ return stream;
+ }
+}
diff --git a/tests/MoissonMontreal.Tests/Api/DonationImportEndpointTests.cs b/tests/MoissonMontreal.Tests/Api/DonationImportEndpointTests.cs
new file mode 100644
index 0000000..86b805b
--- /dev/null
+++ b/tests/MoissonMontreal.Tests/Api/DonationImportEndpointTests.cs
@@ -0,0 +1,543 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text;
+using System.Text.Json;
+
+using ClosedXML.Excel;
+
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+using MoissonMontreal.Api.Data;
+using MoissonMontreal.Core.Authorization;
+using MoissonMontreal.Core.Donations;
+using MoissonMontreal.Core.Dtos;
+using MoissonMontreal.Core.Entities;
+using MoissonMontreal.Tests.Fixtures;
+
+namespace MoissonMontreal.Tests.Api;
+
+[Trait("Category", "Integration")]
+public class DonationImportEndpointTests(PermissionsApiFactory factory) : IClassFixture, IAsyncLifetime
+{
+ private const string Route = "/api/donation-imports";
+ private const string SupplyEmail = "supply.import@moissonmontreal.org";
+ private const string SupplyObjectId = "cccccccc-0000-0000-0000-000000000001";
+ private const string FinanceEmail = "finance.import@moissonmontreal.org";
+ private const string FinanceObjectId = "cccccccc-0000-0000-0000-000000000002";
+
+ private static readonly DateOnly DonationDate = new(2026, 11, 15);
+
+ private static readonly object[] Headers =
+ ["Type", "N°", "Withholding Tax Prod. Post. Group", "Description", "Code d'emplacement", "Quantité", "Code d’unité de mesure", "Qualité du test"];
+
+ private int _supplyUserId;
+
+ public async Task InitializeAsync()
+ {
+ await using var context = factory.CreateDbContext();
+ var existing = await context.Users.SingleOrDefaultAsync(u => u.Email == SupplyEmail);
+ if (existing is not null)
+ {
+ _supplyUserId = existing.Id;
+ return;
+ }
+
+ var supply = NewUser(SupplyEmail, "Sam Supply", SupplyObjectId, await RoleIdAsync(context, RoleCodes.Supply));
+ context.Users.Add(supply);
+ context.Users.Add(NewUser(FinanceEmail, "Fred Finance", FinanceObjectId, await RoleIdAsync(context, RoleCodes.Finance)));
+ await context.SaveChangesAsync();
+ _supplyUserId = supply.Id;
+ }
+
+ public Task DisposeAsync() => Task.CompletedTask;
+
+ [Fact]
+ public async Task Import_ValuesEachLineAsCheckedByHand_AndFreezesThePriceAndPercentage()
+ {
+ var scenario = await SeedAsync(
+ ("Citron lime", 12.50m),
+ ("Poivron", 18.75m),
+ ("Tomate", 9.99m),
+ ("Brocoli", 14.333m),
+ ("Fruits et Légumes variés", 7.1235m),
+ ("Pomme", 0.45m),
+ ("Laitue", 3.00m));
+ using var file = Export(
+ Line(scenario.Code(0), "Citron lime", 48, "Bon"),
+ Line(scenario.Code(1), "Poivron", 100, "Moyen"),
+ Line(scenario.Code(2), "Tomate", 56, "Bon"),
+ Line(scenario.Code(3), "Brocoli", 32, "Moyen"),
+ Line(scenario.Code(4), "Fruits et Légumes variés", 46, "Bon"),
+ Line(scenario.Code(5), "Pomme", 1, "Moyen"),
+ Line(scenario.Code(6), "Laitue", 20, "Mauvais"));
+
+ var response = await ImportAsync(file, scenario);
+
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ var report = await response.Content.ReadFromJsonAsync();
+ Assert.NotNull(report);
+ Assert.Equal(
+ (DonationImportStatus.Imported, 7, 7, 0, 0, 2654.18m),
+ (report.Import.Status, report.Import.RowsRead, report.Import.RowsImported, report.Import.RowsRejected, report.Import.RowsAlreadyImported, report.Import.TotalValue));
+
+ var lines = await GetAsync>($"{Route}/{report.Import.Id}/lines?pageSize=100");
+ Assert.Equal(
+ new[]
+ {
+ (scenario.Code(0), 48m, "A", 100m, 12.50m, 600.00m),
+ (scenario.Code(1), 100m, "B", 50m, 18.75m, 937.50m),
+ (scenario.Code(2), 56m, "A", 100m, 9.99m, 559.44m),
+ (scenario.Code(3), 32m, "B", 50m, 14.333m, 229.33m),
+ (scenario.Code(4), 46m, "A", 100m, 7.1235m, 327.68m),
+ (scenario.Code(5), 1m, "B", 50m, 0.45m, 0.23m),
+ (scenario.Code(6), 20m, "C", 0m, 3.00m, 0.00m),
+ }.OrderBy(l => l.Item1, StringComparer.Ordinal),
+ lines.Items
+ .OrderBy(l => l.BusinessCentralCode, StringComparer.Ordinal)
+ .Select(l => (l.BusinessCentralCode!, l.Quantity, l.QualityClass, l.QualityPercent!.Value, l.UnitPrice!.Value, l.Value!.Value)));
+ Assert.All(lines.Items, l => Assert.Equal(new DateOnly(2026, 11, 1), l.PriceEffectiveDate));
+ }
+
+ [Fact]
+ public async Task Import_UsesThePriceInEffectOnTheDonationDate()
+ {
+ var scenario = await SeedAsync(("Poivron", 10.00m));
+ await AddPriceAsync(scenario.CatalogItemIds[0], 99.00m, new DateOnly(2026, 12, 1));
+
+ var report = await ImportReportAsync(Export(Line(scenario.Code(0), "Poivron", 10, "Bon")), scenario);
+
+ Assert.Equal(100.00m, report.Import.TotalValue);
+ }
+
+ [Fact]
+ public async Task Import_KeepsTheFrozenValue_WhenThePriceGridChangesLater()
+ {
+ var scenario = await SeedAsync(("Tomate", 9.99m));
+ var report = await ImportReportAsync(Export(Line(scenario.Code(0), "Tomate", 56, "Bon")), scenario);
+
+ await using (var context = factory.CreateDbContext())
+ {
+ await context.Prices
+ .Where(p => p.CatalogItemId == scenario.CatalogItemIds[0])
+ .ExecuteUpdateAsync(p => p.SetProperty(x => x.UnitPrice, 50.00m));
+ }
+
+ var line = Assert.Single((await GetAsync>($"{Route}/{report.Import.Id}/lines")).Items);
+ Assert.Equal((9.99m, 559.44m), (line.UnitPrice, line.Value));
+ }
+
+ [Fact]
+ public async Task Import_RejectsTheInvalidRows_WithTheirRowNumberAndReason_AndImportsTheOthers()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m), ("Brocoli", 14.00m), ("Kiwi", 5.00m), ("Ancien", 4.00m));
+ await SetUnitAsync(scenario.CatalogItemIds[1], "CA");
+ await AddPriceAsync(scenario.CatalogItemIds[2], 5.00m, new DateOnly(2026, 12, 1), replace: true);
+ await DeactivateAsync(scenario.CatalogItemIds[3]);
+ var unmapped = "UNMAPPED-" + Guid.NewGuid().ToString("N")[..8];
+ using var file = Export(
+ Line(scenario.Code(0), "Citron lime", 48, "Bon"),
+ Line(unmapped, "Mangue", 10, "Bon"),
+ Line(scenario.Code(1), "Brocoli", 32, "Bon"),
+ Line(scenario.Code(2), "Kiwi", 5, "Bon"),
+ Line(scenario.Code(3), "Ancien", 5, "Bon"),
+ Line(scenario.Code(0), "Citron lime", "", "Bon"),
+ ["Commentaire", "", "", "Livraison en retard", "", "", "", ""]);
+
+ var report = await ImportReportAsync(file, scenario);
+
+ Assert.Equal(
+ (DonationImportStatus.ImportedWithErrors, 7, 1, 6, 600.00m),
+ (report.Import.Status, report.Import.RowsRead, report.Import.RowsImported, report.Import.RowsRejected, report.Import.TotalValue));
+ Assert.Equal([unmapped], report.UnmappedItems);
+ Assert.Empty(report.UnknownDonors);
+ var errors = await GetAsync>($"{Route}/{report.Import.Id}/errors");
+ Assert.Equal(
+ [
+ (3, DonationImportErrorCode.UnmappedItem),
+ (4, DonationImportErrorCode.UnitMismatch),
+ (5, DonationImportErrorCode.NoPriceOnDate),
+ (6, DonationImportErrorCode.InactiveCatalogItem),
+ (7, DonationImportErrorCode.MissingQuantity),
+ (8, DonationImportErrorCode.NotAnItemLine),
+ ],
+ errors.Items.Select(e => (e.RowNumber, e.Code)));
+ Assert.All(errors.Items, e => Assert.False(string.IsNullOrWhiteSpace(e.Message)));
+ }
+
+ [Fact]
+ public async Task Import_RejectsALineThatIsNotInKg_EvenWhenTheCatalogItemUsesTheSameUnit()
+ {
+ var scenario = await SeedAsync(("Poivron", 18.75m));
+ await SetUnitAsync(scenario.CatalogItemIds[0], "CA");
+
+ var report = await ImportReportAsync(Export(Line(scenario.Code(0), "Poivron", 100, "Bon", unit: "CA")), scenario);
+
+ Assert.Equal(
+ (DonationImportStatus.NothingImported, 0, 1, 0m),
+ (report.Import.Status, report.Import.RowsImported, report.Import.RowsRejected, report.Import.TotalValue));
+ var error = Assert.Single((await GetAsync>($"{Route}/{report.Import.Id}/errors")).Items);
+ Assert.Equal((2, DonationImportErrorCode.UnitMismatch), (error.RowNumber, error.Code));
+ Assert.Equal(0, await DonationCountAsync(scenario.DocumentNumber));
+ }
+
+ [Fact]
+ public async Task Import_RejectsEveryLine_WhenNoDonorHasTheCode()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m));
+ var unknown = scenario with { DonorCode = "UNKNOWN-" + Guid.NewGuid().ToString("N")[..8] };
+
+ var report = await ImportReportAsync(Export(Line(scenario.Code(0), "Citron lime", 48, "Bon")), unknown);
+
+ Assert.Equal((DonationImportStatus.NothingImported, 0, 1), (report.Import.Status, report.Import.RowsImported, report.Import.RowsRejected));
+ Assert.Equal([unknown.DonorCode], report.UnknownDonors);
+ Assert.Equal(0, await DonationCountAsync(unknown.DocumentNumber));
+ }
+
+ [Fact]
+ public async Task Import_AsksForConfirmation_WhenTheSameFileIsImportedAgain_AndNeverCreatesDuplicates()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m), ("Poivron", 18.75m));
+ var bytes = Export(Line(scenario.Code(0), "Citron lime", 48, "Bon"), Line(scenario.Code(1), "Poivron", 100, "Moyen")).ToArray();
+ var first = await ImportReportAsync(new MemoryStream(bytes), scenario);
+
+ var again = await ImportAsync(new MemoryStream(bytes), scenario);
+
+ Assert.Equal(HttpStatusCode.Conflict, again.StatusCode);
+ using var problem = JsonDocument.Parse(await again.Content.ReadAsStringAsync());
+ Assert.Equal(first.Import.Id, problem.RootElement.GetProperty("previousImportId").GetGuid());
+ Assert.Equal("Sam Supply", problem.RootElement.GetProperty("importedBy").GetString());
+
+ var confirmed = await ImportReportAsync(new MemoryStream(bytes), scenario, confirmDuplicate: true);
+
+ Assert.Equal((0, 2, 0m), (confirmed.Import.RowsImported, confirmed.Import.RowsAlreadyImported, confirmed.Import.TotalValue));
+ Assert.Equal(2, await DonationCountAsync(scenario.DocumentNumber));
+ }
+
+ [Fact]
+ public async Task Import_DoesNotDuplicateLines_FromTwoFilesThatOverlap()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m), ("Poivron", 18.75m), ("Tomate", 9.99m));
+ await ImportReportAsync(
+ Export(Line(scenario.Code(0), "Citron lime", 48, "Bon"), Line(scenario.Code(1), "Poivron", 100, "Moyen")),
+ scenario);
+
+ var second = await ImportReportAsync(
+ Export(
+ Line(scenario.Code(0), "Citron lime", 48, "Bon"),
+ ["Commentaire", "", "", "Ajout", "", "", "", ""],
+ Line(scenario.Code(1), "Poivron", 100, "Moyen"),
+ Line(scenario.Code(2), "Tomate", 56, "Bon")),
+ scenario);
+
+ Assert.Equal((1, 2, 1), (second.Import.RowsImported, second.Import.RowsAlreadyImported, second.Import.RowsRejected));
+ Assert.Equal(3, await DonationCountAsync(scenario.DocumentNumber));
+ }
+
+ [Fact]
+ public async Task Import_SavesNothing_WhenItFailsMidway()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m), ("Poivron", 18.75m));
+ await using (var context = factory.CreateDbContext())
+ {
+ await context.Database.ExecuteSqlRawAsync("""
+ CREATE OR REPLACE FUNCTION crash_import() RETURNS trigger AS $$
+ BEGIN RAISE EXCEPTION 'simulated crash'; END
+ $$ LANGUAGE plpgsql;
+ CREATE TRIGGER crash_import BEFORE INSERT ON food_items
+ FOR EACH ROW WHEN (NEW.name = 'Panne simulée') EXECUTE FUNCTION crash_import();
+ """);
+ }
+
+ try
+ {
+ await Record.ExceptionAsync(() => ImportAsync(
+ Export(Line(scenario.Code(0), "Citron lime", 48, "Bon"), Line(scenario.Code(1), "Panne simulée", 100, "Moyen")),
+ scenario));
+ }
+ finally
+ {
+ await using var context = factory.CreateDbContext();
+ await context.Database.ExecuteSqlRawAsync("DROP TRIGGER crash_import ON food_items; DROP FUNCTION crash_import();");
+ }
+
+ await using var check = factory.CreateDbContext();
+ Assert.Equal(0, await DonationCountAsync(scenario.DocumentNumber));
+ Assert.False(await check.DonationImports.AnyAsync(i => i.DocumentNumber == scenario.DocumentNumber));
+ }
+
+ [Fact]
+ public async Task Import_RecordsWhoImportedAndWhen_InTheHistory()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m));
+ var before = DateTimeOffset.UtcNow;
+ var report = await ImportReportAsync(Export(Line(scenario.Code(0), "Citron lime", 48, "Bon")), scenario, fileName: "COMA-000295.xlsx");
+
+ var history = await GetAsync>($"{Route}?pageSize=100");
+
+ var entry = Assert.Single(history.Items, i => i.Id == report.Import.Id);
+ Assert.Equal(("Sam Supply", "COMA-000295.xlsx", scenario.DocumentNumber, "Boulangerie Saint-Laurent"), (entry.ImportedBy, entry.FileName, entry.DocumentNumber, entry.DonorName));
+ Assert.InRange(entry.ImportedAt, before.AddMinutes(-1), DateTimeOffset.UtcNow.AddMinutes(1));
+ Assert.True(history.TotalCount >= 1);
+ }
+
+ [Fact]
+ public async Task Import_RefusesAnEmptyFile()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m));
+
+ await AssertFileProblemAsync(
+ await ImportAsync(new MemoryStream(), scenario),
+ "No file was sent, or the file is empty. Send the Business Central export in a form field named file.");
+ }
+
+ [Fact]
+ public async Task Import_RefusesAFileWithoutDonationLines()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m));
+
+ await AssertFileProblemAsync(await ImportAsync(Export(), scenario), "The Lignes sheet has no donation line.");
+ }
+
+ [Theory]
+ [InlineData("Type;N°;Quantité\nArticle;1000094;48")]
+ [InlineData("ÿþT\u0000y\u0000p\u0000e\u0000")]
+ public async Task Import_RefusesAMalformedOrBadlyEncodedFile(string content)
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m));
+
+ await AssertFileProblemAsync(
+ await ImportAsync(new MemoryStream(Encoding.Latin1.GetBytes(content)), scenario),
+ "The file is not a valid Excel (.xlsx) file.");
+ }
+
+ [Fact]
+ public async Task Import_RefusesAFileThatIsNotAnXlsxFile()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m));
+
+ await AssertFileProblemAsync(
+ await ImportAsync(Export(Line(scenario.Code(0), "Citron lime", 48, "Bon")), scenario, fileName: "export.csv"),
+ "The file must be an Excel file (.xlsx).");
+ }
+
+ [Fact]
+ public async Task Import_RefusesAnOversizedFile()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m));
+
+ await AssertFileProblemAsync(
+ await ImportAsync(new MemoryStream(new byte[10 * 1024 * 1024 + 1]), scenario),
+ "The file is too large. The limit is 10 MB.");
+ }
+
+ [Fact]
+ public async Task Import_RequiresTheDonorTheDocumentAndTheDate()
+ {
+ using var client = Client(SupplyEmail, SupplyObjectId);
+ using var form = new MultipartFormDataContent { { File(Export()), "file", "export.xlsx" } };
+
+ var response = await client.PostAsync(Route, form);
+
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ var problem = await response.Content.ReadFromJsonAsync();
+ Assert.Equal(["documentNumber", "donationDate", "donorCode"], problem!.Errors.Keys.Order());
+ }
+
+ [Fact]
+ public async Task Import_IsRefused_ForARoleThatCannotManageDonations()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m));
+
+ var response = await ImportAsync(Export(Line(scenario.Code(0), "Citron lime", 48, "Bon")), scenario, FinanceEmail, FinanceObjectId);
+
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task Errors_ArePaginated()
+ {
+ var scenario = await SeedAsync(("Citron lime", 12.50m));
+ var unmapped = Enumerable.Range(0, 5).Select(i => Line($"NONE-{i}-{Guid.NewGuid():N}"[..20], "Inconnu", 1, "Bon")).ToArray();
+ var report = await ImportReportAsync(Export(unmapped), scenario);
+
+ var page = await GetAsync>($"{Route}/{report.Import.Id}/errors?page=2&pageSize=2");
+
+ Assert.Equal((2, 2, 5), (page.Page, page.PageSize, page.TotalCount));
+ Assert.Equal([4, 5], page.Items.Select(e => e.RowNumber));
+ }
+
+ [Fact]
+ public async Task Report_ReturnsNotFound_ForAnUnknownImport()
+ {
+ using var client = Client(SupplyEmail, SupplyObjectId);
+
+ Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync($"{Route}/{Guid.NewGuid()}")).StatusCode);
+ Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync($"{Route}/{Guid.NewGuid()}/errors")).StatusCode);
+ }
+
+ private async Task SeedAsync(params (string Name, decimal Price)[] items)
+ {
+ await using var context = factory.CreateDbContext();
+ var suffix = Guid.NewGuid().ToString("N")[..8];
+ var donor = new Donor { Name = "Boulangerie Saint-Laurent", BusinessCentralCode = $"F-{suffix}" };
+ context.Donors.Add(donor);
+
+ var catalogItems = items.Select(item => new CatalogItem
+ {
+ Name = item.Name,
+ Category = "Fruits et légumes",
+ BusinessCentralCode = $"{item.Name[..3]}-{suffix}-{Guid.NewGuid():N}"[..30],
+ Unit = "KG",
+ QualityClassCode = "A",
+ Prices = [new Price { UnitPrice = item.Price, EffectiveDate = new DateOnly(2026, 11, 1) }],
+ }).ToList();
+ context.CatalogItems.AddRange(catalogItems);
+ foreach (var catalogItem in catalogItems)
+ {
+ context.BcItemMappings.Add(new BcItemMapping
+ {
+ BusinessCentralCode = catalogItem.BusinessCentralCode,
+ CatalogItem = catalogItem,
+ ConfirmedByUserId = _supplyUserId,
+ });
+ }
+
+ await context.SaveChangesAsync();
+ return new Scenario(
+ donor.BusinessCentralCode!,
+ $"COMA-{suffix}",
+ catalogItems.Select(c => c.BusinessCentralCode).ToList(),
+ catalogItems.Select(c => c.Id).ToList());
+ }
+
+ private async Task AddPriceAsync(Guid catalogItemId, decimal unitPrice, DateOnly effectiveDate, bool replace = false)
+ {
+ await using var context = factory.CreateDbContext();
+ if (replace)
+ {
+ await context.Prices.Where(p => p.CatalogItemId == catalogItemId).ExecuteDeleteAsync();
+ }
+
+ context.Prices.Add(new Price { CatalogItemId = catalogItemId, UnitPrice = unitPrice, EffectiveDate = effectiveDate });
+ await context.SaveChangesAsync();
+ }
+
+ private async Task SetUnitAsync(Guid catalogItemId, string unit)
+ {
+ await using var context = factory.CreateDbContext();
+ await context.CatalogItems.Where(c => c.Id == catalogItemId).ExecuteUpdateAsync(c => c.SetProperty(x => x.Unit, unit));
+ }
+
+ private async Task DeactivateAsync(Guid catalogItemId)
+ {
+ await using var context = factory.CreateDbContext();
+ await context.CatalogItems.Where(c => c.Id == catalogItemId).ExecuteUpdateAsync(c => c.SetProperty(x => x.IsActive, false));
+ }
+
+ private async Task DonationCountAsync(string documentNumber)
+ {
+ await using var context = factory.CreateDbContext();
+ return await context.FoodItems.CountAsync(f => f.SourceKey != null && f.SourceKey.StartsWith(documentNumber + "/"));
+ }
+
+ private async Task ImportReportAsync(
+ Stream file, Scenario scenario, bool confirmDuplicate = false, string fileName = "export.xlsx")
+ {
+ var response = await ImportAsync(file, scenario, confirmDuplicate: confirmDuplicate, fileName: fileName);
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!;
+ }
+
+ private Task ImportAsync(
+ Stream file,
+ Scenario scenario,
+ string email = SupplyEmail,
+ string objectId = SupplyObjectId,
+ bool confirmDuplicate = false,
+ string fileName = "export.xlsx")
+ {
+ var client = Client(email, objectId);
+ var form = new MultipartFormDataContent
+ {
+ { File(file), "file", fileName },
+ { new StringContent(scenario.DonorCode), "donorCode" },
+ { new StringContent(scenario.DocumentNumber), "documentNumber" },
+ { new StringContent(DonationDate.ToString("yyyy-MM-dd")), "donationDate" },
+ { new StringContent(confirmDuplicate ? "true" : "false"), "confirmDuplicate" },
+ };
+ return client.PostAsync(Route, form);
+ }
+
+ private async Task GetAsync(string url)
+ {
+ using var client = Client(SupplyEmail, SupplyObjectId);
+ var response = await client.GetAsync(url);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync