diff --git a/docs/auth/roles-permissions.md b/docs/auth/roles-permissions.md
index 53152f7..2ed47d6 100644
--- a/docs/auth/roles-permissions.md
+++ b/docs/auth/roles-permissions.md
@@ -53,11 +53,11 @@ The department names above come from the PRD. The admin chooses the role that ma
| --- | --- |
| The employee is not signed in, or their session expired | 401: the app asks them to sign in |
| The employee's role does not allow the action | 403: access refused |
-| The employee signed in with Microsoft but was never added to the app | 403 for every protected action |
-| The admin removed the employee's access | 403 for every protected action, even for a former Admin |
-| The employee's account is already linked to another Microsoft account | 403 for every protected action |
+| The employee signed in with Microsoft but was never added to the app | 403 for every action |
+| The admin removed the employee's access | 403 for every action, even for a former Admin |
+| The employee's account is already linked to another Microsoft account | 403 for every action |
-The first time an employee does an action that requires a permission, their Microsoft account is linked to the account the admin created with their email. After that, the app recognizes them by their Microsoft account, even if their email changes. An account whose access was removed can still be linked, but the API keeps refusing its actions.
+The first time the employee uses the app after signing in, their Microsoft account is linked to the account the admin created with their email. After that, the app recognizes them by their Microsoft account, even if their email changes. An account whose access was removed can still be linked, but the API keeps refusing its actions.
If the employee's Microsoft account is recreated (for example, IT deleted and recreated it), the app no longer recognizes them and refuses all their actions. The app cannot reset this link yet (see Open points).
@@ -89,9 +89,11 @@ Use the constants in `Permissions`, never a role name. The roles allowed for eac
| `PermissionHandler` | `src/MoissonMontreal.Api/Authorization/` | Allows the request when the employee's role is in the list, otherwise the API answers 403 |
| `UserLookupService` | `src/MoissonMontreal.Api/Authorization/` | Finds the employee's active account in the `users` table and links it at the first permission check |
-The role is read from the database only when an endpoint requires a permission. Endpoints such as `/health` and `api/me` do not read it.
+The default policy, set in `src/MoissonMontreal.Api/Program.cs`, also requires an active account with any role (`RoleCodes.All`). So an endpoint without a permission still refuses a deactivated or never-added employee.
-The Microsoft account is linked by `UserLookupService`, called from `PermissionHandler`, the first time the employee calls an endpoint that requires a permission. Signing in or calling `/api/me` does not link the account, so `entra_object_id` can still be empty after a sign-in.
+Every endpoint reads the employee's account and role from the database, except `/health`. `api/me` returns the role, so the desktop app can show only what the employee is allowed to use.
+
+The Microsoft account is linked by `UserLookupService`, called from `PermissionHandler`, the first time the employee calls any endpoint, usually `/api/me` right after signing in.
### Tests
diff --git a/docs/database/images/schema.png b/docs/database/images/schema.png
index 340f943..c11ea35 100644
Binary files a/docs/database/images/schema.png and b/docs/database/images/schema.png differ
diff --git a/docs/database/images/users-roles.png b/docs/database/images/users-roles.png
index 1656371..2bb839d 100644
Binary files a/docs/database/images/users-roles.png and b/docs/database/images/users-roles.png differ
diff --git a/docs/database/schema.dbml b/docs/database/schema.dbml
index 62c91a8..e43ae08 100644
--- a/docs/database/schema.dbml
+++ b/docs/database/schema.dbml
@@ -3,8 +3,9 @@
// Matches the migrations 20261103000127_CreateUsersAndRoles, 20261105163138_CreateDonorsAndFoodItems,
// 20261107041912_CreateReceipts, 20261110175320_CreateCatalogItemsAndPrices,
// 20261112060008_CreateQualityClasses, 20261117040905_AddCatalogItemDetails,
-// 20261120031640_MakeCatalogItemQualityClassOptional, 20261124214039_AddBcItemMappings, 20261127052039_AddReceiptStatus
-// 20261127053347_AddReceiptNumbers, 20261128005314_AddDonorProfile and 20261128222105_AddDonorListSearch.
+// 20261120031640_MakeCatalogItemQualityClassOptional, 20261124214039_AddBcItemMappings, 20261127052039_AddReceiptStatus,
+// 20261127053347_AddReceiptNumbers, 20261128005314_AddDonorProfile, 20261128222105_AddDonorListSearch
+// and 20261204061822_AddUserAccountChanges.
Project moisson_montreal {
database_type: 'PostgreSQL'
@@ -49,6 +50,32 @@ Table users {
Note: 'Employees allowed to use the app'
}
+Table user_account_changes {
+ id uuid [not null, default: `gen_random_uuid()`]
+ user_id integer [not null, note: 'Account that was changed']
+ action varchar(20) [not null, note: 'Created, Updated, RoleChanged, Deactivated or Reactivated']
+ old_email varchar(256) [null, note: 'Empty when the action did not touch the email']
+ new_email varchar(256) [null]
+ old_display_name varchar(200) [null, note: 'Empty when the action did not touch the name']
+ new_display_name varchar(200) [null]
+ old_role_id integer [null, note: 'Empty when the action did not touch the role']
+ new_role_id integer [null]
+ old_is_active boolean [null, note: 'Empty when the action did not touch the access']
+ new_is_active boolean [null]
+ changed_by_user_id integer [not null, note: 'Administrator who made the change']
+ changed_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
+
+ indexes {
+ id [pk, name: 'pk_user_account_changes']
+ user_id [name: 'ix_user_account_changes_user_id']
+ changed_by_user_id [name: 'ix_user_account_changes_changed_by_user_id']
+ old_role_id [name: 'ix_user_account_changes_old_role_id']
+ new_role_id [name: 'ix_user_account_changes_new_role_id']
+ }
+
+ Note: 'History of every change made to an account, with the before and after values. Only the values the action touched are filled'
+}
+
Table donors {
id uuid [not null, default: `gen_random_uuid()`]
name varchar(255) [not null, note: 'Full name of a person, or name of an organization']
@@ -316,6 +343,14 @@ Table bc_item_mapping_changes {
Ref fk_users_roles_role_id: users.role_id > roles.id [delete: restrict]
+Ref fk_user_account_changes_users_user_id: user_account_changes.user_id > users.id [delete: restrict]
+
+Ref fk_user_account_changes_users_changed_by_user_id: user_account_changes.changed_by_user_id > users.id [delete: restrict]
+
+Ref fk_user_account_changes_roles_old_role_id: user_account_changes.old_role_id > roles.id [delete: restrict]
+
+Ref fk_user_account_changes_roles_new_role_id: user_account_changes.new_role_id > roles.id [delete: restrict]
+
Ref fk_food_items_donors_donor_id: food_items.donor_id > donors.id [delete: restrict]
Ref fk_food_items_catalog_items_catalog_item_id: food_items.catalog_item_id > catalog_items.id [delete: restrict]
@@ -349,6 +384,7 @@ Ref fk_bc_item_mapping_changes_users_changed_by_user_id: bc_item_mapping_changes
TableGroup accounts {
roles
users
+ user_account_changes
}
TableGroup donations {
diff --git a/docs/database/schema.md b/docs/database/schema.md
index 2f6cb1b..a165050 100644
--- a/docs/database/schema.md
+++ b/docs/database/schema.md
@@ -6,7 +6,7 @@ The database has four parts:
| Part | Tables | What it holds |
| --- | --- | --- |
-| Accounts | roles, users | Who can use the app and what each person is allowed to do |
+| Accounts | roles, users, user_account_changes | Who can use the app, what each person is allowed to do, and every change made to their access |
| Donations | donors, food_items, quality_classes | Who gave food, what they gave, when, and in what condition |
| Tax receipts | receipts, receipt_items, receipt_status_changes, receipt_number_counters | The receipts given to donors, the value of each food item on them, every change of their status, and their numbers |
| Price grid | catalog_items, prices, bc_item_mappings, bc_item_mapping_changes | The types of food the app knows, the price of each one over time, and which Business Central item each one values |
@@ -35,6 +35,12 @@ One row per employee who has access to the app: their work email, their name, th
More detail: [Users and roles](users-roles.md).
+### user_account_changes
+
+The history of every change an administrator made to an account: added, name or email edited, role changed, access removed or given back. Each row keeps who made the change, when, and the values before and after it.
+
+More detail: [Users and roles](users-roles.md).
+
### donors
The organizations and people who give food: name, type (individual or organization), street address, city, province, postal code, contact person, email, phone, notes and Business Central code. The name and the address are printed on the tax receipt. Two donors can have the same name, for example two branches of the same grocery chain, but two donors cannot share a Business Central code. A donor can be deactivated, which hides it from the donor list. Each donor also keeps its name without accents and in lowercase, which the search by name reads.
@@ -223,6 +229,7 @@ Each table comes from one of these migrations:
| receipt number, receipt_number_counters | [20261127053347_AddReceiptNumbers](../../src/MoissonMontreal.Api/Data/Migrations/20261127053347_AddReceiptNumbers.cs) | [0010_add_receipt_numbers.sql](sql/0010_add_receipt_numbers.sql) | [receipts.md](receipts.md) |
| donor profile | [20261128005314_AddDonorProfile](../../src/MoissonMontreal.Api/Data/Migrations/20261128005314_AddDonorProfile.cs) | [0011_add_donor_profile.sql](sql/0011_add_donor_profile.sql) | [donors.md](donors.md) |
| donor list and search | [20261128222105_AddDonorListSearch](../../src/MoissonMontreal.Api/Data/Migrations/20261128222105_AddDonorListSearch.cs) | [0012_add_donor_list_search.sql](sql/0012_add_donor_list_search.sql) | [donors.md](donors.md) |
+| user_account_changes | [20261204061822_AddUserAccountChanges](../../src/MoissonMontreal.Api/Data/Migrations/20261204061822_AddUserAccountChanges.cs) | [0013_add_user_account_changes.sql](sql/0013_add_user_account_changes.sql) | [users-roles.md](users-roles.md) |
The SQL scripts must be run in order on an empty database.
diff --git a/docs/database/sql/0013_add_user_account_changes.sql b/docs/database/sql/0013_add_user_account_changes.sql
new file mode 100644
index 0000000..6d2f4e3
--- /dev/null
+++ b/docs/database/sql/0013_add_user_account_changes.sql
@@ -0,0 +1,35 @@
+START TRANSACTION;
+CREATE TABLE user_account_changes (
+ id uuid NOT NULL DEFAULT (gen_random_uuid()),
+ user_id integer NOT NULL,
+ action character varying(20) NOT NULL,
+ old_email character varying(256),
+ new_email character varying(256),
+ old_display_name character varying(200),
+ new_display_name character varying(200),
+ old_role_id integer,
+ new_role_id integer,
+ old_is_active boolean,
+ new_is_active boolean,
+ changed_by_user_id integer NOT NULL,
+ changed_at timestamp with time zone NOT NULL DEFAULT (now()),
+ CONSTRAINT pk_user_account_changes PRIMARY KEY (id),
+ CONSTRAINT fk_user_account_changes_roles_new_role_id FOREIGN KEY (new_role_id) REFERENCES roles (id) ON DELETE RESTRICT,
+ CONSTRAINT fk_user_account_changes_roles_old_role_id FOREIGN KEY (old_role_id) REFERENCES roles (id) ON DELETE RESTRICT,
+ CONSTRAINT fk_user_account_changes_users_changed_by_user_id FOREIGN KEY (changed_by_user_id) REFERENCES users (id) ON DELETE RESTRICT,
+ CONSTRAINT fk_user_account_changes_users_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE RESTRICT
+);
+
+CREATE INDEX ix_user_account_changes_changed_by_user_id ON user_account_changes (changed_by_user_id);
+
+CREATE INDEX ix_user_account_changes_new_role_id ON user_account_changes (new_role_id);
+
+CREATE INDEX ix_user_account_changes_old_role_id ON user_account_changes (old_role_id);
+
+CREATE INDEX ix_user_account_changes_user_id ON user_account_changes (user_id);
+
+INSERT INTO "__EFMigrationsHistory" (migration_id, product_version)
+VALUES ('20261204061822_AddUserAccountChanges', '10.0.13');
+
+COMMIT;
+
diff --git a/docs/database/users-roles.dbml b/docs/database/users-roles.dbml
index db22dda..6e8beb1 100644
--- a/docs/database/users-roles.dbml
+++ b/docs/database/users-roles.dbml
@@ -1,6 +1,6 @@
// Users and roles
// Paste this file into https://dbdiagram.io to render the diagram.
-// Matches the migration 20261103000127_CreateUsersAndRoles.
+// Matches the migrations 20261103000127_CreateUsersAndRoles and 20261204061822_AddUserAccountChanges.
Table roles {
id integer [not null, note: 'Fixed values, inserted by the migration']
@@ -40,8 +40,42 @@ Table users {
Note: 'Employees allowed to use the app'
}
+Table user_account_changes {
+ id uuid [not null, default: `gen_random_uuid()`]
+ user_id integer [not null, note: 'Account that was changed']
+ action varchar(20) [not null, note: 'Created, Updated, RoleChanged, Deactivated or Reactivated']
+ old_email varchar(256) [null, note: 'Empty when the action did not touch the email']
+ new_email varchar(256) [null]
+ old_display_name varchar(200) [null, note: 'Empty when the action did not touch the name']
+ new_display_name varchar(200) [null]
+ old_role_id integer [null, note: 'Empty when the action did not touch the role']
+ new_role_id integer [null]
+ old_is_active boolean [null, note: 'Empty when the action did not touch the access']
+ new_is_active boolean [null]
+ changed_by_user_id integer [not null, note: 'Administrator who made the change']
+ changed_at timestamptz [not null, default: `now()`, note: 'Stored in UTC']
+
+ indexes {
+ id [pk, name: 'pk_user_account_changes']
+ user_id [name: 'ix_user_account_changes_user_id']
+ changed_by_user_id [name: 'ix_user_account_changes_changed_by_user_id']
+ old_role_id [name: 'ix_user_account_changes_old_role_id']
+ new_role_id [name: 'ix_user_account_changes_new_role_id']
+ }
+
+ Note: 'History of every change made to an account, with the before and after values. Only the values the action touched are filled'
+}
+
Ref fk_users_roles_role_id: users.role_id > roles.id [delete: restrict]
+Ref fk_user_account_changes_users_user_id: user_account_changes.user_id > users.id [delete: restrict]
+
+Ref fk_user_account_changes_users_changed_by_user_id: user_account_changes.changed_by_user_id > users.id [delete: restrict]
+
+Ref fk_user_account_changes_roles_old_role_id: user_account_changes.old_role_id > roles.id [delete: restrict]
+
+Ref fk_user_account_changes_roles_new_role_id: user_account_changes.new_role_id > roles.id [delete: restrict]
+
Records roles(id, code, name) {
1, 'Supply', 'Supply'
2, 'SupplyDirector', 'Supply Director'
diff --git a/docs/database/users-roles.md b/docs/database/users-roles.md
index 7e37358..7ae21bb 100644
--- a/docs/database/users-roles.md
+++ b/docs/database/users-roles.md
@@ -35,13 +35,33 @@ One row per employee who has been given access to the app.
| --- | --- |
| id | Number that identifies the user, assigned automatically |
| email | Microsoft work email of the employee. Two users cannot share the same email. |
-| entra_object_id | Identifier of the employee's Microsoft account. It stays empty until the employee's first action that requires a permission. |
+| entra_object_id | Identifier of the employee's Microsoft account. It stays empty until the employee signs in for the first time. |
| display_name | Name shown in the app |
| role_id | The role of the employee (see the roles table) |
| is_active | Yes while the employee has access. Set to no when the admin removes access. |
| created_at | Date and time the access was given |
| updated_at | Date and time of the last change, empty if never changed |
+The table also uses PostgreSQL's hidden `xmin` column as a version number: it changes on every update, so if two administrators edit the same account at the same time, the second save is refused instead of silently overwriting the first one. No column is added for this.
+
+### user_account_changes
+
+One row per change an administrator made to an account. Only the values the change touched are filled: for example, removing access only fills the two active columns.
+
+| Column | Meaning |
+| --- | --- |
+| id | Identifier of the change, assigned automatically |
+| user_id | The account that was changed |
+| action | Created, Updated (name or email), RoleChanged, Deactivated or Reactivated |
+| old_email / new_email | Email before and after the change |
+| old_display_name / new_display_name | Name before and after the change |
+| old_role_id / new_role_id | Role before and after the change (see the roles table) |
+| old_is_active / new_is_active | Access before and after the change |
+| changed_by_user_id | The administrator who made the change |
+| changed_at | Date and time of the change |
+
+The history keeps old emails and names, including those of employees who left, so it is always known who did what.
+
## How the tables are linked
Each user has exactly one role. A role can be given to many users. For example, several people in Finance all share the Finance role.
@@ -57,13 +77,28 @@ Passwords are not stored in the app. Employees sign in with their Microsoft work
## Life of an account
-1. The admin adds the employee with their work email, name and role.
-2. The first time an employee's action requires a permission, the app links the employee's Microsoft account to that row.
-3. The admin can change the role at any time.
-4. When the admin removes access, the account is deactivated rather than deleted, so the history of who did what is kept.
+1. The admin adds the employee with their work email, name and role, from the Accounts screen.
+2. The first time the employee signs in, the app links their Microsoft account to that row.
+3. The admin can edit the name and email, and change the role at any time. A role change takes effect on the employee's next action.
+4. When the admin removes access, the account is deactivated rather than deleted, so the history of who did what is kept. The employee is refused from their next action and sees the same message as someone who was never added. The admin can give the access back later.
+
+Every change is written to user_account_changes with the admin who made it.
+
+Two rules protect the app from being left without an administrator:
+- An admin cannot change their own role or remove their own access.
+- The last active admin cannot lose the role or be deactivated. An admin who has never signed in still counts as active.
The very first Admin account cannot be added from the app, since no admin exists yet. It is inserted once directly in the database during the setup on Azure.
+### Handing over the administrator role
+
+When an administrator leaves, for example at the end of the project:
+1. The leaving admin gives the Admin role to the person who takes over.
+2. The new admin signs in once, so their account shows as linked. This confirms the email is right before the old admin loses access.
+3. The new admin removes the access of the old admin.
+
+The app cannot prevent the only admin from becoming unreachable, for example if they leave Moisson Montréal and IT closes their Microsoft account before they hand over. Their account still counts as an admin in the app, but nobody can sign in with it. The role then has to be given to someone else directly in the database, as for the very first admin. Keeping at least two active admins avoids this.
+
## Migration
| Item | Location |
@@ -73,3 +108,15 @@ The very first Admin account cannot be added from the app, since no admin exists
| Table settings | [UserConfiguration.cs](../../src/MoissonMontreal.Api/Data/Configurations/UserConfiguration.cs) and [RoleConfiguration.cs](../../src/MoissonMontreal.Api/Data/Configurations/RoleConfiguration.cs) |
The SQL script is generated from the migration with `dotnet ef migrations script 0 CreateUsersAndRoles --project src/MoissonMontreal.Api --output docs/database/sql/0001_create_users_and_roles.sql`. It can be run on an empty Azure Database for PostgreSQL server and records itself in the migration history, so Entity Framework will not apply it a second time.
+
+### Account history
+
+| Item | Location |
+| --- | --- |
+| Entity Framework migration | [20261204061822_AddUserAccountChanges](../../src/MoissonMontreal.Api/Data/Migrations/20261204061822_AddUserAccountChanges.cs) |
+| Equivalent SQL script | [0013_add_user_account_changes.sql](sql/0013_add_user_account_changes.sql) |
+| Table settings | [UserAccountChangeConfiguration.cs](../../src/MoissonMontreal.Api/Data/Configurations/UserAccountChangeConfiguration.cs) |
+
+This migration adds the user_account_changes table. The version of users uses the system column `xmin`, so the SQL script adds no column to users.
+
+The SQL script is generated from the migration with `dotnet ef migrations script AddDonorListSearch AddUserAccountChanges --project src/MoissonMontreal.Api --output docs/database/sql/0013_add_user_account_changes.sql`, and the byte order mark (BOM) at the start of the generated file is removed. It must be run after [0012_add_donor_list_search.sql](sql/0012_add_donor_list_search.sql).
diff --git a/src/MoissonMontreal.Api/Accounts/AccountService.cs b/src/MoissonMontreal.Api/Accounts/AccountService.cs
new file mode 100644
index 0000000..38c2405
--- /dev/null
+++ b/src/MoissonMontreal.Api/Accounts/AccountService.cs
@@ -0,0 +1,428 @@
+using Microsoft.EntityFrameworkCore;
+using MoissonMontreal.Api.Data;
+using MoissonMontreal.Api.Data.Configurations;
+using MoissonMontreal.Core.Accounts;
+using MoissonMontreal.Core.Authorization;
+using MoissonMontreal.Core.Entities;
+using Npgsql;
+
+namespace MoissonMontreal.Api.Accounts;
+
+///
+/// Adds employees and changes their account: name and email, role, and access. An account is never deleted, so the history of
+/// who did what stays attributed. Every change is saved together with its history row, and the app always keeps at least one
+/// active administrator.
+///
+/// Database context of the request.
+public class AccountService(MoissonDbContext db)
+{
+ ///
+ /// Adds an employee. The account is linked to their Microsoft account the first time they sign in.
+ ///
+ /// Work email. Spaces around it are removed and it is stored in lowercase.
+ /// Name shown in the app. Spaces around it are removed.
+ /// Code of the role, such as Supply.
+ /// Administrator who adds the employee.
+ /// Token that cancels the database queries.
+ /// The new account, with its role.
+ /// The email or the name is empty or too long.
+ /// No role has this code.
+ /// Another account already uses this email, even deactivated.
+ public async Task AddAsync(
+ string email,
+ string displayName,
+ string roleCode,
+ int adminUserId,
+ CancellationToken cancellationToken = default)
+ {
+ var normalizedEmail = NormalizeEmail(email);
+ var normalizedName = NormalizeDisplayName(displayName);
+ var role = await FindRoleAsync(roleCode, cancellationToken);
+
+ if (await db.Users.AnyAsync(u => u.Email == normalizedEmail, cancellationToken))
+ {
+ throw new AccountEmailAlreadyUsedException(normalizedEmail);
+ }
+
+ var user = new User
+ {
+ Email = normalizedEmail,
+ DisplayName = normalizedName,
+ RoleId = role.Id,
+ Role = role,
+ IsActive = true,
+ };
+ db.Users.Add(user);
+ db.UserAccountChanges.Add(new UserAccountChange
+ {
+ User = user,
+ Action = UserAccountAction.Created,
+ NewEmail = normalizedEmail,
+ NewDisplayName = normalizedName,
+ NewRoleId = role.Id,
+ NewIsActive = true,
+ ChangedByUserId = adminUserId,
+ });
+
+ await SaveAsync(user, normalizedEmail, cancellationToken);
+ return user;
+ }
+
+ ///
+ /// Edits the name and the email of an account. Only the values that changed are written to the history,
+ /// and nothing is saved when neither changed.
+ ///
+ /// Account to edit.
+ /// New work email. Spaces around it are removed and it is stored in lowercase.
+ /// New name. Spaces around it are removed.
+ /// Version of the account when the administrator loaded it.
+ /// Administrator who edits the account.
+ /// Token that cancels the database queries.
+ /// The edited account, with its role.
+ /// The email or the name is empty or too long.
+ /// No account has this identifier.
+ /// Someone else changed the account since it was loaded.
+ /// Another account already uses the new email.
+ public async Task UpdateAsync(
+ int userId,
+ string email,
+ string displayName,
+ uint expectedVersion,
+ int adminUserId,
+ CancellationToken cancellationToken = default)
+ {
+ var normalizedEmail = NormalizeEmail(email);
+ var normalizedName = NormalizeDisplayName(displayName);
+ var user = await FindAtVersionAsync(userId, expectedVersion, cancellationToken);
+
+ var emailChanged = user.Email != normalizedEmail;
+ var nameChanged = user.DisplayName != normalizedName;
+ if (!emailChanged && !nameChanged)
+ {
+ return user;
+ }
+
+ if (emailChanged && await db.Users.AnyAsync(u => u.Email == normalizedEmail && u.Id != userId, cancellationToken))
+ {
+ throw new AccountEmailAlreadyUsedException(normalizedEmail);
+ }
+
+ db.UserAccountChanges.Add(new UserAccountChange
+ {
+ UserId = userId,
+ Action = UserAccountAction.Updated,
+ OldEmail = emailChanged ? user.Email : null,
+ NewEmail = emailChanged ? normalizedEmail : null,
+ OldDisplayName = nameChanged ? user.DisplayName : null,
+ NewDisplayName = nameChanged ? normalizedName : null,
+ ChangedByUserId = adminUserId,
+ });
+ user.Email = normalizedEmail;
+ user.DisplayName = normalizedName;
+ user.UpdatedAt = DateTimeOffset.UtcNow;
+
+ await SaveAsync(user, normalizedEmail, cancellationToken);
+ return user;
+ }
+
+ ///
+ /// Gives an account another role. It takes effect on the employee's next request.
+ ///
+ /// Account whose role changes.
+ /// Code of the new role.
+ /// Version of the account when the administrator loaded it.
+ /// Administrator who changes the role.
+ /// Token that cancels the database queries.
+ /// The account, with its new role.
+ /// The administrator tries to change their own role.
+ /// No role has this code.
+ /// No account has this identifier.
+ /// Someone else changed the account since it was loaded.
+ /// The account is the last active administrator.
+ public async Task ChangeRoleAsync(
+ int userId,
+ string roleCode,
+ uint expectedVersion,
+ int adminUserId,
+ CancellationToken cancellationToken = default)
+ {
+ RefuseOwnAccount(userId, adminUserId);
+ var role = await FindRoleAsync(roleCode, cancellationToken);
+
+ await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
+ var adminRoleId = await LockActiveAdminsAndAccountAsync(userId, cancellationToken);
+ var user = await FindAtVersionAsync(userId, expectedVersion, cancellationToken);
+
+ if (user.RoleId == role.Id)
+ {
+ return user;
+ }
+
+ if (role.Id != adminRoleId)
+ {
+ await RefuseLosingLastActiveAdminAsync(user, adminRoleId, cancellationToken);
+ }
+
+ db.UserAccountChanges.Add(new UserAccountChange
+ {
+ UserId = userId,
+ Action = UserAccountAction.RoleChanged,
+ OldRoleId = user.RoleId,
+ NewRoleId = role.Id,
+ ChangedByUserId = adminUserId,
+ });
+ user.RoleId = role.Id;
+ user.Role = role;
+ user.UpdatedAt = DateTimeOffset.UtcNow;
+
+ await SaveAsync(user, user.Email, cancellationToken);
+ await transaction.CommitAsync(cancellationToken);
+ return user;
+ }
+
+ ///
+ /// Removes an employee's access. The account is kept, and the employee is refused from their next request.
+ ///
+ /// Account to deactivate.
+ /// Version of the account when the administrator loaded it.
+ /// Administrator who removes the access.
+ /// Token that cancels the database queries.
+ /// The deactivated account, with its role.
+ /// The administrator tries to remove their own access.
+ /// No account has this identifier.
+ /// Someone else changed the account since it was loaded.
+ /// The account is the last active administrator.
+ public async Task DeactivateAsync(
+ int userId,
+ uint expectedVersion,
+ int adminUserId,
+ CancellationToken cancellationToken = default)
+ {
+ RefuseOwnAccount(userId, adminUserId);
+
+ await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
+ var adminRoleId = await LockActiveAdminsAndAccountAsync(userId, cancellationToken);
+ var user = await FindAtVersionAsync(userId, expectedVersion, cancellationToken);
+
+ if (!user.IsActive)
+ {
+ return user;
+ }
+
+ await RefuseLosingLastActiveAdminAsync(user, adminRoleId, cancellationToken);
+
+ await SetActiveAsync(user, false, UserAccountAction.Deactivated, adminUserId, cancellationToken);
+ await transaction.CommitAsync(cancellationToken);
+ return user;
+ }
+
+ ///
+ /// Gives an employee their access back. What they created before stays attributed to them.
+ ///
+ /// Account to reactivate.
+ /// Version of the account when the administrator loaded it.
+ /// Administrator who gives the access back.
+ /// Token that cancels the database queries.
+ /// The reactivated account, with its role.
+ /// No account has this identifier.
+ /// Someone else changed the account since it was loaded.
+ public async Task ReactivateAsync(
+ int userId,
+ uint expectedVersion,
+ int adminUserId,
+ CancellationToken cancellationToken = default)
+ {
+ var user = await FindAtVersionAsync(userId, expectedVersion, cancellationToken);
+ if (user.IsActive)
+ {
+ return user;
+ }
+
+ await SetActiveAsync(user, true, UserAccountAction.Reactivated, adminUserId, cancellationToken);
+ return user;
+ }
+
+ ///
+ /// Removes the spaces around an email, puts it in lowercase and refuses an empty, invalid or too long one.
+ ///
+ /// Email as received.
+ /// The email in lowercase, without spaces around it.
+ /// The email is empty, has no @ or is too long.
+ private static string NormalizeEmail(string email)
+ {
+ var normalized = (email ?? string.Empty).Trim().ToLowerInvariant();
+ if (normalized.Length == 0 || !normalized.Contains('@') || normalized.Length > User.EmailMaxLength)
+ {
+ throw new ArgumentException(
+ $"The email must contain @ and be at most {User.EmailMaxLength} characters.", nameof(email));
+ }
+
+ return normalized;
+ }
+
+ ///
+ /// Removes the spaces around a name and refuses an empty or too long one.
+ ///
+ /// Name as received.
+ /// The name without spaces around it.
+ /// The name is empty or too long.
+ private static string NormalizeDisplayName(string displayName)
+ {
+ var normalized = (displayName ?? string.Empty).Trim();
+ if (normalized.Length == 0 || normalized.Length > User.DisplayNameMaxLength)
+ {
+ throw new ArgumentException(
+ $"The name is required and must be at most {User.DisplayNameMaxLength} characters.", nameof(displayName));
+ }
+
+ return normalized;
+ }
+
+ ///
+ /// Refuses a change an administrator makes to their own role or access.
+ ///
+ /// Account being changed.
+ /// Administrator making the change.
+ /// Both are the same account.
+ private static void RefuseOwnAccount(int userId, int adminUserId)
+ {
+ if (userId == adminUserId)
+ {
+ throw new OwnAccountChangeException(userId);
+ }
+ }
+
+ ///
+ /// Loads a role by its code.
+ ///
+ /// Code of the role.
+ /// Token that cancels the database query.
+ /// The role.
+ /// No role has this code.
+ private async Task FindRoleAsync(string roleCode, CancellationToken cancellationToken) =>
+ await db.Roles.SingleOrDefaultAsync(r => r.Code == roleCode, cancellationToken)
+ ?? throw new RoleNotFoundException(roleCode);
+
+ ///
+ /// Loads an account with its role, and checks it has not changed since the administrator loaded it.
+ /// The version is also given to Entity Framework, so a change made between this check and the save is refused too.
+ ///
+ /// Identifier of the account.
+ /// Version of the account when the administrator loaded it.
+ /// Token that cancels the database query.
+ /// The account, tracked by Entity Framework.
+ /// No account has this identifier.
+ /// The version is different.
+ private async Task FindAtVersionAsync(int userId, uint expectedVersion, CancellationToken cancellationToken)
+ {
+ var user = await db.Users.Include(u => u.Role).SingleOrDefaultAsync(u => u.Id == userId, cancellationToken)
+ ?? throw new AccountNotFoundException(userId);
+
+ if (user.Version != expectedVersion)
+ {
+ throw new AccountEditedMeanwhileException(userId);
+ }
+
+ db.Entry(user).Property(u => u.Version).OriginalValue = expectedVersion;
+ return user;
+ }
+
+ ///
+ /// Locks the rows of the active administrators and of the account, until the transaction ends.
+ /// Two changes that could remove the last administrator at the same time then run one after the other,
+ /// and the second one sees the result of the first.
+ ///
+ /// Account being changed.
+ /// Token that cancels the database query.
+ /// Identifier of the administrator role.
+ private async Task LockActiveAdminsAndAccountAsync(int userId, CancellationToken cancellationToken)
+ {
+ var adminRoleId = await db.Roles.Where(r => r.Code == RoleCodes.Admin).Select(r => r.Id).SingleAsync(cancellationToken);
+
+ // Only the id is selected: SELECT * would not return the xmin column used as the version.
+ await db.Database.ExecuteSqlAsync(
+ $"SELECT id FROM users WHERE (role_id = {adminRoleId} AND is_active) OR id = {userId} ORDER BY id FOR UPDATE",
+ cancellationToken);
+
+ return adminRoleId;
+ }
+
+ ///
+ /// Refuses a change that would make an active administrator lose the role or the access when no other active
+ /// administrator exists.
+ ///
+ /// Account being changed.
+ /// Identifier of the administrator role.
+ /// Token that cancels the database query.
+ /// The account is the last active administrator.
+ private async Task RefuseLosingLastActiveAdminAsync(User user, int adminRoleId, CancellationToken cancellationToken)
+ {
+ if (!user.IsActive || user.RoleId != adminRoleId)
+ {
+ return;
+ }
+
+ var otherActiveAdmins = await db.Users.CountAsync(
+ u => u.Id != user.Id && u.IsActive && u.RoleId == adminRoleId,
+ cancellationToken);
+
+ if (otherActiveAdmins == 0)
+ {
+ throw new LastActiveAdminException(user.Id);
+ }
+ }
+
+ ///
+ /// Changes the access of an account and writes the history row.
+ ///
+ /// Account to change, tracked by Entity Framework.
+ /// New access.
+ /// Deactivated or Reactivated.
+ /// Administrator making the change.
+ /// Token that cancels the database query.
+ private async Task SetActiveAsync(
+ User user,
+ bool isActive,
+ UserAccountAction action,
+ int adminUserId,
+ CancellationToken cancellationToken)
+ {
+ db.UserAccountChanges.Add(new UserAccountChange
+ {
+ UserId = user.Id,
+ Action = action,
+ OldIsActive = user.IsActive,
+ NewIsActive = isActive,
+ ChangedByUserId = adminUserId,
+ });
+ user.IsActive = isActive;
+ user.UpdatedAt = DateTimeOffset.UtcNow;
+
+ await SaveAsync(user, user.Email, cancellationToken);
+ }
+
+ ///
+ /// Saves the pending changes and turns the database refusals into clear errors.
+ ///
+ /// Account being saved.
+ /// Email being saved, used in the error when it is already used.
+ /// Token that cancels the save.
+ /// Someone else changed the account between the check and the save.
+ /// Another account saved the same email between the check and the save.
+ private async Task SaveAsync(User user, string email, CancellationToken cancellationToken)
+ {
+ try
+ {
+ await db.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException)
+ {
+ throw new AccountEditedMeanwhileException(user.Id);
+ }
+ catch (DbUpdateException exception) when (
+ exception.InnerException is PostgresException { ConstraintName: UserConfiguration.EmailIndex })
+ {
+ throw new AccountEmailAlreadyUsedException(email);
+ }
+ }
+}
diff --git a/src/MoissonMontreal.Api/Controllers/AccountsController.cs b/src/MoissonMontreal.Api/Controllers/AccountsController.cs
new file mode 100644
index 0000000..47eccd3
--- /dev/null
+++ b/src/MoissonMontreal.Api/Controllers/AccountsController.cs
@@ -0,0 +1,367 @@
+using System.Linq.Expressions;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+using MoissonMontreal.Api.Accounts;
+using MoissonMontreal.Api.Authorization;
+using MoissonMontreal.Api.Data;
+using MoissonMontreal.Core.Accounts;
+using MoissonMontreal.Core.Authorization;
+using MoissonMontreal.Core.Dtos;
+using MoissonMontreal.Core.Entities;
+
+namespace MoissonMontreal.Api.Controllers;
+
+///
+/// Lets an administrator list employees' accounts, add them, edit them, change their role and remove or give back their access.
+/// Every route requires , so every rule is enforced on the server.
+///
+/// Database context of the request.
+/// Service that changes the accounts and writes their history.
+/// Service that finds the account of the signed-in administrator.
+[ApiController]
+[Route("api/accounts")]
+[Authorize(Policy = Permissions.ManageAccounts)]
+public class AccountsController(
+ MoissonDbContext db,
+ AccountService accounts,
+ UserLookupService userLookup) : ControllerBase
+{
+ ///
+ /// Turns an account into the shape returned by the API, inside the database query.
+ ///
+ private static readonly Expression> AsDto = u => new AccountDto(
+ u.Id,
+ u.Email,
+ u.DisplayName,
+ u.Role.Code,
+ u.Role.Name,
+ u.IsActive,
+ u.EntraObjectId != null,
+ u.CreatedAt,
+ u.UpdatedAt,
+ u.Version);
+
+ ///
+ /// Same as , for an account already loaded with its role.
+ ///
+ private static readonly Func ToDto = AsDto.Compile();
+
+ ///
+ /// Lists every account: active ones first, then deactivated ones, each sorted by name.
+ ///
+ /// Token that cancels the database query.
+ /// The accounts.
+ [HttpGet]
+ [ProducesResponseType>(StatusCodes.Status200OK)]
+ public async Task>> List(CancellationToken cancellationToken) =>
+ await db.Users
+ .OrderByDescending(u => u.IsActive)
+ .ThenBy(u => u.DisplayName)
+ .Select(AsDto)
+ .ToListAsync(cancellationToken);
+
+ ///
+ /// Lists the roles an account can be given.
+ ///
+ /// Token that cancels the database query.
+ /// The roles, in the order of their identifier.
+ [HttpGet("roles")]
+ [ProducesResponseType>(StatusCodes.Status200OK)]
+ public async Task>> ListRoles(CancellationToken cancellationToken) =>
+ await db.Roles
+ .OrderBy(r => r.Id)
+ .Select(r => new RoleDto(r.Code, r.Name))
+ .ToListAsync(cancellationToken);
+
+ ///
+ /// Returns one account.
+ ///
+ /// Identifier of the account.
+ /// Token that cancels the database query.
+ /// The account, or 404.
+ [HttpGet("{id:int}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task> Get(int id, CancellationToken cancellationToken)
+ {
+ var account = await db.Users.Where(u => u.Id == id).Select(AsDto).SingleOrDefaultAsync(cancellationToken);
+ return account is null ? AccountNotFound(new AccountNotFoundException(id)) : account;
+ }
+
+ ///
+ /// Returns every change made to an account, newest first.
+ ///
+ /// Identifier of the account.
+ /// Token that cancels the database query.
+ /// The changes, or 404 when the account does not exist.
+ [HttpGet("{id:int}/history")]
+ [ProducesResponseType>(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task>> GetHistory(int id, CancellationToken cancellationToken)
+ {
+ if (!await db.Users.AnyAsync(u => u.Id == id, cancellationToken))
+ {
+ return AccountNotFound(new AccountNotFoundException(id));
+ }
+
+ return await db.UserAccountChanges
+ .Where(c => c.UserId == id)
+ .OrderByDescending(c => c.ChangedAt)
+ .Select(c => new AccountChangeDto(
+ c.Id,
+ c.Action.ToString(),
+ c.OldEmail,
+ c.NewEmail,
+ c.OldDisplayName,
+ c.NewDisplayName,
+ db.Roles.Where(r => r.Id == c.OldRoleId).Select(r => r.Code).FirstOrDefault(),
+ db.Roles.Where(r => r.Id == c.NewRoleId).Select(r => r.Code).FirstOrDefault(),
+ c.OldIsActive,
+ c.NewIsActive,
+ c.ChangedByUserId,
+ c.ChangedBy.DisplayName,
+ c.ChangedAt))
+ .ToListAsync(cancellationToken);
+ }
+
+ ///
+ /// Adds an employee. They can sign in as soon as the account exists.
+ ///
+ /// Email, name and role.
+ /// Token that cancels the database queries.
+ /// 201 with the account, 400 when a field is missing or invalid, or 409 when the email is already used.
+ [HttpPost]
+ [ProducesResponseType(StatusCodes.Status201Created)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> Create(AccountCreateRequest request, CancellationToken cancellationToken)
+ {
+ var errors = new Dictionary();
+ RequireText(errors, nameof(request.Email), request.Email);
+ RequireText(errors, nameof(request.DisplayName), request.DisplayName);
+ RequireText(errors, nameof(request.RoleCode), request.RoleCode);
+ if (errors.Count > 0)
+ {
+ return ValidationProblem(new ValidationProblemDetails(errors));
+ }
+
+ return await RunAsync(async admin =>
+ {
+ var user = await accounts.AddAsync(
+ request.Email!, request.DisplayName!, request.RoleCode!, admin.Id, cancellationToken);
+ return CreatedAtAction(nameof(Get), new { id = user.Id }, ToDto(user));
+ }, cancellationToken);
+ }
+
+ ///
+ /// Edits the name and the email of an account.
+ ///
+ /// Identifier of the account.
+ /// New email, new name and the version the administrator loaded.
+ /// Token that cancels the database queries.
+ /// 200 with the account, 400, 404, or 409 when the email is used or the account changed in the meantime.
+ [HttpPut("{id:int}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> Update(int id, AccountUpdateRequest request, CancellationToken cancellationToken)
+ {
+ var errors = new Dictionary();
+ RequireText(errors, nameof(request.Email), request.Email);
+ RequireText(errors, nameof(request.DisplayName), request.DisplayName);
+ RequireVersion(errors, request.Version);
+ if (errors.Count > 0)
+ {
+ return ValidationProblem(new ValidationProblemDetails(errors));
+ }
+
+ return await RunAsync(async admin => ToDto(await accounts.UpdateAsync(
+ id, request.Email!, request.DisplayName!, request.Version!.Value, admin.Id, cancellationToken)), cancellationToken);
+ }
+
+ ///
+ /// Gives an account another role. It takes effect on the employee's next request.
+ ///
+ /// Identifier of the account.
+ /// Code of the new role and the version the administrator loaded.
+ /// Token that cancels the database queries.
+ /// 200 with the account, 400 for an unknown role or the administrator's own account, 404,
+ /// or 409 when the account changed in the meantime or is the last active administrator.
+ [HttpPut("{id:int}/role")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> ChangeRole(int id, AccountRoleRequest request, CancellationToken cancellationToken)
+ {
+ var errors = new Dictionary();
+ RequireText(errors, nameof(request.RoleCode), request.RoleCode);
+ RequireVersion(errors, request.Version);
+ if (errors.Count > 0)
+ {
+ return ValidationProblem(new ValidationProblemDetails(errors));
+ }
+
+ return await RunAsync(async admin => ToDto(await accounts.ChangeRoleAsync(
+ id, request.RoleCode!, request.Version!.Value, admin.Id, cancellationToken)), cancellationToken);
+ }
+
+ ///
+ /// Removes an employee's access. The account is kept and the employee is refused from their next request.
+ ///
+ /// Identifier of the account.
+ /// Version the administrator loaded.
+ /// Token that cancels the database queries.
+ /// 200 with the account, 400 for the administrator's own account, 404,
+ /// or 409 when the account changed in the meantime or is the last active administrator.
+ [HttpPost("{id:int}/deactivate")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> Deactivate(int id, AccountVersionRequest request, CancellationToken cancellationToken)
+ {
+ var errors = new Dictionary();
+ RequireVersion(errors, request.Version);
+ if (errors.Count > 0)
+ {
+ return ValidationProblem(new ValidationProblemDetails(errors));
+ }
+
+ return await RunAsync(async admin => ToDto(await accounts.DeactivateAsync(
+ id, request.Version!.Value, admin.Id, cancellationToken)), cancellationToken);
+ }
+
+ ///
+ /// Gives an employee their access back.
+ ///
+ /// Identifier of the account.
+ /// Version the administrator loaded.
+ /// Token that cancels the database queries.
+ /// 200 with the account, 400, 404, or 409 when the account changed in the meantime.
+ [HttpPost("{id:int}/reactivate")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> Reactivate(int id, AccountVersionRequest request, CancellationToken cancellationToken)
+ {
+ var errors = new Dictionary();
+ RequireVersion(errors, request.Version);
+ if (errors.Count > 0)
+ {
+ return ValidationProblem(new ValidationProblemDetails(errors));
+ }
+
+ return await RunAsync(async admin => ToDto(await accounts.ReactivateAsync(
+ id, request.Version!.Value, admin.Id, cancellationToken)), cancellationToken);
+ }
+
+ ///
+ /// Adds an error when a text field is missing or blank.
+ ///
+ /// Errors collected for the request.
+ /// Name of the field.
+ /// Value received.
+ private static void RequireText(Dictionary errors, string field, string? value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ errors[field] = [$"{field} is required."];
+ }
+ }
+
+ ///
+ /// Adds an error when the version is missing.
+ ///
+ /// Errors collected for the request.
+ /// Version received.
+ private static void RequireVersion(Dictionary errors, uint? version)
+ {
+ if (version is null)
+ {
+ errors["Version"] = ["Version is required: send the version of the account you loaded."];
+ }
+ }
+
+ ///
+ /// Finds the signed-in administrator, runs a change, and turns the service errors into HTTP answers.
+ ///
+ /// Change to run with the administrator's account.
+ /// Token that cancels the database query.
+ /// The answer of the change, or the matching error.
+ private async Task> RunAsync(
+ Func>> change,
+ CancellationToken cancellationToken)
+ {
+ if (await userLookup.FindActiveUserAsync(User, cancellationToken) is not { } admin)
+ {
+ return Forbid();
+ }
+
+ try
+ {
+ return await change(admin);
+ }
+ catch (ArgumentException e)
+ {
+ var field = e.ParamName == "email" ? "Email" : "DisplayName";
+ return ValidationProblem(new ValidationProblemDetails(new Dictionary
+ {
+ [field] = [e.Message.Replace($" (Parameter '{e.ParamName}')", string.Empty)],
+ }));
+ }
+ catch (RoleNotFoundException e)
+ {
+ return ValidationProblem(new ValidationProblemDetails(new Dictionary
+ {
+ ["RoleCode"] = [e.Message],
+ }));
+ }
+ catch (OwnAccountChangeException e)
+ {
+ return Error(StatusCodes.Status400BadRequest, "Own account", e.Message);
+ }
+ catch (AccountNotFoundException e)
+ {
+ return AccountNotFound(e);
+ }
+ catch (AccountEmailAlreadyUsedException e)
+ {
+ return Error(StatusCodes.Status409Conflict, "Email already used", e.Message);
+ }
+ catch (AccountEditedMeanwhileException e)
+ {
+ return Error(StatusCodes.Status409Conflict, "Account changed by someone else", e.Message);
+ }
+ catch (LastActiveAdminException e)
+ {
+ return Error(StatusCodes.Status409Conflict, "Last active administrator", e.Message);
+ }
+ }
+
+ ///
+ /// Builds an error answer with a status, a short title and the detail shown to the administrator.
+ ///
+ /// HTTP status code.
+ /// Short title of the error.
+ /// Message shown to the administrator.
+ /// The error answer.
+ private ObjectResult Error(int status, string title, string detail) =>
+ new(ProblemDetailsFactory.CreateProblemDetails(HttpContext, status, title: title, detail: detail)) { StatusCode = status };
+
+ ///
+ /// Builds the 404 answer for an account that does not exist.
+ ///
+ /// Error describing the missing account.
+ /// A 404 with the account identifier.
+ private NotFoundObjectResult AccountNotFound(AccountNotFoundException e)
+ {
+ var problem = ProblemDetailsFactory.CreateProblemDetails(
+ HttpContext, StatusCodes.Status404NotFound, title: "Account not found", detail: e.Message);
+ problem.Extensions["userId"] = e.UserId;
+ return NotFound(problem);
+ }
+}
diff --git a/src/MoissonMontreal.Api/Controllers/MeController.cs b/src/MoissonMontreal.Api/Controllers/MeController.cs
index b9b4ba5..b9581d0 100644
--- a/src/MoissonMontreal.Api/Controllers/MeController.cs
+++ b/src/MoissonMontreal.Api/Controllers/MeController.cs
@@ -1,17 +1,37 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
+using MoissonMontreal.Api.Authorization;
using MoissonMontreal.Core.Dtos;
namespace MoissonMontreal.Api.Controllers;
+///
+/// Tells the desktop app who is signed in and with which role, so it can show only what the employee is allowed to use.
+/// Like every route, it refuses a deactivated or never-added account.
+///
+/// Service that finds the app account of the signed-in employee.
[ApiController]
[Route("api/me")]
-public class MeController : ControllerBase
+public class MeController(UserLookupService userLookup) : ControllerBase
{
+ ///
+ /// Returns the signed-in employee and their role.
+ ///
+ /// Token that cancels the database query.
+ /// The employee, or 403 when they have no active account.
[HttpGet]
- public ActionResult Get() => new CurrentUserDto(
- ObjectId: User.FindFirstValue("oid"),
- Name: User.FindFirstValue("name"),
- Email: User.FindFirstValue("email") ?? User.FindFirstValue("preferred_username"),
- TenantId: User.FindFirstValue("tid"));
+ public async Task> Get(CancellationToken cancellationToken)
+ {
+ if (await userLookup.FindActiveUserAsync(User, cancellationToken) is not { } user)
+ {
+ return Forbid();
+ }
+
+ return new CurrentUserDto(
+ ObjectId: User.FindFirstValue("oid"),
+ Name: User.FindFirstValue("name"),
+ Email: User.FindFirstValue("email") ?? User.FindFirstValue("preferred_username"),
+ TenantId: User.FindFirstValue("tid"),
+ Role: user.Role.Code);
+ }
}
diff --git a/src/MoissonMontreal.Api/Data/Configurations/UserAccountChangeConfiguration.cs b/src/MoissonMontreal.Api/Data/Configurations/UserAccountChangeConfiguration.cs
new file mode 100644
index 0000000..3a5a400
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Configurations/UserAccountChangeConfiguration.cs
@@ -0,0 +1,57 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+using MoissonMontreal.Core.Entities;
+
+namespace MoissonMontreal.Api.Data.Configurations;
+
+///
+/// Database rules of the user_account_changes table, the history of every change made to an employee's account.
+///
+public class UserAccountChangeConfiguration : IEntityTypeConfiguration
+{
+ ///
+ /// Longest action name stored, such as RoleChanged.
+ ///
+ private const int ActionMaxLength = 20;
+
+ ///
+ /// Configures the columns, the action stored as text, the index on the account and the links to users and roles.
+ ///
+ /// Builder used to configure the account change entity.
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.Property(c => c.Id).HasDefaultValueSql("gen_random_uuid()");
+
+ builder.Property(c => c.Action)
+ .HasConversion()
+ .HasMaxLength(ActionMaxLength);
+
+ builder.Property(c => c.OldEmail).HasMaxLength(User.EmailMaxLength);
+ builder.Property(c => c.NewEmail).HasMaxLength(User.EmailMaxLength);
+
+ builder.Property(c => c.OldDisplayName).HasMaxLength(User.DisplayNameMaxLength);
+ builder.Property(c => c.NewDisplayName).HasMaxLength(User.DisplayNameMaxLength);
+
+ builder.Property(c => c.ChangedAt).HasDefaultValueSql("now()");
+
+ builder.HasOne(c => c.User)
+ .WithMany()
+ .HasForeignKey(c => c.UserId)
+ .OnDelete(DeleteBehavior.Restrict);
+
+ builder.HasOne(c => c.ChangedBy)
+ .WithMany()
+ .HasForeignKey(c => c.ChangedByUserId)
+ .OnDelete(DeleteBehavior.Restrict);
+
+ builder.HasOne()
+ .WithMany()
+ .HasForeignKey(c => c.OldRoleId)
+ .OnDelete(DeleteBehavior.Restrict);
+
+ builder.HasOne()
+ .WithMany()
+ .HasForeignKey(c => c.NewRoleId)
+ .OnDelete(DeleteBehavior.Restrict);
+ }
+}
diff --git a/src/MoissonMontreal.Api/Data/Configurations/UserConfiguration.cs b/src/MoissonMontreal.Api/Data/Configurations/UserConfiguration.cs
index c3b815a..0a52251 100644
--- a/src/MoissonMontreal.Api/Data/Configurations/UserConfiguration.cs
+++ b/src/MoissonMontreal.Api/Data/Configurations/UserConfiguration.cs
@@ -9,6 +9,11 @@ namespace MoissonMontreal.Api.Data.Configurations;
///
public class UserConfiguration : IEntityTypeConfiguration
{
+ ///
+ /// Name of the unique index on the email, used to recognize a save refused because the email is already used.
+ ///
+ public const string EmailIndex = "ix_users_email";
+
///
/// Configures the columns, constraints, unique indexes and role relationship of the users table.
///
@@ -17,17 +22,20 @@ public void Configure(EntityTypeBuilder builder)
{
builder.ToTable(t => t.HasCheckConstraint("ck_users_email_lowercase", "email = lower(email)"));
- builder.Property(u => u.Email).HasMaxLength(256).IsRequired();
- builder.HasIndex(u => u.Email).IsUnique();
+ builder.Property(u => u.Email).HasMaxLength(User.EmailMaxLength).IsRequired();
+ builder.HasIndex(u => u.Email).IsUnique().HasDatabaseName(EmailIndex);
builder.HasIndex(u => u.EntraObjectId).IsUnique();
- builder.Property(u => u.DisplayName).HasMaxLength(200).IsRequired();
+ builder.Property(u => u.DisplayName).HasMaxLength(User.DisplayNameMaxLength).IsRequired();
builder.Property(u => u.IsActive).HasDefaultValue(true).HasSentinel(true);
builder.Property(u => u.CreatedAt).HasDefaultValueSql("now()");
+ // Mapped to the PostgreSQL system column xmin, which changes on every update, so no column is added.
+ builder.Property(u => u.Version).IsRowVersion();
+
builder.HasOne(u => u.Role)
.WithMany(r => r.Users)
.HasForeignKey(u => u.RoleId)
diff --git a/src/MoissonMontreal.Api/Data/Migrations/20261204061822_AddUserAccountChanges.Designer.cs b/src/MoissonMontreal.Api/Data/Migrations/20261204061822_AddUserAccountChanges.Designer.cs
new file mode 100644
index 0000000..90d2bfb
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Migrations/20261204061822_AddUserAccountChanges.Designer.cs
@@ -0,0 +1,1132 @@
+//
+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("20261204061822_AddUserAccountChanges")]
+ partial class AddUserAccountChanges
+ {
+ ///
+ 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.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("CatalogItemId")
+ .HasColumnType("uuid")
+ .HasColumnName("catalog_item_id");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("DonationDate")
+ .HasColumnType("date")
+ .HasColumnName("donation_date");
+
+ b.Property("DonorId")
+ .HasColumnType("uuid")
+ .HasColumnName("donor_id");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)")
+ .HasColumnName("name");
+
+ b.Property("Quality")
+ .IsRequired()
+ .HasMaxLength(1)
+ .HasColumnType("character varying(1)")
+ .HasColumnName("quality");
+
+ b.Property("Quantity")
+ .HasPrecision(12, 2)
+ .HasColumnType("numeric(12,2)")
+ .HasColumnName("quantity");
+
+ b.Property("Unit")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasColumnName("unit");
+
+ b.HasKey("Id")
+ .HasName("pk_food_items");
+
+ b.HasAlternateKey("Id", "DonorId")
+ .HasName("ak_food_items_id_donor_id");
+
+ b.HasIndex("CatalogItemId")
+ .HasDatabaseName("ix_food_items_catalog_item_id");
+
+ b.HasIndex("DonorId")
+ .HasDatabaseName("ix_food_items_donor_id");
+
+ b.HasIndex("Quality")
+ .HasDatabaseName("ix_food_items_quality");
+
+ b.ToTable("food_items", null, t =>
+ {
+ t.HasCheckConstraint("ck_food_items_name_not_empty", "length(name) > 0");
+
+ t.HasCheckConstraint("ck_food_items_quantity_positive", "quantity > 0");
+
+ t.HasCheckConstraint("ck_food_items_unit_not_empty", "length(unit) > 0");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.Price", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("CatalogItemId")
+ .HasColumnType("uuid")
+ .HasColumnName("catalog_item_id");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("EffectiveDate")
+ .HasColumnType("date")
+ .HasColumnName("effective_date");
+
+ b.Property("UnitPrice")
+ .HasPrecision(12, 4)
+ .HasColumnType("numeric(12,4)")
+ .HasColumnName("unit_price");
+
+ b.HasKey("Id")
+ .HasName("pk_prices");
+
+ b.HasIndex("CatalogItemId", "EffectiveDate")
+ .IsUnique()
+ .HasDatabaseName("ix_prices_catalog_item_id_effective_date");
+
+ b.ToTable("prices", null, t =>
+ {
+ t.HasCheckConstraint("ck_prices_unit_price_positive", "unit_price > 0");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.QualityClass", b =>
+ {
+ b.Property("Code")
+ .HasMaxLength(1)
+ .HasColumnType("character varying(1)")
+ .HasColumnName("code");
+
+ b.Property("MaxPercentage")
+ .HasPrecision(5, 2)
+ .HasColumnType("numeric(5,2)")
+ .HasColumnName("max_percentage");
+
+ b.Property("MinPercentage")
+ .HasPrecision(5, 2)
+ .HasColumnType("numeric(5,2)")
+ .HasColumnName("min_percentage");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)")
+ .HasColumnName("name");
+
+ b.Property("Percentage")
+ .HasPrecision(5, 2)
+ .HasColumnType("numeric(5,2)")
+ .HasColumnName("percentage");
+
+ b.HasKey("Code")
+ .HasName("pk_quality_classes");
+
+ b.HasIndex("Name")
+ .IsUnique()
+ .HasDatabaseName("ix_quality_classes_name");
+
+ b.ToTable("quality_classes", null, t =>
+ {
+ t.HasCheckConstraint("ck_quality_classes_code_format", "code ~ '^[A-Z]$'");
+
+ t.HasCheckConstraint("ck_quality_classes_name_not_empty", "length(name) > 0");
+
+ t.HasCheckConstraint("ck_quality_classes_percentage_in_range", "percentage BETWEEN min_percentage AND max_percentage");
+
+ t.HasCheckConstraint("ck_quality_classes_range_valid", "min_percentage >= 0 AND min_percentage <= max_percentage AND max_percentage <= 100");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.Receipt", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("DonorId")
+ .HasColumnType("uuid")
+ .HasColumnName("donor_id");
+
+ b.Property("ReceiptDate")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("date")
+ .HasColumnName("receipt_date")
+ .HasDefaultValueSql("(now() AT TIME ZONE 'America/Montreal')::date");
+
+ b.Property("ReceiptNumber")
+ .HasMaxLength(10)
+ .HasColumnType("character varying(10)")
+ .HasColumnName("receipt_number");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasDefaultValue("Draft")
+ .HasColumnName("status");
+
+ b.Property("TotalAmount")
+ .HasPrecision(12, 2)
+ .HasColumnType("numeric(12,2)")
+ .HasColumnName("total_amount");
+
+ b.HasKey("Id")
+ .HasName("pk_receipts");
+
+ b.HasAlternateKey("Id", "DonorId")
+ .HasName("ak_receipts_id_donor_id");
+
+ b.HasIndex("DonorId")
+ .HasDatabaseName("ix_receipts_donor_id");
+
+ b.HasIndex("ReceiptNumber")
+ .IsUnique()
+ .HasDatabaseName("ix_receipts_receipt_number");
+
+ b.ToTable("receipts", null, t =>
+ {
+ t.HasCheckConstraint("ck_receipts_issued_has_receipt_number", "status <> 'Issued' OR receipt_number IS NOT NULL");
+
+ t.HasCheckConstraint("ck_receipts_receipt_number_format", "receipt_number ~ '^DEN_[0-9]{6}$'");
+
+ t.HasCheckConstraint("ck_receipts_receipt_number_only_once_issued", "status IN ('Issued', 'Cancelled') OR receipt_number IS NULL");
+
+ t.HasCheckConstraint("ck_receipts_status_valid", "status IN ('Draft', 'PendingSupplyApproval', 'PendingFinanceApproval', 'Approved', 'Issued', 'Cancelled')");
+
+ t.HasCheckConstraint("ck_receipts_total_amount_not_negative", "total_amount >= 0");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.ReceiptItem", b =>
+ {
+ b.Property("ReceiptId")
+ .HasColumnType("uuid")
+ .HasColumnName("receipt_id");
+
+ b.Property("FoodItemId")
+ .HasColumnType("uuid")
+ .HasColumnName("food_item_id");
+
+ b.Property("DonorId")
+ .HasColumnType("uuid")
+ .HasColumnName("donor_id");
+
+ b.Property("QualityPercent")
+ .HasPrecision(5, 2)
+ .HasColumnType("numeric(5,2)")
+ .HasColumnName("quality_percent");
+
+ b.Property("Quantity")
+ .HasPrecision(12, 2)
+ .HasColumnType("numeric(12,2)")
+ .HasColumnName("quantity");
+
+ b.Property("ReceiptCancelled")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(false)
+ .HasColumnName("receipt_cancelled");
+
+ b.Property("Unit")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasColumnName("unit");
+
+ b.Property("UnitPrice")
+ .HasPrecision(12, 4)
+ .HasColumnType("numeric(12,4)")
+ .HasColumnName("unit_price");
+
+ b.HasKey("ReceiptId", "FoodItemId")
+ .HasName("pk_receipt_items");
+
+ b.HasIndex("FoodItemId")
+ .IsUnique()
+ .HasDatabaseName("ix_receipt_items_food_item_id")
+ .HasFilter("NOT receipt_cancelled");
+
+ b.HasIndex("FoodItemId", "DonorId")
+ .HasDatabaseName("ix_receipt_items_food_item_id_donor_id");
+
+ b.HasIndex("ReceiptId", "DonorId")
+ .HasDatabaseName("ix_receipt_items_receipt_id_donor_id");
+
+ b.ToTable("receipt_items", null, t =>
+ {
+ t.HasCheckConstraint("ck_receipt_items_quality_percent_range", "quality_percent BETWEEN 0 AND 100");
+
+ t.HasCheckConstraint("ck_receipt_items_quantity_positive", "quantity > 0");
+
+ t.HasCheckConstraint("ck_receipt_items_unit_not_empty", "length(unit) > 0");
+
+ t.HasCheckConstraint("ck_receipt_items_unit_price_positive", "unit_price > 0");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.ReceiptNumberCounter", b =>
+ {
+ b.Property("Series")
+ .HasMaxLength(10)
+ .HasColumnType("character varying(10)")
+ .HasColumnName("series");
+
+ b.Property("LastNumber")
+ .HasColumnType("integer")
+ .HasColumnName("last_number");
+
+ b.HasKey("Series")
+ .HasName("pk_receipt_number_counters");
+
+ b.ToTable("receipt_number_counters", null, t =>
+ {
+ t.HasCheckConstraint("ck_receipt_number_counters_last_number_in_range", "last_number BETWEEN 0 AND 999999");
+ });
+
+ b.HasData(
+ new
+ {
+ Series = "DEN",
+ LastNumber = 0
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.ReceiptStatusChange", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("ChangedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("changed_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("ChangedByUserId")
+ .HasColumnType("integer")
+ .HasColumnName("changed_by_user_id");
+
+ b.Property("FromStatus")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasColumnName("from_status");
+
+ b.Property("Reason")
+ .HasMaxLength(1000)
+ .HasColumnType("character varying(1000)")
+ .HasColumnName("reason");
+
+ b.Property("ReceiptId")
+ .HasColumnType("uuid")
+ .HasColumnName("receipt_id");
+
+ b.Property("ToStatus")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)")
+ .HasColumnName("to_status");
+
+ b.HasKey("Id")
+ .HasName("pk_receipt_status_changes");
+
+ b.HasIndex("ChangedByUserId")
+ .HasDatabaseName("ix_receipt_status_changes_changed_by_user_id");
+
+ b.HasIndex("ReceiptId", "ChangedAt")
+ .HasDatabaseName("ix_receipt_status_changes_receipt_id_changed_at");
+
+ b.ToTable("receipt_status_changes", null, t =>
+ {
+ t.HasCheckConstraint("ck_receipt_status_changes_from_status_valid", "from_status IN ('Draft', 'PendingSupplyApproval', 'PendingFinanceApproval', 'Approved', 'Issued', 'Cancelled')");
+
+ t.HasCheckConstraint("ck_receipt_status_changes_reason_not_empty", "length(reason) > 0");
+
+ t.HasCheckConstraint("ck_receipt_status_changes_reason_required", "to_status NOT IN ('Draft', 'Cancelled') OR reason IS NOT NULL");
+
+ t.HasCheckConstraint("ck_receipt_status_changes_status_differs", "from_status <> to_status");
+
+ t.HasCheckConstraint("ck_receipt_status_changes_to_status_valid", "to_status IN ('Draft', 'PendingSupplyApproval', 'PendingFinanceApproval', 'Approved', 'Issued', 'Cancelled')");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.Role", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("integer")
+ .HasColumnName("id");
+
+ b.Property("Code")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("code");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)")
+ .HasColumnName("name");
+
+ b.HasKey("Id")
+ .HasName("pk_roles");
+
+ b.HasIndex("Code")
+ .IsUnique()
+ .HasDatabaseName("ix_roles_code");
+
+ b.HasIndex("Name")
+ .IsUnique()
+ .HasDatabaseName("ix_roles_name");
+
+ b.ToTable("roles", (string)null);
+
+ b.HasData(
+ new
+ {
+ Id = 1,
+ Code = "Supply",
+ Name = "Supply"
+ },
+ new
+ {
+ Id = 2,
+ Code = "SupplyDirector",
+ Name = "Supply Director"
+ },
+ new
+ {
+ Id = 3,
+ Code = "Finance",
+ Name = "Finance"
+ },
+ new
+ {
+ Id = 4,
+ Code = "Admin",
+ Name = "Admin"
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.User", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer")
+ .HasColumnName("id");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("DisplayName")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("display_name");
+
+ b.Property("Email")
+ .IsRequired()
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)")
+ .HasColumnName("email");
+
+ b.Property("EntraObjectId")
+ .HasColumnType("uuid")
+ .HasColumnName("entra_object_id");
+
+ b.Property("IsActive")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(true)
+ .HasColumnName("is_active");
+
+ b.Property("RoleId")
+ .HasColumnType("integer")
+ .HasColumnName("role_id");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.Property("Version")
+ .IsConcurrencyToken()
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("xid")
+ .HasColumnName("xmin");
+
+ b.HasKey("Id")
+ .HasName("pk_users");
+
+ b.HasIndex("Email")
+ .IsUnique()
+ .HasDatabaseName("ix_users_email");
+
+ b.HasIndex("EntraObjectId")
+ .IsUnique()
+ .HasDatabaseName("ix_users_entra_object_id");
+
+ b.HasIndex("RoleId")
+ .HasDatabaseName("ix_users_role_id");
+
+ b.ToTable("users", null, t =>
+ {
+ t.HasCheckConstraint("ck_users_email_lowercase", "email = lower(email)");
+ });
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.UserAccountChange", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasColumnName("id")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("Action")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasColumnName("action");
+
+ b.Property("ChangedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("changed_at")
+ .HasDefaultValueSql("now()");
+
+ b.Property("ChangedByUserId")
+ .HasColumnType("integer")
+ .HasColumnName("changed_by_user_id");
+
+ b.Property("NewDisplayName")
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("new_display_name");
+
+ b.Property("NewEmail")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)")
+ .HasColumnName("new_email");
+
+ b.Property("NewIsActive")
+ .HasColumnType("boolean")
+ .HasColumnName("new_is_active");
+
+ b.Property("NewRoleId")
+ .HasColumnType("integer")
+ .HasColumnName("new_role_id");
+
+ b.Property("OldDisplayName")
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("old_display_name");
+
+ b.Property("OldEmail")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)")
+ .HasColumnName("old_email");
+
+ b.Property("OldIsActive")
+ .HasColumnType("boolean")
+ .HasColumnName("old_is_active");
+
+ b.Property("OldRoleId")
+ .HasColumnType("integer")
+ .HasColumnName("old_role_id");
+
+ b.Property("UserId")
+ .HasColumnType("integer")
+ .HasColumnName("user_id");
+
+ b.HasKey("Id")
+ .HasName("pk_user_account_changes");
+
+ b.HasIndex("ChangedByUserId")
+ .HasDatabaseName("ix_user_account_changes_changed_by_user_id");
+
+ b.HasIndex("NewRoleId")
+ .HasDatabaseName("ix_user_account_changes_new_role_id");
+
+ b.HasIndex("OldRoleId")
+ .HasDatabaseName("ix_user_account_changes_old_role_id");
+
+ b.HasIndex("UserId")
+ .HasDatabaseName("ix_user_account_changes_user_id");
+
+ b.ToTable("user_account_changes", (string)null);
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.BcItemMapping", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", "CatalogItem")
+ .WithMany()
+ .HasForeignKey("CatalogItemId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_bc_item_mappings_catalog_items_catalog_item_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.User", "ConfirmedBy")
+ .WithMany()
+ .HasForeignKey("ConfirmedByUserId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_bc_item_mappings_users_confirmed_by_user_id");
+
+ b.Navigation("CatalogItem");
+
+ b.Navigation("ConfirmedBy");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.BcItemMappingChange", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.User", "ChangedBy")
+ .WithMany()
+ .HasForeignKey("ChangedByUserId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_bc_item_mapping_changes_users_changed_by_user_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", null)
+ .WithMany()
+ .HasForeignKey("NewCatalogItemId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_bc_item_mapping_changes_catalog_items_new_catalog_item_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", null)
+ .WithMany()
+ .HasForeignKey("OldCatalogItemId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_bc_item_mapping_changes_catalog_items_old_catalog_item_id");
+
+ b.Navigation("ChangedBy");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.CatalogItem", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.QualityClass", "QualityClass")
+ .WithMany()
+ .HasForeignKey("QualityClassCode")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_catalog_items_quality_classes_quality_class");
+
+ b.Navigation("QualityClass");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.FoodItem", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", "CatalogItem")
+ .WithMany()
+ .HasForeignKey("CatalogItemId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .HasConstraintName("fk_food_items_catalog_items_catalog_item_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.Donor", "Donor")
+ .WithMany("FoodItems")
+ .HasForeignKey("DonorId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_food_items_donors_donor_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.QualityClass", "QualityClass")
+ .WithMany()
+ .HasForeignKey("Quality")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_food_items_quality_classes_quality");
+
+ b.Navigation("CatalogItem");
+
+ b.Navigation("Donor");
+
+ b.Navigation("QualityClass");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.Price", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.CatalogItem", "CatalogItem")
+ .WithMany("Prices")
+ .HasForeignKey("CatalogItemId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_prices_catalog_items_catalog_item_id");
+
+ b.Navigation("CatalogItem");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.Receipt", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.Donor", "Donor")
+ .WithMany()
+ .HasForeignKey("DonorId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_receipts_donors_donor_id");
+
+ b.Navigation("Donor");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.ReceiptItem", b =>
+ {
+ b.HasOne("MoissonMontreal.Core.Entities.FoodItem", "FoodItem")
+ .WithMany()
+ .HasForeignKey("FoodItemId", "DonorId")
+ .HasPrincipalKey("Id", "DonorId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_receipt_items_food_items_food_item_id_donor_id");
+
+ b.HasOne("MoissonMontreal.Core.Entities.Receipt", "Receipt")
+ .WithMany("Items")
+ .HasForeignKey("ReceiptId", "DonorId")
+ .HasPrincipalKey("Id", "DonorId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired()
+ .HasConstraintName("fk_receipt_items_receipts_receipt_id_donor_id");
+
+ b.Navigation("FoodItem");
+
+ b.Navigation("Receipt");
+ });
+
+ modelBuilder.Entity("MoissonMontreal.Core.Entities.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.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/20261204061822_AddUserAccountChanges.cs b/src/MoissonMontreal.Api/Data/Migrations/20261204061822_AddUserAccountChanges.cs
new file mode 100644
index 0000000..c27b13b
--- /dev/null
+++ b/src/MoissonMontreal.Api/Data/Migrations/20261204061822_AddUserAccountChanges.cs
@@ -0,0 +1,110 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace MoissonMontreal.Api.Data.Migrations
+{
+ ///
+ /// Adds the history of the changes made to employees' accounts, and the row version of users.
+ ///
+ public partial class AddUserAccountChanges : Migration
+ {
+ ///
+ /// Creates the user_account_changes table. The row version of users uses the PostgreSQL system column xmin,
+ /// so the generated SQL adds no column to users.
+ ///
+ /// Builder of the migration steps.
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "xmin",
+ table: "users",
+ type: "xid",
+ rowVersion: true,
+ nullable: false,
+ defaultValue: 0u);
+
+ migrationBuilder.CreateTable(
+ name: "user_account_changes",
+ columns: table => new
+ {
+ id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
+ user_id = table.Column(type: "integer", nullable: false),
+ action = table.Column(type: "character varying(20)", maxLength: 20, nullable: false),
+ old_email = table.Column(type: "character varying(256)", maxLength: 256, nullable: true),
+ new_email = table.Column(type: "character varying(256)", maxLength: 256, nullable: true),
+ old_display_name = table.Column(type: "character varying(200)", maxLength: 200, nullable: true),
+ new_display_name = table.Column(type: "character varying(200)", maxLength: 200, nullable: true),
+ old_role_id = table.Column(type: "integer", nullable: true),
+ new_role_id = table.Column(type: "integer", nullable: true),
+ old_is_active = table.Column(type: "boolean", nullable: true),
+ new_is_active = table.Column(type: "boolean", nullable: true),
+ changed_by_user_id = table.Column(type: "integer", nullable: false),
+ changed_at = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("pk_user_account_changes", x => x.id);
+ table.ForeignKey(
+ name: "fk_user_account_changes_roles_new_role_id",
+ column: x => x.new_role_id,
+ principalTable: "roles",
+ principalColumn: "id",
+ onDelete: ReferentialAction.Restrict);
+ table.ForeignKey(
+ name: "fk_user_account_changes_roles_old_role_id",
+ column: x => x.old_role_id,
+ principalTable: "roles",
+ principalColumn: "id",
+ onDelete: ReferentialAction.Restrict);
+ table.ForeignKey(
+ name: "fk_user_account_changes_users_changed_by_user_id",
+ column: x => x.changed_by_user_id,
+ principalTable: "users",
+ principalColumn: "id",
+ onDelete: ReferentialAction.Restrict);
+ table.ForeignKey(
+ name: "fk_user_account_changes_users_user_id",
+ column: x => x.user_id,
+ principalTable: "users",
+ principalColumn: "id",
+ onDelete: ReferentialAction.Restrict);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "ix_user_account_changes_changed_by_user_id",
+ table: "user_account_changes",
+ column: "changed_by_user_id");
+
+ migrationBuilder.CreateIndex(
+ name: "ix_user_account_changes_new_role_id",
+ table: "user_account_changes",
+ column: "new_role_id");
+
+ migrationBuilder.CreateIndex(
+ name: "ix_user_account_changes_old_role_id",
+ table: "user_account_changes",
+ column: "old_role_id");
+
+ migrationBuilder.CreateIndex(
+ name: "ix_user_account_changes_user_id",
+ table: "user_account_changes",
+ column: "user_id");
+ }
+
+ ///
+ /// Removes the user_account_changes table.
+ ///
+ /// Builder of the migration steps.
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "user_account_changes");
+
+ migrationBuilder.DropColumn(
+ name: "xmin",
+ table: "users");
+ }
+ }
+}
diff --git a/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs b/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs
index 4519cf5..4963600 100644
--- a/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs
+++ b/src/MoissonMontreal.Api/Data/Migrations/MoissonDbContextModelSnapshot.cs
@@ -796,6 +796,12 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
+ b.Property("Version")
+ .IsConcurrencyToken()
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("xid")
+ .HasColumnName("xmin");
+
b.HasKey("Id")
.HasName("pk_users");
@@ -816,6 +822,88 @@ protected override void BuildModel(ModelBuilder modelBuilder)
});
});
+ 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")
@@ -981,6 +1069,39 @@ protected override void BuildModel(ModelBuilder modelBuilder)
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");
diff --git a/src/MoissonMontreal.Api/Data/MoissonDbContext.cs b/src/MoissonMontreal.Api/Data/MoissonDbContext.cs
index 938dca3..746f6c7 100644
--- a/src/MoissonMontreal.Api/Data/MoissonDbContext.cs
+++ b/src/MoissonMontreal.Api/Data/MoissonDbContext.cs
@@ -68,6 +68,11 @@ public class MoissonDbContext(DbContextOptions options) : DbCo
///
public DbSet BcItemMappingChanges => Set();
+ ///
+ /// History of every change an administrator made to an employee's account, with the before and after values.
+ ///
+ public DbSet UserAccountChanges => Set();
+
///
/// Names every table, column, key and index in snake_case.
///
diff --git a/src/MoissonMontreal.Api/Program.cs b/src/MoissonMontreal.Api/Program.cs
index c011433..d9bd275 100644
--- a/src/MoissonMontreal.Api/Program.cs
+++ b/src/MoissonMontreal.Api/Program.cs
@@ -2,11 +2,13 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Identity.Web;
+using MoissonMontreal.Api.Accounts;
using MoissonMontreal.Api.Data;
using MoissonMontreal.Api.Authorization;
using MoissonMontreal.Api.Catalog;
using MoissonMontreal.Api.Pricing;
using MoissonMontreal.Api.Receipts;
+using MoissonMontreal.Core.Authorization;
var builder = WebApplication.CreateBuilder(args);
@@ -28,9 +30,12 @@
JwtBearerDefaults.AuthenticationScheme,
options => options.MapInboundClaims = false);
+// A valid Microsoft token is not enough: the employee must also have an active account in the users table,
+// so a deactivated or never-added account is refused on every route, not only on routes with a permission.
var accessAsUserPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireScope("access_as_user")
+ .AddRequirements(new PermissionRequirement(RoleCodes.All))
.Build();
builder.Services.AddAuthorizationBuilder()
@@ -43,6 +48,7 @@
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
+builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
diff --git a/src/MoissonMontreal.Core/Accounts/AccountEditedMeanwhileException.cs b/src/MoissonMontreal.Core/Accounts/AccountEditedMeanwhileException.cs
new file mode 100644
index 0000000..b2b755b
--- /dev/null
+++ b/src/MoissonMontreal.Core/Accounts/AccountEditedMeanwhileException.cs
@@ -0,0 +1,15 @@
+namespace MoissonMontreal.Core.Accounts;
+
+///
+/// Thrown when an account was changed by someone else since the administrator loaded it.
+/// Nothing is saved, so the other change is not overwritten: the administrator reloads the account and tries again.
+///
+/// Identifier of the account changed in the meantime.
+public class AccountEditedMeanwhileException(int userId)
+ : Exception($"Account {userId} was changed by someone else. Reload it and try again.")
+{
+ ///
+ /// Identifier of the account changed in the meantime.
+ ///
+ public int UserId { get; } = userId;
+}
diff --git a/src/MoissonMontreal.Core/Accounts/AccountEmailAlreadyUsedException.cs b/src/MoissonMontreal.Core/Accounts/AccountEmailAlreadyUsedException.cs
new file mode 100644
index 0000000..8d60bb3
--- /dev/null
+++ b/src/MoissonMontreal.Core/Accounts/AccountEmailAlreadyUsedException.cs
@@ -0,0 +1,14 @@
+namespace MoissonMontreal.Core.Accounts;
+
+///
+/// Thrown when an account is added or edited with an email another account already uses, regardless of case.
+/// The other account may be deactivated: it can then be reactivated instead of added again.
+///
+/// Email already used, in lowercase.
+public class AccountEmailAlreadyUsedException(string email) : Exception($"The email {email} is already used by another account.")
+{
+ ///
+ /// Email already used, in lowercase.
+ ///
+ public string Email { get; } = email;
+}
diff --git a/src/MoissonMontreal.Core/Accounts/AccountNotFoundException.cs b/src/MoissonMontreal.Core/Accounts/AccountNotFoundException.cs
new file mode 100644
index 0000000..3f56637
--- /dev/null
+++ b/src/MoissonMontreal.Core/Accounts/AccountNotFoundException.cs
@@ -0,0 +1,13 @@
+namespace MoissonMontreal.Core.Accounts;
+
+///
+/// Thrown when an account is changed but no account has this identifier.
+///
+/// Identifier that matches no account.
+public class AccountNotFoundException(int userId) : Exception($"Account {userId} does not exist.")
+{
+ ///
+ /// Identifier that matches no account.
+ ///
+ public int UserId { get; } = userId;
+}
diff --git a/src/MoissonMontreal.Core/Accounts/LastActiveAdminException.cs b/src/MoissonMontreal.Core/Accounts/LastActiveAdminException.cs
new file mode 100644
index 0000000..327126a
--- /dev/null
+++ b/src/MoissonMontreal.Core/Accounts/LastActiveAdminException.cs
@@ -0,0 +1,14 @@
+namespace MoissonMontreal.Core.Accounts;
+
+///
+/// Thrown when a change would leave the app without any active administrator, so nobody could manage accounts anymore.
+///
+/// Identifier of the last active administrator.
+public class LastActiveAdminException(int userId)
+ : Exception($"Account {userId} is the last active administrator: it cannot lose the role or be deactivated.")
+{
+ ///
+ /// Identifier of the last active administrator.
+ ///
+ public int UserId { get; } = userId;
+}
diff --git a/src/MoissonMontreal.Core/Accounts/OwnAccountChangeException.cs b/src/MoissonMontreal.Core/Accounts/OwnAccountChangeException.cs
new file mode 100644
index 0000000..765a8c6
--- /dev/null
+++ b/src/MoissonMontreal.Core/Accounts/OwnAccountChangeException.cs
@@ -0,0 +1,15 @@
+namespace MoissonMontreal.Core.Accounts;
+
+///
+/// Thrown when an administrator tries to change their own role or remove their own access,
+/// so they cannot lock themselves out by mistake. Another administrator has to do it.
+///
+/// Identifier of the administrator's own account.
+public class OwnAccountChangeException(int userId)
+ : Exception("You cannot change your own role or remove your own access. Ask another administrator.")
+{
+ ///
+ /// Identifier of the administrator's own account.
+ ///
+ public int UserId { get; } = userId;
+}
diff --git a/src/MoissonMontreal.Core/Accounts/RoleNotFoundException.cs b/src/MoissonMontreal.Core/Accounts/RoleNotFoundException.cs
new file mode 100644
index 0000000..913eaaa
--- /dev/null
+++ b/src/MoissonMontreal.Core/Accounts/RoleNotFoundException.cs
@@ -0,0 +1,13 @@
+namespace MoissonMontreal.Core.Accounts;
+
+///
+/// Thrown when an account is given a role code that matches no role.
+///
+/// Code that matches no role.
+public class RoleNotFoundException(string roleCode) : Exception($"Role {roleCode} does not exist.")
+{
+ ///
+ /// Code that matches no role.
+ ///
+ public string RoleCode { get; } = roleCode;
+}
diff --git a/src/MoissonMontreal.Core/Authorization/RoleCodes.cs b/src/MoissonMontreal.Core/Authorization/RoleCodes.cs
index 9ddbf72..da58878 100644
--- a/src/MoissonMontreal.Core/Authorization/RoleCodes.cs
+++ b/src/MoissonMontreal.Core/Authorization/RoleCodes.cs
@@ -25,4 +25,9 @@ public static class RoleCodes
/// Administrator: everything, plus accounts, the price grid and the quality percentages.
///
public const string Admin = "Admin";
+
+ ///
+ /// Codes of every role, used when any active employee is allowed regardless of their role.
+ ///
+ public static IReadOnlyList All { get; } = [Supply, SupplyDirector, Finance, Admin];
}
diff --git a/src/MoissonMontreal.Core/Dtos/AccountChangeDto.cs b/src/MoissonMontreal.Core/Dtos/AccountChangeDto.cs
new file mode 100644
index 0000000..812588b
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/AccountChangeDto.cs
@@ -0,0 +1,33 @@
+namespace MoissonMontreal.Core.Dtos;
+
+///
+/// One change in the history of an account. Action is Created, Updated, RoleChanged, Deactivated or Reactivated.
+/// Only the values the change touched are filled; the others are null.
+///
+/// Identifier of the change.
+/// Kind of change.
+/// Email before the change.
+/// Email after the change.
+/// Name before the change.
+/// Name after the change.
+/// Role before the change.
+/// Role after the change.
+/// Access before the change.
+/// Access after the change.
+/// Administrator who made the change.
+/// Name of the administrator who made the change.
+/// Date and time of the change.
+public record AccountChangeDto(
+ Guid Id,
+ string Action,
+ string? OldEmail,
+ string? NewEmail,
+ string? OldDisplayName,
+ string? NewDisplayName,
+ string? OldRoleCode,
+ string? NewRoleCode,
+ bool? OldIsActive,
+ bool? NewIsActive,
+ int ChangedByUserId,
+ string ChangedByName,
+ DateTimeOffset ChangedAt);
diff --git a/src/MoissonMontreal.Core/Dtos/AccountCreateRequest.cs b/src/MoissonMontreal.Core/Dtos/AccountCreateRequest.cs
new file mode 100644
index 0000000..32e6d81
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/AccountCreateRequest.cs
@@ -0,0 +1,9 @@
+namespace MoissonMontreal.Core.Dtos;
+
+///
+/// Fields sent when an administrator adds an employee.
+///
+/// Work email of the employee.
+/// Name shown in the app.
+/// Code of the role, such as Supply.
+public record AccountCreateRequest(string? Email, string? DisplayName, string? RoleCode);
diff --git a/src/MoissonMontreal.Core/Dtos/AccountDto.cs b/src/MoissonMontreal.Core/Dtos/AccountDto.cs
new file mode 100644
index 0000000..c67b90c
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/AccountDto.cs
@@ -0,0 +1,27 @@
+namespace MoissonMontreal.Core.Dtos;
+
+///
+/// An employee's account returned by the API. Version must be sent back with every change, so a change made by another
+/// administrator in the meantime is detected instead of overwritten.
+///
+/// Identifier of the account.
+/// Work email, in lowercase.
+/// Name shown in the app.
+/// Code of the role, such as Admin.
+/// Name of the role shown on screen.
+/// False once the employee's access was removed.
+/// True once the employee has signed in and their Microsoft account is linked.
+/// Date and time the account was added.
+/// Date and time of the last change, or null if never changed.
+/// Version of the account, to send back with the next change.
+public record AccountDto(
+ int Id,
+ string Email,
+ string DisplayName,
+ string RoleCode,
+ string RoleName,
+ bool IsActive,
+ bool IsLinked,
+ DateTimeOffset CreatedAt,
+ DateTimeOffset? UpdatedAt,
+ uint Version);
diff --git a/src/MoissonMontreal.Core/Dtos/AccountRoleRequest.cs b/src/MoissonMontreal.Core/Dtos/AccountRoleRequest.cs
new file mode 100644
index 0000000..dd5dbe5
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/AccountRoleRequest.cs
@@ -0,0 +1,8 @@
+namespace MoissonMontreal.Core.Dtos;
+
+///
+/// Fields sent when an administrator gives an account another role.
+///
+/// Code of the new role.
+/// Version of the account the administrator loaded.
+public record AccountRoleRequest(string? RoleCode, uint? Version);
diff --git a/src/MoissonMontreal.Core/Dtos/AccountUpdateRequest.cs b/src/MoissonMontreal.Core/Dtos/AccountUpdateRequest.cs
new file mode 100644
index 0000000..387ff97
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/AccountUpdateRequest.cs
@@ -0,0 +1,9 @@
+namespace MoissonMontreal.Core.Dtos;
+
+///
+/// Fields sent when an administrator edits the name and the email of an account.
+///
+/// New work email.
+/// New name.
+/// Version of the account the administrator loaded.
+public record AccountUpdateRequest(string? Email, string? DisplayName, uint? Version);
diff --git a/src/MoissonMontreal.Core/Dtos/AccountVersionRequest.cs b/src/MoissonMontreal.Core/Dtos/AccountVersionRequest.cs
new file mode 100644
index 0000000..b0edb6c
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/AccountVersionRequest.cs
@@ -0,0 +1,7 @@
+namespace MoissonMontreal.Core.Dtos;
+
+///
+/// Field sent when an administrator removes or gives back an employee's access.
+///
+/// Version of the account the administrator loaded.
+public record AccountVersionRequest(uint? Version);
diff --git a/src/MoissonMontreal.Core/Dtos/CurrentUserDto.cs b/src/MoissonMontreal.Core/Dtos/CurrentUserDto.cs
index 60c37e4..44811a0 100644
--- a/src/MoissonMontreal.Core/Dtos/CurrentUserDto.cs
+++ b/src/MoissonMontreal.Core/Dtos/CurrentUserDto.cs
@@ -1,3 +1,11 @@
namespace MoissonMontreal.Core.Dtos;
-public record CurrentUserDto(string? ObjectId, string? Name, string? Email, string? TenantId);
+///
+/// The signed-in employee, as returned by GET /api/me: who they are in Microsoft Entra ID, and their role in the app.
+///
+/// Identifier of the employee's Microsoft account (the oid claim).
+/// Name from the Microsoft account.
+/// Work email, or the Microsoft username when the token has no email.
+/// Identifier of the Moisson Montréal tenant.
+/// Code of the employee's role in the app, such as Admin. It comes from the users table, not from Entra ID.
+public record CurrentUserDto(string? ObjectId, string? Name, string? Email, string? TenantId, string Role);
diff --git a/src/MoissonMontreal.Core/Dtos/RoleDto.cs b/src/MoissonMontreal.Core/Dtos/RoleDto.cs
new file mode 100644
index 0000000..1417fba
--- /dev/null
+++ b/src/MoissonMontreal.Core/Dtos/RoleDto.cs
@@ -0,0 +1,8 @@
+namespace MoissonMontreal.Core.Dtos;
+
+///
+/// A role an administrator can give to an account.
+///
+/// Code of the role, sent back when the role is chosen.
+/// Name of the role shown on screen.
+public record RoleDto(string Code, string Name);
diff --git a/src/MoissonMontreal.Core/Entities/User.cs b/src/MoissonMontreal.Core/Entities/User.cs
index 80dc05b..77e027e 100644
--- a/src/MoissonMontreal.Core/Entities/User.cs
+++ b/src/MoissonMontreal.Core/Entities/User.cs
@@ -5,6 +5,16 @@ namespace MoissonMontreal.Core.Entities;
///
public class User
{
+ ///
+ /// Longest email stored for a user.
+ ///
+ public const int EmailMaxLength = 256;
+
+ ///
+ /// Longest name stored for a user.
+ ///
+ public const int DisplayNameMaxLength = 200;
+
///
/// Identifier of the user in the app, assigned by the database.
///
@@ -49,4 +59,10 @@ public class User
/// Date and time of the last change, or null if the user was never changed.
///
public DateTimeOffset? UpdatedAt { get; set; }
+
+ ///
+ /// Version of the row, changed by the database on every update. Two administrators editing the account at the same time
+ /// cannot silently overwrite each other: the second save sees a different version and is refused.
+ ///
+ public uint Version { get; set; }
}
\ No newline at end of file
diff --git a/src/MoissonMontreal.Core/Entities/UserAccountAction.cs b/src/MoissonMontreal.Core/Entities/UserAccountAction.cs
new file mode 100644
index 0000000..67aadc9
--- /dev/null
+++ b/src/MoissonMontreal.Core/Entities/UserAccountAction.cs
@@ -0,0 +1,32 @@
+namespace MoissonMontreal.Core.Entities;
+
+///
+/// Kind of change an administrator made to an employee's account.
+///
+public enum UserAccountAction
+{
+ ///
+ /// The employee was added with a work email, a name and a role.
+ ///
+ Created,
+
+ ///
+ /// The name or the email of the account was edited.
+ ///
+ Updated,
+
+ ///
+ /// The employee was given another role.
+ ///
+ RoleChanged,
+
+ ///
+ /// The employee's access was removed. The account is kept so the history stays attributed to them.
+ ///
+ Deactivated,
+
+ ///
+ /// The employee's access was given back.
+ ///
+ Reactivated
+}
diff --git a/src/MoissonMontreal.Core/Entities/UserAccountChange.cs b/src/MoissonMontreal.Core/Entities/UserAccountChange.cs
new file mode 100644
index 0000000..7df5041
--- /dev/null
+++ b/src/MoissonMontreal.Core/Entities/UserAccountChange.cs
@@ -0,0 +1,83 @@
+namespace MoissonMontreal.Core.Entities;
+
+///
+/// One change an administrator made to an employee's account, kept for history with its before and after values.
+/// Only the values the action touched are filled: for example, a deactivation only fills the active flags.
+///
+public class UserAccountChange
+{
+ ///
+ /// Identifier of the change, assigned by the database.
+ ///
+ public Guid Id { get; set; }
+
+ ///
+ /// Identifier of the account that was changed.
+ ///
+ public int UserId { get; set; }
+
+ ///
+ /// Account that was changed.
+ ///
+ public User User { get; set; } = null!;
+
+ ///
+ /// Kind of change.
+ ///
+ public UserAccountAction Action { get; set; }
+
+ ///
+ /// Email before the change, or null when the action did not touch the email.
+ ///
+ public string? OldEmail { get; set; }
+
+ ///
+ /// Email after the change, or null when the action did not touch the email.
+ ///
+ public string? NewEmail { get; set; }
+
+ ///
+ /// Name before the change, or null when the action did not touch the name.
+ ///
+ public string? OldDisplayName { get; set; }
+
+ ///
+ /// Name after the change, or null when the action did not touch the name.
+ ///
+ public string? NewDisplayName { get; set; }
+
+ ///
+ /// Identifier of the role before the change, or null when the action did not touch the role.
+ ///
+ public int? OldRoleId { get; set; }
+
+ ///
+ /// Identifier of the role after the change, or null when the action did not touch the role.
+ ///
+ public int? NewRoleId { get; set; }
+
+ ///
+ /// Whether the account was active before the change, or null when the action did not touch it.
+ ///
+ public bool? OldIsActive { get; set; }
+
+ ///
+ /// Whether the account is active after the change, or null when the action did not touch it.
+ ///
+ public bool? NewIsActive { get; set; }
+
+ ///
+ /// Identifier of the administrator who made the change.
+ ///
+ public int ChangedByUserId { get; set; }
+
+ ///
+ /// Administrator who made the change.
+ ///
+ public User ChangedBy { get; set; } = null!;
+
+ ///
+ /// Date and time of the change, set by the database.
+ ///
+ public DateTimeOffset ChangedAt { get; set; }
+}
diff --git a/src/MoissonMontreal.Desktop/Design/DesignData.cs b/src/MoissonMontreal.Desktop/Design/DesignData.cs
index d1f69d0..f3fec4d 100644
--- a/src/MoissonMontreal.Desktop/Design/DesignData.cs
+++ b/src/MoissonMontreal.Desktop/Design/DesignData.cs
@@ -20,7 +20,12 @@ public static class DesignData
///
/// Login page ViewModel whose sign-in does nothing.
///
- public static LoginViewModel Login { get; } = new(new FakeAuthService(), () => { });
+ public static LoginViewModel Login { get; } = new(new FakeAuthService(), () => System.Threading.Tasks.Task.CompletedTask);
+
+ ///
+ /// Account page ViewModel backed by a , signed in as the preview administrator.
+ ///
+ public static AccountsViewModel Accounts { get; } = new(new FakeApiClient(), "preview@example.org");
///
/// Donor profile page ViewModel backed by a , with an empty form.
diff --git a/src/MoissonMontreal.Desktop/Design/FakeApiClient.cs b/src/MoissonMontreal.Desktop/Design/FakeApiClient.cs
index 758a40f..c161b2d 100644
--- a/src/MoissonMontreal.Desktop/Design/FakeApiClient.cs
+++ b/src/MoissonMontreal.Desktop/Design/FakeApiClient.cs
@@ -1,17 +1,26 @@
using System;
using System.Collections.Generic;
+using System.Net;
using System.Threading;
using System.Threading.Tasks;
-using MoissonMontreal.Core.Dtos;
using MoissonMontreal.Desktop.Services;
+using MoissonMontreal.Core.Authorization;
+using MoissonMontreal.Core.Dtos;
namespace MoissonMontreal.Desktop.Design;
///
-/// Fake API client for the IDE previewer. Always reports the API as online, without any network call.
+/// Fake API client for the IDE previewer. Always reports the API as online and returns sample data, without any network call.
///
public class FakeApiClient : IApiClient
{
+ ///
+ /// Sample account shown in the previewer.
+ ///
+ private static readonly AccountDto SampleAccount = new(
+ 2, "jean.tremblay@moissonmontreal.org", "Jean Tremblay", RoleCodes.Supply, "Supply",
+ true, true, DateTimeOffset.UtcNow, null, 1);
+
///
public Task IsApiReachableAsync(CancellationToken cancellationToken = default)
{
@@ -19,17 +28,61 @@ public Task IsApiReachableAsync(CancellationToken cancellationToken = defa
}
///
- public Task GetCurrentUserAsync(CancellationToken cancellationToken = default)
+ public Task> GetCurrentUserAsync(CancellationToken cancellationToken = default)
{
var user = new CurrentUserDto(
ObjectId: "00000000-0000-0000-0000-000000000000",
Name: "Preview User",
Email: "preview@example.org",
- TenantId: null);
- return Task.FromResult(user);
+ TenantId: null,
+ Role: RoleCodes.Admin);
+ return Task.FromResult(ApiResult.Ok(user, HttpStatusCode.OK));
}
///
+ public Task>> GetAccountsAsync(CancellationToken cancellationToken = default)
+ {
+ List accounts =
+ [
+ new(1, "preview@example.org", "Preview User", RoleCodes.Admin, "Admin", true, true, DateTimeOffset.UtcNow, null, 1),
+ SampleAccount,
+ new(3, "former.employee@moissonmontreal.org", "Former Employee", RoleCodes.Finance, "Finance", false, true, DateTimeOffset.UtcNow, null, 1),
+ ];
+ return Task.FromResult(ApiResult>.Ok(accounts, HttpStatusCode.OK));
+ }
+
+ ///
+ public Task>> GetRolesAsync(CancellationToken cancellationToken = default)
+ {
+ List roles =
+ [
+ new(RoleCodes.Supply, "Supply"),
+ new(RoleCodes.SupplyDirector, "Supply Director"),
+ new(RoleCodes.Finance, "Finance"),
+ new(RoleCodes.Admin, "Admin"),
+ ];
+ return Task.FromResult(ApiResult>.Ok(roles, HttpStatusCode.OK));
+ }
+
+ ///
+ public Task> CreateAccountAsync(AccountCreateRequest request, CancellationToken cancellationToken = default) =>
+ Task.FromResult(ApiResult.Ok(SampleAccount, HttpStatusCode.Created));
+
+ ///
+ public Task> UpdateAccountAsync(int id, AccountUpdateRequest request, CancellationToken cancellationToken = default) =>
+ Task.FromResult(ApiResult.Ok(SampleAccount, HttpStatusCode.OK));
+
+ ///
+ public Task> ChangeAccountRoleAsync(int id, AccountRoleRequest request, CancellationToken cancellationToken = default) =>
+ Task.FromResult(ApiResult.Ok(SampleAccount, HttpStatusCode.OK));
+
+ ///
+ public Task> DeactivateAccountAsync(int id, uint version, CancellationToken cancellationToken = default) =>
+ Task.FromResult(ApiResult.Ok(SampleAccount, HttpStatusCode.OK));
+
+ ///
+ public Task> ReactivateAccountAsync(int id, uint version, CancellationToken cancellationToken = default) =>
+ Task.FromResult(ApiResult.Ok(SampleAccount, HttpStatusCode.OK));
public Task GetDonorAsync(Guid id, CancellationToken cancellationToken = default)
{
return Task.FromResult(DonorResult.Of(DonorResultStatus.NotFound));
diff --git a/src/MoissonMontreal.Desktop/Services/ApiClient.cs b/src/MoissonMontreal.Desktop/Services/ApiClient.cs
index 0fbde47..8d47e3b 100644
--- a/src/MoissonMontreal.Desktop/Services/ApiClient.cs
+++ b/src/MoissonMontreal.Desktop/Services/ApiClient.cs
@@ -1,5 +1,6 @@
-using System;
using System.Collections.Generic;
+using System.Linq;
+using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
@@ -15,6 +16,11 @@ namespace MoissonMontreal.Desktop.Services;
///
public class ApiClient : IApiClient
{
+ ///
+ /// Message shown when the API cannot be reached at all.
+ ///
+ private const string ServerUnavailableMessage = "The server is unavailable. Check your internet connection and try again.";
+
///
/// HTTP client configured in App with the API's base address and timeout.
///
@@ -50,28 +56,116 @@ public async Task IsApiReachableAsync(CancellationToken cancellationToken
}
///
- public async Task GetCurrentUserAsync(CancellationToken cancellationToken = default)
+ public Task> GetCurrentUserAsync(CancellationToken cancellationToken = default) =>
+ SendAsync(HttpMethod.Get, "api/me", null, cancellationToken);
+
+ ///
+ public Task>> GetAccountsAsync(CancellationToken cancellationToken = default) =>
+ SendAsync>(HttpMethod.Get, "api/accounts", null, cancellationToken);
+
+ ///
+ public Task>> GetRolesAsync(CancellationToken cancellationToken = default) =>
+ SendAsync>(HttpMethod.Get, "api/accounts/roles", null, cancellationToken);
+
+ ///
+ public Task> CreateAccountAsync(AccountCreateRequest request, CancellationToken cancellationToken = default) =>
+ SendAsync(HttpMethod.Post, "api/accounts", request, cancellationToken);
+
+ ///
+ public Task> UpdateAccountAsync(int id, AccountUpdateRequest request, CancellationToken cancellationToken = default) =>
+ SendAsync(HttpMethod.Put, $"api/accounts/{id}", request, cancellationToken);
+
+ ///
+ public Task> ChangeAccountRoleAsync(int id, AccountRoleRequest request, CancellationToken cancellationToken = default) =>
+ SendAsync(HttpMethod.Put, $"api/accounts/{id}/role", request, cancellationToken);
+
+ ///
+ public Task> DeactivateAccountAsync(int id, uint version, CancellationToken cancellationToken = default) =>
+ SendAsync(HttpMethod.Post, $"api/accounts/{id}/deactivate", new AccountVersionRequest(version), cancellationToken);
+
+ ///
+ public Task> ReactivateAccountAsync(int id, uint version, CancellationToken cancellationToken = default) =>
+ SendAsync(HttpMethod.Post, $"api/accounts/{id}/reactivate", new AccountVersionRequest(version), cancellationToken);
+
+ ///
+ /// Sends a request and turns the answer into a value or a message the screen can show.
+ ///
+ /// Type of the value the API returns.
+ /// HTTP method.
+ /// Path of the route, relative to the API's base address.
+ /// Object sent as JSON, or null for no body.
+ /// Lets the caller stop the request early.
+ /// The value, or a failure with the HTTP status and a message.
+ private async Task> SendAsync(HttpMethod method, string path, object? body, CancellationToken cancellationToken)
{
try
{
- using var response = await _httpClient.GetAsync("api/me", cancellationToken);
+ using var request = new HttpRequestMessage(method, path);
+ if (body is not null)
+ {
+ request.Content = JsonContent.Create(body, body.GetType());
+ }
+
+ using var response = await _httpClient.SendAsync(request, cancellationToken);
if (!response.IsSuccessStatusCode)
{
- return null;
+ return ApiResult.Fail(response.StatusCode, await ReadErrorAsync(response, cancellationToken));
}
- return await response.Content.ReadFromJsonAsync(cancellationToken);
+ var value = await response.Content.ReadFromJsonAsync(cancellationToken);
+ return value is null
+ ? ApiResult.Fail(response.StatusCode, "The server sent an empty answer.")
+ : ApiResult.Ok(value, response.StatusCode);
}
catch (HttpRequestException)
{
- return null;
+ return ApiResult.Fail(null, ServerUnavailableMessage);
}
catch (TaskCanceledException)
{
- return null;
+ return ApiResult.Fail(null, ServerUnavailableMessage);
}
}
+ ///
+ /// Reads the message of an error answer: the field errors of a validation problem, or the detail of another problem.
+ /// Falls back to a message based on the status when the answer has no readable body.
+ ///
+ /// Error answer of the API.
+ /// Lets the caller stop reading early.
+ /// A message the screen can show.
+ private static async Task ReadErrorAsync(HttpResponseMessage response, CancellationToken cancellationToken)
+ {
+ try
+ {
+ using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
+ var root = document.RootElement;
+ if (root.TryGetProperty("errors", out var errors) && errors.ValueKind == JsonValueKind.Object)
+ {
+ var messages = errors.EnumerateObject()
+ .SelectMany(field => field.Value.EnumerateArray().Select(message => message.GetString()))
+ .Where(message => !string.IsNullOrWhiteSpace(message));
+ return string.Join(" ", messages);
+ }
+
+ if (root.TryGetProperty("detail", out var detail) && detail.GetString() is { Length: > 0 } detailText)
+ {
+ return detailText;
+ }
+ }
+ catch (JsonException)
+ {
+ // The answer has no JSON body, for example a 403 sent by the authorization policy.
+ }
+
+ return response.StatusCode switch
+ {
+ HttpStatusCode.Unauthorized => "Your session has expired. Sign out and sign in again.",
+ HttpStatusCode.Forbidden => "You do not have access to this action.",
+ _ => $"The server refused the request ({(int)response.StatusCode}).",
+ };
+ }
+
///
public Task GetDonorAsync(Guid id, CancellationToken cancellationToken = default) =>
SendDonorAsync(() => _httpClient.GetAsync($"api/donors/{id}", cancellationToken), cancellationToken);
diff --git a/src/MoissonMontreal.Desktop/Services/ApiResult.cs b/src/MoissonMontreal.Desktop/Services/ApiResult.cs
new file mode 100644
index 0000000..2f6b0ab
--- /dev/null
+++ b/src/MoissonMontreal.Desktop/Services/ApiResult.cs
@@ -0,0 +1,34 @@
+using System.Net;
+
+namespace MoissonMontreal.Desktop.Services;
+
+///
+/// Result of a call to the API: the value when it succeeded, or a message the screen can show when it failed.
+///
+/// Type of the value returned by the API.
+/// Value returned by the API, or null when the call failed.
+/// HTTP status of the answer, or null when the API could not be reached.
+/// Message explaining the failure, or null when the call succeeded.
+public record ApiResult(T? Value, HttpStatusCode? StatusCode, string? ErrorMessage)
+{
+ ///
+ /// True when the API answered with a value.
+ ///
+ public bool IsSuccess => ErrorMessage is null && Value is not null;
+
+ ///
+ /// Builds a successful result.
+ ///
+ /// Value returned by the API.
+ /// HTTP status of the answer.
+ /// The successful result.
+ public static ApiResult Ok(T value, HttpStatusCode statusCode) => new(value, statusCode, null);
+
+ ///
+ /// Builds a failed result.
+ ///
+ /// HTTP status of the answer, or null when the API could not be reached.
+ /// Message explaining the failure.
+ /// The failed result.
+ public static ApiResult Fail(HttpStatusCode? statusCode, string errorMessage) => new(default, statusCode, errorMessage);
+}
diff --git a/src/MoissonMontreal.Desktop/Services/IApiClient.cs b/src/MoissonMontreal.Desktop/Services/IApiClient.cs
index 9ffff12..dfc9acd 100644
--- a/src/MoissonMontreal.Desktop/Services/IApiClient.cs
+++ b/src/MoissonMontreal.Desktop/Services/IApiClient.cs
@@ -1,3 +1,4 @@
+using System.Collections.Generic;
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -18,11 +19,69 @@ public interface IApiClient
Task IsApiReachableAsync(CancellationToken cancellationToken = default);
///
- /// Gets the signed-in user from the API's api/me endpoint, which requires a valid access token.
+ /// Gets the signed-in employee and their role from the API's api/me endpoint.
///
/// Lets the caller stop the request early.
- /// The current user, or null if the API refused the request (for example 401 without a valid token) or could not be reached.
- Task GetCurrentUserAsync(CancellationToken cancellationToken = default);
+ /// The employee, or a failure: 403 when they have no active account, no status when the API could not be reached.
+ Task> GetCurrentUserAsync(CancellationToken cancellationToken = default);
+
+ ///
+ /// Lists every account, active ones first. Administrators only.
+ ///
+ /// Lets the caller stop the request early.
+ /// The accounts, or a failure with a message.
+ Task>> GetAccountsAsync(CancellationToken cancellationToken = default);
+
+ ///
+ /// Lists the roles an account can be given. Administrators only.
+ ///
+ /// Lets the caller stop the request early.
+ /// The roles, or a failure with a message.
+ Task>> GetRolesAsync(CancellationToken cancellationToken = default);
+
+ ///
+ /// Adds an employee. Administrators only.
+ ///
+ /// Email, name and role of the employee.
+ /// Lets the caller stop the request early.
+ /// The new account, or a failure with a message.
+ Task> CreateAccountAsync(AccountCreateRequest request, CancellationToken cancellationToken = default);
+
+ ///
+ /// Edits the name and the email of an account. Administrators only.
+ ///
+ /// Identifier of the account.
+ /// New email, new name and the version of the account shown on screen.
+ /// Lets the caller stop the request early.
+ /// The edited account, or a failure with a message.
+ Task> UpdateAccountAsync(int id, AccountUpdateRequest request, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gives an account another role. Administrators only.
+ ///
+ /// Identifier of the account.
+ /// Code of the new role and the version of the account shown on screen.
+ /// Lets the caller stop the request early.
+ /// The account with its new role, or a failure with a message.
+ Task> ChangeAccountRoleAsync(int id, AccountRoleRequest request, CancellationToken cancellationToken = default);
+
+ ///
+ /// Removes an employee's access. Administrators only.
+ ///
+ /// Identifier of the account.
+ /// Version of the account shown on screen.
+ /// Lets the caller stop the request early.
+ /// The deactivated account, or a failure with a message.
+ Task> DeactivateAccountAsync(int id, uint version, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gives an employee their access back. Administrators only.
+ ///
+ /// Identifier of the account.
+ /// Version of the account shown on screen.
+ /// Lets the caller stop the request early.
+ /// The reactivated account, or a failure with a message.
+ Task> ReactivateAccountAsync(int id, uint version, CancellationToken cancellationToken = default);
///
/// Gets one donor.
diff --git a/src/MoissonMontreal.Desktop/ViewModels/AccountsViewModel.cs b/src/MoissonMontreal.Desktop/ViewModels/AccountsViewModel.cs
new file mode 100644
index 0000000..01c82b4
--- /dev/null
+++ b/src/MoissonMontreal.Desktop/ViewModels/AccountsViewModel.cs
@@ -0,0 +1,343 @@
+using System;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Threading.Tasks;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using MoissonMontreal.Core.Dtos;
+using MoissonMontreal.Desktop.Services;
+
+namespace MoissonMontreal.Desktop.ViewModels;
+
+///
+/// Logic of the temporary account screen, for administrators: list the accounts, add an employee, edit an account,
+/// change its role and remove or give back its access. Role and access changes ask for a confirmation first.
+/// The API enforces every rule; this screen only shows its answers.
+///
+public partial class AccountsViewModel : ViewModelBase
+{
+ ///
+ /// Client used to call the account routes of the API.
+ ///
+ private readonly IApiClient _apiClient;
+
+ ///
+ /// Email of the signed-in administrator, used to disable the actions they cannot do on their own account.
+ ///
+ private readonly string? _currentUserEmail;
+
+ ///
+ /// Change waiting for the administrator's confirmation, or null when nothing is waiting.
+ ///
+ private Func? _pendingChange;
+
+ ///