-- SET search_path TO adempiere;
-- SELECT * FROM fnt_get_past_period(1000020);
-- SELECT * FROM fnt_get_past_period(1000019);
-- SELECT * FROM fnt_get_past_period(1000012);
CREATE OR REPLACE FUNCTION fnt_get_past_period(p_period_id NUMERIC(10,0))
RETURNS NUMERIC(10,0)
AS $$
DECLARE
v_past_year NUMERIC(10,0) = EXTRACT(YEAR FROM NOW());
v_actual_year NUMERIC(10,0) = EXTRACT(YEAR FROM NOW());
v_next_year NUMERIC(10,0) = EXTRACT(YEAR FROM NOW());
v_period_num NUMERIC(10,0) = 0;
v_past_period NUMERIC(10,0) = 0;
BEGIN
SELECT
(y.fiscalyear::int - 1)::NUMERIC(10,0) AS past_year,
y.fiscalyear::NUMERIC(10,0) AS actual_year,
(y.fiscalyear::int + 1)::NUMERIC(10,0) AS next_year,
p.periodno AS period_num
INTO
v_past_year,
v_actual_year,
v_next_year,
v_period_num
FROM c_period AS p
JOIN c_year AS y
ON p.c_year_id = y.c_year_id
WHERE p.ad_client_id = 1000000
AND p.periodtype = 'S'
AND p.c_period_id = p_period_id;
v_past_period =
(
SELECT
COALESCE((
SELECT
p.c_period_id
FROM c_period p
JOIN c_year y
ON p.c_year_id = y.c_year_id
WHERE p.ad_client_id = 1000000
AND y.fiscalyear::NUMERIC(10,0) = v_actual_year
AND p.periodtype = 'S'
AND p.periodno = (v_period_num - 1)
),
COALESCE((
SELECT
p.c_period_id
FROM c_period p
JOIN c_year y
ON p.c_year_id = y.c_year_id
WHERE p.ad_client_id = 1000000
AND y.fiscalyear::NUMERIC(10,0) = v_past_year
AND p.periodtype = 'S'
AND p.periodno =
(
SELECT
MAX(pp.periodno)
FROM c_period pp
JOIN c_year yy
ON pp.c_year_id = yy.c_year_id
WHERE pp.ad_client_id = 1000000
AND yy.fiscalyear::NUMERIC(10,0) = v_past_year
AND pp.periodtype = 'S'
)
), 0)
)
);
RETURN v_past_period;
END;
$$ LANGUAGE plpgsql;
No hay comentarios:
Publicar un comentario