sprint-planner.js 37 KB

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