supersam/supabase/migrations/20260908_autocall_exclusion...

43 lines
2.4 KiB
SQL

-- ============================================================
-- SuperSam: Автодозвон — исключения в view реестра (Фаза 8b)
-- 08.09.2026. Аддитивная. Дополняет order_group_comms_flags полями
-- autocall_excluded / autocall_exclusion_reason, чтобы фронт показывал
-- бейдж «не звоним (исключение)» без отдельного запроса.
-- ============================================================
drop view if exists public.order_group_comms_flags;
create view public.order_group_comms_flags as
select
og.id,
og.autocall_opt_out,
og.delivery_date_source,
og.notification_status,
og.delivery_status,
og.customer_phone_normalized,
(select l.outcome from public.autocall_log l where l.order_group_id = og.id order by l.created_at desc limit 1) as last_call_outcome,
(select l.changed from public.autocall_log l where l.order_group_id = og.id order by l.created_at desc limit 1) as last_call_changed,
(select l.created_at from public.autocall_log l where l.order_group_id = og.id order by l.created_at desc limit 1) as last_call_at,
(select count(*) from public.autocall_log l where l.order_group_id = og.id) as call_attempts,
(select count(*) from public.autocall_log l where l.order_group_id = og.id
and l.outcome in ('no_input_day','no_input_half')) as no_input_count,
-- Исключение автодозвона (префикс/номер)
(select e.reason from public.autocall_exclusions e
where e.active
and (
(e.rule_type = 'phone' and coalesce(og.customer_phone_normalized, regexp_replace(coalesce(og.customer_phone,''),'\D','','g')) = e.value)
or
(e.rule_type = 'prefix' and coalesce(og.customer_phone_normalized, regexp_replace(coalesce(og.customer_phone,''),'\D','','g')) like e.value || '%')
)
limit 1) as autocall_exclusion_reason,
(select e.value from public.autocall_exclusions e
where e.active
and (
(e.rule_type = 'phone' and coalesce(og.customer_phone_normalized, regexp_replace(coalesce(og.customer_phone,''),'\D','','g')) = e.value)
or
(e.rule_type = 'prefix' and coalesce(og.customer_phone_normalized, regexp_replace(coalesce(og.customer_phone,''),'\D','','g')) like e.value || '%')
)
limit 1) as autocall_exclusion_value
from public.order_groups og;
grant select on public.order_group_comms_flags to authenticated;