Compare commits
26
Commits
af0588c5ef
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
df3b84079c | ||
|
|
d11e4fd0c4 | ||
|
|
a2ba83e6f8 | ||
|
|
0d564ff299 | ||
|
|
bc4aa8242c | ||
|
|
9d23828345 | ||
|
|
e60ab43abd | ||
|
|
6d2150d1b2 | ||
|
|
7f78d2274c | ||
|
|
e739d5ea5b | ||
|
|
09209be500 | ||
|
|
c86a79b46e | ||
|
|
b65fad16e4 | ||
|
|
a60d0effff | ||
|
|
c230aef034 | ||
|
|
ca0df97e73 | ||
|
|
5c3f734bbc | ||
|
|
e3ed72c9b0 | ||
|
|
3c3b6dc4e6 | ||
|
|
c3796720b7 | ||
|
|
35fd2b90d2 | ||
|
|
4b2f0f3bf7 | ||
|
|
29fe8bee39 | ||
|
|
49a1700706 | ||
|
|
04b58d3075 | ||
|
|
076a573711 |
@@ -28,6 +28,7 @@
|
||||
**/values.dev.yaml
|
||||
/bin
|
||||
/target
|
||||
!/target/**/monzo-ingestion
|
||||
/.idea
|
||||
LICENSE
|
||||
README.md
|
||||
|
||||
@@ -1 +1 @@
|
||||
DATABASE_URL=postgres://postgres@localhost/logos_neu
|
||||
DATABASE_URL=postgres://postgres@localhost/monzo_development
|
||||
|
||||
+21
-22
@@ -1,13 +1,12 @@
|
||||
name: Rust CI
|
||||
name: Build and Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BINARY_NAME: monzo-ingestion
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -27,12 +26,12 @@ jobs:
|
||||
components: rustfmt, clippy
|
||||
|
||||
- name: Add ARM64 target
|
||||
run: rustup target add aarch64-unknown-linux-gnu
|
||||
run: rustup target add aarch64-unknown-linux-musl
|
||||
|
||||
- name: Install ARM64 toolchain
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y gcc-aarch64-linux-gnu
|
||||
apt-get install -y gcc-aarch64-linux-gnu build-essential musl-tools
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v3
|
||||
@@ -54,23 +53,9 @@ jobs:
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: build
|
||||
args: --release --all-features --target aarch64-unknown-linux-gnu
|
||||
args: --release --all-features --target aarch64-unknown-linux-musl
|
||||
env:
|
||||
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
|
||||
|
||||
- name: Run tests
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
args: --all-features
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: binaries
|
||||
path: |
|
||||
target/release/${{ github.event.repository.name }}
|
||||
target/aarch64-unknown-linux-gnu/release/${{ github.event.repository.name }}
|
||||
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER: aarch64-linux-gnu-gcc
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
@@ -85,6 +70,18 @@ jobs:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: binaries
|
||||
path: |
|
||||
target/release/${{ env.RUST_BINARY_NAME }}
|
||||
target/aarch64-unknown-linux-musl/release/${{ env.RUST_BINARY_NAME }}
|
||||
|
||||
# # The target directory is kept in the .dockerignore file, so allow these to be copied in we need to move them to a
|
||||
# # new directory.
|
||||
# - run: mv target docker-binaries
|
||||
|
||||
- name: Build and push multi-arch Docker image
|
||||
uses: docker/build-push-action@v4
|
||||
with:
|
||||
@@ -92,7 +89,9 @@ jobs:
|
||||
file: ./Dockerfile
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: git.joshuacoles.me/${{ github.repository }}:latest,git.joshuacoles.me/${{ github.repository }}:${{ github.sha }}
|
||||
tags: git.joshuacoles.me/${{ github.repository }}:${{ github.sha }},git.joshuacoles.me/${{ github.repository }}:latest
|
||||
build-args: |
|
||||
BINARY_NAME=${{ env.RUST_BINARY_NAME }}
|
||||
|
||||
- uses: robiningelbrecht/ntfy-action@v1.0.0
|
||||
name: Notify via ntfy.sh
|
||||
|
||||
Generated
+1576
-1013
File diff suppressed because it is too large
Load Diff
+17
-17
@@ -7,31 +7,31 @@ edition = "2021"
|
||||
entity = { path = "entity" }
|
||||
migration = { path = "migration" }
|
||||
|
||||
axum = { version = "0.7.5", features = ["multipart"] }
|
||||
tokio = { version = "1.37.0", features = ["full"] }
|
||||
sea-orm = { version = "1.0.0-rc.4", features = [
|
||||
axum = { version = "0.8.8", features = ["multipart"] }
|
||||
tokio = { version = "1.48.0", features = ["full"] }
|
||||
sea-orm = { version = "1.1.0", features = [
|
||||
"sqlx-postgres",
|
||||
"runtime-tokio-rustls",
|
||||
"macros"
|
||||
] }
|
||||
|
||||
serde = { version = "1.0.203", features = ["derive"] }
|
||||
serde_json = "1.0.117"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
tracing-subscriber = "0.3.18"
|
||||
tracing = "0.1.40"
|
||||
anyhow = { version = "1.0.86", features = ["backtrace"] }
|
||||
thiserror = "1.0.61"
|
||||
http = "1.1.0"
|
||||
chrono = { version = "0.4.38", features = ["serde"] }
|
||||
num-traits = "0.2.19"
|
||||
anyhow = { version = "1.0", features = ["backtrace"] }
|
||||
thiserror = "2.0"
|
||||
http = "1.1"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
num-traits = "0.2"
|
||||
csv = "1.3.0"
|
||||
clap = "4.5.4"
|
||||
testcontainers = "0.17.0"
|
||||
testcontainers-modules = { version = "0.5.0", features = ["postgres"] }
|
||||
sqlx = { version = "0.7.4", features = ["postgres"] }
|
||||
tower-http = { version = "0.5.2", features = ["trace"] }
|
||||
bytes = "1.6.0"
|
||||
once_cell = "1.19.0"
|
||||
clap = "4.5"
|
||||
testcontainers = "0.26"
|
||||
testcontainers-modules = { version = "0.14", features = ["postgres"] }
|
||||
sqlx = { version = "0.8", features = ["postgres"] }
|
||||
tower-http = { version = "0.6", features = ["trace"] }
|
||||
bytes = "1.7"
|
||||
once_cell = "1.19"
|
||||
|
||||
[workspace]
|
||||
members = [".", "migration", "entity"]
|
||||
|
||||
+12
-12
@@ -1,14 +1,14 @@
|
||||
FROM --platform=$BUILDPLATFORM debian:bullseye-slim AS builder
|
||||
FROM busybox AS platform_determiner
|
||||
ARG TARGETPLATFORM
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN case "$TARGETPLATFORM" in \
|
||||
"linux/amd64") BINARY_PATH="target/release/toggl-bridge" ;; \
|
||||
"linux/arm64") BINARY_PATH="target/aarch64-unknown-linux-gnu/release/toggl-bridge" ;; \
|
||||
*) exit 1 ;; \
|
||||
esac && \
|
||||
mv "$BINARY_PATH" /usr/local/bin/toggl-bridge
|
||||
ARG BINARY_NAME
|
||||
|
||||
FROM --platform=$TARGETPLATFORM debian:bullseye-slim
|
||||
COPY --from=builder /usr/local/bin/toggl-bridge /usr/local/bin/
|
||||
CMD ["toggl-bridge"]
|
||||
COPY /target /target
|
||||
RUN case "$TARGETPLATFORM" in \
|
||||
"linux/amd64") BINARY_PATH="/target/release/${BINARY_NAME}" ;; \
|
||||
"linux/arm64") BINARY_PATH="/target/aarch64-unknown-linux-musl/release/${BINARY_NAME}" ;; \
|
||||
*) exit 1 ;; \
|
||||
esac && mv "$BINARY_PATH" "/usr/bin/monzo-ingestion" && chmod +x "/usr/bin/monzo-ingestion"
|
||||
|
||||
FROM --platform=$TARGETPLATFORM debian:bookworm-slim
|
||||
COPY --from=platform_determiner /usr/bin/monzo-ingestion /usr/local/bin/monzo-ingestion
|
||||
ENTRYPOINT ["/usr/local/bin/monzo-ingestion"]
|
||||
|
||||
+1
-1
@@ -9,5 +9,5 @@ name = "entity"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
sea-orm = { version = "1.0.0-rc.4" }
|
||||
sea-orm = { version = "1.1.0" }
|
||||
serde = { version = "1.0.203", features = ["derive"] }
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "account")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::transaction::Entity")]
|
||||
Transaction,
|
||||
}
|
||||
|
||||
impl Related<super::transaction::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Transaction.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.2
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -14,6 +14,21 @@ pub struct Model {
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::transaction::Entity",
|
||||
from = "Column::TransactionId",
|
||||
to = "super::transaction::Column::Id",
|
||||
on_update = "NoAction",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Transaction,
|
||||
}
|
||||
|
||||
impl Related<super::transaction::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Transaction.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.2
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
|
||||
|
||||
pub mod prelude;
|
||||
|
||||
pub mod account;
|
||||
pub mod expenditure;
|
||||
pub mod transaction;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.2
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
|
||||
|
||||
pub use super::account::Entity as Account;
|
||||
pub use super::expenditure::Entity as Expenditure;
|
||||
pub use super::transaction::Entity as Transaction;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.2
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -18,9 +18,33 @@ pub struct Model {
|
||||
pub description: Option<String>,
|
||||
#[sea_orm(unique)]
|
||||
pub identity_hash: Option<i64>,
|
||||
pub account_id: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::account::Entity",
|
||||
from = "Column::AccountId",
|
||||
to = "super::account::Column::Id",
|
||||
on_update = "NoAction",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Account,
|
||||
#[sea_orm(has_many = "super::expenditure::Entity")]
|
||||
Expenditure,
|
||||
}
|
||||
|
||||
impl Related<super::account::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Account.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::expenditure::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Expenditure.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
@@ -12,7 +12,7 @@ path = "src/lib.rs"
|
||||
async-std = { version = "1", features = ["attributes", "tokio1"] }
|
||||
|
||||
[dependencies.sea-orm-migration]
|
||||
version = "1.0.0-rc.4"
|
||||
version = "1.1.0"
|
||||
features = [
|
||||
"runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
|
||||
"sqlx-postgres", # `DATABASE_DRIVER` feature
|
||||
|
||||
@@ -3,6 +3,9 @@ pub use sea_orm_migration::prelude::*;
|
||||
pub mod m20230904_141851_create_monzo_tables;
|
||||
mod m20240529_195030_add_transaction_identity_hash;
|
||||
mod m20240603_162500_make_title_optional;
|
||||
mod m20241015_195220_add_account_to_transactions;
|
||||
mod m20241015_200222_add_expenditure_transaction_fk;
|
||||
mod m20241015_200652_add_accounts;
|
||||
|
||||
pub struct Migrator;
|
||||
|
||||
@@ -17,6 +20,9 @@ impl MigratorTrait for Migrator {
|
||||
Box::new(m20230904_141851_create_monzo_tables::Migration),
|
||||
Box::new(m20240529_195030_add_transaction_identity_hash::Migration),
|
||||
Box::new(m20240603_162500_make_title_optional::Migration),
|
||||
Box::new(m20241015_195220_add_account_to_transactions::Migration),
|
||||
Box::new(m20241015_200222_add_expenditure_transaction_fk::Migration),
|
||||
Box::new(m20241015_200652_add_accounts::Migration),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
use sea_orm_migration::{prelude::*, schema::*};
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(Account::Table)
|
||||
.if_not_exists()
|
||||
.col(
|
||||
ColumnDef::new(Account::Id)
|
||||
.integer()
|
||||
.auto_increment()
|
||||
.not_null()
|
||||
.primary_key(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(Account::Name)
|
||||
.string()
|
||||
.not_null(),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager.alter_table(
|
||||
TableAlterStatement::new()
|
||||
.table(Transaction::Table)
|
||||
.add_column(ColumnDef::new(Transaction::AccountId).integer())
|
||||
.to_owned(),
|
||||
).await?;
|
||||
|
||||
manager
|
||||
.create_foreign_key(
|
||||
ForeignKey::create()
|
||||
.name("fk_transaction_account_id")
|
||||
.from(Transaction::Table, Transaction::AccountId)
|
||||
.to(Account::Table, Account::Id)
|
||||
.on_delete(ForeignKeyAction::Cascade)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager.alter_table(
|
||||
TableAlterStatement::new()
|
||||
.table(Transaction::Table)
|
||||
.drop_column(Transaction::AccountId)
|
||||
.to_owned(),
|
||||
).await?;
|
||||
|
||||
manager.drop_table(Table::drop().table(Account::Table).to_owned()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Account {
|
||||
Table,
|
||||
Id,
|
||||
Name,
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Transaction {
|
||||
Table,
|
||||
AccountId,
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use sea_orm_migration::{prelude::*, schema::*};
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_foreign_key(
|
||||
ForeignKey::create()
|
||||
.name("fk_expenditure_transaction_id")
|
||||
.from(Expenditure::Table, Expenditure::TransactionId)
|
||||
.to(Transaction::Table, Transaction::Id)
|
||||
.on_delete(ForeignKeyAction::Cascade)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager.drop_foreign_key(ForeignKey::drop().name("fk_expenditure_transaction_id").to_owned()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Transaction {
|
||||
Table,
|
||||
Id,
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Expenditure {
|
||||
Table,
|
||||
TransactionId,
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use sea_orm_migration::{prelude::*, schema::*};
|
||||
use crate::sea_orm::sqlx;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager.exec_stmt(
|
||||
InsertStatement::new()
|
||||
.into_table(Account::Table)
|
||||
.columns(vec![Account::Name])
|
||||
.values_panic(["Monzo".into()])
|
||||
.values_panic(["Flex".into()])
|
||||
.to_owned()
|
||||
).await?;
|
||||
|
||||
let id: i32 = manager.get_connection().query_one(
|
||||
sea_orm::Statement::from_string(
|
||||
manager.get_database_backend(),
|
||||
"SELECT id FROM account WHERE name = 'Monzo'",
|
||||
)
|
||||
).await?.expect("Monzo account not found").try_get_by_index(0)?;
|
||||
|
||||
manager.exec_stmt(
|
||||
UpdateStatement::new()
|
||||
.table(Transaction::Table)
|
||||
.values([(Transaction::AccountId, id.into())])
|
||||
.to_owned()
|
||||
).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
// This is a data creation migration, so we do not roll back the migration
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Account {
|
||||
Table,
|
||||
Id,
|
||||
Name,
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Transaction {
|
||||
Table,
|
||||
AccountId,
|
||||
}
|
||||
+62
-25
@@ -20,14 +20,15 @@ pub struct Insertion {
|
||||
pub async fn insert(
|
||||
db: &DatabaseConnection,
|
||||
monzo_rows: Vec<MonzoRow>,
|
||||
account_id: i32,
|
||||
) -> Result<Vec<String>, AppError> {
|
||||
let mut new_transaction_ids = Vec::new();
|
||||
let insertions = monzo_rows
|
||||
.into_iter()
|
||||
.map(MonzoRow::into_insertion)
|
||||
.map(|row| MonzoRow::into_insertion(row, account_id))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
for insertions in insertions.chunks(400) {
|
||||
for insertions in insertions.chunks(200) {
|
||||
let (new_or_updated_insertions, inserted_transaction_ids) =
|
||||
whittle_insertions(insertions, db).await?;
|
||||
|
||||
@@ -118,7 +119,7 @@ async fn whittle_insertions<'a>(
|
||||
.select_only()
|
||||
.columns([transaction::Column::IdentityHash])
|
||||
.filter(transaction::Column::IdentityHash.is_not_null())
|
||||
.into_tuple::<(i64, )>()
|
||||
.into_tuple::<(i64,)>()
|
||||
.all(tx)
|
||||
.await?;
|
||||
|
||||
@@ -132,7 +133,7 @@ async fn whittle_insertions<'a>(
|
||||
let hash = i.identity_hash;
|
||||
!existing_hashes
|
||||
.iter()
|
||||
.any(|(existing_hash, )| *existing_hash == hash)
|
||||
.any(|(existing_hash,)| *existing_hash == hash)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -158,16 +159,17 @@ async fn notify_new_transactions(
|
||||
|
||||
mod tests {
|
||||
use super::{insert, notify_new_transactions, update_expenditures, update_transactions};
|
||||
use crate::ingestion::ingestion_logic::from_json_row;
|
||||
use anyhow::Error;
|
||||
use tokio::sync::OnceCell;
|
||||
use entity::account;
|
||||
use migration::MigratorTrait;
|
||||
use sea_orm::{DatabaseConnection, TransactionTrait};
|
||||
use sea_orm::{ActiveModelTrait, DatabaseConnection, TransactionTrait};
|
||||
use serde_json::Value;
|
||||
use sqlx::postgres::PgListener;
|
||||
use sqlx::PgPool;
|
||||
use sqlx::{Executor, PgPool};
|
||||
use testcontainers::runners::AsyncRunner;
|
||||
use testcontainers::ContainerAsync;
|
||||
use crate::ingestion::ingestion_logic::from_json_row;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DatabaseInstance {
|
||||
@@ -202,13 +204,19 @@ mod tests {
|
||||
Ok(instance)
|
||||
}
|
||||
|
||||
async fn get_or_initialize_db_instance() -> Result<
|
||||
&'static DatabaseInstance,
|
||||
Error,
|
||||
> {
|
||||
Ok(INSTANCE.get_or_init(|| async {
|
||||
initialise_db().await.unwrap()
|
||||
}).await)
|
||||
async fn get_or_initialize_db_instance() -> Result<&'static DatabaseInstance, Error> {
|
||||
Ok(INSTANCE
|
||||
.get_or_init(|| async { initialise_db().await.unwrap() })
|
||||
.await)
|
||||
}
|
||||
|
||||
async fn create_test_account(db: &DatabaseConnection) -> Result<i32, Error> {
|
||||
let new_account = account::ActiveModel {
|
||||
id: sea_orm::ActiveValue::NotSet,
|
||||
name: sea_orm::ActiveValue::Set("Test Account".to_string()),
|
||||
};
|
||||
let inserted = new_account.insert(db).await?;
|
||||
Ok(inserted.id)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -252,6 +260,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn test_notify_on_insert() -> Result<(), Error> {
|
||||
let dbi = get_or_initialize_db_instance().await?;
|
||||
let account_id = create_test_account(&dbi.db).await?;
|
||||
let mut listener = PgListener::connect_with(&dbi.pool).await?;
|
||||
listener.listen("monzo_new_transactions").await?;
|
||||
|
||||
@@ -259,17 +268,17 @@ mod tests {
|
||||
let json: Vec<Vec<Value>> = serde_json::from_str(json).unwrap();
|
||||
let data = json
|
||||
.iter()
|
||||
.map(|row| from_json_row(row.clone()))
|
||||
.collect::<Result<Vec<_>, anyhow::Error>>()
|
||||
.unwrap();
|
||||
.map(|row| from_json_row(row))
|
||||
.collect::<Result<Vec<_>, anyhow::Error>>()?;
|
||||
|
||||
insert(&dbi.db, data.clone()).await?;
|
||||
insert(&dbi.db, data.clone(), account_id).await?;
|
||||
let notification = listener.recv().await?;
|
||||
let payload = notification.payload();
|
||||
let mut payload = serde_json::from_str::<Vec<String>>(&payload)?;
|
||||
payload.sort();
|
||||
|
||||
let mut ids = data.iter()
|
||||
let mut ids = data
|
||||
.iter()
|
||||
.map(|row| row.transaction_id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -277,23 +286,51 @@ mod tests {
|
||||
|
||||
assert_eq!(payload, ids, "Inserted IDs do not match");
|
||||
|
||||
insert(&dbi.db, data.clone()).await?;
|
||||
insert(&dbi.db, data.clone(), account_id).await?;
|
||||
let notification = listener.recv().await?;
|
||||
let payload = notification.payload();
|
||||
let payload = serde_json::from_str::<Vec<String>>(&payload)?;
|
||||
assert_eq!(payload, Vec::<String>::new(), "Re-inserting identical rows triggered double notification");
|
||||
assert_eq!(
|
||||
payload,
|
||||
Vec::<String>::new(),
|
||||
"Re-inserting identical rows triggered double notification"
|
||||
);
|
||||
|
||||
let mut altered_data = data.clone();
|
||||
altered_data[0].description = Some("New description".to_string());
|
||||
|
||||
assert_ne!(altered_data[0].compute_hash(), data[0].compute_hash(), "Alterations have the same hash");
|
||||
assert_ne!(
|
||||
altered_data[0].compute_hash(),
|
||||
data[0].compute_hash(),
|
||||
"Alterations have the same hash"
|
||||
);
|
||||
|
||||
insert(&dbi.db, altered_data.clone()).await?;
|
||||
insert(&dbi.db, altered_data.clone(), account_id).await?;
|
||||
let notification = listener.recv().await?;
|
||||
let payload = notification.payload();
|
||||
let payload = serde_json::from_str::<Vec<String>>(&payload)?;
|
||||
assert_eq!(payload, vec![altered_data[0].transaction_id.clone()], "Re-inserting altered row failed to re-trigger notification");
|
||||
assert_eq!(
|
||||
payload,
|
||||
vec![altered_data[0].transaction_id.clone()],
|
||||
"Re-inserting altered row failed to re-trigger notification"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn get_account_id(
|
||||
p0: &DatabaseConnection,
|
||||
p1: Option<String>,
|
||||
) -> Result<i32, AppError> {
|
||||
let p1 = p1.unwrap_or("Monzo".to_string());
|
||||
|
||||
entity::prelude::Account::find()
|
||||
.filter(entity::account::Column::Name.eq(p1))
|
||||
.select_only()
|
||||
.column(entity::account::Column::Id)
|
||||
.into_tuple::<i32>()
|
||||
.one(p0)
|
||||
.await?
|
||||
.ok_or(AppError::BadRequest(anyhow!("Account not found")))
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#[allow(dead_code)]
|
||||
mod headings {
|
||||
pub mod headings {
|
||||
#[allow(unused_imports)]
|
||||
pub use super::super::ingestion_logic::headings::*;
|
||||
|
||||
// Additional FLex headings
|
||||
// Additional Flex headings
|
||||
pub const MONEY_OUT: usize = 16;
|
||||
pub const MONEY_IN: usize = 17;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use sea_orm::prelude::Decimal;
|
||||
use sea_orm::IntoActiveModel;
|
||||
use serde_json::Value;
|
||||
use std::hash::Hash;
|
||||
use crate::ingestion::flex;
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) mod headings {
|
||||
@@ -77,7 +78,7 @@ impl MonzoRow {
|
||||
hasher.finish() as i64
|
||||
}
|
||||
|
||||
pub fn into_insertion(self) -> Result<Insertion, anyhow::Error> {
|
||||
pub fn into_insertion(self, account_id: i32) -> Result<Insertion, anyhow::Error> {
|
||||
let identity_hash = self.compute_hash();
|
||||
|
||||
let expenditures: Vec<_> = match &self.category_split {
|
||||
@@ -106,6 +107,7 @@ impl MonzoRow {
|
||||
total_amount: self.total_amount,
|
||||
description: self.description,
|
||||
identity_hash: Some(identity_hash),
|
||||
account_id: Some(account_id),
|
||||
}
|
||||
.into_active_model(),
|
||||
|
||||
@@ -138,7 +140,7 @@ fn parse_timestamp(date: &str, time: &str) -> anyhow::Result<NaiveDateTime> {
|
||||
Ok(date.and_time(time))
|
||||
}
|
||||
|
||||
pub fn from_json_row(row: Vec<Value>) -> anyhow::Result<MonzoRow> {
|
||||
pub fn from_json_row(row: &[Value]) -> anyhow::Result<MonzoRow> {
|
||||
let date = DateTime::parse_from_rfc3339(row[headings::DATE].as_str().context("No date")?)
|
||||
.context("Failed to parse date")?;
|
||||
|
||||
@@ -176,7 +178,7 @@ fn test_json() {
|
||||
|
||||
let json_rows = json
|
||||
.iter()
|
||||
.map(|row| from_json_row(row.clone()))
|
||||
.map(|row| from_json_row(&row))
|
||||
.collect::<Result<Vec<_>, anyhow::Error>>()
|
||||
.unwrap();
|
||||
|
||||
|
||||
+89
-19
@@ -9,34 +9,99 @@ use sea_orm::DatabaseConnection;
|
||||
use serde_json::Value;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[derive(serde::Deserialize, Debug)]
|
||||
#[serde(untagged)]
|
||||
pub enum MonzoBatchedJsonInput {
|
||||
Legacy(Vec<Vec<Value>>),
|
||||
New {
|
||||
account_id: Option<u8>,
|
||||
rows: Vec<Vec<Value>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl MonzoBatchedJsonInput {
|
||||
fn account_id(&self) -> Option<u8> {
|
||||
match self {
|
||||
MonzoBatchedJsonInput::Legacy(_) => None,
|
||||
MonzoBatchedJsonInput::New { account_id, .. } => *account_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn rows(&self) -> &[Vec<Value>] {
|
||||
match self {
|
||||
MonzoBatchedJsonInput::Legacy(rows) => rows,
|
||||
MonzoBatchedJsonInput::New { rows, .. } => rows,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn monzo_batched_json(
|
||||
Extension(db): Extension<DatabaseConnection>,
|
||||
Json(data): Json<Vec<Vec<Value>>>,
|
||||
Json(data): Json<MonzoBatchedJsonInput>,
|
||||
) -> Result<&'static str, AppError> {
|
||||
let data = data
|
||||
.into_iter()
|
||||
.skip(1) // Skip the header row.
|
||||
.map(from_json_row)
|
||||
let rows = data
|
||||
.rows()
|
||||
.iter()
|
||||
.skip_while(|row| row[0] == Value::String("Transaction ID".to_string()))
|
||||
.map(|row| from_json_row(row.as_ref()))
|
||||
.collect::<Result<_, _>>()?;
|
||||
|
||||
db::insert(&db, data).await?;
|
||||
// We default to the main account for JSON ingestion for now.
|
||||
db::insert(&db, rows, data.account_id().unwrap_or(1) as i32).await?;
|
||||
|
||||
Ok("Ok")
|
||||
}
|
||||
|
||||
async fn extract_csv(mut multipart: Multipart) -> Result<Option<Bytes>, MultipartError> {
|
||||
let csv = loop {
|
||||
match multipart.next_field().await? {
|
||||
Some(field) if field.name() == Some("csv") => {
|
||||
break Some(field.bytes().await?);
|
||||
async fn extract_csv_and_account_name(
|
||||
mut multipart: Multipart,
|
||||
) -> Result<(Option<Bytes>, Option<String>), MultipartError> {
|
||||
let mut csv = None;
|
||||
let mut account_name = None;
|
||||
|
||||
while let Some(field) = multipart.next_field().await? {
|
||||
match field.name() {
|
||||
Some("csv") => {
|
||||
csv = Some(field.bytes().await?);
|
||||
}
|
||||
|
||||
Some(_) => {}
|
||||
None => break None,
|
||||
Some("account_id") => {
|
||||
account_name = Some(field.text().await?);
|
||||
}
|
||||
};
|
||||
|
||||
Ok(csv)
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if csv.is_some() && account_name.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok((csv, account_name))
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Debug, Clone)]
|
||||
pub struct ShortcutBody {
|
||||
pub body: String,
|
||||
pub account_name: String,
|
||||
}
|
||||
|
||||
pub async fn shortcuts_csv(
|
||||
Extension(db): Extension<DatabaseConnection>,
|
||||
Json(shortcut_body): Json<ShortcutBody>,
|
||||
) -> Result<&'static str, AppError> {
|
||||
let account_id = db::get_account_id(&db, Some(shortcut_body.account_name)).await?;
|
||||
|
||||
let csv = Cursor::new(shortcut_body.body.as_bytes());
|
||||
let mut csv = csv::Reader::from_reader(csv);
|
||||
let data = csv.records();
|
||||
let data = data
|
||||
.filter_map(|f| f.ok())
|
||||
.map(from_csv_row)
|
||||
.collect::<Result<_, _>>()?;
|
||||
|
||||
db::insert(&db, data, account_id).await?;
|
||||
|
||||
Ok("Ok")
|
||||
}
|
||||
|
||||
pub async fn monzo_batched_csv(
|
||||
@@ -45,10 +110,15 @@ pub async fn monzo_batched_csv(
|
||||
) -> Result<&'static str, AppError> {
|
||||
static CSV_MISSING_ERR_MSG: &str = "No CSV file provided. Expected a multipart request with a `csv` field containing the contents of the CSV.";
|
||||
|
||||
let csv = extract_csv(multipart)
|
||||
let (csv, account_name) = extract_csv_and_account_name(multipart)
|
||||
.await
|
||||
.map_err(|e| AppError::BadRequest(anyhow!(e)))
|
||||
.and_then(|csv| csv.ok_or(AppError::BadRequest(anyhow!(CSV_MISSING_ERR_MSG))))?;
|
||||
.map_err(|e| AppError::BadRequest(anyhow!(e)))?;
|
||||
|
||||
let Some(csv) = csv else {
|
||||
return Err(AppError::BadRequest(anyhow!(CSV_MISSING_ERR_MSG)));
|
||||
};
|
||||
|
||||
let account_id = db::get_account_id(&db, account_name).await?;
|
||||
|
||||
let csv = Cursor::new(csv);
|
||||
let mut csv = csv::Reader::from_reader(csv);
|
||||
@@ -58,7 +128,7 @@ pub async fn monzo_batched_csv(
|
||||
.map(from_csv_row)
|
||||
.collect::<Result<_, _>>()?;
|
||||
|
||||
db::insert(&db, data).await?;
|
||||
db::insert(&db, data, account_id).await?;
|
||||
|
||||
Ok("Ok")
|
||||
}
|
||||
|
||||
+9
-3
@@ -4,7 +4,7 @@ mod ingestion;
|
||||
use crate::error::AppError;
|
||||
use crate::ingestion::db;
|
||||
use crate::ingestion::ingestion_logic::from_csv_row;
|
||||
use crate::ingestion::routes::{monzo_batched_csv, monzo_batched_json};
|
||||
use crate::ingestion::routes::{monzo_batched_csv, monzo_batched_json, shortcuts_csv};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Extension, Router};
|
||||
use clap::{Parser, Subcommand};
|
||||
@@ -44,6 +44,10 @@ enum Commands {
|
||||
Csv {
|
||||
/// The path of the CSV file to ingest.
|
||||
csv_file: PathBuf,
|
||||
|
||||
/// The name of the account to ingest the CSV for.
|
||||
#[clap(long, short)]
|
||||
account: String,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -94,7 +98,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
serve_web(addr, connection).await?;
|
||||
}
|
||||
|
||||
Commands::Csv { csv_file } => {
|
||||
Commands::Csv { csv_file, account: account_name } => {
|
||||
let mut csv = csv::Reader::from_reader(File::open(csv_file)?);
|
||||
let data = csv.records();
|
||||
let data = data
|
||||
@@ -102,7 +106,8 @@ async fn main() -> anyhow::Result<()> {
|
||||
.map(from_csv_row)
|
||||
.collect::<Result<_, _>>()?;
|
||||
|
||||
db::insert(&connection, data).await?;
|
||||
let account_id = db::get_account_id(&connection, Some(account_name)).await?;
|
||||
db::insert(&connection, data, account_id).await?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +119,7 @@ async fn serve_web(address: SocketAddr, connection: DatabaseConnection) -> anyho
|
||||
.route("/health", get(health_check))
|
||||
.route("/monzo-batch-export", post(monzo_batched_json))
|
||||
.route("/monzo-csv-ingestion", post(monzo_batched_csv))
|
||||
.route("/shortcuts-csv-import", post(shortcuts_csv))
|
||||
.layer(Extension(connection.clone()))
|
||||
.layer(TraceLayer::new_for_http());
|
||||
|
||||
|
||||
Reference in New Issue
Block a user