Enregistre les changements d'articles par lots en arrière-plan

Cocher, ajouter, modifier ou supprimer un article s'affiche aussitôt :
le changement attend dans une file, fusionné avec les précédents, puis
part avec les autres en une seule requête, une à la fois. Le serveur
applique le lot dans une transaction et résout les ids temporaires des
articles ajoutés. Sans réseau, le lot est gardé et renvoyé plus tard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Romulus21andClaude Opus 5.5 committed 2026-10-16 08:47:25 +02:00
1 parent f3f5f0cee1
commit 6c593b0201
7 files changed
+565 -126

No files matched your search

+72 -18
View File
@@ -3,7 +3,7 @@ use sqlx::{Row, SqliteConnection};
use std::str::FromStr;
use crate::model::{
Account, Category, Icon, Item, ItemInput, ListColor, Member, Quantity, ShoppingList, Suggestion, Unit, User,
Account, Category, Icon, Item, ItemInput, ItemOp, ListColor, Member, Quantity, ShoppingList, Suggestion, Unit, User,
};
pub async fn connect(url: &str) -> Result<SqlitePool, sqlx::Error> {
@@ -352,7 +352,7 @@ pub async fn item_list_id(pool: &SqlitePool, item_id: i64) -> Result<Option<i64>
}
/// Remembers the product in the user's catalog so it can be suggested later.
async fn record_in_catalog(pool: &SqlitePool, user_id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
async fn record_in_catalog(conn: &mut SqliteConnection, user_id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
sqlx::query(
"INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1)
ON CONFLICT(user_id, name) DO UPDATE SET
@@ -364,12 +364,12 @@ async fn record_in_catalog(pool: &SqlitePool, user_id: i64, input: &ItemInput) -
.bind(&input.name)
.bind(input.icon.as_str())
.bind(input.category.as_str())
.execute(pool)
.execute(&mut *conn)
.await?;
Ok(())
}
pub async fn add_item(pool: &SqlitePool, user_id: i64, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> {
async fn add_item(conn: &mut SqliteConnection, user_id: i64, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> {
let row = sqlx::query(
"INSERT INTO items (list_id, name, amount, unit, icon, category)
VALUES (?, ?, ?, ?, ?, ?) RETURNING id",
@@ -380,13 +380,13 @@ pub async fn add_item(pool: &SqlitePool, user_id: i64, list_id: i64, input: &Ite
.bind(input.quantity.map(|q| q.unit.as_str()))
.bind(input.icon.as_str())
.bind(input.category.as_str())
.fetch_one(pool)
.fetch_one(&mut *conn)
.await?;
record_in_catalog(pool, user_id, input).await?;
record_in_catalog(conn, user_id, input).await?;
row.try_get("id")
}
pub async fn update_item(pool: &SqlitePool, id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
async fn update_item(conn: &mut SqliteConnection, id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
sqlx::query(
"UPDATE items SET name = ?, amount = ?, unit = ?, icon = ?, category = ? WHERE id = ?",
)
@@ -396,25 +396,49 @@ pub async fn update_item(pool: &SqlitePool, id: i64, input: &ItemInput) -> Resul
.bind(input.icon.as_str())
.bind(input.category.as_str())
.bind(id)
.execute(pool)
.execute(conn)
.await?;
Ok(())
}
pub async fn delete_item(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM items WHERE id = ?").bind(id).execute(pool).await?;
async fn delete_item(conn: &mut SqliteConnection, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM items WHERE id = ?").bind(id).execute(conn).await?;
Ok(())
}
pub async fn set_checked(pool: &SqlitePool, id: i64, checked: bool) -> Result<(), sqlx::Error> {
async fn set_checked(conn: &mut SqliteConnection, id: i64, checked: bool) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE items SET checked = ? WHERE id = ?")
.bind(checked)
.bind(id)
.execute(pool)
.execute(conn)
.await?;
Ok(())
}
/// Applies the changes, in order, in one transaction. Ops may target items
/// added earlier in the batch by their temporary id; returns the
/// (temporary id, real id) of each added item.
pub async fn apply_item_ops(pool: &SqlitePool, user_id: i64, ops: &[ItemOp]) -> Result<Vec<(i64, i64)>, sqlx::Error> {
let mut tx = pool.begin().await?;
let mut created: Vec<(i64, i64)> = Vec::new();
for op in ops {
let id = created
.iter()
.find(|&&(temp, _)| temp == op.id())
.map_or(op.id(), |&(_, real)| real);
match op {
ItemOp::Add { id: temp, list_id, input } => {
created.push((*temp, add_item(&mut tx, user_id, *list_id, input).await?));
}
ItemOp::Update { input, .. } => update_item(&mut tx, id, input).await?,
ItemOp::Delete { .. } => delete_item(&mut tx, id).await?,
ItemOp::SetChecked { checked, .. } => set_checked(&mut tx, id, *checked).await?,
}
}
tx.commit().await?;
Ok(created)
}
/// The user's most used products not already on the list.
pub async fn suggestions(pool: &SqlitePool, user_id: i64, list_id: i64, limit: i64) -> Result<Vec<Suggestion>, sqlx::Error> {
sqlx::query(
@@ -449,6 +473,11 @@ mod tests {
connect("sqlite::memory:").await.unwrap()
}
/// The in-memory pool has a single connection: drop it before using the pool.
async fn conn(pool: &SqlitePool) -> sqlx::pool::PoolConnection<sqlx::Sqlite> {
pool.acquire().await.unwrap()
}
async fn user(pool: &SqlitePool, email: &str) -> i64 {
register(pool, email, "Test", "hash").await.unwrap()
}
@@ -517,28 +546,53 @@ mod tests {
let me = user(&pool, "a@x.fr").await;
let list = lists(&pool, me).await.unwrap()[0].id;
let id = add_item(&pool, me, list, &input("Avocats")).await.unwrap();
let id = add_item(&mut *conn(&pool).await, me, list, &input("Avocats")).await.unwrap();
assert_eq!(item_list_id(&pool, id).await.unwrap(), Some(list));
let mut edited = input("Avocats");
edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece });
update_item(&pool, id, &edited).await.unwrap();
set_checked(&pool, id, true).await.unwrap();
update_item(&mut *conn(&pool).await, id, &edited).await.unwrap();
set_checked(&mut *conn(&pool).await, id, true).await.unwrap();
let all = items(&pool, list).await.unwrap();
assert_eq!(all.len(), 1);
assert_eq!(all[0].quantity.unwrap().label(), "×4");
assert!(all[0].checked);
delete_item(&pool, id).await.unwrap();
delete_item(&mut *conn(&pool).await, id).await.unwrap();
assert!(items(&pool, list).await.unwrap().is_empty());
}
#[tokio::test]
async fn batch_resolves_temporary_ids() {
let pool = pool().await;
let me = user(&pool, "a@x.fr").await;
let list = lists(&pool, me).await.unwrap()[0].id;
let mut edited = input("Pommes");
edited.quantity = None;
let ops = [
ItemOp::Add { id: -1, list_id: list, input: input("Pommes") },
ItemOp::Add { id: -2, list_id: list, input: input("Poires") },
ItemOp::Update { id: -1, input: edited },
ItemOp::SetChecked { id: -1, checked: true },
ItemOp::Delete { id: -2 },
];
let created = apply_item_ops(&pool, me, &ops).await.unwrap();
assert_eq!(created.len(), 2);
let all = items(&pool, list).await.unwrap();
assert_eq!(all.len(), 1);
assert_eq!(all[0].id, created[0].1);
assert_eq!(all[0].quantity, None);
assert!(all[0].checked);
}
#[tokio::test]
async fn suggestions_skip_items_on_list() {
let pool = pool().await;
let me = user(&pool, "a@x.fr").await;
let list = lists(&pool, me).await.unwrap()[0].id;
add_item(&pool, me, list, &input("beurre")).await.unwrap();
add_item(&mut *conn(&pool).await, me, list, &input("beurre")).await.unwrap();
let names: Vec<_> = suggestions(&pool, me, list, 3)
.await
@@ -555,7 +609,7 @@ mod tests {
let pool = pool().await;
let me = user(&pool, "a@x.fr").await;
let list = create_list(&pool, me, "Apéro", ListColor::Pink).await.unwrap();
add_item(&pool, me, list, &input("Chips")).await.unwrap();
add_item(&mut *conn(&pool).await, me, list, &input("Chips")).await.unwrap();
delete_list(&pool, list).await.unwrap();
assert!(items(&pool, list).await.unwrap().is_empty());
}