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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -483,4 +483,7 @@ $RECYCLE.BIN/

# PRD
PRD*.pdf
PRD*.docx
PRD*.docx

# Real Business Central exports contain personal data (Loi 25): never commit them
data/private/
203 changes: 203 additions & 0 deletions docs/database/donation-imports.md
Original file line number Diff line number Diff line change
@@ -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.
Binary file modified docs/database/images/prices.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/database/images/quality-classes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/database/images/receipts.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/database/images/schema.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading