diff --git a/docs/database/receipt-statuses.md b/docs/database/receipt-statuses.md
index fde12db..c2319ed 100644
--- a/docs/database/receipt-statuses.md
+++ b/docs/database/receipt-statuses.md
@@ -99,6 +99,10 @@ Each action has its own endpoint:
| The receipt does not exist | 404 |
| The employee is not signed in | 401 |
+Issuing a receipt also checks that everything a tax receipt needs is there: the settings of the organization, the full name and address of the donor, at least one food item, and a total that matches its lines. If something is missing, the API answers 422 with one message per problem in `problems`, such as "The donor profile is incomplete: the postal code is missing.", and the receipt stays Approved without a number. When the receipt is issued, the name and address of the donor and the description and date of each food item are frozen on it. See [the tax receipt PDF](../receipts/tax-receipt-pdf.md).
+
+To correct an issued receipt, call `POST /api/receipts/{id}/replace` with `{ "reason": "..." }`. It cancels the receipt and creates its replacement in Draft in one transaction. The replacement goes through approval again and gets a new number when it is issued.
+
## For developers
| Piece | Location | Role |
diff --git a/docs/database/receipts.dbml b/docs/database/receipts.dbml
index 8fce4ec..49c2b07 100644
--- a/docs/database/receipts.dbml
+++ b/docs/database/receipts.dbml
@@ -3,6 +3,7 @@
// Matches the migration 20261107041912_CreateReceipts, with the status added by 20261127052039_AddReceiptStatus
// and the receipt number added by 20261127053347_AddReceiptNumbers.
// donors and food_items come from the migration 20261105163138_CreateDonorsAndFoodItems (donor profile columns from 20261128005314_AddDonorProfile, active flag and search name from 20261128222105_AddDonorListSearch),
+// The frozen issue details, the advantage and the replacement link come from 20261204154702_AddReceiptIssueDetails.
// 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)
@@ -140,12 +141,21 @@ Table receipts {
created_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
status varchar(30) [not null, default: 'Draft', note: 'Where the receipt is in the approval process. See receipt-statuses.md']
receipt_number varchar(10) [null, note: 'Unique number such as DEN_000001, given when the receipt is issued and kept if it is cancelled']
+ advantage_amount numeric(12,2) [not null, default: 0.0, note: 'Value of the advantage the donor received, in dollars. Eligible amount = total_amount - advantage_amount']
+ issued_at timestamptz [null, note: 'Stored in UTC, empty until the receipt is issued']
+ donor_name varchar(255) [null, note: 'Donor name frozen when the receipt is issued']
+ donor_address text [null, note: 'Donor street address frozen when the receipt is issued']
+ donor_city varchar(100) [null, note: 'Donor city frozen when the receipt is issued']
+ donor_province varchar(50) [null, note: 'Donor province frozen when the receipt is issued']
+ donor_postal_code varchar(20) [null, note: 'Donor postal code frozen when the receipt is issued']
+ replaces_receipt_id uuid [null, note: 'Cancelled receipt this one replaces, empty if none']
indexes {
id [pk, name: 'pk_receipts']
(id, donor_id) [unique, name: 'ak_receipts_id_donor_id']
donor_id [name: 'ix_receipts_donor_id']
receipt_number [unique, name: 'ix_receipts_receipt_number']
+ replaces_receipt_id [unique, name: 'ix_receipts_replaces_receipt_id']
}
checks {
@@ -154,6 +164,9 @@ Table receipts {
`receipt_number ~ '^DEN_[0-9]{6}$'` [name: 'ck_receipts_receipt_number_format']
`status <> 'Issued' OR receipt_number IS NOT NULL` [name: 'ck_receipts_issued_has_receipt_number']
`status IN ('Issued', 'Cancelled') OR receipt_number IS NULL` [name: 'ck_receipts_receipt_number_only_once_issued']
+ `advantage_amount >= 0 AND (advantage_amount = 0 OR advantage_amount <= total_amount)` [name: 'ck_receipts_advantage_amount_range']
+ `receipt_number IS NULL OR (issued_at IS NOT NULL AND donor_name IS NOT NULL)` [name: 'ck_receipts_issued_details_frozen']
+ `replaces_receipt_id <> id` [name: 'ck_receipts_replaces_another_receipt']
}
Note: 'Tax receipts given to donors'
@@ -168,6 +181,8 @@ Table receipt_items {
unit_price numeric(12,4) [not null, note: 'Price of one unit when the receipt was made']
quality_percent numeric(5,2) [not null, note: 'A = 100, B = 50 to 75, C = 0']
receipt_cancelled boolean [not null, default: false, note: 'True once the receipt is cancelled. The line is kept, but the food item is free again']
+ description varchar(255) [null, note: 'Food item name frozen when the receipt is issued']
+ donation_date date [null, note: 'Donation date frozen when the receipt is issued']
indexes {
(receipt_id, food_item_id) [pk, name: 'pk_receipt_items']
@@ -272,6 +287,8 @@ Ref fk_catalog_items_quality_classes_quality_class: catalog_items.quality_class
Ref fk_receipts_donors_donor_id: receipts.donor_id > donors.id [delete: restrict]
+Ref fk_receipts_receipts_replaces_receipt_id: receipts.replaces_receipt_id > receipts.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]
diff --git a/docs/database/receipts.md b/docs/database/receipts.md
index 1401991..35461e7 100644
--- a/docs/database/receipts.md
+++ b/docs/database/receipts.md
@@ -26,6 +26,13 @@ One row per tax receipt.
| status | Where the receipt is in the approval process: Draft, PendingSupplyApproval, PendingFinanceApproval, Approved, Issued or Cancelled. A new receipt starts as Draft. |
| receipt_number | Unique number of the receipt, such as DEN_000001. Empty until the receipt is issued, then kept even if the receipt is cancelled. |
+Columns added for the PDF of the receipt (migration [20261204154702_AddReceiptIssueDetails](../../src/MoissonMontreal.Api/Data/Migrations/20261204154702_AddReceiptIssueDetails.cs)):
+
+- advantage_amount: value of the advantage the donor received in return for the gift, in dollars. 0 for a plain food donation. The eligible amount printed on the receipt is total_amount minus advantage_amount.
+- issued_at: date and time the receipt was issued, stored in UTC. Empty until then. Its date in Montreal time is the date of issue printed on the receipt.
+- donor_name, donor_address, donor_city, donor_province, donor_postal_code: name and address of the donor, copied from the donor profile when the receipt is issued. The PDF of an issued receipt uses these columns, never the donor profile, so a later change to the donor does not change a receipt already given.
+- replaces_receipt_id: the cancelled receipt this one replaces, or empty. A receipt can be replaced only once.
+
### receipt_items
One row per food item on a receipt.
@@ -41,6 +48,11 @@ One row per food item on a receipt.
| quality_percent | Share of the price kept for the item's quality grade: 100 for grade A, between 50 and 75 for grade B, 0 for grade C |
| receipt_cancelled | Yes once the receipt is cancelled. The line is kept as a record of the cancelled receipt, but the food item can then go on a new receipt. |
+Columns added for the PDF of the receipt:
+
+- description: name of the food item, copied when the receipt is issued and printed as the description of the line.
+- donation_date: day the food was received, copied when the receipt is issued and printed on the line.
+
### receipt_status_changes
One row every time the status of a receipt changes. Rows are only added, so the history of a receipt is never rewritten.
@@ -141,6 +153,10 @@ created_at is a precise moment, stored and read back in UTC. Convert it to Ameri
15. Two receipts cannot have the same number.
16. An issued receipt must have a number, and a receipt that was never issued (Draft, waiting for approval or Approved) cannot have one. A receipt cancelled after it was issued keeps its number.
17. A receipt number is DEN_ followed by 6 digits.
+18. The advantage cannot be negative, and cannot be larger than the total.
+19. A receipt with a number must have its date of issue and the donor name frozen on it.
+20. A receipt cannot replace itself, and two receipts cannot replace the same receipt.
+21. Once a receipt has a number, the database refuses any change to it: only its status can go from Issued to Cancelled, and receipt_cancelled can only be turned on for its lines. It cannot be deleted, and no line can be added to it, removed from it, or moved to or from it. Two triggers enforce this: tr_receipts_issued_read_only and tr_receipt_items_issued_read_only. To correct an issued receipt, cancel it and issue a replacement (see [the tax receipt PDF](../receipts/tax-receipt-pdf.md)).
Because donor_id is part of both links, the app cannot change the donor of a receipt or of a food item once it is saved.
@@ -158,6 +174,8 @@ A cancelled receipt keeps its lines, so the original stays readable. Cancelling
| Receipt number migration | [20261127053347_AddReceiptNumbers](../../src/MoissonMontreal.Api/Data/Migrations/20261127053347_AddReceiptNumbers.cs), with [0010_add_receipt_numbers.sql](sql/0010_add_receipt_numbers.sql) and [ReceiptNumberCounterConfiguration.cs](../../src/MoissonMontreal.Api/Data/Configurations/ReceiptNumberCounterConfiguration.cs) |
| Status and history migration | [20261127052039_AddReceiptStatus](../../src/MoissonMontreal.Api/Data/Migrations/20261127052039_AddReceiptStatus.cs), with [0009_add_receipt_status.sql](sql/0009_add_receipt_status.sql) and [ReceiptStatusChangeConfiguration.cs](../../src/MoissonMontreal.Api/Data/Configurations/ReceiptStatusChangeConfiguration.cs) |
+The PDF details migration is [20261204154702_AddReceiptIssueDetails](../../src/MoissonMontreal.Api/Data/Migrations/20261204154702_AddReceiptIssueDetails.cs), with [0015_add_receipt_issue_details.sql](sql/0015_add_receipt_issue_details.sql). It freezes the receipts already issued with the donor and the food items as they are when it runs, and the date of their first issue (or their creation date when their history has none).
+
The SQL script is generated from the migration with `dotnet ef migrations script CreateDonorsAndFoodItems CreateReceipts --project src/MoissonMontreal.Api --output docs/database/sql/0003_create_receipts.sql`. It must be run after [0001_create_users_and_roles.sql](sql/0001_create_users_and_roles.sql) and [0002_create_donors_and_food_items.sql](sql/0002_create_donors_and_food_items.sql). It records itself in the migration history, so Entity Framework will not apply it a second time.
The generated file starts with a UTF-8 byte order mark (BOM). Remove it before committing, for example with `sed -i '1s/^\xEF\xBB\xBF//' docs/database/sql/0003_create_receipts.sql`.
diff --git a/docs/database/schema.dbml b/docs/database/schema.dbml
index 64369ad..89d6356 100644
--- a/docs/database/schema.dbml
+++ b/docs/database/schema.dbml
@@ -241,12 +241,21 @@ Table receipts {
created_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
status varchar(30) [not null, default: 'Draft', note: 'Where the receipt is in the approval process. See receipt-statuses.md']
receipt_number varchar(10) [null, note: 'Unique number such as DEN_000001, given when the receipt is issued and kept if it is cancelled']
+ advantage_amount numeric(12,2) [not null, default: 0.0, note: 'Value of the advantage the donor received, in dollars. Eligible amount = total_amount - advantage_amount']
+ issued_at timestamptz [null, note: 'Stored in UTC, empty until the receipt is issued']
+ donor_name varchar(255) [null, note: 'Donor name frozen when the receipt is issued']
+ donor_address text [null, note: 'Donor street address frozen when the receipt is issued']
+ donor_city varchar(100) [null, note: 'Donor city frozen when the receipt is issued']
+ donor_province varchar(50) [null, note: 'Donor province frozen when the receipt is issued']
+ donor_postal_code varchar(20) [null, note: 'Donor postal code frozen when the receipt is issued']
+ replaces_receipt_id uuid [null, note: 'Cancelled receipt this one replaces, empty if none']
indexes {
id [pk, name: 'pk_receipts']
(id, donor_id) [unique, name: 'ak_receipts_id_donor_id', note: 'Lets receipt_items check the donor']
donor_id [name: 'ix_receipts_donor_id']
receipt_number [unique, name: 'ix_receipts_receipt_number']
+ replaces_receipt_id [unique, name: 'ix_receipts_replaces_receipt_id']
}
checks {
@@ -255,6 +264,9 @@ Table receipts {
`receipt_number ~ '^DEN_[0-9]{6}$'` [name: 'ck_receipts_receipt_number_format']
`status <> 'Issued' OR receipt_number IS NOT NULL` [name: 'ck_receipts_issued_has_receipt_number']
`status IN ('Issued', 'Cancelled') OR receipt_number IS NULL` [name: 'ck_receipts_receipt_number_only_once_issued']
+ `advantage_amount >= 0 AND (advantage_amount = 0 OR advantage_amount <= total_amount)` [name: 'ck_receipts_advantage_amount_range']
+ `receipt_number IS NULL OR (issued_at IS NOT NULL AND donor_name IS NOT NULL)` [name: 'ck_receipts_issued_details_frozen']
+ `replaces_receipt_id <> id` [name: 'ck_receipts_replaces_another_receipt']
}
Note: 'Tax receipts given to donors'
@@ -310,6 +322,8 @@ Table receipt_items {
unit_price numeric(12,4) [not null, note: 'Price of one unit when the receipt was made']
quality_percent numeric(5,2) [not null, note: 'A = 100, B = 50 to 75, C = 0']
receipt_cancelled boolean [not null, default: false, note: 'True once the receipt is cancelled. The line is kept, but the food item is free again']
+ description varchar(255) [null, note: 'Food item name frozen when the receipt is issued']
+ donation_date date [null, note: 'Donation date frozen when the receipt is issued']
indexes {
(receipt_id, food_item_id) [pk, name: 'pk_receipt_items']
@@ -441,6 +455,8 @@ Ref fk_food_items_quality_classes_quality: food_items.quality > quality_classes.
Ref fk_receipts_donors_donor_id: receipts.donor_id > donors.id [delete: restrict]
+Ref fk_receipts_receipts_replaces_receipt_id: receipts.replaces_receipt_id > receipts.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]
diff --git a/docs/database/sql/0015_add_receipt_issue_details.sql b/docs/database/sql/0015_add_receipt_issue_details.sql
new file mode 100644
index 0000000..78541c9
--- /dev/null
+++ b/docs/database/sql/0015_add_receipt_issue_details.sql
@@ -0,0 +1,107 @@
+START TRANSACTION;
+ALTER TABLE receipts ADD advantage_amount numeric(12,2) NOT NULL DEFAULT 0.0;
+
+ALTER TABLE receipts ADD donor_address text;
+
+ALTER TABLE receipts ADD donor_city character varying(100);
+
+ALTER TABLE receipts ADD donor_name character varying(255);
+
+ALTER TABLE receipts ADD donor_postal_code character varying(20);
+
+ALTER TABLE receipts ADD donor_province character varying(50);
+
+ALTER TABLE receipts ADD issued_at timestamp with time zone;
+
+ALTER TABLE receipts ADD replaces_receipt_id uuid;
+
+ALTER TABLE receipt_items ADD description character varying(255);
+
+ALTER TABLE receipt_items ADD donation_date date;
+
+UPDATE receipts AS r
+SET issued_at = coalesce(
+ (SELECT min(c.changed_at) FROM receipt_status_changes AS c WHERE c.receipt_id = r.id AND c.to_status = 'Issued'),
+ r.created_at),
+ donor_name = d.name,
+ donor_address = d.address,
+ donor_city = d.city,
+ donor_province = d.province,
+ donor_postal_code = d.postal_code
+FROM donors AS d
+WHERE d.id = r.donor_id AND r.receipt_number IS NOT NULL;
+
+UPDATE receipt_items AS i
+SET description = f.name,
+ donation_date = f.donation_date
+FROM food_items AS f, receipts AS r
+WHERE f.id = i.food_item_id AND r.id = i.receipt_id AND r.receipt_number IS NOT NULL;
+
+CREATE UNIQUE INDEX ix_receipts_replaces_receipt_id ON receipts (replaces_receipt_id);
+
+ALTER TABLE receipts ADD CONSTRAINT ck_receipts_advantage_amount_range CHECK (advantage_amount >= 0 AND (advantage_amount = 0 OR advantage_amount <= total_amount));
+
+ALTER TABLE receipts ADD CONSTRAINT ck_receipts_issued_details_frozen CHECK (receipt_number IS NULL OR (issued_at IS NOT NULL AND donor_name IS NOT NULL));
+
+ALTER TABLE receipts ADD CONSTRAINT ck_receipts_replaces_another_receipt CHECK (replaces_receipt_id <> id);
+
+ALTER TABLE receipts ADD CONSTRAINT fk_receipts_receipts_replaces_receipt_id FOREIGN KEY (replaces_receipt_id) REFERENCES receipts (id) ON DELETE RESTRICT;
+
+CREATE FUNCTION refuse_change_to_issued_receipt() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF OLD.receipt_number IS NULL THEN
+ RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
+ END IF;
+
+ IF TG_OP = 'UPDATE'
+ AND (to_jsonb(NEW) - 'status') = (to_jsonb(OLD) - 'status')
+ AND (NEW.status = OLD.status OR (OLD.status = 'Issued' AND NEW.status = 'Cancelled')) THEN
+ RETURN NEW;
+ END IF;
+
+ RAISE EXCEPTION 'Receipt % is issued and cannot be changed. Cancel it and issue a replacement instead.', OLD.receipt_number
+ USING ERRCODE = 'integrity_constraint_violation', CONSTRAINT = 'tr_receipts_issued_read_only';
+END;
+$$;
+
+CREATE TRIGGER tr_receipts_issued_read_only
+BEFORE UPDATE OR DELETE ON receipts
+FOR EACH ROW EXECUTE FUNCTION refuse_change_to_issued_receipt();
+
+CREATE FUNCTION refuse_change_to_issued_receipt_item() RETURNS trigger LANGUAGE plpgsql AS $$
+DECLARE
+ old_number text;
+ new_number text;
+BEGIN
+ IF TG_OP <> 'INSERT' THEN
+ SELECT receipt_number INTO old_number FROM receipts WHERE id = OLD.receipt_id;
+ END IF;
+
+ IF TG_OP <> 'DELETE' THEN
+ SELECT receipt_number INTO new_number FROM receipts WHERE id = NEW.receipt_id;
+ END IF;
+
+ IF old_number IS NULL AND new_number IS NULL THEN
+ RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
+ END IF;
+
+ IF TG_OP = 'UPDATE'
+ AND (to_jsonb(NEW) - 'receipt_cancelled') = (to_jsonb(OLD) - 'receipt_cancelled')
+ AND (NEW.receipt_cancelled OR NOT OLD.receipt_cancelled) THEN
+ RETURN NEW;
+ END IF;
+
+ RAISE EXCEPTION 'Receipt % is issued and its food items cannot be changed. Cancel it and issue a replacement instead.', coalesce(old_number, new_number)
+ USING ERRCODE = 'integrity_constraint_violation', CONSTRAINT = 'tr_receipt_items_issued_read_only';
+END;
+$$;
+
+CREATE TRIGGER tr_receipt_items_issued_read_only
+BEFORE INSERT OR UPDATE OR DELETE ON receipt_items
+FOR EACH ROW EXECUTE FUNCTION refuse_change_to_issued_receipt_item();
+
+INSERT INTO "__EFMigrationsHistory" (migration_id, product_version)
+VALUES ('20261204154702_AddReceiptIssueDetails', '10.0.13');
+
+COMMIT;
+
diff --git a/docs/receipts/tax-receipt-pdf.md b/docs/receipts/tax-receipt-pdf.md
new file mode 100644
index 0000000..c73de76
--- /dev/null
+++ b/docs/receipts/tax-receipt-pdf.md
@@ -0,0 +1,91 @@
+# Tax receipt PDF
+
+The end product of the app is the official receipt given to a donor for a gift of food. It has tax value, so this page lists what is printed on it, where each value comes from, and what is still to confirm with Moisson Montréal.
+
+This page is not legal or tax advice. The list of mentions below comes from general knowledge of the Canada Revenue Agency (CRA) requirements and must be checked against the CRA documentation and the Quebec requirements before receipts are issued for real.
+
+## Endpoints
+
+- `GET /api/receipts/{id}/pdf` returns the PDF. It needs the permission to prepare, issue and generate receipts.
+ - An issued receipt is printed from what was frozen on it when it was issued. The file is named after its number, such as DEN_000001.pdf.
+ - A cancelled receipt that had been issued is printed with its number and a "REÇU ANNULÉ / CANCELLED RECEIPT" banner, for the records.
+ - A receipt not issued yet is printed as a preview from the current donor profile and food items, with no number and an "APERÇU / PREVIEW" banner, so it can be checked before it is issued.
+ - If a value required on the receipt is missing, the API answers 422 with one message per problem in `problems`, and no PDF is made.
+- `POST /api/receipts/{id}/issue` issues the receipt (see [receipt statuses](../database/receipt-statuses.md)). It refuses with 422 when a value is missing, and the receipt keeps its status and gets no number.
+- `POST /api/receipts/{id}/replace` with `{ "reason": "..." }` cancels an issued receipt and creates its replacement (see below).
+
+## What is printed
+
+The receipt is in French, with the English translation of each mention under it or next to it.
+
+Mentions to validate with Moisson Montréal and the CRA documentation:
+
+- The statement "Reçu officiel aux fins de l'impôt sur le revenu / Official receipt for income tax purposes".
+- The name and address of the organization, as on file with the CRA.
+- The charity registration number.
+- The serial number of the receipt, such as DEN_000001, given by [receipt numbering](../database/receipt-statuses.md#receipt-numbers).
+- The place of issue.
+- The date the gift was received. When the food was given on several days, the first and last days are printed, and each line shows its own date.
+- The date the receipt was issued.
+- The full name and address of the donor.
+- A description of the food received, one line per food item, with its quantity, unit price, quality percentage and fair market value.
+- The fair market value of the property received, the amount of the advantage (0,00 $ for a plain food donation) and the eligible amount of the gift.
+- The name and address of the appraiser, printed only when one is set.
+- The signature of an authorized person, with their name and title.
+- The name of the Canada Revenue Agency and the address of its website, canada.ca/charities-giving.
+- On a replacement receipt: "Ce reçu annule et remplace le reçu n° ... / This receipt cancels and replaces receipt No. ...".
+
+Each of these mentions is checked in the text extracted from the PDF by `ReceiptPdfRendererTests`. The wording is copied in the test on purpose, so a mention removed by mistake makes it fail.
+
+Amounts are printed in the Quebec format, such as 1 234,56 $, and dates as 2026-11-30.
+
+## Where the values come from
+
+- The organization: the `ReceiptIssuer` section of the API settings (legal name, address, city, province, postal code, registration number, place of issue, name and title of the signatory, appraiser, CRA website). The values in `appsettings.json` are empty on purpose: until they are filled with the real values of Moisson Montréal, every receipt is refused with a message naming the setting to fill, such as "Set ReceiptIssuer:RegistrationNumber in the API settings."
+- The donor: the [donor profile](../database/donors.md), copied onto the receipt when it is issued.
+- The food items and their value: the lines of the receipt, valued from the import with the price grid and the quality percentage (see [how the value is calculated](../database/receipts.md#how-the-value-is-calculated)). The description and the donation date of each food item are copied onto its line when the receipt is issued.
+
+## Refusals
+
+A receipt is not issued, and its PDF is not made, when:
+
+- A setting of the organization is empty.
+- The donor has no name, street address, city, province or postal code. The message names each missing part and asks to complete the donor profile.
+- The receipt has no food item, or a food item has no description or date.
+- The total of the receipt does not match the sum of its lines.
+- The advantage is negative or larger than the total.
+
+## Issued receipts never change
+
+When a receipt is issued, the name and address of the donor are copied onto it, and the description and date of each food item are copied onto its lines, in the same transaction as its number. The PDF of an issued receipt only uses these copies, so changing the donor profile or a food item afterwards does not change it.
+
+The database refuses any change to a receipt that has a number, apart from its cancellation (see rule 21 in [receipts.md](../database/receipts.md#rules-enforced-by-the-database)). There is no endpoint to edit a receipt.
+
+## Cancellation and replacement
+
+A mistake on an issued receipt is never corrected on the receipt itself. `POST /api/receipts/{id}/replace` does, in one transaction:
+
+1. Cancels the issued receipt, with the reason given. It keeps its number, which is never given again, and its PDF stays available with a cancelled banner.
+2. Creates a new receipt in Draft for the same donor, with a copy of the food items and their values, that refers to the cancelled receipt (replaces_receipt_id).
+
+The replacement is corrected if needed, then goes through approval and is issued with a new number like any receipt. Its PDF states which receipt it cancels and replaces. A receipt can be replaced only once. The exact behavior (for example whether the replacement keeps the original number or date) is to be confirmed with Moisson Montréal.
+
+## Still to confirm with Moisson Montréal
+
+- The receipt template: the layout follows a generic receipt until the client template is compared with it. The PDF must visually match the template provided by the client.
+- The list of mentions above, against the CRA documentation, and whether Revenu Québec requires anything more.
+- The real values of the `ReceiptIssuer` settings, including the exact legal name as on file with the CRA.
+- The signature: the receipt has a signature line with the name of the signatory. Whether a scanned signature should be printed, and who may sign, is to be decided.
+- Whether the description should be the name of the food item, the name of the catalog item, or both.
+- The cancellation and replacement process, and whether Finance should also be able to download the PDF.
+- The settings of the organization are read when the PDF is made. If the address of the organization changes, a receipt issued before would be reprinted with the new address. Freezing them on the receipt as well is to be decided.
+
+## For developers
+
+- `ReceiptPdfRenderer` (`src/MoissonMontreal.Api/Receipts/`) draws the PDF with QuestPDF on letter paper. The font is Lato, shipped with QuestPDF and embedded in the PDF, so accents print the same on every computer and the server needs no installed font. The table of food items continues on the next pages with its header repeated, and long names and descriptions wrap.
+- `ReceiptMentions` holds the wording of each mention.
+- `ReceiptDocumentService` builds the content of the receipt from the database: the frozen copy for an issued receipt, the current data for a preview.
+- `ReceiptIssueCheck` (`src/MoissonMontreal.Core/Receipts/`) lists the problems that prevent a receipt from being issued.
+- `ReceiptStatusService` freezes the donor and the lines when a receipt is issued, and cancels and replaces a receipt.
+- QuestPDF is free under its Community license for charitable organizations, which Moisson Montréal is. This is to be confirmed by Moisson Montréal, since the license would otherwise be paid.
+- Tests: `ReceiptPdfRendererTests` (mentions, accents, letter paper, embedded fonts, long text and pagination), `ReceiptIssueCheckTests` (refusals), `ReceiptDocumentEndpointTests` (from a real calculation to the PDF, freezing, replacement, and the database refusing changes), `ReceiptIssueDetailsMigrationTests` (receipts issued before the migration).
diff --git a/src/MoissonMontreal.Api/Controllers/ReceiptDocumentsController.cs b/src/MoissonMontreal.Api/Controllers/ReceiptDocumentsController.cs
new file mode 100644
index 0000000..52c3a0e
--- /dev/null
+++ b/src/MoissonMontreal.Api/Controllers/ReceiptDocumentsController.cs
@@ -0,0 +1,77 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using MoissonMontreal.Api.Receipts;
+using MoissonMontreal.Core.Authorization;
+using MoissonMontreal.Core.Dtos;
+using MoissonMontreal.Core.Receipts;
+
+namespace MoissonMontreal.Api.Controllers;
+
+///
+/// The tax receipt as a document: its PDF, and the cancellation and replacement of an issued receipt.
+///
+[ApiController]
+[Route("api/receipts/{receiptId:guid}")]
+public class ReceiptDocumentsController(ReceiptDocumentService documents, ReceiptStatusService statuses) : ControllerBase
+{
+ ///
+ /// Returns the PDF of the receipt. An issued receipt is printed from what was frozen when it was issued, a cancelled one
+ /// with a cancelled banner, and a receipt not issued yet as a preview without a number.
+ ///
+ [HttpGet("pdf")]
+ [Authorize(Policy = Permissions.ManageReceipts)]
+ [Produces("application/pdf")]
+ public async Task Pdf(Guid receiptId, CancellationToken cancellationToken)
+ {
+ try
+ {
+ var (number, pdf) = await documents.RenderAsync(receiptId, cancellationToken);
+ return File(pdf, "application/pdf", number is null ? $"apercu-{receiptId}.pdf" : $"{number}.pdf");
+ }
+ catch (ReceiptNotFoundException e)
+ {
+ return NotFound(CreateProblem(StatusCodes.Status404NotFound, "Receipt not found", e.Message));
+ }
+ catch (ReceiptDataMissingException e)
+ {
+ return UnprocessableEntity(ReceiptProblems.DataMissing(ProblemDetailsFactory, HttpContext, e));
+ }
+ }
+
+ ///
+ /// Cancels an issued receipt and creates its replacement in Draft, which refers to the cancelled receipt.
+ ///
+ [HttpPost("replace")]
+ [Authorize(Policy = Permissions.ManageReceipts)]
+ public async Task> Replace(
+ Guid receiptId, ReceiptReasonRequest request, CancellationToken cancellationToken)
+ {
+ try
+ {
+ var (cancellation, replacement) = await statuses.ReplaceAsync(receiptId, request.Reason, User, cancellationToken);
+ return Created(
+ $"/api/receipts/{replacement.Id}/pdf",
+ new ReceiptReplacementDto(receiptId, cancellation.ReceiptNumber, replacement.Id));
+ }
+ catch (ReceiptNotFoundException e)
+ {
+ return NotFound(CreateProblem(StatusCodes.Status404NotFound, "Receipt not found", e.Message));
+ }
+ catch (ReceiptNotReplaceableException e)
+ {
+ var problem = CreateProblem(StatusCodes.Status409Conflict, "Receipt cannot be replaced", e.Message);
+ problem.Extensions["currentStatus"] = e.Status;
+ return Conflict(problem);
+ }
+ catch (InvalidReceiptReasonException e)
+ {
+ return ValidationProblem(new ValidationProblemDetails(new Dictionary
+ {
+ [nameof(ReceiptReasonRequest.Reason)] = [e.Message],
+ }));
+ }
+ }
+
+ private ProblemDetails CreateProblem(int status, string title, string detail) =>
+ ProblemDetailsFactory.CreateProblemDetails(HttpContext, status, title: title, detail: detail);
+}
diff --git a/src/MoissonMontreal.Api/Controllers/ReceiptStatusController.cs b/src/MoissonMontreal.Api/Controllers/ReceiptStatusController.cs
index a6db045..bdd0cf2 100644
--- a/src/MoissonMontreal.Api/Controllers/ReceiptStatusController.cs
+++ b/src/MoissonMontreal.Api/Controllers/ReceiptStatusController.cs
@@ -80,6 +80,10 @@ private async Task> ApplyAsync(
{
return StatusCode(StatusCodes.Status403Forbidden, CreateProblem(StatusCodes.Status403Forbidden, "Cannot approve your own receipt", e.Message));
}
+ catch (ReceiptDataMissingException e)
+ {
+ return UnprocessableEntity(ReceiptProblems.DataMissing(ProblemDetailsFactory, HttpContext, e));
+ }
}
private ProblemDetails CreateProblem(int status, string title, string detail) =>
diff --git a/src/MoissonMontreal.Api/Data/Configurations/ReceiptConfiguration.cs b/src/MoissonMontreal.Api/Data/Configurations/ReceiptConfiguration.cs
index 5dd35f5..276953d 100644
--- a/src/MoissonMontreal.Api/Data/Configurations/ReceiptConfiguration.cs
+++ b/src/MoissonMontreal.Api/Data/Configurations/ReceiptConfiguration.cs
@@ -12,6 +12,8 @@ public class ReceiptConfiguration : IEntityTypeConfiguration
{
public const string ReceiptNumberIndex = "ix_receipts_receipt_number";
+ public const string ReplacesReceiptIdIndex = "ix_receipts_replaces_receipt_id";
+
///
/// Configures the columns, constraint and donor relationship of the receipts table.
///
@@ -31,6 +33,13 @@ public void Configure(EntityTypeBuilder builder)
t.HasCheckConstraint(
"ck_receipts_receipt_number_only_once_issued",
$"status IN ('{nameof(ReceiptStatus.Issued)}', '{nameof(ReceiptStatus.Cancelled)}') OR receipt_number IS NULL");
+ t.HasCheckConstraint(
+ "ck_receipts_advantage_amount_range",
+ "advantage_amount >= 0 AND (advantage_amount = 0 OR advantage_amount <= total_amount)");
+ t.HasCheckConstraint(
+ "ck_receipts_issued_details_frozen",
+ "receipt_number IS NULL OR (issued_at IS NOT NULL AND donor_name IS NOT NULL)");
+ t.HasCheckConstraint("ck_receipts_replaces_another_receipt", "replaces_receipt_id <> id");
});
builder.Property(r => r.Id).HasDefaultValueSql("gen_random_uuid()");
@@ -52,6 +61,25 @@ public void Configure(EntityTypeBuilder builder)
.IsUnique()
.HasDatabaseName(ReceiptNumberIndex);
+ builder.Property(r => r.AdvantageAmount).HasPrecision(12, 2).HasDefaultValue(0m);
+
+ builder.Property(r => r.DonorName).HasMaxLength(Donor.NameMaxLength);
+
+ builder.Property(r => r.DonorCity).HasMaxLength(Donor.CityMaxLength);
+
+ builder.Property(r => r.DonorProvince).HasMaxLength(Donor.ProvinceMaxLength);
+
+ builder.Property(r => r.DonorPostalCode).HasMaxLength(Donor.PostalCodeMaxLength);
+
+ builder.HasIndex(r => r.ReplacesReceiptId)
+ .IsUnique()
+ .HasDatabaseName(ReplacesReceiptIdIndex);
+
+ builder.HasOne(r => r.ReplacesReceipt)
+ .WithOne()
+ .HasForeignKey(r => r.ReplacesReceiptId)
+ .OnDelete(DeleteBehavior.Restrict);
+
builder.HasOne(r => r.Donor)
.WithMany()
.HasForeignKey(r => r.DonorId)
diff --git a/src/MoissonMontreal.Api/Data/Configurations/ReceiptItemConfiguration.cs b/src/MoissonMontreal.Api/Data/Configurations/ReceiptItemConfiguration.cs
index af70ce6..c27c714 100644
--- a/src/MoissonMontreal.Api/Data/Configurations/ReceiptItemConfiguration.cs
+++ b/src/MoissonMontreal.Api/Data/Configurations/ReceiptItemConfiguration.cs
@@ -40,6 +40,8 @@ public void Configure(EntityTypeBuilder builder)
builder.Property(i => i.QualityPercent).HasPrecision(5, 2);
+ builder.Property(i => i.Description).HasMaxLength(255);
+
builder.HasOne(i => i.Receipt)
.WithMany(r => r.Items)
.HasForeignKey(i => new { i.ReceiptId, i.DonorId })
diff --git a/src/MoissonMontreal.Api/Data/Migrations/20261204154702_AddReceiptIssueDetails.Designer.cs b/src/MoissonMontreal.Api/Data/Migrations/20261204154702_AddReceiptIssueDetails.Designer.cs
new file mode 100644
index 0000000..0b0e34b
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Migrations/20261204154702_AddReceiptIssueDetails.Designer.cs
@@ -0,0 +1,1455 @@
+//
+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("20261204154702_AddReceiptIssueDetails")]
+ partial class AddReceiptIssueDetails
+ {
+ ///
+ 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("AdvantageAmount")
+ .ValueGeneratedOnAdd()
+ .HasPrecision(12, 2)
+ .HasColumnType("numeric(12,2)")
+ .HasDefaultValue(0m)
+ .HasColumnName("advantage_amount");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("DonorAddress")
+ .HasColumnType("text")
+ .HasColumnName("donor_address");
+
+ b.Property("DonorCity")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)")
+ .HasColumnName("donor_city");
+
+ b.Property("DonorId")
+ .HasColumnType("uuid")
+ .HasColumnName("donor_id");
+
+ b.Property("DonorName")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("donor_name");
+
+ b.Property("DonorPostalCode")
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasColumnName("donor_postal_code");
+
+ b.Property("DonorProvince")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("donor_province");
+
+ b.Property("IssuedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("issued_at");
+
+ 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("ReplacesReceiptId")
+ .HasColumnType("uuid")
+ .HasColumnName("replaces_receipt_id");
+
+ 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.HasIndex("ReplacesReceiptId")
+ .IsUnique()
+ .HasDatabaseName("ix_receipts_replaces_receipt_id");
+
+ b.ToTable("receipts", null, t =>
+ {
+ t.HasCheckConstraint("ck_receipts_advantage_amount_range", "advantage_amount >= 0 AND (advantage_amount = 0 OR advantage_amount <= total_amount)");
+
+ t.HasCheckConstraint("ck_receipts_issued_details_frozen", "receipt_number IS NULL OR (issued_at IS NOT NULL AND donor_name IS NOT NULL)");
+
+ 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_replaces_another_receipt", "replaces_receipt_id <> id");
+
+ 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("Description")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("description");
+
+ b.Property("DonationDate")
+ .HasColumnType("date")
+ .HasColumnName("donation_date");
+
+ 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.HasOne("MoissonMontreal.Core.Entities.Receipt", "ReplacesReceipt")
+ .WithOne()
+ .HasForeignKey("MoissonMontreal.Core.Entities.Receipt", "ReplacesReceiptId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_receipts_receipts_replaces_receipt_id");
+
+ b.Navigation("Donor");
+
+ b.Navigation("ReplacesReceipt");
+ });
+
+ 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/20261204154702_AddReceiptIssueDetails.cs b/src/MoissonMontreal.Api/Data/Migrations/20261204154702_AddReceiptIssueDetails.cs
new file mode 100644
index 0000000..b5dd966
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Migrations/20261204154702_AddReceiptIssueDetails.cs
@@ -0,0 +1,275 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace MoissonMontreal.Api.Data.Migrations
+{
+ ///
+ public partial class AddReceiptIssueDetails : Migration
+ {
+ ///
+ /// Adds what is frozen on a receipt when it is issued, the advantage and the link to the receipt it replaces.
+ /// Written by hand, keep them if this migration is regenerated:
+ /// the receipts issued before this migration get the donor and the food items as they are now, and the date of their
+ /// first issue (or their creation date when their history has none), and two triggers refuse any change to an issued
+ /// receipt other than its cancellation.
+ ///
+ /// Builder used to describe the operations.
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "advantage_amount",
+ table: "receipts",
+ type: "numeric(12,2)",
+ precision: 12,
+ scale: 2,
+ nullable: false,
+ defaultValue: 0m);
+
+ migrationBuilder.AddColumn(
+ name: "donor_address",
+ table: "receipts",
+ type: "text",
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "donor_city",
+ table: "receipts",
+ type: "character varying(100)",
+ maxLength: 100,
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "donor_name",
+ table: "receipts",
+ type: "character varying(255)",
+ maxLength: 255,
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "donor_postal_code",
+ table: "receipts",
+ type: "character varying(20)",
+ maxLength: 20,
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "donor_province",
+ table: "receipts",
+ type: "character varying(50)",
+ maxLength: 50,
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "issued_at",
+ table: "receipts",
+ type: "timestamp with time zone",
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "replaces_receipt_id",
+ table: "receipts",
+ type: "uuid",
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "description",
+ table: "receipt_items",
+ type: "character varying(255)",
+ maxLength: 255,
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "donation_date",
+ table: "receipt_items",
+ type: "date",
+ nullable: true);
+
+ migrationBuilder.Sql("""
+ UPDATE receipts AS r
+ SET issued_at = coalesce(
+ (SELECT min(c.changed_at) FROM receipt_status_changes AS c WHERE c.receipt_id = r.id AND c.to_status = 'Issued'),
+ r.created_at),
+ donor_name = d.name,
+ donor_address = d.address,
+ donor_city = d.city,
+ donor_province = d.province,
+ donor_postal_code = d.postal_code
+ FROM donors AS d
+ WHERE d.id = r.donor_id AND r.receipt_number IS NOT NULL;
+ """);
+
+ migrationBuilder.Sql("""
+ UPDATE receipt_items AS i
+ SET description = f.name,
+ donation_date = f.donation_date
+ FROM food_items AS f, receipts AS r
+ WHERE f.id = i.food_item_id AND r.id = i.receipt_id AND r.receipt_number IS NOT NULL;
+ """);
+
+ migrationBuilder.CreateIndex(
+ name: "ix_receipts_replaces_receipt_id",
+ table: "receipts",
+ column: "replaces_receipt_id",
+ unique: true);
+
+ migrationBuilder.AddCheckConstraint(
+ name: "ck_receipts_advantage_amount_range",
+ table: "receipts",
+ sql: "advantage_amount >= 0 AND (advantage_amount = 0 OR advantage_amount <= total_amount)");
+
+ migrationBuilder.AddCheckConstraint(
+ name: "ck_receipts_issued_details_frozen",
+ table: "receipts",
+ sql: "receipt_number IS NULL OR (issued_at IS NOT NULL AND donor_name IS NOT NULL)");
+
+ migrationBuilder.AddCheckConstraint(
+ name: "ck_receipts_replaces_another_receipt",
+ table: "receipts",
+ sql: "replaces_receipt_id <> id");
+
+ migrationBuilder.AddForeignKey(
+ name: "fk_receipts_receipts_replaces_receipt_id",
+ table: "receipts",
+ column: "replaces_receipt_id",
+ principalTable: "receipts",
+ principalColumn: "id",
+ onDelete: ReferentialAction.Restrict);
+
+ migrationBuilder.Sql(ReadOnlyTriggers);
+ }
+
+ ///
+ /// Once a receipt has a number, it is never changed again: only its status can go from Issued to Cancelled, and the
+ /// receipt_cancelled flag of its lines can only be turned on. It cannot be deleted, and no line can be added, removed,
+ /// or moved to or from it.
+ /// to_jsonb compares every column, so a column added later is protected too.
+ ///
+ private const string ReadOnlyTriggers = """
+ CREATE FUNCTION refuse_change_to_issued_receipt() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN
+ IF OLD.receipt_number IS NULL THEN
+ RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
+ END IF;
+
+ IF TG_OP = 'UPDATE'
+ AND (to_jsonb(NEW) - 'status') = (to_jsonb(OLD) - 'status')
+ AND (NEW.status = OLD.status OR (OLD.status = 'Issued' AND NEW.status = 'Cancelled')) THEN
+ RETURN NEW;
+ END IF;
+
+ RAISE EXCEPTION 'Receipt % is issued and cannot be changed. Cancel it and issue a replacement instead.', OLD.receipt_number
+ USING ERRCODE = 'integrity_constraint_violation', CONSTRAINT = 'tr_receipts_issued_read_only';
+ END;
+ $$;
+
+ CREATE TRIGGER tr_receipts_issued_read_only
+ BEFORE UPDATE OR DELETE ON receipts
+ FOR EACH ROW EXECUTE FUNCTION refuse_change_to_issued_receipt();
+
+ CREATE FUNCTION refuse_change_to_issued_receipt_item() RETURNS trigger LANGUAGE plpgsql AS $$
+ DECLARE
+ old_number text;
+ new_number text;
+ BEGIN
+ IF TG_OP <> 'INSERT' THEN
+ SELECT receipt_number INTO old_number FROM receipts WHERE id = OLD.receipt_id;
+ END IF;
+
+ IF TG_OP <> 'DELETE' THEN
+ SELECT receipt_number INTO new_number FROM receipts WHERE id = NEW.receipt_id;
+ END IF;
+
+ IF old_number IS NULL AND new_number IS NULL THEN
+ RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
+ END IF;
+
+ IF TG_OP = 'UPDATE'
+ AND (to_jsonb(NEW) - 'receipt_cancelled') = (to_jsonb(OLD) - 'receipt_cancelled')
+ AND (NEW.receipt_cancelled OR NOT OLD.receipt_cancelled) THEN
+ RETURN NEW;
+ END IF;
+
+ RAISE EXCEPTION 'Receipt % is issued and its food items cannot be changed. Cancel it and issue a replacement instead.', coalesce(old_number, new_number)
+ USING ERRCODE = 'integrity_constraint_violation', CONSTRAINT = 'tr_receipt_items_issued_read_only';
+ END;
+ $$;
+
+ CREATE TRIGGER tr_receipt_items_issued_read_only
+ BEFORE INSERT OR UPDATE OR DELETE ON receipt_items
+ FOR EACH ROW EXECUTE FUNCTION refuse_change_to_issued_receipt_item();
+ """;
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.Sql("""
+ DROP TRIGGER tr_receipt_items_issued_read_only ON receipt_items;
+ DROP FUNCTION refuse_change_to_issued_receipt_item();
+ DROP TRIGGER tr_receipts_issued_read_only ON receipts;
+ DROP FUNCTION refuse_change_to_issued_receipt();
+ """);
+
+ migrationBuilder.DropForeignKey(
+ name: "fk_receipts_receipts_replaces_receipt_id",
+ table: "receipts");
+
+ migrationBuilder.DropIndex(
+ name: "ix_receipts_replaces_receipt_id",
+ table: "receipts");
+
+ migrationBuilder.DropCheckConstraint(
+ name: "ck_receipts_advantage_amount_range",
+ table: "receipts");
+
+ migrationBuilder.DropCheckConstraint(
+ name: "ck_receipts_issued_details_frozen",
+ table: "receipts");
+
+ migrationBuilder.DropCheckConstraint(
+ name: "ck_receipts_replaces_another_receipt",
+ table: "receipts");
+
+ migrationBuilder.DropColumn(
+ name: "advantage_amount",
+ table: "receipts");
+
+ migrationBuilder.DropColumn(
+ name: "donor_address",
+ table: "receipts");
+
+ migrationBuilder.DropColumn(
+ name: "donor_city",
+ table: "receipts");
+
+ migrationBuilder.DropColumn(
+ name: "donor_name",
+ table: "receipts");
+
+ migrationBuilder.DropColumn(
+ name: "donor_postal_code",
+ table: "receipts");
+
+ migrationBuilder.DropColumn(
+ name: "donor_province",
+ table: "receipts");
+
+ migrationBuilder.DropColumn(
+ name: "issued_at",
+ table: "receipts");
+
+ migrationBuilder.DropColumn(
+ name: "replaces_receipt_id",
+ table: "receipts");
+
+ migrationBuilder.DropColumn(
+ name: "description",
+ table: "receipt_items");
+
+ migrationBuilder.DropColumn(
+ name: "donation_date",
+ table: "receipt_items");
+ }
+ }
+}
diff --git a/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs b/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs
index ad78058..9acef17 100644
--- a/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs
+++ b/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs
@@ -686,16 +686,51 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
+ b.Property("AdvantageAmount")
+ .ValueGeneratedOnAdd()
+ .HasPrecision(12, 2)
+ .HasColumnType("numeric(12,2)")
+ .HasDefaultValue(0m)
+ .HasColumnName("advantage_amount");
+
b.Property("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at")
.HasDefaultValueSql("now()");
+ b.Property("DonorAddress")
+ .HasColumnType("text")
+ .HasColumnName("donor_address");
+
+ b.Property("DonorCity")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)")
+ .HasColumnName("donor_city");
+
b.Property("DonorId")
.HasColumnType("uuid")
.HasColumnName("donor_id");
+ b.Property("DonorName")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("donor_name");
+
+ b.Property("DonorPostalCode")
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasColumnName("donor_postal_code");
+
+ b.Property("DonorProvince")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("donor_province");
+
+ b.Property("IssuedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("issued_at");
+
b.Property("ReceiptDate")
.ValueGeneratedOnAdd()
.HasColumnType("date")
@@ -707,6 +742,10 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.HasColumnType("character varying(10)")
.HasColumnName("receipt_number");
+ b.Property("ReplacesReceiptId")
+ .HasColumnType("uuid")
+ .HasColumnName("replaces_receipt_id");
+
b.Property("Status")
.IsRequired()
.ValueGeneratedOnAdd()
@@ -733,14 +772,24 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.IsUnique()
.HasDatabaseName("ix_receipts_receipt_number");
+ b.HasIndex("ReplacesReceiptId")
+ .IsUnique()
+ .HasDatabaseName("ix_receipts_replaces_receipt_id");
+
b.ToTable("receipts", null, t =>
{
+ t.HasCheckConstraint("ck_receipts_advantage_amount_range", "advantage_amount >= 0 AND (advantage_amount = 0 OR advantage_amount <= total_amount)");
+
+ t.HasCheckConstraint("ck_receipts_issued_details_frozen", "receipt_number IS NULL OR (issued_at IS NOT NULL AND donor_name IS NOT NULL)");
+
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_replaces_another_receipt", "replaces_receipt_id <> id");
+
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");
@@ -757,6 +806,15 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.HasColumnType("uuid")
.HasColumnName("food_item_id");
+ b.Property("Description")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("description");
+
+ b.Property("DonationDate")
+ .HasColumnType("date")
+ .HasColumnName("donation_date");
+
b.Property("DonorId")
.HasColumnType("uuid")
.HasColumnName("donor_id");
@@ -1260,7 +1318,15 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.IsRequired()
.HasConstraintName("fk_receipts_donors_donor_id");
+ b.HasOne("MoissonMontreal.Core.Entities.Receipt", "ReplacesReceipt")
+ .WithOne()
+ .HasForeignKey("MoissonMontreal.Core.Entities.Receipt", "ReplacesReceiptId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_receipts_receipts_replaces_receipt_id");
+
b.Navigation("Donor");
+
+ b.Navigation("ReplacesReceipt");
});
modelBuilder.Entity("MoissonMontreal.Core.Entities.ReceiptItem", b =>
diff --git a/src/MoissonMontreal.Api/MoissonMontreal.Api.csproj b/src/MoissonMontreal.Api/MoissonMontreal.Api.csproj
index 893d47c..50c05ad 100644
--- a/src/MoissonMontreal.Api/MoissonMontreal.Api.csproj
+++ b/src/MoissonMontreal.Api/MoissonMontreal.Api.csproj
@@ -18,6 +18,7 @@
+
diff --git a/src/MoissonMontreal.Api/Program.cs b/src/MoissonMontreal.Api/Program.cs
index a5095b1..3539e7d 100644
--- a/src/MoissonMontreal.Api/Program.cs
+++ b/src/MoissonMontreal.Api/Program.cs
@@ -10,6 +10,7 @@
using MoissonMontreal.Api.Pricing;
using MoissonMontreal.Api.Receipts;
using MoissonMontreal.Core.Authorization;
+using MoissonMontreal.Core.Receipts;
var builder = WebApplication.CreateBuilder(args);
@@ -53,6 +54,8 @@
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
+builder.Services.AddScoped();
+builder.Services.Configure(builder.Configuration.GetSection(ReceiptIssuer.SectionName));
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
diff --git a/src/MoissonMontreal.Api/Receipts/ReceiptDocumentService.cs b/src/MoissonMontreal.Api/Receipts/ReceiptDocumentService.cs
new file mode 100644
index 0000000..8106a9a
--- /dev/null
+++ b/src/MoissonMontreal.Api/Receipts/ReceiptDocumentService.cs
@@ -0,0 +1,117 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Options;
+using MoissonMontreal.Api.Data;
+using MoissonMontreal.Core.Pricing;
+using MoissonMontreal.Core.Receipts;
+
+namespace MoissonMontreal.Api.Receipts;
+
+///
+/// Builds the PDF of a receipt. An issued or cancelled receipt is printed only from what was frozen on it when it was issued,
+/// so a later change to the donor profile or to the food items never changes it. A receipt not issued yet is printed as a
+/// preview from the current donor profile and food items, with no number, so it can be checked before it is issued.
+///
+public class ReceiptDocumentService(MoissonDbContext db, IOptionsSnapshot issuer)
+{
+ private static readonly TimeZoneInfo Montreal = FindMontrealTimeZone();
+
+ ///
+ /// Returns the receipt number, or null for a preview, and the PDF of the receipt.
+ ///
+ /// The receipt does not exist.
+ /// A value required on the receipt is missing, such as the donor address.
+ public async Task<(string? ReceiptNumber, byte[] Pdf)> RenderAsync(Guid receiptId, CancellationToken cancellationToken = default)
+ {
+ var document = await BuildAsync(receiptId, cancellationToken);
+ try
+ {
+ return (document.ReceiptNumber, ReceiptPdfRenderer.Render(document));
+ }
+ catch (ReceiptTextNotPrintableException e)
+ {
+ throw new ReceiptDataMissingException(receiptId, [e.Message]);
+ }
+ }
+
+ ///
+ /// Returns everything printed on the receipt.
+ ///
+ /// The receipt does not exist.
+ /// A value required on the receipt is missing, such as the donor address.
+ public async Task BuildAsync(Guid receiptId, CancellationToken cancellationToken = default)
+ {
+ var receipt = await db.Receipts
+ .AsNoTracking()
+ .Include(r => r.Donor)
+ .Include(r => r.ReplacesReceipt)
+ .Include(r => r.Items).ThenInclude(i => i.FoodItem)
+ .AsSplitQuery()
+ .SingleOrDefaultAsync(r => r.Id == receiptId, cancellationToken)
+ ?? throw new ReceiptNotFoundException(receiptId);
+
+ var issued = receipt.ReceiptNumber is not null;
+ var donor = issued
+ ? new ReceiptDonor(receipt.DonorName, receipt.DonorAddress, receipt.DonorCity, receipt.DonorProvince, receipt.DonorPostalCode)
+ : new ReceiptDonor(receipt.Donor.Name, receipt.Donor.Address, receipt.Donor.City, receipt.Donor.Province, receipt.Donor.PostalCode);
+
+ var lines = receipt.Items
+ .Where(i => issued || !i.ReceiptCancelled)
+ .Select(i => new ReceiptDocumentLine(
+ issued ? i.Description ?? string.Empty : i.FoodItem.Name,
+ issued ? i.DonationDate : i.FoodItem.DonationDate,
+ i.Quantity,
+ i.Unit,
+ i.UnitPrice,
+ i.QualityPercent,
+ DonationValue.CalculateLine(i.Quantity, i.UnitPrice, i.QualityPercent)))
+ .OrderBy(l => l.DonationDate)
+ .ThenBy(l => l.Description, StringComparer.CurrentCulture)
+ .ToList();
+
+ var problems = ReceiptIssueCheck.FindProblems(issuer.Value, donor, lines, receipt.TotalAmount, receipt.AdvantageAmount);
+ if (problems.Count > 0)
+ {
+ throw new ReceiptDataMissingException(receiptId, problems);
+ }
+
+ var kind = (issued, receipt.Status) switch
+ {
+ (true, ReceiptStatus.Cancelled) => ReceiptDocumentKind.Cancelled,
+ (true, _) => ReceiptDocumentKind.Official,
+ _ => ReceiptDocumentKind.Preview,
+ };
+
+ return new ReceiptDocument(
+ kind,
+ issuer.Value,
+ receipt.ReceiptNumber,
+ receipt.IssuedAt is { } issuedAt ? ToMontrealDate(issuedAt) : null,
+ donor,
+ lines,
+ receipt.TotalAmount,
+ receipt.AdvantageAmount,
+ receipt.ReplacesReceipt?.ReceiptNumber);
+ }
+
+ ///
+ /// Day of a moment in Montreal time, which is the date printed on the receipt.
+ ///
+ public static DateOnly ToMontrealDate(DateTimeOffset moment) =>
+ DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, Montreal).DateTime);
+
+ ///
+ /// Finds the Montreal time zone under its IANA name, or under its Windows name on a Windows server without ICU.
+ ///
+ private static TimeZoneInfo FindMontrealTimeZone()
+ {
+ foreach (var id in new[] { "America/Montreal", "America/Toronto", "Eastern Standard Time" })
+ {
+ if (TimeZoneInfo.TryFindSystemTimeZoneById(id, out var zone))
+ {
+ return zone;
+ }
+ }
+
+ throw new TimeZoneNotFoundException("The Montreal time zone is not available on this server.");
+ }
+}
diff --git a/src/MoissonMontreal.Api/Receipts/ReceiptMentions.cs b/src/MoissonMontreal.Api/Receipts/ReceiptMentions.cs
new file mode 100644
index 0000000..85f3377
--- /dev/null
+++ b/src/MoissonMontreal.Api/Receipts/ReceiptMentions.cs
@@ -0,0 +1,68 @@
+namespace MoissonMontreal.Api.Receipts;
+
+///
+/// Wording printed on every tax receipt. The list of mentions comes from general knowledge of the Canada Revenue Agency (CRA)
+/// requirements for a receipt of a gift of property, not from an official source: it must be validated with Moisson Montréal
+/// and against the CRA documentation, with the Quebec requirements, before receipts are issued for real.
+/// See docs/receipts/tax-receipt-pdf.md. The tests check each mention in the text of the PDF with their own copy of the wording.
+///
+public static class ReceiptMentions
+{
+ public const string TitleFr = "Reçu officiel aux fins de l'impôt sur le revenu";
+ public const string TitleEn = "Official receipt for income tax purposes";
+
+ public const string RegistrationNumberFr = "Numéro d'enregistrement de l'organisme de bienfaisance";
+ public const string RegistrationNumberEn = "Charity registration number";
+
+ public const string SerialNumberFr = "Reçu n°";
+ public const string SerialNumberEn = "Receipt No.";
+
+ public const string DonationDateFr = "Date de réception du don";
+ public const string DonationDateEn = "Date the gift was received";
+
+ public const string IssueDateFr = "Date de délivrance du reçu";
+ public const string IssueDateEn = "Date the receipt was issued";
+
+ public const string PlaceOfIssueFr = "Lieu de délivrance";
+ public const string PlaceOfIssueEn = "Place of issue";
+
+ public const string DonorFr = "Nom et adresse du donateur";
+ public const string DonorEn = "Donor's name and address";
+
+ public const string DescriptionFr = "Description des biens reçus (don en nature)";
+ public const string DescriptionEn = "Description of the property received (gift in kind)";
+
+ public const string LineValueFr = "Juste valeur marchande";
+ public const string LineValueEn = "Fair market value";
+
+ public const string FairMarketValueFr = "Juste valeur marchande des biens reçus";
+ public const string FairMarketValueEn = "Fair market value of the property received";
+
+ public const string AdvantageFr = "Montant de l'avantage";
+ public const string AdvantageEn = "Amount of the advantage";
+
+ public const string EligibleAmountFr = "Montant admissible du don aux fins de l'impôt";
+ public const string EligibleAmountEn = "Eligible amount of the gift for tax purposes";
+
+ public const string AppraiserFr = "Évaluateur";
+ public const string AppraiserEn = "Appraiser";
+
+ public const string SignatureFr = "Signature autorisée";
+ public const string SignatureEn = "Authorized signature";
+
+ public const string CraFr = "Agence du revenu du Canada";
+ public const string CraEn = "Canada Revenue Agency";
+
+ public const string ReplacesFr = "Ce reçu annule et remplace le reçu n°";
+ public const string ReplacesEn = "This receipt cancels and replaces receipt No.";
+
+ public const string CancelledFr = "REÇU ANNULÉ : ce reçu n'est plus valide aux fins de l'impôt";
+ public const string CancelledEn = "CANCELLED RECEIPT: not valid for income tax purposes";
+ public const string CancelledWatermark = "ANNULÉ / CANCELLED";
+
+ public const string PreviewFr = "APERÇU : ce document n'est pas un reçu officiel";
+ public const string PreviewEn = "PREVIEW: this document is not an official receipt";
+ public const string PreviewWatermark = "APERÇU / PREVIEW";
+
+ public const string NumberToBeAssigned = "à attribuer / to be assigned";
+}
diff --git a/src/MoissonMontreal.Api/Receipts/ReceiptPdfRenderer.cs b/src/MoissonMontreal.Api/Receipts/ReceiptPdfRenderer.cs
new file mode 100644
index 0000000..f3b1341
--- /dev/null
+++ b/src/MoissonMontreal.Api/Receipts/ReceiptPdfRenderer.cs
@@ -0,0 +1,375 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+using MoissonMontreal.Core.Receipts;
+using QuestPDF.Drawing.Exceptions;
+using QuestPDF.Fluent;
+using QuestPDF.Helpers;
+using QuestPDF.Infrastructure;
+
+namespace MoissonMontreal.Api.Receipts;
+
+///
+/// Draws a tax receipt as a PDF on letter paper, in French with the English translation of each mention.
+/// The layout follows the receipt template of Moisson Montréal as far as it is known; it must be compared with the template
+/// provided by the client before it is used for real receipts. The font is Lato, embedded in the PDF, so accents print the
+/// same on every computer. Long names and descriptions wrap, and the table of food items continues on the next pages,
+/// with its header repeated.
+///
+public static partial class ReceiptPdfRenderer
+{
+ private const string Font = "Lato";
+ private const float BaseFontSize = 9;
+ private const string Primary = "#1F4E79";
+ private const string Muted = "#5A5A5A";
+ private const string Rule = "#BFBFBF";
+
+ private static readonly NumberFormatInfo FrenchNumbers = CreateFrenchNumbers();
+
+ static ReceiptPdfRenderer()
+ {
+ // Moisson Montréal is a registered charity, which the QuestPDF Community license covers.
+ QuestPDF.Settings.License = LicenseType.Community;
+ // Use only the fonts shipped with QuestPDF, so the PDF is the same on every server.
+ QuestPDF.Settings.UseSystemFonts = false;
+ }
+
+ ///
+ /// Returns the PDF of a receipt.
+ ///
+ ///
+ /// A text of the receipt has characters the font cannot print, such as an emoji. They are never dropped silently,
+ /// because the receipt must show the donor's name exactly.
+ ///
+ public static byte[] Render(ReceiptDocument receipt)
+ {
+ try
+ {
+ return Document.Create(container => container.Page(page => ComposePage(page, receipt)))
+ .WithMetadata(new DocumentMetadata
+ {
+ Title = receipt.ReceiptNumber is null
+ ? $"{ReceiptMentions.TitleFr} ({ReceiptMentions.PreviewFr})"
+ : $"{ReceiptMentions.TitleFr} {receipt.ReceiptNumber}",
+ Author = receipt.Issuer.LegalName,
+ Subject = ReceiptMentions.TitleEn,
+ Language = "fr-CA",
+ })
+ .GeneratePdf();
+ }
+ catch (DocumentDrawingException e) when (e.Message.Contains("glyph", StringComparison.OrdinalIgnoreCase))
+ {
+ throw new ReceiptTextNotPrintableException(QuotedText().Match(e.Message) is { Success: true } match ? match.Groups[1].Value : null, e);
+ }
+ }
+
+ ///
+ /// Formats an amount the way it is printed on the receipt, such as 1 234,56 $.
+ ///
+ public static string FormatMoney(decimal amount) => amount.ToString("#,##0.00", FrenchNumbers) + " $";
+
+ ///
+ /// Formats a unit price, with up to 4 decimals, such as 0,125 $.
+ ///
+ public static string FormatUnitPrice(decimal amount) => amount.ToString("#,##0.00##", FrenchNumbers) + " $";
+
+ ///
+ /// Formats a date the way it is printed on the receipt: 2026-11-30.
+ ///
+ public static string FormatDate(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
+
+ private static void ComposePage(PageDescriptor page, ReceiptDocument receipt)
+ {
+ page.Size(PageSizes.Letter);
+ page.Margin(0.6f, Unit.Inch);
+ page.PageColor(Colors.White);
+ page.DefaultTextStyle(x => x.FontFamily(Font).FontSize(BaseFontSize).LineHeight(1.2f));
+
+ page.Header().Element(c => ComposeHeader(c, receipt));
+ page.Content().PaddingVertical(10).Element(c => ComposeContent(c, receipt));
+ page.Footer().Element(c => ComposeFooter(c, receipt));
+
+ if (receipt.Kind != ReceiptDocumentKind.Official)
+ {
+ page.Foreground()
+ .AlignCenter()
+ .AlignMiddle()
+ .Rotate(-30)
+ .Text(receipt.Kind == ReceiptDocumentKind.Cancelled ? ReceiptMentions.CancelledWatermark : ReceiptMentions.PreviewWatermark)
+ .FontSize(64)
+ .Bold()
+ .FontColor("#33C00000");
+ }
+ }
+
+ private static void ComposeHeader(IContainer container, ReceiptDocument receipt)
+ {
+ var issuer = receipt.Issuer;
+ container.Column(column =>
+ {
+ column.Item().Row(row =>
+ {
+ row.RelativeItem(3).Column(org =>
+ {
+ org.Item().Text(issuer.LegalName).FontSize(14).Bold().FontColor(Primary);
+ org.Item().Text(issuer.Address);
+ org.Item().Text($"{issuer.City} ({issuer.Province}) {issuer.PostalCode}");
+ org.Item().PaddingTop(2).Text(text =>
+ {
+ text.Span($"{ReceiptMentions.RegistrationNumberFr} / {ReceiptMentions.RegistrationNumberEn} : ").FontColor(Muted);
+ text.Span(issuer.RegistrationNumber).Bold();
+ });
+ });
+
+ row.RelativeItem(2).AlignRight().Column(title =>
+ {
+ title.Item().AlignRight().Text(ReceiptMentions.TitleFr).FontSize(11).Bold().FontColor(Primary);
+ title.Item().AlignRight().Text(ReceiptMentions.TitleEn).Italic().FontColor(Muted);
+ title.Item().PaddingTop(4).AlignRight().Text(text =>
+ {
+ text.Span($"{ReceiptMentions.SerialNumberFr} / {ReceiptMentions.SerialNumberEn} : ").FontColor(Muted);
+ text.Span(receipt.ReceiptNumber ?? ReceiptMentions.NumberToBeAssigned).Bold().FontSize(11);
+ });
+ });
+ });
+
+ column.Item().PaddingTop(6).LineHorizontal(1).LineColor(Primary);
+ });
+ }
+
+ private static void ComposeContent(IContainer container, ReceiptDocument receipt)
+ {
+ container.Column(column =>
+ {
+ column.Spacing(10);
+
+ if (receipt.Kind == ReceiptDocumentKind.Preview)
+ {
+ column.Item().Background("#FDECEA").Padding(6)
+ .Text($"{ReceiptMentions.PreviewFr} / {ReceiptMentions.PreviewEn}").Bold().FontColor("#C00000");
+ }
+ else if (receipt.Kind == ReceiptDocumentKind.Cancelled)
+ {
+ column.Item().Background("#FDECEA").Padding(6)
+ .Text($"{ReceiptMentions.CancelledFr} / {ReceiptMentions.CancelledEn}").Bold().FontColor("#C00000");
+ }
+
+ if (receipt.ReplacedReceiptNumber is not null)
+ {
+ column.Item().Border(1).BorderColor(Primary).Padding(6).Text(text =>
+ {
+ text.Span($"{ReceiptMentions.ReplacesFr} {receipt.ReplacedReceiptNumber}").Bold();
+ text.Span($" / {ReceiptMentions.ReplacesEn} {receipt.ReplacedReceiptNumber}").Italic();
+ });
+ }
+
+ column.Item().Row(row =>
+ {
+ row.Spacing(16);
+ row.RelativeItem().Element(c => ComposeDonor(c, receipt.Donor));
+ row.RelativeItem().Element(c => ComposeDates(c, receipt));
+ });
+
+ column.Item().Element(c => ComposeLines(c, receipt));
+ column.Item().Element(c => ComposeTotals(c, receipt));
+
+ if (!string.IsNullOrWhiteSpace(receipt.Issuer.AppraiserName))
+ {
+ column.Item().Text(text =>
+ {
+ text.Span($"{ReceiptMentions.AppraiserFr} / {ReceiptMentions.AppraiserEn} : ").FontColor(Muted);
+ text.Span($"{receipt.Issuer.AppraiserName}, {receipt.Issuer.AppraiserAddress}");
+ });
+ }
+
+ column.Item().ShowEntire().Element(c => ComposeSignature(c, receipt));
+ });
+ }
+
+ private static void ComposeDonor(IContainer container, ReceiptDonor donor)
+ {
+ container.Border(1).BorderColor(Rule).Padding(8).Column(column =>
+ {
+ column.Item().Text($"{ReceiptMentions.DonorFr} / {ReceiptMentions.DonorEn}").FontColor(Muted);
+ column.Item().PaddingTop(2).Text(donor.Name ?? string.Empty).FontSize(11).Bold();
+ column.Item().Text(donor.Address ?? string.Empty);
+ column.Item().Text($"{donor.City} ({donor.Province}) {donor.PostalCode}");
+ });
+ }
+
+ private static void ComposeDates(IContainer container, ReceiptDocument receipt)
+ {
+ container.Border(1).BorderColor(Rule).Padding(8).Column(column =>
+ {
+ column.Spacing(3);
+ Field(column, ReceiptMentions.DonationDateFr, ReceiptMentions.DonationDateEn, DonationDates(receipt));
+ Field(
+ column,
+ ReceiptMentions.IssueDateFr,
+ ReceiptMentions.IssueDateEn,
+ receipt.IssueDate is { } issued ? FormatDate(issued) : ReceiptMentions.NumberToBeAssigned);
+ Field(column, ReceiptMentions.PlaceOfIssueFr, ReceiptMentions.PlaceOfIssueEn, receipt.Issuer.PlaceOfIssue);
+ });
+
+ static void Field(ColumnDescriptor column, string french, string english, string value) =>
+ column.Item().Text(text =>
+ {
+ text.Span($"{french} / {english} : ").FontColor(Muted);
+ text.Span(value).Bold();
+ });
+ }
+
+ private static string DonationDates(ReceiptDocument receipt) =>
+ (receipt.FirstDonationDate, receipt.LastDonationDate) switch
+ {
+ ({ } first, { } last) when first == last => FormatDate(first),
+ ({ } first, { } last) => $"{FormatDate(first)} au / to {FormatDate(last)}",
+ _ => string.Empty,
+ };
+
+ private static void ComposeLines(IContainer container, ReceiptDocument receipt)
+ {
+ container.Column(column =>
+ {
+ column.Item().PaddingBottom(4)
+ .Text($"{ReceiptMentions.DescriptionFr} / {ReceiptMentions.DescriptionEn}")
+ .Bold()
+ .FontColor(Primary);
+
+ column.Item().Table(table =>
+ {
+ table.ColumnsDefinition(columns =>
+ {
+ columns.ConstantColumn(62);
+ columns.RelativeColumn(4);
+ columns.ConstantColumn(62);
+ columns.ConstantColumn(62);
+ columns.ConstantColumn(44);
+ columns.ConstantColumn(72);
+ });
+
+ table.Header(header =>
+ {
+ HeaderCell(header.Cell(), "Date", "Date");
+ HeaderCell(header.Cell(), "Description", "Description");
+ HeaderCell(header.Cell(), "Quantité", "Quantity", right: true);
+ HeaderCell(header.Cell(), "Prix unitaire", "Unit price", right: true);
+ HeaderCell(header.Cell(), "Qualité", "Quality", right: true);
+ HeaderCell(header.Cell(), ReceiptMentions.LineValueFr, ReceiptMentions.LineValueEn, right: true);
+ });
+
+ foreach (var line in receipt.Lines)
+ {
+ BodyCell(table.Cell()).Text(line.DonationDate is { } date ? FormatDate(date) : string.Empty);
+ BodyCell(table.Cell()).Text(line.Description);
+ BodyCell(table.Cell()).AlignRight().Text($"{line.Quantity.ToString("#,##0.##", FrenchNumbers)} {line.Unit}");
+ BodyCell(table.Cell()).AlignRight().Text(FormatUnitPrice(line.UnitPrice));
+ BodyCell(table.Cell()).AlignRight().Text($"{line.QualityPercent.ToString("0.##", FrenchNumbers)} %");
+ BodyCell(table.Cell()).AlignRight().Text(FormatMoney(line.Value));
+ }
+ });
+ });
+
+ static void HeaderCell(IContainer cell, string french, string english, bool right = false)
+ {
+ var box = cell.Background("#EAF1F8").BorderBottom(1).BorderColor(Primary).PaddingVertical(3).PaddingHorizontal(4);
+ if (right)
+ {
+ box = box.AlignRight();
+ }
+
+ box.Column(c =>
+ {
+ c.Item().Text(french).Bold().FontSize(8);
+ c.Item().Text(english).Italic().FontSize(7).FontColor(Muted);
+ });
+ }
+
+ static IContainer BodyCell(IContainer cell) =>
+ cell.BorderBottom(0.5f).BorderColor(Rule).PaddingVertical(3).PaddingHorizontal(4);
+ }
+
+ private static void ComposeTotals(IContainer container, ReceiptDocument receipt)
+ {
+ container.ShowEntire().AlignRight().Width(300).Column(column =>
+ {
+ Total(column, ReceiptMentions.FairMarketValueFr, ReceiptMentions.FairMarketValueEn, receipt.FairMarketValue, bold: false);
+ Total(column, ReceiptMentions.AdvantageFr, ReceiptMentions.AdvantageEn, receipt.AdvantageAmount, bold: false);
+ column.Item().LineHorizontal(1).LineColor(Primary);
+ Total(column, ReceiptMentions.EligibleAmountFr, ReceiptMentions.EligibleAmountEn, receipt.EligibleAmount, bold: true);
+ });
+
+ static void Total(ColumnDescriptor column, string french, string english, decimal amount, bool bold) =>
+ column.Item().PaddingVertical(2).Row(row =>
+ {
+ row.RelativeItem().Column(label =>
+ {
+ var text = label.Item().Text(french);
+ if (bold)
+ {
+ text.Bold();
+ }
+
+ label.Item().Text(english).Italic().FontSize(7).FontColor(Muted);
+ });
+ var value = row.ConstantItem(90).AlignRight().Text(FormatMoney(amount));
+ if (bold)
+ {
+ value.Bold().FontSize(11);
+ }
+ });
+ }
+
+ private static void ComposeSignature(IContainer container, ReceiptDocument receipt)
+ {
+ container.PaddingTop(10).Row(row =>
+ {
+ row.RelativeItem().AlignBottom().Column(cra =>
+ {
+ cra.Item().Text($"{ReceiptMentions.CraFr} / {ReceiptMentions.CraEn} :").FontColor(Muted);
+ cra.Item().Text(receipt.Issuer.CraWebsite).Bold();
+ });
+
+ row.ConstantItem(220).Column(signature =>
+ {
+ signature.Item().Height(36);
+ signature.Item().LineHorizontal(0.75f).LineColor(Colors.Black);
+ signature.Item().Text($"{ReceiptMentions.SignatureFr} / {ReceiptMentions.SignatureEn}").FontColor(Muted);
+ signature.Item().Text(receipt.Issuer.SignatoryName).Bold();
+ if (!string.IsNullOrWhiteSpace(receipt.Issuer.SignatoryTitle))
+ {
+ signature.Item().Text(receipt.Issuer.SignatoryTitle);
+ }
+ });
+ });
+ }
+
+ private static void ComposeFooter(IContainer container, ReceiptDocument receipt)
+ {
+ container.BorderTop(0.5f).BorderColor(Rule).PaddingTop(4).Row(row =>
+ {
+ row.RelativeItem().Text($"{receipt.Issuer.LegalName} | {ReceiptMentions.SerialNumberFr} {receipt.ReceiptNumber ?? ReceiptMentions.NumberToBeAssigned}")
+ .FontSize(7)
+ .FontColor(Muted);
+ row.ConstantItem(80).AlignRight().Text(text =>
+ {
+ text.DefaultTextStyle(x => x.FontSize(7).FontColor(Muted));
+ text.Span("Page ");
+ text.CurrentPageNumber();
+ text.Span(" / ");
+ text.TotalPages();
+ });
+ });
+ }
+
+ private static NumberFormatInfo CreateFrenchNumbers()
+ {
+ var numbers = (NumberFormatInfo)CultureInfo.GetCultureInfo("fr-CA").NumberFormat.Clone();
+ // A no-break space keeps 1 234,56 $ on one line, and Lato has the glyph, unlike the narrow no-break space of recent ICU.
+ numbers.NumberGroupSeparator = " ";
+ numbers.NumberDecimalSeparator = ",";
+ return numbers;
+ }
+
+ [GeneratedRegex("\"(.*)\"", RegexOptions.Singleline)]
+ private static partial Regex QuotedText();
+}
diff --git a/src/MoissonMontreal.Api/Receipts/ReceiptProblems.cs b/src/MoissonMontreal.Api/Receipts/ReceiptProblems.cs
new file mode 100644
index 0000000..2387337
--- /dev/null
+++ b/src/MoissonMontreal.Api/Receipts/ReceiptProblems.cs
@@ -0,0 +1,25 @@
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Infrastructure;
+using MoissonMontreal.Core.Receipts;
+
+namespace MoissonMontreal.Api.Receipts;
+
+///
+/// Answers shared by the receipt endpoints.
+///
+public static class ReceiptProblems
+{
+ ///
+ /// 422 answer that lists every value missing on the receipt, so the employee knows what to fix.
+ ///
+ public static ProblemDetails DataMissing(ProblemDetailsFactory factory, HttpContext context, ReceiptDataMissingException e)
+ {
+ var problem = factory.CreateProblemDetails(
+ context,
+ StatusCodes.Status422UnprocessableEntity,
+ title: "Receipt data missing",
+ detail: string.Join(" ", e.Problems));
+ problem.Extensions["problems"] = e.Problems;
+ return problem;
+ }
+}
diff --git a/src/MoissonMontreal.Api/Receipts/ReceiptStatusService.cs b/src/MoissonMontreal.Api/Receipts/ReceiptStatusService.cs
index 3c033c6..94388da 100644
--- a/src/MoissonMontreal.Api/Receipts/ReceiptStatusService.cs
+++ b/src/MoissonMontreal.Api/Receipts/ReceiptStatusService.cs
@@ -1,24 +1,29 @@
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Options;
using MoissonMontreal.Api.Authorization;
using MoissonMontreal.Api.Data;
using MoissonMontreal.Core.Entities;
+using MoissonMontreal.Core.Pricing;
using MoissonMontreal.Core.Receipts;
namespace MoissonMontreal.Api.Receipts;
-public class ReceiptStatusService(MoissonDbContext db, UserLookupService users)
+public class ReceiptStatusService(MoissonDbContext db, UserLookupService users, IOptionsSnapshot issuer)
{
///
/// Applies an action to a receipt: checks it against , then changes the status and
/// records who made the change in one transaction. The receipt row is locked before its status and its submitter are
/// read, so an action on the same receipt at the same time waits, then is checked against the new status and submitter.
- /// When the receipt is issued, it also takes the next receipt number in that same transaction.
+ /// When the receipt is issued, it checks that everything required on a tax receipt is there, freezes the donor's name and
+ /// address and the description and date of each food item on the receipt, and takes the next receipt number, all in that
+ /// same transaction.
///
/// The receipt does not exist.
/// The action is not allowed from the current status.
/// The reason is missing, empty or too long.
/// The employee submitted the receipt and tries to approve it.
+ /// The receipt is issued but a value required on it is missing.
public async Task ApplyAsync(
Guid receiptId,
ReceiptAction action,
@@ -26,39 +31,120 @@ public async Task ApplyAsync(
ClaimsPrincipal employee,
CancellationToken cancellationToken = default)
{
- var user = await users.FindActiveUserAsync(employee, cancellationToken)
- ?? throw new InvalidOperationException("Only an employee with an active account can change the status of a receipt.");
+ var user = await FindUserAsync(employee, cancellationToken);
await using var dbTransaction = await db.Database.BeginTransactionAsync(cancellationToken);
- var receipt = (await db.Receipts
+ var receipt = await LockReceiptAsync(receiptId, cancellationToken);
+ var applied = await ApplyLockedAsync(receipt, action, reason, user, cancellationToken);
+
+ await dbTransaction.CommitAsync(cancellationToken);
+ return applied;
+ }
+
+ ///
+ /// Cancels an issued receipt and creates its replacement in one transaction. The cancelled receipt keeps its number and
+ /// stays readable. The replacement starts in Draft with a copy of the food items and their values, refers to the cancelled
+ /// receipt, and goes through approval again before it is issued with a new number.
+ ///
+ /// The receipt does not exist.
+ /// The receipt is not issued.
+ /// The reason is missing, empty or too long.
+ public async Task<(AppliedReceiptAction Cancellation, Receipt Replacement)> ReplaceAsync(
+ Guid receiptId,
+ string? reason,
+ ClaimsPrincipal employee,
+ CancellationToken cancellationToken = default)
+ {
+ var user = await FindUserAsync(employee, cancellationToken);
+
+ await using var dbTransaction = await db.Database.BeginTransactionAsync(cancellationToken);
+
+ var original = await LockReceiptAsync(receiptId, cancellationToken);
+ if (original.Status != ReceiptStatus.Issued)
+ {
+ throw new ReceiptNotReplaceableException(receiptId, original.Status);
+ }
+
+ var lines = await db.ReceiptItems.AsNoTracking().Where(i => i.ReceiptId == receiptId).ToListAsync(cancellationToken);
+ var cancellation = await ApplyLockedAsync(original, ReceiptAction.Cancel, reason, user, cancellationToken);
+
+ var replacement = new Receipt
+ {
+ DonorId = original.DonorId,
+ TotalAmount = original.TotalAmount,
+ AdvantageAmount = original.AdvantageAmount,
+ ReplacesReceiptId = original.Id,
+ Items = [.. lines.Select(line => new ReceiptItem
+ {
+ FoodItemId = line.FoodItemId,
+ DonorId = line.DonorId,
+ Quantity = line.Quantity,
+ Unit = line.Unit,
+ UnitPrice = line.UnitPrice,
+ QualityPercent = line.QualityPercent,
+ })],
+ };
+ db.Receipts.Add(replacement);
+ await db.SaveChangesAsync(cancellationToken);
+ await dbTransaction.CommitAsync(cancellationToken);
+
+ return (cancellation, replacement);
+ }
+
+ private async Task FindUserAsync(ClaimsPrincipal employee, CancellationToken cancellationToken) =>
+ await users.FindActiveUserAsync(employee, cancellationToken)
+ ?? throw new InvalidOperationException("Only an employee with an active account can change the status of a receipt.");
+
+ private async Task LockReceiptAsync(Guid receiptId, CancellationToken cancellationToken) =>
+ (await db.Receipts
.FromSql($"SELECT * FROM receipts WHERE id = {receiptId} FOR UPDATE")
.AsNoTracking()
.ToListAsync(cancellationToken))
.SingleOrDefault()
?? throw new ReceiptNotFoundException(receiptId);
+ ///
+ /// Applies an action to a receipt already locked by the current transaction. The caller commits.
+ ///
+ private async Task ApplyLockedAsync(
+ Receipt receipt,
+ ReceiptAction action,
+ string? reason,
+ User user,
+ CancellationToken cancellationToken)
+ {
var transition = ReceiptStateMachine.GetTransition(receipt.Status, action);
var savedReason = ReadReason(transition, reason);
- if (transition.ForbiddenToSubmitter && await FindSubmitterIdAsync(receiptId, cancellationToken) == user.Id)
+ if (transition.ForbiddenToSubmitter && await FindSubmitterIdAsync(receipt.Id, cancellationToken) == user.Id)
{
- throw new SubmitterCannotApproveException(receiptId, action);
+ throw new SubmitterCannotApproveException(receipt.Id, action);
}
- var newNumber = transition.To == ReceiptStatus.Issued
+ var frozen = transition.To == ReceiptStatus.Issued
+ ? await FreezeIssueDetailsAsync(receipt, cancellationToken)
+ : null;
+
+ var newNumber = frozen is not null
? ReceiptNumber.Format(await TakeNextReceiptSequenceAsync(cancellationToken))
: null;
await db.Receipts
- .Where(r => r.Id == receiptId)
+ .Where(r => r.Id == receipt.Id)
.ExecuteUpdateAsync(
setters =>
{
setters.SetProperty(r => r.Status, transition.To);
- if (newNumber is not null)
+ if (newNumber is not null && frozen is not null)
{
setters.SetProperty(r => r.ReceiptNumber, newNumber);
+ setters.SetProperty(r => r.IssuedAt, DateTimeOffset.UtcNow);
+ setters.SetProperty(r => r.DonorName, frozen.Name);
+ setters.SetProperty(r => r.DonorAddress, frozen.Address);
+ setters.SetProperty(r => r.DonorCity, frozen.City);
+ setters.SetProperty(r => r.DonorProvince, frozen.Province);
+ setters.SetProperty(r => r.DonorPostalCode, frozen.PostalCode);
}
},
cancellationToken);
@@ -66,13 +152,13 @@ await db.Receipts
if (transition.To == ReceiptStatus.Cancelled)
{
await db.ReceiptItems
- .Where(i => i.ReceiptId == receiptId)
+ .Where(i => i.ReceiptId == receipt.Id)
.ExecuteUpdateAsync(i => i.SetProperty(x => x.ReceiptCancelled, true), cancellationToken);
}
var change = new ReceiptStatusChange
{
- ReceiptId = receiptId,
+ ReceiptId = receipt.Id,
FromStatus = transition.From,
ToStatus = transition.To,
ChangedBy = user,
@@ -80,11 +166,86 @@ await db.ReceiptItems
};
db.ReceiptStatusChanges.Add(change);
await db.SaveChangesAsync(cancellationToken);
- await dbTransaction.CommitAsync(cancellationToken);
return new AppliedReceiptAction(change, newNumber ?? receipt.ReceiptNumber);
}
+ ///
+ /// Checks that the receipt has everything a tax receipt needs, then copies the description and donation date of each food
+ /// item onto its line. Returns the donor's name and address to freeze on the receipt. The lines are written before the
+ /// receipt gets its number, because the database refuses any change to the lines of a numbered receipt.
+ ///
+ /// A value required on the receipt is missing.
+ private async Task FreezeIssueDetailsAsync(Receipt receipt, CancellationToken cancellationToken)
+ {
+ var donor = await db.Donors
+ .AsNoTracking()
+ .Where(d => d.Id == receipt.DonorId)
+ .Select(d => new ReceiptDonor(d.Name, d.Address, d.City, d.Province, d.PostalCode))
+ .SingleAsync(cancellationToken);
+ donor = new ReceiptDonor(donor.Name?.Trim(), donor.Address?.Trim(), donor.City?.Trim(), donor.Province?.Trim(), donor.PostalCode?.Trim());
+
+ var lines = (await db.ReceiptItems
+ .AsNoTracking()
+ .Where(i => i.ReceiptId == receipt.Id && !i.ReceiptCancelled)
+ .Select(i => new { i.FoodItem.Name, i.FoodItem.DonationDate, i.Quantity, i.Unit, i.UnitPrice, i.QualityPercent })
+ .ToListAsync(cancellationToken))
+ .Select(i => new ReceiptDocumentLine(
+ i.Name,
+ i.DonationDate,
+ i.Quantity,
+ i.Unit,
+ i.UnitPrice,
+ i.QualityPercent,
+ DonationValue.CalculateLine(i.Quantity, i.UnitPrice, i.QualityPercent)))
+ .ToList();
+
+ var problems = ReceiptIssueCheck.FindProblems(issuer.Value, donor, lines, receipt.TotalAmount, receipt.AdvantageAmount);
+ if (problems.Count > 0)
+ {
+ throw new ReceiptDataMissingException(receipt.Id, problems);
+ }
+
+ EnsurePrintable(receipt, donor, lines);
+
+ await db.Database.ExecuteSqlAsync(
+ $"""
+ UPDATE receipt_items AS i
+ SET description = f.name, donation_date = f.donation_date
+ FROM food_items AS f
+ WHERE f.id = i.food_item_id AND i.receipt_id = {receipt.Id}
+ """,
+ cancellationToken);
+
+ return donor;
+ }
+
+ ///
+ /// Draws the receipt once before it is issued, so a receipt that cannot be printed, for example because the donor's name
+ /// has an emoji, is refused now instead of being frozen and never printable.
+ ///
+ /// A text of the receipt cannot be printed.
+ private void EnsurePrintable(Receipt receipt, ReceiptDonor donor, List lines)
+ {
+ try
+ {
+ ReceiptPdfRenderer.Render(new ReceiptDocument(
+ ReceiptDocumentKind.Official,
+ issuer.Value,
+ ReceiptNumber.Format(1),
+ ReceiptDocumentService.ToMontrealDate(DateTimeOffset.UtcNow),
+ donor,
+ lines,
+ receipt.TotalAmount,
+ receipt.AdvantageAmount,
+ null));
+ }
+ catch (ReceiptTextNotPrintableException e)
+ {
+ throw new ReceiptDataMissingException(receipt.Id, [e.Message]);
+ }
+ }
+
private static string? ReadReason(ReceiptTransition transition, string? reason)
{
if (!transition.RequiresReason)
diff --git a/src/MoissonMontreal.Api/Receipts/ReceiptTextNotPrintableException.cs b/src/MoissonMontreal.Api/Receipts/ReceiptTextNotPrintableException.cs
new file mode 100644
index 0000000..31eb14f
--- /dev/null
+++ b/src/MoissonMontreal.Api/Receipts/ReceiptTextNotPrintableException.cs
@@ -0,0 +1,15 @@
+namespace MoissonMontreal.Api.Receipts;
+
+///
+/// A text of the receipt has characters the receipt font cannot print, such as an emoji or a non-Latin script.
+///
+public class ReceiptTextNotPrintableException(string? text, Exception innerException)
+ : Exception(BuildMessage(text), innerException)
+{
+ public string? Text { get; } = text;
+
+ private static string BuildMessage(string? text) =>
+ (text is null ? "A text of the receipt" : $"The text \"{text}\"") +
+ " has characters the receipt cannot print, such as an emoji or a non-Latin script. " +
+ "Correct the donor profile or the food item name before generating the receipt.";
+}
diff --git a/src/MoissonMontreal.Api/appsettings.json b/src/MoissonMontreal.Api/appsettings.json
index 4bd70bc..971f2d7 100644
--- a/src/MoissonMontreal.Api/appsettings.json
+++ b/src/MoissonMontreal.Api/appsettings.json
@@ -11,5 +11,19 @@
"Microsoft.AspNetCore": "Warning"
}
},
- "AllowedHosts": "*"
+ "AllowedHosts": "*",
+ "ReceiptIssuer": {
+ "LegalName": "",
+ "Address": "",
+ "City": "",
+ "Province": "",
+ "PostalCode": "",
+ "RegistrationNumber": "",
+ "PlaceOfIssue": "",
+ "SignatoryName": "",
+ "SignatoryTitle": "",
+ "AppraiserName": "",
+ "AppraiserAddress": "",
+ "CraWebsite": "canada.ca/organismes-bienfaisance-dons | canada.ca/charities-giving"
+ }
}
diff --git a/src/MoissonMontreal.Core/Dtos/ReceiptReplacementDto.cs b/src/MoissonMontreal.Core/Dtos/ReceiptReplacementDto.cs
new file mode 100644
index 0000000..5df9aa2
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/ReceiptReplacementDto.cs
@@ -0,0 +1,9 @@
+namespace MoissonMontreal.Core.Dtos;
+
+///
+/// Result of the cancellation and replacement of an issued receipt.
+///
+/// Identifier of the issued receipt, now cancelled.
+/// Number of the cancelled receipt, kept and never given again.
+/// Identifier of the new receipt, in Draft, which goes through approval before it is issued.
+public record ReceiptReplacementDto(Guid CancelledReceiptId, string? CancelledReceiptNumber, Guid ReplacementReceiptId);
diff --git a/src/MoissonMontreal.Core/Entities/Receipt.cs b/src/MoissonMontreal.Core/Entities/Receipt.cs
index e5182fc..0e24968 100644
--- a/src/MoissonMontreal.Core/Entities/Receipt.cs
+++ b/src/MoissonMontreal.Core/Entities/Receipt.cs
@@ -58,4 +58,51 @@ public class Receipt
/// Every status change of this receipt, with who made it and when.
///
public ICollection StatusChanges { get; set; } = [];
+
+ ///
+ /// Value of the advantage the donor received in return for the gift, in dollars. Zero for a plain food donation.
+ /// The eligible amount printed on the receipt is minus this amount.
+ ///
+ public decimal AdvantageAmount { get; set; }
+
+ ///
+ /// Date and time the receipt was issued, stored in UTC. Empty until the receipt is issued.
+ ///
+ public DateTimeOffset? IssuedAt { get; set; }
+
+ ///
+ /// Name of the donor as printed on the receipt, copied from the donor profile when the receipt is issued.
+ /// A later change to the donor does not change it. Empty until the receipt is issued.
+ ///
+ public string? DonorName { get; set; }
+
+ ///
+ /// Street address of the donor, copied from the donor profile when the receipt is issued.
+ ///
+ public string? DonorAddress { get; set; }
+
+ ///
+ /// City of the donor, copied from the donor profile when the receipt is issued.
+ ///
+ public string? DonorCity { get; set; }
+
+ ///
+ /// Province of the donor, copied from the donor profile when the receipt is issued.
+ ///
+ public string? DonorProvince { get; set; }
+
+ ///
+ /// Postal code of the donor, copied from the donor profile when the receipt is issued.
+ ///
+ public string? DonorPostalCode { get; set; }
+
+ ///
+ /// Identifier of the cancelled receipt this one replaces, or null if it replaces none.
+ ///
+ public Guid? ReplacesReceiptId { get; set; }
+
+ ///
+ /// Cancelled receipt this one replaces, or null if it replaces none.
+ ///
+ public Receipt? ReplacesReceipt { get; set; }
}
\ No newline at end of file
diff --git a/src/MoissonMontreal.Core/Entities/ReceiptItem.cs b/src/MoissonMontreal.Core/Entities/ReceiptItem.cs
index bb3ed4e..5d77c48 100644
--- a/src/MoissonMontreal.Core/Entities/ReceiptItem.cs
+++ b/src/MoissonMontreal.Core/Entities/ReceiptItem.cs
@@ -56,4 +56,15 @@ public class ReceiptItem
/// free again, so it can go on a new receipt.
///
public bool ReceiptCancelled { get; set; }
+
+ ///
+ /// Description of the food as printed on the receipt, copied from the food item when the receipt is issued.
+ /// Empty until then.
+ ///
+ public string? Description { get; set; }
+
+ ///
+ /// Day the food was received, copied from the food item when the receipt is issued. Empty until then.
+ ///
+ public DateOnly? DonationDate { get; set; }
}
\ No newline at end of file
diff --git a/src/MoissonMontreal.Core/Receipts/ReceiptDataMissingException.cs b/src/MoissonMontreal.Core/Receipts/ReceiptDataMissingException.cs
new file mode 100644
index 0000000..8e93c17
--- /dev/null
+++ b/src/MoissonMontreal.Core/Receipts/ReceiptDataMissingException.cs
@@ -0,0 +1,13 @@
+namespace MoissonMontreal.Core.Receipts;
+
+///
+/// A receipt cannot be issued or printed because a value required on a tax receipt is missing or wrong, such as an incomplete
+/// donor address. Each problem has its own message, written so an employee knows what to fix.
+///
+public class ReceiptDataMissingException(Guid receiptId, IReadOnlyList problems)
+ : Exception($"Receipt {receiptId} cannot be generated: {string.Join(" ", problems)}")
+{
+ public Guid ReceiptId { get; } = receiptId;
+
+ public IReadOnlyList Problems { get; } = problems;
+}
diff --git a/src/MoissonMontreal.Core/Receipts/ReceiptDocument.cs b/src/MoissonMontreal.Core/Receipts/ReceiptDocument.cs
new file mode 100644
index 0000000..e629afb
--- /dev/null
+++ b/src/MoissonMontreal.Core/Receipts/ReceiptDocument.cs
@@ -0,0 +1,101 @@
+namespace MoissonMontreal.Core.Receipts;
+
+///
+/// Everything printed on a tax receipt, ready to be drawn as a PDF. For an issued receipt, every value comes from what was
+/// frozen on the receipt when it was issued, so a later change to the donor or the food items does not change the document.
+///
+/// Whether the document is a valid receipt, a cancelled one or a preview.
+/// Organization that issues the receipt.
+/// Serial number of the receipt, or null for a preview.
+/// Day the receipt was issued in Montreal time, or null for a preview.
+/// Name and address of the donor.
+/// Food items given, one per line, in the order they are printed.
+/// Fair market value of the gift: the sum of the line values, in dollars.
+/// Value of the advantage the donor received, in dollars. Zero if none.
+/// Number of the cancelled receipt this one replaces, or null.
+public sealed record ReceiptDocument(
+ ReceiptDocumentKind Kind,
+ ReceiptIssuer Issuer,
+ string? ReceiptNumber,
+ DateOnly? IssueDate,
+ ReceiptDonor Donor,
+ IReadOnlyList Lines,
+ decimal FairMarketValue,
+ decimal AdvantageAmount,
+ string? ReplacedReceiptNumber)
+{
+ ///
+ /// Amount the donor can claim: the fair market value minus the advantage.
+ ///
+ public decimal EligibleAmount => FairMarketValue - AdvantageAmount;
+
+ ///
+ /// First day a food item of the receipt was received.
+ ///
+ public DateOnly? FirstDonationDate => Lines.Where(l => l.DonationDate is not null).Min(l => l.DonationDate);
+
+ ///
+ /// Last day a food item of the receipt was received.
+ ///
+ public DateOnly? LastDonationDate => Lines.Where(l => l.DonationDate is not null).Max(l => l.DonationDate);
+}
+
+///
+/// Whether a receipt document can be given to the donor.
+///
+public enum ReceiptDocumentKind
+{
+ ///
+ /// An issued receipt, valid for income tax purposes.
+ ///
+ Official,
+
+ ///
+ /// A receipt that was issued, then cancelled. It is printed with a cancelled banner, for the records only.
+ ///
+ Cancelled,
+
+ ///
+ /// A receipt not issued yet, printed with a preview banner and no number, so it can be checked before it is issued.
+ ///
+ Preview,
+}
+
+///
+/// Name and address of a donor as printed on a receipt.
+///
+public sealed record ReceiptDonor(string? Name, string? Address, string? City, string? Province, string? PostalCode)
+{
+ ///
+ /// Returns the name of each part of the name and address that is empty, such as "postal code".
+ ///
+ public IReadOnlyList MissingParts()
+ {
+ var missing = new List();
+ if (string.IsNullOrWhiteSpace(Name)) missing.Add("name");
+ if (string.IsNullOrWhiteSpace(Address)) missing.Add("street address");
+ if (string.IsNullOrWhiteSpace(City)) missing.Add("city");
+ if (string.IsNullOrWhiteSpace(Province)) missing.Add("province");
+ if (string.IsNullOrWhiteSpace(PostalCode)) missing.Add("postal code");
+ return missing;
+ }
+}
+
+///
+/// One food item printed on a receipt.
+///
+/// Description of the food.
+/// Day the food was received.
+/// Quantity given.
+/// Unit of the quantity, such as kg.
+/// Price of one unit used for the value, in dollars.
+/// Share of the price kept for the quality of the food, from 0 to 100.
+/// Fair market value of the line, rounded to the cent.
+public sealed record ReceiptDocumentLine(
+ string Description,
+ DateOnly? DonationDate,
+ decimal Quantity,
+ string Unit,
+ decimal UnitPrice,
+ decimal QualityPercent,
+ decimal Value);
diff --git a/src/MoissonMontreal.Core/Receipts/ReceiptIssueCheck.cs b/src/MoissonMontreal.Core/Receipts/ReceiptIssueCheck.cs
new file mode 100644
index 0000000..5ed75c7
--- /dev/null
+++ b/src/MoissonMontreal.Core/Receipts/ReceiptIssueCheck.cs
@@ -0,0 +1,74 @@
+using System.Globalization;
+using MoissonMontreal.Core.Pricing;
+
+namespace MoissonMontreal.Core.Receipts;
+
+///
+/// Lists what prevents a receipt from being a valid tax receipt: a setting of the organization not filled, an incomplete donor
+/// name or address, no food item, or a total that does not match its lines. A receipt is issued only when the list is empty.
+///
+public static class ReceiptIssueCheck
+{
+ ///
+ /// Returns one message per problem, or an empty list when the receipt can be issued.
+ ///
+ /// Organization that issues the receipt.
+ /// Name and address of the donor that would be printed.
+ /// Food items of the receipt.
+ /// Total stored on the receipt.
+ /// Advantage stored on the receipt.
+ public static IReadOnlyList FindProblems(
+ ReceiptIssuer issuer,
+ ReceiptDonor donor,
+ IReadOnlyCollection lines,
+ decimal totalAmount,
+ decimal advantageAmount)
+ {
+ var problems = new List(issuer.FindMissingSettings());
+
+ var missingDonorParts = donor.MissingParts();
+ if (missingDonorParts.Count > 0)
+ {
+ problems.Add(
+ $"The donor profile is incomplete: the {Join(missingDonorParts)} {(missingDonorParts.Count == 1 ? "is" : "are")} missing. " +
+ "Complete the donor profile before issuing the receipt.");
+ }
+
+ if (lines.Count == 0)
+ {
+ problems.Add("The receipt has no food item. Add the donated food before issuing the receipt.");
+ }
+ else
+ {
+ if (lines.Any(l => string.IsNullOrWhiteSpace(l.Description)))
+ {
+ problems.Add("A food item of the receipt has no description.");
+ }
+
+ if (lines.Any(l => l.DonationDate is null))
+ {
+ problems.Add("A food item of the receipt has no donation date.");
+ }
+
+ var sum = lines.Sum(l => DonationValue.CalculateLine(l.Quantity, l.UnitPrice, l.QualityPercent));
+ if (sum != totalAmount)
+ {
+ problems.Add(
+ $"The total of the receipt ({Format(totalAmount)}) does not match the sum of its food items ({Format(sum)}). " +
+ "Recalculate the receipt before issuing it.");
+ }
+ }
+
+ if (advantageAmount < 0 || advantageAmount > totalAmount)
+ {
+ problems.Add($"The advantage ({Format(advantageAmount)}) must be between $0.00 and the total of the receipt.");
+ }
+
+ return problems;
+ }
+
+ private static string Join(IReadOnlyList parts) =>
+ parts.Count == 1 ? parts[0] : $"{string.Join(", ", parts.Take(parts.Count - 1))} and {parts[^1]}";
+
+ private static string Format(decimal amount) => amount.ToString("$0.00", CultureInfo.InvariantCulture);
+}
diff --git a/src/MoissonMontreal.Core/Receipts/ReceiptIssuer.cs b/src/MoissonMontreal.Core/Receipts/ReceiptIssuer.cs
new file mode 100644
index 0000000..a31f7ef
--- /dev/null
+++ b/src/MoissonMontreal.Core/Receipts/ReceiptIssuer.cs
@@ -0,0 +1,110 @@
+namespace MoissonMontreal.Core.Receipts;
+
+///
+/// The organization that issues the tax receipts, as registered with the Canada Revenue Agency (CRA).
+/// Read from the ReceiptIssuer section of the API settings. Every required value must be filled before a receipt can be
+/// issued: a receipt without them may be refused by the CRA.
+///
+public class ReceiptIssuer
+{
+ ///
+ /// Name of the settings section.
+ ///
+ public const string SectionName = "ReceiptIssuer";
+
+ ///
+ /// Default address of the CRA charities page printed on every receipt, in French and in English.
+ ///
+ public const string DefaultCraWebsite = "canada.ca/organismes-bienfaisance-dons | canada.ca/charities-giving";
+
+ ///
+ /// Name of the organization exactly as on file with the CRA.
+ ///
+ public string LegalName { get; set; } = string.Empty;
+
+ ///
+ /// Street address of the organization as on file with the CRA.
+ ///
+ public string Address { get; set; } = string.Empty;
+
+ ///
+ /// City of the organization as on file with the CRA.
+ ///
+ public string City { get; set; } = string.Empty;
+
+ ///
+ /// Province of the organization as on file with the CRA.
+ ///
+ public string Province { get; set; } = string.Empty;
+
+ ///
+ /// Postal code of the organization as on file with the CRA.
+ ///
+ public string PostalCode { get; set; } = string.Empty;
+
+ ///
+ /// Charity registration number given by the CRA, such as 123456789 RR 0001.
+ ///
+ public string RegistrationNumber { get; set; } = string.Empty;
+
+ ///
+ /// Place where the receipts are issued, such as Montréal (Québec).
+ ///
+ public string PlaceOfIssue { get; set; } = string.Empty;
+
+ ///
+ /// Name of the person authorized to sign the receipts.
+ ///
+ public string SignatoryName { get; set; } = string.Empty;
+
+ ///
+ /// Title of the person authorized to sign the receipts, such as Director of Finance. Optional.
+ ///
+ public string? SignatoryTitle { get; set; }
+
+ ///
+ /// Name of the appraiser who set the value of the donated food, printed only when it is set. Optional.
+ ///
+ public string? AppraiserName { get; set; }
+
+ ///
+ /// Address of the appraiser, printed with their name. Required when is set.
+ ///
+ public string? AppraiserAddress { get; set; }
+
+ ///
+ /// Address of the CRA web page printed on every receipt.
+ ///
+ public string CraWebsite { get; set; } = DefaultCraWebsite;
+
+ ///
+ /// Returns one message for each required value that is empty, naming the setting to fill.
+ ///
+ public IReadOnlyList FindMissingSettings()
+ {
+ var missing = new List();
+ Require(LegalName, nameof(LegalName), "name of the organization");
+ Require(Address, nameof(Address), "address of the organization");
+ Require(City, nameof(City), "city of the organization");
+ Require(Province, nameof(Province), "province of the organization");
+ Require(PostalCode, nameof(PostalCode), "postal code of the organization");
+ Require(RegistrationNumber, nameof(RegistrationNumber), "charity registration number");
+ Require(PlaceOfIssue, nameof(PlaceOfIssue), "place of issue");
+ Require(SignatoryName, nameof(SignatoryName), "name of the authorized signatory");
+ Require(CraWebsite, nameof(CraWebsite), "address of the CRA website");
+ if (!string.IsNullOrWhiteSpace(AppraiserName))
+ {
+ Require(AppraiserAddress, nameof(AppraiserAddress), "address of the appraiser");
+ }
+
+ return missing;
+
+ void Require(string? value, string key, string label)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ missing.Add($"The {label} is not configured. Set {SectionName}:{key} in the API settings.");
+ }
+ }
+ }
+}
diff --git a/src/MoissonMontreal.Core/Receipts/ReceiptNotReplaceableException.cs b/src/MoissonMontreal.Core/Receipts/ReceiptNotReplaceableException.cs
new file mode 100644
index 0000000..9d7e28a
--- /dev/null
+++ b/src/MoissonMontreal.Core/Receipts/ReceiptNotReplaceableException.cs
@@ -0,0 +1,12 @@
+namespace MoissonMontreal.Core.Receipts;
+
+///
+/// Only an issued receipt can be cancelled and replaced. A receipt not issued yet is corrected in Draft instead.
+///
+public class ReceiptNotReplaceableException(Guid receiptId, ReceiptStatus status)
+ : Exception($"Receipt {receiptId} is {status}: only an issued receipt can be cancelled and replaced.")
+{
+ public Guid ReceiptId { get; } = receiptId;
+
+ public ReceiptStatus Status { get; } = status;
+}
diff --git a/tests/MoissonMontreal.Tests/Api/ReceiptDocumentEndpointTests.cs b/tests/MoissonMontreal.Tests/Api/ReceiptDocumentEndpointTests.cs
new file mode 100644
index 0000000..3f88bfb
--- /dev/null
+++ b/tests/MoissonMontreal.Tests/Api/ReceiptDocumentEndpointTests.cs
@@ -0,0 +1,525 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using Microsoft.EntityFrameworkCore;
+using MoissonMontreal.Api.Data;
+using MoissonMontreal.Api.Pricing;
+using MoissonMontreal.Api.Receipts;
+using MoissonMontreal.Core.Authorization;
+using MoissonMontreal.Core.Dtos;
+using MoissonMontreal.Core.Entities;
+using MoissonMontreal.Core.Receipts;
+using MoissonMontreal.Tests.Fixtures;
+using Npgsql;
+
+namespace MoissonMontreal.Tests.Api;
+
+[Trait("Category", "Integration")]
+public class ReceiptDocumentEndpointTests(PermissionsApiFactory factory) : IClassFixture, IAsyncLifetime
+{
+ private static readonly Employee Supply = new(RoleCodes.Supply, "Sam Supply", "cccccccc-0000-0000-0000-000000000001");
+ private static readonly Employee Director = new(RoleCodes.SupplyDirector, "Dana Director", "cccccccc-0000-0000-0000-000000000002");
+ private static readonly Employee Finance = new(RoleCodes.Finance, "Fred Finance", "cccccccc-0000-0000-0000-000000000003");
+
+ private static readonly DateOnly November1 = new(2026, 11, 1);
+ private static readonly DateOnly November3 = new(2026, 11, 3);
+ private static readonly DateOnly November10 = new(2026, 11, 10);
+
+ public async Task InitializeAsync()
+ {
+ await using var context = factory.CreateDbContext();
+ if (await context.Users.AnyAsync(u => u.Email == Supply.Email))
+ {
+ return;
+ }
+
+ foreach (var employee in new[] { Supply, Director, Finance })
+ {
+ context.Users.Add(new User
+ {
+ Email = employee.Email,
+ DisplayName = employee.Name,
+ EntraObjectId = Guid.Parse(employee.ObjectId),
+ RoleId = await context.Roles.Where(r => r.Code == employee.Role).Select(r => r.Id).SingleAsync(),
+ });
+ }
+
+ await context.SaveChangesAsync();
+ }
+
+ public Task DisposeAsync() => Task.CompletedTask;
+
+ [Fact]
+ public async Task IssuedReceipt_IsGeneratedFromTheCalculatedValues_AndShowsItsNumber()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Épicerie Côté & Fils");
+
+ await ApproveAsync(receiptId);
+ var issue = await PostAsync(Supply, receiptId, "issue");
+ var number = (await issue.Content.ReadFromJsonAsync())?.ReceiptNumber;
+ var response = await GetPdfAsync(Supply, receiptId);
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal("application/pdf", response.Content.Headers.ContentType?.MediaType);
+ Assert.Equal($"{number}.pdf", response.Content.Headers.ContentDisposition?.FileNameStar ?? response.Content.Headers.ContentDisposition?.FileName);
+ var text = PdfText.Read(await response.Content.ReadAsByteArrayAsync());
+ // Bread: 12.50 kg × $4.00 × 50 % (class B default) = $25.00. Cheese: 3 kg × $10.00 × 100 % = $30.00. Total $55.00.
+ Assert.Contains(number!, text.All);
+ Assert.Contains("Épicerie Côté & Fils", text.All);
+ Assert.Contains("Pain de blé", text.All);
+ Assert.Contains("Fromage cheddar", text.All);
+ Assert.Contains("25,00 $", text.All);
+ Assert.Contains("30,00 $", text.All);
+ Assert.Contains("55,00 $", text.All);
+ Assert.Contains("2026-11-03 au / to 2026-11-10", text.All);
+ Assert.Contains(TestReceiptIssuer.RegistrationNumber, text.All);
+ Assert.Contains(ReceiptDocumentService.ToMontrealDate(DateTimeOffset.UtcNow).ToString("yyyy-MM-dd"), text.All);
+ }
+
+ [Fact]
+ public async Task LaterChangeToTheDonorOrFoodItem_DoesNotChangeAnIssuedReceipt()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie Saint-Éloi");
+ await ApproveAsync(receiptId);
+ await PostAsync(Supply, receiptId, "issue");
+
+ await using (var context = factory.CreateDbContext())
+ {
+ var donorId = await context.Receipts.Where(r => r.Id == receiptId).Select(r => r.DonorId).SingleAsync();
+ await context.Donors.Where(d => d.Id == donorId).ExecuteUpdateAsync(d => d
+ .SetProperty(x => x.Name, "Nouveau nom inc.")
+ .SetProperty(x => x.Address, "1, rue Changée")
+ .SetProperty(x => x.PostalCode, (string?)null));
+ await context.FoodItems.Where(f => f.DonorId == donorId).ExecuteUpdateAsync(f => f.SetProperty(x => x.Name, "Nom modifié"));
+ }
+
+ var text = PdfText.Read(await (await GetPdfAsync(Supply, receiptId)).Content.ReadAsByteArrayAsync());
+
+ Assert.Contains("Boulangerie Saint-Éloi", text.All);
+ Assert.Contains("4500, boulevard Saint-Laurent", text.All);
+ Assert.Contains("H2T 1R2", text.All);
+ Assert.Contains("Pain de blé", text.All);
+ Assert.DoesNotContain("Nouveau nom", text.All);
+ Assert.DoesNotContain("Nom modifié", text.All);
+ }
+
+ [Fact]
+ public async Task Issue_IsRefused_WithAnExplicitMessage_WhenTheDonorAddressIsIncomplete()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Ferme sans adresse", donor => donor.PostalCode = null);
+ await ApproveAsync(receiptId);
+
+ var response = await PostAsync(Supply, receiptId, "issue");
+
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ var problem = await response.Content.ReadFromJsonAsync();
+ var problems = problem.GetProperty("problems").EnumerateArray().Select(p => p.GetString()).ToList();
+ Assert.Contains(problems, p => p!.Contains("postal code is missing", StringComparison.Ordinal));
+ await using var context = factory.CreateDbContext();
+ var receipt = await context.Receipts.AsNoTracking().SingleAsync(r => r.Id == receiptId);
+ Assert.Equal(ReceiptStatus.Approved, receipt.Status);
+ Assert.Null(receipt.ReceiptNumber);
+ }
+
+ [Fact]
+ public async Task RefusedIssue_DoesNotUseANumber()
+ {
+ var incomplete = await CreateValuedReceiptAsync("Ferme sans ville", donor => donor.City = " ");
+ var complete = await CreateValuedReceiptAsync("Ferme complète");
+ await ApproveAsync(incomplete);
+ await ApproveAsync(complete);
+
+ await PostAsync(Supply, incomplete, "issue");
+ var number = (await (await PostAsync(Supply, complete, "issue")).Content.ReadFromJsonAsync())?.ReceiptNumber;
+
+ await using var context = factory.CreateDbContext();
+ var last = await context.ReceiptNumberCounters.Where(c => c.Series == ReceiptNumber.Series).Select(c => c.LastNumber).SingleAsync();
+ Assert.Equal(ReceiptNumber.Format(last), number);
+ }
+
+ [Fact]
+ public async Task Preview_IsRefused_WithAnExplicitMessage_WhenTheDonorAddressIsIncomplete()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Ferme sans adresse", donor => donor.Address = null);
+
+ var response = await GetPdfAsync(Supply, receiptId);
+
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ var problem = await response.Content.ReadFromJsonAsync();
+ Assert.Contains("street address is missing", problem.GetProperty("detail").GetString());
+ }
+
+ [Fact]
+ public async Task ReceiptNotIssuedYet_IsAPreview_FromTheCurrentDonorProfile()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Marché Jean-Talon");
+
+ var response = await GetPdfAsync(Supply, receiptId);
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var text = PdfText.Read(await response.Content.ReadAsByteArrayAsync());
+ Assert.Contains("APERÇU", text.All);
+ Assert.Contains("Marché Jean-Talon", text.All);
+ Assert.DoesNotContain("DEN_", text.All);
+ }
+
+ [Fact]
+ public async Task Replace_CancelsTheIssuedReceipt_AndCreatesADraftThatRefersToIt()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie à remplacer");
+ await ApproveAsync(receiptId);
+ var number = (await (await PostAsync(Supply, receiptId, "issue")).Content.ReadFromJsonAsync())?.ReceiptNumber;
+
+ var response = await PostAsync(Supply, receiptId, "replace", new ReceiptReasonRequest("Mauvaise adresse du donateur"));
+
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ var replacement = await response.Content.ReadFromJsonAsync();
+ Assert.Equal(number, replacement?.CancelledReceiptNumber);
+ await using var context = factory.CreateDbContext();
+ var original = await context.Receipts.AsNoTracking().Include(r => r.StatusChanges).SingleAsync(r => r.Id == receiptId);
+ var copy = await context.Receipts.AsNoTracking().Include(r => r.Items).SingleAsync(r => r.Id == replacement!.ReplacementReceiptId);
+ Assert.Equal(ReceiptStatus.Cancelled, original.Status);
+ Assert.Equal(number, original.ReceiptNumber);
+ Assert.Contains(original.StatusChanges, c => c.ToStatus == ReceiptStatus.Cancelled && c.Reason == "Mauvaise adresse du donateur");
+ Assert.Equal(ReceiptStatus.Draft, copy.Status);
+ Assert.Equal(receiptId, copy.ReplacesReceiptId);
+ Assert.Null(copy.ReceiptNumber);
+ Assert.Equal(original.TotalAmount, copy.TotalAmount);
+ Assert.Equal(2, copy.Items.Count);
+ }
+
+ [Fact]
+ public async Task IssuedReplacement_StatesTheReceiptItReplaces_AndTheCancelledReceiptStaysReadable()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie à remplacer");
+ await ApproveAsync(receiptId);
+ var number = (await (await PostAsync(Supply, receiptId, "issue")).Content.ReadFromJsonAsync())?.ReceiptNumber;
+ var replacement = await (await PostAsync(Supply, receiptId, "replace", new ReceiptReasonRequest("Mauvaise quantité")))
+ .Content.ReadFromJsonAsync();
+
+ await PostAsync(Supply, replacement!.ReplacementReceiptId, "submit");
+ await ApproveAsync(replacement.ReplacementReceiptId, alreadySubmitted: true);
+ var newNumber = (await (await PostAsync(Supply, replacement.ReplacementReceiptId, "issue")).Content.ReadFromJsonAsync())?.ReceiptNumber;
+
+ var replacementText = PdfText.Read(await (await GetPdfAsync(Supply, replacement.ReplacementReceiptId)).Content.ReadAsByteArrayAsync());
+ var cancelledText = PdfText.Read(await (await GetPdfAsync(Supply, receiptId)).Content.ReadAsByteArrayAsync());
+ Assert.NotEqual(number, newNumber);
+ Assert.Contains(newNumber!, replacementText.All);
+ Assert.Contains($"Ce reçu annule et remplace le reçu n° {number}", replacementText.All);
+ Assert.Contains(number!, cancelledText.All);
+ Assert.Contains("REÇU ANNULÉ", cancelledText.All);
+ }
+
+ [Fact]
+ public async Task Replace_IsRefused_WhenTheReceiptIsNotIssued()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie en brouillon");
+
+ var response = await PostAsync(Supply, receiptId, "replace", new ReceiptReasonRequest("Erreur"));
+
+ Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task Replace_RequiresAReason()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie sans raison");
+ await ApproveAsync(receiptId);
+ await PostAsync(Supply, receiptId, "issue");
+
+ var response = await PostAsync(Supply, receiptId, "replace", new ReceiptReasonRequest(" "));
+
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task Pdf_RequiresThePermissionToManageReceipts()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie protégée");
+
+ var response = await GetPdfAsync(Finance, receiptId);
+
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task Pdf_Returns404_ForAnUnknownReceipt()
+ {
+ Assert.Equal(HttpStatusCode.NotFound, (await GetPdfAsync(Supply, Guid.NewGuid())).StatusCode);
+ }
+
+ [Theory]
+ [InlineData("UPDATE receipts SET donor_name = 'Autre' WHERE id = @id")]
+ [InlineData("UPDATE receipts SET total_amount = total_amount + 1 WHERE id = @id")]
+ [InlineData("UPDATE receipts SET status = 'Draft' WHERE id = @id")]
+ [InlineData("DELETE FROM receipts WHERE id = @id")]
+ [InlineData("UPDATE receipt_items SET quantity = quantity + 1 WHERE receipt_id = @id")]
+ [InlineData("UPDATE receipt_items SET description = 'Autre' WHERE receipt_id = @id")]
+ [InlineData("DELETE FROM receipt_items WHERE receipt_id = @id")]
+ public async Task Database_RefusesAnyChangeToAnIssuedReceipt(string sql)
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie figée");
+ await ApproveAsync(receiptId);
+ await PostAsync(Supply, receiptId, "issue");
+
+ await using var context = factory.CreateDbContext();
+ var e = await Assert.ThrowsAsync(() =>
+ context.Database.ExecuteSqlRawAsync(sql, new NpgsqlParameter("id", receiptId)));
+
+ Assert.StartsWith("tr_", e.ConstraintName);
+ Assert.Contains("is issued and", e.MessageText);
+ }
+
+ [Fact]
+ public async Task Database_RefusesANewLineOnAnIssuedReceipt()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie figée");
+ await ApproveAsync(receiptId);
+ await PostAsync(Supply, receiptId, "issue");
+
+ await using var context = factory.CreateDbContext();
+ var donorId = await context.Receipts.Where(r => r.Id == receiptId).Select(r => r.DonorId).SingleAsync();
+ var extra = new FoodItem { DonorId = donorId, Name = "Ajout", Quantity = 1m, Unit = "kg", DonationDate = November3, Quality = "A" };
+ context.FoodItems.Add(extra);
+ await context.SaveChangesAsync();
+ context.ReceiptItems.Add(new ReceiptItem
+ {
+ ReceiptId = receiptId,
+ DonorId = donorId,
+ FoodItemId = extra.Id,
+ Quantity = 1m,
+ Unit = "kg",
+ UnitPrice = 1m,
+ QualityPercent = 100m,
+ });
+
+ await PostgresConstraintAssertions.AssertViolatesConstraintAsync(context, "tr_receipt_items_issued_read_only");
+ }
+
+ [Fact]
+ public async Task CancellingAnIssuedReceipt_IsStillAllowedByTheDatabase()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie annulée");
+ await ApproveAsync(receiptId);
+ await PostAsync(Supply, receiptId, "issue");
+
+ var response = await PostAsync(Supply, receiptId, "cancel", new ReceiptReasonRequest("Don en double"));
+
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ }
+
+ [Theory]
+ [InlineData("Ferme du maïs 🌽")]
+ [InlineData("寿司 Montréal")]
+ public async Task Issue_IsRefused_WhenTheDonorNameCannotBePrinted_AndDoesNotUseANumber(string donorName)
+ {
+ var receiptId = await CreateValuedReceiptAsync(donorName);
+ await ApproveAsync(receiptId);
+ var before = await LastNumberAsync();
+
+ var issue = await PostAsync(Supply, receiptId, "issue");
+ var preview = await GetPdfAsync(Supply, receiptId);
+
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, issue.StatusCode);
+ Assert.Contains("cannot print", (await issue.Content.ReadFromJsonAsync()).GetProperty("detail").GetString());
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, preview.StatusCode);
+ Assert.Equal(before, await LastNumberAsync());
+ await using var context = factory.CreateDbContext();
+ Assert.Equal(ReceiptStatus.Approved, await context.Receipts.Where(r => r.Id == receiptId).Select(r => r.Status).SingleAsync());
+ }
+
+ [Fact]
+ public async Task SimultaneousReplacements_CreateOnlyOneReplacement()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie pressée");
+ await ApproveAsync(receiptId);
+ await PostAsync(Supply, receiptId, "issue");
+
+ var responses = await Task.WhenAll(
+ PostAsync(Supply, receiptId, "replace", new ReceiptReasonRequest("Erreur 1")),
+ PostAsync(Supply, receiptId, "replace", new ReceiptReasonRequest("Erreur 2")));
+
+ Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Created);
+ Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Conflict);
+ await using var context = factory.CreateDbContext();
+ Assert.Equal(1, await context.Receipts.CountAsync(r => r.ReplacesReceiptId == receiptId));
+ }
+
+ [Fact]
+ public async Task ReplacingTheReplacedReceiptAgain_IsRefused()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie remplacée");
+ await ApproveAsync(receiptId);
+ await PostAsync(Supply, receiptId, "issue");
+ await PostAsync(Supply, receiptId, "replace", new ReceiptReasonRequest("Erreur"));
+
+ var again = await PostAsync(Supply, receiptId, "replace", new ReceiptReasonRequest("Encore"));
+
+ Assert.Equal(HttpStatusCode.Conflict, again.StatusCode);
+ }
+
+ [Fact]
+ public async Task Database_RefusesMovingALineIntoAnIssuedReceipt()
+ {
+ var issuedId = await CreateValuedReceiptAsync("Boulangerie figée");
+ await ApproveAsync(issuedId);
+ await PostAsync(Supply, issuedId, "issue");
+ await using var context = factory.CreateDbContext();
+ var donorId = await context.Receipts.Where(r => r.Id == issuedId).Select(r => r.DonorId).SingleAsync();
+ var extra = new FoodItem { DonorId = donorId, Name = "Ajout", Quantity = 1m, Unit = "kg", DonationDate = November3, Quality = "A" };
+ context.FoodItems.Add(extra);
+ var draft = new Receipt
+ {
+ DonorId = donorId,
+ TotalAmount = 1m,
+ Items = [new ReceiptItem { FoodItem = extra, Quantity = 1m, Unit = "kg", UnitPrice = 1m, QualityPercent = 100m }],
+ };
+ context.Receipts.Add(draft);
+ await context.SaveChangesAsync();
+
+ var e = await Assert.ThrowsAsync(() => context.Database.ExecuteSqlRawAsync(
+ "UPDATE receipt_items SET receipt_id = @issued WHERE receipt_id = @draft",
+ new NpgsqlParameter("issued", issuedId),
+ new NpgsqlParameter("draft", draft.Id)));
+
+ Assert.Equal("tr_receipt_items_issued_read_only", e.ConstraintName);
+ }
+
+ [Fact]
+ public async Task Database_RefusesUncancellingTheLinesOfACancelledReceipt()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie annulée");
+ await ApproveAsync(receiptId);
+ await PostAsync(Supply, receiptId, "issue");
+ await PostAsync(Supply, receiptId, "cancel", new ReceiptReasonRequest("Don en double"));
+
+ await using var context = factory.CreateDbContext();
+ var e = await Assert.ThrowsAsync(() => context.Database.ExecuteSqlRawAsync(
+ "UPDATE receipt_items SET receipt_cancelled = false WHERE receipt_id = @id",
+ new NpgsqlParameter("id", receiptId)));
+
+ Assert.Equal("tr_receipt_items_issued_read_only", e.ConstraintName);
+ }
+
+ [Fact]
+ public async Task Database_RefusesUncancellingAnIssuedReceipt()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie annulée");
+ await ApproveAsync(receiptId);
+ await PostAsync(Supply, receiptId, "issue");
+ await PostAsync(Supply, receiptId, "cancel", new ReceiptReasonRequest("Don en double"));
+
+ await using var context = factory.CreateDbContext();
+ var e = await Assert.ThrowsAsync(() => context.Database.ExecuteSqlRawAsync(
+ "UPDATE receipts SET status = 'Issued' WHERE id = @id",
+ new NpgsqlParameter("id", receiptId)));
+
+ Assert.Equal("tr_receipts_issued_read_only", e.ConstraintName);
+ }
+
+ [Fact]
+ public async Task DraftReceipt_CanStillBeChangedAndDeleted()
+ {
+ var receiptId = await CreateValuedReceiptAsync("Boulangerie en brouillon");
+
+ await using var context = factory.CreateDbContext();
+ await context.ReceiptItems.Where(i => i.ReceiptId == receiptId).ExecuteUpdateAsync(i => i.SetProperty(x => x.Quantity, 20m));
+ await context.ReceiptItems.Where(i => i.ReceiptId == receiptId).ExecuteDeleteAsync();
+ await context.Receipts.Where(r => r.Id == receiptId).ExecuteDeleteAsync();
+
+ Assert.False(await context.Receipts.AnyAsync(r => r.Id == receiptId));
+ }
+
+ private async Task LastNumberAsync()
+ {
+ await using var context = factory.CreateDbContext();
+ return await context.ReceiptNumberCounters.Where(c => c.Series == ReceiptNumber.Series).Select(c => c.LastNumber).SingleAsync();
+ }
+
+ ///
+ /// Creates a donor with two donated food items matched to the catalog, values them with
+ /// as the import does, and saves a Draft receipt with those values.
+ ///
+ private async Task CreateValuedReceiptAsync(string donorName, Action? changeDonor = null)
+ {
+ await using var context = factory.CreateDbContext();
+ var donor = TestDonors.Complete(donorName);
+ changeDonor?.Invoke(donor);
+ var bread = TestCatalogItems.Create("Pain");
+ var cheese = TestCatalogItems.Create("Fromage");
+ context.Prices.Add(new Price { CatalogItem = bread, UnitPrice = 4.00m, EffectiveDate = November1 });
+ context.Prices.Add(new Price { CatalogItem = cheese, UnitPrice = 10.00m, EffectiveDate = November1 });
+ var breadDonation = new FoodItem
+ {
+ Donor = donor, CatalogItem = bread, Name = "Pain de blé", Quantity = 12.50m, Unit = "kg", DonationDate = November3, Quality = "B",
+ };
+ var cheeseDonation = new FoodItem
+ {
+ Donor = donor, CatalogItem = cheese, Name = "Fromage cheddar", Quantity = 3m, Unit = "kg", DonationDate = November10, Quality = "A",
+ };
+ context.FoodItems.AddRange(breadDonation, cheeseDonation);
+ await context.SaveChangesAsync();
+
+ var valuation = new DonationValueService(context, new PriceService(context));
+ var values = new List
+ {
+ await valuation.CalculateAsync(breadDonation.Id),
+ await valuation.CalculateAsync(cheeseDonation.Id),
+ };
+
+ var receipt = new Receipt
+ {
+ DonorId = donor.Id,
+ TotalAmount = values.Sum(v => v.Value),
+ Items = [.. values.Select(v => new ReceiptItem
+ {
+ FoodItemId = v.FoodItemId,
+ Quantity = v.Quantity,
+ Unit = v.Unit,
+ UnitPrice = v.UnitPrice,
+ QualityPercent = v.QualityPercent,
+ })],
+ };
+ context.Receipts.Add(receipt);
+ await context.SaveChangesAsync();
+ return receipt.Id;
+ }
+
+ private async Task ApproveAsync(Guid receiptId, bool alreadySubmitted = false)
+ {
+ if (!alreadySubmitted)
+ {
+ Assert.Equal(HttpStatusCode.OK, (await PostAsync(Supply, receiptId, "submit")).StatusCode);
+ }
+
+ Assert.Equal(HttpStatusCode.OK, (await PostAsync(Director, receiptId, "approve-level-1")).StatusCode);
+ Assert.Equal(HttpStatusCode.OK, (await PostAsync(Finance, receiptId, "approve-level-2")).StatusCode);
+ }
+
+ private async Task PostAsync(Employee employee, Guid receiptId, string action, ReceiptReasonRequest? body = null)
+ {
+ using var client = CreateClient(employee);
+ var url = $"/api/receipts/{receiptId}/{action}";
+ return body is null ? await client.PostAsync(url, null) : await client.PostAsJsonAsync(url, body);
+ }
+
+ private async Task GetPdfAsync(Employee employee, Guid receiptId)
+ {
+ using var client = CreateClient(employee);
+ return await client.GetAsync($"/api/receipts/{receiptId}/pdf");
+ }
+
+ private HttpClient CreateClient(Employee employee)
+ {
+ var client = factory.CreateClient();
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
+ "Bearer", factory.CreateToken(email: employee.Email, objectId: employee.ObjectId));
+ return client;
+ }
+
+ private sealed record Employee(string Role, string Name, string ObjectId)
+ {
+ public string Email => $"{Role.ToLowerInvariant()}.documents@moissonmontreal.org";
+ }
+}
diff --git a/tests/MoissonMontreal.Tests/Api/ReceiptIssueDetailsMigrationTests.cs b/tests/MoissonMontreal.Tests/Api/ReceiptIssueDetailsMigrationTests.cs
new file mode 100644
index 0000000..5ad13b2
--- /dev/null
+++ b/tests/MoissonMontreal.Tests/Api/ReceiptIssueDetailsMigrationTests.cs
@@ -0,0 +1,62 @@
+using System.Data.Common;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using MoissonMontreal.Api.Data;
+using MoissonMontreal.Tests.Fixtures;
+
+namespace MoissonMontreal.Tests.Api;
+
+[Trait("Category", "Integration")]
+public class ReceiptIssueDetailsMigrationTests(PostgresFixture postgres) : IClassFixture
+{
+ [Fact]
+ public async Task Migrate_FreezesTheReceiptsIssuedBeforeIt_AndLeavesTheOthersEmpty()
+ {
+ await using var context = CreateContext("receipt_issue_details_existing");
+ await context.GetService().MigrateAsync("20261204063259_AddDonationImports");
+ await context.Database.ExecuteSqlRawAsync("""
+ INSERT INTO users (email, display_name, role_id) VALUES ('supply@moissonmontreal.org', 'Sam Supply', 1);
+ INSERT INTO donors (name, search_name, type, address, city, province, postal_code)
+ VALUES ('Boulangerie Saint-Éloi', 'boulangerie saint-eloi', 'organization', '4500, boulevard Saint-Laurent', 'Montréal', 'QC', 'H2T 1R2');
+ INSERT INTO food_items (donor_id, name, quantity, unit, donation_date, quality)
+ SELECT id, 'Pain', 12.50, 'kg', '2026-11-03', 'B' FROM donors;
+ INSERT INTO food_items (donor_id, name, quantity, unit, donation_date, quality)
+ SELECT id, 'Pommes', 3, 'kg', '2026-11-04', 'A' FROM donors;
+ INSERT INTO receipts (donor_id, total_amount, status, receipt_number, created_at)
+ SELECT id, 37.50, 'Issued', 'DEN_000001', '2026-11-05T10:00:00Z' FROM donors;
+ INSERT INTO receipts (donor_id, total_amount, status, created_at)
+ SELECT id, 7.47, 'Approved', '2026-11-06T10:00:00Z' FROM donors;
+ INSERT INTO receipt_items (receipt_id, food_item_id, donor_id, quantity, unit, unit_price, quality_percent)
+ SELECT r.id, f.id, r.donor_id, 12.50, 'kg', 4.00, 75 FROM receipts r, food_items f WHERE r.total_amount = 37.50 AND f.name = 'Pain';
+ INSERT INTO receipt_items (receipt_id, food_item_id, donor_id, quantity, unit, unit_price, quality_percent)
+ SELECT r.id, f.id, r.donor_id, 3, 'kg', 2.49, 100 FROM receipts r, food_items f WHERE r.total_amount = 7.47 AND f.name = 'Pommes';
+ INSERT INTO receipt_status_changes (receipt_id, from_status, to_status, changed_by_user_id, changed_at)
+ SELECT r.id, 'Approved', 'Issued', u.id, '2026-11-07T15:00:00Z' FROM receipts r, users u WHERE r.total_amount = 37.50;
+ """);
+
+ await context.Database.MigrateAsync();
+
+ var receipts = await context.Receipts.AsNoTracking().Include(r => r.Items).OrderBy(r => r.TotalAmount).ToListAsync();
+ var approved = receipts[0];
+ var issued = receipts[1];
+ Assert.Equal("Boulangerie Saint-Éloi", issued.DonorName);
+ Assert.Equal("4500, boulevard Saint-Laurent", issued.DonorAddress);
+ Assert.Equal("H2T 1R2", issued.DonorPostalCode);
+ Assert.Equal(new DateTimeOffset(2026, 11, 7, 15, 0, 0, TimeSpan.Zero), issued.IssuedAt);
+ Assert.Equal(0m, issued.AdvantageAmount);
+ var line = Assert.Single(issued.Items);
+ Assert.Equal("Pain", line.Description);
+ Assert.Equal(new DateOnly(2026, 11, 3), line.DonationDate);
+ Assert.Null(approved.DonorName);
+ Assert.Null(approved.IssuedAt);
+ Assert.Null(Assert.Single(approved.Items).Description);
+ }
+
+ private MoissonDbContext CreateContext(string database)
+ {
+ var builder = new DbConnectionStringBuilder { ConnectionString = postgres.ConnectionString };
+ builder["Database"] = database;
+ return new MoissonDbContext(new DbContextOptionsBuilder().UseNpgsql(builder.ConnectionString).Options);
+ }
+}
diff --git a/tests/MoissonMontreal.Tests/Api/ReceiptNumberMigrationTests.cs b/tests/MoissonMontreal.Tests/Api/ReceiptNumberMigrationTests.cs
index 46dcbc0..3b02960 100644
--- a/tests/MoissonMontreal.Tests/Api/ReceiptNumberMigrationTests.cs
+++ b/tests/MoissonMontreal.Tests/Api/ReceiptNumberMigrationTests.cs
@@ -143,6 +143,8 @@ private async Task AddReceiptAsync(ReceiptStatus status, string? number =
TotalAmount = 44.97m,
Status = status,
ReceiptNumber = number,
+ IssuedAt = number is null ? null : DateTimeOffset.UtcNow,
+ DonorName = number is null ? null : "Boulangerie Saint-Laurent",
};
private MoissonDbContext CreateContext(string? database = null)
diff --git a/tests/MoissonMontreal.Tests/Api/ReceiptNumberingEndpointTests.cs b/tests/MoissonMontreal.Tests/Api/ReceiptNumberingEndpointTests.cs
index 516955a..a831e5e 100644
--- a/tests/MoissonMontreal.Tests/Api/ReceiptNumberingEndpointTests.cs
+++ b/tests/MoissonMontreal.Tests/Api/ReceiptNumberingEndpointTests.cs
@@ -163,11 +163,24 @@ private async Task PostAsync(Guid receiptId, string action,
private async Task CreateReceiptAsync(ReceiptStatus status)
{
await using var context = factory.CreateDbContext();
+ var donor = TestDonors.Complete();
+ var bread = new FoodItem
+ {
+ Donor = donor,
+ Name = "Pain",
+ Quantity = 12.50m,
+ Unit = "kg",
+ DonationDate = new DateOnly(2026, 11, 3),
+ Quality = "B",
+ };
+ context.FoodItems.Add(bread);
+ await context.SaveChangesAsync();
var receipt = new Receipt
{
- Donor = new Donor { Name = "Boulangerie Saint-Laurent" },
- TotalAmount = 44.97m,
+ DonorId = donor.Id,
+ TotalAmount = 37.50m,
Status = status,
+ Items = [new ReceiptItem { FoodItemId = bread.Id, Quantity = 12.50m, Unit = "kg", UnitPrice = 4.00m, QualityPercent = 75m }],
};
context.Receipts.Add(receipt);
await context.SaveChangesAsync();
diff --git a/tests/MoissonMontreal.Tests/Api/ReceiptStatusEndpointTests.cs b/tests/MoissonMontreal.Tests/Api/ReceiptStatusEndpointTests.cs
index 6a15ece..681e217 100644
--- a/tests/MoissonMontreal.Tests/Api/ReceiptStatusEndpointTests.cs
+++ b/tests/MoissonMontreal.Tests/Api/ReceiptStatusEndpointTests.cs
@@ -381,7 +381,7 @@ private async Task UserIdAsync(Employee employee)
private async Task<(Guid ReceiptId, Guid DonorId, Guid FoodItemId)> CreateReceiptWithAFoodItemAsync()
{
await using var context = factory.CreateDbContext();
- var donor = new Donor { Name = "Boulangerie Saint-Laurent" };
+ var donor = TestDonors.Complete();
var bread = new FoodItem
{
Donor = donor,
@@ -408,14 +408,7 @@ private async Task UserIdAsync(Employee employee)
QualityPercent = 75m,
};
- private async Task CreateReceiptAsync()
- {
- await using var context = factory.CreateDbContext();
- var receipt = new Receipt { Donor = new Donor { Name = "Boulangerie Saint-Laurent" }, TotalAmount = 44.97m };
- context.Receipts.Add(receipt);
- await context.SaveChangesAsync();
- return receipt.Id;
- }
+ private async Task CreateReceiptAsync() => (await CreateReceiptWithAFoodItemAsync()).ReceiptId;
private async Task StatusOfAsync(Guid receiptId)
{
diff --git a/tests/MoissonMontreal.Tests/Fixtures/BackupTestData.sql b/tests/MoissonMontreal.Tests/Fixtures/BackupTestData.sql
index d1abee2..16de614 100644
--- a/tests/MoissonMontreal.Tests/Fixtures/BackupTestData.sql
+++ b/tests/MoissonMontreal.Tests/Fixtures/BackupTestData.sql
@@ -6,9 +6,10 @@ INSERT INTO users (email, display_name, role_id)
SELECT 'employee' || i || '@example.org', 'Employee ' || i, i % 4 + 1
FROM generate_series(1, 20) AS i;
-INSERT INTO donors (id, name, type, business_central_code, city, notes)
+INSERT INTO donors (id, name, search_name, type, business_central_code, city, notes)
SELECT md5('donor' || i)::uuid,
'Donor ' || i,
+ 'donor ' || i,
CASE WHEN i % 3 = 0 THEN 'individual' ELSE 'organization' END,
'D' || lpad(i::text, 6, '0'),
'Montréal',
@@ -33,13 +34,14 @@ SELECT 'BCX' || i, 'Created', md5('catalog' || i)::uuid, (SELECT min(id) FROM us
FROM generate_series(1, 500) AS i;
-- One receipt in four is issued and gets a receipt number; the others are at an earlier status.
-INSERT INTO receipts (id, donor_id, total_amount, receipt_date, status, receipt_number)
+-- The issued ones are inserted as Approved and issued once their lines are added, below, because the database refuses
+-- any new line on a receipt that has a number.
+INSERT INTO receipts (id, donor_id, total_amount, receipt_date, status)
SELECT md5('receipt' || r)::uuid,
md5('donor' || ((r - 1) % 2000 + 1))::uuid,
round((r * 37 % 100000) / 100.0, 2),
DATE '2026-01-01' + r % 300,
- (ARRAY['Issued', 'Draft', 'PendingFinanceApproval', 'Approved'])[r % 4 + 1],
- CASE WHEN r % 4 = 0 THEN 'DEN_' || lpad((r / 4)::text, 6, '0') END
+ (ARRAY['Approved', 'Draft', 'PendingFinanceApproval', 'Approved'])[r % 4 + 1]
FROM generate_series(1, 10000) AS r;
UPDATE receipt_number_counters SET last_number = 2500 WHERE series = 'DEN';
@@ -69,3 +71,23 @@ SELECT md5('receipt' || ((f - 1) / 5 + 1))::uuid,
round((f % 500 + 1) / 100.0 + 0.99, 2),
(ARRAY[100, 50, 0])[f % 3 + 1]
FROM generate_series(1, 50000) AS f;
+
+-- Issue one receipt in four: copy the description and date of its food items onto its lines, then give it its number
+-- and freeze the donor's name and address on it, as the API does.
+UPDATE receipt_items AS i
+SET description = f.name, donation_date = f.donation_date
+FROM food_items AS f
+WHERE f.id = i.food_item_id
+ AND i.receipt_id IN (SELECT md5('receipt' || r)::uuid FROM generate_series(4, 10000, 4) AS r);
+
+UPDATE receipts AS rc
+SET status = 'Issued',
+ receipt_number = 'DEN_' || lpad((n.r / 4)::text, 6, '0'),
+ issued_at = TIMESTAMPTZ '2026-11-01 12:00:00+00',
+ donor_name = d.name,
+ donor_address = d.address,
+ donor_city = d.city,
+ donor_province = d.province,
+ donor_postal_code = d.postal_code
+FROM generate_series(4, 10000, 4) AS n(r), donors AS d
+WHERE rc.id = md5('receipt' || n.r)::uuid AND d.id = rc.donor_id;
diff --git a/tests/MoissonMontreal.Tests/Fixtures/PdfText.cs b/tests/MoissonMontreal.Tests/Fixtures/PdfText.cs
new file mode 100644
index 0000000..7ade6ff
--- /dev/null
+++ b/tests/MoissonMontreal.Tests/Fixtures/PdfText.cs
@@ -0,0 +1,44 @@
+using System.Text;
+using System.Text.RegularExpressions;
+using UglyToad.PdfPig;
+using UglyToad.PdfPig.DocumentLayoutAnalysis.TextExtractor;
+
+namespace MoissonMontreal.Tests.Fixtures;
+
+///
+/// Reads a PDF the way a person or a search tool would: the text of each page, with every run of spaces, line breaks and
+/// no-break spaces made one space, and the size of each page in points.
+///
+public sealed partial class PdfText
+{
+ private PdfText(IReadOnlyList pages, IReadOnlyList<(double Width, double Height)> sizes, bool fontsEmbedded)
+ {
+ Pages = pages;
+ PageSizes = sizes;
+ FontsEmbedded = fontsEmbedded;
+ }
+
+ public IReadOnlyList Pages { get; }
+
+ public IReadOnlyList<(double Width, double Height)> PageSizes { get; }
+
+ public bool FontsEmbedded { get; }
+
+ public string All => string.Join(" ", Pages);
+
+ public static PdfText Read(byte[] pdf)
+ {
+ using var document = PdfDocument.Open(pdf);
+ var pages = document.GetPages().ToList();
+ var raw = Encoding.Latin1.GetString(pdf);
+ return new PdfText(
+ [.. pages.Select(p => Normalize(ContentOrderTextExtractor.GetText(p)))],
+ [.. pages.Select(p => (p.Width, p.Height))],
+ raw.Contains("/FontFile", StringComparison.Ordinal));
+ }
+
+ public static string Normalize(string text) => Spaces().Replace(text, " ").Trim();
+
+ [GeneratedRegex(@"[\s ]+")]
+ private static partial Regex Spaces();
+}
diff --git a/tests/MoissonMontreal.Tests/Fixtures/PermissionsApiFactory.cs b/tests/MoissonMontreal.Tests/Fixtures/PermissionsApiFactory.cs
index 6d538d8..ba22245 100644
--- a/tests/MoissonMontreal.Tests/Fixtures/PermissionsApiFactory.cs
+++ b/tests/MoissonMontreal.Tests/Fixtures/PermissionsApiFactory.cs
@@ -29,6 +29,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.UseSetting("ConnectionStrings:Moisson", _postgres.ConnectionString);
+ TestReceiptIssuer.Apply(builder);
builder.ConfigureTestServices(services => services
.AddControllers()
.AddApplicationPart(typeof(PermissionTestController).Assembly));
diff --git a/tests/MoissonMontreal.Tests/Fixtures/TestDonors.cs b/tests/MoissonMontreal.Tests/Fixtures/TestDonors.cs
new file mode 100644
index 0000000..2c66ab0
--- /dev/null
+++ b/tests/MoissonMontreal.Tests/Fixtures/TestDonors.cs
@@ -0,0 +1,18 @@
+using MoissonMontreal.Core.Entities;
+
+namespace MoissonMontreal.Tests.Fixtures;
+
+///
+/// Donors with everything a tax receipt needs.
+///
+public static class TestDonors
+{
+ public static Donor Complete(string name = "Boulangerie Saint-Laurent") => new()
+ {
+ Name = name,
+ Address = "4500, boulevard Saint-Laurent",
+ City = "Montréal",
+ Province = "QC",
+ PostalCode = "H2T 1R2",
+ };
+}
diff --git a/tests/MoissonMontreal.Tests/Fixtures/TestReceiptIssuer.cs b/tests/MoissonMontreal.Tests/Fixtures/TestReceiptIssuer.cs
new file mode 100644
index 0000000..db9299d
--- /dev/null
+++ b/tests/MoissonMontreal.Tests/Fixtures/TestReceiptIssuer.cs
@@ -0,0 +1,50 @@
+using Microsoft.AspNetCore.Hosting;
+using MoissonMontreal.Core.Receipts;
+
+namespace MoissonMontreal.Tests.Fixtures;
+
+///
+/// Organization settings used by the tests. They are made up: the real values come from Moisson Montréal.
+///
+public static class TestReceiptIssuer
+{
+ public const string LegalName = "Organisme Test Montréal";
+ public const string Address = "1234, rue de l'Église";
+ public const string City = "Montréal";
+ public const string Province = "QC";
+ public const string PostalCode = "H1A 1A1";
+ public const string RegistrationNumber = "123456789 RR 0001";
+ public const string PlaceOfIssue = "Montréal (Québec)";
+ public const string SignatoryName = "Hélène Côté";
+ public const string SignatoryTitle = "Directrice des finances";
+
+ public static ReceiptIssuer Create() => new()
+ {
+ LegalName = LegalName,
+ Address = Address,
+ City = City,
+ Province = Province,
+ PostalCode = PostalCode,
+ RegistrationNumber = RegistrationNumber,
+ PlaceOfIssue = PlaceOfIssue,
+ SignatoryName = SignatoryName,
+ SignatoryTitle = SignatoryTitle,
+ };
+
+ ///
+ /// Gives the API host the test organization settings.
+ ///
+ public static void Apply(IWebHostBuilder builder)
+ {
+ var issuer = Create();
+ builder.UseSetting($"{ReceiptIssuer.SectionName}:{nameof(ReceiptIssuer.LegalName)}", issuer.LegalName);
+ builder.UseSetting($"{ReceiptIssuer.SectionName}:{nameof(ReceiptIssuer.Address)}", issuer.Address);
+ builder.UseSetting($"{ReceiptIssuer.SectionName}:{nameof(ReceiptIssuer.City)}", issuer.City);
+ builder.UseSetting($"{ReceiptIssuer.SectionName}:{nameof(ReceiptIssuer.Province)}", issuer.Province);
+ builder.UseSetting($"{ReceiptIssuer.SectionName}:{nameof(ReceiptIssuer.PostalCode)}", issuer.PostalCode);
+ builder.UseSetting($"{ReceiptIssuer.SectionName}:{nameof(ReceiptIssuer.RegistrationNumber)}", issuer.RegistrationNumber);
+ builder.UseSetting($"{ReceiptIssuer.SectionName}:{nameof(ReceiptIssuer.PlaceOfIssue)}", issuer.PlaceOfIssue);
+ builder.UseSetting($"{ReceiptIssuer.SectionName}:{nameof(ReceiptIssuer.SignatoryName)}", issuer.SignatoryName);
+ builder.UseSetting($"{ReceiptIssuer.SectionName}:{nameof(ReceiptIssuer.SignatoryTitle)}", issuer.SignatoryTitle);
+ }
+}
diff --git a/tests/MoissonMontreal.Tests/MoissonMontreal.Tests.csproj b/tests/MoissonMontreal.Tests/MoissonMontreal.Tests.csproj
index 4c752b6..f0d8a7a 100644
--- a/tests/MoissonMontreal.Tests/MoissonMontreal.Tests.csproj
+++ b/tests/MoissonMontreal.Tests/MoissonMontreal.Tests.csproj
@@ -12,6 +12,7 @@
+
diff --git a/tests/MoissonMontreal.Tests/Receipts/ReceiptIssueCheckTests.cs b/tests/MoissonMontreal.Tests/Receipts/ReceiptIssueCheckTests.cs
new file mode 100644
index 0000000..1c87e21
--- /dev/null
+++ b/tests/MoissonMontreal.Tests/Receipts/ReceiptIssueCheckTests.cs
@@ -0,0 +1,77 @@
+using MoissonMontreal.Core.Receipts;
+using MoissonMontreal.Tests.Fixtures;
+
+namespace MoissonMontreal.Tests.Receipts;
+
+public class ReceiptIssueCheckTests
+{
+ private static readonly ReceiptDonor CompleteDonor = new("Boulangerie Saint-Éloi", "4500, boulevard Saint-Laurent", "Montréal", "QC", "H2T 1R2");
+
+ private static readonly ReceiptDocumentLine Bread = new("Pain", new DateOnly(2026, 11, 3), 12.50m, "kg", 4.00m, 75m, 37.50m);
+
+ [Fact]
+ public void CompleteReceipt_HasNoProblem()
+ {
+ Assert.Empty(ReceiptIssueCheck.FindProblems(TestReceiptIssuer.Create(), CompleteDonor, [Bread], 37.50m, 0m));
+ }
+
+ [Fact]
+ public void IncompleteDonorAddress_IsRefused_WithTheMissingParts()
+ {
+ var donor = CompleteDonor with { Address = " ", PostalCode = null };
+
+ var problems = ReceiptIssueCheck.FindProblems(TestReceiptIssuer.Create(), donor, [Bread], 37.50m, 0m);
+
+ var problem = Assert.Single(problems);
+ Assert.Contains("the street address and postal code are missing", problem);
+ Assert.Contains("Complete the donor profile", problem);
+ }
+
+ [Fact]
+ public void MissingOrganizationSetting_IsRefused_WithTheSettingToFill()
+ {
+ var issuer = TestReceiptIssuer.Create();
+ issuer.RegistrationNumber = "";
+
+ var problems = ReceiptIssueCheck.FindProblems(issuer, CompleteDonor, [Bread], 37.50m, 0m);
+
+ Assert.Equal(["The charity registration number is not configured. Set ReceiptIssuer:RegistrationNumber in the API settings."], problems);
+ }
+
+ [Fact]
+ public void AppraiserWithoutAddress_IsRefused()
+ {
+ var issuer = TestReceiptIssuer.Create();
+ issuer.AppraiserName = "Évaluations Gagnon inc.";
+
+ var problems = ReceiptIssueCheck.FindProblems(issuer, CompleteDonor, [Bread], 37.50m, 0m);
+
+ Assert.Contains(problems, p => p.Contains("ReceiptIssuer:AppraiserAddress", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ReceiptWithoutFoodItems_IsRefused()
+ {
+ var problems = ReceiptIssueCheck.FindProblems(TestReceiptIssuer.Create(), CompleteDonor, [], 0m, 0m);
+
+ Assert.Contains(problems, p => p.StartsWith("The receipt has no food item", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void TotalThatDoesNotMatchTheLines_IsRefused()
+ {
+ var problems = ReceiptIssueCheck.FindProblems(TestReceiptIssuer.Create(), CompleteDonor, [Bread], 44.97m, 0m);
+
+ Assert.Equal(
+ ["The total of the receipt ($44.97) does not match the sum of its food items ($37.50). Recalculate the receipt before issuing it."],
+ problems);
+ }
+
+ [Fact]
+ public void AdvantageLargerThanTheTotal_IsRefused()
+ {
+ var problems = ReceiptIssueCheck.FindProblems(TestReceiptIssuer.Create(), CompleteDonor, [Bread], 37.50m, 40m);
+
+ Assert.Contains(problems, p => p.StartsWith("The advantage ($40.00)", StringComparison.Ordinal));
+ }
+}
diff --git a/tests/MoissonMontreal.Tests/Receipts/ReceiptPdfRendererTests.cs b/tests/MoissonMontreal.Tests/Receipts/ReceiptPdfRendererTests.cs
new file mode 100644
index 0000000..0f3d6f3
--- /dev/null
+++ b/tests/MoissonMontreal.Tests/Receipts/ReceiptPdfRendererTests.cs
@@ -0,0 +1,268 @@
+using MoissonMontreal.Api.Receipts;
+using MoissonMontreal.Core.Receipts;
+using MoissonMontreal.Tests.Fixtures;
+
+namespace MoissonMontreal.Tests.Receipts;
+
+// The wording below is written again on purpose instead of reading ReceiptMentions, so a mention removed or changed by
+// mistake in the code makes a test fail. The list must be validated with Moisson Montréal and the CRA documentation:
+// see docs/receipts/tax-receipt-pdf.md.
+public class ReceiptPdfRendererTests
+{
+ private const double LetterWidth = 612;
+ private const double LetterHeight = 792;
+
+ private static readonly DateOnly November3 = new(2026, 11, 3);
+ private static readonly DateOnly November10 = new(2026, 11, 10);
+ private static readonly DateOnly November30 = new(2026, 11, 30);
+
+ public static TheoryData MandatoryMentions => new()
+ {
+ { "official receipt statement (fr)", "Reçu officiel aux fins de l'impôt sur le revenu" },
+ { "official receipt statement (en)", "Official receipt for income tax purposes" },
+ { "organization name", TestReceiptIssuer.LegalName },
+ { "organization address", TestReceiptIssuer.Address },
+ { "organization city and postal code", $"{TestReceiptIssuer.City} ({TestReceiptIssuer.Province}) {TestReceiptIssuer.PostalCode}" },
+ { "registration number label", "Numéro d'enregistrement de l'organisme de bienfaisance" },
+ { "registration number", TestReceiptIssuer.RegistrationNumber },
+ { "serial number label", "Reçu n°" },
+ { "serial number", "DEN_000123" },
+ { "place of issue label", "Lieu de délivrance" },
+ { "place of issue", TestReceiptIssuer.PlaceOfIssue },
+ { "donation date label", "Date de réception du don" },
+ { "donation dates", "2026-11-03 au / to 2026-11-10" },
+ { "issue date label", "Date de délivrance du reçu" },
+ { "issue date", "2026-11-30" },
+ { "donor label", "Nom et adresse du donateur" },
+ { "donor name", "Boulangerie Saint-Éloi" },
+ { "donor address", "4500, boulevard Saint-Laurent" },
+ { "donor city and postal code", "Montréal (QC) H2T 1R2" },
+ { "description label", "Description des biens reçus" },
+ { "description of a line", "Pain de blé entier" },
+ { "fair market value label", "Juste valeur marchande des biens reçus" },
+ { "fair market value", "1 044,97 $" },
+ { "advantage label", "Montant de l'avantage" },
+ { "advantage", "0,00 $" },
+ { "eligible amount label", "Montant admissible du don aux fins de l'impôt" },
+ { "signature label", "Signature autorisée" },
+ { "signatory", TestReceiptIssuer.SignatoryName },
+ { "CRA name", "Agence du revenu du Canada" },
+ { "CRA website", "canada.ca/charities-giving" },
+ };
+
+ [Theory]
+ [MemberData(nameof(MandatoryMentions))]
+ public void OfficialReceipt_ShowsEveryMandatoryMention(string mention, string expected)
+ {
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(Official()));
+
+ Assert.True(text.All.Contains(expected, StringComparison.Ordinal), $"The {mention} \"{expected}\" is missing from:\n{text.All}");
+ }
+
+ [Fact]
+ public void Appraiser_IsShown_OnlyWhenThereIsOne()
+ {
+ var withoutAppraiser = PdfText.Read(ReceiptPdfRenderer.Render(Official()));
+ var issuer = TestReceiptIssuer.Create();
+ issuer.AppraiserName = "Évaluations Gagnon inc.";
+ issuer.AppraiserAddress = "10, rue Sainte-Catherine, Montréal";
+ var withAppraiser = PdfText.Read(ReceiptPdfRenderer.Render(Official() with { Issuer = issuer }));
+
+ Assert.DoesNotContain("Évaluateur", withoutAppraiser.All);
+ Assert.Contains("Évaluateur / Appraiser", withAppraiser.All);
+ Assert.Contains("Évaluations Gagnon inc., 10, rue Sainte-Catherine, Montréal", withAppraiser.All);
+ }
+
+ [Fact]
+ public void Advantage_IsSubtracted_FromTheEligibleAmount()
+ {
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(Official() with { AdvantageAmount = 44.97m }));
+
+ Assert.Contains("44,97 $", text.All);
+ Assert.Contains("1 000,00 $", text.All);
+ }
+
+ [Fact]
+ public void Pdf_IsOnLetterPaper_WithEmbeddedFonts()
+ {
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(Official()));
+
+ Assert.All(text.PageSizes, size => Assert.Equal((LetterWidth, LetterHeight), size));
+ Assert.True(text.FontsEmbedded, "The fonts must be embedded so the receipt prints the same everywhere.");
+ }
+
+ [Fact]
+ public void AccentsAndSpecialCharacters_AreKept()
+ {
+ var special = "Crème brûlée & œufs « bio » à 50 % (Ç, É, À, Ô, Ï, Ù, ë)";
+ var receipt = Official() with { Lines = [Line(special, November3, 1m, 10m)], FairMarketValue = 10m };
+
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(receipt));
+
+ Assert.Contains(special, text.All);
+ }
+
+ [Fact]
+ public void ManyLines_ContinueOnMorePages_AllOnLetterPaper_WithTheTotalsAfterTheLastLine()
+ {
+ var lines = Enumerable.Range(1, 120)
+ .Select(i => Line($"Article de test numéro {i:000}", November3, 1m, 1m))
+ .ToList();
+ var receipt = Official() with { Lines = lines, FairMarketValue = 120m };
+
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(receipt));
+
+ Assert.True(text.Pages.Count > 1, "120 lines must not fit on one page.");
+ Assert.All(text.PageSizes, size => Assert.Equal((LetterWidth, LetterHeight), size));
+ Assert.All(Enumerable.Range(1, 120), i => Assert.Contains($"Article de test numéro {i:000}", text.All));
+ Assert.All(text.Pages, page => Assert.Contains("DEN_000123", page));
+ Assert.All(
+ text.Pages.Where(page => page.Contains("Article de test", StringComparison.Ordinal)),
+ page => Assert.Contains("Description Description", page));
+ Assert.Contains($"Page {text.Pages.Count} / {text.Pages.Count}", text.Pages[^1]);
+ Assert.True(
+ text.All.IndexOf("Montant admissible du don", StringComparison.Ordinal) > text.All.IndexOf("Article de test numéro 120", StringComparison.Ordinal),
+ "The totals must come after the last line.");
+ Assert.Contains("120,00 $", text.All);
+ Assert.Contains("Signature autorisée", text.Pages[^1]);
+ }
+
+ [Fact]
+ public void LongNamesAndDescriptions_Wrap_WithoutLosingText()
+ {
+ var longName = string.Join(" ", Enumerable.Repeat("Coopérative alimentaire régionale", 7));
+ var longWord = new string('é', 255);
+ var longDescription = string.Join(" ", Enumerable.Repeat("Légumes variés", 18));
+ var receipt = Official() with
+ {
+ Donor = Official().Donor with { Name = longName },
+ Lines = [Line(longDescription, November3, 1m, 5m), Line(longWord, November3, 1m, 5m)],
+ FairMarketValue = 10m,
+ };
+
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(receipt));
+
+ var compact = text.All.Replace(" ", string.Empty, StringComparison.Ordinal);
+ Assert.Contains(longName.Replace(" ", string.Empty, StringComparison.Ordinal), compact);
+ Assert.Contains(longDescription.Replace(" ", string.Empty, StringComparison.Ordinal), compact);
+ Assert.Contains(longWord, compact);
+ }
+
+ [Fact]
+ public void ReplacementReceipt_StatesWhichReceiptItReplaces()
+ {
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(Official() with { ReplacedReceiptNumber = "DEN_000045" }));
+
+ Assert.Contains("Ce reçu annule et remplace le reçu n° DEN_000045", text.All);
+ Assert.Contains("This receipt cancels and replaces receipt No. DEN_000045", text.All);
+ }
+
+ [Fact]
+ public void CancelledReceipt_SaysItIsNotValid()
+ {
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(Official() with { Kind = ReceiptDocumentKind.Cancelled }));
+
+ Assert.Contains("REÇU ANNULÉ", text.All);
+ Assert.Contains("not valid for income tax purposes", text.All);
+ }
+
+ [Fact]
+ public void Preview_HasNoNumber_AndSaysItIsNotAReceipt()
+ {
+ var preview = Official() with { Kind = ReceiptDocumentKind.Preview, ReceiptNumber = null, IssueDate = null };
+
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(preview));
+
+ Assert.Contains("APERÇU : ce document n'est pas un reçu officiel", text.All);
+ Assert.Contains("à attribuer / to be assigned", text.All);
+ Assert.DoesNotContain("DEN_", text.All);
+ }
+
+ [Theory]
+ [InlineData("Pain 🍞")]
+ [InlineData("寿司")]
+ public void TextTheFontCannotPrint_IsRefused_NotDroppedSilently(string description)
+ {
+ var receipt = Official() with { Lines = [Line(description, November3, 1m, 10m)], FairMarketValue = 10m };
+
+ var e = Assert.Throws(() => ReceiptPdfRenderer.Render(receipt));
+
+ Assert.Equal(description, e.Text);
+ Assert.Contains($"The text \"{description}\" has characters the receipt cannot print", e.Message);
+ }
+
+ [Fact]
+ public void TypographicCharactersAndLineBreaks_AreKept()
+ {
+ var receipt = Official() with
+ {
+ Lines = [Line("Œufs € ½ – « bio » “frais” ’ …", November3, 1m, 10m), Line("Ligne\tavec\nsaut", November3, 1m, 10m)],
+ FairMarketValue = 20m,
+ };
+
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(receipt));
+
+ Assert.Contains("Œufs € ½ – « bio » “frais” ’ …", text.All);
+ Assert.Contains("Ligne avec saut", text.All);
+ }
+
+ [Fact]
+ public void ZeroValueReceipt_IsPrinted_WithZeroAmounts()
+ {
+ var receipt = Official() with { Lines = [Line("Pain de grade C", November3, 10m, 4m, 0m)], FairMarketValue = 0m };
+
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(receipt));
+
+ Assert.Contains("Pain de grade C", text.All);
+ Assert.Contains("0 %", text.All);
+ }
+
+ [Fact]
+ public void SingleDonationDay_IsPrintedOnce()
+ {
+ var receipt = Official() with { Lines = [Line("Pain", November3, 1m, 10m), Line("Lait", November3, 1m, 10m)], FairMarketValue = 20m };
+
+ var text = PdfText.Read(ReceiptPdfRenderer.Render(receipt));
+
+ Assert.Contains("Date the gift was received : 2026-11-03", text.All);
+ Assert.DoesNotContain("au / to", text.All);
+ }
+
+ [Theory]
+ [InlineData("2026-12-31T04:59:59Z", "2026-12-30")]
+ [InlineData("2026-12-31T05:00:00Z", "2026-12-31")]
+ [InlineData("2027-01-01T03:00:00Z", "2026-12-31")]
+ [InlineData("2026-07-01T03:59:59Z", "2026-06-30")]
+ public void IssueDate_IsTheDayInMontreal_NotInUtc(string utc, string expected)
+ {
+ Assert.Equal(DateOnly.Parse(expected), ReceiptDocumentService.ToMontrealDate(DateTimeOffset.Parse(utc)));
+ }
+
+ [Theory]
+ [InlineData(0, "0,00 $")]
+ [InlineData(0.23, "0,23 $")]
+ [InlineData(1234.5, "1 234,50 $")]
+ [InlineData(1234567.89, "1 234 567,89 $")]
+ public void FormatMoney_UsesTheQuebecFormat(decimal amount, string expected)
+ {
+ Assert.Equal(expected, PdfText.Normalize(ReceiptPdfRenderer.FormatMoney(amount)));
+ }
+
+ private static ReceiptDocument Official() => new(
+ ReceiptDocumentKind.Official,
+ TestReceiptIssuer.Create(),
+ "DEN_000123",
+ November30,
+ new ReceiptDonor("Boulangerie Saint-Éloi", "4500, boulevard Saint-Laurent", "Montréal", "QC", "H2T 1R2"),
+ [
+ Line("Pain de blé entier", November3, 12.50m, 4.00m, 75m),
+ Line("Pommes Cortland (caisse)", November10, 3m, 2.49m, 100m),
+ Line("Fromage cheddar québécois", November10, 100m, 10.00m, 100m),
+ ],
+ 1044.97m,
+ 0m,
+ null);
+
+ private static ReceiptDocumentLine Line(string description, DateOnly date, decimal quantity, decimal unitPrice, decimal percent = 100m) =>
+ new(description, date, quantity, "kg", unitPrice, percent, Math.Round(quantity * unitPrice * percent / 100m, 2, MidpointRounding.AwayFromZero));
+}