begin; create index if not exists payment_orders_created_status_idx on public.payment_orders(created_at desc, status); create or replace function public.get_payment_order_stats(p_from timestamptz default null, p_to timestamptz default null) returns table (total_orders bigint, paid_orders bigint, pending_orders bigint, failed_expired_orders bigint, paid_amount_cents bigint, granted_credits bigint) language sql security definer set search_path = public, pg_temp as $$ select count(*)::bigint, count(*) filter (where status = 'paid')::bigint, count(*) filter (where status = 'pending')::bigint, count(*) filter (where status in ('failed', 'expired'))::bigint, coalesce(sum(money_cents) filter (where status = 'paid'), 0)::bigint, coalesce(sum(credits) filter (where status = 'paid'), 0)::bigint from public.payment_orders where (p_from is null or created_at >= p_from) and (p_to is null or created_at <= p_to); $$; revoke all on function public.get_payment_order_stats(timestamptz, timestamptz) from public, anon, authenticated; grant execute on function public.get_payment_order_stats(timestamptz, timestamptz) to service_role; commit;