File size: 4,452 Bytes
70d9e6c
deaa6d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70d9e6c
deaa6d8
 
 
 
 
 
bec7397
deaa6d8
 
 
70d9e6c
deaa6d8
70d9e6c
 
 
 
deaa6d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70d9e6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/** Reports tab — detection jobs, history, PDF export (FR-05). */

function formatReportDate(iso) {
  if (!iso) return '—';
  try {
    return new Date(iso).toLocaleString();
  } catch (_) {
    return iso;
  }
}

async function loadReportsList() {
  const el = document.getElementById('reports-list');
  if (!el) return;
  el.innerHTML = '<p class="dim">Loading reports…</p>';
  try {
    let jobs = [];
    try {
      const jobsData = await ddaApi('GET', '/api/dda/jobs?limit=30');
      jobs = jobsData.jobs || [];
    } catch (_) {
      /* jobs API optional — history still works */
    }
    const history = await ddaApi('GET', '/api/history');
    const rows = [];

    jobs.forEach((j) => {
      rows.push({
        kind: 'job',
        id: j.id,
        runId: j.runId,
        title: j.title || `${j.basePath} vs ${j.comparisonPath}`,
        status: j.status,
        changePct: j.report?.changePercentage,
        regions: j.report?.regionsCount,
        createdAt: j.createdAt,
        error: j.errorMessage,
      });
    });

    (history || []).forEach((r) => {
      if (rows.some((x) => x.runId === r.id)) return;
      rows.push({
        kind: 'run',
        id: r.id,
        runId: r.id,
        title: r.title,
        status: 'completed',
        changePct: r.changePercentage,
        regions: r.regionsCount,
        createdAt: r.createdAt,
      });
    });

    rows.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));

    if (!rows.length) {
      el.innerHTML = '<p class="dim">No detection reports yet. Run a comparison on the Change Detection tab.</p>';
      return;
    }

    el.innerHTML = `
      <table class="dda-reports-table">
        <thead>
          <tr>
            <th>Date</th>
            <th>Title</th>
            <th>Status</th>
            <th>Change %</th>
            <th>Regions</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          ${rows.map((r) => `
            <tr>
              <td>${formatReportDate(r.createdAt)}</td>
              <td>${escapeHtml(r.title)}</td>
              <td><span class="dda-status dda-status-${r.status}">${r.status}</span></td>
              <td>${r.changePct != null ? r.changePct.toFixed(2) + '%' : '—'}</td>
              <td>${r.regions ?? '—'}</td>
              <td class="dda-report-actions-cell">
                ${r.status === 'completed' && r.runId
                  ? `<button type="button" class="btn btn-secondary btn-sm" data-view-run="${r.runId}">View</button>
                     <a class="btn btn-secondary btn-sm" href="/dda/reports/${r.runId}" target="_blank" rel="noopener">Report</a>
                     <a class="btn btn-secondary btn-sm" href="/api/dda/reports/${r.runId}/pdf" download>PDF</a>`
                  : (r.error ? `<span class="dim" title="${String(r.error).replace(/"/g, '')}">Error</span>` : '—')}
              </td>
            </tr>`).join('')}
        </tbody>
      </table>`;

    el.querySelectorAll('[data-view-run]').forEach((btn) => {
      btn.addEventListener('click', async () => {
        const runId = btn.dataset.viewRun;
        try {
          const data = await ddaApi('GET', `/api/history/${runId}`);
          if (typeof showDdaResult === 'function') showDdaResult(data);
        } catch (err) {
          if (typeof showDdaError === 'function') showDdaError(err.message);
        }
      });
    });
  } catch (err) {
    el.innerHTML = `<p class="dim">Could not load reports: ${err.message}</p>`;
  }
}

window.loadReportsList = loadReportsList;

document.getElementById('btn-reports-refresh')?.addEventListener('click', loadReportsList);

document.querySelectorAll('.dda-tab').forEach((btn) => {
  if (btn.dataset.tab === 'reports') {
    btn.addEventListener('click', () => loadReportsList());
  }
});

document.addEventListener('DOMContentLoaded', () => {
  try {
    const openRun = sessionStorage.getItem('dda_open_run');
    if (openRun) {
      sessionStorage.removeItem('dda_open_run');
      document.querySelector('.dda-tab[data-tab="reports"]')?.click();
      setTimeout(async () => {
        try {
          const data = await ddaApi('GET', `/api/history/${openRun}`);
          if (typeof showDdaResult === 'function') showDdaResult(data);
        } catch (_) {}
      }, 300);
    }
  } catch (_) {}

  if (document.getElementById('tab-reports')?.classList.contains('active')) {
    loadReportsList();
  }
});