Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor database schema #12

Merged
merged 2 commits into from
Mar 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 0 additions & 49 deletions migrations/2024-01-22-103957_init/up.sql

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
-- This file should undo anything in `up.sql`
DROP TABLE invoice_attachments;

DROP TABLE invoice_rows;

DROP TABLE invoices;
DROP TABLE parties;
DROP TYPE invoice_status;

DROP INDEX idx_invoices_status;

DROP INDEX idx_invoices_creation_time;

DROP TABLE addresses;

DROP TYPE invoice_status;
46 changes: 46 additions & 0 deletions migrations/2024-03-14-222214_init/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
-- Enum for invoice status
CREATE TYPE invoice_status AS ENUM ('open', 'accepted', 'paid', 'cancelled');

-- Addresses table
CREATE TABLE addresses (
id SERIAL PRIMARY KEY,
street VARCHAR(128) NOT NULL,
city VARCHAR(128) NOT NULL,
zip VARCHAR(128) NOT NULL,
CONSTRAINT no_duplicates UNIQUE (street, city, zip)
);

CREATE TABLE invoices (
id SERIAL PRIMARY KEY,
status invoice_status NOT NULL DEFAULT 'open',
creation_time TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
recipient_name VARCHAR(128) NOT NULL,
recipient_email VARCHAR(128) NOT NULL,
bank_account_number VARCHAR(128) NOT NULL,
address_id INT NOT NULL,
FOREIGN KEY (address_id) REFERENCES addresses(id)
);

CREATE INDEX idx_invoices_status ON invoices(status);

CREATE INDEX idx_invoices_creation_time ON invoices(creation_time);

-- Invoice rows table
CREATE TABLE invoice_rows (
id SERIAL PRIMARY KEY,
invoice_id INT NOT NULL,
product VARCHAR(128) NOT NULL,
quantity INT NOT NULL,
unit VARCHAR(128) NOT NULL,
unit_price INT NOT NULL,
FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE
);

