CREATE OR REPLACE FUNCTION check_material_availability()
RETURNS TRIGGER AS
$$
DECLARE
required_materials RECORD;
available_quantity INTEGER;
BEGIN
FOR required_materials IN
SELECT item_id, count
FROM service_types_needed_items
WHERE service_type_id = NEW.service_type_id
LOOP
SELECT quantity
INTO available_quantity
FROM storage_items si
JOIN storage s ON s.outlet_id = (SELECT accept_outlet_id FROM orders WHERE id = NEW.order_id)
WHERE item_id = required_materials.item_id
AND storage_id = s.id;
IF available_quantity IS NULL THEN
available_quantity := 0;
END IF;
IF available_quantity < required_materials.count THEN
RAISE EXCEPTION 'Not enough materials available on the storage for this service order. Item ID: %, Required Count: %, Available Count: %', required_materials.item_id, required_materials.count, available_quantity;
ELSE
RAISE NOTICE 'Material available on the storage for this service order. Item ID: %, Required Count: %, Available Count: %', required_materials.item_id, required_materials.count, available_quantity;
UPDATE storage_items
SET quantity = quantity - required_materials.count
FROM storage_items
JOIN storage s ON storage_items.storage_id = s.id
JOIN service_types_needed_items m ON storage_items.item_id = m.item_id
WHERE storage_id = s.id
AND item_id = required_materials.item_id;
END IF;
END LOOP;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER check_material_availability_trigger
BEFORE INSERT
ON service_orders
FOR EACH ROW
EXECUTE FUNCTION check_material_availability();