| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135 |
- /* global jQuery */
- /**
- * Main planning view (/sprints/{id}) — Section A: Arbeitstage grid.
- *
- * Behaviours:
- * - Day cells (per worker, per week) snap to 0.5 on blur, batch-saved via
- * PATCH /sprints/{id}/week-cells with 400 ms debounce.
- * - The Arbeitstage header row is derived from the weekday selection in
- * Sprint Settings — it's read-only here (Phase 12).
- * - RTB inputs snap to 0.05 on blur, saved via PATCH /sprints/{id}/workers/{sw_id}.
- * - Worker rows are sortable (jQuery UI). Drop posts to
- * POST /sprints/{id}/workers/reorder.
- *
- * All capacity values are recomputed client-side with the same formula as
- * `App\Services\CapacityCalculator` so the UI stays in sync without waiting
- * for the server response.
- */
- (function ($) {
- 'use strict';
- const $root = $('[data-sprint-root]');
- if ($root.length === 0) { return; }
- const sprintId = parseInt($root.data('sprint-id'), 10);
- const csrf = String($root.data('csrf') || '');
- const reserveFraction = Number($root.data('reserve-fraction') || 0);
- // Phase 15: the presentation view stamps data-beamer="1" on the root so
- // we can namespace its localStorage keys (don't clobber the user's
- // workflow on /sprints/{id}) and flip on vertical-header rotation if
- // the task table overflows after the first filter pass.
- const isBeamer = Number($root.data('beamer')) === 1;
- const keySuffix = isBeamer ? ':beamer' : '';
- // Phase 18: per-cell task-assignment status. The flag is rendered onto
- // the [data-task-section] element so both this view and present.php
- // light up identically. When false, the per-cell selectors and the
- // toolbar Status filter are simply absent from the DOM.
- const taskStatusEnabled =
- $root.find('[data-task-section]').attr('data-task-status-enabled') === '1';
- const STATUSES = ['zugewiesen', 'gestartet', 'abgeschlossen', 'abgebrochen'];
- // ---------------------------------------------------------------------
- // Capacity math — MUST match App\Services\CapacityCalculator
- // ---------------------------------------------------------------------
- function roundHalf(x) { return Math.round(x * 2) / 2; }
- function snap05(x) { return roundHalf(x); }
- function snap005(x) { return Math.round(x * 20) / 20; }
- function fmtDays(x) {
- const n = Number(x);
- if (Math.abs(n - Math.round(n)) < 1e-9) { return String(Math.round(n)); }
- return n.toFixed(1);
- }
- function fmtRtb(x) { return Number(x).toFixed(2); }
- function capacity(ressourcen, committedPrio1) {
- committedPrio1 = committedPrio1 || 0;
- const afterReserves = roundHalf(ressourcen * (1 - reserveFraction));
- const available = afterReserves - committedPrio1;
- return { ressourcen, afterReserves, committedPrio1, available };
- }
- // Sum of prio-1 task assignment cells per sprint worker, read from DOM.
- function committedPrio1FromDom() {
- const per = {};
- $root.find('tr[data-task-row]').each(function () {
- const $row = $(this);
- if (parseInt($row.attr('data-prio'), 10) !== 1) { return; }
- $row.find('[data-assign]').each(function () {
- const key = String($(this).data('sw-id'));
- const v = Number($(this).val());
- if (!Number.isNaN(v) && v > 0) {
- per[key] = (per[key] || 0) + v;
- }
- });
- });
- return per;
- }
- // ---------------------------------------------------------------------
- // HTTP helper — spec §7 envelopes
- // ---------------------------------------------------------------------
- function request(method, url, body) {
- const opts = {
- method,
- headers: {
- Accept: 'application/json',
- 'X-CSRF-Token': csrf,
- },
- credentials: 'same-origin',
- };
- if (body !== undefined) {
- opts.headers['Content-Type'] = 'application/json';
- opts.body = JSON.stringify(body);
- }
- return fetch(url, opts).then(async function (res) {
- let payload = null;
- try { payload = await res.json(); } catch (_) { /* ignore */ }
- if (!res.ok || !payload || payload.ok !== true) {
- const msg = (payload && payload.error && payload.error.message)
- ? payload.error.message
- : res.statusText || 'Request failed';
- const err = new Error(msg);
- err.status = res.status;
- err.payload = payload;
- throw err;
- }
- return payload.data;
- });
- }
- // ---------------------------------------------------------------------
- // Status line (shared with settings page styling)
- // ---------------------------------------------------------------------
- const $status = $root.find('[data-status]');
- let statusTimer = null;
- function flash(text, isError) {
- $status
- .text(text)
- .removeClass('text-green-700 text-red-700 bg-green-50 bg-red-50 border-green-200 border-red-200')
- .addClass(isError ? 'text-red-700 bg-red-50 border-red-200' : 'text-green-700 bg-green-50 border-green-200')
- .removeClass('opacity-0').addClass('opacity-100');
- clearTimeout(statusTimer);
- statusTimer = setTimeout(function () {
- $status.removeClass('opacity-100').addClass('opacity-0');
- }, 2500);
- }
- // ---------------------------------------------------------------------
- // Recompute worker row sum + capacity summary locally
- // ---------------------------------------------------------------------
- function recomputeRow(swId, commitMap) {
- const $row = $root.find('[data-sw-row][data-sw-id="' + swId + '"]');
- let sum = 0;
- $row.find('[data-day]').each(function () {
- const v = Number($(this).val());
- if (!Number.isNaN(v)) { sum += v; }
- });
- const committed = (commitMap || committedPrio1FromDom())[String(swId)] || 0;
- const cap = capacity(sum, committed);
- $row.find('[data-sum-days]').text(fmtDays(cap.ressourcen));
- $root.find('[data-cap-ressourcen][data-sw-id="' + swId + '"]').text(fmtDays(cap.ressourcen));
- $root.find('[data-cap-after-reserves][data-sw-id="' + swId + '"]').text(fmtDays(cap.afterReserves));
- const $avail = $root.find('[data-cap-available][data-sw-id="' + swId + '"]');
- $avail.text(fmtDays(cap.available));
- if (cap.available < 0) {
- $avail.removeClass('text-slate-900').addClass('text-red-700');
- } else {
- $avail.removeClass('text-red-700').addClass('text-slate-900');
- }
- }
- // Recompute every worker row (capacity summary) — called when a task-side
- // change might affect committed prio-1 values.
- function recomputeAllCapacity() {
- const commit = committedPrio1FromDom();
- $root.find('[data-sw-row]').each(function () {
- recomputeRow(parseInt($(this).data('sw-id'), 10), commit);
- });
- }
- // ---------------------------------------------------------------------
- // Pending-cell queue, debounced batch save
- // ---------------------------------------------------------------------
- // key = "swId:weekId" → { sw_id, week_id, days }
- const pendingCells = new Map();
- let cellDebounce = null;
- function queueCell(swId, weekId, days) {
- pendingCells.set(swId + ':' + weekId, {
- sprint_worker_id: swId,
- sprint_week_id: weekId,
- days: days,
- });
- clearTimeout(cellDebounce);
- cellDebounce = setTimeout(flushCells, 400);
- }
- function flushCells() {
- if (pendingCells.size === 0) { return; }
- const cells = Array.from(pendingCells.values());
- pendingCells.clear();
- request('PATCH', '/sprints/' + sprintId + '/week-cells', cells)
- .then(function (data) {
- if (data.applied === 0 && data.noop > 0) {
- flash('No changes');
- } else {
- flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells'));
- }
- // Trust the server's capacity numbers — same formula, but a
- // safety net if an input was tampered with.
- if (data.per_worker && typeof data.per_worker === 'object') {
- Object.keys(data.per_worker).forEach(function (swIdStr) {
- const c = data.per_worker[swIdStr];
- $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
- $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
- const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
- $av.text(fmtDays(c.available));
- if (c.available < 0) {
- $av.removeClass('text-slate-900').addClass('text-red-700');
- } else {
- $av.removeClass('text-red-700').addClass('text-slate-900');
- }
- $root.find('[data-sw-row][data-sw-id="' + swIdStr + '"] [data-sum-days]').text(fmtDays(c.ressourcen));
- });
- }
- })
- .catch(function (e) { flash(e.message, true); });
- }
- // ---------------------------------------------------------------------
- // Day cells
- // ---------------------------------------------------------------------
- $root.on('blur change', '[data-day]', function () {
- const $el = $(this);
- let v = Number($el.val());
- if (Number.isNaN(v)) { v = 0; }
- if (v < 0) { v = 0; }
- if (v > 5) { v = 5; }
- v = snap05(v);
- $el.val(fmtDays(v));
- const swId = parseInt($el.data('sw-id'), 10);
- const weekId = parseInt($el.data('week-id'), 10);
- queueCell(swId, weekId, v);
- recomputeRow(swId);
- });
- // ---------------------------------------------------------------------
- // Per-row RTB edit
- // ---------------------------------------------------------------------
- $root.on('blur change', '[data-rtb]', function () {
- const $el = $(this);
- let v = Number($el.val());
- if (Number.isNaN(v)) { v = 0; }
- if (v < 0) { v = 0; }
- if (v > 1) { v = 1; }
- v = snap005(v);
- $el.val(fmtRtb(v));
- const swId = parseInt($el.data('sw-id'), 10);
- request('PATCH', '/sprints/' + sprintId + '/workers/' + swId, { rtb: v })
- .then(function () { flash('Saved'); })
- .catch(function (e) { flash(e.message, true); });
- });
- // ---------------------------------------------------------------------
- // Worker row drag-reorder (admin only — tbody only exists with handles)
- // ---------------------------------------------------------------------
- const sortableAvailable = typeof $.fn.sortable === 'function';
- if (!sortableAvailable) {
- // jQuery UI didn't load (SRI mismatch, offline CDN, ad blocker).
- // Drag-reorder is unavailable but the rest of the page still works.
- // eslint-disable-next-line no-console
- console.warn('[sprint-planner] jQuery UI not loaded — drag reorder disabled.');
- }
- const $tbody = $root.find('[data-tbody]');
- if (sortableAvailable && $tbody.find('.handle').length > 0) {
- $tbody.sortable({
- handle: '.handle',
- items: 'tr[data-sw-row]',
- axis: 'y',
- helper: function (e, tr) {
- // Preserve the td widths so the row doesn't collapse while dragging.
- const $cells = tr.children();
- const $clone = tr.clone();
- $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
- return $clone;
- },
- update: function () {
- const ordering = $tbody.find('tr[data-sw-row]').map(function (i, el) {
- return {
- sprint_worker_id: parseInt($(el).data('sw-id'), 10),
- sort_order: i + 1,
- };
- }).get();
- request('POST', '/sprints/' + sprintId + '/workers/reorder', ordering)
- .then(function (data) {
- if (data.moved) {
- // Column order in the task list below depends on
- // this ordering — simplest to re-render.
- window.location.reload();
- } else {
- flash('No changes');
- }
- })
- .catch(function (e) { flash(e.message, true); });
- },
- });
- }
- // =====================================================================
- // Task list — create/edit/delete/reorder + assignments + filter/sort
- // =====================================================================
- const $taskTbody = $root.find('[data-task-tbody]');
- const hasTaskUi = $taskTbody.length > 0;
- // --- Worker/owner helpers read from the DOM once ----------------------
- function sprintWorkerHeaders() {
- const out = [];
- $root.find('[data-task-table] thead th[data-sort-col^="sw-"]').each(function () {
- const col = String($(this).attr('data-sort-col'));
- out.push({
- id: parseInt(col.slice(3), 10),
- name: $(this).clone().children().remove().end().text().trim(),
- });
- });
- return out;
- }
- // The owner dropdown used to be a plain <select>, but Phase 10 replaced
- // it with a checkbox multi-filter. We now scrape the real source of
- // truth: the [data-owner-filter-opt] inputs, skipping the special
- // "__none__" entry. Empty list → new task rows get an empty dropdown,
- // which was the symptom the user hit after Phase 10 landed.
- function ownerChoices() {
- const out = [];
- $root.find('[data-owner-filter-opt]').each(function () {
- const v = String($(this).val());
- if (v === '' || v === '__none__') { return; }
- const id = parseInt(v, 10);
- if (!Number.isFinite(id)) { return; }
- const name = String($(this).closest('label').find('span').text()).trim();
- out.push({ id: id, name: name });
- });
- return out;
- }
- // --- Build a task row <tr> from an object ----------------------------
- function buildTaskRow(task, assignments) {
- assignments = assignments || {};
- const $tr = $('<tr>')
- .attr('data-task-row', '')
- .attr('data-task-id', task.id)
- .attr('data-prio', task.priority)
- .attr('data-owner', task.owner_worker_id || '')
- .attr('data-sort-order', task.sort_order);
- // handle
- $tr.append($('<td class="px-2 py-1"></td>').append(
- $('<span class="handle cursor-grab text-slate-400 select-none">').html('≡')
- ));
- // title
- $tr.append(
- $('<td class="px-2 py-1 min-w-[14rem]"></td>').append(
- $('<input type="text" data-title class="w-full rounded border border-slate-200 px-2 py-1 focus:outline-none focus:ring-2 focus:ring-slate-400">')
- .val(task.title)
- )
- );
- // owner
- const $sel = $('<select data-owner-select class="w-full rounded border border-slate-200 px-2 py-1 bg-white focus:outline-none focus:ring-2 focus:ring-slate-400">');
- $sel.append('<option value="">—</option>');
- ownerChoices().forEach(function (o) {
- const $opt = $('<option>').val(o.id).text(o.name);
- if (Number(o.id) === Number(task.owner_worker_id)) { $opt.attr('selected', 'selected'); }
- $sel.append($opt);
- });
- $tr.append($('<td class="px-2 py-1" data-col="owner"></td>').append($sel));
- // priority
- const $prio = $('<select data-prio-select class="rounded border border-slate-200 px-2 py-1 bg-white font-mono focus:outline-none focus:ring-2 focus:ring-slate-400"><option value="1">1</option><option value="2">2</option></select>');
- $prio.val(String(task.priority));
- $tr.append($('<td class="px-2 py-1 text-center" data-col="prio"></td>').append($prio));
- // tot
- let tot = 0;
- Object.keys(assignments).forEach(function (k) { tot += Number(assignments[k]) || 0; });
- $tr.append($('<td class="px-2 py-1 text-center font-mono font-semibold" data-col="tot" data-task-tot>').text(fmtDays(tot)));
- // per-worker assignment cells
- sprintWorkerHeaders().forEach(function (sw) {
- const v = Number(assignments[sw.id] || 0);
- const $td = $('<td class="px-1 py-1 text-center"></td>')
- .attr('data-col', 'sw-' + sw.id)
- .attr('data-sort-value-sw-' + sw.id, v.toFixed(2));
- const $input = $('<input type="number" min="0" step="0.5" data-assign class="w-14 rounded border border-slate-200 px-1 py-1 text-center font-mono focus:outline-none focus:ring-2 focus:ring-slate-400">')
- .val(fmtDays(v))
- .attr('data-sw-id', sw.id);
- if (taskStatusEnabled) {
- // New tasks always start with the default status.
- const $cell = $('<span class="assign-cell assign-status-zugewiesen"></span>')
- .attr('data-assign-cell', '')
- .attr('data-sw-id', sw.id)
- .attr('data-status', 'zugewiesen');
- $cell.append($input);
- const $status = $('<select data-assign-status aria-label="Status" class="assign-status-select"></select>')
- .attr('data-sw-id', sw.id);
- STATUSES.forEach(function (s) {
- $('<option>').val(s).text(s).appendTo($status);
- });
- $status.val('zugewiesen');
- $cell.append($status);
- $td.append($cell);
- } else {
- $td.append($input);
- }
- $tr.append($td);
- });
- // delete
- $tr.append(
- $('<td class="px-1 py-1 text-right"></td>').append(
- $('<button type="button" data-delete-task class="text-sm text-red-600 hover:underline">').text('×')
- )
- );
- return $tr;
- }
- // --- Add task ---------------------------------------------------------
- $root.on('click', '[data-add-task]', function () {
- request('POST', '/sprints/' + sprintId + '/tasks', { title: '', priority: 1 })
- .then(function (data) {
- $root.find('[data-empty-tasks]').remove();
- const $row = buildTaskRow(data.task, data.assignments || {});
- $taskTbody.append($row);
- // Clear any active sort so the new row is actually visible at the end.
- clearSort();
- applyColumnVisibility();
- applyFilters();
- $row.find('[data-title]').trigger('focus').trigger('select');
- flash('Task added');
- })
- .catch(function (e) { flash(e.message, true); });
- });
- // --- Edit task fields (title / owner / prio) --------------------------
- const titleDebounce = {};
- $root.on('input', '[data-title]', function () {
- const $inp = $(this);
- const taskId = parseInt($inp.closest('tr').data('task-id'), 10);
- clearTimeout(titleDebounce[taskId]);
- titleDebounce[taskId] = setTimeout(function () {
- const title = String($inp.val()).trim();
- if (title === '') {
- flash('Title cannot be empty', true);
- return;
- }
- request('PATCH', '/tasks/' + taskId, { title: title })
- .then(function () { flash('Saved'); })
- .catch(function (e) { flash(e.message, true); });
- }, 400);
- });
- $root.on('change', '[data-owner-select]', function () {
- const $sel = $(this);
- const $row = $sel.closest('tr');
- const taskId = parseInt($row.data('task-id'), 10);
- const v = $sel.val();
- const owner = v === '' ? null : parseInt(String(v), 10);
- $row.attr('data-owner', owner === null ? '' : owner);
- request('PATCH', '/tasks/' + taskId, { owner_worker_id: owner })
- .then(function () { flash('Saved'); applyFilters(); })
- .catch(function (e) { flash(e.message, true); });
- });
- $root.on('change', '[data-prio-select]', function () {
- const $sel = $(this);
- const $row = $sel.closest('tr');
- const taskId = parseInt($row.data('task-id'), 10);
- const prio = parseInt(String($sel.val()), 10);
- $row.attr('data-prio', prio);
- request('PATCH', '/tasks/' + taskId, { priority: prio })
- .then(function (data) {
- flash('Saved');
- applyFilters();
- applyServerCapacity(data && data.per_worker);
- recomputeAllCapacity();
- })
- .catch(function (e) { flash(e.message, true); });
- });
- // --- Delete task ------------------------------------------------------
- $root.on('click', '[data-delete-task]', function () {
- const $row = $(this).closest('tr');
- const taskId = parseInt($row.data('task-id'), 10);
- const title = $row.find('[data-title]').val() || '(untitled)';
- if (!window.confirm('Delete task "' + title + '"?')) { return; }
- request('DELETE', '/tasks/' + taskId)
- .then(function (data) {
- $row.remove();
- applyServerCapacity(data && data.per_worker);
- recomputeAllCapacity();
- flash('Task deleted');
- if ($taskTbody.children('tr[data-task-row]').length === 0) {
- // Re-show the empty-state row (simpler than templating).
- window.location.reload();
- }
- })
- .catch(function (e) { flash(e.message, true); });
- });
- // --- Assignment cells (per task, per sprint worker) -------------------
- // Same shape as the Arbeitstage cell queue, but against /tasks/{id}/assignments.
- const pendingAssign = new Map(); // taskId -> Map<swId, days>
- const assignTimers = {};
- function queueAssign(taskId, swId, days) {
- if (!pendingAssign.has(taskId)) { pendingAssign.set(taskId, new Map()); }
- pendingAssign.get(taskId).set(swId, days);
- clearTimeout(assignTimers[taskId]);
- assignTimers[taskId] = setTimeout(function () { flushAssign(taskId); }, 400);
- }
- function flushAssign(taskId) {
- const m = pendingAssign.get(taskId);
- if (!m || m.size === 0) { return; }
- const cells = [];
- m.forEach(function (days, swId) {
- cells.push({ sprint_worker_id: swId, days: days });
- });
- pendingAssign.delete(taskId);
- request('PATCH', '/tasks/' + taskId + '/assignments', cells)
- .then(function (data) {
- if (data.applied === 0 && data.noop > 0) { flash('No changes'); }
- else { flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells')); }
- applyServerCapacity(data && data.per_worker);
- })
- .catch(function (e) { flash(e.message, true); });
- }
- $root.on('blur change', '[data-assign]', function () {
- const $el = $(this);
- let v = Number($el.val());
- if (Number.isNaN(v) || v < 0) { v = 0; }
- v = snap05(v);
- $el.val(fmtDays(v));
- $el.closest('td').attr('data-sort-value-sw-' + $el.data('sw-id'), v.toFixed(2));
- const taskId = parseInt($el.closest('tr').data('task-id'), 10);
- const swId = parseInt($el.data('sw-id'), 10);
- queueAssign(taskId, swId, v);
- // Row total
- let tot = 0;
- $el.closest('tr').find('[data-assign]').each(function () {
- const n = Number($(this).val());
- if (!Number.isNaN(n)) { tot += n; }
- });
- $el.closest('tr').find('[data-task-tot]').text(fmtDays(tot));
- // Available recompute (in case this is a prio-1 task)
- recomputeAllCapacity();
- });
- // --- Phase 18: per-cell status save pipeline -------------------------
- // Independent of the days pipeline: hits /tasks/{id}/assignments/status
- // (signed-in route, gated by app_settings.task_status_enabled). Same
- // debounce semantics + same audit weight (one row per changed cell).
- const pendingStatus = new Map(); // taskId -> Map<swId, status>
- const statusTimers = {};
- function queueStatus(taskId, swId, status) {
- if (!pendingStatus.has(taskId)) { pendingStatus.set(taskId, new Map()); }
- pendingStatus.get(taskId).set(swId, status);
- clearTimeout(statusTimers[taskId]);
- statusTimers[taskId] = setTimeout(function () { flushStatus(taskId); }, 400);
- }
- function flushStatus(taskId) {
- const m = pendingStatus.get(taskId);
- if (!m || m.size === 0) { return; }
- const cells = [];
- m.forEach(function (status, swId) {
- cells.push({ sprint_worker_id: swId, status: status });
- });
- pendingStatus.delete(taskId);
- request('PATCH', '/tasks/' + taskId + '/assignments/status', cells)
- .then(function (data) {
- if (data.applied === 0 && data.noop > 0) { flash('No changes'); }
- else { flash('Saved ' + data.applied + (data.applied === 1 ? ' status' : ' statuses')); }
- })
- .catch(function (e) { flash(e.message, true); });
- }
- function applyStatusClass($cell, next) {
- // Replace any existing assign-status-* with the new one. Keep the
- // class set deterministic (any unknown classes get scrubbed).
- STATUSES.forEach(function (s) { $cell.removeClass('assign-status-' + s); });
- $cell.addClass('assign-status-' + next);
- $cell.attr('data-status', next);
- }
- $root.on('change', '[data-assign-status]', function () {
- const $sel = $(this);
- const next = String($sel.val() || '');
- if (STATUSES.indexOf(next) === -1) { return; }
- const $cell = $sel.closest('[data-assign-cell]');
- applyStatusClass($cell, next);
- const taskId = parseInt($sel.closest('tr').data('task-id'), 10);
- const swId = parseInt($sel.data('sw-id'), 10);
- queueStatus(taskId, swId, next);
- // Re-evaluate the status filter immediately so the row hides /
- // shows without waiting for the server round-trip.
- applyFilters();
- });
- function applyServerCapacity(perWorker) {
- if (!perWorker || typeof perWorker !== 'object') { return; }
- Object.keys(perWorker).forEach(function (swIdStr) {
- const c = perWorker[swIdStr];
- $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
- $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
- const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
- $av.text(fmtDays(c.available));
- if (c.available < 0) {
- $av.removeClass('text-slate-900').addClass('text-red-700');
- } else {
- $av.removeClass('text-red-700').addClass('text-slate-900');
- }
- });
- }
- // --- Task reorder (drag) ----------------------------------------------
- if (sortableAvailable && hasTaskUi && $taskTbody.find('.handle').length > 0) {
- $taskTbody.sortable({
- handle: '.handle',
- items: 'tr[data-task-row]',
- axis: 'y',
- helper: function (e, tr) {
- const $cells = tr.children();
- const $clone = tr.clone();
- $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
- return $clone;
- },
- start: function () {
- // Drag only makes sense when no sort is active.
- if (currentSort.col !== null) { clearSort(); }
- },
- update: function () {
- const ordering = $taskTbody.find('tr[data-task-row]').map(function (i, el) {
- return { task_id: parseInt($(el).data('task-id'), 10), sort_order: i + 1 };
- }).get();
- request('POST', '/sprints/' + sprintId + '/tasks/reorder', ordering)
- .then(function (data) {
- ordering.forEach(function (o) {
- $taskTbody.find('tr[data-task-id="' + o.task_id + '"]').attr('data-sort-order', o.sort_order);
- });
- flash(data.moved ? 'Order saved' : 'No changes');
- })
- .catch(function (e) { flash(e.message, true); });
- },
- });
- }
- // --- Multi-select owner filter (persisted in localStorage) -------------
- const ownerFilterKey = 'sp:' + sprintId + ':ownerFilter' + keySuffix;
- /** @type {Set<string>} */
- const ownerFilterSet = (function () {
- try {
- const raw = window.localStorage.getItem(ownerFilterKey);
- if (raw) {
- const arr = JSON.parse(raw);
- if (Array.isArray(arr)) { return new Set(arr.map(String)); }
- }
- } catch (_) { /* ignore */ }
- return new Set();
- })();
- function persistOwnerFilter() {
- try {
- window.localStorage.setItem(ownerFilterKey, JSON.stringify(Array.from(ownerFilterSet)));
- } catch (_) { /* ignore quota / private mode */ }
- }
- function updateOwnerFilterUi() {
- // Reflect state back into the checkboxes.
- $root.find('[data-owner-filter-opt]').each(function () {
- $(this).prop('checked', ownerFilterSet.has(String($(this).val())));
- });
- // Count label on the trigger.
- const n = ownerFilterSet.size;
- $root.find('[data-owner-filter-count]').text(n === 0 ? '' : '(' + n + ')');
- }
- $root.on('change', '[data-owner-filter-opt]', function () {
- const v = String($(this).val());
- if ($(this).is(':checked')) { ownerFilterSet.add(v); } else { ownerFilterSet.delete(v); }
- persistOwnerFilter();
- updateOwnerFilterUi();
- applyFilters();
- });
- $root.on('click', '[data-owner-filter-clear]', function () {
- ownerFilterSet.clear();
- persistOwnerFilter();
- updateOwnerFilterUi();
- applyFilters();
- });
- $root.on('click', '[data-owner-filter-trigger]', function (ev) {
- ev.stopPropagation();
- $root.find('[data-columns-dropdown]').addClass('hidden');
- $root.find('[data-owner-filter-dropdown]').toggleClass('hidden');
- });
- // --- Focus filter (single sprint worker, persisted) -------------------
- const focusKey = 'sp:' + sprintId + ':focusWorker' + keySuffix;
- let focusWorker = (function () {
- try {
- const raw = window.localStorage.getItem(focusKey);
- if (raw === null) { return ''; }
- return String(raw);
- } catch (_) { return ''; }
- })();
- function persistFocus() {
- try { window.localStorage.setItem(focusKey, String(focusWorker)); }
- catch (_) { /* ignore */ }
- }
- function updateFocusUi() {
- const $sel = $root.find('[data-focus-select]');
- if ($sel.length === 0) { return; }
- // If the stored worker is no longer a sprint member, fall back to "".
- if (focusWorker !== '' && $sel.find('option[value="' + focusWorker + '"]').length === 0) {
- focusWorker = '';
- persistFocus();
- }
- $sel.val(focusWorker);
- }
- // --- Phase 18: status filter (multi-select, persisted) ----------------
- const statusFilterKey = 'sp:' + sprintId + ':statusFilter' + keySuffix;
- /** @type {Set<string>} */
- const statusFilterSet = (function () {
- if (!taskStatusEnabled) { return new Set(); }
- try {
- const raw = window.localStorage.getItem(statusFilterKey);
- if (raw) {
- const arr = JSON.parse(raw);
- if (Array.isArray(arr)) { return new Set(arr.map(String)); }
- }
- } catch (_) { /* ignore */ }
- return new Set();
- })();
- function persistStatusFilter() {
- try {
- window.localStorage.setItem(statusFilterKey, JSON.stringify(Array.from(statusFilterSet)));
- } catch (_) { /* ignore quota / private mode */ }
- }
- function updateStatusFilterUi() {
- $root.find('[data-status-filter-opt]').each(function () {
- $(this).prop('checked', statusFilterSet.has(String($(this).val())));
- });
- const n = statusFilterSet.size;
- $root.find('[data-status-filter-count]').text(n === 0 ? '' : '(' + n + ')');
- }
- $root.on('change', '[data-status-filter-opt]', function () {
- const v = String($(this).val());
- if (STATUSES.indexOf(v) === -1) { return; }
- if ($(this).is(':checked')) { statusFilterSet.add(v); } else { statusFilterSet.delete(v); }
- persistStatusFilter();
- updateStatusFilterUi();
- applyFilters();
- });
- $root.on('click', '[data-status-filter-clear]', function () {
- statusFilterSet.clear();
- persistStatusFilter();
- updateStatusFilterUi();
- applyFilters();
- });
- $root.on('click', '[data-status-filter-trigger]', function (ev) {
- ev.stopPropagation();
- $root.find('[data-owner-filter-dropdown]').addClass('hidden');
- $root.find('[data-columns-dropdown]').addClass('hidden');
- $root.find('[data-status-filter-dropdown]').toggleClass('hidden');
- });
- // Predicate: row passes if at least one of its cells is in the picked
- // status set. The default 'zugewiesen' state matches only when there's
- // actual work assigned (days > 0) so picking it doesn't match every
- // task; the explicit states (gestartet/abgeschlossen/abgebrochen) match
- // regardless of days because a user only sets them deliberately.
- function rowMatchesStatusFilter($row) {
- if (statusFilterSet.size === 0) { return true; }
- let matched = false;
- $row.find('[data-assign-cell]').each(function () {
- const $cell = $(this);
- const status = String($cell.attr('data-status') || 'zugewiesen');
- if (!statusFilterSet.has(status)) { return; }
- if (status === 'zugewiesen') {
- const $inp = $cell.find('[data-assign]');
- const days = $inp.length
- ? (Number($inp.val()) || 0)
- : (Number($cell.find('.font-mono').text()) || 0);
- if (days > 0) { matched = true; return false; }
- return;
- }
- matched = true;
- return false;
- });
- return matched;
- }
- // --- Filters (search / prio / owner / focus / status) ----------------
- function applyFilters() {
- const q = String($root.find('[data-task-search]').val() || '').trim().toLowerCase();
- const prio = String($root.find('[data-prio-filter]').val() || '');
- const focus = String(focusWorker || '');
- let visibleCount = 0;
- $taskTbody.children('tr[data-task-row]').each(function () {
- const $row = $(this);
- const title = String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
- const rowPrio = String($row.attr('data-prio'));
- const rowOwner = String($row.attr('data-owner') || '');
- // The filter set treats "" (no owner) as the special "__none__" key.
- const ownerKey = rowOwner === '' ? '__none__' : rowOwner;
- let ok = true;
- if (q !== '' && !title.includes(q)) { ok = false; }
- if (prio !== '' && rowPrio !== prio) { ok = false; }
- if (ownerFilterSet.size > 0 && !ownerFilterSet.has(ownerKey)) { ok = false; }
- if (focus !== '') {
- // Zero-tolerance matches capacity math: treat 0 / 0.0 / empty
- // as "no assignment" (Number(v) > 0, not !== 0).
- const v = Number($row.find('[data-assign][data-sw-id="' + focus + '"]').val());
- if (!(v > 0)) { ok = false; }
- }
- if (ok && taskStatusEnabled && !rowMatchesStatusFilter($row)) { ok = false; }
- $row.toggle(ok);
- if (ok) { visibleCount++; }
- });
- const totalRows = $taskTbody.children('tr[data-task-row]').length;
- $root.find('[data-task-empty-filter]').toggle(totalRows > 0 && visibleCount === 0);
- applyFocusColumnVisibility();
- updateResetVisibility();
- }
- // Column auto-hide: when a focus worker is selected, any sw column that
- // is all-zero for the currently visible rows collapses. We tag cells
- // with `.focus-auto-hidden` rather than mutating `hiddenCols` so that
- // clearing Focus restores whatever the user picked in the Columns
- // dropdown.
- function applyFocusColumnVisibility() {
- // Always clear the transient class first — keeps the function
- // idempotent and correct when focus goes from set → "".
- $root.find('.focus-auto-hidden').removeClass('focus-auto-hidden');
- if (!focusWorker) { return; }
- // Walk every sw column. If no currently visible row has a > 0
- // assignment for that sw, hide every `[data-col="sw-{id}"]` cell.
- $root.find('[data-task-table] thead th[data-sort-col^="sw-"]').each(function () {
- const col = String($(this).attr('data-sort-col')); // e.g. "sw-42"
- const swId = col.slice(3);
- let anyNonZero = false;
- $taskTbody.children('tr[data-task-row]:visible').each(function () {
- const v = Number($(this).find('[data-assign][data-sw-id="' + swId + '"]').val());
- if (v > 0) { anyNonZero = true; return false; /* break */ }
- });
- if (!anyNonZero) {
- $root.find('[data-col="' + col + '"]').addClass('focus-auto-hidden');
- }
- });
- }
- let searchDebounce = null;
- $root.on('input', '[data-task-search]', function () {
- clearTimeout(searchDebounce);
- searchDebounce = setTimeout(applyFilters, 120);
- });
- $root.on('change', '[data-prio-filter]', applyFilters);
- $root.on('change', '[data-focus-select]', function () {
- focusWorker = String($(this).val() || '');
- persistFocus();
- applyFilters();
- });
- // --- Column visibility toggle (persisted in localStorage) --------------
- const columnsKey = 'sp:' + sprintId + ':hiddenCols' + keySuffix;
- /** @type {Set<string>} */
- const hiddenCols = (function () {
- try {
- const raw = window.localStorage.getItem(columnsKey);
- if (raw) {
- const arr = JSON.parse(raw);
- if (Array.isArray(arr)) { return new Set(arr.map(String)); }
- }
- // Phase 15: first-time-ever in beamer mode seeds the hidden set
- // with the non-discussion columns so the task table fits the
- // viewport at 1920×1080. User toggles from the Columns dropdown
- // persist from then on — we only seed when the key is missing.
- if (isBeamer) {
- const defaults = ['owner', 'prio', 'tot'];
- window.localStorage.setItem(columnsKey, JSON.stringify(defaults));
- return new Set(defaults);
- }
- } catch (_) { /* ignore */ }
- return new Set();
- })();
- function persistHiddenCols() {
- try {
- window.localStorage.setItem(columnsKey, JSON.stringify(Array.from(hiddenCols)));
- } catch (_) { /* ignore */ }
- }
- function applyColumnVisibility() {
- // Tailwind's .hidden is display:none; works on table cells.
- $root.find('[data-col]').each(function () {
- const col = String($(this).attr('data-col'));
- $(this).toggleClass('hidden', hiddenCols.has(col));
- });
- // Reflect state into the Columns dropdown checkboxes.
- $root.find('[data-column-opt]').each(function () {
- $(this).prop('checked', !hiddenCols.has(String($(this).val())));
- });
- }
- $root.on('change', '[data-column-opt]', function () {
- const v = String($(this).val());
- if ($(this).is(':checked')) { hiddenCols.delete(v); } else { hiddenCols.add(v); }
- persistHiddenCols();
- applyColumnVisibility();
- updateResetVisibility();
- });
- // --- Reset button (clears every filter + column-hide in one click) ----
- function filtersActive() {
- const q = String($root.find('[data-task-search]').val() || '').trim();
- const prio = String($root.find('[data-prio-filter]').val() || '');
- return q !== ''
- || prio !== ''
- || ownerFilterSet.size > 0
- || String(focusWorker || '') !== ''
- || hiddenCols.size > 0
- || (taskStatusEnabled && statusFilterSet.size > 0);
- }
- function updateResetVisibility() {
- $root.find('[data-reset-filters]').toggleClass('hidden', !filtersActive());
- }
- $root.on('click', '[data-reset-filters]', function () {
- $root.find('[data-task-search]').val('');
- $root.find('[data-prio-filter]').val('');
- ownerFilterSet.clear();
- persistOwnerFilter();
- focusWorker = '';
- persistFocus();
- hiddenCols.clear();
- persistHiddenCols();
- if (taskStatusEnabled) {
- statusFilterSet.clear();
- persistStatusFilter();
- }
- updateOwnerFilterUi();
- updateFocusUi();
- if (taskStatusEnabled) { updateStatusFilterUi(); }
- applyColumnVisibility();
- applyFilters();
- });
- $root.on('click', '[data-columns-trigger]', function (ev) {
- ev.stopPropagation();
- $root.find('[data-owner-filter-dropdown]').addClass('hidden');
- $root.find('[data-columns-dropdown]').toggleClass('hidden');
- });
- // Close either dropdown when clicking outside.
- $(document).on('click', function (ev) {
- if ($(ev.target).closest('[data-owner-filter-root]').length === 0) {
- $root.find('[data-owner-filter-dropdown]').addClass('hidden');
- }
- if ($(ev.target).closest('[data-columns-root]').length === 0) {
- $root.find('[data-columns-dropdown]').addClass('hidden');
- }
- if ($(ev.target).closest('[data-status-filter-root]').length === 0) {
- $root.find('[data-status-filter-dropdown]').addClass('hidden');
- }
- });
- // --- Column sort (client-side) ----------------------------------------
- const currentSort = { col: null, dir: null }; // dir: 'asc' | 'desc'
- function clearSort() {
- currentSort.col = null; currentSort.dir = null;
- $root.find('[data-sort-col]').each(function () {
- $(this).find('.sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
- });
- // Restore original order by data-sort-order
- const rows = $taskTbody.children('tr[data-task-row]').get();
- rows.sort(function (a, b) {
- return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
- });
- rows.forEach(function (el) { $taskTbody.append(el); });
- }
- function rowValueFor(col, $row) {
- if (col === 'title') {
- return String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
- }
- if (col === 'owner') {
- const id = String($row.attr('data-owner') || '');
- if (id === '') { return '\uFFFF'; } // sort empty last
- const opt = $row.find('[data-owner-select] option:selected');
- return String(opt.text() || '').toLowerCase();
- }
- if (col === 'prio') { return Number($row.attr('data-prio')); }
- if (col === 'tot') { return Number($row.find('[data-task-tot]').text()) || 0; }
- if (col.indexOf('sw-') === 0) {
- const swId = col.slice(3);
- return Number($row.find('[data-assign][data-sw-id="' + swId + '"]').val()) || 0;
- }
- return 0;
- }
- function applySort(col) {
- let dir;
- if (currentSort.col !== col) { dir = 'asc'; }
- else if (currentSort.dir === 'asc') { dir = 'desc'; }
- else { clearSort(); return; } // third click clears
- currentSort.col = col;
- currentSort.dir = dir;
- $root.find('[data-sort-col] .sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
- $root.find('[data-sort-col="' + col + '"] .sort-ind')
- .text(dir === 'asc' ? '↑' : '↓')
- .removeClass('opacity-30').addClass('opacity-100');
- const rows = $taskTbody.children('tr[data-task-row]').get();
- rows.sort(function (a, b) {
- const va = rowValueFor(col, $(a));
- const vb = rowValueFor(col, $(b));
- if (va < vb) { return dir === 'asc' ? -1 : 1; }
- if (va > vb) { return dir === 'asc' ? 1 : -1; }
- // Stable-ish tiebreak: fall back to data-sort-order
- return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
- });
- rows.forEach(function (el) { $taskTbody.append(el); });
- }
- $root.on('click', '[data-sort-col]', function () {
- applySort(String($(this).attr('data-sort-col')));
- });
- // =====================================================================
- // Boot
- // =====================================================================
- // Recompute once at boot in case the server-rendered sums drift from the
- // JS formula (e.g. after a stale reload).
- $root.find('[data-sw-row]').each(function () {
- recomputeRow(parseInt($(this).data('sw-id'), 10));
- });
- // Restore persisted task-list UI state BEFORE applyFilters so hidden
- // columns don't briefly flash in before being toggled off.
- updateOwnerFilterUi();
- updateFocusUi();
- if (taskStatusEnabled) { updateStatusFilterUi(); }
- applyColumnVisibility();
- applyFilters();
- // Reset button visibility is a function of every filter; applyFilters
- // already calls updateResetVisibility, but call it once more at boot
- // in case the tbody is empty (applyFilters short-circuits nothing,
- // but this is defensive).
- updateResetVisibility();
- // Phase 15: in beamer mode, if the rendered task table is wider than
- // its scroll container, rotate worker-column headers to vertical.
- // Measure once after the first applyFilters() run (inputs laid out,
- // hidden columns collapsed) and escalate a single step — horizontal
- // scroll is a fallback but never a spinlock.
- if (isBeamer && hasTaskUi) {
- const table = $root.find('[data-task-table]').get(0);
- const container = table ? table.parentElement : null;
- if (table && container && table.scrollWidth > container.clientWidth) {
- $root.addClass('beamer-vertical-headers');
- if (table.scrollWidth > container.clientWidth) {
- // eslint-disable-next-line no-console
- console.warn('[sprint-planner] beamer: table still overflows after vertical headers; horizontal scroll enabled.');
- }
- }
- }
- })(jQuery);
|