Skip to content
This repository has been archived by the owner on Aug 3, 2024. It is now read-only.

Commit

Permalink
deleting newly inserted shipment if its not populated
Browse files Browse the repository at this point in the history
  • Loading branch information
dvalnn committed May 29, 2024
1 parent 95ce448 commit 4aba711
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
21 changes: 21 additions & 0 deletions src/db_api/shipments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,27 @@ impl MaterialShipment {
Ok(())
}

pub async fn count_by_shipment_id(
id: i64,
con: &mut PgConnection,
) -> sqlx::Result<i64> {
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
}
Expand Down
23 changes: 14 additions & 9 deletions src/scheduler/resource_planning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -68,21 +68,26 @@ 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
for ms in material_shipments {
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(())
Expand Down

0 comments on commit 4aba711

Please sign in to comment.