sprint-planner.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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"></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"></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-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-sort-value-sw-' + sw.id, v.toFixed(2));
  327. $td.append(
  328. $('<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">')
  329. .val(fmtDays(v))
  330. .attr('data-sw-id', sw.id)
  331. );
  332. $tr.append($td);
  333. });
  334. // delete
  335. $tr.append(
  336. $('<td class="px-1 py-1 text-right"></td>').append(
  337. $('<button type="button" data-delete-task class="text-sm text-red-600 hover:underline">').text('×')
  338. )
  339. );
  340. return $tr;
  341. }
  342. // --- Add task ---------------------------------------------------------
  343. $root.on('click', '[data-add-task]', function () {
  344. request('POST', '/sprints/' + sprintId + '/tasks', { title: '', priority: 1 })
  345. .then(function (data) {
  346. $root.find('[data-empty-tasks]').remove();
  347. const $row = buildTaskRow(data.task, data.assignments || {});
  348. $taskTbody.append($row);
  349. // Clear any active sort so the new row is actually visible at the end.
  350. clearSort();
  351. applyFilters();
  352. $row.find('[data-title]').trigger('focus').trigger('select');
  353. flash('Task added');
  354. })
  355. .catch(function (e) { flash(e.message, true); });
  356. });
  357. // --- Edit task fields (title / owner / prio) --------------------------
  358. const titleDebounce = {};
  359. $root.on('input', '[data-title]', function () {
  360. const $inp = $(this);
  361. const taskId = parseInt($inp.closest('tr').data('task-id'), 10);
  362. clearTimeout(titleDebounce[taskId]);
  363. titleDebounce[taskId] = setTimeout(function () {
  364. const title = String($inp.val()).trim();
  365. if (title === '') {
  366. flash('Title cannot be empty', true);
  367. return;
  368. }
  369. request('PATCH', '/tasks/' + taskId, { title: title })
  370. .then(function () { flash('Saved'); })
  371. .catch(function (e) { flash(e.message, true); });
  372. }, 400);
  373. });
  374. $root.on('change', '[data-owner-select]', function () {
  375. const $sel = $(this);
  376. const $row = $sel.closest('tr');
  377. const taskId = parseInt($row.data('task-id'), 10);
  378. const v = $sel.val();
  379. const owner = v === '' ? null : parseInt(String(v), 10);
  380. $row.attr('data-owner', owner === null ? '' : owner);
  381. request('PATCH', '/tasks/' + taskId, { owner_worker_id: owner })
  382. .then(function () { flash('Saved'); applyFilters(); })
  383. .catch(function (e) { flash(e.message, true); });
  384. });
  385. $root.on('change', '[data-prio-select]', function () {
  386. const $sel = $(this);
  387. const $row = $sel.closest('tr');
  388. const taskId = parseInt($row.data('task-id'), 10);
  389. const prio = parseInt(String($sel.val()), 10);
  390. $row.attr('data-prio', prio);
  391. request('PATCH', '/tasks/' + taskId, { priority: prio })
  392. .then(function (data) {
  393. flash('Saved');
  394. applyFilters();
  395. applyServerCapacity(data && data.per_worker);
  396. recomputeAllCapacity();
  397. })
  398. .catch(function (e) { flash(e.message, true); });
  399. });
  400. // --- Delete task ------------------------------------------------------
  401. $root.on('click', '[data-delete-task]', function () {
  402. const $row = $(this).closest('tr');
  403. const taskId = parseInt($row.data('task-id'), 10);
  404. const title = $row.find('[data-title]').val() || '(untitled)';
  405. if (!window.confirm('Delete task "' + title + '"?')) { return; }
  406. request('DELETE', '/tasks/' + taskId)
  407. .then(function (data) {
  408. $row.remove();
  409. applyServerCapacity(data && data.per_worker);
  410. recomputeAllCapacity();
  411. flash('Task deleted');
  412. if ($taskTbody.children('tr[data-task-row]').length === 0) {
  413. // Re-show the empty-state row (simpler than templating).
  414. window.location.reload();
  415. }
  416. })
  417. .catch(function (e) { flash(e.message, true); });
  418. });
  419. // --- Assignment cells (per task, per sprint worker) -------------------
  420. // Same shape as the Arbeitstage cell queue, but against /tasks/{id}/assignments.
  421. const pendingAssign = new Map(); // taskId -> Map<swId, days>
  422. const assignTimers = {};
  423. function queueAssign(taskId, swId, days) {
  424. if (!pendingAssign.has(taskId)) { pendingAssign.set(taskId, new Map()); }
  425. pendingAssign.get(taskId).set(swId, days);
  426. clearTimeout(assignTimers[taskId]);
  427. assignTimers[taskId] = setTimeout(function () { flushAssign(taskId); }, 400);
  428. }
  429. function flushAssign(taskId) {
  430. const m = pendingAssign.get(taskId);
  431. if (!m || m.size === 0) { return; }
  432. const cells = [];
  433. m.forEach(function (days, swId) {
  434. cells.push({ sprint_worker_id: swId, days: days });
  435. });
  436. pendingAssign.delete(taskId);
  437. request('PATCH', '/tasks/' + taskId + '/assignments', cells)
  438. .then(function (data) {
  439. if (data.applied === 0 && data.noop > 0) { flash('No changes'); }
  440. else { flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells')); }
  441. applyServerCapacity(data && data.per_worker);
  442. })
  443. .catch(function (e) { flash(e.message, true); });
  444. }
  445. $root.on('blur change', '[data-assign]', function () {
  446. const $el = $(this);
  447. let v = Number($el.val());
  448. if (Number.isNaN(v) || v < 0) { v = 0; }
  449. v = snap05(v);
  450. $el.val(fmtDays(v));
  451. $el.closest('td').attr('data-sort-value-sw-' + $el.data('sw-id'), v.toFixed(2));
  452. const taskId = parseInt($el.closest('tr').data('task-id'), 10);
  453. const swId = parseInt($el.data('sw-id'), 10);
  454. queueAssign(taskId, swId, v);
  455. // Row total
  456. let tot = 0;
  457. $el.closest('tr').find('[data-assign]').each(function () {
  458. const n = Number($(this).val());
  459. if (!Number.isNaN(n)) { tot += n; }
  460. });
  461. $el.closest('tr').find('[data-task-tot]').text(fmtDays(tot));
  462. // Available recompute (in case this is a prio-1 task)
  463. recomputeAllCapacity();
  464. });
  465. function applyServerCapacity(perWorker) {
  466. if (!perWorker || typeof perWorker !== 'object') { return; }
  467. Object.keys(perWorker).forEach(function (swIdStr) {
  468. const c = perWorker[swIdStr];
  469. $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
  470. $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
  471. const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
  472. $av.text(fmtDays(c.available));
  473. if (c.available < 0) {
  474. $av.removeClass('text-slate-900').addClass('text-red-700');
  475. } else {
  476. $av.removeClass('text-red-700').addClass('text-slate-900');
  477. }
  478. });
  479. }
  480. // --- Task reorder (drag) ----------------------------------------------
  481. if (sortableAvailable && hasTaskUi && $taskTbody.find('.handle').length > 0) {
  482. $taskTbody.sortable({
  483. handle: '.handle',
  484. items: 'tr[data-task-row]',
  485. axis: 'y',
  486. helper: function (e, tr) {
  487. const $cells = tr.children();
  488. const $clone = tr.clone();
  489. $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
  490. return $clone;
  491. },
  492. start: function () {
  493. // Drag only makes sense when no sort is active.
  494. if (currentSort.col !== null) { clearSort(); }
  495. },
  496. update: function () {
  497. const ordering = $taskTbody.find('tr[data-task-row]').map(function (i, el) {
  498. return { task_id: parseInt($(el).data('task-id'), 10), sort_order: i + 1 };
  499. }).get();
  500. request('POST', '/sprints/' + sprintId + '/tasks/reorder', ordering)
  501. .then(function (data) {
  502. ordering.forEach(function (o) {
  503. $taskTbody.find('tr[data-task-id="' + o.task_id + '"]').attr('data-sort-order', o.sort_order);
  504. });
  505. flash(data.moved ? 'Order saved' : 'No changes');
  506. })
  507. .catch(function (e) { flash(e.message, true); });
  508. },
  509. });
  510. }
  511. // --- Multi-select owner filter (persisted in localStorage) -------------
  512. const ownerFilterKey = 'sp:' + sprintId + ':ownerFilter';
  513. /** @type {Set<string>} */
  514. const ownerFilterSet = (function () {
  515. try {
  516. const raw = window.localStorage.getItem(ownerFilterKey);
  517. if (raw) {
  518. const arr = JSON.parse(raw);
  519. if (Array.isArray(arr)) { return new Set(arr.map(String)); }
  520. }
  521. } catch (_) { /* ignore */ }
  522. return new Set();
  523. })();
  524. function persistOwnerFilter() {
  525. try {
  526. window.localStorage.setItem(ownerFilterKey, JSON.stringify(Array.from(ownerFilterSet)));
  527. } catch (_) { /* ignore quota / private mode */ }
  528. }
  529. function updateOwnerFilterUi() {
  530. // Reflect state back into the checkboxes.
  531. $root.find('[data-owner-filter-opt]').each(function () {
  532. $(this).prop('checked', ownerFilterSet.has(String($(this).val())));
  533. });
  534. // Count label on the trigger.
  535. const n = ownerFilterSet.size;
  536. $root.find('[data-owner-filter-count]').text(n === 0 ? '' : '(' + n + ')');
  537. }
  538. $root.on('change', '[data-owner-filter-opt]', function () {
  539. const v = String($(this).val());
  540. if ($(this).is(':checked')) { ownerFilterSet.add(v); } else { ownerFilterSet.delete(v); }
  541. persistOwnerFilter();
  542. updateOwnerFilterUi();
  543. applyFilters();
  544. });
  545. $root.on('click', '[data-owner-filter-clear]', function () {
  546. ownerFilterSet.clear();
  547. persistOwnerFilter();
  548. updateOwnerFilterUi();
  549. applyFilters();
  550. });
  551. $root.on('click', '[data-owner-filter-trigger]', function (ev) {
  552. ev.stopPropagation();
  553. $root.find('[data-columns-dropdown]').addClass('hidden');
  554. $root.find('[data-owner-filter-dropdown]').toggleClass('hidden');
  555. });
  556. // --- Filters (search / prio / owner) ----------------------------------
  557. function applyFilters() {
  558. const q = String($root.find('[data-task-search]').val() || '').trim().toLowerCase();
  559. const prio = String($root.find('[data-prio-filter]').val() || '');
  560. let visibleCount = 0;
  561. $taskTbody.children('tr[data-task-row]').each(function () {
  562. const $row = $(this);
  563. const title = String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
  564. const rowPrio = String($row.attr('data-prio'));
  565. const rowOwner = String($row.attr('data-owner') || '');
  566. // The filter set treats "" (no owner) as the special "__none__" key.
  567. const ownerKey = rowOwner === '' ? '__none__' : rowOwner;
  568. let ok = true;
  569. if (q !== '' && !title.includes(q)) { ok = false; }
  570. if (prio !== '' && rowPrio !== prio) { ok = false; }
  571. if (ownerFilterSet.size > 0 && !ownerFilterSet.has(ownerKey)) { ok = false; }
  572. $row.toggle(ok);
  573. if (ok) { visibleCount++; }
  574. });
  575. const totalRows = $taskTbody.children('tr[data-task-row]').length;
  576. $root.find('[data-task-empty-filter]').toggle(totalRows > 0 && visibleCount === 0);
  577. }
  578. let searchDebounce = null;
  579. $root.on('input', '[data-task-search]', function () {
  580. clearTimeout(searchDebounce);
  581. searchDebounce = setTimeout(applyFilters, 120);
  582. });
  583. $root.on('change', '[data-prio-filter]', applyFilters);
  584. // --- Column visibility toggle (persisted in localStorage) --------------
  585. const columnsKey = 'sp:' + sprintId + ':hiddenCols';
  586. /** @type {Set<string>} */
  587. const hiddenCols = (function () {
  588. try {
  589. const raw = window.localStorage.getItem(columnsKey);
  590. if (raw) {
  591. const arr = JSON.parse(raw);
  592. if (Array.isArray(arr)) { return new Set(arr.map(String)); }
  593. }
  594. } catch (_) { /* ignore */ }
  595. return new Set();
  596. })();
  597. function persistHiddenCols() {
  598. try {
  599. window.localStorage.setItem(columnsKey, JSON.stringify(Array.from(hiddenCols)));
  600. } catch (_) { /* ignore */ }
  601. }
  602. function applyColumnVisibility() {
  603. // Tailwind's .hidden is display:none; works on table cells.
  604. $root.find('[data-col]').each(function () {
  605. const col = String($(this).attr('data-col'));
  606. $(this).toggleClass('hidden', hiddenCols.has(col));
  607. });
  608. // Reflect state into the Columns dropdown checkboxes.
  609. $root.find('[data-column-opt]').each(function () {
  610. $(this).prop('checked', !hiddenCols.has(String($(this).val())));
  611. });
  612. }
  613. $root.on('change', '[data-column-opt]', function () {
  614. const v = String($(this).val());
  615. if ($(this).is(':checked')) { hiddenCols.delete(v); } else { hiddenCols.add(v); }
  616. persistHiddenCols();
  617. applyColumnVisibility();
  618. });
  619. $root.on('click', '[data-columns-trigger]', function (ev) {
  620. ev.stopPropagation();
  621. $root.find('[data-owner-filter-dropdown]').addClass('hidden');
  622. $root.find('[data-columns-dropdown]').toggleClass('hidden');
  623. });
  624. // Close either dropdown when clicking outside.
  625. $(document).on('click', function (ev) {
  626. if ($(ev.target).closest('[data-owner-filter-root]').length === 0) {
  627. $root.find('[data-owner-filter-dropdown]').addClass('hidden');
  628. }
  629. if ($(ev.target).closest('[data-columns-root]').length === 0) {
  630. $root.find('[data-columns-dropdown]').addClass('hidden');
  631. }
  632. });
  633. // --- Column sort (client-side) ----------------------------------------
  634. const currentSort = { col: null, dir: null }; // dir: 'asc' | 'desc'
  635. function clearSort() {
  636. currentSort.col = null; currentSort.dir = null;
  637. $root.find('[data-sort-col]').each(function () {
  638. $(this).find('.sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
  639. });
  640. // Restore original order by data-sort-order
  641. const rows = $taskTbody.children('tr[data-task-row]').get();
  642. rows.sort(function (a, b) {
  643. return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
  644. });
  645. rows.forEach(function (el) { $taskTbody.append(el); });
  646. }
  647. function rowValueFor(col, $row) {
  648. if (col === 'title') {
  649. return String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
  650. }
  651. if (col === 'owner') {
  652. const id = String($row.attr('data-owner') || '');
  653. if (id === '') { return '\uFFFF'; } // sort empty last
  654. const opt = $row.find('[data-owner-select] option:selected');
  655. return String(opt.text() || '').toLowerCase();
  656. }
  657. if (col === 'prio') { return Number($row.attr('data-prio')); }
  658. if (col === 'tot') { return Number($row.find('[data-task-tot]').text()) || 0; }
  659. if (col.indexOf('sw-') === 0) {
  660. const swId = col.slice(3);
  661. return Number($row.find('[data-assign][data-sw-id="' + swId + '"]').val()) || 0;
  662. }
  663. return 0;
  664. }
  665. function applySort(col) {
  666. let dir;
  667. if (currentSort.col !== col) { dir = 'asc'; }
  668. else if (currentSort.dir === 'asc') { dir = 'desc'; }
  669. else { clearSort(); return; } // third click clears
  670. currentSort.col = col;
  671. currentSort.dir = dir;
  672. $root.find('[data-sort-col] .sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
  673. $root.find('[data-sort-col="' + col + '"] .sort-ind')
  674. .text(dir === 'asc' ? '↑' : '↓')
  675. .removeClass('opacity-30').addClass('opacity-100');
  676. const rows = $taskTbody.children('tr[data-task-row]').get();
  677. rows.sort(function (a, b) {
  678. const va = rowValueFor(col, $(a));
  679. const vb = rowValueFor(col, $(b));
  680. if (va < vb) { return dir === 'asc' ? -1 : 1; }
  681. if (va > vb) { return dir === 'asc' ? 1 : -1; }
  682. // Stable-ish tiebreak: fall back to data-sort-order
  683. return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
  684. });
  685. rows.forEach(function (el) { $taskTbody.append(el); });
  686. }
  687. $root.on('click', '[data-sort-col]', function () {
  688. applySort(String($(this).attr('data-sort-col')));
  689. });
  690. // =====================================================================
  691. // Boot
  692. // =====================================================================
  693. // Recompute once at boot in case the server-rendered sums drift from the
  694. // JS formula (e.g. after a stale reload).
  695. $root.find('[data-sw-row]').each(function () {
  696. recomputeRow(parseInt($(this).data('sw-id'), 10));
  697. });
  698. // Restore persisted task-list UI state BEFORE applyFilters so hidden
  699. // columns don't briefly flash in before being toggled off.
  700. updateOwnerFilterUi();
  701. applyColumnVisibility();
  702. applyFilters();
  703. })(jQuery);