From 6c593b0201d08c3df20a7da3f1693582b4c18c64 Mon Sep 17 00:00:00 2001 From: Romulus21 Date: Fri, 16 Oct 2026 08:47:25 +0200 Subject: [PATCH] =?UTF-8?q?Enregistre=20les=20changements=20d'articles=20p?= =?UTF-8?q?ar=20lots=20en=20arri=C3=A8re-plan?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/api.rs | 121 ++++++++++------- src/app/mod.rs | 105 +++++++-------- src/app/sheets.rs | 14 +- src/app/sync.rs | 323 ++++++++++++++++++++++++++++++++++++++++++++++ src/app/tiles.rs | 4 +- src/db.rs | 90 ++++++++++--- src/model.rs | 34 +++++ 7 files changed, 565 insertions(+), 126 deletions(-) create mode 100644 src/app/sync.rs diff --git a/src/api.rs b/src/api.rs index f775fb4..cf7affb 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,7 +1,7 @@ use leptos::prelude::*; use leptos::server_fn::codec::Json; -use crate::model::{Account, Item, ItemInput, ListColor, Member, ShoppingList, Suggestion, User}; +use crate::model::{Account, Item, ItemOp, ListColor, Member, ShoppingList, Suggestion, SyncReport, User}; pub const NOT_LOGGED_IN: &str = "Session expirée, reconnecte-toi."; @@ -62,16 +62,6 @@ mod server { } } - /// Fails unless the item belongs to a list the user can access; returns that list. - pub async fn require_item(pool: &SqlitePool, user: &User, item_id: i64) -> Result { - let list_id = crate::db::item_list_id(pool, item_id) - .await - .map_err(db_err)? - .ok_or_else(|| ServerFnError::new("Article introuvable."))?; - require_list(pool, user, list_id).await?; - Ok(list_id) - } - /// Everyone who can see the list, to pass to [`notify`] once it changed. pub async fn audience(pool: &SqlitePool, list_id: i64) -> Result, ServerFnError> { crate::db::list_audience(pool, list_id).await.map_err(db_err) @@ -90,6 +80,13 @@ mod server { Ok(()) } + pub fn message(err: ServerFnError) -> String { + match err { + ServerFnError::ServerError(msg) => msg, + err => err.to_string(), + } + } + pub fn clean_name(name: &str, max: usize) -> Result { let name = name.trim(); if name.is_empty() || name.chars().count() > max { @@ -379,47 +376,81 @@ pub async fn get_items(list_id: i64) -> Result, ServerFnError> { crate::db::items(&pool, list_id).await.map_err(db_err) } +/// Applies a batch of item changes queued by the browser. Changes to items +/// deleted meanwhile are dropped; invalid ones are skipped and reported. #[server(input = Json)] -pub async fn add_item(list_id: i64, input: ItemInput) -> Result { +pub async fn sync_items(ops: Vec) -> Result { + use crate::model::ItemInput; use server::*; let pool = pool()?; let user = require_user(&pool).await?; - require_list(&pool, &user, list_id).await?; - let input = ItemInput { name: clean_name(&input.name, 60)?, ..input }; - let id = crate::db::add_item(&pool, user.id, list_id, &input).await.map_err(db_err)?; - notify_list(&pool, list_id).await?; - Ok(id) -} -#[server(input = Json)] -pub async fn update_item(id: i64, input: ItemInput) -> Result<(), ServerFnError> { - use server::*; - let pool = pool()?; - let user = require_user(&pool).await?; - let list_id = require_item(&pool, &user, id).await?; - let input = ItemInput { name: clean_name(&input.name, 60)?, ..input }; - crate::db::update_item(&pool, id, &input).await.map_err(db_err)?; - notify_list(&pool, list_id).await -} + // Lists checked so far, and whether the user can access them. + let mut access: Vec<(i64, bool)> = Vec::new(); + // Temporary ids added in this batch, with their list. + let mut added: Vec<(i64, i64)> = Vec::new(); + let mut accepted = Vec::with_capacity(ops.len()); + let mut rejected = None; + for op in ops { + let list_id = match &op { + ItemOp::Add { id, list_id, .. } if *id < 0 => Some(*list_id), + ItemOp::Add { .. } => None, + op if op.id() < 0 => added.iter().find(|&&(temp, _)| temp == op.id()).map(|&(_, list)| list), + op => crate::db::item_list_id(&pool, op.id()).await.map_err(db_err)?, + }; + let Some(list_id) = list_id else { continue }; + let allowed = match access.iter().find(|&&(list, _)| list == list_id) { + Some(&(_, allowed)) => allowed, + None => { + let allowed = crate::db::list_role(&pool, user.id, list_id).await.map_err(db_err)?.is_some(); + access.push((list_id, allowed)); + allowed + } + }; + if !allowed { + if matches!(op, ItemOp::Add { .. }) { + rejected.get_or_insert_with(|| "Liste introuvable.".to_owned()); + } + continue; + } -#[server] -pub async fn delete_item(id: i64) -> Result<(), ServerFnError> { - use server::*; - let pool = pool()?; - let user = require_user(&pool).await?; - let list_id = require_item(&pool, &user, id).await?; - crate::db::delete_item(&pool, id).await.map_err(db_err)?; - notify_list(&pool, list_id).await -} + let op = match op { + ItemOp::Add { id, list_id, input } => match clean_name(&input.name, 60) { + Ok(name) => ItemOp::Add { id, list_id, input: ItemInput { name, ..input } }, + Err(err) => { + rejected.get_or_insert(message(err)); + continue; + } + }, + ItemOp::Update { id, input } => match clean_name(&input.name, 60) { + Ok(name) => ItemOp::Update { id, input: ItemInput { name, ..input } }, + Err(err) => { + rejected.get_or_insert(message(err)); + continue; + } + }, + op => op, + }; + if let ItemOp::Add { id, list_id, .. } = op { + added.push((id, list_id)); + } + accepted.push(op); + } -#[server] -pub async fn set_checked(id: i64, checked: bool) -> Result<(), ServerFnError> { - use server::*; - let pool = pool()?; - let user = require_user(&pool).await?; - let list_id = require_item(&pool, &user, id).await?; - crate::db::set_checked(&pool, id, checked).await.map_err(db_err)?; - notify_list(&pool, list_id).await + if accepted.is_empty() { + return Ok(SyncReport { created: Vec::new(), rejected }); + } + let created = crate::db::apply_item_ops(&pool, user.id, &accepted).await.map_err(db_err)?; + let mut users = Vec::new(); + for &(list_id, allowed) in &access { + if allowed { + users.extend(audience(&pool, list_id).await?); + } + } + users.sort_unstable(); + users.dedup(); + notify(users); + Ok(SyncReport { created, rejected }) } #[server] diff --git a/src/app/mod.rs b/src/app/mod.rs index 4051932..fcdcb24 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -3,9 +3,9 @@ mod admin; mod icons; mod live; mod sheets; +mod sync; mod tiles; -use std::collections::HashMap; use std::future::Future; use leptos::prelude::*; @@ -16,10 +16,11 @@ use leptos_router::hooks::use_params_map; use leptos_router::path; use crate::api::{get_items, get_lists, get_suggestions}; -use crate::model::{Item, ShoppingList, Suggestion, User}; +use crate::model::{Item, ItemOp, ShoppingList, Suggestion, User}; use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser}; use admin::AdminPage; use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet}; +use sync::Sync; use tiles::{BasketTile, ItemTile, SuggestionTile}; pub fn shell(options: LeptosOptions) -> impl IntoView { @@ -86,9 +87,8 @@ pub struct Ctx { /// Bumped after every mutation so resources refetch. refresh: RwSignal, error: RwSignal>, - /// Checked state applied before fresh data shows it, with the number of - /// calls still in flight for that item. - optimistic: RwSignal>, + /// Item changes waiting to be saved. + sync: Sync, item_editor: RwSignal>, list_editor: RwSignal>, account_open: RwSignal, @@ -123,27 +123,13 @@ impl Ctx { self.error.set(Some(msg)); } + /// Shows the item change at once and saves it in the background. + fn change(self, op: ItemOp) { + self.sync.push(self, op); + } + fn toggle(self, item: &Item) { - let (id, checked) = (item.id, !item.checked); - self.optimistic.update(|map| { - let in_flight = map.get(&id).map_or(0, |&(_, n)| n); - map.insert(id, (checked, in_flight + 1)); - }); - spawn_local(async move { - match crate::api::set_checked(id, checked).await { - Ok(()) => self.optimistic.update_untracked(|map| { - if let Some((_, in_flight)) = map.get_mut(&id) { - *in_flight -= 1; - } - }), - Err(err) => { - self.optimistic.update(|map| { - map.remove(&id); - }); - self.report(err); - } - } - }); + self.change(ItemOp::SetChecked { id: item.id, checked: !item.checked }); } } @@ -164,7 +150,7 @@ fn ListsView(user: User) -> impl IntoView { let ctx = Ctx { refresh: RwSignal::new(0), error: RwSignal::new(None), - optimistic: RwSignal::new(HashMap::new()), + sync: Sync::new(), item_editor: RwSignal::new(None), list_editor: RwSignal::new(None), account_open: RwSignal::new(false), @@ -173,6 +159,7 @@ fn ListsView(user: User) -> impl IntoView { }; provide_context(ctx); live::subscribe(ctx.refresh); + ctx.sync.flush_on_hide(ctx); let params = use_params_map(); let active_id = Memo::new(move |_| { @@ -185,10 +172,14 @@ fn ListsView(user: User) -> impl IntoView { let lists = Resource::new(move || ctx.refresh.get(), |_| get_lists()); let items = Resource::new( move || (active_id.get(), ctx.refresh.get()), - |(id, _)| async move { - match id { - Some(id) => get_items(id).await, - None => Ok(Vec::new()), + move |(id, _)| { + // What the data will include, to drop the changes it shows. + let saved = ctx.sync.saved(); + async move { + match id { + Some(id) => get_items(id).await.map(|items| (items, saved)), + None => Ok((Vec::new(), saved)), + } } }, ); @@ -218,6 +209,11 @@ fn ListsView(user: User) -> impl IntoView { + +

