From 4aba711f6d4ee521d4329af15c8e8a71d456c05f Mon Sep 17 00:00:00 2001 From: Tiago Amorim Date: Thu, 30 May 2024 00:25:56 +0100 Subject: [PATCH] deleting newly inserted shipment if its not populated --- src/db_api/shipments.rs | 21 +++++++++++++++++++++ src/scheduler/resource_planning.rs | 23 ++++++++++++++--------- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/src/db_api/shipments.rs b/src/db_api/shipments.rs index 3cdef07..28f845d 100644 --- a/src/db_api/shipments.rs +++ b/src/db_api/shipments.rs @@ -182,6 +182,27 @@ impl MaterialShipment { Ok(()) } + pub async fn count_by_shipment_id( + id: i64, + con: &mut PgConnection, + ) -> sqlx::Result { + let count = sqlx::query_scalar!( + r#" + SELECT COUNT(*) + FROM raw_material_shipments + WHERE shipment_id = $1 + "#, + id + ) + .fetch_one(con) + .await?; + + match count { + Some(count) => Ok(count), + None => Ok(0), + } + } + pub fn raw_material_id(&self) -> Uuid { self.raw_material_id } diff --git a/src/scheduler/resource_planning.rs b/src/scheduler/resource_planning.rs index 11b5e1c..f2f7ace 100644 --- a/src/scheduler/resource_planning.rs +++ b/src/scheduler/resource_planning.rs @@ -52,7 +52,7 @@ async fn resolve_day_needs( // 5. Insert new shipments into de dabase to get their IDs // 6. Link remaining pending items to new purchase orders - if let Some(shipment) = pr.purchase_order { + let ship_id = if let Some(shipment) = pr.purchase_order { let id = shipment.insert(&mut tx).await?; let items_to_insert = pending @@ -68,14 +68,10 @@ async fn resolve_day_needs( .any(|i| i.raw_material_id() == p.item_id) }); material_shipments.extend(items_to_insert); - - if material_shipments.is_empty() { - tracing::info!("No material shipments to insert"); - Shipment::delete(id, &mut tx).await?; - tx.commit().await?; - return Ok(()); - } - } + Some(id) + } else { + None + }; // 7. Insert the new populate the material shipments join table // with the new tuples @@ -83,6 +79,15 @@ async fn resolve_day_needs( ms.insert(&mut tx).await?; } + // 8. Check if the new shipment has items allocated to it else delete it + if let Some(id) = ship_id { + let count = MaterialShipment::count_by_shipment_id(id, &mut tx).await?; + if count == 0 { + Shipment::delete(id, &mut tx).await?; + tracing::warn!("Deleted shipment with id: {}", id); + } + } + tx.commit().await?; Ok(())