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

Commit

Permalink
moved item status update upon shipment arrival to database trigger fu…
Browse files Browse the repository at this point in the history
…nction
  • Loading branch information
dvalnn committed May 12, 2024
1 parent af52685 commit 85827e5
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 46 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

This file was deleted.

35 changes: 35 additions & 0 deletions migrations/012_shipments.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,38 @@ CREATE TABLE IF NOT EXISTS shipments (
quantity int NOT NULL,
cost money NOT NULL
);

CREATE FUNCTION shipment_arrived() RETURNS TRIGGER AS $$
BEGIN
WITH item_prices AS (
SELECT unit_price
FROM suppliers
JOIN shipments AS sh
ON sh.supplier_id = suppliers.id WHERE sh.id = NEW.id
)
UPDATE
items
SET
status = 'in_stock',
warehouse = 'W1',
acc_cost = (SELECT unit_price FROM item_prices)
WHERE id IN
(
SELECT items.id
FROM items
JOIN raw_material_shipments AS rs
ON rs.raw_material_id = items.id
JOIN shipments AS s
ON rs.shipment_id = s.id
WHERE s.id = NEW.id
);

RAISE NOTICE 'Shipment % arrived', NEW.id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER shipment_arrived_trigger
AFTER UPDATE OF arrival_date ON shipments
FOR EACH ROW
EXECUTE FUNCTION shipment_arrived();
31 changes: 1 addition & 30 deletions src/db_api/shipments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,36 +43,6 @@ impl Shipment {
}

pub async fn arrived(id: i64, date: i32, con: &PgPool) -> sqlx::Result<()> {
sqlx::query!(
r#"
WITH item_prices AS (
SELECT unit_price
FROM suppliers
JOIN shipments AS sh
ON sh.supplier_id = suppliers.id WHERE sh.id = $1
)
UPDATE
items
SET
status = 'in_stock',
warehouse = 'W1',
acc_cost = (SELECT unit_price FROM item_prices)
WHERE id IN
(
SELECT items.id
FROM items
JOIN raw_material_shipments AS rs
ON rs.raw_material_id = items.id
JOIN shipments AS s
ON rs.shipment_id = s.id
WHERE s.id = $1
)
"#,
id,
)
.execute(con)
.await?;

sqlx::query!(
r#"
UPDATE shipments
Expand Down Expand Up @@ -102,6 +72,7 @@ impl Shipment {
FROM shipments AS ship
JOIN suppliers AS sup ON ship.supplier_id = sup.id
WHERE request_date + delivery_time = $1
AND arrival_date IS NULL
"#,
date
)
Expand Down

0 comments on commit 85827e5

Please sign in to comment.