// Dashboard, tab «Esportazione» (spec §7.9, §10.3, tappa E2; from mockup 06 and step 2 of mockup 09): the copy at // work with its progress and «Interrompi»; the jobs to resume («Riprendi», «Annulla») and the folders in pause // («Riprova»); the last jobs, each with its resoconto. The progress is asked every second while a copy works, every five // seconds otherwise (decision D20), as the import does. A pause is an amber notice here, never the red strip. import { api } from '../core/api.js'; import { h, icon, fill, later } from '../core/dom.js'; import { t, at, bytes, capitalize, number } from '../core/text.js'; import { confirmDialog, dialog, label, showError, toast } from '../core/ui.js'; const STATE_LOOK = { running: ['accento', 'play'], interrupted: ['ambra', 'pause'], paused: ['ambra', 'pause'], completed: ['verde', 'circle-check'], cancelled: ['', 'x'], }; const FILE_STATES = ['copied', 'adopted', 'alreadyCopied', 'skipped', 'missing', 'failed', 'pending']; export async function mountExport(page) { page.title(t('attivita.titolo')); document.title = t('app.titoloPagina', { pagina: `${t('esportazione.dashboard.esportazione')} · ${t('attivita.titolo')}` }); const current = h('section.blocco.copia-in-corso'); const pending = h('section.blocco', { hidden: true }); const recent = h('section.blocco'); fill(page.body, h('div.attivita.esportazione-dashboard', current, pending, recent)); let overview = null; let runs = []; let progress = null; let wasRunning = null; let timer = 0; let ticks = 0; let stopped = false; // One reading at a time: a command or a change during a reading asks for one more right after it, never a second chain. let inFlight = false; let rerun = false; page.onLeave(() => { stopped = true; clearTimeout(timer); }); async function loadSide() { try { [overview, runs] = await Promise.all([ api('/api/export', { signal: page.signal }), api('/api/export/runs?limit=20', { signal: page.signal }), ]); drawPending(); drawRecent(); } catch (error) { if (error.name !== 'AbortError') showError(error); } } async function poll() { if (stopped) return; if (inFlight) { rerun = true; return; } inFlight = true; clearTimeout(timer); try { await read(); } finally { inFlight = false; } if (stopped) return; clearTimeout(timer); if (rerun) { rerun = false; wasRunning = null; poll(); return; } timer = setTimeout(poll, progress && progress.running ? 1000 : 5000); } async function read() { try { progress = await api('/api/export/progress', { signal: page.signal }); } catch (error) { if (error.name === 'AbortError') return; progress = null; } drawCurrent(); const running = Boolean(progress && progress.running); ticks += 1; // The jobs and the folders follow the copy: when it starts or ends, and every few seconds while it works. if (running !== wasRunning || !running || ticks % 5 === 0) await loadSide(); wasRunning = running; } /** Asks again now (after a command), keeping one timer. */ function again() { clearTimeout(timer); wasRunning = null; poll(); } // ------------------------------------------------------------------------------------------- in corso function drawCurrent() { const p = progress; const head = h('div.testa-blocco', h('h2', t('esportazione.dashboard.inCorso'))); if (!p || !p.running) { fill(current, head, h('p.vuoto-elenco.pannello', t('esportazione.dashboard.nessunaInCorso'))); return; } const percent = Math.round((p.fraction || 0) * 100); const bar = h('div.misura.grande-misura', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(percent), 'aria-label': t('esportazione.dashboard.copio', { cartella: p.destination || '' }) }, h('i', { style: { width: `${percent}%` } })); const phase = p.phase && p.phase !== 'copying' && p.phase !== 'finished' ? t(`esportazione.dashboard.fasi.${p.phase}`) : ''; const count = [t('esportazione.dashboard.fatti', { fatti: number(p.filesDone), totale: number(p.filesTotal) })]; if (p.bytesTotal) count.push(t('esportazione.dashboard.byte', { fatti: bytes(p.bytesDone), totale: bytes(p.bytesTotal) })); fill(current, head, h('div.pannello.avanzamento-import.avanzamento-copia', h('h2.sez', t('esportazione.dashboard.copio', { cartella: p.destination || '' })), bar, h('p.conteggio.dati', count.join(' · ')), phase ? h('p.avviso.ambra.fase-copia', icon(p.phase === 'waitingForSession' ? 'hourglass' : 'info', 's'), h('span', phase)) : null, h('p.aiuto.piccolo.file-corrente', p.currentFile ? t('esportazione.dashboard.ora', { file: p.currentFile }) : ''), h('div.riga-azione', h('button.btn', { type: 'button', onclick: interrupt }, icon('pause', 's'), t('esportazione.dashboard.interrompi'))))); } async function interrupt(e) { e.currentTarget.disabled = true; try { const result = await api('/api/export/interrupt', { method: 'POST' }); toast(result.message); } catch (error) { showError(error); } again(); } // ------------------------------------------------------------------------------------------- da riprendere function drawPending() { const waiting = runs.filter((r) => !r.running && (r.state === 'interrupted' || r.state === 'paused')); const folders = overview ? [overview.general, ...(overview.own || [])].filter((d) => d && (d.pausedAt || d.problem)) : []; pending.hidden = !waiting.length && !folders.length; if (pending.hidden) { pending.replaceChildren(); return; } const busy = Boolean(progress && progress.running); fill(pending, h('div.testa-blocco', h('h2', t('esportazione.dashboard.daRiprendere')), waiting.length > 1 ? h('div.destra', h('button.btn.piccolo', { type: 'button', disabled: busy, onclick: resumeAll }, icon('play', 's'), t('esportazione.dashboard.riprendiTutte'))) : null), folders.map((d) => h('div.avviso.ambra.avviso-azione.riga-riprendi', icon('pause', 's'), h('span', t('esportazione.dashboard.cartellaInPausa', { cartella: d.label, problema: d.problem || t('esportazione.inPausa') })), h('button.btn.piccolo', { type: 'button', onclick: (e) => retry(d, e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.riprova')))), waiting.map((r) => h('div.avviso.ambra.avviso-azione.riga-riprendi', icon('pause', 's'), h('span', r.state === 'paused' ? t('esportazione.dashboard.ferma', { cartella: r.destination, problema: r.error || t('esportazione.inPausa') }) : t('esportazione.dashboard.interrotta', { cartella: r.destination, fatti: number(r.done), totale: number(r.total) })), h('button.btn.primo.piccolo', { type: 'button', disabled: busy, onclick: (e) => resume(r, e.currentTarget) }, icon('play', 's'), t('esportazione.dashboard.riprendi')), h('button.btn.nudo.piccolo', { type: 'button', onclick: () => discard(r) }, t('esportazione.dashboard.annulla'))))); } async function resume(run, button) { button.disabled = true; try { const result = await api(`/api/export/runs/${run.id}/resume`, { method: 'POST' }); toast(result.message); } catch (error) { button.disabled = false; showError(error); } again(); } async function resumeAll(e) { e.currentTarget.disabled = true; try { const result = await api('/api/export/resume', { method: 'POST' }); toast(result.message); } catch (error) { showError(error); } again(); } async function retry(d, button) { button.disabled = true; try { const result = await api(`/api/export/destinations/${d.id}/resume`, { method: 'POST' }); toast(result.message); } catch (error) { button.disabled = false; showError(error); } again(); } async function discard(run) { const ok = await confirmDialog({ title: t('esportazione.dashboard.annullaTitolo', { cartella: run.destination }), text: t('esportazione.dashboard.annullaTesto'), buttons: [ { label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true }, { label: t('esportazione.dashboard.annullaSi'), value: true, kind: 'pericolo' }, ], }); if (!ok) return; try { const result = await api(`/api/export/runs/${run.id}/discard`, { method: 'POST' }); toast(result.message); } catch (error) { showError(error); } again(); } // ------------------------------------------------------------------------------------------- ultimi lavori function drawRecent() { const head = h('div.testa-blocco', h('h2', t('esportazione.dashboard.ultimi'))); if (!runs.length) { fill(recent, head, h('p.vuoto-elenco.pannello', t('esportazione.dashboard.vuoto'))); return; } fill(recent, head, h('div.pannello', h('ul.elenco-attivita.largo', runs.map((r) => { const state = r.running ? 'running' : r.state; const [kind, look] = STATE_LOOK[state] || STATE_LOOK.cancelled; return h('li', h('span.quando.dati', capitalize(at(r.startedAt))), h('div.chi-cosa', h('b', jobName(r)), h('span', [t('esportazione.dashboard.fatti', { fatti: number(r.done), totale: number(r.total) }), r.error].filter(Boolean).join(' · '))), label(t(`esportazione.dashboard.stati.${state}`), kind, look), h('button.btn.piccolo', { type: 'button', onclick: () => openReport(r) }, t('esportazione.dashboard.resoconto'))); })))); } const onChange = later(() => again(), 400); page.onLibrary((change) => { if (change.reason === 'export') onChange(); }); page.onLeave(() => onChange.cancel()); await poll(); } function jobName(run) { return t(run.kind === 'recognize' ? 'esportazione.dashboard.lavoroControllo' : 'esportazione.dashboard.lavoroCopia', { cartella: run.destination }); } /** The resoconto of a job: files per state, per account, and the files that need a look (at most 200). */ async function openReport(run) { let report; try { report = await api(`/api/export/runs/${run.id}/report`); } catch (error) { showError(error); return; } const r = report.run; const when = [t('esportazione.dashboard.iniziata', { quando: at(r.startedAt) })]; if (r.completedAt) when.push(t('esportazione.dashboard.finita', { quando: at(r.completedAt) })); const states = FILE_STATES.filter((s) => report.byState[s]).map((s) => t(`esportazione.dashboard.statiFile.${s}`, { n: report.byState[s] })); if (report.bytesCopied) states.push(t('esportazione.dashboard.copiatiByte', { spazio: bytes(report.bytesCopied) })); const accounts = report.accounts.length ? h('div.pannello', h('table.tab.resoconto-account', h('thead', h('tr', h('th', { scope: 'col' }, t('esportazione.dashboard.colonne.account')), h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.copiati')), h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.gia')), h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.saltati')), h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.falliti')))), h('tbody', report.accounts.map((a) => h('tr', h('td', `@${a.username}`), h('td.num.dati', number(a.copied)), h('td.num.dati', number(a.alreadyCopied)), h('td.num.dati', number(a.skipped)), h('td.num.dati', number(a.failed))))))) : null; const problems = report.problems.length ? h('div.pannello', h('ul.elenco-attivita.problemi-copia', report.problems.map((p) => h('li', h('div.chi-cosa', h('b', `@${p.username}`, p.path ? h('span.codice.dati', p.path) : null), h('span', p.text)))))) : h('p.aiuto', t('esportazione.dashboard.nessunProblema')); await dialog({ title: t('esportazione.dashboard.resocontoTitolo', { lavoro: jobName(r) }), className: 'resoconto-copia', build: (close) => ({ body: h('div.contenuto', h('p.aiuto', `${when.join(', ')} · ${t(`esportazione.dashboard.stati.${r.running ? 'running' : r.state}`)}`), h('p.riepilogo-copia', states.join(' · ')), accounts ? h('h3', t('esportazione.dashboard.perAccount')) : null, accounts, h('h3', t('esportazione.dashboard.problemi')), problems), footer: h('footer', h('div.destra', h('button.btn', { type: 'button', autofocus: true, onclick: () => close() }, t('comune.chiudi')))), }), }); }