diff --git a/postman/collections/Expenses Server/API/Accounts/Members/.resources/definition.yaml b/postman/collections/Expenses Server/API/Accounts/Members/.resources/definition.yaml new file mode 100644 index 0000000..07c39b7 --- /dev/null +++ b/postman/collections/Expenses Server/API/Accounts/Members/.resources/definition.yaml @@ -0,0 +1,2 @@ +$kind: collection +order: 518 diff --git a/postman/collections/Expenses Server/API/Accounts/Members/Get member.request.yaml b/postman/collections/Expenses Server/API/Accounts/Members/Get member.request.yaml new file mode 100644 index 0000000..37c57ef --- /dev/null +++ b/postman/collections/Expenses Server/API/Accounts/Members/Get member.request.yaml @@ -0,0 +1,5 @@ +$kind: http-request +url: "{{base_url}}/api/accounts/00000000-0000-0000-0003-000000000001/members/00000000-0000-0000-0006-000000000003" +method: GET +settings: {} +order: 2000 diff --git a/postman/collections/Expenses Server/API/Accounts/Members/List members.request.yaml b/postman/collections/Expenses Server/API/Accounts/Members/List members.request.yaml new file mode 100644 index 0000000..53819ab --- /dev/null +++ b/postman/collections/Expenses Server/API/Accounts/Members/List members.request.yaml @@ -0,0 +1,14 @@ +$kind: http-request +url: "{{base_url}}/api/accounts/00000000-0000-0000-0003-000000000001/members?limit=20&offset=0" +method: GET +queryParams: + - key: limit + value: "20" + disabled: false + description: "" + - key: offset + value: "0" + disabled: false + description: "" +settings: {} +order: 1000 diff --git a/postman/collections/Expenses Server/API/Accounts/Members/Remove member.request.yaml b/postman/collections/Expenses Server/API/Accounts/Members/Remove member.request.yaml new file mode 100644 index 0000000..cdda75e --- /dev/null +++ b/postman/collections/Expenses Server/API/Accounts/Members/Remove member.request.yaml @@ -0,0 +1,5 @@ +$kind: http-request +url: "{{base_url}}/api/accounts/00000000-0000-0000-0003-000000000001/members/00000000-0000-0000-0006-000000000003" +method: DELETE +settings: {} +order: 4000 diff --git a/postman/collections/Expenses Server/API/Accounts/Members/Upsert member.request.yaml b/postman/collections/Expenses Server/API/Accounts/Members/Upsert member.request.yaml new file mode 100644 index 0000000..793046a --- /dev/null +++ b/postman/collections/Expenses Server/API/Accounts/Members/Upsert member.request.yaml @@ -0,0 +1,11 @@ +$kind: http-request +url: "{{base_url}}/api/accounts/00000000-0000-0000-0003-000000000001/members/00000000-0000-0000-0006-000000000003" +method: PUT +body: + type: json + content: |- + { + "user_id": "00000000-0000-0000-0000-000000000002" + } +settings: {} +order: 3000 diff --git a/server/.sqlx/query-0782e5945f71e1541ead35a500ce23d6241853c39b99a575b75b3795b54493d9.json b/server/.sqlx/query-0782e5945f71e1541ead35a500ce23d6241853c39b99a575b75b3795b54493d9.json new file mode 100644 index 0000000..94b1737 --- /dev/null +++ b/server/.sqlx/query-0782e5945f71e1541ead35a500ce23d6241853c39b99a575b75b3795b54493d9.json @@ -0,0 +1,80 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO account_members (id, account_id, user_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (id, account_id) DO UPDATE SET\n user_id = EXCLUDED.user_id\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n COALESCE(old_row.account_id, new_row.account_id) AS \"old_account_id!\",\n COALESCE(old_row.user_id, new_row.user_id) AS \"old_user_id!\",\n new_row.id AS \"id!\",\n new_row.account_id AS \"account_id!\",\n new_row.user_id AS \"user_id!\"\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "old_id?", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "old_account_id!", + "type_info": "Uuid", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "old_user_id!", + "type_info": "Uuid", + "origin": "Expression" + }, + { + "ordinal": 3, + "name": "id!", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "id" + } + } + }, + { + "ordinal": 4, + "name": "account_id!", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "account_id" + } + } + }, + { + "ordinal": 5, + "name": "user_id!", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "user_id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false, + null, + null, + false, + false, + false + ] + }, + "hash": "0782e5945f71e1541ead35a500ce23d6241853c39b99a575b75b3795b54493d9" +} diff --git a/server/.sqlx/query-d4855797f718e952505eff69420fe7884714c2e6f5f10215c38c2a5571bbcd9a.json b/server/.sqlx/query-d4855797f718e952505eff69420fe7884714c2e6f5f10215c38c2a5571bbcd9a.json new file mode 100644 index 0000000..3e9b191 --- /dev/null +++ b/server/.sqlx/query-d4855797f718e952505eff69420fe7884714c2e6f5f10215c38c2a5571bbcd9a.json @@ -0,0 +1,54 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT id, account_id, user_id\n FROM account_members\n WHERE account_id = $1\n ORDER BY id\n LIMIT $2\n OFFSET $3\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "account_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "account_id" + } + } + }, + { + "ordinal": 2, + "name": "user_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "user_id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Int8", + "Int8" + ] + }, + "nullable": [ + false, + false, + false + ] + }, + "hash": "d4855797f718e952505eff69420fe7884714c2e6f5f10215c38c2a5571bbcd9a" +} diff --git a/server/.sqlx/query-e2bb42012ebde4620c1a6a3b7802d3b07ea759310f7f20feb9929d87509c4c34.json b/server/.sqlx/query-e2bb42012ebde4620c1a6a3b7802d3b07ea759310f7f20feb9929d87509c4c34.json new file mode 100644 index 0000000..a54f560 --- /dev/null +++ b/server/.sqlx/query-e2bb42012ebde4620c1a6a3b7802d3b07ea759310f7f20feb9929d87509c4c34.json @@ -0,0 +1,53 @@ +{ + "db_name": "PostgreSQL", + "query": "\n DELETE FROM account_members\n WHERE account_id = $1 AND id = $2\n RETURNING id, account_id, user_id\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "account_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "account_id" + } + } + }, + { + "ordinal": 2, + "name": "user_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "user_id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false + ] + }, + "hash": "e2bb42012ebde4620c1a6a3b7802d3b07ea759310f7f20feb9929d87509c4c34" +} diff --git a/server/.sqlx/query-fec880b0ff2fddb5e5a835abed62e7e85e8c7838740a6a41cb50a677c8bcdd11.json b/server/.sqlx/query-fec880b0ff2fddb5e5a835abed62e7e85e8c7838740a6a41cb50a677c8bcdd11.json new file mode 100644 index 0000000..1c9f765 --- /dev/null +++ b/server/.sqlx/query-fec880b0ff2fddb5e5a835abed62e7e85e8c7838740a6a41cb50a677c8bcdd11.json @@ -0,0 +1,53 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT id, account_id, user_id\n FROM account_members\n WHERE account_id = $1 AND id = $2\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "account_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "account_id" + } + } + }, + { + "ordinal": 2, + "name": "user_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "account_members", + "name": "user_id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false + ] + }, + "hash": "fec880b0ff2fddb5e5a835abed62e7e85e8c7838740a6a41cb50a677c8bcdd11" +} diff --git a/server/migrations/20260918000001_create_account_members.sql b/server/migrations/20260918000001_create_account_members.sql index f19294e..1a9f7ab 100644 --- a/server/migrations/20260918000001_create_account_members.sql +++ b/server/migrations/20260918000001_create_account_members.sql @@ -1,5 +1,7 @@ CREATE TABLE account_members ( + id UUID DEFAULT gen_random_uuid (), account_id UUID NOT NULL CONSTRAINT fk_account_members_account REFERENCES accounts (id), user_id UUID NOT NULL CONSTRAINT fk_account_members_user REFERENCES users (id), - PRIMARY KEY (account_id, user_id) + PRIMARY KEY (id, account_id), + CONSTRAINT uq_account_members_account_user UNIQUE (account_id, user_id) ); \ No newline at end of file diff --git a/server/migrations/20261231000000_seed_demo_data.sql b/server/migrations/20261231000000_seed_demo_data.sql index 0204e3d..2709e92 100644 --- a/server/migrations/20261231000000_seed_demo_data.sql +++ b/server/migrations/20261231000000_seed_demo_data.sql @@ -50,12 +50,14 @@ VALUES ( ); INSERT INTO - account_members (account_id, user_id) + account_members (id, account_id, user_id) VALUES ( + '00000000-0000-0000-0006-000000000001', '00000000-0000-0000-0003-000000000001', '00000000-0000-0000-0000-000000000001' ), ( + '00000000-0000-0000-0006-000000000002', '00000000-0000-0000-0003-000000000002', '00000000-0000-0000-0000-000000000002' ); diff --git a/server/src/database.rs b/server/src/database.rs index 4b3d094..1827b06 100644 --- a/server/src/database.rs +++ b/server/src/database.rs @@ -1,3 +1,4 @@ +pub mod account_members; pub mod accounts; pub mod dtos; mod error_codes; @@ -8,7 +9,7 @@ pub mod user_app_secrets; pub mod user_apps; pub mod users; -use error_codes::PG_FOREIGN_KEY_VIOLATION; +use error_codes::{PG_FOREIGN_KEY_VIOLATION, PG_UNIQUE_VIOLATION}; #[derive(Debug, thiserror::Error)] pub enum DatabaseError { @@ -19,6 +20,13 @@ pub enum DatabaseError { source: sqlx::Error, }, + #[error("unique violation ({constraint}): {source}")] + UniqueViolation { + constraint: Constraint, + #[source] + source: sqlx::Error, + }, + #[error("internal error: {0}")] Internal(#[source] sqlx::Error), } @@ -39,6 +47,19 @@ impl From for DatabaseError { source: sqlx::Error::Database(db_err), } } + sqlx::Error::Database(db_err) + if db_err.code().as_deref() == Some(PG_UNIQUE_VIOLATION) => + { + let constraint = db_err + .constraint() + .map(Constraint::from) + .unwrap_or(Constraint::Unnamed); + + DatabaseError::UniqueViolation { + constraint, + source: sqlx::Error::Database(db_err), + } + } _ => DatabaseError::Internal(err), } } @@ -46,6 +67,15 @@ impl From for DatabaseError { #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Constraint { + #[error("account member account constraint")] + AccountMemberAccount, + + #[error("account member account user constraint")] + AccountMemberAccountUser, + + #[error("account member user constraint")] + AccountMemberUser, + #[error("user app user constraint")] UserAppUser, @@ -68,6 +98,9 @@ pub enum Constraint { impl From<&str> for Constraint { fn from(constraint: &str) -> Self { match constraint { + "fk_account_members_account" => Constraint::AccountMemberAccount, + "uq_account_members_account_user" => Constraint::AccountMemberAccountUser, + "fk_account_members_user" => Constraint::AccountMemberUser, "fk_user_apps_user" => Constraint::UserAppUser, "fk_user_app_secrets_app" => Constraint::UserAppSecretApp, "fk_transactions_account" => Constraint::TransactionAccount, diff --git a/server/src/database/account_members.rs b/server/src/database/account_members.rs new file mode 100644 index 0000000..05a355b --- /dev/null +++ b/server/src/database/account_members.rs @@ -0,0 +1,129 @@ +use uuid::Uuid; + +use super::{ + DatabaseError, + dtos::{AccountMemberRow, Upsert}, +}; + +pub struct Query { + pub account_id: Uuid, + pub limit: Option, + pub offset: Option, +} + +pub async fn list<'e, E>(executor: E, query: Query) -> Result, DatabaseError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + sqlx::query_as!( + AccountMemberRow, + r#" + SELECT id, account_id, user_id + FROM account_members + WHERE account_id = $1 + ORDER BY id + LIMIT $2 + OFFSET $3 + "#, + query.account_id, + query.limit, + query.offset, + ) + .fetch_all(executor) + .await + .map_err(DatabaseError::from) +} + +pub async fn get_by_id<'e, E>( + executor: E, + account_id: Uuid, + id: Uuid, +) -> Result, DatabaseError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + sqlx::query_as!( + AccountMemberRow, + r#" + SELECT id, account_id, user_id + FROM account_members + WHERE account_id = $1 AND id = $2 + "#, + account_id, + id, + ) + .fetch_optional(executor) + .await + .map_err(DatabaseError::from) +} + +pub async fn upsert<'e, E>( + executor: E, + member: AccountMemberRow, +) -> Result, DatabaseError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + let row = sqlx::query!( + r#" + INSERT INTO account_members (id, account_id, user_id) + VALUES ($1, $2, $3) + ON CONFLICT (id, account_id) DO UPDATE SET + user_id = EXCLUDED.user_id + RETURNING WITH (OLD AS old_row, NEW AS new_row) + old_row.id AS "old_id?", + COALESCE(old_row.account_id, new_row.account_id) AS "old_account_id!", + COALESCE(old_row.user_id, new_row.user_id) AS "old_user_id!", + new_row.id AS "id!", + new_row.account_id AS "account_id!", + new_row.user_id AS "user_id!" + "#, + member.id, + member.account_id, + member.user_id, + ) + .fetch_one(executor) + .await + .map_err(DatabaseError::from)?; + + // `old_id` indicates whether there was a previous row before the upsert, other old fields are + // coalesced with the new row's values in case there was no previous row. This enables static + // typing on the previous row instead of having to check nullability for each old field in code. + let previous = row.old_id.map(|id| AccountMemberRow { + id, + account_id: row.old_account_id, + user_id: row.old_user_id, + }); + + Ok(Upsert { + previous, + current: AccountMemberRow { + id: row.id, + account_id: row.account_id, + user_id: row.user_id, + }, + }) +} + +pub async fn delete_by_id<'e, E>( + executor: E, + account_id: Uuid, + id: Uuid, +) -> Result, DatabaseError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + sqlx::query_as!( + AccountMemberRow, + r#" + DELETE FROM account_members + WHERE account_id = $1 AND id = $2 + RETURNING id, account_id, user_id + "#, + account_id, + id, + ) + .fetch_optional(executor) + .await + .map_err(DatabaseError::from) +} diff --git a/server/src/database/dtos.rs b/server/src/database/dtos.rs index 5fdf78a..702e08b 100644 --- a/server/src/database/dtos.rs +++ b/server/src/database/dtos.rs @@ -1,4 +1,5 @@ mod account; +mod account_member; mod recurring_transaction; mod results; mod token; @@ -8,6 +9,7 @@ mod user_app; mod user_app_secret; pub use account::*; +pub use account_member::*; pub use recurring_transaction::*; pub use results::*; pub use token::*; diff --git a/server/src/database/dtos/account_member.rs b/server/src/database/dtos/account_member.rs new file mode 100644 index 0000000..3b741c3 --- /dev/null +++ b/server/src/database/dtos/account_member.rs @@ -0,0 +1,7 @@ +use uuid::Uuid; + +pub struct AccountMemberRow { + pub id: Uuid, + pub account_id: Uuid, + pub user_id: Uuid, +} diff --git a/server/src/database/error_codes.rs b/server/src/database/error_codes.rs index 76fbd24..c66ddaf 100644 --- a/server/src/database/error_codes.rs +++ b/server/src/database/error_codes.rs @@ -1 +1,2 @@ pub const PG_FOREIGN_KEY_VIOLATION: &str = "23503"; +pub const PG_UNIQUE_VIOLATION: &str = "23505"; diff --git a/server/src/domain.rs b/server/src/domain.rs index d3027c2..5785064 100644 --- a/server/src/domain.rs +++ b/server/src/domain.rs @@ -1,4 +1,5 @@ mod account; +mod account_member; mod cents; mod direction; mod recurring_transaction; @@ -10,6 +11,7 @@ mod user_app; mod user_app_secret; pub use account::*; +pub use account_member::*; pub use cents::*; pub use direction::*; pub use recurring_transaction::*; diff --git a/server/src/domain/account_member.rs b/server/src/domain/account_member.rs new file mode 100644 index 0000000..83064f1 --- /dev/null +++ b/server/src/domain/account_member.rs @@ -0,0 +1,8 @@ +use uuid::Uuid; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccountMember { + pub id: Uuid, + pub account_id: Uuid, + pub user_id: Uuid, +} diff --git a/server/src/repository.rs b/server/src/repository.rs index bdf7103..4d4027b 100644 --- a/server/src/repository.rs +++ b/server/src/repository.rs @@ -3,6 +3,7 @@ use crate::{ domain::{CentsError, ScheduleError, UserAppSecretError}, }; +pub mod account_members; pub mod accounts; pub mod dtos; mod encoding; @@ -21,6 +22,13 @@ pub enum RepositoryError { #[error(transparent)] Decode(#[from] DecodeError), + #[error("duplicate ({entity})")] + Duplicate { + entity: DuplicateEntity, + #[source] + source: DatabaseError, + }, + #[error("reference violation ({kind}: {relation})")] ReferenceViolation { relation: ReferenceRelation, @@ -60,8 +68,17 @@ pub enum DecodeError { UserAppSecret(#[from] UserAppSecretError), } +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum DuplicateEntity { + #[error("account member")] + AccountMember, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] pub enum ReferenceRelation { + #[error("account member")] + AccountMember, + #[error("account")] Account, diff --git a/server/src/repository/account_members.rs b/server/src/repository/account_members.rs new file mode 100644 index 0000000..ab105f2 --- /dev/null +++ b/server/src/repository/account_members.rs @@ -0,0 +1,227 @@ +use uuid::Uuid; + +use super::{ + DecodeError, DuplicateEntity, QueryConversionError, ReferenceRelation, ReferenceViolationKind, + RepositoryError, dtos::Upsert, +}; +use crate::{ + database::{Constraint, DatabaseError, account_members as db, dtos::AccountMemberRow}, + domain::AccountMember, +}; + +pub struct Query { + pub account_id: Uuid, + pub limit: Option, + pub offset: Option, +} + +pub async fn list<'e, E>(executor: E, query: Query) -> Result, RepositoryError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + let query = db::Query { + account_id: query.account_id, + limit: query + .limit + .map(|limit| i64::try_from(limit).map_err(|_| QueryConversionError::Limit(limit))) + .transpose()?, + offset: query + .offset + .map(|offset| i64::try_from(offset).map_err(|_| QueryConversionError::Offset(offset))) + .transpose()?, + }; + + let members = db::list(executor, query) + .await? + .into_iter() + .map(decode) + .collect::, _>>()?; + + Ok(members) +} + +pub async fn get_by_id<'e, E>( + executor: E, + account_id: Uuid, + id: Uuid, +) -> Result, RepositoryError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + let member = db::get_by_id(executor, account_id, id) + .await? + .map(decode) + .transpose()?; + + Ok(member) +} + +pub async fn upsert<'e, E>( + executor: E, + member: AccountMember, +) -> Result, RepositoryError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + let member = db::upsert(executor, encode(member)) + .await + .map_err(classify_upsert_error)? + .try_map(decode)? + .into(); + + Ok(member) +} + +fn classify_upsert_error(error: DatabaseError) -> RepositoryError { + match &error { + DatabaseError::ForeignKeyViolation { + constraint: Constraint::AccountMemberAccount, + .. + } => RepositoryError::ReferenceViolation { + relation: ReferenceRelation::Account, + kind: ReferenceViolationKind::Missing, + source: error, + }, + DatabaseError::ForeignKeyViolation { + constraint: Constraint::AccountMemberUser, + .. + } => RepositoryError::ReferenceViolation { + relation: ReferenceRelation::User, + kind: ReferenceViolationKind::Missing, + source: error, + }, + DatabaseError::UniqueViolation { + constraint: Constraint::AccountMemberAccountUser, + .. + } => RepositoryError::Duplicate { + entity: DuplicateEntity::AccountMember, + source: error, + }, + _ => RepositoryError::Database(error), + } +} + +pub async fn delete_by_id<'e, E>( + executor: E, + account_id: Uuid, + id: Uuid, +) -> Result, RepositoryError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + let member = db::delete_by_id(executor, account_id, id) + .await? + .map(decode) + .transpose()?; + + Ok(member) +} + +fn decode(row: AccountMemberRow) -> Result { + Ok(AccountMember { + id: row.id, + account_id: row.account_id, + user_id: row.user_id, + }) +} + +fn encode(member: AccountMember) -> AccountMemberRow { + AccountMemberRow { + id: member.id, + account_id: member.account_id, + user_id: member.user_id, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn foreign_key_violation(constraint: Constraint) -> DatabaseError { + DatabaseError::ForeignKeyViolation { + constraint, + source: sqlx::Error::Protocol("test database cause".to_owned()), + } + } + + #[test] + fn classifies_account_member_upsert_account_foreign_key_violation() { + let error = classify_upsert_error(foreign_key_violation(Constraint::AccountMemberAccount)); + assert!(matches!( + error, + RepositoryError::ReferenceViolation { + relation: ReferenceRelation::Account, + kind: ReferenceViolationKind::Missing, + .. + } + )); + } + + #[test] + fn classifies_account_member_upsert_user_foreign_key_violation() { + let error = classify_upsert_error(foreign_key_violation(Constraint::AccountMemberUser)); + assert!(matches!( + error, + RepositoryError::ReferenceViolation { + relation: ReferenceRelation::User, + kind: ReferenceViolationKind::Missing, + .. + } + )); + } + + #[test] + fn keeps_unknown_upsert_foreign_keys_generic() { + let error = classify_upsert_error(foreign_key_violation(Constraint::Unnamed)); + assert!(matches!(error, RepositoryError::Database(_))); + } + + fn row() -> AccountMemberRow { + AccountMemberRow { + id: Uuid::new_v4(), + account_id: Uuid::new_v4(), + user_id: Uuid::new_v4(), + } + } + + #[test] + fn classifies_account_member_upsert_unique_violation() { + let error = classify_upsert_error(DatabaseError::UniqueViolation { + constraint: Constraint::AccountMemberAccountUser, + source: sqlx::Error::Protocol("test database cause".to_owned()), + }); + assert!(matches!( + error, + RepositoryError::Duplicate { + entity: DuplicateEntity::AccountMember, + .. + } + )); + } + + #[test] + fn keeps_unknown_upsert_unique_violations_generic() { + let error = classify_upsert_error(DatabaseError::UniqueViolation { + constraint: Constraint::Unnamed, + source: sqlx::Error::Protocol("test database cause".to_owned()), + }); + assert!(matches!(error, RepositoryError::Database(_))); + } + + #[test] + fn decodes_valid_rows() { + let row = row(); + let (id, account_id, user_id) = (row.id, row.account_id, row.user_id); + let member = decode(row).unwrap(); + assert_eq!(member.id, id); + assert_eq!(member.account_id, account_id); + assert_eq!(member.user_id, user_id); + } + + #[test] + fn round_trips_through_rows() { + let member = decode(row()).unwrap(); + let round_trip = decode(encode(member.clone())).unwrap(); + assert_eq!(round_trip, member); + } +} diff --git a/server/src/repository/accounts.rs b/server/src/repository/accounts.rs index f5914bd..7d6ace5 100644 --- a/server/src/repository/accounts.rs +++ b/server/src/repository/accounts.rs @@ -106,6 +106,14 @@ where fn classify_delete_error(error: DatabaseError) -> RepositoryError { match &error { + DatabaseError::ForeignKeyViolation { + constraint: Constraint::AccountMemberAccount, + .. + } => RepositoryError::ReferenceViolation { + relation: ReferenceRelation::AccountMember, + kind: ReferenceViolationKind::StillReferenced, + source: error, + }, DatabaseError::ForeignKeyViolation { constraint: Constraint::TransactionAccount, .. @@ -153,6 +161,19 @@ mod tests { } } + #[test] + fn classifies_account_member_account_delete_foreign_key_constraint() { + let error = classify_delete_error(foreign_key_violation(Constraint::AccountMemberAccount)); + assert!(matches!( + error, + RepositoryError::ReferenceViolation { + relation: ReferenceRelation::AccountMember, + kind: ReferenceViolationKind::StillReferenced, + .. + } + )); + } + #[test] fn classifies_account_delete_foreign_key_constraint() { let error = classify_delete_error(foreign_key_violation( diff --git a/server/src/repository/users.rs b/server/src/repository/users.rs index 57d2f7a..8a0bbe2 100644 --- a/server/src/repository/users.rs +++ b/server/src/repository/users.rs @@ -1,8 +1,11 @@ use uuid::Uuid; -use super::{DecodeError, QueryConversionError, RepositoryError, dtos::Upsert}; +use super::{ + DecodeError, QueryConversionError, ReferenceRelation, ReferenceViolationKind, RepositoryError, + dtos::Upsert, +}; use crate::{ - database::{DatabaseError, dtos::UserRow, users as db}, + database::{Constraint, DatabaseError, dtos::UserRow, users as db}, domain::User, }; @@ -70,7 +73,17 @@ where } fn classify_delete_error(error: DatabaseError) -> RepositoryError { - RepositoryError::Database(error) + match &error { + DatabaseError::ForeignKeyViolation { + constraint: Constraint::AccountMemberUser, + .. + } => RepositoryError::ReferenceViolation { + relation: ReferenceRelation::AccountMember, + kind: ReferenceViolationKind::StillReferenced, + source: error, + }, + _ => RepositoryError::Database(error), + } } fn decode(row: UserRow) -> Result { @@ -85,8 +98,6 @@ fn encode(user: User) -> UserRow { mod tests { use uuid::Uuid; - use crate::database::Constraint; - use super::*; fn foreign_key_violation(constraint: Constraint) -> DatabaseError { @@ -96,6 +107,20 @@ mod tests { } } + #[test] + fn classifies_account_member_user_delete_foreign_key_constraint() { + let error = classify_delete_error(foreign_key_violation(Constraint::AccountMemberUser)); + + assert!(matches!( + error, + RepositoryError::ReferenceViolation { + relation: ReferenceRelation::AccountMember, + kind: ReferenceViolationKind::StillReferenced, + .. + } + )); + } + #[test] fn keeps_unknown_user_delete_foreign_keys_generic() { let error = classify_delete_error(foreign_key_violation(Constraint::Unnamed)); diff --git a/server/src/routes.rs b/server/src/routes.rs index 42d835e..fccbd92 100644 --- a/server/src/routes.rs +++ b/server/src/routes.rs @@ -2,6 +2,7 @@ use axum::{http::StatusCode, routing::get}; use crate::error::AppError; +mod account_members; mod accounts; mod auth_passkey; mod auth_token; @@ -19,6 +20,10 @@ pub fn create_router(pool: sqlx::PgPool) -> axum::Router { .nest("/auth/passkey", auth_passkey::create_router()) .nest("/auth/token", auth_token::create_router()) .nest("/accounts", accounts::create_router()) + .nest( + "/accounts/{account_id}/members", + account_members::create_router(), + ) .nest( "/scheduled-transactions", scheduled_transactions::create_router(), diff --git a/server/src/routes/account_members.rs b/server/src/routes/account_members.rs new file mode 100644 index 0000000..d28dccb --- /dev/null +++ b/server/src/routes/account_members.rs @@ -0,0 +1,125 @@ +use axum::{extract::State, http::StatusCode}; +use serde::Deserialize; +use sqlx::PgPool; +use uuid::Uuid; + +use super::{ + dtos::account_member::{AccountMemberRequest, AccountMemberResponse}, + extractors::{Auth, Json, Path, Query}, +}; +use crate::{ + error::AppError, + repository::{self, RepositoryError}, +}; + +pub fn create_router() -> axum::Router { + axum::Router::new() + .route("/", axum::routing::get(list_account_members)) + .route( + "/{member_id}", + axum::routing::get(get_account_member) + .put(upsert_account_member) + .delete(delete_account_member), + ) +} + +#[derive(Debug, Deserialize)] +pub struct QueryParams { + pub limit: Option, + pub offset: Option, +} + +#[axum::debug_handler] +#[tracing::instrument(skip(pool))] +async fn list_account_members( + Auth(auth): Auth, + State(pool): State, + Path(account_id): Path, + Query(query): Query, +) -> Result>, AppError> { + let query = repository::account_members::Query { + account_id, + limit: Some(query.limit.unwrap_or(20)), + offset: query.offset, + }; + + let mut tx = pool.begin().await.map_err(RepositoryError::from)?; + ensure_account_exists(&mut tx, account_id).await?; + let members = repository::account_members::list(&mut *tx, query) + .await? + .into_iter() + .map(AccountMemberResponse::from) + .collect(); + tx.commit().await.map_err(RepositoryError::from)?; + + Ok(Json(members)) +} + +#[axum::debug_handler] +#[tracing::instrument(skip(pool))] +async fn get_account_member( + Auth(auth): Auth, + State(pool): State, + Path((account_id, member_id)): Path<(Uuid, Uuid)>, +) -> Result, AppError> { + let mut tx = pool.begin().await.map_err(RepositoryError::from)?; + ensure_account_exists(&mut tx, account_id).await?; + let member = repository::account_members::get_by_id(&mut *tx, account_id, member_id) + .await? + .ok_or(AppError::NotFound)?; + tx.commit().await.map_err(RepositoryError::from)?; + + Ok(Json(member.into())) +} + +#[axum::debug_handler] +#[tracing::instrument(skip(pool, member))] +async fn upsert_account_member( + Auth(auth): Auth, + State(pool): State, + Path((account_id, member_id)): Path<(Uuid, Uuid)>, + Json(member): Json, +) -> Result<(StatusCode, Json), AppError> { + let member = member.into_domain(member_id, account_id)?; + + let mut tx = pool.begin().await.map_err(RepositoryError::from)?; + ensure_account_exists(&mut tx, account_id).await?; + let upserted = repository::account_members::upsert(&mut *tx, member).await?; + tx.commit().await.map_err(RepositoryError::from)?; + + let status = if upserted.previous.is_some() { + StatusCode::OK + } else { + StatusCode::CREATED + }; + + Ok((status, Json(upserted.current.into()))) +} + +#[axum::debug_handler] +#[tracing::instrument(skip(pool))] +async fn delete_account_member( + Auth(auth): Auth, + State(pool): State, + Path((account_id, member_id)): Path<(Uuid, Uuid)>, +) -> Result { + let mut tx = pool.begin().await.map_err(RepositoryError::from)?; + ensure_account_exists(&mut tx, account_id).await?; + let deleted = + repository::account_members::delete_by_id(&mut *tx, account_id, member_id).await?; + tx.commit().await.map_err(RepositoryError::from)?; + + deleted.ok_or(AppError::NotFound)?; + + Ok(StatusCode::NO_CONTENT) +} + +async fn ensure_account_exists( + connection: &mut sqlx::PgConnection, + account_id: Uuid, +) -> Result<(), AppError> { + repository::accounts::get_by_id(&mut *connection, account_id) + .await? + .map(|_| ()) + .ok_or(AppError::NotFound) +} diff --git a/server/src/routes/dtos.rs b/server/src/routes/dtos.rs index b110a98..f05fbd0 100644 --- a/server/src/routes/dtos.rs +++ b/server/src/routes/dtos.rs @@ -1,4 +1,5 @@ pub mod account; +pub mod account_member; pub mod direction; pub mod scheduled_transaction; pub mod token; diff --git a/server/src/routes/dtos/account_member.rs b/server/src/routes/dtos/account_member.rs new file mode 100644 index 0000000..381e29a --- /dev/null +++ b/server/src/routes/dtos/account_member.rs @@ -0,0 +1,88 @@ +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::domain; + +#[derive(Debug, Clone, Deserialize)] +pub struct AccountMemberRequest { + pub user_id: Uuid, +} + +impl AccountMemberRequest { + pub fn into_domain( + self, + id: Uuid, + account_id: Uuid, + ) -> Result { + Ok(domain::AccountMember { + id, + account_id, + user_id: self.user_id, + }) + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct AccountMemberResponse { + pub id: Uuid, + pub user_id: Uuid, +} + +impl From for AccountMemberResponse { + fn from(member: domain::AccountMember) -> Self { + Self { + id: member.id, + user_id: member.user_id, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request() -> AccountMemberRequest { + AccountMemberRequest { + user_id: Uuid::nil(), + } + } + + #[test] + fn serializes_account_member_response() { + let id = Uuid::new_v4(); + let member = request().into_domain(id, Uuid::new_v4()).unwrap(); + let response = serde_json::to_value(AccountMemberResponse::from(member)).unwrap(); + + assert_eq!(response["id"], id.to_string()); + assert_eq!(response["user_id"], Uuid::nil().to_string()); + assert!(response.get("account_id").is_none()); + } + + #[test] + fn deserializes_account_member_response_as_request() { + let member = request() + .into_domain(Uuid::new_v4(), Uuid::new_v4()) + .unwrap(); + let response = serde_json::to_value(AccountMemberResponse::from(member)).unwrap(); + let request: AccountMemberRequest = serde_json::from_value(response).unwrap(); + + assert_eq!(request.user_id, Uuid::nil()); + } + + #[test] + fn converts_between_dto_and_domain() { + let id = Uuid::new_v4(); + let account_id = Uuid::new_v4(); + let user_id = Uuid::new_v4(); + let member = AccountMemberRequest { user_id } + .into_domain(id, account_id) + .unwrap(); + assert_eq!(member.id, id); + assert_eq!(member.account_id, account_id); + assert_eq!(member.user_id, user_id); + + let response = AccountMemberResponse::from(member); + assert_eq!(response.id, id); + assert_eq!(response.user_id, user_id); + } +} diff --git a/server/src/routes/errors.rs b/server/src/routes/errors.rs index d6f7a9e..c68e5ba 100644 --- a/server/src/routes/errors.rs +++ b/server/src/routes/errors.rs @@ -103,6 +103,12 @@ impl ClientError for RepositoryError { match self { Self::Database(_) | Self::Decode(_) => internal_error(), Self::QueryConversion(error) => (StatusCode::BAD_REQUEST, error.to_string().into()), + Self::Duplicate { entity, .. } => match entity { + crate::repository::DuplicateEntity::AccountMember => ( + StatusCode::CONFLICT, + "User is already a member of this account".into(), + ), + }, Self::ReferenceViolation { relation, kind, .. } => { use crate::repository::{ ReferenceRelation as Relation, ReferenceViolationKind as Kind, @@ -112,6 +118,14 @@ impl ClientError for RepositoryError { StatusCode::UNPROCESSABLE_ENTITY, "Account cannot be found".into(), ), + (Kind::Missing, Relation::User) => ( + StatusCode::UNPROCESSABLE_ENTITY, + "User cannot be found".into(), + ), + (Kind::StillReferenced, Relation::AccountMember) => ( + StatusCode::CONFLICT, + "Still referenced by one or more account members".into(), + ), (Kind::StillReferenced, Relation::RecurringTransaction) => ( StatusCode::CONFLICT, "Still referenced by one or more recurring transactions".into(),