first commit
This commit is contained in:
commit
dd6a740645
37 files changed
+5424
No files matched your search
@@ -0,0 +1,87 @@
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use super::{PALETTE, affected, clean_color, clean_name};
|
||||
use crate::clock;
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::{Client, UpdateInput};
|
||||
|
||||
pub async fn list(pool: &SqlitePool, include_archived: bool) -> AppResult<Vec<Client>> {
|
||||
Ok(sqlx::query_as(
|
||||
"SELECT id, name, color, archived, created_at FROM clients
|
||||
WHERE ?1 OR archived = 0
|
||||
ORDER BY archived, name COLLATE NOCASE",
|
||||
)
|
||||
.bind(include_archived)
|
||||
.fetch_all(pool)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn get(pool: &SqlitePool, id: i64) -> AppResult<Client> {
|
||||
Ok(
|
||||
sqlx::query_as("SELECT id, name, color, archived, created_at FROM clients WHERE id = ?1")
|
||||
.bind(id)
|
||||
.fetch_one(pool)
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn create(pool: &SqlitePool, name: &str, color: Option<&str>) -> AppResult<Client> {
|
||||
let name = clean_name(name)?;
|
||||
let color = match color {
|
||||
Some(c) => clean_color(c)?,
|
||||
None => next_color(pool).await?,
|
||||
};
|
||||
let id = sqlx::query("INSERT INTO clients (name, color, created_at) VALUES (?1, ?2, ?3)")
|
||||
.bind(name)
|
||||
.bind(color)
|
||||
.bind(clock::ts(&clock::now()))
|
||||
.execute(pool)
|
||||
.await?
|
||||
.last_insert_rowid();
|
||||
get(pool, id).await
|
||||
}
|
||||
|
||||
pub async fn update(pool: &SqlitePool, id: i64, input: &UpdateInput) -> AppResult<Client> {
|
||||
let name = input.name.as_deref().map(clean_name).transpose()?;
|
||||
let color = match &input.color {
|
||||
None => None,
|
||||
Some(Some(c)) => Some(clean_color(c)?),
|
||||
Some(None) => {
|
||||
return Err(AppError::Validation(
|
||||
"un client doit avoir une couleur".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
affected(
|
||||
sqlx::query(
|
||||
"UPDATE clients SET name = COALESCE(?2, name), archived = COALESCE(?3, archived),
|
||||
color = COALESCE(?4, color)
|
||||
WHERE id = ?1",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(name)
|
||||
.bind(input.archived)
|
||||
.bind(color)
|
||||
.execute(pool)
|
||||
.await?,
|
||||
)?;
|
||||
get(pool, id).await
|
||||
}
|
||||
|
||||
/// The palette color for the next client, cycling once all are used.
|
||||
pub async fn next_color(pool: &SqlitePool) -> AppResult<String> {
|
||||
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM clients")
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(PALETTE[count as usize % PALETTE.len()].to_owned())
|
||||
}
|
||||
|
||||
/// Deletes the client with all its projects and time entries.
|
||||
pub async fn delete(pool: &SqlitePool, id: i64) -> AppResult<()> {
|
||||
affected(
|
||||
sqlx::query("DELETE FROM clients WHERE id = ?1")
|
||||
.bind(id)
|
||||
.execute(pool)
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user