1
0

sprint-planner.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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. * - Max-working-days cells (the "Arbeitstage" row) snap to 0.5 on blur,
  9. * saved via PATCH /sprints/{id}/week/{week_id}.
  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. function recomputeSumMax() {
  138. let sum = 0;
  139. $root.find('[data-week-max]').each(function () {
  140. const v = Number($(this).val());
  141. if (!Number.isNaN(v)) { sum += v; }
  142. });
  143. $root.find('[data-sum-max]').text(fmtDays(sum));
  144. }
  145. // ---------------------------------------------------------------------
  146. // Pending-cell queue, debounced batch save
  147. // ---------------------------------------------------------------------
  148. // key = "swId:weekId" → { sw_id, week_id, days }
  149. const pendingCells = new Map();
  150. let cellDebounce = null;
  151. function queueCell(swId, weekId, days) {
  152. pendingCells.set(swId + ':' + weekId, {
  153. sprint_worker_id: swId,
  154. sprint_week_id: weekId,
  155. days: days,
  156. });
  157. clearTimeout(cellDebounce);
  158. cellDebounce = setTimeout(flushCells, 400);
  159. }
  160. function flushCells() {
  161. if (pendingCells.size === 0) { return; }
  162. const cells = Array.from(pendingCells.values());
  163. pendingCells.clear();
  164. request('PATCH', '/sprints/' + sprintId + '/week-cells', cells)
  165. .then(function (data) {
  166. if (data.applied === 0 && data.noop > 0) {
  167. flash('No changes');
  168. } else {
  169. flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells'));
  170. }
  171. // Trust the server's capacity numbers — same formula, but a
  172. // safety net if an input was tampered with.
  173. if (data.per_worker && typeof data.per_worker === 'object') {
  174. Object.keys(data.per_worker).forEach(function (swIdStr) {
  175. const c = data.per_worker[swIdStr];
  176. $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
  177. $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
  178. const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
  179. $av.text(fmtDays(c.available));
  180. if (c.available < 0) {
  181. $av.removeClass('text-slate-900').addClass('text-red-700');
  182. } else {
  183. $av.removeClass('text-red-700').addClass('text-slate-900');
  184. }
  185. $root.find('[data-sw-row][data-sw-id="' + swIdStr + '"] [data-sum-days]').text(fmtDays(c.ressourcen));
  186. });
  187. }
  188. })
  189. .catch(function (e) { flash(e.message, true); });
  190. }
  191. // ---------------------------------------------------------------------
  192. // Day cells
  193. // ---------------------------------------------------------------------
  194. $root.on('blur change', '[data-day]', function () {
  195. const $el = $(this);
  196. let v = Number($el.val());
  197. if (Number.isNaN(v)) { v = 0; }
  198. if (v < 0) { v = 0; }
  199. if (v > 5) { v = 5; }
  200. v = snap05(v);
  201. $el.val(fmtDays(v));
  202. const swId = parseInt($el.data('sw-id'), 10);
  203. const weekId = parseInt($el.data('week-id'), 10);
  204. queueCell(swId, weekId, v);
  205. recomputeRow(swId);
  206. });
  207. // ---------------------------------------------------------------------
  208. // Max working days (Arbeitstage row)
  209. // ---------------------------------------------------------------------
  210. $root.on('blur change', '[data-week-max]', function () {
  211. const $el = $(this);
  212. let v = Number($el.val());
  213. if (Number.isNaN(v)) { v = 0; }
  214. if (v < 0) { v = 0; }
  215. if (v > 5) { v = 5; }
  216. v = snap05(v);
  217. $el.val(fmtDays(v));
  218. const weekId = parseInt($el.data('week-id'), 10);
  219. recomputeSumMax();
  220. request('PATCH', '/sprints/' + sprintId + '/week/' + weekId, { max_working_days: v })
  221. .then(function () { flash('Saved'); })
  222. .catch(function (e) { flash(e.message, true); });
  223. });
  224. // ---------------------------------------------------------------------
  225. // Per-row RTB edit
  226. // ---------------------------------------------------------------------
  227. $root.on('blur change', '[data-rtb]', function () {
  228. const $el = $(this);
  229. let v = Number($el.val());
  230. if (Number.isNaN(v)) { v = 0; }
  231. if (v < 0) { v = 0; }
  232. if (v > 1) { v = 1; }
  233. v = snap005(v);
  234. $el.val(fmtRtb(v));
  235. const swId = parseInt($el.data('sw-id'), 10);
  236. request('PATCH', '/sprints/' + sprintId + '/workers/' + swId, { rtb: v })
  237. .then(function () { flash('Saved'); })
  238. .catch(function (e) { flash(e.message, true); });
  239. });
  240. // ---------------------------------------------------------------------
  241. // Worker row drag-reorder (admin only — tbody only exists with handles)
  242. // ---------------------------------------------------------------------
  243. const sortableAvailable = typeof $.fn.sortable === 'function';
  244. if (!sortableAvailable) {
  245. // jQuery UI didn't load (SRI mismatch, offline CDN, ad blocker).
  246. // Drag-reorder is unavailable but the rest of the page still works.
  247. // eslint-disable-next-line no-console
  248. console.warn('[sprint-planner] jQuery UI not loaded — drag reorder disabled.');
  249. }
  250. const $tbody = $root.find('[data-tbody]');
  251. if (sortableAvailable && $tbody.find('.handle').length > 0) {
  252. $tbody.sortable({
  253. handle: '.handle',
  254. items: 'tr[data-sw-row]',
  255. axis: 'y',
  256. helper: function (e, tr) {
  257. // Preserve the td widths so the row doesn't collapse while dragging.
  258. const $cells = tr.children();
  259. const $clone = tr.clone();
  260. $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
  261. return $clone;
  262. },
  263. update: function () {
  264. const ordering = $tbody.find('tr[data-sw-row]').map(function (i, el) {
  265. return {
  266. sprint_worker_id: parseInt($(el).data('sw-id'), 10),
  267. sort_order: i + 1,
  268. };
  269. }).get();
  270. request('POST', '/sprints/' + sprintId + '/workers/reorder', ordering)
  271. .then(function (data) {
  272. if (data.moved) {
  273. // Column order in the task list below depends on
  274. // this ordering — simplest to re-render.
  275. window.location.reload();
  276. } else {
  277. flash('No changes');
  278. }
  279. })
  280. .catch(function (e) { flash(e.message, true); });
  281. },
  282. });
  283. }
  284. // =====================================================================
  285. // Task list — create/edit/delete/reorder + assignments + filter/sort
  286. // =====================================================================
  287. const $taskTbody = $root.find('[data-task-tbody]');
  288. const hasTaskUi = $taskTbody.length > 0;
  289. // --- Worker/owner helpers read from the DOM once ----------------------
  290. function sprintWorkerHeaders() {
  291. const out = [];
  292. $root.find('[data-task-table] thead th[data-sort-col^="sw-"]').each(function () {
  293. const col = String($(this).attr('data-sort-col'));
  294. out.push({
  295. id: parseInt(col.slice(3), 10),
  296. name: $(this).clone().children().remove().end().text().trim(),
  297. });
  298. });
  299. return out;
  300. }
  301. function ownerChoices() {
  302. const out = [];
  303. $root.find('[data-owner-filter] option').each(function () {
  304. const v = $(this).val();
  305. if (v === '' || v === '__none__') { return; }
  306. out.push({ id: parseInt(String(v), 10), name: String($(this).text()).trim() });
  307. });
  308. return out;
  309. }
  310. // --- Build a task row <tr> from an object ----------------------------
  311. function buildTaskRow(task, assignments) {
  312. assignments = assignments || {};
  313. const $tr = $('<tr>')
  314. .attr('data-task-row', '')
  315. .attr('data-task-id', task.id)
  316. .attr('data-prio', task.priority)
  317. .attr('data-owner', task.owner_worker_id || '')
  318. .attr('data-sort-order', task.sort_order);
  319. // handle
  320. $tr.append($('<td class="px-2 py-1"></td>').append(
  321. $('<span class="handle cursor-grab text-slate-400 select-none">').html('&#8801;')
  322. ));
  323. // title
  324. $tr.append(
  325. $('<td class="px-2 py-1 min-w-[14rem]"></td>').append(
  326. $('<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">')
  327. .val(task.title)
  328. )
  329. );
  330. // owner
  331. 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">');
  332. $sel.append('<option value="">—</option>');
  333. ownerChoices().forEach(function (o) {
  334. const $opt = $('<option>').val(o.id).text(o.name);
  335. if (Number(o.id) === Number(task.owner_worker_id)) { $opt.attr('selected', 'selected'); }
  336. $sel.append($opt);
  337. });
  338. $tr.append($('<td class="px-2 py-1"></td>').append($sel));
  339. // priority
  340. 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>');
  341. $prio.val(String(task.priority));
  342. $tr.append($('<td class="px-2 py-1 text-center"></td>').append($prio));
  343. // tot
  344. let tot = 0;
  345. Object.keys(assignments).forEach(function (k) { tot += Number(assignments[k]) || 0; });
  346. $tr.append($('<td class="px-2 py-1 text-center font-mono font-semibold" data-task-tot>').text(fmtDays(tot)));
  347. // per-worker assignment cells
  348. sprintWorkerHeaders().forEach(function (sw) {
  349. const v = Number(assignments[sw.id] || 0);
  350. const $td = $('<td class="px-1 py-1 text-center"></td>')
  351. .attr('data-sort-value-sw-' + sw.id, v.toFixed(2));
  352. $td.append(
  353. $('<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">')
  354. .val(fmtDays(v))
  355. .attr('data-sw-id', sw.id)
  356. );
  357. $tr.append($td);
  358. });
  359. // delete
  360. $tr.append(
  361. $('<td class="px-1 py-1 text-right"></td>').append(
  362. $('<button type="button" data-delete-task class="text-sm text-red-600 hover:underline">').text('×')
  363. )
  364. );
  365. return $tr;
  366. }
  367. // --- Add task ---------------------------------------------------------
  368. $root.on('click', '[data-add-task]', function () {
  369. request('POST', '/sprints/' + sprintId + '/tasks', { title: '', priority: 1 })
  370. .then(function (data) {
  371. $root.find('[data-empty-tasks]').remove();
  372. const $row = buildTaskRow(data.task, data.assignments || {});
  373. $taskTbody.append($row);
  374. // Clear any active sort so the new row is actually visible at the end.
  375. clearSort();
  376. applyFilters();
  377. $row.find('[data-title]').trigger('focus').trigger('select');
  378. flash('Task added');
  379. })
  380. .catch(function (e) { flash(e.message, true); });
  381. });
  382. // --- Edit task fields (title / owner / prio) --------------------------
  383. const titleDebounce = {};
  384. $root.on('input', '[data-title]', function () {
  385. const $inp = $(this);
  386. const taskId = parseInt($inp.closest('tr').data('task-id'), 10);
  387. clearTimeout(titleDebounce[taskId]);
  388. titleDebounce[taskId] = setTimeout(function () {
  389. const title = String($inp.val()).trim();
  390. if (title === '') {
  391. flash('Title cannot be empty', true);
  392. return;
  393. }
  394. request('PATCH', '/tasks/' + taskId, { title: title })
  395. .then(function () { flash('Saved'); })
  396. .catch(function (e) { flash(e.message, true); });
  397. }, 400);
  398. });
  399. $root.on('change', '[data-owner-select]', function () {
  400. const $sel = $(this);
  401. const $row = $sel.closest('tr');
  402. const taskId = parseInt($row.data('task-id'), 10);
  403. const v = $sel.val();
  404. const owner = v === '' ? null : parseInt(String(v), 10);
  405. $row.attr('data-owner', owner === null ? '' : owner);
  406. request('PATCH', '/tasks/' + taskId, { owner_worker_id: owner })
  407. .then(function () { flash('Saved'); applyFilters(); })
  408. .catch(function (e) { flash(e.message, true); });
  409. });
  410. $root.on('change', '[data-prio-select]', function () {
  411. const $sel = $(this);
  412. const $row = $sel.closest('tr');
  413. const taskId = parseInt($row.data('task-id'), 10);
  414. const prio = parseInt(String($sel.val()), 10);
  415. $row.attr('data-prio', prio);
  416. request('PATCH', '/tasks/' + taskId, { priority: prio })
  417. .then(function (data) {
  418. flash('Saved');
  419. applyFilters();
  420. applyServerCapacity(data && data.per_worker);
  421. recomputeAllCapacity();
  422. })
  423. .catch(function (e) { flash(e.message, true); });
  424. });
  425. // --- Delete task ------------------------------------------------------
  426. $root.on('click', '[data-delete-task]', function () {
  427. const $row = $(this).closest('tr');
  428. const taskId = parseInt($row.data('task-id'), 10);
  429. const title = $row.find('[data-title]').val() || '(untitled)';
  430. if (!window.confirm('Delete task "' + title + '"?')) { return; }
  431. request('DELETE', '/tasks/' + taskId)
  432. .then(function (data) {
  433. $row.remove();
  434. applyServerCapacity(data && data.per_worker);
  435. recomputeAllCapacity();
  436. flash('Task deleted');
  437. if ($taskTbody.children('tr[data-task-row]').length === 0) {
  438. // Re-show the empty-state row (simpler than templating).
  439. window.location.reload();
  440. }
  441. })
  442. .catch(function (e) { flash(e.message, true); });
  443. });
  444. // --- Assignment cells (per task, per sprint worker) -------------------
  445. // Same shape as the Arbeitstage cell queue, but against /tasks/{id}/assignments.
  446. const pendingAssign = new Map(); // taskId -> Map<swId, days>
  447. const assignTimers = {};
  448. function queueAssign(taskId, swId, days) {
  449. if (!pendingAssign.has(taskId)) { pendingAssign.set(taskId, new Map()); }
  450. pendingAssign.get(taskId).set(swId, days);
  451. clearTimeout(assignTimers[taskId]);
  452. assignTimers[taskId] = setTimeout(function () { flushAssign(taskId); }, 400);
  453. }
  454. function flushAssign(taskId) {
  455. const m = pendingAssign.get(taskId);
  456. if (!m || m.size === 0) { return; }
  457. const cells = [];
  458. m.forEach(function (days, swId) {
  459. cells.push({ sprint_worker_id: swId, days: days });
  460. });
  461. pendingAssign.delete(taskId);
  462. request('PATCH', '/tasks/' + taskId + '/assignments', cells)
  463. .then(function (data) {
  464. if (data.applied === 0 && data.noop > 0) { flash('No changes'); }
  465. else { flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells')); }
  466. applyServerCapacity(data && data.per_worker);
  467. })
  468. .catch(function (e) { flash(e.message, true); });
  469. }
  470. $root.on('blur change', '[data-assign]', function () {
  471. const $el = $(this);
  472. let v = Number($el.val());
  473. if (Number.isNaN(v) || v < 0) { v = 0; }
  474. v = snap05(v);
  475. $el.val(fmtDays(v));
  476. $el.closest('td').attr('data-sort-value-sw-' + $el.data('sw-id'), v.toFixed(2));
  477. const taskId = parseInt($el.closest('tr').data('task-id'), 10);
  478. const swId = parseInt($el.data('sw-id'), 10);
  479. queueAssign(taskId, swId, v);
  480. // Row total
  481. let tot = 0;
  482. $el.closest('tr').find('[data-assign]').each(function () {
  483. const n = Number($(this).val());
  484. if (!Number.isNaN(n)) { tot += n; }
  485. });
  486. $el.closest('tr').find('[data-task-tot]').text(fmtDays(tot));
  487. // Available recompute (in case this is a prio-1 task)
  488. recomputeAllCapacity();
  489. });
  490. function applyServerCapacity(perWorker) {
  491. if (!perWorker || typeof perWorker !== 'object') { return; }
  492. Object.keys(perWorker).forEach(function (swIdStr) {
  493. const c = perWorker[swIdStr];
  494. $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
  495. $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
  496. const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
  497. $av.text(fmtDays(c.available));
  498. if (c.available < 0) {
  499. $av.removeClass('text-slate-900').addClass('text-red-700');
  500. } else {
  501. $av.removeClass('text-red-700').addClass('text-slate-900');
  502. }
  503. });
  504. }
  505. // --- Task reorder (drag) ----------------------------------------------
  506. if (sortableAvailable && hasTaskUi && $taskTbody.find('.handle').length > 0) {
  507. $taskTbody.sortable({
  508. handle: '.handle',
  509. items: 'tr[data-task-row]',
  510. axis: 'y',
  511. helper: function (e, tr) {
  512. const $cells = tr.children();
  513. const $clone = tr.clone();
  514. $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
  515. return $clone;
  516. },
  517. start: function () {
  518. // Drag only makes sense when no sort is active.
  519. if (currentSort.col !== null) { clearSort(); }
  520. },
  521. update: function () {
  522. const ordering = $taskTbody.find('tr[data-task-row]').map(function (i, el) {
  523. return { task_id: parseInt($(el).data('task-id'), 10), sort_order: i + 1 };
  524. }).get();
  525. request('POST', '/sprints/' + sprintId + '/tasks/reorder', ordering)
  526. .then(function (data) {
  527. ordering.forEach(function (o) {
  528. $taskTbody.find('tr[data-task-id="' + o.task_id + '"]').attr('data-sort-order', o.sort_order);
  529. });
  530. flash(data.moved ? 'Order saved' : 'No changes');
  531. })
  532. .catch(function (e) { flash(e.message, true); });
  533. },
  534. });
  535. }
  536. // --- Filters (search / prio / owner) ----------------------------------
  537. function applyFilters() {
  538. const q = String($root.find('[data-task-search]').val() || '').trim().toLowerCase();
  539. const prio = String($root.find('[data-prio-filter]').val() || '');
  540. const owner = String($root.find('[data-owner-filter]').val() || '');
  541. let visibleCount = 0;
  542. $taskTbody.children('tr[data-task-row]').each(function () {
  543. const $row = $(this);
  544. const title = String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
  545. const rowPrio = String($row.attr('data-prio'));
  546. const rowOwner = String($row.attr('data-owner') || '');
  547. let ok = true;
  548. if (q !== '' && !title.includes(q)) { ok = false; }
  549. if (prio !== '' && rowPrio !== prio) { ok = false; }
  550. if (owner === '__none__') {
  551. if (rowOwner !== '') { ok = false; }
  552. } else if (owner !== '' && rowOwner !== owner) {
  553. ok = false;
  554. }
  555. $row.toggle(ok);
  556. if (ok) { visibleCount++; }
  557. });
  558. const totalRows = $taskTbody.children('tr[data-task-row]').length;
  559. $root.find('[data-task-empty-filter]').toggle(totalRows > 0 && visibleCount === 0);
  560. }
  561. let searchDebounce = null;
  562. $root.on('input', '[data-task-search]', function () {
  563. clearTimeout(searchDebounce);
  564. searchDebounce = setTimeout(applyFilters, 120);
  565. });
  566. $root.on('change', '[data-prio-filter], [data-owner-filter]', applyFilters);
  567. // --- Column sort (client-side) ----------------------------------------
  568. const currentSort = { col: null, dir: null }; // dir: 'asc' | 'desc'
  569. function clearSort() {
  570. currentSort.col = null; currentSort.dir = null;
  571. $root.find('[data-sort-col]').each(function () {
  572. $(this).find('.sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
  573. });
  574. // Restore original order by data-sort-order
  575. const rows = $taskTbody.children('tr[data-task-row]').get();
  576. rows.sort(function (a, b) {
  577. return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
  578. });
  579. rows.forEach(function (el) { $taskTbody.append(el); });
  580. }
  581. function rowValueFor(col, $row) {
  582. if (col === 'title') {
  583. return String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
  584. }
  585. if (col === 'owner') {
  586. const id = String($row.attr('data-owner') || '');
  587. if (id === '') { return '\uFFFF'; } // sort empty last
  588. const opt = $row.find('[data-owner-select] option:selected');
  589. return String(opt.text() || '').toLowerCase();
  590. }
  591. if (col === 'prio') { return Number($row.attr('data-prio')); }
  592. if (col === 'tot') { return Number($row.find('[data-task-tot]').text()) || 0; }
  593. if (col.indexOf('sw-') === 0) {
  594. const swId = col.slice(3);
  595. return Number($row.find('[data-assign][data-sw-id="' + swId + '"]').val()) || 0;
  596. }
  597. return 0;
  598. }
  599. function applySort(col) {
  600. let dir;
  601. if (currentSort.col !== col) { dir = 'asc'; }
  602. else if (currentSort.dir === 'asc') { dir = 'desc'; }
  603. else { clearSort(); return; } // third click clears
  604. currentSort.col = col;
  605. currentSort.dir = dir;
  606. $root.find('[data-sort-col] .sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
  607. $root.find('[data-sort-col="' + col + '"] .sort-ind')
  608. .text(dir === 'asc' ? '↑' : '↓')
  609. .removeClass('opacity-30').addClass('opacity-100');
  610. const rows = $taskTbody.children('tr[data-task-row]').get();
  611. rows.sort(function (a, b) {
  612. const va = rowValueFor(col, $(a));
  613. const vb = rowValueFor(col, $(b));
  614. if (va < vb) { return dir === 'asc' ? -1 : 1; }
  615. if (va > vb) { return dir === 'asc' ? 1 : -1; }
  616. // Stable-ish tiebreak: fall back to data-sort-order
  617. return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
  618. });
  619. rows.forEach(function (el) { $taskTbody.append(el); });
  620. }
  621. $root.on('click', '[data-sort-col]', function () {
  622. applySort(String($(this).attr('data-sort-col')));
  623. });
  624. // =====================================================================
  625. // Boot
  626. // =====================================================================
  627. // Recompute once at boot in case the server-rendered sums drift from the
  628. // JS formula (e.g. after a stale reload).
  629. $root.find('[data-sw-row]').each(function () {
  630. recomputeRow(parseInt($(this).data('sw-id'), 10));
  631. });
  632. recomputeSumMax();
  633. applyFilters();
  634. })(jQuery);