sprint-planner.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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) {
  38. const afterReserves = roundHalf(ressourcen * (1 - reserveFraction));
  39. const available = afterReserves; // committed prio-1 lands in Phase 6
  40. return { ressourcen, afterReserves, available };
  41. }
  42. // ---------------------------------------------------------------------
  43. // HTTP helper — spec §7 envelopes
  44. // ---------------------------------------------------------------------
  45. function request(method, url, body) {
  46. const opts = {
  47. method,
  48. headers: {
  49. Accept: 'application/json',
  50. 'X-CSRF-Token': csrf,
  51. },
  52. credentials: 'same-origin',
  53. };
  54. if (body !== undefined) {
  55. opts.headers['Content-Type'] = 'application/json';
  56. opts.body = JSON.stringify(body);
  57. }
  58. return fetch(url, opts).then(async function (res) {
  59. let payload = null;
  60. try { payload = await res.json(); } catch (_) { /* ignore */ }
  61. if (!res.ok || !payload || payload.ok !== true) {
  62. const msg = (payload && payload.error && payload.error.message)
  63. ? payload.error.message
  64. : res.statusText || 'Request failed';
  65. const err = new Error(msg);
  66. err.status = res.status;
  67. err.payload = payload;
  68. throw err;
  69. }
  70. return payload.data;
  71. });
  72. }
  73. // ---------------------------------------------------------------------
  74. // Status line (shared with settings page styling)
  75. // ---------------------------------------------------------------------
  76. const $status = $root.find('[data-status]');
  77. let statusTimer = null;
  78. function flash(text, isError) {
  79. $status
  80. .text(text)
  81. .removeClass('text-green-700 text-red-700 bg-green-50 bg-red-50 border-green-200 border-red-200')
  82. .addClass(isError ? 'text-red-700 bg-red-50 border-red-200' : 'text-green-700 bg-green-50 border-green-200')
  83. .removeClass('opacity-0').addClass('opacity-100');
  84. clearTimeout(statusTimer);
  85. statusTimer = setTimeout(function () {
  86. $status.removeClass('opacity-100').addClass('opacity-0');
  87. }, 2500);
  88. }
  89. // ---------------------------------------------------------------------
  90. // Recompute worker row sum + capacity summary locally
  91. // ---------------------------------------------------------------------
  92. function recomputeRow(swId) {
  93. const $row = $root.find('[data-sw-row][data-sw-id="' + swId + '"]');
  94. let sum = 0;
  95. $row.find('[data-day]').each(function () {
  96. const v = Number($(this).val());
  97. if (!Number.isNaN(v)) { sum += v; }
  98. });
  99. const cap = capacity(sum);
  100. $row.find('[data-sum-days]').text(fmtDays(cap.ressourcen));
  101. $root.find('[data-cap-ressourcen][data-sw-id="' + swId + '"]').text(fmtDays(cap.ressourcen));
  102. $root.find('[data-cap-after-reserves][data-sw-id="' + swId + '"]').text(fmtDays(cap.afterReserves));
  103. const $avail = $root.find('[data-cap-available][data-sw-id="' + swId + '"]');
  104. $avail.text(fmtDays(cap.available));
  105. if (cap.available < 0) {
  106. $avail.removeClass('text-slate-900').addClass('text-red-700');
  107. } else {
  108. $avail.removeClass('text-red-700').addClass('text-slate-900');
  109. }
  110. }
  111. function recomputeSumMax() {
  112. let sum = 0;
  113. $root.find('[data-week-max]').each(function () {
  114. const v = Number($(this).val());
  115. if (!Number.isNaN(v)) { sum += v; }
  116. });
  117. $root.find('[data-sum-max]').text(fmtDays(sum));
  118. }
  119. // ---------------------------------------------------------------------
  120. // Pending-cell queue, debounced batch save
  121. // ---------------------------------------------------------------------
  122. // key = "swId:weekId" → { sw_id, week_id, days }
  123. const pendingCells = new Map();
  124. let cellDebounce = null;
  125. function queueCell(swId, weekId, days) {
  126. pendingCells.set(swId + ':' + weekId, {
  127. sprint_worker_id: swId,
  128. sprint_week_id: weekId,
  129. days: days,
  130. });
  131. clearTimeout(cellDebounce);
  132. cellDebounce = setTimeout(flushCells, 400);
  133. }
  134. function flushCells() {
  135. if (pendingCells.size === 0) { return; }
  136. const cells = Array.from(pendingCells.values());
  137. pendingCells.clear();
  138. request('PATCH', '/sprints/' + sprintId + '/week-cells', cells)
  139. .then(function (data) {
  140. if (data.applied === 0 && data.noop > 0) {
  141. flash('No changes');
  142. } else {
  143. flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells'));
  144. }
  145. // Trust the server's capacity numbers — same formula, but a
  146. // safety net if an input was tampered with.
  147. if (data.per_worker && typeof data.per_worker === 'object') {
  148. Object.keys(data.per_worker).forEach(function (swIdStr) {
  149. const c = data.per_worker[swIdStr];
  150. $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
  151. $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
  152. const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
  153. $av.text(fmtDays(c.available));
  154. if (c.available < 0) {
  155. $av.removeClass('text-slate-900').addClass('text-red-700');
  156. } else {
  157. $av.removeClass('text-red-700').addClass('text-slate-900');
  158. }
  159. $root.find('[data-sw-row][data-sw-id="' + swIdStr + '"] [data-sum-days]').text(fmtDays(c.ressourcen));
  160. });
  161. }
  162. })
  163. .catch(function (e) { flash(e.message, true); });
  164. }
  165. // ---------------------------------------------------------------------
  166. // Day cells
  167. // ---------------------------------------------------------------------
  168. $root.on('blur change', '[data-day]', function () {
  169. const $el = $(this);
  170. let v = Number($el.val());
  171. if (Number.isNaN(v)) { v = 0; }
  172. if (v < 0) { v = 0; }
  173. if (v > 5) { v = 5; }
  174. v = snap05(v);
  175. $el.val(fmtDays(v));
  176. const swId = parseInt($el.data('sw-id'), 10);
  177. const weekId = parseInt($el.data('week-id'), 10);
  178. queueCell(swId, weekId, v);
  179. recomputeRow(swId);
  180. });
  181. // ---------------------------------------------------------------------
  182. // Max working days (Arbeitstage row)
  183. // ---------------------------------------------------------------------
  184. $root.on('blur change', '[data-week-max]', function () {
  185. const $el = $(this);
  186. let v = Number($el.val());
  187. if (Number.isNaN(v)) { v = 0; }
  188. if (v < 0) { v = 0; }
  189. if (v > 5) { v = 5; }
  190. v = snap05(v);
  191. $el.val(fmtDays(v));
  192. const weekId = parseInt($el.data('week-id'), 10);
  193. recomputeSumMax();
  194. request('PATCH', '/sprints/' + sprintId + '/week/' + weekId, { max_working_days: v })
  195. .then(function () { flash('Saved'); })
  196. .catch(function (e) { flash(e.message, true); });
  197. });
  198. // ---------------------------------------------------------------------
  199. // Per-row RTB edit
  200. // ---------------------------------------------------------------------
  201. $root.on('blur change', '[data-rtb]', function () {
  202. const $el = $(this);
  203. let v = Number($el.val());
  204. if (Number.isNaN(v)) { v = 0; }
  205. if (v < 0) { v = 0; }
  206. if (v > 1) { v = 1; }
  207. v = snap005(v);
  208. $el.val(fmtRtb(v));
  209. const swId = parseInt($el.data('sw-id'), 10);
  210. request('PATCH', '/sprints/' + sprintId + '/workers/' + swId, { rtb: v })
  211. .then(function () { flash('Saved'); })
  212. .catch(function (e) { flash(e.message, true); });
  213. });
  214. // ---------------------------------------------------------------------
  215. // Worker row drag-reorder (admin only — tbody only exists with handles)
  216. // ---------------------------------------------------------------------
  217. const $tbody = $root.find('[data-tbody]');
  218. if ($tbody.find('.handle').length > 0) {
  219. $tbody.sortable({
  220. handle: '.handle',
  221. items: 'tr[data-sw-row]',
  222. axis: 'y',
  223. helper: function (e, tr) {
  224. // Preserve the td widths so the row doesn't collapse while dragging.
  225. const $cells = tr.children();
  226. const $clone = tr.clone();
  227. $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
  228. return $clone;
  229. },
  230. update: function () {
  231. const ordering = $tbody.find('tr[data-sw-row]').map(function (i, el) {
  232. return {
  233. sprint_worker_id: parseInt($(el).data('sw-id'), 10),
  234. sort_order: i + 1,
  235. };
  236. }).get();
  237. request('POST', '/sprints/' + sprintId + '/workers/reorder', ordering)
  238. .then(function (data) { flash(data.moved ? 'Order saved' : 'No changes'); })
  239. .catch(function (e) { flash(e.message, true); });
  240. },
  241. });
  242. }
  243. // Recompute once at boot in case the server-rendered sums drift from the
  244. // JS formula (e.g. after a stale reload).
  245. $root.find('[data-sw-row]').each(function () {
  246. recomputeRow(parseInt($(this).data('sw-id'), 10));
  247. });
  248. recomputeSumMax();
  249. })(jQuery);