Refactored src and dst account to just account in preparation for a "counter party", instead of a full account.
This commit is contained in:
-56
@@ -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"
|
||||
}
|
||||
+10
-4
@@ -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"
|
||||
}
|
||||
+91
@@ -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"
|
||||
}
|
||||
+63
@@ -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"
|
||||
}
|
||||
+10
-4
@@ -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"
|
||||
}
|
||||
-98
@@ -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"
|
||||
}
|
||||
+13
-19
@@ -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"
|
||||
}
|
||||
+13
-19
@@ -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"
|
||||
}
|
||||
@@ -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)
|
||||
);
|
||||
@@ -0,0 +1,4 @@
|
||||
CREATE TABLE counter_parties (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
|
||||
label TEXT
|
||||
);
|
||||
@@ -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
|
||||
);
|
||||
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
|
||||
+6
-10
@@ -43,11 +43,11 @@ impl From<sqlx::Error> 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()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Uuid>,
|
||||
pub destination_account_id: Option<Uuid>,
|
||||
pub starts_at: DateTime<Utc>,
|
||||
pub ends_at: Option<DateTime<Utc>>,
|
||||
pub recurrence_every: i32,
|
||||
|
||||
@@ -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<Utc>,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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<Uuid>,
|
||||
pub destination_account_id: Option<Uuid>,
|
||||
pub schedule: Schedule,
|
||||
}
|
||||
|
||||
@@ -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<Utc>,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
+12
-9
@@ -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")
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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<RecurringTransaction, DecodeEr
|
||||
Ok(RecurringTransaction {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
account_id: row.account_id,
|
||||
amount: Cents::try_from(row.amount_cents)?,
|
||||
direction: decode_direction(row.direction)?,
|
||||
source_account_id: row.source_account_id,
|
||||
destination_account_id: row.destination_account_id,
|
||||
schedule: Schedule::new(row.starts_at, row.ends_at, recurrence, weekend_adjustment)?,
|
||||
})
|
||||
}
|
||||
@@ -147,10 +142,9 @@ fn encode(transaction: RecurringTransaction) -> 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]
|
||||
|
||||
@@ -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<Delete, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
@@ -88,20 +103,22 @@ where
|
||||
fn decode(row: TransactionRow) -> Result<Transaction, DecodeError> {
|
||||
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]
|
||||
|
||||
@@ -28,10 +28,9 @@ impl From<RecurringTransactionResponse> 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<AccountRequest>,
|
||||
pub destination_account: Option<AccountRequest>,
|
||||
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<AccountResponse>,
|
||||
pub destination_account: Option<AccountResponse>,
|
||||
pub schedule: ScheduleResponse,
|
||||
}
|
||||
|
||||
impl RecurringTransactionResponse {
|
||||
pub fn new(
|
||||
transaction: domain::RecurringTransaction,
|
||||
source_account: Option<domain::Account>,
|
||||
destination_account: Option<domain::Account>,
|
||||
account: domain::Account,
|
||||
schedule_next: Option<DateTime<Utc>>,
|
||||
) -> 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::<ScheduledTransactionRequest>(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::<ScheduledTransactionRequest>(null_account).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Utc>,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
impl TransactionRequest {
|
||||
pub fn into_domain(self, id: Uuid) -> Result<domain::Transaction, domain::DomainError> {
|
||||
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<Utc>,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
impl From<domain::Transaction> 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::<TransactionRequest>(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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ async fn list_scheduled_transactions(
|
||||
let responses = transactions
|
||||
.into_iter()
|
||||
.map(|transaction| create_response(transaction, &accounts, now))
|
||||
.collect();
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
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<HashMap<Uuid, domain::Account>, AppError> {
|
||||
let account_ids = transactions
|
||||
.iter()
|
||||
.flat_map(|transaction| {
|
||||
[
|
||||
transaction.source_account_id,
|
||||
transaction.destination_account_id,
|
||||
]
|
||||
})
|
||||
.flatten()
|
||||
.map(|transaction| transaction.account_id)
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
@@ -151,15 +145,13 @@ fn create_response(
|
||||
transaction: domain::RecurringTransaction,
|
||||
accounts: &HashMap<Uuid, domain::Account>,
|
||||
now: DateTime<Utc>,
|
||||
) -> 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<ScheduledTransactionResponse, AppError> {
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -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<PgPool>,
|
||||
Query(query): Query<QueryParams>,
|
||||
) -> Result<Json<Vec<TransactionResponse>>, 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::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Json(responses))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -65,11 +73,15 @@ async fn get_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<TransactionResponse>, 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<TransactionResponse>), 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<HashMap<Uuid, domain::Account>, AppError> {
|
||||
let account_ids = transactions
|
||||
.iter()
|
||||
.map(|transaction| transaction.account_id)
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(account_repository::get_by_ids(connection, &account_ids).await?)
|
||||
}
|
||||
|
||||
fn create_response(
|
||||
transaction: domain::Transaction,
|
||||
accounts: &HashMap<Uuid, domain::Account>,
|
||||
) -> Result<TransactionResponse, AppError> {
|
||||
let account = accounts
|
||||
.get(&transaction.account_id)
|
||||
.cloned()
|
||||
.ok_or(AppError::Internal)?;
|
||||
|
||||
Ok(TransactionResponse::new(transaction, account))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user