CREATE DEFINER = CURRENT_USER TRIGGER `powerpme`.`stock_detail_AFTER_INSERT` AFTER INSERT ON `stock_detail` FOR EACH ROW
BEGIN
	DECLARE NewQuantite FLOAT ;
    
    SELECT sum(quantite) 
    INTO NewQuantite
    FROM powerpme.stock_detail  WHERE (reference_produit LIKE new.reference_produit) AND (local_nom LIKE new.local_nom);
    
    IF NewQuantite = 0
    THEN
		DELETE FROM powerpme.stock 
        WHERE (local_nom LIKE new.local_nom) AND  (produit_reference LIKE new.reference_produit);
	ELSE
		INSERT INTO powerpme.stock (local_nom, produit_reference, quantite) 
        VALUES(new.local_nom, new.reference_produit, NewQuantite) 
        ON DUPLICATE KEY UPDATE   quantite=NewQuantite;
    END IF ;
    
END







/* Workbeanch */

DROP TRIGGER IF EXISTS `powerpme`.`stock_detail_AFTER_INSERT`;

DELIMITER $$
USE `powerpme`$$
CREATE DEFINER = CURRENT_USER TRIGGER `powerpme`.`stock_detail_AFTER_INSERT` AFTER INSERT ON `stock_detail` FOR EACH ROW
BEGIN
	DECLARE NewQuantite FLOAT ;
    
    SELECT sum(quantite) 
    INTO NewQuantite
    FROM powerpme.stock_detail  WHERE (reference_produit LIKE new.reference_produit) AND (local_nom LIKE new.local_nom);
    
    IF NewQuantite = 0
    THEN
		DELETE FROM powerpme.stock 
        WHERE (local_nom LIKE new.local_nom) AND  (produit_reference LIKE new.reference_produit);
	ELSE
		INSERT INTO powerpme.stock (local_nom, produit_reference, quantite) 
        VALUES(new.local_nom, new.reference_produit, NewQuantite) 
        ON DUPLICATE KEY UPDATE   quantite=NewQuantite;
    END IF ;
    
END$$
DELIMITER ;
