| 1 | DROP VIEW IF EXISTS public.v_customer_device_sim_timeline;
|
|---|
| 2 |
|
|---|
| 3 | CREATE VIEW public.v_customer_device_sim_timeline AS
|
|---|
| 4 | SELECT c.customer_id,
|
|---|
| 5 | CASE WHEN c.customer_type = 'business' THEN c.company_name ELSE c.first_name || ' ' || c.last_name END AS customer_name,
|
|---|
| 6 | a.account_number, s.subscription_number,
|
|---|
| 7 | 'device'::text AS asset_type, d.device_id AS asset_id, d.imei AS asset_identifier,
|
|---|
| 8 | d.manufacturer, d.model, d.device_type, NULL::text AS sim_type,
|
|---|
| 9 | da.assigned_from AS period_start, da.assigned_to AS period_end,
|
|---|
| 10 | da.assignment_status AS lifecycle_status
|
|---|
| 11 | FROM public.customers c
|
|---|
| 12 | JOIN public.accounts a ON a.customer_id = c.customer_id
|
|---|
| 13 | JOIN public.subscriptions s ON s.account_id = a.account_id
|
|---|
| 14 | JOIN public.device_assignments da ON da.subscription_id = s.subscription_id
|
|---|
| 15 | JOIN public.devices d ON d.device_id = da.device_id
|
|---|
| 16 | UNION ALL
|
|---|
| 17 | SELECT c.customer_id,
|
|---|
| 18 | CASE WHEN c.customer_type = 'business' THEN c.company_name ELSE c.first_name || ' ' || c.last_name END,
|
|---|
| 19 | a.account_number, s.subscription_number,
|
|---|
| 20 | 'sim', sc.sim_id, sc.msisdn, NULL::text, NULL::text, NULL::text, sc.sim_type,
|
|---|
| 21 | ssh.start_date, ssh.end_date,
|
|---|
| 22 | CASE WHEN ssh.end_date IS NULL THEN 'active' ELSE 'historical' END
|
|---|
| 23 | FROM public.customers c
|
|---|
| 24 | JOIN public.accounts a ON a.customer_id = c.customer_id
|
|---|
| 25 | JOIN public.subscriptions s ON s.account_id = a.account_id
|
|---|
| 26 | JOIN public.sim_card_subscription_history ssh ON ssh.subscription_id = s.subscription_id
|
|---|
| 27 | JOIN public.sim_cards sc ON sc.sim_id = ssh.sim_id;
|
|---|
| 28 |
|
|---|
| 29 |
|
|---|
| 30 | COMMENT ON VIEW public.v_customer_device_sim_timeline IS
|
|---|
| 31 | 'Unified device and SIM event timeline. UNION ALL avoids a device by SIM multiplication.';
|
|---|