1
0

sprint-planner.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. // The owner dropdown used to be a plain <select>, but Phase 10 replaced
  283. // it with a checkbox multi-filter. We now scrape the real source of
  284. // truth: the [data-owner-filter-opt] inputs, skipping the special
  285. // "__none__" entry. Empty list → new task rows get an empty dropdown,
  286. // which was the symptom the user hit after Phase 10 landed.
  287. function ownerChoices() {
  288. const out = [];
  289. $root.find('[data-owner-filter-opt]').each(function () {
  290. const v = String($(this).val());
  291. if (v === '' || v === '__none__') { return; }
  292. const id = parseInt(v, 10);
  293. if (!Number.isFinite(id)) { return; }
  294. const name = String($(this).closest('label').find('span').text()).trim();
  295. out.push({ id: id, name: name });
  296. });
  297. return out;
  298. }
  299. // --- Build a task row <tr> from an object ----------------------------
  300. function buildTaskRow(task, assignments) {
  301. assignments = assignments || {};
  302. const $tr = $('<tr>')
  303. .attr('data-task-row', '')
  304. .attr('data-task-id', task.id)
  305. .attr('data-prio', task.priority)
  306. .attr('data-owner', task.owner_worker_id || '')
  307. .attr('data-sort-order', task.sort_order);
  308. // handle
  309. $tr.append($('<td class="px-2 py-1"></td>').append(
  310. $('<span class="handle cursor-grab text-slate-400 select-none">').html('&#8801;')
  311. ));
  312. // title
  313. $tr.append(
  314. $('<td class="px-2 py-1 min-w-[14rem]"></td>').append(
  315. $('<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">')
  316. .val(task.title)
  317. )
  318. );
  319. // owner
  320. 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">');
  321. $sel.append('<option value="">—</option>');
  322. ownerChoices().forEach(function (o) {
  323. const $opt = $('<option>').val(o.id).text(o.name);
  324. if (Number(o.id) === Number(task.owner_worker_id)) { $opt.attr('selected', 'selected'); }
  325. $sel.append($opt);
  326. });
  327. $tr.append($('<td class="px-2 py-1" data-col="owner"></td>').append($sel));
  328. // priority
  329. 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>');
  330. $prio.val(String(task.priority));
  331. $tr.append($('<td class="px-2 py-1 text-center" data-col="prio"></td>').append($prio));
  332. // tot
  333. let tot = 0;
  334. Object.keys(assignments).forEach(function (k) { tot += Number(assignments[k]) || 0; });
  335. $tr.append($('<td class="px-2 py-1 text-center font-mono font-semibold" data-col="tot" data-task-tot>').text(fmtDays(tot)));
  336. // per-worker assignment cells
  337. sprintWorkerHeaders().forEach(function (sw) {
  338. const v = Number(assignments[sw.id] || 0);
  339. const $td = $('<td class="px-1 py-1 text-center"></td>')
  340. .attr('data-col', 'sw-' + sw.id)
  341. .attr('data-sort-value-sw-' + sw.id, v.toFixed(2));
  342. $td.append(
  343. $('<input type="number" min="0" step="0.5" data-assign data-stepper 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">')
  344. .val(fmtDays(v))
  345. .attr('data-sw-id', sw.id)
  346. );
  347. $tr.append($td);
  348. });
  349. // delete
  350. $tr.append(
  351. $('<td class="px-1 py-1 text-right"></td>').append(
  352. $('<button type="button" data-delete-task class="text-sm text-red-600 hover:underline">').text('×')
  353. )
  354. );
  355. return $tr;
  356. }
  357. // --- Add task ---------------------------------------------------------
  358. $root.on('click', '[data-add-task]', function () {
  359. request('POST', '/sprints/' + sprintId + '/tasks', { title: '', priority: 1 })
  360. .then(function (data) {
  361. $root.find('[data-empty-tasks]').remove();
  362. const $row = buildTaskRow(data.task, data.assignments || {});
  363. $taskTbody.append($row);
  364. // Clear any active sort so the new row is actually visible at the end.
  365. clearSort();
  366. applyColumnVisibility();
  367. applyFilters();
  368. $row.find('[data-title]').trigger('focus').trigger('select');
  369. flash('Task added');
  370. })
  371. .catch(function (e) { flash(e.message, true); });
  372. });
  373. // --- Edit task fields (title / owner / prio) --------------------------
  374. const titleDebounce = {};
  375. $root.on('input', '[data-title]', function () {
  376. const $inp = $(this);
  377. const taskId = parseInt($inp.closest('tr').data('task-id'), 10);
  378. clearTimeout(titleDebounce[taskId]);
  379. titleDebounce[taskId] = setTimeout(function () {
  380. const title = String($inp.val()).trim();
  381. if (title === '') {
  382. flash('Title cannot be empty', true);
  383. return;
  384. }
  385. request('PATCH', '/tasks/' + taskId, { title: title })
  386. .then(function () { flash('Saved'); })
  387. .catch(function (e) { flash(e.message, true); });
  388. }, 400);
  389. });
  390. $root.on('change', '[data-owner-select]', function () {
  391. const $sel = $(this);
  392. const $row = $sel.closest('tr');
  393. const taskId = parseInt($row.data('task-id'), 10);
  394. const v = $sel.val();
  395. const owner = v === '' ? null : parseInt(String(v), 10);
  396. $row.attr('data-owner', owner === null ? '' : owner);
  397. request('PATCH', '/tasks/' + taskId, { owner_worker_id: owner })
  398. .then(function () { flash('Saved'); applyFilters(); })
  399. .catch(function (e) { flash(e.message, true); });
  400. });
  401. $root.on('change', '[data-prio-select]', function () {
  402. const $sel = $(this);
  403. const $row = $sel.closest('tr');
  404. const taskId = parseInt($row.data('task-id'), 10);
  405. const prio = parseInt(String($sel.val()), 10);
  406. $row.attr('data-prio', prio);
  407. request('PATCH', '/tasks/' + taskId, { priority: prio })
  408. .then(function (data) {
  409. flash('Saved');
  410. applyFilters();
  411. applyServerCapacity(data && data.per_worker);
  412. recomputeAllCapacity();
  413. })
  414. .catch(function (e) { flash(e.message, true); });
  415. });
  416. // --- Delete task ------------------------------------------------------
  417. $root.on('click', '[data-delete-task]', function () {
  418. const $row = $(this).closest('tr');
  419. const taskId = parseInt($row.data('task-id'), 10);
  420. const title = $row.find('[data-title]').val() || '(untitled)';
  421. if (!window.confirm('Delete task "' + title + '"?')) { return; }
  422. request('DELETE', '/tasks/' + taskId)
  423. .then(function (data) {
  424. $row.remove();
  425. applyServerCapacity(data && data.per_worker);
  426. recomputeAllCapacity();
  427. flash('Task deleted');
  428. if ($taskTbody.children('tr[data-task-row]').length === 0) {
  429. // Re-show the empty-state row (simpler than templating).
  430. window.location.reload();
  431. }
  432. })
  433. .catch(function (e) { flash(e.message, true); });
  434. });
  435. // --- Assignment cells (per task, per sprint worker) -------------------
  436. // Same shape as the Arbeitstage cell queue, but against /tasks/{id}/assignments.
  437. const pendingAssign = new Map(); // taskId -> Map<swId, days>
  438. const assignTimers = {};
  439. function queueAssign(taskId, swId, days) {
  440. if (!pendingAssign.has(taskId)) { pendingAssign.set(taskId, new Map()); }
  441. pendingAssign.get(taskId).set(swId, days);
  442. clearTimeout(assignTimers[taskId]);
  443. assignTimers[taskId] = setTimeout(function () { flushAssign(taskId); }, 400);
  444. }
  445. function flushAssign(taskId) {
  446. const m = pendingAssign.get(taskId);
  447. if (!m || m.size === 0) { return; }
  448. const cells = [];
  449. m.forEach(function (days, swId) {
  450. cells.push({ sprint_worker_id: swId, days: days });
  451. });
  452. pendingAssign.delete(taskId);
  453. request('PATCH', '/tasks/' + taskId + '/assignments', cells)
  454. .then(function (data) {
  455. if (data.applied === 0 && data.noop > 0) { flash('No changes'); }
  456. else { flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells')); }
  457. applyServerCapacity(data && data.per_worker);
  458. })
  459. .catch(function (e) { flash(e.message, true); });
  460. }
  461. $root.on('blur change', '[data-assign]', function () {
  462. const $el = $(this);
  463. let v = Number($el.val());
  464. if (Number.isNaN(v) || v < 0) { v = 0; }
  465. v = snap05(v);
  466. $el.val(fmtDays(v));
  467. $el.closest('td').attr('data-sort-value-sw-' + $el.data('sw-id'), v.toFixed(2));
  468. const taskId = parseInt($el.closest('tr').data('task-id'), 10);
  469. const swId = parseInt($el.data('sw-id'), 10);
  470. queueAssign(taskId, swId, v);
  471. // Row total
  472. let tot = 0;
  473. $el.closest('tr').find('[data-assign]').each(function () {
  474. const n = Number($(this).val());
  475. if (!Number.isNaN(n)) { tot += n; }
  476. });
  477. $el.closest('tr').find('[data-task-tot]').text(fmtDays(tot));
  478. // Available recompute (in case this is a prio-1 task)
  479. recomputeAllCapacity();
  480. });
  481. function applyServerCapacity(perWorker) {
  482. if (!perWorker || typeof perWorker !== 'object') { return; }
  483. Object.keys(perWorker).forEach(function (swIdStr) {
  484. const c = perWorker[swIdStr];
  485. $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
  486. $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
  487. const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
  488. $av.text(fmtDays(c.available));
  489. if (c.available < 0) {
  490. $av.removeClass('text-slate-900').addClass('text-red-700');
  491. } else {
  492. $av.removeClass('text-red-700').addClass('text-slate-900');
  493. }
  494. });
  495. }
  496. // --- Task reorder (drag) ----------------------------------------------
  497. if (sortableAvailable && hasTaskUi && $taskTbody.find('.handle').length > 0) {
  498. $taskTbody.sortable({
  499. handle: '.handle',
  500. items: 'tr[data-task-row]',
  501. axis: 'y',
  502. helper: function (e, tr) {
  503. const $cells = tr.children();
  504. const $clone = tr.clone();
  505. $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
  506. return $clone;
  507. },
  508. start: function () {
  509. // Drag only makes sense when no sort is active.
  510. if (currentSort.col !== null) { clearSort(); }
  511. },
  512. update: function () {
  513. const ordering = $taskTbody.find('tr[data-task-row]').map(function (i, el) {
  514. return { task_id: parseInt($(el).data('task-id'), 10), sort_order: i + 1 };
  515. }).get();
  516. request('POST', '/sprints/' + sprintId + '/tasks/reorder', ordering)
  517. .then(function (data) {
  518. ordering.forEach(function (o) {
  519. $taskTbody.find('tr[data-task-id="' + o.task_id + '"]').attr('data-sort-order', o.sort_order);
  520. });
  521. flash(data.moved ? 'Order saved' : 'No changes');
  522. })
  523. .catch(function (e) { flash(e.message, true); });
  524. },
  525. });
  526. }
  527. // --- Multi-select owner filter (persisted in localStorage) -------------
  528. const ownerFilterKey = 'sp:' + sprintId + ':ownerFilter' + keySuffix;
  529. /** @type {Set<string>} */
  530. const ownerFilterSet = (function () {
  531. try {
  532. const raw = window.localStorage.getItem(ownerFilterKey);
  533. if (raw) {
  534. const arr = JSON.parse(raw);
  535. if (Array.isArray(arr)) { return new Set(arr.map(String)); }
  536. }
  537. } catch (_) { /* ignore */ }
  538. return new Set();
  539. })();
  540. function persistOwnerFilter() {
  541. try {
  542. window.localStorage.setItem(ownerFilterKey, JSON.stringify(Array.from(ownerFilterSet)));
  543. } catch (_) { /* ignore quota / private mode */ }
  544. }
  545. function updateOwnerFilterUi() {
  546. // Reflect state back into the checkboxes.
  547. $root.find('[data-owner-filter-opt]').each(function () {
  548. $(this).prop('checked', ownerFilterSet.has(String($(this).val())));
  549. });
  550. // Count label on the trigger.
  551. const n = ownerFilterSet.size;
  552. $root.find('[data-owner-filter-count]').text(n === 0 ? '' : '(' + n + ')');
  553. }
  554. $root.on('change', '[data-owner-filter-opt]', function () {
  555. const v = String($(this).val());
  556. if ($(this).is(':checked')) { ownerFilterSet.add(v); } else { ownerFilterSet.delete(v); }
  557. persistOwnerFilter();
  558. updateOwnerFilterUi();
  559. applyFilters();
  560. });
  561. $root.on('click', '[data-owner-filter-clear]', function () {
  562. ownerFilterSet.clear();
  563. persistOwnerFilter();
  564. updateOwnerFilterUi();
  565. applyFilters();
  566. });
  567. $root.on('click', '[data-owner-filter-trigger]', function (ev) {
  568. ev.stopPropagation();
  569. $root.find('[data-columns-dropdown]').addClass('hidden');
  570. $root.find('[data-owner-filter-dropdown]').toggleClass('hidden');
  571. });
  572. // --- Focus filter (single sprint worker, persisted) -------------------
  573. const focusKey = 'sp:' + sprintId + ':focusWorker' + keySuffix;
  574. let focusWorker = (function () {
  575. try {
  576. const raw = window.localStorage.getItem(focusKey);
  577. if (raw === null) { return ''; }
  578. return String(raw);
  579. } catch (_) { return ''; }
  580. })();
  581. function persistFocus() {
  582. try { window.localStorage.setItem(focusKey, String(focusWorker)); }
  583. catch (_) { /* ignore */ }
  584. }
  585. function updateFocusUi() {
  586. const $sel = $root.find('[data-focus-select]');
  587. if ($sel.length === 0) { return; }
  588. // If the stored worker is no longer a sprint member, fall back to "".
  589. if (focusWorker !== '' && $sel.find('option[value="' + focusWorker + '"]').length === 0) {
  590. focusWorker = '';
  591. persistFocus();
  592. }
  593. $sel.val(focusWorker);
  594. }
  595. // --- Filters (search / prio / owner / focus) --------------------------
  596. function applyFilters() {
  597. const q = String($root.find('[data-task-search]').val() || '').trim().toLowerCase();
  598. const prio = String($root.find('[data-prio-filter]').val() || '');
  599. const focus = String(focusWorker || '');
  600. let visibleCount = 0;
  601. $taskTbody.children('tr[data-task-row]').each(function () {
  602. const $row = $(this);
  603. const title = String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
  604. const rowPrio = String($row.attr('data-prio'));
  605. const rowOwner = String($row.attr('data-owner') || '');
  606. // The filter set treats "" (no owner) as the special "__none__" key.
  607. const ownerKey = rowOwner === '' ? '__none__' : rowOwner;
  608. let ok = true;
  609. if (q !== '' && !title.includes(q)) { ok = false; }
  610. if (prio !== '' && rowPrio !== prio) { ok = false; }
  611. if (ownerFilterSet.size > 0 && !ownerFilterSet.has(ownerKey)) { ok = false; }
  612. if (focus !== '') {
  613. // Zero-tolerance matches capacity math: treat 0 / 0.0 / empty
  614. // as "no assignment" (Number(v) > 0, not !== 0).
  615. const v = Number($row.find('[data-assign][data-sw-id="' + focus + '"]').val());
  616. if (!(v > 0)) { ok = false; }
  617. }
  618. $row.toggle(ok);
  619. if (ok) { visibleCount++; }
  620. });
  621. const totalRows = $taskTbody.children('tr[data-task-row]').length;
  622. $root.find('[data-task-empty-filter]').toggle(totalRows > 0 && visibleCount === 0);
  623. applyFocusColumnVisibility();
  624. updateResetVisibility();
  625. }
  626. // Column auto-hide: when a focus worker is selected, any sw column that
  627. // is all-zero for the currently visible rows collapses. We tag cells
  628. // with `.focus-auto-hidden` rather than mutating `hiddenCols` so that
  629. // clearing Focus restores whatever the user picked in the Columns
  630. // dropdown.
  631. function applyFocusColumnVisibility() {
  632. // Always clear the transient class first — keeps the function
  633. // idempotent and correct when focus goes from set → "".
  634. $root.find('.focus-auto-hidden').removeClass('focus-auto-hidden');
  635. if (!focusWorker) { return; }
  636. // Walk every sw column. If no currently visible row has a > 0
  637. // assignment for that sw, hide every `[data-col="sw-{id}"]` cell.
  638. $root.find('[data-task-table] thead th[data-sort-col^="sw-"]').each(function () {
  639. const col = String($(this).attr('data-sort-col')); // e.g. "sw-42"
  640. const swId = col.slice(3);
  641. let anyNonZero = false;
  642. $taskTbody.children('tr[data-task-row]:visible').each(function () {
  643. const v = Number($(this).find('[data-assign][data-sw-id="' + swId + '"]').val());
  644. if (v > 0) { anyNonZero = true; return false; /* break */ }
  645. });
  646. if (!anyNonZero) {
  647. $root.find('[data-col="' + col + '"]').addClass('focus-auto-hidden');
  648. }
  649. });
  650. }
  651. let searchDebounce = null;
  652. $root.on('input', '[data-task-search]', function () {
  653. clearTimeout(searchDebounce);
  654. searchDebounce = setTimeout(applyFilters, 120);
  655. });
  656. $root.on('change', '[data-prio-filter]', applyFilters);
  657. $root.on('change', '[data-focus-select]', function () {
  658. focusWorker = String($(this).val() || '');
  659. persistFocus();
  660. applyFilters();
  661. });
  662. // --- Column visibility toggle (persisted in localStorage) --------------
  663. const columnsKey = 'sp:' + sprintId + ':hiddenCols' + keySuffix;
  664. /** @type {Set<string>} */
  665. const hiddenCols = (function () {
  666. try {
  667. const raw = window.localStorage.getItem(columnsKey);
  668. if (raw) {
  669. const arr = JSON.parse(raw);
  670. if (Array.isArray(arr)) { return new Set(arr.map(String)); }
  671. }
  672. // Phase 15: first-time-ever in beamer mode seeds the hidden set
  673. // with the non-discussion columns so the task table fits the
  674. // viewport at 1920×1080. User toggles from the Columns dropdown
  675. // persist from then on — we only seed when the key is missing.
  676. if (isBeamer) {
  677. const defaults = ['owner', 'prio', 'tot'];
  678. window.localStorage.setItem(columnsKey, JSON.stringify(defaults));
  679. return new Set(defaults);
  680. }
  681. } catch (_) { /* ignore */ }
  682. return new Set();
  683. })();
  684. function persistHiddenCols() {
  685. try {
  686. window.localStorage.setItem(columnsKey, JSON.stringify(Array.from(hiddenCols)));
  687. } catch (_) { /* ignore */ }
  688. }
  689. function applyColumnVisibility() {
  690. // Tailwind's .hidden is display:none; works on table cells.
  691. $root.find('[data-col]').each(function () {
  692. const col = String($(this).attr('data-col'));
  693. $(this).toggleClass('hidden', hiddenCols.has(col));
  694. });
  695. // Reflect state into the Columns dropdown checkboxes.
  696. $root.find('[data-column-opt]').each(function () {
  697. $(this).prop('checked', !hiddenCols.has(String($(this).val())));
  698. });
  699. }
  700. $root.on('change', '[data-column-opt]', function () {
  701. const v = String($(this).val());
  702. if ($(this).is(':checked')) { hiddenCols.delete(v); } else { hiddenCols.add(v); }
  703. persistHiddenCols();
  704. applyColumnVisibility();
  705. updateResetVisibility();
  706. });
  707. // --- Reset button (clears every filter + column-hide in one click) ----
  708. function filtersActive() {
  709. const q = String($root.find('[data-task-search]').val() || '').trim();
  710. const prio = String($root.find('[data-prio-filter]').val() || '');
  711. return q !== ''
  712. || prio !== ''
  713. || ownerFilterSet.size > 0
  714. || String(focusWorker || '') !== ''
  715. || hiddenCols.size > 0;
  716. }
  717. function updateResetVisibility() {
  718. $root.find('[data-reset-filters]').toggleClass('hidden', !filtersActive());
  719. }
  720. $root.on('click', '[data-reset-filters]', function () {
  721. $root.find('[data-task-search]').val('');
  722. $root.find('[data-prio-filter]').val('');
  723. ownerFilterSet.clear();
  724. persistOwnerFilter();
  725. focusWorker = '';
  726. persistFocus();
  727. hiddenCols.clear();
  728. persistHiddenCols();
  729. updateOwnerFilterUi();
  730. updateFocusUi();
  731. applyColumnVisibility();
  732. applyFilters();
  733. });
  734. $root.on('click', '[data-columns-trigger]', function (ev) {
  735. ev.stopPropagation();
  736. $root.find('[data-owner-filter-dropdown]').addClass('hidden');
  737. $root.find('[data-columns-dropdown]').toggleClass('hidden');
  738. });
  739. // Close either dropdown when clicking outside.
  740. $(document).on('click', function (ev) {
  741. if ($(ev.target).closest('[data-owner-filter-root]').length === 0) {
  742. $root.find('[data-owner-filter-dropdown]').addClass('hidden');
  743. }
  744. if ($(ev.target).closest('[data-columns-root]').length === 0) {
  745. $root.find('[data-columns-dropdown]').addClass('hidden');
  746. }
  747. });
  748. // --- Column sort (client-side) ----------------------------------------
  749. const currentSort = { col: null, dir: null }; // dir: 'asc' | 'desc'
  750. function clearSort() {
  751. currentSort.col = null; currentSort.dir = null;
  752. $root.find('[data-sort-col]').each(function () {
  753. $(this).find('.sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
  754. });
  755. // Restore original order by data-sort-order
  756. const rows = $taskTbody.children('tr[data-task-row]').get();
  757. rows.sort(function (a, b) {
  758. return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
  759. });
  760. rows.forEach(function (el) { $taskTbody.append(el); });
  761. }
  762. function rowValueFor(col, $row) {
  763. if (col === 'title') {
  764. return String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
  765. }
  766. if (col === 'owner') {
  767. const id = String($row.attr('data-owner') || '');
  768. if (id === '') { return '\uFFFF'; } // sort empty last
  769. const opt = $row.find('[data-owner-select] option:selected');
  770. return String(opt.text() || '').toLowerCase();
  771. }
  772. if (col === 'prio') { return Number($row.attr('data-prio')); }
  773. if (col === 'tot') { return Number($row.find('[data-task-tot]').text()) || 0; }
  774. if (col.indexOf('sw-') === 0) {
  775. const swId = col.slice(3);
  776. return Number($row.find('[data-assign][data-sw-id="' + swId + '"]').val()) || 0;
  777. }
  778. return 0;
  779. }
  780. function applySort(col) {
  781. let dir;
  782. if (currentSort.col !== col) { dir = 'asc'; }
  783. else if (currentSort.dir === 'asc') { dir = 'desc'; }
  784. else { clearSort(); return; } // third click clears
  785. currentSort.col = col;
  786. currentSort.dir = dir;
  787. $root.find('[data-sort-col] .sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
  788. $root.find('[data-sort-col="' + col + '"] .sort-ind')
  789. .text(dir === 'asc' ? '↑' : '↓')
  790. .removeClass('opacity-30').addClass('opacity-100');
  791. const rows = $taskTbody.children('tr[data-task-row]').get();
  792. rows.sort(function (a, b) {
  793. const va = rowValueFor(col, $(a));
  794. const vb = rowValueFor(col, $(b));
  795. if (va < vb) { return dir === 'asc' ? -1 : 1; }
  796. if (va > vb) { return dir === 'asc' ? 1 : -1; }
  797. // Stable-ish tiebreak: fall back to data-sort-order
  798. return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
  799. });
  800. rows.forEach(function (el) { $taskTbody.append(el); });
  801. }
  802. $root.on('click', '[data-sort-col]', function () {
  803. applySort(String($(this).attr('data-sort-col')));
  804. });
  805. // =====================================================================
  806. // Boot
  807. // =====================================================================
  808. // Recompute once at boot in case the server-rendered sums drift from the
  809. // JS formula (e.g. after a stale reload).
  810. $root.find('[data-sw-row]').each(function () {
  811. recomputeRow(parseInt($(this).data('sw-id'), 10));
  812. });
  813. // Restore persisted task-list UI state BEFORE applyFilters so hidden
  814. // columns don't briefly flash in before being toggled off.
  815. updateOwnerFilterUi();
  816. updateFocusUi();
  817. applyColumnVisibility();
  818. applyFilters();
  819. // Reset button visibility is a function of every filter; applyFilters
  820. // already calls updateResetVisibility, but call it once more at boot
  821. // in case the tbody is empty (applyFilters short-circuits nothing,
  822. // but this is defensive).
  823. updateResetVisibility();
  824. // Phase 15: in beamer mode, if the rendered task table is wider than
  825. // its scroll container, rotate worker-column headers to vertical.
  826. // Measure once after the first applyFilters() run (inputs laid out,
  827. // hidden columns collapsed) and escalate a single step — horizontal
  828. // scroll is a fallback but never a spinlock.
  829. if (isBeamer && hasTaskUi) {
  830. const table = $root.find('[data-task-table]').get(0);
  831. const container = table ? table.parentElement : null;
  832. if (table && container && table.scrollWidth > container.clientWidth) {
  833. $root.addClass('beamer-vertical-headers');
  834. if (table.scrollWidth > container.clientWidth) {
  835. // eslint-disable-next-line no-console
  836. console.warn('[sprint-planner] beamer: table still overflows after vertical headers; horizontal scroll enabled.');
  837. }
  838. }
  839. }
  840. })(jQuery);