\pset border 2
\pset format aligned

\echo '== A. All field staff and sync IDs (live) =='
SELECT u.id, u.login, p.name, u.x_fc_is_field_staff, u.x_fc_tech_sync_id, u.active
FROM res_users u JOIN res_partner p ON p.id = u.partner_id
WHERE u.x_fc_is_field_staff = TRUE
   OR (u.x_fc_tech_sync_id IS NOT NULL AND u.x_fc_tech_sync_id <> '')
ORDER BY u.active DESC, u.login;

\echo ''
\echo '== B. Last pull cron run + sync config status =='
SELECT
  (SELECT to_char(lastcall, 'YYYY-MM-DD HH24:MI:SS') FROM ir_cron WHERE cron_name LIKE 'Fusion Tasks: Sync Remote Tasks (Pull)') AS last_pull_cron,
  (SELECT to_char(last_sync, 'YYYY-MM-DD HH24:MI:SS') FROM fusion_task_sync_config LIMIT 1) AS last_sync,
  (SELECT LEFT(COALESCE(last_sync_error,'(none)'),120) FROM fusion_task_sync_config LIMIT 1) AS last_sync_error,
  to_char(NOW(), 'YYYY-MM-DD HH24:MI:SS') AS now;

\echo ''
\echo '== C. Tasks by tech in next 7 days (target: simranjeet + hk shadows now appear) =='
SELECT
  u.login AS tech_login,
  u.x_fc_tech_sync_id AS sync_id,
  COALESCE(NULLIF(t.x_fc_sync_source,''), '<local>') AS source,
  COUNT(*) AS cnt
FROM fusion_technician_task t
JOIN res_users u ON u.id = t.technician_id
WHERE t.scheduled_date BETWEEN CURRENT_DATE - 1 AND CURRENT_DATE + 7
  AND t.active = TRUE
GROUP BY 1,2,3
ORDER BY 1,3;
