diff --git a/server/.sqlx/query-2c91d06bd5687a10c8b54386586b1c5be73ae4cc1a72351a78f26c136c429e1d.json b/server/.sqlx/query-2c91d06bd5687a10c8b54386586b1c5be73ae4cc1a72351a78f26c136c429e1d.json deleted file mode 100644 index bfbf7b4..0000000 --- a/server/.sqlx/query-2c91d06bd5687a10c8b54386586b1c5be73ae4cc1a72351a78f26c136c429e1d.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n\t\tINSERT INTO transactions (id, description, amount_cents, direction, date)\n\t\tVALUES ($1, $2, $3, $4, $5)\n\t\tON CONFLICT (id) DO UPDATE SET\n\t\t\tdescription = EXCLUDED.description,\n\t\t\tamount_cents = EXCLUDED.amount_cents,\n\t\t\tdirection = EXCLUDED.direction,\n\t\t\tdate = EXCLUDED.date\n\t\tRETURNING WITH (OLD AS old_row, NEW AS new_row)\n\t\t\told_row.id AS \"old_id?\",\n\t\t\tnew_row.id AS \"id!\",\n\t\t\tnew_row.description AS \"description!\",\n\t\t\tnew_row.amount_cents AS \"amount_cents!\",\n\t\t\tnew_row.direction AS \"direction!\",\n\t\t\tnew_row.date AS \"date!\"\n\t\t", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "old_id?", - "type_info": "Uuid" - }, - { - "ordinal": 1, - "name": "id!", - "type_info": "Uuid" - }, - { - "ordinal": 2, - "name": "description!", - "type_info": "Text" - }, - { - "ordinal": 3, - "name": "amount_cents!", - "type_info": "Int8" - }, - { - "ordinal": 4, - "name": "direction!", - "type_info": "Text" - }, - { - "ordinal": 5, - "name": "date!", - "type_info": "Timestamptz" - } - ], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Int8", - "Text", - "Timestamptz" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - false - ] - }, - "hash": "2c91d06bd5687a10c8b54386586b1c5be73ae4cc1a72351a78f26c136c429e1d" -} diff --git a/server/.sqlx/query-04e8934ac1d987fc859ed21a3fdc41f62165efb6248575e78d577ca333d025c2.json b/server/.sqlx/query-6fbffb56421dfc314468e6f7ea5b76594dfcdb06bd5d82ba61330fb8e51e88dc.json similarity index 68% rename from server/.sqlx/query-04e8934ac1d987fc859ed21a3fdc41f62165efb6248575e78d577ca333d025c2.json rename to server/.sqlx/query-6fbffb56421dfc314468e6f7ea5b76594dfcdb06bd5d82ba61330fb8e51e88dc.json index ad1dd76..0519897 100644 --- a/server/.sqlx/query-04e8934ac1d987fc859ed21a3fdc41f62165efb6248575e78d577ca333d025c2.json +++ b/server/.sqlx/query-6fbffb56421dfc314468e6f7ea5b76594dfcdb06bd5d82ba61330fb8e51e88dc.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n\t\tSELECT id, description, amount_cents, direction, date\n\t\tFROM transactions\n\t\tWHERE id = $1\n\t\t", + "query": "\n SELECT id, account_id, amount_cents, direction, date, description\n\t\tFROM transactions\n\t\tWHERE id = $1\n\t\t", "describe": { "columns": [ { @@ -10,8 +10,8 @@ }, { "ordinal": 1, - "name": "description", - "type_info": "Text" + "name": "account_id", + "type_info": "Uuid" }, { "ordinal": 2, @@ -27,6 +27,11 @@ "ordinal": 4, "name": "date", "type_info": "Timestamptz" + }, + { + "ordinal": 5, + "name": "description", + "type_info": "Text" } ], "parameters": { @@ -39,8 +44,9 @@ false, false, false, + false, false ] }, - "hash": "04e8934ac1d987fc859ed21a3fdc41f62165efb6248575e78d577ca333d025c2" + "hash": "6fbffb56421dfc314468e6f7ea5b76594dfcdb06bd5d82ba61330fb8e51e88dc" } diff --git a/server/.sqlx/query-7d7363a1746170ceec82763cadcf2e0803753901e73a2a8e04c87eb061bb724e.json b/server/.sqlx/query-7d7363a1746170ceec82763cadcf2e0803753901e73a2a8e04c87eb061bb724e.json new file mode 100644 index 0000000..eebbcb1 --- /dev/null +++ b/server/.sqlx/query-7d7363a1746170ceec82763cadcf2e0803753901e73a2a8e04c87eb061bb724e.json @@ -0,0 +1,91 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO recurring_transactions (\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (id) DO UPDATE SET\n name = EXCLUDED.name,\n account_id = EXCLUDED.account_id,\n amount_cents = EXCLUDED.amount_cents,\n direction = EXCLUDED.direction,\n starts_at = EXCLUDED.starts_at,\n ends_at = EXCLUDED.ends_at,\n recurrence_every = EXCLUDED.recurrence_every,\n recurrence_unit = EXCLUDED.recurrence_unit,\n weekend_adjustment = EXCLUDED.weekend_adjustment\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n new_row.id AS \"id!\",\n new_row.name AS \"name!\",\n new_row.account_id AS \"account_id!\",\n new_row.amount_cents AS \"amount_cents!\",\n new_row.direction AS \"direction!\",\n new_row.starts_at AS \"starts_at!\",\n new_row.ends_at AS \"ends_at?\",\n new_row.recurrence_every AS \"recurrence_every!\",\n new_row.recurrence_unit AS \"recurrence_unit!\",\n new_row.weekend_adjustment AS \"weekend_adjustment?\"\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "old_id?", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "id!", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "name!", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "account_id!", + "type_info": "Uuid" + }, + { + "ordinal": 4, + "name": "amount_cents!", + "type_info": "Int8" + }, + { + "ordinal": 5, + "name": "direction!", + "type_info": "Text" + }, + { + "ordinal": 6, + "name": "starts_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 7, + "name": "ends_at?", + "type_info": "Timestamptz" + }, + { + "ordinal": 8, + "name": "recurrence_every!", + "type_info": "Int4" + }, + { + "ordinal": 9, + "name": "recurrence_unit!", + "type_info": "Text" + }, + { + "ordinal": 10, + "name": "weekend_adjustment?", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Uuid", + "Int8", + "Text", + "Timestamptz", + "Timestamptz", + "Int4", + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + true + ] + }, + "hash": "7d7363a1746170ceec82763cadcf2e0803753901e73a2a8e04c87eb061bb724e" +} diff --git a/server/.sqlx/query-8999f47eebb460120538c7d2bdbb40dadf634e98977ae59d2398579f9be82d6f.json b/server/.sqlx/query-8999f47eebb460120538c7d2bdbb40dadf634e98977ae59d2398579f9be82d6f.json new file mode 100644 index 0000000..fbe0b94 --- /dev/null +++ b/server/.sqlx/query-8999f47eebb460120538c7d2bdbb40dadf634e98977ae59d2398579f9be82d6f.json @@ -0,0 +1,63 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO transactions (id, account_id, amount_cents, direction, date, description)\n VALUES ($1, $2, $3, $4, $5, $6)\n\t\tON CONFLICT (id) DO UPDATE SET\n account_id = EXCLUDED.account_id,\n\t\t\tamount_cents = EXCLUDED.amount_cents,\n\t\t\tdirection = EXCLUDED.direction,\n\t\t\tdate = EXCLUDED.date,\n\t\t\tdescription = EXCLUDED.description\n\t\tRETURNING WITH (OLD AS old_row, NEW AS new_row)\n\t\t\told_row.id AS \"old_id?\",\n\t\t\tnew_row.id AS \"id!\",\n new_row.account_id AS \"account_id!\",\n\t\t\tnew_row.amount_cents AS \"amount_cents!\",\n\t\t\tnew_row.direction AS \"direction!\",\n\t\t\tnew_row.date AS \"date!\",\n\t\t\tnew_row.description AS \"description!\"\n\t\t", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "old_id?", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "id!", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "account_id!", + "type_info": "Uuid" + }, + { + "ordinal": 3, + "name": "amount_cents!", + "type_info": "Int8" + }, + { + "ordinal": 4, + "name": "direction!", + "type_info": "Text" + }, + { + "ordinal": 5, + "name": "date!", + "type_info": "Timestamptz" + }, + { + "ordinal": 6, + "name": "description!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Int8", + "Text", + "Timestamptz", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "8999f47eebb460120538c7d2bdbb40dadf634e98977ae59d2398579f9be82d6f" +} diff --git a/server/.sqlx/query-e7d222f4f85fc93521d38786aff2d2b7012139d5b3175a4eae06988317475c5d.json b/server/.sqlx/query-a962ef0282ca37bb5eba2ee1b0bd93da2527f7e5a0c4332527f1e533f3ecd4f0.json similarity index 66% rename from server/.sqlx/query-e7d222f4f85fc93521d38786aff2d2b7012139d5b3175a4eae06988317475c5d.json rename to server/.sqlx/query-a962ef0282ca37bb5eba2ee1b0bd93da2527f7e5a0c4332527f1e533f3ecd4f0.json index 3ea41b1..4c3d7db 100644 --- a/server/.sqlx/query-e7d222f4f85fc93521d38786aff2d2b7012139d5b3175a4eae06988317475c5d.json +++ b/server/.sqlx/query-a962ef0282ca37bb5eba2ee1b0bd93da2527f7e5a0c4332527f1e533f3ecd4f0.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n\t\tSELECT id, description, amount_cents, direction, date\n\t\tFROM transactions\n\t\tORDER BY date DESC, id DESC\n\t\tLIMIT $1\n\t\tOFFSET $2\n\t\t", + "query": "\n SELECT id, account_id, amount_cents, direction, date, description\n\t\tFROM transactions\n\t\tORDER BY date DESC, id DESC\n\t\tLIMIT $1\n\t\tOFFSET $2\n\t\t", "describe": { "columns": [ { @@ -10,8 +10,8 @@ }, { "ordinal": 1, - "name": "description", - "type_info": "Text" + "name": "account_id", + "type_info": "Uuid" }, { "ordinal": 2, @@ -27,6 +27,11 @@ "ordinal": 4, "name": "date", "type_info": "Timestamptz" + }, + { + "ordinal": 5, + "name": "description", + "type_info": "Text" } ], "parameters": { @@ -40,8 +45,9 @@ false, false, false, + false, false ] }, - "hash": "e7d222f4f85fc93521d38786aff2d2b7012139d5b3175a4eae06988317475c5d" + "hash": "a962ef0282ca37bb5eba2ee1b0bd93da2527f7e5a0c4332527f1e533f3ecd4f0" } diff --git a/server/.sqlx/query-cd3573646e7cfe523b7dc97092134f22568eb9288e8d56522bdfbbc2aab43fb4.json b/server/.sqlx/query-cd3573646e7cfe523b7dc97092134f22568eb9288e8d56522bdfbbc2aab43fb4.json deleted file mode 100644 index f0dc97d..0000000 --- a/server/.sqlx/query-cd3573646e7cfe523b7dc97092134f22568eb9288e8d56522bdfbbc2aab43fb4.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO recurring_transactions (\n id,\n name,\n amount_cents,\n direction,\n source_account_id,\n destination_account_id,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n ON CONFLICT (id) DO UPDATE SET\n name = EXCLUDED.name,\n amount_cents = EXCLUDED.amount_cents,\n direction = EXCLUDED.direction,\n source_account_id = EXCLUDED.source_account_id,\n destination_account_id = EXCLUDED.destination_account_id,\n starts_at = EXCLUDED.starts_at,\n ends_at = EXCLUDED.ends_at,\n recurrence_every = EXCLUDED.recurrence_every,\n recurrence_unit = EXCLUDED.recurrence_unit,\n weekend_adjustment = EXCLUDED.weekend_adjustment\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n new_row.id AS \"id!\",\n new_row.name AS \"name!\",\n new_row.amount_cents AS \"amount_cents!\",\n new_row.direction AS \"direction!\",\n new_row.source_account_id AS \"source_account_id?\",\n new_row.destination_account_id AS \"destination_account_id?\",\n new_row.starts_at AS \"starts_at!\",\n new_row.ends_at AS \"ends_at?\",\n new_row.recurrence_every AS \"recurrence_every!\",\n new_row.recurrence_unit AS \"recurrence_unit!\",\n new_row.weekend_adjustment AS \"weekend_adjustment?\"\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "old_id?", - "type_info": "Uuid" - }, - { - "ordinal": 1, - "name": "id!", - "type_info": "Uuid" - }, - { - "ordinal": 2, - "name": "name!", - "type_info": "Text" - }, - { - "ordinal": 3, - "name": "amount_cents!", - "type_info": "Int8" - }, - { - "ordinal": 4, - "name": "direction!", - "type_info": "Text" - }, - { - "ordinal": 5, - "name": "source_account_id?", - "type_info": "Uuid" - }, - { - "ordinal": 6, - "name": "destination_account_id?", - "type_info": "Uuid" - }, - { - "ordinal": 7, - "name": "starts_at!", - "type_info": "Timestamptz" - }, - { - "ordinal": 8, - "name": "ends_at?", - "type_info": "Timestamptz" - }, - { - "ordinal": 9, - "name": "recurrence_every!", - "type_info": "Int4" - }, - { - "ordinal": 10, - "name": "recurrence_unit!", - "type_info": "Text" - }, - { - "ordinal": 11, - "name": "weekend_adjustment?", - "type_info": "Text" - } - ], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Int8", - "Text", - "Uuid", - "Uuid", - "Timestamptz", - "Timestamptz", - "Int4", - "Text", - "Text" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - true, - true, - false, - true, - false, - false, - true - ] - }, - "hash": "cd3573646e7cfe523b7dc97092134f22568eb9288e8d56522bdfbbc2aab43fb4" -} diff --git a/server/.sqlx/query-fae9d6766e5bce18e7917df6a0d6ad13ec035b8d409b880d6cff2ef9e2615fa4.json b/server/.sqlx/query-ed9ae08575930c5b161d3f0c0f50479e51b54e348e1651f4a4e9b8328741cec7.json similarity index 69% rename from server/.sqlx/query-fae9d6766e5bce18e7917df6a0d6ad13ec035b8d409b880d6cff2ef9e2615fa4.json rename to server/.sqlx/query-ed9ae08575930c5b161d3f0c0f50479e51b54e348e1651f4a4e9b8328741cec7.json index 5f5bfce..0bb429b 100644 --- a/server/.sqlx/query-fae9d6766e5bce18e7917df6a0d6ad13ec035b8d409b880d6cff2ef9e2615fa4.json +++ b/server/.sqlx/query-ed9ae08575930c5b161d3f0c0f50479e51b54e348e1651f4a4e9b8328741cec7.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT\n id,\n name,\n amount_cents,\n direction,\n source_account_id,\n destination_account_id,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_transactions\n WHERE id = $1\n ", + "query": "\n SELECT\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_transactions\n WHERE id = $1\n ", "describe": { "columns": [ { @@ -15,46 +15,41 @@ }, { "ordinal": 2, + "name": "account_id", + "type_info": "Uuid" + }, + { + "ordinal": 3, "name": "amount_cents", "type_info": "Int8" }, { - "ordinal": 3, + "ordinal": 4, "name": "direction", "type_info": "Text" }, - { - "ordinal": 4, - "name": "source_account_id", - "type_info": "Uuid" - }, { "ordinal": 5, - "name": "destination_account_id", - "type_info": "Uuid" - }, - { - "ordinal": 6, "name": "starts_at", "type_info": "Timestamptz" }, { - "ordinal": 7, + "ordinal": 6, "name": "ends_at", "type_info": "Timestamptz" }, { - "ordinal": 8, + "ordinal": 7, "name": "recurrence_every", "type_info": "Int4" }, { - "ordinal": 9, + "ordinal": 8, "name": "recurrence_unit", "type_info": "Text" }, { - "ordinal": 10, + "ordinal": 9, "name": "weekend_adjustment", "type_info": "Text" } @@ -69,8 +64,7 @@ false, false, false, - true, - true, + false, false, true, false, @@ -78,5 +72,5 @@ true ] }, - "hash": "fae9d6766e5bce18e7917df6a0d6ad13ec035b8d409b880d6cff2ef9e2615fa4" + "hash": "ed9ae08575930c5b161d3f0c0f50479e51b54e348e1651f4a4e9b8328741cec7" } diff --git a/server/.sqlx/query-a67033cd73e269ec203817b402ef40647a1965dca8419e6aa9d33a5dfa9e5426.json b/server/.sqlx/query-f4b604ad13d3424a7f3fc32bb40aa91981fe861b661169ac5310e9df0e7b99d9.json similarity index 67% rename from server/.sqlx/query-a67033cd73e269ec203817b402ef40647a1965dca8419e6aa9d33a5dfa9e5426.json rename to server/.sqlx/query-f4b604ad13d3424a7f3fc32bb40aa91981fe861b661169ac5310e9df0e7b99d9.json index b7b04a9..84e9c34 100644 --- a/server/.sqlx/query-a67033cd73e269ec203817b402ef40647a1965dca8419e6aa9d33a5dfa9e5426.json +++ b/server/.sqlx/query-f4b604ad13d3424a7f3fc32bb40aa91981fe861b661169ac5310e9df0e7b99d9.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT\n id,\n name,\n amount_cents,\n direction,\n source_account_id,\n destination_account_id,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_transactions\n ORDER BY starts_at DESC, id DESC\n LIMIT $1 OFFSET $2\n ", + "query": "\n SELECT\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_transactions\n ORDER BY starts_at DESC, id DESC\n LIMIT $1 OFFSET $2\n ", "describe": { "columns": [ { @@ -15,46 +15,41 @@ }, { "ordinal": 2, + "name": "account_id", + "type_info": "Uuid" + }, + { + "ordinal": 3, "name": "amount_cents", "type_info": "Int8" }, { - "ordinal": 3, + "ordinal": 4, "name": "direction", "type_info": "Text" }, - { - "ordinal": 4, - "name": "source_account_id", - "type_info": "Uuid" - }, { "ordinal": 5, - "name": "destination_account_id", - "type_info": "Uuid" - }, - { - "ordinal": 6, "name": "starts_at", "type_info": "Timestamptz" }, { - "ordinal": 7, + "ordinal": 6, "name": "ends_at", "type_info": "Timestamptz" }, { - "ordinal": 8, + "ordinal": 7, "name": "recurrence_every", "type_info": "Int4" }, { - "ordinal": 9, + "ordinal": 8, "name": "recurrence_unit", "type_info": "Text" }, { - "ordinal": 10, + "ordinal": 9, "name": "weekend_adjustment", "type_info": "Text" } @@ -70,8 +65,7 @@ false, false, false, - true, - true, + false, false, true, false, @@ -79,5 +73,5 @@ true ] }, - "hash": "a67033cd73e269ec203817b402ef40647a1965dca8419e6aa9d33a5dfa9e5426" + "hash": "f4b604ad13d3424a7f3fc32bb40aa91981fe861b661169ac5310e9df0e7b99d9" } diff --git a/server/migrations/20260918000001_create_account_members.sql b/server/migrations/20260918000001_create_account_members.sql new file mode 100644 index 0000000..f19294e --- /dev/null +++ b/server/migrations/20260918000001_create_account_members.sql @@ -0,0 +1,5 @@ +CREATE TABLE account_members ( + 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) +); \ No newline at end of file diff --git a/server/migrations/20260918100000_create_counter_parties.sql b/server/migrations/20260918100000_create_counter_parties.sql new file mode 100644 index 0000000..93a71f1 --- /dev/null +++ b/server/migrations/20260918100000_create_counter_parties.sql @@ -0,0 +1,4 @@ +CREATE TABLE counter_parties ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid (), + label TEXT +); \ No newline at end of file diff --git a/server/migrations/20260919000000_create_transactions.sql b/server/migrations/20260919000000_create_transactions.sql index 5127411..4f15700 100644 --- a/server/migrations/20260919000000_create_transactions.sql +++ b/server/migrations/20260919000000_create_transactions.sql @@ -1,7 +1,8 @@ CREATE TABLE transactions ( id UUID PRIMARY KEY DEFAULT gen_random_uuid (), - description TEXT NOT NULL, + account_id UUID NOT NULL CONSTRAINT fk_transactions_account REFERENCES accounts (id), amount_cents BIGINT NOT NULL CHECK (amount_cents >= 0), direction TEXT NOT NULL CHECK (direction IN ('in', 'out')), - date TIMESTAMPTZ NOT NULL DEFAULT now() + date TIMESTAMPTZ NOT NULL DEFAULT now(), + description TEXT NOT NULL ); \ No newline at end of file diff --git a/server/migrations/20260920000000_create_recurring_transactions.sql b/server/migrations/20260920000000_create_recurring_transactions.sql index a6968f6..72eb531 100644 --- a/server/migrations/20260920000000_create_recurring_transactions.sql +++ b/server/migrations/20260920000000_create_recurring_transactions.sql @@ -1,10 +1,9 @@ CREATE TABLE recurring_transactions ( id UUID PRIMARY KEY DEFAULT gen_random_uuid (), name TEXT NOT NULL, + account_id UUID NOT NULL CONSTRAINT fk_recurring_transactions_account REFERENCES accounts (id), amount_cents BIGINT NOT NULL CHECK (amount_cents >= 0), direction TEXT NOT NULL CHECK (direction IN ('in', 'out')), - source_account_id UUID CONSTRAINT fk_recurring_transactions_source_account REFERENCES accounts (id), - destination_account_id UUID CONSTRAINT fk_recurring_transactions_destination_account REFERENCES accounts (id), starts_at TIMESTAMPTZ NOT NULL, ends_at TIMESTAMPTZ, recurrence_every INTEGER NOT NULL CHECK (recurrence_every > 0), diff --git a/server/migrations/20260928000000_seed_demo_data.sql b/server/migrations/20260928000000_seed_demo_data.sql index 0ec8de2..b696616 100644 --- a/server/migrations/20260928000000_seed_demo_data.sql +++ b/server/migrations/20260928000000_seed_demo_data.sql @@ -18,34 +18,36 @@ VALUES ( INSERT INTO transactions ( id, - description, + account_id, amount_cents, direction, - date + date, + description ) VALUES ( '00000000-0000-0000-0000-000000000001', - 'Salary', + '00000000-0000-0000-0000-000000000001', 320000, 'in', - '2026-09-01T09:00:00Z' + '2026-09-01T09:00:00Z', + 'Salary' ), ( '00000000-0000-0000-0000-000000000002', - 'Groceries', + '00000000-0000-0000-0000-000000000001', 8450, 'out', - '2026-09-18T17:30:00Z' + '2026-09-18T17:30:00Z', + 'Groceries' ); INSERT INTO recurring_transactions ( id, name, + account_id, amount_cents, direction, - source_account_id, - destination_account_id, starts_at, ends_at, recurrence_every, @@ -55,10 +57,9 @@ INSERT INTO VALUES ( '00000000-0000-0000-0000-000000000101', 'Salary', + '00000000-0000-0000-0000-000000000001', 320000, 'in', - '00000000-0000-0000-0000-000000000001', - NULL, '2026-10-01T09:00:00Z', NULL, 1, @@ -68,10 +69,9 @@ VALUES ( ( '00000000-0000-0000-0000-000000000102', 'Rent', + '00000000-0000-0000-0000-000000000001', 125000, 'out', - NULL, - '00000000-0000-0000-0000-000000000001', '2026-10-01T09:00:00Z', NULL, 1, diff --git a/server/src/database.rs b/server/src/database.rs index 8c05388..8f13ec1 100644 --- a/server/src/database.rs +++ b/server/src/database.rs @@ -43,11 +43,11 @@ impl From for DatabaseError { #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Constraint { - #[error("recurring transaction source account constraint")] - RecurringTransactionSourceAccount, + #[error("transaction account constraint")] + TransactionAccount, - #[error("recurring transaction destination account constraint")] - RecurringTransactionDestinationAccount, + #[error("recurring transaction account constraint")] + RecurringTransactionAccount, #[error("unknown constraint ({0:?})")] Unknown(String), @@ -59,12 +59,8 @@ pub enum Constraint { impl From<&str> for Constraint { fn from(constraint: &str) -> Self { match constraint { - "fk_recurring_transactions_source_account" => { - Constraint::RecurringTransactionSourceAccount - } - "fk_recurring_transactions_destination_account" => { - Constraint::RecurringTransactionDestinationAccount - } + "fk_transactions_account" => Constraint::TransactionAccount, + "fk_recurring_transactions_account" => Constraint::RecurringTransactionAccount, _ => Constraint::Unknown(constraint.to_string()), } } diff --git a/server/src/database/dtos/recurring_transaction.rs b/server/src/database/dtos/recurring_transaction.rs index 9068612..16641b1 100644 --- a/server/src/database/dtos/recurring_transaction.rs +++ b/server/src/database/dtos/recurring_transaction.rs @@ -4,10 +4,9 @@ use uuid::Uuid; pub struct RecurringTransactionRow { pub id: Uuid, pub name: String, + pub account_id: Uuid, pub amount_cents: i64, pub direction: String, - pub source_account_id: Option, - pub destination_account_id: Option, pub starts_at: DateTime, pub ends_at: Option>, pub recurrence_every: i32, diff --git a/server/src/database/dtos/transaction.rs b/server/src/database/dtos/transaction.rs index a18cfdf..57c62fc 100644 --- a/server/src/database/dtos/transaction.rs +++ b/server/src/database/dtos/transaction.rs @@ -3,8 +3,9 @@ use uuid::Uuid; pub struct TransactionRow { pub id: Uuid, - pub description: String, + pub account_id: Uuid, pub amount_cents: i64, pub direction: String, pub date: DateTime, + pub description: String, } diff --git a/server/src/database/recurring_transactions.rs b/server/src/database/recurring_transactions.rs index fdf03e0..dcb14fd 100644 --- a/server/src/database/recurring_transactions.rs +++ b/server/src/database/recurring_transactions.rs @@ -32,10 +32,9 @@ where SELECT id, name, + account_id, amount_cents, direction, - source_account_id, - destination_account_id, starts_at, ends_at, recurrence_every, @@ -66,10 +65,9 @@ where SELECT id, name, + account_id, amount_cents, direction, - source_account_id, - destination_account_id, starts_at, ends_at, recurrence_every, @@ -97,23 +95,21 @@ where INSERT INTO recurring_transactions ( id, name, + account_id, amount_cents, direction, - source_account_id, - destination_account_id, starts_at, ends_at, recurrence_every, recurrence_unit, weekend_adjustment ) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, + account_id = EXCLUDED.account_id, amount_cents = EXCLUDED.amount_cents, direction = EXCLUDED.direction, - source_account_id = EXCLUDED.source_account_id, - destination_account_id = EXCLUDED.destination_account_id, starts_at = EXCLUDED.starts_at, ends_at = EXCLUDED.ends_at, recurrence_every = EXCLUDED.recurrence_every, @@ -123,10 +119,9 @@ where old_row.id AS "old_id?", new_row.id AS "id!", new_row.name AS "name!", + new_row.account_id AS "account_id!", new_row.amount_cents AS "amount_cents!", new_row.direction AS "direction!", - new_row.source_account_id AS "source_account_id?", - new_row.destination_account_id AS "destination_account_id?", new_row.starts_at AS "starts_at!", new_row.ends_at AS "ends_at?", new_row.recurrence_every AS "recurrence_every!", @@ -135,10 +130,9 @@ where "#, transaction.id, transaction.name, + transaction.account_id, transaction.amount_cents, transaction.direction, - transaction.source_account_id, - transaction.destination_account_id, transaction.starts_at, transaction.ends_at, transaction.recurrence_every, @@ -152,10 +146,9 @@ where let transaction = RecurringTransactionRow { id: row.id, name: row.name, + account_id: row.account_id, amount_cents: row.amount_cents, direction: row.direction, - source_account_id: row.source_account_id, - destination_account_id: row.destination_account_id, starts_at: row.starts_at, ends_at: row.ends_at, recurrence_every: row.recurrence_every, diff --git a/server/src/database/transactions.rs b/server/src/database/transactions.rs index 9876882..782fe9d 100644 --- a/server/src/database/transactions.rs +++ b/server/src/database/transactions.rs @@ -26,7 +26,7 @@ where sqlx::query_as!( TransactionRow, r#" - SELECT id, description, amount_cents, direction, date + SELECT id, account_id, amount_cents, direction, date, description FROM transactions ORDER BY date DESC, id DESC LIMIT $1 @@ -50,7 +50,7 @@ where sqlx::query_as!( TransactionRow, r#" - SELECT id, description, amount_cents, direction, date + SELECT id, account_id, amount_cents, direction, date, description FROM transactions WHERE id = $1 "#, @@ -70,26 +70,29 @@ where { let row = sqlx::query!( r#" - INSERT INTO transactions (id, description, amount_cents, direction, date) - VALUES ($1, $2, $3, $4, $5) + INSERT INTO transactions (id, account_id, amount_cents, direction, date, description) + VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id) DO UPDATE SET - description = EXCLUDED.description, + account_id = EXCLUDED.account_id, amount_cents = EXCLUDED.amount_cents, direction = EXCLUDED.direction, - date = EXCLUDED.date + date = EXCLUDED.date, + description = EXCLUDED.description RETURNING WITH (OLD AS old_row, NEW AS new_row) old_row.id AS "old_id?", new_row.id AS "id!", - new_row.description AS "description!", + new_row.account_id AS "account_id!", new_row.amount_cents AS "amount_cents!", new_row.direction AS "direction!", - new_row.date AS "date!" + new_row.date AS "date!", + new_row.description AS "description!" "#, transaction.id, - transaction.description, + transaction.account_id, transaction.amount_cents, transaction.direction, transaction.date, + transaction.description, ) .fetch_one(executor) .await @@ -97,10 +100,11 @@ where let transaction = TransactionRow { id: row.id, - description: row.description, + account_id: row.account_id, amount_cents: row.amount_cents, direction: row.direction, date: row.date, + description: row.description, }; if row.old_id.is_some() { diff --git a/server/src/domain/recurring_transaction.rs b/server/src/domain/recurring_transaction.rs index 6c735e5..64b09a2 100644 --- a/server/src/domain/recurring_transaction.rs +++ b/server/src/domain/recurring_transaction.rs @@ -6,9 +6,8 @@ use super::{Cents, Direction, Schedule}; pub struct RecurringTransaction { pub id: Uuid, pub name: String, + pub account_id: Uuid, pub amount: Cents, pub direction: Direction, - pub source_account_id: Option, - pub destination_account_id: Option, pub schedule: Schedule, } diff --git a/server/src/domain/transaction.rs b/server/src/domain/transaction.rs index 4cd7a32..c8856a4 100644 --- a/server/src/domain/transaction.rs +++ b/server/src/domain/transaction.rs @@ -6,8 +6,9 @@ use super::{Cents, Direction}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Transaction { pub id: Uuid, - pub description: String, + pub account_id: Uuid, pub amount: Cents, pub direction: Direction, pub date: DateTime, + pub description: String, } diff --git a/server/src/error.rs b/server/src/error.rs index 85a0847..90a676f 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -21,6 +21,9 @@ pub enum AppError { #[error("repository error")] Repository(#[from] RepositoryError), + + #[error("internal server error")] + Internal, } impl IntoResponse for AppError { @@ -42,23 +45,20 @@ impl IntoResponse for AppError { tracing::error!(%error, "invalid stored data"); } Self::Repository(RepositoryError::ReferenceViolation { - relation: ReferenceRelation::SourceAccount, + relation: ReferenceRelation::Account, kind: ReferenceViolationKind::Missing, .. }) => { - return error_response( - StatusCode::UNPROCESSABLE_ENTITY, - "Source account cannot be found", - ); + return error_response(StatusCode::UNPROCESSABLE_ENTITY, "Account cannot be found"); } Self::Repository(RepositoryError::ReferenceViolation { - relation: ReferenceRelation::DestinationAccount, - kind: ReferenceViolationKind::Missing, + relation: ReferenceRelation::Transaction, + kind: ReferenceViolationKind::StillReferenced, .. }) => { return error_response( - StatusCode::UNPROCESSABLE_ENTITY, - "Destination account cannot be found", + StatusCode::CONFLICT, + "Still referenced by one or more transactions", ); } Self::Repository(RepositoryError::ReferenceViolation { @@ -81,6 +81,9 @@ impl IntoResponse for AppError { Self::Repository(RepositoryError::QueryConversion(error)) => { return error_response(StatusCode::BAD_REQUEST, error.to_string()); } + Self::Internal => { + tracing::error!("internal server error"); + } } error_response(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error") diff --git a/server/src/repository.rs b/server/src/repository.rs index fcdc672..b01d4e2 100644 --- a/server/src/repository.rs +++ b/server/src/repository.rs @@ -56,11 +56,11 @@ pub enum DecodeError { #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] pub enum ReferenceRelation { - #[error("source account")] - SourceAccount, + #[error("account")] + Account, - #[error("destination account")] - DestinationAccount, + #[error("transaction")] + Transaction, #[error("recurring transaction")] RecurringTransaction, diff --git a/server/src/repository/accounts.rs b/server/src/repository/accounts.rs index cfec3f1..250a2d6 100644 --- a/server/src/repository/accounts.rs +++ b/server/src/repository/accounts.rs @@ -119,9 +119,15 @@ where fn classify_delete_error(error: DatabaseError) -> RepositoryError { match &error { DatabaseError::ForeignKeyViolation { - constraint: - Constraint::RecurringTransactionSourceAccount - | Constraint::RecurringTransactionDestinationAccount, + constraint: Constraint::TransactionAccount, + .. + } => RepositoryError::ReferenceViolation { + relation: ReferenceRelation::Transaction, + kind: ReferenceViolationKind::StillReferenced, + source: error, + }, + DatabaseError::ForeignKeyViolation { + constraint: Constraint::RecurringTransactionAccount, .. } => RepositoryError::ReferenceViolation { relation: ReferenceRelation::RecurringTransaction, @@ -162,7 +168,7 @@ mod tests { #[test] fn classifies_account_delete_foreign_key_constraint() { let error = classify_delete_error(foreign_key_violation( - Constraint::RecurringTransactionSourceAccount, + Constraint::RecurringTransactionAccount, )); assert!(matches!( &error, @@ -172,16 +178,24 @@ mod tests { .. } )); + } - let database_error = std::error::Error::source(&error).unwrap(); - let sqlx_error = std::error::Error::source(database_error).unwrap(); - assert!(sqlx_error.to_string().contains("test database cause")); + #[test] + fn classifies_transaction_account_delete_foreign_key_constraint() { + let error = classify_delete_error(foreign_key_violation(Constraint::TransactionAccount)); + assert!(matches!( + error, + RepositoryError::ReferenceViolation { + relation: ReferenceRelation::Transaction, + kind: ReferenceViolationKind::StillReferenced, + .. + } + )); } #[test] fn keeps_unknown_account_delete_foreign_keys_generic() { let error = classify_delete_error(foreign_key_violation(Constraint::Unnamed)); - assert!(matches!(error, RepositoryError::Database(_))); } @@ -197,7 +211,6 @@ mod tests { let row = row(); let id = row.id; let account = decode(row).unwrap(); - assert_eq!(account.id, id); assert_eq!(account.name, "Savings"); } diff --git a/server/src/repository/recurring_transactions.rs b/server/src/repository/recurring_transactions.rs index 6b907a3..8a6c2a7 100644 --- a/server/src/repository/recurring_transactions.rs +++ b/server/src/repository/recurring_transactions.rs @@ -93,13 +93,9 @@ where fn classify_upsert_error(error: DatabaseError) -> RepositoryError { let relation = match &error { DatabaseError::ForeignKeyViolation { - constraint: Constraint::RecurringTransactionSourceAccount, + constraint: Constraint::RecurringTransactionAccount, .. - } => Some(ReferenceRelation::SourceAccount), - DatabaseError::ForeignKeyViolation { - constraint: Constraint::RecurringTransactionDestinationAccount, - .. - } => Some(ReferenceRelation::DestinationAccount), + } => Some(ReferenceRelation::Account), _ => None, }; @@ -133,10 +129,9 @@ fn decode(row: RecurringTransactionRow) -> Result RecurringTransactionRow { RecurringTransactionRow { id: transaction.id, name: transaction.name, + account_id: transaction.account_id, amount_cents: transaction.amount.into(), direction: encode_direction(transaction.direction).to_owned(), - source_account_id: transaction.source_account_id, - destination_account_id: transaction.destination_account_id, starts_at: transaction.schedule.start(), ends_at: transaction.schedule.end(), recurrence_every: recurrence.every.into(), @@ -179,29 +173,13 @@ mod tests { #[test] fn classifies_upsert_foreign_key_constraints() { - let source = classify_upsert_error(foreign_key_violation( - Constraint::RecurringTransactionSourceAccount, + let account = classify_upsert_error(foreign_key_violation( + Constraint::RecurringTransactionAccount, )); assert!(matches!( - &source, + &account, RepositoryError::ReferenceViolation { - relation: ReferenceRelation::SourceAccount, - kind: ReferenceViolationKind::Missing, - .. - } - )); - - let database_error = std::error::Error::source(&source).unwrap(); - let sqlx_error = std::error::Error::source(database_error).unwrap(); - assert!(sqlx_error.to_string().contains("test database cause")); - - let destination = classify_upsert_error(foreign_key_violation( - Constraint::RecurringTransactionDestinationAccount, - )); - assert!(matches!( - &destination, - RepositoryError::ReferenceViolation { - relation: ReferenceRelation::DestinationAccount, + relation: ReferenceRelation::Account, kind: ReferenceViolationKind::Missing, .. } @@ -211,7 +189,6 @@ mod tests { #[test] fn keeps_unknown_upsert_foreign_keys_generic() { let error = classify_upsert_error(foreign_key_violation(Constraint::Unnamed)); - assert!(matches!(error, RepositoryError::Database(_))); } @@ -219,10 +196,9 @@ mod tests { RecurringTransactionRow { id: Uuid::new_v4(), name: "Rent".to_owned(), + account_id: Uuid::new_v4(), amount_cents: 120_000, direction: "out".to_owned(), - source_account_id: Some(Uuid::new_v4()), - destination_account_id: Some(Uuid::new_v4()), starts_at: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(), ends_at: None, recurrence_every: 1, @@ -234,29 +210,23 @@ mod tests { #[test] fn decodes_valid_rows() { let row = row(); - let (id, start, source_account_id, destination_account_id) = ( - row.id, - row.starts_at, - row.source_account_id, - row.destination_account_id, - ); + let (id, start, account_id) = (row.id, row.starts_at, row.account_id); let transaction = decode(row).unwrap(); - let recurrence = transaction.schedule.recurrence(); - assert_eq!(transaction.id, id); assert_eq!(transaction.name, "Rent"); assert_eq!(transaction.amount.get(), 120_000); assert_eq!(transaction.direction, Direction::Out); - assert_eq!(transaction.source_account_id, source_account_id); - assert_eq!(transaction.destination_account_id, destination_account_id); + assert_eq!(transaction.account_id, account_id); assert_eq!(transaction.schedule.start(), start); assert_eq!(transaction.schedule.end(), None); - assert_eq!(recurrence.every.get(), 1); - assert_eq!(recurrence.unit, RecurrenceUnit::Month); assert_eq!( transaction.schedule.weekend_adjustment(), Some(WeekendAdjustment::NextBusinessDay) ); + + let recurrence = transaction.schedule.recurrence(); + assert_eq!(recurrence.every.get(), 1); + assert_eq!(recurrence.unit, RecurrenceUnit::Month); } #[test] diff --git a/server/src/repository/transactions.rs b/server/src/repository/transactions.rs index 8c0e4a2..ac2e6c5 100644 --- a/server/src/repository/transactions.rs +++ b/server/src/repository/transactions.rs @@ -1,12 +1,12 @@ use uuid::Uuid; use super::{ - DecodeError, QueryConversionError, RepositoryError, + DecodeError, QueryConversionError, ReferenceRelation, ReferenceViolationKind, RepositoryError, dtos::{Delete, Upsert}, encoding::{decode_direction, encode_direction}, }; use crate::{ - database::{dtos::TransactionRow, transactions as db}, + database::{Constraint, DatabaseError, dtos::TransactionRow, transactions as db}, domain::{Cents, Transaction}, }; @@ -72,12 +72,27 @@ where E: sqlx::Executor<'e, Database = sqlx::Postgres>, { let transaction = db::upsert(executor, encode(transaction)) - .await? + .await + .map_err(classify_upsert_error)? .try_map(decode)?; Ok(transaction.into()) } +fn classify_upsert_error(error: DatabaseError) -> RepositoryError { + match &error { + DatabaseError::ForeignKeyViolation { + constraint: Constraint::TransactionAccount, + .. + } => RepositoryError::ReferenceViolation { + relation: ReferenceRelation::Account, + kind: ReferenceViolationKind::Missing, + source: error, + }, + _ => RepositoryError::Database(error), + } +} + pub async fn delete<'e, E>(executor: E, id: Uuid) -> Result where E: sqlx::Executor<'e, Database = sqlx::Postgres>, @@ -88,20 +103,22 @@ where fn decode(row: TransactionRow) -> Result { Ok(Transaction { id: row.id, - description: row.description, + account_id: row.account_id, amount: Cents::try_from(row.amount_cents)?, direction: decode_direction(row.direction)?, date: row.date, + description: row.description, }) } fn encode(transaction: Transaction) -> TransactionRow { TransactionRow { id: transaction.id, - description: transaction.description, + account_id: transaction.account_id, amount_cents: transaction.amount.into(), direction: encode_direction(transaction.direction).to_owned(), date: transaction.date, + description: transaction.description, } } @@ -113,27 +130,55 @@ mod tests { use super::*; use crate::domain::Direction; + fn foreign_key_violation(constraint: Constraint) -> DatabaseError { + DatabaseError::ForeignKeyViolation { + constraint, + source: sqlx::Error::Protocol("test database cause".to_owned()), + } + } + + #[test] + fn classifies_account_upsert_foreign_key_violation() { + let error = classify_upsert_error(foreign_key_violation(Constraint::TransactionAccount)); + assert!(matches!( + error, + RepositoryError::ReferenceViolation { + relation: ReferenceRelation::Account, + 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() -> TransactionRow { TransactionRow { id: Uuid::new_v4(), - description: "Groceries".to_owned(), + account_id: Uuid::new_v4(), amount_cents: 4250, direction: "out".to_owned(), date: Utc::now(), + description: "Groceries".to_owned(), } } #[test] fn decodes_valid_rows() { let row = row(); - let (id, date) = (row.id, row.date); + let (id, account_id, date) = (row.id, row.account_id, row.date); let transaction = decode(row).unwrap(); assert_eq!(transaction.id, id); - assert_eq!(transaction.description, "Groceries"); + assert_eq!(transaction.account_id, account_id); assert_eq!(transaction.amount.get(), 4250); assert_eq!(transaction.direction, Direction::Out); assert_eq!(transaction.date, date); + assert_eq!(transaction.description, "Groceries"); } #[test] diff --git a/server/src/routes/dtos/scheduled_transaction.rs b/server/src/routes/dtos/scheduled_transaction.rs index e856a53..e2536ef 100644 --- a/server/src/routes/dtos/scheduled_transaction.rs +++ b/server/src/routes/dtos/scheduled_transaction.rs @@ -28,10 +28,9 @@ impl From for ScheduledTransactionResponse { #[derive(Debug, Clone, Deserialize)] pub struct RecurringTransactionRequest { pub name: String, + pub account: AccountRequest, pub amount_cents: u64, pub direction: Direction, - pub source_account: Option, - pub destination_account: Option, pub schedule: ScheduleRequest, } @@ -48,10 +47,9 @@ impl RecurringTransactionRequest { Ok(domain::RecurringTransaction { id, name: self.name, + account_id: self.account.id, amount: self.amount_cents.try_into()?, direction: self.direction.into(), - source_account_id: self.source_account.as_ref().map(|account| account.id), - destination_account_id: self.destination_account.as_ref().map(|account| account.id), schedule: domain::Schedule::new( self.schedule.start, self.schedule.end, @@ -66,33 +64,27 @@ impl RecurringTransactionRequest { pub struct RecurringTransactionResponse { pub id: Uuid, pub name: String, + pub account: AccountResponse, pub amount_cents: u64, pub direction: Direction, - pub source_account: Option, - pub destination_account: Option, pub schedule: ScheduleResponse, } impl RecurringTransactionResponse { pub fn new( transaction: domain::RecurringTransaction, - source_account: Option, - destination_account: Option, + account: domain::Account, schedule_next: Option>, ) -> Self { Self { id: transaction.id, name: transaction.name, + account: AccountResponse { + id: account.id, + name: account.name, + }, amount_cents: transaction.amount.get(), direction: transaction.direction.into(), - source_account: source_account.map(|account| AccountResponse { - id: account.id, - name: account.name, - }), - destination_account: destination_account.map(|account| AccountResponse { - id: account.id, - name: account.name, - }), schedule: ScheduleResponse::new(transaction.schedule, schedule_next), } } @@ -225,8 +217,10 @@ mod tests { let transaction = request().into_domain(Uuid::nil()).unwrap(); ScheduledTransactionResponse::from(RecurringTransactionResponse::new( transaction, - None, - None, + domain::Account { + id: Uuid::nil(), + name: "Checking".to_owned(), + }, None, )) } @@ -234,10 +228,9 @@ mod tests { fn request() -> RecurringTransactionRequest { RecurringTransactionRequest { name: "Rent".to_owned(), + account: super::AccountRequest { id: Uuid::nil() }, amount_cents: 1234, direction: Direction::Out, - source_account: None, - destination_account: None, schedule: ScheduleRequest { start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(), end: None, @@ -258,8 +251,10 @@ mod tests { assert_eq!(response["name"], "Rent"); assert_eq!(response["amount_cents"], 1234); assert_eq!(response["direction"], "out"); - assert!(response["source_account"].is_null()); - assert!(response["destination_account"].is_null()); + assert_eq!(response["account"]["id"], Uuid::nil().to_string()); + assert_eq!(response["account"]["name"], "Checking"); + assert!(response.get("source_account").is_none()); + assert!(response.get("destination_account").is_none()); assert!(response["schedule"]["start"].is_string()); assert!(response["schedule"]["end"].is_null()); assert_eq!(response["schedule"]["recurrence"]["every"], 2); @@ -274,39 +269,21 @@ mod tests { } #[test] - fn serializes_recurring_transaction_response_with_source_and_destination_accounts() { - let source_id = Uuid::new_v4(); - let destination_id = Uuid::new_v4(); - + fn serializes_recurring_transaction_response_with_account() { + let account_id = Uuid::new_v4(); let mut transaction = request(); - transaction.source_account = Some(super::AccountRequest { id: source_id }); - transaction.destination_account = Some(super::AccountRequest { id: destination_id }); - + transaction.account = super::AccountRequest { id: account_id }; let transaction = transaction.into_domain(Uuid::nil()).unwrap(); - let source_account = Some(domain::Account { - id: source_id, + let account = domain::Account { + id: account_id, name: "Checking".to_owned(), - }); - let destination_account = Some(domain::Account { - id: destination_id, - name: "Savings".to_owned(), - }); + }; - let response = RecurringTransactionResponse::new( - transaction, - source_account, - destination_account, - None, - ); + let response = RecurringTransactionResponse::new(transaction, account, None); let response = serde_json::to_value(response).unwrap(); - assert_eq!(response["source_account"]["id"], source_id.to_string()); - assert_eq!(response["source_account"]["name"], "Checking"); - assert_eq!( - response["destination_account"]["id"], - destination_id.to_string() - ); - assert_eq!(response["destination_account"]["name"], "Savings"); + assert_eq!(response["account"]["id"], account_id.to_string()); + assert_eq!(response["account"]["name"], "Checking"); } #[test] @@ -315,6 +292,7 @@ mod tests { let request: ScheduledTransactionRequest = serde_json::from_value(response).unwrap(); let ScheduledTransactionRequest::Recurring(request) = request; assert_eq!(request.name, "Rent"); + assert_eq!(request.account.id, Uuid::nil()); assert_eq!(request.amount_cents, 1234); assert!(matches!(request.direction, Direction::Out)); assert_eq!( @@ -342,6 +320,7 @@ mod tests { assert_eq!(transaction.id, id); assert_eq!(transaction.amount.get(), 1234); assert_eq!(transaction.direction, domain::Direction::Out); + assert_eq!(transaction.account_id, Uuid::nil()); assert_eq!(recurrence.every.get(), 2); assert_eq!(recurrence.unit, domain::RecurrenceUnit::Month); assert_eq!( @@ -349,4 +328,15 @@ mod tests { Some(domain::WeekendAdjustment::NextBusinessDay) ); } + + #[test] + fn requires_account_in_recurring_transaction_request() { + let mut missing_account = serde_json::to_value(scheduled_response()).unwrap(); + missing_account.as_object_mut().unwrap().remove("account"); + assert!(serde_json::from_value::(missing_account).is_err()); + + let mut null_account = serde_json::to_value(scheduled_response()).unwrap(); + null_account["account"] = serde_json::Value::Null; + assert!(serde_json::from_value::(null_account).is_err()); + } } diff --git a/server/src/routes/dtos/transaction.rs b/server/src/routes/dtos/transaction.rs index 88367d0..ea22c22 100644 --- a/server/src/routes/dtos/transaction.rs +++ b/server/src/routes/dtos/transaction.rs @@ -7,20 +7,22 @@ use crate::domain; #[derive(Debug, Clone, Deserialize)] pub struct TransactionRequest { - pub description: String, + pub account: AccountRequest, pub amount_cents: u64, pub direction: Direction, pub date: DateTime, + pub description: String, } impl TransactionRequest { pub fn into_domain(self, id: Uuid) -> Result { Ok(domain::Transaction { id, - description: self.description, + account_id: self.account.id, amount: self.amount_cents.try_into()?, direction: self.direction.into(), date: self.date, + description: self.description, }) } } @@ -28,24 +30,40 @@ impl TransactionRequest { #[derive(Debug, Clone, Serialize)] pub struct TransactionResponse { pub id: Uuid, - pub description: String, + pub account: AccountResponse, pub amount_cents: u64, pub direction: Direction, pub date: DateTime, + pub description: String, } -impl From for TransactionResponse { - fn from(transaction: domain::Transaction) -> Self { +impl TransactionResponse { + pub fn new(transaction: domain::Transaction, account: domain::Account) -> Self { Self { id: transaction.id, - description: transaction.description, + account: AccountResponse { + id: account.id, + name: account.name, + }, amount_cents: transaction.amount.get(), direction: transaction.direction.into(), date: transaction.date, + description: transaction.description, } } } +#[derive(Debug, Clone, Deserialize)] +pub struct AccountRequest { + pub id: Uuid, +} + +#[derive(Debug, Clone, Serialize)] +pub struct AccountResponse { + pub id: Uuid, + pub name: String, +} + #[cfg(test)] mod tests { use chrono::TimeZone; @@ -54,10 +72,11 @@ mod tests { fn request() -> TransactionRequest { TransactionRequest { - description: "Groceries".to_string(), + account: AccountRequest { id: Uuid::nil() }, amount_cents: 4250, direction: Direction::Out, date: Utc.with_ymd_and_hms(2026, 9, 29, 12, 0, 0).unwrap(), + description: "Groceries".to_string(), } } @@ -66,26 +85,53 @@ mod tests { let id = Uuid::nil(); let date = request().date; let transaction = request().into_domain(id).unwrap(); - let response = serde_json::to_value(TransactionResponse::from(transaction)).unwrap(); + let account = domain::Account { + id: Uuid::nil(), + name: "Checking".to_owned(), + }; + let response = + serde_json::to_value(TransactionResponse::new(transaction, account)).unwrap(); assert_eq!(response["id"], id.to_string()); - assert_eq!(response["description"], "Groceries"); + assert_eq!(response["account"]["id"], Uuid::nil().to_string()); + assert_eq!(response["account"]["name"], "Checking"); assert_eq!(response["amount_cents"], 4250); assert_eq!(response["direction"], "out"); assert_eq!(response["date"], serde_json::to_value(date).unwrap()); + assert_eq!(response["description"], "Groceries"); } #[test] fn deserializes_transaction_response_as_request() { let date = request().date; let transaction = request().into_domain(Uuid::nil()).unwrap(); - let response = serde_json::to_value(TransactionResponse::from(transaction)).unwrap(); + let account = domain::Account { + id: Uuid::nil(), + name: "Checking".to_owned(), + }; + let response = + serde_json::to_value(TransactionResponse::new(transaction, account)).unwrap(); let request: TransactionRequest = serde_json::from_value(response).unwrap(); - assert_eq!(request.description, "Groceries"); assert_eq!(request.amount_cents, 4250); + assert_eq!(request.account.id, Uuid::nil()); assert!(matches!(request.direction, Direction::Out)); assert_eq!(request.date, date); + assert_eq!(request.description, "Groceries"); + } + + #[test] + fn requires_account_in_transaction_request() { + let transaction = request().into_domain(Uuid::nil()).unwrap(); + let account = domain::Account { + id: Uuid::nil(), + name: "Checking".to_owned(), + }; + let mut response = + serde_json::to_value(TransactionResponse::new(transaction, account)).unwrap(); + response.as_object_mut().unwrap().remove("account"); + + assert!(serde_json::from_value::(response).is_err()); } #[test] @@ -93,18 +139,28 @@ mod tests { let id = Uuid::new_v4(); let request = request(); let date = request.date; + let account_id = request.account.id; let transaction = request.into_domain(id).unwrap(); assert_eq!(transaction.id, id); + assert_eq!(transaction.account_id, account_id); assert_eq!(transaction.amount.get(), 4250); assert_eq!(transaction.direction, domain::Direction::Out); assert_eq!(transaction.date, date); - let response = TransactionResponse::from(transaction); + let response = TransactionResponse::new( + transaction, + domain::Account { + id: account_id, + name: "Checking".to_owned(), + }, + ); assert_eq!(response.id, id); - assert_eq!(response.description, "Groceries"); + assert_eq!(response.account.id, account_id); + assert_eq!(response.account.name, "Checking"); assert_eq!(response.amount_cents, 4250); assert!(matches!(response.direction, Direction::Out)); assert_eq!(response.date, date); + assert_eq!(response.description, "Groceries"); } } diff --git a/server/src/routes/scheduled_transactions.rs b/server/src/routes/scheduled_transactions.rs index 4734dbf..1b4d019 100644 --- a/server/src/routes/scheduled_transactions.rs +++ b/server/src/routes/scheduled_transactions.rs @@ -68,7 +68,7 @@ async fn list_scheduled_transactions( let responses = transactions .into_iter() .map(|transaction| create_response(transaction, &accounts, now)) - .collect(); + .collect::, _>>()?; Ok(Json(responses)) } @@ -87,7 +87,7 @@ async fn get_scheduled_transaction( get_accounts_for_transactions(&mut tx, std::slice::from_ref(&transaction)).await?; tx.commit().await.map_err(RepositoryError::from)?; - Ok(Json(create_response(transaction, &accounts, Utc::now()))) + Ok(Json(create_response(transaction, &accounts, Utc::now())?)) } #[axum::debug_handler] @@ -111,7 +111,7 @@ async fn upsert_scheduled_transaction( Ok(( status, - Json(create_response(transaction, &accounts, Utc::now())), + Json(create_response(transaction, &accounts, Utc::now())?), )) } @@ -133,13 +133,7 @@ async fn get_accounts_for_transactions( ) -> Result, AppError> { let account_ids = transactions .iter() - .flat_map(|transaction| { - [ - transaction.source_account_id, - transaction.destination_account_id, - ] - }) - .flatten() + .map(|transaction| transaction.account_id) .collect::>() .into_iter() .collect::>(); @@ -151,15 +145,13 @@ fn create_response( transaction: domain::RecurringTransaction, accounts: &HashMap, now: DateTime, -) -> ScheduledTransactionResponse { - let source_account = transaction - .source_account_id - .and_then(|id| accounts.get(&id).cloned()); - let destination_account = transaction - .destination_account_id - .and_then(|id| accounts.get(&id).cloned()); +) -> Result { + let account = accounts + .get(&transaction.account_id) + .cloned() + .ok_or(AppError::Internal)?; let next = transaction.schedule.next_occurrence(now); - RecurringTransactionResponse::new(transaction, source_account, destination_account, next).into() + Ok(RecurringTransactionResponse::new(transaction, account, next).into()) } diff --git a/server/src/routes/transactions.rs b/server/src/routes/transactions.rs index a89917e..0363156 100644 --- a/server/src/routes/transactions.rs +++ b/server/src/routes/transactions.rs @@ -1,3 +1,5 @@ +use std::collections::{HashMap, HashSet}; + use axum::{extract::State, http::StatusCode}; use serde::Deserialize; use sqlx::PgPool; @@ -8,8 +10,10 @@ use super::{ extractors::{json::Json, path::Path, query::Query}, }; use crate::{ + domain, error::AppError, repository::{ + RepositoryError, accounts as account_repository, dtos::{Delete, Upsert}, transactions as repository, }, @@ -50,13 +54,17 @@ async fn list_transactions( State(pool): State, Query(query): Query, ) -> Result>, AppError> { - let transactions = repository::list(&pool, query.try_into()?) - .await? - .into_iter() - .map(TransactionResponse::from) - .collect(); + let mut tx = pool.begin().await.map_err(RepositoryError::from)?; + let transactions = repository::list(&mut *tx, query.try_into()?).await?; + let accounts = get_accounts_for_transactions(&mut tx, &transactions).await?; + tx.commit().await.map_err(RepositoryError::from)?; - Ok(Json(transactions)) + let responses = transactions + .into_iter() + .map(|transaction| create_response(transaction, &accounts)) + .collect::, _>>()?; + + Ok(Json(responses)) } #[axum::debug_handler] @@ -65,11 +73,15 @@ async fn get_transaction( State(pool): State, Path(id): Path, ) -> Result, AppError> { - let transaction = repository::get(&pool, id) + let mut tx = pool.begin().await.map_err(RepositoryError::from)?; + let transaction = repository::get(&mut *tx, id) .await? .ok_or(AppError::NotFound)?; + let accounts = + get_accounts_for_transactions(&mut tx, std::slice::from_ref(&transaction)).await?; + tx.commit().await.map_err(RepositoryError::from)?; - Ok(Json(transaction.into())) + Ok(Json(create_response(transaction, &accounts)?)) } #[axum::debug_handler] @@ -81,12 +93,16 @@ async fn upsert_transaction( ) -> Result<(StatusCode, Json), AppError> { let transaction = transaction.into_domain(id)?; - let (status, transaction) = match repository::upsert(&pool, transaction).await? { + let mut tx = pool.begin().await.map_err(RepositoryError::from)?; + let (status, transaction) = match repository::upsert(&mut *tx, transaction).await? { Upsert::Created(transaction) => (StatusCode::CREATED, transaction), Upsert::Updated(transaction) => (StatusCode::OK, transaction), }; + let accounts = + get_accounts_for_transactions(&mut tx, std::slice::from_ref(&transaction)).await?; + tx.commit().await.map_err(RepositoryError::from)?; - Ok((status, Json(transaction.into()))) + Ok((status, Json(create_response(transaction, &accounts)?))) } #[axum::debug_handler] @@ -100,3 +116,29 @@ async fn delete_transaction( Delete::NotFound => Err(AppError::NotFound), } } + +async fn get_accounts_for_transactions( + connection: &mut sqlx::PgConnection, + transactions: &[domain::Transaction], +) -> Result, AppError> { + let account_ids = transactions + .iter() + .map(|transaction| transaction.account_id) + .collect::>() + .into_iter() + .collect::>(); + + Ok(account_repository::get_by_ids(connection, &account_ids).await?) +} + +fn create_response( + transaction: domain::Transaction, + accounts: &HashMap, +) -> Result { + let account = accounts + .get(&transaction.account_id) + .cloned() + .ok_or(AppError::Internal)?; + + Ok(TransactionResponse::new(transaction, account)) +}