-- Invoice attachments table
CREATE TABLE invoice_attachments (
id SERIAL PRIMARY KEY,
invoice_id INT NOT NULL,
filename VARCHAR(128) NOT NULL,
hash VARCHAR(64) NOT NULL,
FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE
);
41 changes: 31 additions & 10 deletions src/api/invoices.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::database::DatabaseConnection;
use crate::error::Error;
use crate::models::{Attachment, Invoice, InvoiceRow};
use axum::{async_trait, body::Bytes, http::StatusCode, Json};
use axum_typed_multipart::{
FieldData, FieldMetadata, TryFromChunks, TryFromMultipart, TypedMultipart, TypedMultipartError,
};
use axum_valid::Garde;
use chrono::{DateTime, NaiveDate, Utc};
use chrono::{DateTime, Utc};
use futures::stream::Stream;
use futures::stream::{self, TryStreamExt};
use garde::Validate;
Expand All @@ -28,14 +29,19 @@ impl TryFromChunks for CreateInvoice {
/// Body for the request for creating new invoices
#[derive(Clone, Debug, Serialize, Deserialize, Validate)]
pub struct CreateInvoice {
/// The other party of the invoice
/// The recipient's name
#[garde(byte_length(max = 128))]
pub recipient_name: String,
/// The recipient's email
#[garde(byte_length(max = 128))]
pub recipient_email: String,
/// The recipient's address
#[garde(dive)]
pub counter_party: crate::models::NewParty,
/// The due date of the invoice.
/// It cannot be in the past
//TODO: #[garde(time(op = after_now))]
#[garde(skip)]
pub due_date: NaiveDate,
pub address: crate::models::NewAddress,
/// The recipient's bank account number
// TODO: maybe validate with https://crates.io/crates/iban_validate/
#[garde(byte_length(max = 128))]
pub bank_account_number: String,
/// The rows of the invoice
#[garde(length(min = 1), dive)]
pub rows: Vec<CreateInvoiceRow>,
Expand Down Expand Up @@ -84,11 +90,26 @@ pub struct PopulatedInvoice {
pub id: i32,
pub status: crate::models::InvoiceStatus,
pub creation_time: DateTime<Utc>,
pub due_date: NaiveDate,
pub counter_party: crate::models::Party,
pub recipient_name: String,
pub recipient_email: String,
pub bank_account_number: String,
pub rows: Vec<crate::models::InvoiceRow>,
pub attachments: Vec<crate::models::Attachment>,
}
impl PopulatedInvoice {
pub fn new(invoice: Invoice, rows: Vec<InvoiceRow>, attachments: Vec<Attachment>) -> Self {
Self {
id: invoice.id,
status: invoice.status,
creation_time: invoice.creation_time,
recipient_name: invoice.recipient_name,
recipient_email: invoice.recipient_email,
bank_account_number: invoice.bank_account_number,
rows,
attachments,
}
}
}

async fn try_handle_file(field: &FieldData<Bytes>) -> Result<CreateInvoiceAttachment, Error> {
let filename = field
Expand Down
91 changes: 32 additions & 59 deletions src/database/invoices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,52 @@ use super::DatabaseConnection;
use crate::api::invoices::{CreateInvoice, PopulatedInvoice};
use crate::error::Error;
use crate::models::*;
use futures::TryStreamExt;

use diesel::prelude::*;
use diesel_async::RunQueryDsl;

impl DatabaseConnection {
pub async fn create_party(&mut self, party: &NewParty) -> Result<Party, Error> {
use crate::schema::parties::dsl::*;
/// create an address, returning an id of the address, either
pub async fn create_address(&mut self, address: &NewAddress) -> Result<i32, Error> {
use crate::schema::addresses::dsl::*;

diesel::insert_into(parties)
.values(party)
diesel::insert_into(addresses)
.values(address)
.on_conflict(diesel::upsert::on_constraint("no_duplicates"))
.do_nothing()
.execute(&mut self.0)
.await?;

// NOTE: Diesel is dumb so we have to requery for the data
// because on_conflict() doesn't support returning()
Ok(parties
Ok(addresses
.select(id)
.filter(
name.eq(&party.name)
.and(street.eq(&party.street))
.and(city.eq(&party.city))
.and(zip.eq(&party.zip))
.and(bank_account.eq(&party.bank_account)),
street
.eq(&address.street)
.and(city.eq(&address.city))
.and(zip.eq(&address.zip)),
)
.first::<Party>(&mut self.0)
.first::<i32>(&mut self.0)
.await?)
}

pub async fn create_invoice(
&mut self,
invoice: CreateInvoice,
) -> Result<PopulatedInvoice, Error> {
let party = self.create_party(&invoice.counter_party).await?;
let address_id = self.create_address(&invoice.address).await?;

// TODO: this could (but should it is totally another question) be done with an impl for CreateInvoice,
// as this is the only thing CreateInvoice is used for
let inv = NewInvoice {
status: InvoiceStatus::Open,
counter_party_id: party.id,
creation_time: chrono::Utc::now(),
due_date: invoice.due_date,
address_id,
recipient_name: invoice.recipient_name,
recipient_email: invoice.recipient_email,
bank_account_number: invoice.bank_account_number,
};

let created = {
let created_invoice = {
use crate::schema::invoices::dsl::*;
diesel::insert_into(invoices)
.values(&inv)
Expand All @@ -62,7 +64,7 @@ impl DatabaseConnection {
.rows
.into_iter()
.map(|r| NewInvoiceRow {
invoice_id: created.id,
invoice_id: created_invoice.id,
product: r.product,
quantity: r.quantity,
unit: r.unit,
Expand All @@ -83,7 +85,7 @@ impl DatabaseConnection {
.attachments
.into_iter()
.map(|a| NewAttachment {
invoice_id: created.id,
invoice_id: created_invoice.id,
hash: a.hash,
filename: a.filename,
})
Expand All @@ -94,41 +96,21 @@ impl DatabaseConnection {
.await?
};

Ok(PopulatedInvoice {
id: created.id,
status: created.status,
creation_time: created.creation_time,
counter_party: party,
rows,
due_date: created.due_date,
attachments,
})
Ok(created_invoice.into_populated(rows, attachments))
kahlstrm marked this conversation as resolved.
Show resolved Hide resolved
}
pub async fn list_invoices(&mut self) -> Result<Vec<PopulatedInvoice>, Error> {
let (invoices, parties): (Vec<Invoice>, Vec<Party>) = {
use crate::schema::invoices;
use crate::schema::parties;
invoices::table
.inner_join(parties::table)
.select((Invoice::as_select(), Party::as_select()))
.load_stream::<(Invoice, Party)>(&mut self.0)
.await?
.try_fold(
(Vec::new(), Vec::new()),
|(mut invoices, mut parties), (invoice, party)| {
invoices.push(invoice);
parties.push(party);
futures::future::ready(Ok((invoices, parties)))
},
)
.await?
};
let invoice_rows = InvoiceRow::belonging_to(&invoices)
use crate::schema::invoices;
let invoices = invoices::table
.select(Invoice::as_select())
.load(&mut self.0)
.await?;

let invoice_rows: Vec<Vec<_>> = InvoiceRow::belonging_to(&invoices)
.select(InvoiceRow::as_select())
.load(&mut self.0)
.await?
.grouped_by(&invoices);
let attachments = Attachment::belonging_to(&invoices)
let attachments: Vec<Vec<_>> = Attachment::belonging_to(&invoices)
.select(Attachment::as_select())
.load(&mut self.0)
.await?
Expand All @@ -137,16 +119,7 @@ impl DatabaseConnection {
.into_iter()
.zip(attachments)
.zip(invoices)
.zip(parties)
.map(|(((rows, attachments), invoice), party)| PopulatedInvoice {
id: invoice.id,
status: invoice.status,
creation_time: invoice.creation_time,
counter_party: party,
rows,
due_date: invoice.due_date,
attachments,
})
.map(|((rows, attachments), invoice)| invoice.into_populated(rows, attachments))
.collect::<Vec<PopulatedInvoice>>())
}
}
Loading
Loading