+ "Réseau indisponible : tes changements partiront dès que possible." +

+
}> impl IntoView { }> {move || Suspend::new(async move { let lists = lists.await?; - let items = items.await?; + let (items, saved) = items.await?; let suggestions = suggestions.await?; Ok::<_, ServerFnError>(view! { - + }) })} @@ -252,6 +248,8 @@ fn ListsView(user: User) -> impl IntoView { fn ListsContent( lists: Vec, items: Vec, + /// Batches of changes saved when `items` was fetched. + saved: u32, suggestions: Vec, active_id: Option, ) -> impl IntoView { @@ -275,28 +273,26 @@ fn ListsContent( .into_any(); }; - // Fresh data includes every confirmed toggle: only keep pending ones, so - // changes made by others since are not masked. - ctx.optimistic - .update_untracked(|map| map.retain(|_, &mut (_, in_flight)| in_flight > 0)); + ctx.sync.settle(saved); - // Items with pending checkbox changes applied, by category then name. - let mut items = items; - items.sort_by_cached_key(Item::sort_key); + // Items with unsaved changes applied, by category then name. let items = StoredValue::new(items); let current = Memo::new(move |_| { - let optimistic = ctx.optimistic.get(); - items.with_value(|items| { - items - .iter() - .cloned() - .map(|mut item| { - if let Some(&(checked, _)) = optimistic.get(&item.id) { - item.checked = checked; - } - item - }) - .collect::>() + let mut items = items.with_value(|items| ctx.sync.apply(active_id, items)); + items.sort_by_cached_key(Item::sort_key); + items + }); + // Hides a suggestion as soon as it is added. + let suggestions = StoredValue::new(suggestions); + let suggestions = Memo::new(move |_| { + current.with(|items| { + suggestions.with_value(|suggestions| { + suggestions + .iter() + .filter(|s| !items.iter().any(|i| i.name.to_lowercase() == s.name.to_lowercase())) + .cloned() + .collect::>() + }) }) }); let to_get = Memo::new(move |_| { @@ -362,10 +358,9 @@ fn ListsContent( - {suggestions - .into_iter() - .map(|suggestion| view! { }) - .collect_view()} + + + diff --git a/src/app/sheets.rs b/src/app/sheets.rs index 59e4cf8..0efafb0 100644 --- a/src/app/sheets.rs +++ b/src/app/sheets.rs @@ -5,7 +5,7 @@ use leptos_router::hooks::use_navigate; use super::Ctx; use super::icons::{IconSvg, icon_label}; use crate::api::get_members; -use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Unit}; +use crate::model::{Category, Icon, Item, ItemInput, ItemOp, ListColor, Quantity, ShoppingList, Unit}; #[derive(Clone, Debug, PartialEq)] pub enum ItemEditor { @@ -86,14 +86,16 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView { icon: icon.get(), category: category.get(), }; - match item_id { - Some(id) => ctx.mutate(crate::api::update_item(id, input), move |_| close()), - None => ctx.mutate(crate::api::add_item(list_id, input), move |_| close()), - } + ctx.change(match item_id { + Some(id) => ItemOp::Update { id, input }, + None => ItemOp::Add { id: 0, list_id, input }, + }); + close(); }; let delete = move |_| { if let Some(id) = item_id { - ctx.mutate(crate::api::delete_item(id), move |_| close()); + ctx.change(ItemOp::Delete { id }); + close(); } }; diff --git a/src/app/sync.rs b/src/app/sync.rs new file mode 100644 index 0000000..b68e174 --- /dev/null +++ b/src/app/sync.rs @@ -0,0 +1,323 @@ +//! Item changes are shown at once and saved in the background: they wait in a +//! queue and leave in batches, one request at a time, so a slow mobile +//! connection never holds the interface back. + +use std::time::Duration; + +use leptos::ev; +use leptos::prelude::*; +use leptos::task::spawn_local; + +use super::Ctx; +use crate::model::{Item, ItemOp, SyncReport}; + +/// Changes made within this delay leave together. +const DEBOUNCE: Duration = Duration::from_millis(400); +const MAX_RETRY_DELAY: Duration = Duration::from_secs(30); + +#[derive(Clone, Copy)] +pub struct Sync(RwSignal); + +#[derive(Default)] +struct State { + /// Changes not sent yet. + queue: Vec, + /// Sent changes, shown until data fetched after they were saved has them. + sent: Vec, + /// Batches saved so far. + saved: u32, + /// Real ids of items added here, by temporary id. + ids: Vec<(i64, i64)>, + /// Last temporary id handed out. + last_temp: i64, + /// A flush is planned. + scheduled: bool, + /// A batch is on its way; the next one waits for its answer. + sending: bool, + /// Failed attempts since the last batch got through. + retries: u32, +} + +struct Batch { + ops: Vec, + /// Value of `saved` once this batch was saved. + saved_as: Option, +} + +enum Outcome { + Saved(SyncReport), + Refused(ServerFnError), + Retry(Duration), +} + +impl Sync { + pub fn new() -> Self { + Self(RwSignal::new(State::default())) + } + + /// Sends what is left when the page is hidden: the phone may freeze it next. + pub fn flush_on_hide(self, ctx: Ctx) { + let handle = window_event_listener(ev::visibilitychange, move |_| { + if document().hidden() { + self.flush(ctx); + } + }); + on_cleanup(move || handle.remove()); + } + + pub fn push(self, ctx: Ctx, op: ItemOp) { + let schedule = self.0.try_update(|state| { + state.push(op); + !std::mem::replace(&mut state.scheduled, true) + }); + if schedule == Some(true) { + set_timeout(move || self.flush(ctx), DEBOUNCE); + } + } + + /// Saved batches so far: data fetched from now on includes them. + pub fn saved(self) -> u32 { + self.0.try_with_untracked(|state| state.saved).unwrap_or_default() + } + + /// Forgets saved changes that data fetched when `saved` batches were + /// saved already shows, so changes made by others since are not masked. + pub fn settle(self, saved: u32) { + self.0.try_update_untracked(|state| { + state.sent.retain(|batch| batch.saved_as.is_none_or(|n| n > saved)); + }); + } + + /// The list's items with the changes not saved or not fetched yet. + pub fn apply(self, list_id: i64, items: &[Item]) -> Vec { + let mut items = items.to_vec(); + self.0.with(|state| { + let ops = state.sent.iter().flat_map(|batch| &batch.ops).chain(&state.queue); + for op in ops { + apply(&mut items, list_id, op); + } + }); + items + } + + /// The last attempt failed for lack of network; changes are kept. + pub fn offline(self) -> bool { + self.0.with(|state| state.retries > 0) + } + + fn flush(self, ctx: Ctx) { + let ops = self.0.try_update(|state| { + state.scheduled = false; + if state.sending || state.queue.is_empty() { + return None; + } + let ops = std::mem::take(&mut state.queue); + state.sent.push(Batch { ops: ops.clone(), saved_as: None }); + state.sending = true; + Some(ops) + }); + let Some(Some(ops)) = ops else { return }; + spawn_local(async move { + let result = crate::api::sync_items(ops).await; + self.answered(ctx, result); + }); + } + + fn answered(self, ctx: Ctx, result: Result) { + let outcome = self.0.try_update(|state| { + state.sending = false; + let mut batch = state.sent.pop().expect("the batch sent is the last one"); + match result { + Ok(report) => { + state.saved += 1; + batch.saved_as = Some(state.saved); + state.sent.push(batch); + state.resolve(&report.created); + state.retries = 0; + Outcome::Saved(report) + } + // Refused by the server: retrying would not help. + Err(err @ ServerFnError::ServerError(_)) => { + state.retries = 0; + Outcome::Refused(err) + } + // Not delivered, or the answer was lost: send it again later. + Err(_) => { + state.queue.splice(0..0, batch.ops); + state.retries += 1; + let delay = Duration::from_secs(1 << state.retries.min(5)).min(MAX_RETRY_DELAY); + Outcome::Retry(delay) + } + } + }); + match outcome { + None => {} + Some(Outcome::Saved(report)) => { + if let Some(msg) = report.rejected { + ctx.error.set(Some(msg)); + } + ctx.refresh.update(|n| *n += 1); + self.flush(ctx); + } + Some(Outcome::Refused(err)) => { + ctx.report(err); + ctx.refresh.update(|n| *n += 1); + self.flush(ctx); + } + Some(Outcome::Retry(delay)) => set_timeout(move || self.flush(ctx), delay), + } + } +} + +impl State { + /// Queues the change, merged with the queued ones for the same item. + fn push(&mut self, mut op: ItemOp) { + if let ItemOp::Add { id, .. } = &mut op { + self.last_temp -= 1; + *id = self.last_temp; + } else if let Some(&(_, real)) = self.ids.iter().find(|&&(temp, _)| temp == op.id()) { + // Still open in an editor from before the item was saved. + *op.id_mut() = real; + } + + let id = op.id(); + let queued_add = self.queue.iter().position(|q| matches!(q, ItemOp::Add { id: added, .. } if *added == id)); + match (op, queued_add) { + (ItemOp::Delete { .. }, Some(_)) => self.queue.retain(|q| q.id() != id), + (ItemOp::Update { input, .. }, Some(index)) => { + if let ItemOp::Add { input: added, .. } = &mut self.queue[index] { + *added = input; + } + } + (op @ ItemOp::Delete { .. }, None) => { + self.queue.retain(|q| q.id() != id); + self.queue.push(op); + } + (op @ (ItemOp::Update { .. } | ItemOp::SetChecked { .. }), _) => { + let same_kind = std::mem::discriminant(&op); + self.queue.retain(|q| q.id() != id || std::mem::discriminant(q) != same_kind); + self.queue.push(op); + } + (op, _) => self.queue.push(op), + } + } + + /// Swaps temporary ids for the ones the server gave. + fn resolve(&mut self, created: &[(i64, i64)]) { + let ops = self.queue.iter_mut().chain(self.sent.iter_mut().flat_map(|batch| &mut batch.ops)); + for op in ops { + if let Some(&(_, real)) = created.iter().find(|&&(temp, _)| temp == op.id()) { + *op.id_mut() = real; + } + } + self.ids.extend_from_slice(created); + } +} + +fn apply(items: &mut Vec, list_id: i64, op: &ItemOp) { + fn find(items: &mut [Item], id: i64) -> Option<&mut Item> { + items.iter_mut().find(|item| item.id == id) + } + match op { + ItemOp::Add { id, list_id: list, input } => { + if *list == list_id && !items.iter().any(|item| item.id == *id) { + items.push(Item { + id: *id, + list_id, + name: input.name.clone(), + quantity: input.quantity, + icon: input.icon, + category: input.category, + checked: false, + }); + } + } + ItemOp::Update { id, input } => { + if let Some(item) = find(items, *id) { + item.name = input.name.clone(); + item.quantity = input.quantity; + item.icon = input.icon; + item.category = input.category; + } + } + ItemOp::Delete { id } => items.retain(|item| item.id != *id), + ItemOp::SetChecked { id, checked } => { + if let Some(item) = find(items, *id) { + item.checked = *checked; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{Category, Icon, ItemInput}; + + fn input(name: &str) -> ItemInput { + ItemInput { name: name.into(), quantity: None, icon: Icon::Basket, category: Category::Autre } + } + + fn add(name: &str) -> ItemOp { + ItemOp::Add { id: 0, list_id: 1, input: input(name) } + } + + #[test] + fn merges_queued_changes() { + let mut state = State::default(); + state.push(ItemOp::SetChecked { id: 5, checked: true }); + state.push(ItemOp::SetChecked { id: 5, checked: false }); + state.push(add("Pain")); + state.push(ItemOp::Update { id: -1, input: input("Pain complet") }); + assert_eq!( + state.queue, + [ + ItemOp::SetChecked { id: 5, checked: false }, + ItemOp::Add { id: -1, list_id: 1, input: input("Pain complet") }, + ] + ); + + state.push(ItemOp::Delete { id: -1 }); + state.push(ItemOp::Delete { id: 5 }); + assert_eq!(state.queue, [ItemOp::Delete { id: 5 }]); + } + + #[test] + fn resolves_temporary_ids() { + let mut state = State::default(); + state.push(add("Pain")); + state.sent.push(Batch { ops: std::mem::take(&mut state.queue), saved_as: None }); + state.push(ItemOp::SetChecked { id: -1, checked: true }); + state.resolve(&[(-1, 42)]); + assert_eq!(state.queue, [ItemOp::SetChecked { id: 42, checked: true }]); + assert_eq!(state.sent[0].ops[0].id(), 42); + + // An editor opened on the temporary item. + state.push(ItemOp::Delete { id: -1 }); + assert_eq!(state.queue, [ItemOp::Delete { id: 42 }]); + } + + #[test] + fn applies_changes_to_fetched_items() { + let item = Item { + id: 7, + list_id: 1, + name: "Lait".into(), + quantity: None, + icon: Icon::Milk, + category: Category::Frais, + checked: false, + }; + let mut items = vec![item]; + apply(&mut items, 1, &ItemOp::SetChecked { id: 7, checked: true }); + apply(&mut items, 1, &ItemOp::Add { id: -1, list_id: 1, input: input("Pain") }); + apply(&mut items, 1, &ItemOp::Add { id: -2, list_id: 2, input: input("Ailleurs") }); + assert!(items[0].checked); + assert_eq!(items.len(), 2); + + // Already in the fetched data. + apply(&mut items, 1, &ItemOp::Add { id: 7, list_id: 1, input: input("Lait") }); + apply(&mut items, 1, &ItemOp::Delete { id: -1 }); + assert_eq!(items.len(), 1); + } +} diff --git a/src/app/tiles.rs b/src/app/tiles.rs index a26d7ec..912a186 100644 --- a/src/app/tiles.rs +++ b/src/app/tiles.rs @@ -3,7 +3,7 @@ use leptos::prelude::*; use super::icons::IconSvg; use super::{Ctx, ItemEditor}; -use crate::model::{Item, ItemInput, Suggestion}; +use crate::model::{Item, ItemInput, ItemOp, Suggestion}; const LONG_PRESS_MS: u64 = 450; @@ -88,7 +88,7 @@ pub fn SuggestionTile(suggestion: Suggestion, list_id: i64) -> impl IntoView { let add = move |_| { let input = ItemInput { name: name.clone(), quantity: None, icon, category }; - ctx.mutate(crate::api::add_item(list_id, input), |_| ()); + ctx.change(ItemOp::Add { id: 0, list_id, input }); }; view! { diff --git a/src/db.rs b/src/db.rs index 40d275e..1d87367 100644 --- a/src/db.rs +++ b/src/db.rs @@ -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 { @@ -352,7 +352,7 @@ pub async fn item_list_id(pool: &SqlitePool, item_id: i64) -> Result } /// 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 { +async fn add_item(conn: &mut SqliteConnection, user_id: i64, list_id: i64, input: &ItemInput) -> Result { 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, 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, 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 { + 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()); } diff --git a/src/model.rs b/src/model.rs index 089fc04..337f778 100644 --- a/src/model.rs +++ b/src/model.rs @@ -289,6 +289,40 @@ pub struct ItemInput { pub category: Category, } +/// A change to items, queued in the browser and sent to the server in batches. +/// Items added in the browser carry a negative temporary `id` until the +/// server gives them a real one. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum ItemOp { + Add { id: i64, list_id: i64, input: ItemInput }, + Update { id: i64, input: ItemInput }, + Delete { id: i64 }, + SetChecked { id: i64, checked: bool }, +} + +impl ItemOp { + pub fn id(&self) -> i64 { + match self { + ItemOp::Add { id, .. } | ItemOp::Update { id, .. } | ItemOp::Delete { id } | ItemOp::SetChecked { id, .. } => *id, + } + } + + pub fn id_mut(&mut self) -> &mut i64 { + match self { + ItemOp::Add { id, .. } | ItemOp::Update { id, .. } | ItemOp::Delete { id } | ItemOp::SetChecked { id, .. } => id, + } + } +} + +/// What the server did with a batch of [`ItemOp`]s. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct SyncReport { + /// (temporary id, real id) of each item added. + pub created: Vec<(i64, i64)>, + /// Why some changes were refused, if any; the others were applied. + pub rejected: Option, +} + #[cfg(test)] mod tests { use super::*;