| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142 |
- /* 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));
- // Phase 18: when the feature is enabled the status attrs +
- // colour class go directly on the <td>. New rows always start
- // at the default status (no nested wrapper).
- if (taskStatusEnabled) {
- $td.addClass('assign-status-zugewiesen')
- .attr('data-assign-cell', '')
- .attr('data-status', 'zugewiesen')
- .attr('data-sw-id', sw.id);
- }
- $td.append(
- $('<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) {
- 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');
- $td.append($status);
- }
- $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 + audit semantics as the days pipeline (one row per changed
- // cell). Skipped entirely when the feature flag is off.
- 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); });
- }
- // Status change handler — only attach when the feature is on, and bail
- // defensively if the cell doesn't carry the data attributes we expect
- // (e.g. on a partially-rendered task row right after `+ Add task`).
- if (taskStatusEnabled) {
- $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]');
- if ($cell.length === 0) { return; }
- const $tr = $sel.closest('tr');
- const taskId = parseInt($tr.attr('data-task-id'), 10);
- const swId = parseInt($sel.attr('data-sw-id'), 10);
- if (!Number.isFinite(taskId) || !Number.isFinite(swId)) { return; }
- // Swap the cell's colour class + data-status. Done first so the
- // visual flip is instant; the server save is debounced.
- STATUSES.forEach(function (s) { $cell.removeClass('assign-status-' + s); });
- $cell.addClass('assign-status-' + next);
- $cell.attr('data-status', next);
- queueStatus(taskId, swId, next);
- 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);
|