sprint-planner.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. /* global jQuery */
  2. /**
  3. * Main planning view (/sprints/{id}) — Section A: Arbeitstage grid.
  4. *
  5. * Behaviours:
  6. * - Day cells (per worker, per week) snap to 0.5 on blur, batch-saved via
  7. * PATCH /sprints/{id}/week-cells with 400 ms debounce.
  8. * - The Arbeitstage header row is derived from the weekday selection in
  9. * Sprint Settings — it's read-only here (Phase 12).
  10. * - RTB inputs snap to 0.05 on blur, saved via PATCH /sprints/{id}/workers/{sw_id}.
  11. * - Worker rows are sortable (jQuery UI). Drop posts to
  12. * POST /sprints/{id}/workers/reorder.
  13. *
  14. * All capacity values are recomputed client-side with the same formula as
  15. * `App\Services\CapacityCalculator` so the UI stays in sync without waiting
  16. * for the server response.
  17. */
  18. (function ($) {
  19. 'use strict';
  20. const $root = $('[data-sprint-root]');
  21. if ($root.length === 0) { return; }
  22. const sprintId = parseInt($root.data('sprint-id'), 10);
  23. const csrf = String($root.data('csrf') || '');
  24. const reserveFraction = Number($root.data('reserve-fraction') || 0);
  25. // Phase 15: the presentation view stamps data-beamer="1" on the root so
  26. // we can namespace its localStorage keys (don't clobber the user's
  27. // workflow on /sprints/{id}) and flip on vertical-header rotation if
  28. // the task table overflows after the first filter pass.
  29. const isBeamer = Number($root.data('beamer')) === 1;
  30. const keySuffix = isBeamer ? ':beamer' : '';
  31. // ---------------------------------------------------------------------
  32. // Capacity math — MUST match App\Services\CapacityCalculator
  33. // ---------------------------------------------------------------------
  34. function roundHalf(x) { return Math.round(x * 2) / 2; }
  35. function snap05(x) { return roundHalf(x); }
  36. function snap005(x) { return Math.round(x * 20) / 20; }
  37. function fmtDays(x) {
  38. const n = Number(x);
  39. if (Math.abs(n - Math.round(n)) < 1e-9) { return String(Math.round(n)); }
  40. return n.toFixed(1);
  41. }
  42. function fmtRtb(x) { return Number(x).toFixed(2); }
  43. function capacity(ressourcen, committedPrio1) {
  44. committedPrio1 = committedPrio1 || 0;
  45. const afterReserves = roundHalf(ressourcen * (1 - reserveFraction));
  46. const available = afterReserves - committedPrio1;
  47. return { ressourcen, afterReserves, committedPrio1, available };
  48. }
  49. // Sum of prio-1 task assignment cells per sprint worker, read from DOM.
  50. function committedPrio1FromDom() {
  51. const per = {};
  52. $root.find('tr[data-task-row]').each(function () {
  53. const $row = $(this);
  54. if (parseInt($row.attr('data-prio'), 10) !== 1) { return; }
  55. $row.find('[data-assign]').each(function () {
  56. const key = String($(this).data('sw-id'));
  57. const v = Number($(this).val());
  58. if (!Number.isNaN(v) && v > 0) {
  59. per[key] = (per[key] || 0) + v;
  60. }
  61. });
  62. });
  63. return per;
  64. }
  65. // ---------------------------------------------------------------------
  66. // HTTP helper — spec §7 envelopes
  67. // ---------------------------------------------------------------------
  68. function request(method, url, body) {
  69. const opts = {
  70. method,
  71. headers: {
  72. Accept: 'application/json',
  73. 'X-CSRF-Token': csrf,
  74. },
  75. credentials: 'same-origin',
  76. };
  77. if (body !== undefined) {
  78. opts.headers['Content-Type'] = 'application/json';
  79. opts.body = JSON.stringify(body);
  80. }
  81. return fetch(url, opts).then(async function (res) {
  82. let payload = null;
  83. try { payload = await res.json(); } catch (_) { /* ignore */ }
  84. if (!res.ok || !payload || payload.ok !== true) {
  85. const msg = (payload && payload.error && payload.error.message)
  86. ? payload.error.message
  87. : res.statusText || 'Request failed';
  88. const err = new Error(msg);
  89. err.status = res.status;
  90. err.payload = payload;
  91. throw err;
  92. }
  93. return payload.data;
  94. });
  95. }
  96. // ---------------------------------------------------------------------
  97. // Status line (shared with settings page styling)
  98. // ---------------------------------------------------------------------
  99. const $status = $root.find('[data-status]');
  100. let statusTimer = null;
  101. function flash(text, isError) {
  102. $status
  103. .text(text)
  104. .removeClass('text-green-700 text-red-700 bg-green-50 bg-red-50 border-green-200 border-red-200')
  105. .addClass(isError ? 'text-red-700 bg-red-50 border-red-200' : 'text-green-700 bg-green-50 border-green-200')
  106. .removeClass('opacity-0').addClass('opacity-100');
  107. clearTimeout(statusTimer);
  108. statusTimer = setTimeout(function () {
  109. $status.removeClass('opacity-100').addClass('opacity-0');
  110. }, 2500);
  111. }
  112. // ---------------------------------------------------------------------
  113. // Recompute worker row sum + capacity summary locally
  114. // ---------------------------------------------------------------------
  115. function recomputeRow(swId, commitMap) {
  116. const $row = $root.find('[data-sw-row][data-sw-id="' + swId + '"]');
  117. let sum = 0;
  118. $row.find('[data-day]').each(function () {
  119. const v = Number($(this).val());
  120. if (!Number.isNaN(v)) { sum += v; }
  121. });
  122. const committed = (commitMap || committedPrio1FromDom())[String(swId)] || 0;
  123. const cap = capacity(sum, committed);
  124. $row.find('[data-sum-days]').text(fmtDays(cap.ressourcen));
  125. $root.find('[data-cap-ressourcen][data-sw-id="' + swId + '"]').text(fmtDays(cap.ressourcen));
  126. $root.find('[data-cap-after-reserves][data-sw-id="' + swId + '"]').text(fmtDays(cap.afterReserves));
  127. const $avail = $root.find('[data-cap-available][data-sw-id="' + swId + '"]');
  128. $avail.text(fmtDays(cap.available));
  129. if (cap.available < 0) {
  130. $avail.removeClass('text-slate-900').addClass('text-red-700');
  131. } else {
  132. $avail.removeClass('text-red-700').addClass('text-slate-900');
  133. }
  134. }
  135. // Recompute every worker row (capacity summary) — called when a task-side
  136. // change might affect committed prio-1 values.
  137. function recomputeAllCapacity() {
  138. const commit = committedPrio1FromDom();
  139. $root.find('[data-sw-row]').each(function () {
  140. recomputeRow(parseInt($(this).data('sw-id'), 10), commit);
  141. });
  142. }
  143. // ---------------------------------------------------------------------
  144. // Pending-cell queue, debounced batch save
  145. // ---------------------------------------------------------------------
  146. // key = "swId:weekId" → { sw_id, week_id, days }
  147. const pendingCells = new Map();
  148. let cellDebounce = null;
  149. function queueCell(swId, weekId, days) {
  150. pendingCells.set(swId + ':' + weekId, {
  151. sprint_worker_id: swId,
  152. sprint_week_id: weekId,
  153. days: days,
  154. });
  155. clearTimeout(cellDebounce);
  156. cellDebounce = setTimeout(flushCells, 400);
  157. }
  158. function flushCells() {
  159. if (pendingCells.size === 0) { return; }
  160. const cells = Array.from(pendingCells.values());
  161. pendingCells.clear();
  162. request('PATCH', '/sprints/' + sprintId + '/week-cells', cells)
  163. .then(function (data) {
  164. if (data.applied === 0 && data.noop > 0) {
  165. flash('No changes');
  166. } else {
  167. flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells'));
  168. }
  169. // Trust the server's capacity numbers — same formula, but a
  170. // safety net if an input was tampered with.
  171. if (data.per_worker && typeof data.per_worker === 'object') {
  172. Object.keys(data.per_worker).forEach(function (swIdStr) {
  173. const c = data.per_worker[swIdStr];
  174. $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
  175. $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
  176. const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
  177. $av.text(fmtDays(c.available));
  178. if (c.available < 0) {
  179. $av.removeClass('text-slate-900').addClass('text-red-700');
  180. } else {
  181. $av.removeClass('text-red-700').addClass('text-slate-900');
  182. }
  183. $root.find('[data-sw-row][data-sw-id="' + swIdStr + '"] [data-sum-days]').text(fmtDays(c.ressourcen));
  184. });
  185. }
  186. })
  187. .catch(function (e) { flash(e.message, true); });
  188. }
  189. // ---------------------------------------------------------------------
  190. // Day cells
  191. // ---------------------------------------------------------------------
  192. $root.on('blur change', '[data-day]', function () {
  193. const $el = $(this);
  194. let v = Number($el.val());
  195. if (Number.isNaN(v)) { v = 0; }
  196. if (v < 0) { v = 0; }
  197. if (v > 5) { v = 5; }
  198. v = snap05(v);
  199. $el.val(fmtDays(v));
  200. const swId = parseInt($el.data('sw-id'), 10);
  201. const weekId = parseInt($el.data('week-id'), 10);
  202. queueCell(swId, weekId, v);
  203. recomputeRow(swId);
  204. });
  205. // ---------------------------------------------------------------------
  206. // Per-row RTB edit
  207. // ---------------------------------------------------------------------
  208. $root.on('blur change', '[data-rtb]', function () {
  209. const $el = $(this);
  210. let v = Number($el.val());
  211. if (Number.isNaN(v)) { v = 0; }
  212. if (v < 0) { v = 0; }
  213. if (v > 1) { v = 1; }
  214. v = snap005(v);
  215. $el.val(fmtRtb(v));
  216. const swId = parseInt($el.data('sw-id'), 10);
  217. request('PATCH', '/sprints/' + sprintId + '/workers/' + swId, { rtb: v })
  218. .then(function () { flash('Saved'); })
  219. .catch(function (e) { flash(e.message, true); });
  220. });
  221. // ---------------------------------------------------------------------
  222. // Worker row drag-reorder (admin only — tbody only exists with handles)
  223. // ---------------------------------------------------------------------
  224. const sortableAvailable = typeof $.fn.sortable === 'function';
  225. if (!sortableAvailable) {
  226. // jQuery UI didn't load (SRI mismatch, offline CDN, ad blocker).
  227. // Drag-reorder is unavailable but the rest of the page still works.
  228. // eslint-disable-next-line no-console
  229. console.warn('[sprint-planner] jQuery UI not loaded — drag reorder disabled.');
  230. }
  231. const $tbody = $root.find('[data-tbody]');
  232. if (sortableAvailable && $tbody.find('.handle').length > 0) {
  233. $tbody.sortable({
  234. handle: '.handle',
  235. items: 'tr[data-sw-row]',
  236. axis: 'y',
  237. helper: function (e, tr) {
  238. // Preserve the td widths so the row doesn't collapse while dragging.
  239. const $cells = tr.children();
  240. const $clone = tr.clone();
  241. $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
  242. return $clone;
  243. },
  244. update: function () {
  245. const ordering = $tbody.find('tr[data-sw-row]').map(function (i, el) {
  246. return {
  247. sprint_worker_id: parseInt($(el).data('sw-id'), 10),
  248. sort_order: i + 1,
  249. };
  250. }).get();
  251. request('POST', '/sprints/' + sprintId + '/workers/reorder', ordering)
  252. .then(function (data) {
  253. if (data.moved) {
  254. // Column order in the task list below depends on
  255. // this ordering — simplest to re-render.
  256. window.location.reload();
  257. } else {
  258. flash('No changes');
  259. }
  260. })
  261. .catch(function (e) { flash(e.message, true); });
  262. },
  263. });
  264. }
  265. // =====================================================================
  266. // Task list — create/edit/delete/reorder + assignments + filter/sort
  267. // =====================================================================
  268. const $taskTbody = $root.find('[data-task-tbody]');
  269. const hasTaskUi = $taskTbody.length > 0;
  270. // --- Worker/owner helpers read from the DOM once ----------------------
  271. function sprintWorkerHeaders() {
  272. const out = [];
  273. $root.find('[data-task-table] thead th[data-sort-col^="sw-"]').each(function () {
  274. const col = String($(this).attr('data-sort-col'));
  275. out.push({
  276. id: parseInt(col.slice(3), 10),
  277. name: $(this).clone().children().remove().end().text().trim(),
  278. });
  279. });
  280. return out;
  281. }
  282. function ownerChoices() {
  283. const out = [];
  284. $root.find('[data-owner-filter] option').each(function () {
  285. const v = $(this).val();
  286. if (v === '' || v === '__none__') { return; }
  287. out.push({ id: parseInt(String(v), 10), name: String($(this).text()).trim() });
  288. });
  289. return out;
  290. }
  291. // --- Build a task row <tr> from an object ----------------------------
  292. function buildTaskRow(task, assignments) {
  293. assignments = assignments || {};
  294. const $tr = $('<tr>')
  295. .attr('data-task-row', '')
  296. .attr('data-task-id', task.id)
  297. .attr('data-prio', task.priority)
  298. .attr('data-owner', task.owner_worker_id || '')
  299. .attr('data-sort-order', task.sort_order);
  300. // handle
  301. $tr.append($('<td class="px-2 py-1"></td>').append(
  302. $('<span class="handle cursor-grab text-slate-400 select-none">').html('&#8801;')
  303. ));
  304. // title
  305. $tr.append(
  306. $('<td class="px-2 py-1 min-w-[14rem]"></td>').append(
  307. $('<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">')
  308. .val(task.title)
  309. )
  310. );
  311. // owner
  312. 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">');
  313. $sel.append('<option value="">—</option>');
  314. ownerChoices().forEach(function (o) {
  315. const $opt = $('<option>').val(o.id).text(o.name);
  316. if (Number(o.id) === Number(task.owner_worker_id)) { $opt.attr('selected', 'selected'); }
  317. $sel.append($opt);
  318. });
  319. $tr.append($('<td class="px-2 py-1" data-col="owner"></td>').append($sel));
  320. // priority
  321. 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>');
  322. $prio.val(String(task.priority));
  323. $tr.append($('<td class="px-2 py-1 text-center" data-col="prio"></td>').append($prio));
  324. // tot
  325. let tot = 0;
  326. Object.keys(assignments).forEach(function (k) { tot += Number(assignments[k]) || 0; });
  327. $tr.append($('<td class="px-2 py-1 text-center font-mono font-semibold" data-col="tot" data-task-tot>').text(fmtDays(tot)));
  328. // per-worker assignment cells
  329. sprintWorkerHeaders().forEach(function (sw) {
  330. const v = Number(assignments[sw.id] || 0);
  331. const $td = $('<td class="px-1 py-1 text-center"></td>')
  332. .attr('data-col', 'sw-' + sw.id)
  333. .attr('data-sort-value-sw-' + sw.id, v.toFixed(2));
  334. $td.append(
  335. $('<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">')
  336. .val(fmtDays(v))
  337. .attr('data-sw-id', sw.id)
  338. );
  339. $tr.append($td);
  340. });
  341. // delete
  342. $tr.append(
  343. $('<td class="px-1 py-1 text-right"></td>').append(
  344. $('<button type="button" data-delete-task class="text-sm text-red-600 hover:underline">').text('×')
  345. )
  346. );
  347. return $tr;
  348. }
  349. // --- Add task ---------------------------------------------------------
  350. $root.on('click', '[data-add-task]', function () {
  351. request('POST', '/sprints/' + sprintId + '/tasks', { title: '', priority: 1 })
  352. .then(function (data) {
  353. $root.find('[data-empty-tasks]').remove();
  354. const $row = buildTaskRow(data.task, data.assignments || {});
  355. $taskTbody.append($row);
  356. // Clear any active sort so the new row is actually visible at the end.
  357. clearSort();
  358. applyColumnVisibility();
  359. applyFilters();
  360. $row.find('[data-title]').trigger('focus').trigger('select');
  361. flash('Task added');
  362. })
  363. .catch(function (e) { flash(e.message, true); });
  364. });
  365. // --- Edit task fields (title / owner / prio) --------------------------
  366. const titleDebounce = {};
  367. $root.on('input', '[data-title]', function () {
  368. const $inp = $(this);
  369. const taskId = parseInt($inp.closest('tr').data('task-id'), 10);
  370. clearTimeout(titleDebounce[taskId]);
  371. titleDebounce[taskId] = setTimeout(function () {
  372. const title = String($inp.val()).trim();
  373. if (title === '') {
  374. flash('Title cannot be empty', true);
  375. return;
  376. }
  377. request('PATCH', '/tasks/' + taskId, { title: title })
  378. .then(function () { flash('Saved'); })
  379. .catch(function (e) { flash(e.message, true); });
  380. }, 400);
  381. });
  382. $root.on('change', '[data-owner-select]', function () {
  383. const $sel = $(this);
  384. const $row = $sel.closest('tr');
  385. const taskId = parseInt($row.data('task-id'), 10);
  386. const v = $sel.val();
  387. const owner = v === '' ? null : parseInt(String(v), 10);
  388. $row.attr('data-owner', owner === null ? '' : owner);
  389. request('PATCH', '/tasks/' + taskId, { owner_worker_id: owner })
  390. .then(function () { flash('Saved'); applyFilters(); })
  391. .catch(function (e) { flash(e.message, true); });
  392. });
  393. $root.on('change', '[data-prio-select]', function () {
  394. const $sel = $(this);
  395. const $row = $sel.closest('tr');
  396. const taskId = parseInt($row.data('task-id'), 10);
  397. const prio = parseInt(String($sel.val()), 10);
  398. $row.attr('data-prio', prio);
  399. request('PATCH', '/tasks/' + taskId, { priority: prio })
  400. .then(function (data) {
  401. flash('Saved');
  402. applyFilters();
  403. applyServerCapacity(data && data.per_worker);
  404. recomputeAllCapacity();
  405. })
  406. .catch(function (e) { flash(e.message, true); });
  407. });
  408. // --- Delete task ------------------------------------------------------
  409. $root.on('click', '[data-delete-task]', function () {
  410. const $row = $(this).closest('tr');
  411. const taskId = parseInt($row.data('task-id'), 10);
  412. const title = $row.find('[data-title]').val() || '(untitled)';
  413. if (!window.confirm('Delete task "' + title + '"?')) { return; }
  414. request('DELETE', '/tasks/' + taskId)
  415. .then(function (data) {
  416. $row.remove();
  417. applyServerCapacity(data && data.per_worker);
  418. recomputeAllCapacity();
  419. flash('Task deleted');
  420. if ($taskTbody.children('tr[data-task-row]').length === 0) {
  421. // Re-show the empty-state row (simpler than templating).
  422. window.location.reload();
  423. }
  424. })
  425. .catch(function (e) { flash(e.message, true); });
  426. });
  427. // --- Assignment cells (per task, per sprint worker) -------------------
  428. // Same shape as the Arbeitstage cell queue, but against /tasks/{id}/assignments.
  429. const pendingAssign = new Map(); // taskId -> Map<swId, days>
  430. const assignTimers = {};
  431. function queueAssign(taskId, swId, days) {
  432. if (!pendingAssign.has(taskId)) { pendingAssign.set(taskId, new Map()); }
  433. pendingAssign.get(taskId).set(swId, days);
  434. clearTimeout(assignTimers[taskId]);
  435. assignTimers[taskId] = setTimeout(function () { flushAssign(taskId); }, 400);
  436. }
  437. function flushAssign(taskId) {
  438. const m = pendingAssign.get(taskId);
  439. if (!m || m.size === 0) { return; }
  440. const cells = [];
  441. m.forEach(function (days, swId) {
  442. cells.push({ sprint_worker_id: swId, days: days });
  443. });
  444. pendingAssign.delete(taskId);
  445. request('PATCH', '/tasks/' + taskId + '/assignments', cells)
  446. .then(function (data) {
  447. if (data.applied === 0 && data.noop > 0) { flash('No changes'); }
  448. else { flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells')); }
  449. applyServerCapacity(data && data.per_worker);
  450. })
  451. .catch(function (e) { flash(e.message, true); });
  452. }
  453. $root.on('blur change', '[data-assign]', function () {
  454. const $el = $(this);
  455. let v = Number($el.val());
  456. if (Number.isNaN(v) || v < 0) { v = 0; }
  457. v = snap05(v);
  458. $el.val(fmtDays(v));
  459. $el.closest('td').attr('data-sort-value-sw-' + $el.data('sw-id'), v.toFixed(2));
  460. const taskId = parseInt($el.closest('tr').data('task-id'), 10);
  461. const swId = parseInt($el.data('sw-id'), 10);
  462. queueAssign(taskId, swId, v);
  463. // Row total
  464. let tot = 0;
  465. $el.closest('tr').find('[data-assign]').each(function () {
  466. const n = Number($(this).val());
  467. if (!Number.isNaN(n)) { tot += n; }
  468. });
  469. $el.closest('tr').find('[data-task-tot]').text(fmtDays(tot));
  470. // Available recompute (in case this is a prio-1 task)
  471. recomputeAllCapacity();
  472. });
  473. function applyServerCapacity(perWorker) {
  474. if (!perWorker || typeof perWorker !== 'object') { return; }
  475. Object.keys(perWorker).forEach(function (swIdStr) {
  476. const c = perWorker[swIdStr];
  477. $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
  478. $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
  479. const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
  480. $av.text(fmtDays(c.available));
  481. if (c.available < 0) {
  482. $av.removeClass('text-slate-900').addClass('text-red-700');
  483. } else {
  484. $av.removeClass('text-red-700').addClass('text-slate-900');
  485. }
  486. });
  487. }
  488. // --- Task reorder (drag) ----------------------------------------------
  489. if (sortableAvailable && hasTaskUi && $taskTbody.find('.handle').length > 0) {
  490. $taskTbody.sortable({
  491. handle: '.handle',
  492. items: 'tr[data-task-row]',
  493. axis: 'y',
  494. helper: function (e, tr) {
  495. const $cells = tr.children();
  496. const $clone = tr.clone();
  497. $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
  498. return $clone;
  499. },
  500. start: function () {
  501. // Drag only makes sense when no sort is active.
  502. if (currentSort.col !== null) { clearSort(); }
  503. },
  504. update: function () {
  505. const ordering = $taskTbody.find('tr[data-task-row]').map(function (i, el) {
  506. return { task_id: parseInt($(el).data('task-id'), 10), sort_order: i + 1 };
  507. }).get();
  508. request('POST', '/sprints/' + sprintId + '/tasks/reorder', ordering)
  509. .then(function (data) {
  510. ordering.forEach(function (o) {
  511. $taskTbody.find('tr[data-task-id="' + o.task_id + '"]').attr('data-sort-order', o.sort_order);
  512. });
  513. flash(data.moved ? 'Order saved' : 'No changes');
  514. })
  515. .catch(function (e) { flash(e.message, true); });
  516. },
  517. });
  518. }
  519. // --- Multi-select owner filter (persisted in localStorage) -------------
  520. const ownerFilterKey = 'sp:' + sprintId + ':ownerFilter' + keySuffix;
  521. /** @type {Set<string>} */
  522. const ownerFilterSet = (function () {
  523. try {
  524. const raw = window.localStorage.getItem(ownerFilterKey);
  525. if (raw) {
  526. const arr = JSON.parse(raw);
  527. if (Array.isArray(arr)) { return new Set(arr.map(String)); }
  528. }
  529. } catch (_) { /* ignore */ }
  530. return new Set();
  531. })();
  532. function persistOwnerFilter() {
  533. try {
  534. window.localStorage.setItem(ownerFilterKey, JSON.stringify(Array.from(ownerFilterSet)));
  535. } catch (_) { /* ignore quota / private mode */ }
  536. }
  537. function updateOwnerFilterUi() {
  538. // Reflect state back into the checkboxes.
  539. $root.find('[data-owner-filter-opt]').each(function () {
  540. $(this).prop('checked', ownerFilterSet.has(String($(this).val())));
  541. });
  542. // Count label on the trigger.
  543. const n = ownerFilterSet.size;
  544. $root.find('[data-owner-filter-count]').text(n === 0 ? '' : '(' + n + ')');
  545. }
  546. $root.on('change', '[data-owner-filter-opt]', function () {
  547. const v = String($(this).val());
  548. if ($(this).is(':checked')) { ownerFilterSet.add(v); } else { ownerFilterSet.delete(v); }
  549. persistOwnerFilter();
  550. updateOwnerFilterUi();
  551. applyFilters();
  552. });
  553. $root.on('click', '[data-owner-filter-clear]', function () {
  554. ownerFilterSet.clear();
  555. persistOwnerFilter();
  556. updateOwnerFilterUi();
  557. applyFilters();
  558. });
  559. $root.on('click', '[data-owner-filter-trigger]', function (ev) {
  560. ev.stopPropagation();
  561. $root.find('[data-columns-dropdown]').addClass('hidden');
  562. $root.find('[data-owner-filter-dropdown]').toggleClass('hidden');
  563. });
  564. // --- Focus filter (single sprint worker, persisted) -------------------
  565. const focusKey = 'sp:' + sprintId + ':focusWorker' + keySuffix;
  566. let focusWorker = (function () {
  567. try {
  568. const raw = window.localStorage.getItem(focusKey);
  569. if (raw === null) { return ''; }
  570. return String(raw);
  571. } catch (_) { return ''; }
  572. })();
  573. function persistFocus() {
  574. try { window.localStorage.setItem(focusKey, String(focusWorker)); }
  575. catch (_) { /* ignore */ }
  576. }
  577. function updateFocusUi() {
  578. const $sel = $root.find('[data-focus-select]');
  579. if ($sel.length === 0) { return; }
  580. // If the stored worker is no longer a sprint member, fall back to "".
  581. if (focusWorker !== '' && $sel.find('option[value="' + focusWorker + '"]').length === 0) {
  582. focusWorker = '';
  583. persistFocus();
  584. }
  585. $sel.val(focusWorker);
  586. }
  587. // --- Filters (search / prio / owner / focus) --------------------------
  588. function applyFilters() {
  589. const q = String($root.find('[data-task-search]').val() || '').trim().toLowerCase();
  590. const prio = String($root.find('[data-prio-filter]').val() || '');
  591. const focus = String(focusWorker || '');
  592. let visibleCount = 0;
  593. $taskTbody.children('tr[data-task-row]').each(function () {
  594. const $row = $(this);
  595. const title = String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
  596. const rowPrio = String($row.attr('data-prio'));
  597. const rowOwner = String($row.attr('data-owner') || '');
  598. // The filter set treats "" (no owner) as the special "__none__" key.
  599. const ownerKey = rowOwner === '' ? '__none__' : rowOwner;
  600. let ok = true;
  601. if (q !== '' && !title.includes(q)) { ok = false; }
  602. if (prio !== '' && rowPrio !== prio) { ok = false; }
  603. if (ownerFilterSet.size > 0 && !ownerFilterSet.has(ownerKey)) { ok = false; }
  604. if (focus !== '') {
  605. // Zero-tolerance matches capacity math: treat 0 / 0.0 / empty
  606. // as "no assignment" (Number(v) > 0, not !== 0).
  607. const v = Number($row.find('[data-assign][data-sw-id="' + focus + '"]').val());
  608. if (!(v > 0)) { ok = false; }
  609. }
  610. $row.toggle(ok);
  611. if (ok) { visibleCount++; }
  612. });
  613. const totalRows = $taskTbody.children('tr[data-task-row]').length;
  614. $root.find('[data-task-empty-filter]').toggle(totalRows > 0 && visibleCount === 0);
  615. applyFocusColumnVisibility();
  616. updateResetVisibility();
  617. }
  618. // Column auto-hide: when a focus worker is selected, any sw column that
  619. // is all-zero for the currently visible rows collapses. We tag cells
  620. // with `.focus-auto-hidden` rather than mutating `hiddenCols` so that
  621. // clearing Focus restores whatever the user picked in the Columns
  622. // dropdown.
  623. function applyFocusColumnVisibility() {
  624. // Always clear the transient class first — keeps the function
  625. // idempotent and correct when focus goes from set → "".
  626. $root.find('.focus-auto-hidden').removeClass('focus-auto-hidden');
  627. if (!focusWorker) { return; }
  628. // Walk every sw column. If no currently visible row has a > 0
  629. // assignment for that sw, hide every `[data-col="sw-{id}"]` cell.
  630. $root.find('[data-task-table] thead th[data-sort-col^="sw-"]').each(function () {
  631. const col = String($(this).attr('data-sort-col')); // e.g. "sw-42"
  632. const swId = col.slice(3);
  633. let anyNonZero = false;
  634. $taskTbody.children('tr[data-task-row]:visible').each(function () {
  635. const v = Number($(this).find('[data-assign][data-sw-id="' + swId + '"]').val());
  636. if (v > 0) { anyNonZero = true; return false; /* break */ }
  637. });
  638. if (!anyNonZero) {
  639. $root.find('[data-col="' + col + '"]').addClass('focus-auto-hidden');
  640. }
  641. });
  642. }
  643. let searchDebounce = null;
  644. $root.on('input', '[data-task-search]', function () {
  645. clearTimeout(searchDebounce);
  646. searchDebounce = setTimeout(applyFilters, 120);
  647. });
  648. $root.on('change', '[data-prio-filter]', applyFilters);
  649. $root.on('change', '[data-focus-select]', function () {
  650. focusWorker = String($(this).val() || '');
  651. persistFocus();
  652. applyFilters();
  653. });
  654. // --- Column visibility toggle (persisted in localStorage) --------------
  655. const columnsKey = 'sp:' + sprintId + ':hiddenCols' + keySuffix;
  656. /** @type {Set<string>} */
  657. const hiddenCols = (function () {
  658. try {
  659. const raw = window.localStorage.getItem(columnsKey);
  660. if (raw) {
  661. const arr = JSON.parse(raw);
  662. if (Array.isArray(arr)) { return new Set(arr.map(String)); }
  663. }
  664. // Phase 15: first-time-ever in beamer mode seeds the hidden set
  665. // with the non-discussion columns so the task table fits the
  666. // viewport at 1920×1080. User toggles from the Columns dropdown
  667. // persist from then on — we only seed when the key is missing.
  668. if (isBeamer) {
  669. const defaults = ['owner', 'prio', 'tot'];
  670. window.localStorage.setItem(columnsKey, JSON.stringify(defaults));
  671. return new Set(defaults);
  672. }
  673. } catch (_) { /* ignore */ }
  674. return new Set();
  675. })();
  676. function persistHiddenCols() {
  677. try {
  678. window.localStorage.setItem(columnsKey, JSON.stringify(Array.from(hiddenCols)));
  679. } catch (_) { /* ignore */ }
  680. }
  681. function applyColumnVisibility() {
  682. // Tailwind's .hidden is display:none; works on table cells.
  683. $root.find('[data-col]').each(function () {
  684. const col = String($(this).attr('data-col'));
  685. $(this).toggleClass('hidden', hiddenCols.has(col));
  686. });
  687. // Reflect state into the Columns dropdown checkboxes.
  688. $root.find('[data-column-opt]').each(function () {
  689. $(this).prop('checked', !hiddenCols.has(String($(this).val())));
  690. });
  691. }
  692. $root.on('change', '[data-column-opt]', function () {
  693. const v = String($(this).val());
  694. if ($(this).is(':checked')) { hiddenCols.delete(v); } else { hiddenCols.add(v); }
  695. persistHiddenCols();
  696. applyColumnVisibility();
  697. updateResetVisibility();
  698. });
  699. // --- Reset button (clears every filter + column-hide in one click) ----
  700. function filtersActive() {
  701. const q = String($root.find('[data-task-search]').val() || '').trim();
  702. const prio = String($root.find('[data-prio-filter]').val() || '');
  703. return q !== ''
  704. || prio !== ''
  705. || ownerFilterSet.size > 0
  706. || String(focusWorker || '') !== ''
  707. || hiddenCols.size > 0;
  708. }
  709. function updateResetVisibility() {
  710. $root.find('[data-reset-filters]').toggleClass('hidden', !filtersActive());
  711. }
  712. $root.on('click', '[data-reset-filters]', function () {
  713. $root.find('[data-task-search]').val('');
  714. $root.find('[data-prio-filter]').val('');
  715. ownerFilterSet.clear();
  716. persistOwnerFilter();
  717. focusWorker = '';
  718. persistFocus();
  719. hiddenCols.clear();
  720. persistHiddenCols();
  721. updateOwnerFilterUi();
  722. updateFocusUi();
  723. applyColumnVisibility();
  724. applyFilters();
  725. });
  726. $root.on('click', '[data-columns-trigger]', function (ev) {
  727. ev.stopPropagation();
  728. $root.find('[data-owner-filter-dropdown]').addClass('hidden');
  729. $root.find('[data-columns-dropdown]').toggleClass('hidden');
  730. });
  731. // Close either dropdown when clicking outside.
  732. $(document).on('click', function (ev) {
  733. if ($(ev.target).closest('[data-owner-filter-root]').length === 0) {
  734. $root.find('[data-owner-filter-dropdown]').addClass('hidden');
  735. }
  736. if ($(ev.target).closest('[data-columns-root]').length === 0) {
  737. $root.find('[data-columns-dropdown]').addClass('hidden');
  738. }
  739. });
  740. // --- Column sort (client-side) ----------------------------------------
  741. const currentSort = { col: null, dir: null }; // dir: 'asc' | 'desc'
  742. function clearSort() {
  743. currentSort.col = null; currentSort.dir = null;
  744. $root.find('[data-sort-col]').each(function () {
  745. $(this).find('.sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
  746. });
  747. // Restore original order by data-sort-order
  748. const rows = $taskTbody.children('tr[data-task-row]').get();
  749. rows.sort(function (a, b) {
  750. return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
  751. });
  752. rows.forEach(function (el) { $taskTbody.append(el); });
  753. }
  754. function rowValueFor(col, $row) {
  755. if (col === 'title') {
  756. return String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
  757. }
  758. if (col === 'owner') {
  759. const id = String($row.attr('data-owner') || '');
  760. if (id === '') { return '\uFFFF'; } // sort empty last
  761. const opt = $row.find('[data-owner-select] option:selected');
  762. return String(opt.text() || '').toLowerCase();
  763. }
  764. if (col === 'prio') { return Number($row.attr('data-prio')); }
  765. if (col === 'tot') { return Number($row.find('[data-task-tot]').text()) || 0; }
  766. if (col.indexOf('sw-') === 0) {
  767. const swId = col.slice(3);
  768. return Number($row.find('[data-assign][data-sw-id="' + swId + '"]').val()) || 0;
  769. }
  770. return 0;
  771. }
  772. function applySort(col) {
  773. let dir;
  774. if (currentSort.col !== col) { dir = 'asc'; }
  775. else if (currentSort.dir === 'asc') { dir = 'desc'; }
  776. else { clearSort(); return; } // third click clears
  777. currentSort.col = col;
  778. currentSort.dir = dir;
  779. $root.find('[data-sort-col] .sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
  780. $root.find('[data-sort-col="' + col + '"] .sort-ind')
  781. .text(dir === 'asc' ? '↑' : '↓')
  782. .removeClass('opacity-30').addClass('opacity-100');
  783. const rows = $taskTbody.children('tr[data-task-row]').get();
  784. rows.sort(function (a, b) {
  785. const va = rowValueFor(col, $(a));
  786. const vb = rowValueFor(col, $(b));
  787. if (va < vb) { return dir === 'asc' ? -1 : 1; }
  788. if (va > vb) { return dir === 'asc' ? 1 : -1; }
  789. // Stable-ish tiebreak: fall back to data-sort-order
  790. return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
  791. });
  792. rows.forEach(function (el) { $taskTbody.append(el); });
  793. }
  794. $root.on('click', '[data-sort-col]', function () {
  795. applySort(String($(this).attr('data-sort-col')));
  796. });
  797. // =====================================================================
  798. // Boot
  799. // =====================================================================
  800. // Recompute once at boot in case the server-rendered sums drift from the
  801. // JS formula (e.g. after a stale reload).
  802. $root.find('[data-sw-row]').each(function () {
  803. recomputeRow(parseInt($(this).data('sw-id'), 10));
  804. });
  805. // Restore persisted task-list UI state BEFORE applyFilters so hidden
  806. // columns don't briefly flash in before being toggled off.
  807. updateOwnerFilterUi();
  808. updateFocusUi();
  809. applyColumnVisibility();
  810. applyFilters();
  811. // Reset button visibility is a function of every filter; applyFilters
  812. // already calls updateResetVisibility, but call it once more at boot
  813. // in case the tbody is empty (applyFilters short-circuits nothing,
  814. // but this is defensive).
  815. updateResetVisibility();
  816. // Phase 15: in beamer mode, if the rendered task table is wider than
  817. // its scroll container, rotate worker-column headers to vertical.
  818. // Measure once after the first applyFilters() run (inputs laid out,
  819. // hidden columns collapsed) and escalate a single step — horizontal
  820. // scroll is a fallback but never a spinlock.
  821. if (isBeamer && hasTaskUi) {
  822. const table = $root.find('[data-task-table]').get(0);
  823. const container = table ? table.parentElement : null;
  824. if (table && container && table.scrollWidth > container.clientWidth) {
  825. $root.addClass('beamer-vertical-headers');
  826. if (table.scrollWidth > container.clientWidth) {
  827. // eslint-disable-next-line no-console
  828. console.warn('[sprint-planner] beamer: table still overflows after vertical headers; horizontal scroll enabled.');
  829. }
  830. }
  831. }
  832. })(jQuery);