DROP FUNCTION IF EXISTS sp_undoschetspreading;

DROP PROCEDURE IF EXISTS sp_undoschetspreading;

CREATE OR REPLACE PROCEDURE sp_undoschetspreading("Schet" uuid)
    LANGUAGE plpgsql
AS
$$
DECLARE
    _pack uuid;
BEGIN
    SELECT p.schetpackid
    INTO _pack
    FROM akuz.t_schet_pack p
    WHERE p.schet = "Schet"
      AND p.smo IS NULL;
    
    IF _pack IS NOT NULL
    THEN
        UPDATE akuz.t_schet_zap
        SET schetpack = _pack
        WHERE schet = "Schet"
          AND schetpack <> _pack;
        
        DELETE FROM akuz.t_schet_pack sp WHERE sp.schet = "Schet" AND sp.schetpackid <> _pack;
        
        WITH sumss
                 AS
                 (SELECT SUM(sl.sumv) AS sumv, SUM(sl.sump) AS sump, SUM(sl.sank_mek) AS sank_mek, _pack AS schetpack
                  FROM akuz.t_schet_sluch sl
                  INNER JOIN
                  akuz.t_schet_zap sz
                      ON sl.schetzap = sz.schetzapid
                  WHERE sz.schetpack = _pack
                 )
        UPDATE akuz.t_schet_pack pack
        SET summav   = sumss.sumv,
            summap   = sumss.sump,
            sank_mek = sumss.sank_mek
        FROM sumss
        WHERE sumss.schetpack = pack.schetpackid
          AND pack.schetpackid = _pack;
    END IF;
END;
$$;
