Files
Online-Topup-V1/enhancement get postign et when posting invoice online topup.sql
2026-05-08 13:55:30 +07:00

143 lines
2.8 KiB
SQL

-- =========================================================
-- RECOMMENDED INDEXES FOR PRODUCTION
-- =========================================================
-- Main filtering index
CREATE INDEX IF NOT EXISTS idx_posting_et_main_filter
ON public.posting_et (
tcode,
pos_status,
fiscal_year
);
-- Prefix LIKE 'INV%'
CREATE INDEX IF NOT EXISTS idx_posting_et_doc_header
ON public.posting_et (doc_header_text);
-- Join & aggregation optimization
CREATE INDEX IF NOT EXISTS idx_posting_et_reference_debit
ON public.posting_et (
reference,
debit_kredit
);
-- Optional covering index for large tables
CREATE INDEX IF NOT EXISTS idx_posting_et_covering
ON public.posting_et (
tcode,
pos_status,
fiscal_year,
reference
);
-- =========================================================
-- PRODUCTION QUERY
-- =========================================================
WITH params AS (
SELECT
EXTRACT(YEAR FROM CURRENT_DATE)::TEXT AS curr_year,
EXTRACT(YEAR FROM CURRENT_DATE - INTERVAL '1 year')::TEXT AS prev_year,
TO_CHAR(CURRENT_DATE, 'MM') AS curr_month
),
base AS (
SELECT
pe.doc_header_text,
pe.ba,
pe.doc_date,
pe.posting_date,
pe.fiscal_year,
TO_CHAR(pe.doc_date::DATE, 'MM') AS fis_period,
pe.doc_type,
pe.reference,
pe.tcode,
pe.amount,
pe.customer,
pe.account,
pe.text,
pe.debit_kredit
FROM public.posting_et pe
CROSS JOIN params p
WHERE
pe.tcode = 'FB70'
AND pe.pos_status = '3'
-- Prefix search still index friendly
AND pe.doc_header_text LIKE 'INV%'
AND (
-- Current year all months
pe.fiscal_year = p.curr_year
OR (
-- Previous year December only
-- only when current month is January
p.curr_month = '01'
AND pe.fiscal_year = p.prev_year
AND TO_CHAR(pe.doc_date::DATE, 'MM') = '12'
)
)
)
SELECT
b.doc_header_text,
b.ba,
b.doc_date,
b.posting_date,
b.fiscal_year,
b.fis_period,
b.doc_type,
b.reference,
b.tcode,
b.amount,
'IDR'::VARCHAR AS currency,
MAX(b.customer) FILTER (
WHERE b.debit_kredit = 'S'
) AS customer,
MAX(b.account) FILTER (
WHERE b.debit_kredit = 'H'
) AS account,
MAX(b.text) FILTER (
WHERE b.debit_kredit = 'S'
) AS text1,
MAX(b.text) FILTER (
WHERE b.debit_kredit = 'H'
) AS text2
FROM base b
GROUP BY
b.doc_header_text,
b.ba,
b.doc_date,
b.posting_date,
b.fiscal_year,
b.fis_period,
b.doc_type,
b.reference,
b.tcode,
b.amount
ORDER BY
b.fiscal_year,
b.doc_date,
b.reference;