| 1 | CREATE OR REPLACE FUNCTION public.get_customer_primary_address_coverage(
|
|---|
| 2 | p_customer_id bigint
|
|---|
| 3 | )
|
|---|
| 4 | RETURNS TABLE
|
|---|
| 5 | (
|
|---|
| 6 | customer_id bigint,
|
|---|
| 7 | address_id bigint,
|
|---|
| 8 | full_address text,
|
|---|
| 9 | site_code text,
|
|---|
| 10 | tower_code text,
|
|---|
| 11 | sector_label text,
|
|---|
| 12 | technology_name text,
|
|---|
| 13 | signal_quality_score numeric,
|
|---|
| 14 | distance_to_site_m numeric
|
|---|
| 15 | )
|
|---|
| 16 | LANGUAGE sql
|
|---|
| 17 | STABLE
|
|---|
| 18 | AS $$
|
|---|
| 19 | SELECT
|
|---|
| 20 | c.customer_id,
|
|---|
| 21 | ca.address_id,
|
|---|
| 22 | concat_ws(', ', ca.street, ca.city, ca.country) AS full_address,
|
|---|
| 23 | ns.site_code,
|
|---|
| 24 | ct.tower_code,
|
|---|
| 25 | ts.sector_label,
|
|---|
| 26 | nt.technology_name,
|
|---|
| 27 | cz.signal_quality_score,
|
|---|
| 28 | round(
|
|---|
| 29 | ST_Distance(ca.location::geography, ns.location::geography)::numeric,
|
|---|
| 30 | 1
|
|---|
| 31 | ) AS distance_to_site_m
|
|---|
| 32 | FROM public.customers c
|
|---|
| 33 | JOIN public.customer_addresses ca
|
|---|
| 34 | ON ca.customer_id = c.customer_id
|
|---|
| 35 | AND ca.is_primary
|
|---|
| 36 | JOIN public.coverage_zones cz
|
|---|
| 37 | ON cz.coverage_area IS NOT NULL
|
|---|
| 38 | AND ca.location IS NOT NULL
|
|---|
| 39 | AND ST_Covers(cz.coverage_area, ca.location)
|
|---|
| 40 | JOIN public.tower_sectors ts ON ts.sector_id = cz.sector_id
|
|---|
| 41 | JOIN public.cell_towers ct ON ct.tower_id = ts.tower_id
|
|---|
| 42 | JOIN public.network_sites ns ON ns.site_id = ct.site_id
|
|---|
| 43 | JOIN public.network_technologies nt
|
|---|
| 44 | ON nt.technology_id = ts.technology_id
|
|---|
| 45 | WHERE c.customer_id = p_customer_id
|
|---|
| 46 | AND c.status = 'active'
|
|---|
| 47 | AND ns.status = 'active'
|
|---|
| 48 | AND ct.status = 'active'
|
|---|
| 49 | AND ts.status = 'active'
|
|---|
| 50 | ORDER BY cz.signal_quality_score DESC NULLS LAST,
|
|---|
| 51 | distance_to_site_m;
|
|---|
| 52 | $$;
|
|---|