sprint-settings.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /**
  2. * /sprints/{id}/settings — vanilla JS + SortableJS.
  3. * - debounced PATCH /sprints/{id} for sprint meta on change; when the
  4. * response signals weeks were resynced, reload to pick up the new rows
  5. * - PATCH /sprints/{id}/week/{week_id} for per-week weekday mask
  6. * - POST /sprints/{id}/workers for adding a worker, DELETE for removing
  7. * - PATCH /sprints/{id}/workers/{sw_id} for RTB and reorder
  8. * - SortableJS replaces jQuery UI sortable on the in-sprint worker list
  9. */
  10. (function () {
  11. 'use strict';
  12. const root = document.querySelector('[data-sprint-root]');
  13. if (!root) { return; }
  14. const sprintId = parseInt(root.getAttribute('data-sprint-id'), 10);
  15. const csrf = String(root.getAttribute('data-csrf') || '');
  16. function qs(sel, ctx) { return (ctx || root).querySelector(sel); }
  17. function qsa(sel, ctx) { return Array.from((ctx || root).querySelectorAll(sel)); }
  18. function on(ctx, ev, sel, fn) {
  19. ctx.addEventListener(ev, function (e) {
  20. const t = e.target.closest(sel);
  21. if (t && ctx.contains(t)) { fn.call(t, e, t); }
  22. });
  23. }
  24. function request(method, url, body) {
  25. const opts = {
  26. method,
  27. headers: { Accept: 'application/json', 'X-CSRF-Token': csrf },
  28. credentials: 'same-origin',
  29. };
  30. if (body !== undefined) {
  31. opts.headers['Content-Type'] = 'application/json';
  32. opts.body = JSON.stringify(body);
  33. }
  34. return fetch(url, opts).then(async function (res) {
  35. let payload = null;
  36. try { payload = await res.json(); } catch (_) { /* ignore */ }
  37. if (!res.ok || !payload || payload.ok !== true) {
  38. const msg = (payload && payload.error && payload.error.message)
  39. ? payload.error.message
  40. : (res.statusText || 'Request failed');
  41. const err = new Error(msg);
  42. err.status = res.status;
  43. err.payload = payload;
  44. throw err;
  45. }
  46. return payload.data;
  47. });
  48. }
  49. const statusEl = qs('[data-status]');
  50. const successCls = ['text-green-700', 'bg-green-50', 'border-green-200'];
  51. const errorCls = ['text-red-700', 'bg-red-50', 'border-red-200'];
  52. let statusTimer = null;
  53. function flash(text, isError) {
  54. if (!statusEl) { return; }
  55. statusEl.textContent = text;
  56. successCls.concat(errorCls).forEach((c) => statusEl.classList.remove(c));
  57. (isError ? errorCls : successCls).forEach((c) => statusEl.classList.add(c));
  58. statusEl.classList.remove('opacity-0');
  59. statusEl.classList.add('opacity-100');
  60. clearTimeout(statusTimer);
  61. statusTimer = setTimeout(function () {
  62. statusEl.classList.remove('opacity-100');
  63. statusEl.classList.add('opacity-0');
  64. }, 2500);
  65. }
  66. // ---- Sprint meta ----------------------------------------------------
  67. function patchMeta(payload) {
  68. return request('PATCH', '/sprints/' + sprintId, payload)
  69. .then(function (data) {
  70. flash('Saved');
  71. // Server resyncs the week set when start_date/end_date change.
  72. // Reload so the table reflects added/removed rows.
  73. if (data && data.weeks_synced) {
  74. window.location.reload();
  75. }
  76. })
  77. .catch((e) => flash(e.message, true));
  78. }
  79. const metaDebounce = {};
  80. on(root, 'change', '[data-meta]', function () {
  81. const field = this.getAttribute('name');
  82. let v = this.value;
  83. if (field === 'reserve_fraction') { v = Number(v) / 100; }
  84. clearTimeout(metaDebounce[field]);
  85. metaDebounce[field] = setTimeout(function () {
  86. const payload = {}; payload[field] = v;
  87. patchMeta(payload);
  88. }, 0);
  89. });
  90. // ---- Per-week weekday checkboxes (Phase 12) ------------------------
  91. function maskFromRow(row) {
  92. let mask = 0;
  93. qsa('[data-day-toggle]', row).forEach(function (cb) {
  94. if (cb.checked) {
  95. const bit = parseInt(cb.getAttribute('data-bit'), 10);
  96. if (Number.isInteger(bit)) { mask |= (1 << bit); }
  97. }
  98. });
  99. return mask;
  100. }
  101. function popcount5(mask) {
  102. let n = 0;
  103. for (let i = 0; i < 5; i++) { if ((mask >> i) & 1) { n++; } }
  104. return n;
  105. }
  106. const weekDebounce = {};
  107. on(root, 'change', '[data-day-toggle]', function () {
  108. const row = this.closest('[data-week-row]');
  109. const weekId = parseInt(row.getAttribute('data-week-id'), 10);
  110. const mask = maskFromRow(row);
  111. const cnt = qs('[data-week-count]', row);
  112. if (cnt) { cnt.textContent = String(popcount5(mask)); }
  113. clearTimeout(weekDebounce[weekId]);
  114. weekDebounce[weekId] = setTimeout(function () {
  115. request('PATCH', '/sprints/' + sprintId + '/week/' + weekId, { active_days_mask: mask })
  116. .then(function (data) {
  117. if (data && data.sprint_week && cnt) {
  118. cnt.textContent = String(data.sprint_week.max_working_days);
  119. }
  120. flash('Saved');
  121. })
  122. .catch((e) => flash(e.message, true));
  123. }, 250);
  124. });
  125. // ---- Worker picker --------------------------------------------------
  126. const available = qs('[data-available]');
  127. const inSprint = qs('[data-in-sprint]');
  128. function workerRowTemplate(sw) {
  129. const li = document.createElement('li');
  130. li.className = 'flex items-center gap-2 px-3 py-2 border-b bg-white last:border-b-0 dark:bg-slate-800 dark:border-slate-700';
  131. li.setAttribute('data-sw-id', String(sw.id));
  132. li.setAttribute('data-worker-id', String(sw.worker_id));
  133. const handle = document.createElement('span');
  134. handle.className = 'handle cursor-grab text-slate-400 select-none dark:text-slate-500';
  135. handle.innerHTML = '&#8801;';
  136. const name = document.createElement('span');
  137. name.className = 'flex-1';
  138. name.textContent = sw.worker_name || '';
  139. const rtb = document.createElement('input');
  140. rtb.type = 'number'; rtb.step = '0.05'; rtb.min = '0'; rtb.max = '1';
  141. rtb.value = Number(sw.rtb).toFixed(2);
  142. rtb.setAttribute('data-rtb', '');
  143. rtb.className = 'w-20 rounded border border-slate-300 px-2 py-1 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-slate-400 dark:bg-slate-800 dark:border-slate-600 dark:text-slate-100 dark:focus:ring-slate-500';
  144. const remove = document.createElement('button');
  145. remove.type = 'button';
  146. remove.setAttribute('data-remove', '');
  147. remove.className = 'text-sm text-red-600 hover:underline dark:text-red-400';
  148. remove.textContent = 'Remove';
  149. li.appendChild(handle);
  150. li.appendChild(name);
  151. li.appendChild(rtb);
  152. li.appendChild(remove);
  153. return li;
  154. }
  155. function availableRowTemplate(worker) {
  156. const li = document.createElement('li');
  157. li.className = 'flex items-center gap-2 px-3 py-2 border-b last:border-b-0 dark:border-slate-700';
  158. li.setAttribute('data-worker-id', String(worker.id));
  159. const name = document.createElement('span');
  160. name.className = 'flex-1';
  161. name.textContent = worker.name || '';
  162. const add = document.createElement('button');
  163. add.type = 'button';
  164. add.setAttribute('data-add', '');
  165. add.className = 'text-sm text-blue-700 hover:underline dark:text-blue-400 dark:hover:text-blue-300';
  166. add.textContent = 'Add →';
  167. li.appendChild(name);
  168. li.appendChild(add);
  169. return li;
  170. }
  171. if (available) {
  172. on(available, 'click', '[data-add]', function () {
  173. const li = this.closest('li');
  174. const workerId = parseInt(li.getAttribute('data-worker-id'), 10);
  175. const span = li.querySelector('span.flex-1');
  176. const name = span ? span.textContent : '';
  177. request('POST', '/sprints/' + sprintId + '/workers', { worker_id: workerId })
  178. .then(function (data) {
  179. const sw = data.sprint_worker;
  180. sw.worker_name = sw.worker_name || name;
  181. inSprint.appendChild(workerRowTemplate(sw));
  182. li.remove();
  183. flash('Worker added');
  184. refreshEmptyStates();
  185. })
  186. .catch((e) => flash(e.message, true));
  187. });
  188. }
  189. if (inSprint) {
  190. on(inSprint, 'click', '[data-remove]', function () {
  191. const li = this.closest('li');
  192. const swId = parseInt(li.getAttribute('data-sw-id'), 10);
  193. const workerId = parseInt(li.getAttribute('data-worker-id'), 10);
  194. const span = li.querySelector('span.flex-1');
  195. const name = span ? span.textContent : '';
  196. request('DELETE', '/sprints/' + sprintId + '/workers/' + swId)
  197. .then(function () {
  198. li.remove();
  199. available.appendChild(availableRowTemplate({ id: workerId, name }));
  200. flash('Worker removed');
  201. refreshEmptyStates();
  202. })
  203. .catch((e) => flash(e.message, true));
  204. });
  205. on(inSprint, 'change', '[data-rtb]', function () {
  206. const li = this.closest('li');
  207. const swId = parseInt(li.getAttribute('data-sw-id'), 10);
  208. let v = Number(this.value);
  209. if (Number.isNaN(v) || v < 0 || v > 1) { flash('RTB must be 0–1', true); return; }
  210. v = Math.round(v * 20) / 20;
  211. this.value = v.toFixed(2);
  212. request('PATCH', '/sprints/' + sprintId + '/workers/' + swId, { rtb: v })
  213. .then(() => flash('Saved'))
  214. .catch((e) => flash(e.message, true));
  215. });
  216. if (typeof window.Sortable === 'function') {
  217. window.Sortable.create(inSprint, {
  218. handle: '.handle',
  219. animation: 150,
  220. onEnd: function () {
  221. const ordering = qsa('li', inSprint).map(function (li, i) {
  222. return {
  223. sprint_worker_id: parseInt(li.getAttribute('data-sw-id'), 10),
  224. sort_order: i + 1,
  225. };
  226. });
  227. request('POST', '/sprints/' + sprintId + '/workers/reorder', ordering)
  228. .then((data) => flash(data.moved ? 'Order saved' : 'No changes'))
  229. .catch((e) => flash(e.message, true));
  230. },
  231. });
  232. } else {
  233. // eslint-disable-next-line no-console
  234. console.warn('[sprint-settings] SortableJS not loaded — drag reorder disabled.');
  235. }
  236. }
  237. function refreshEmptyStates() {
  238. const ea = qs('[data-empty-available]');
  239. const es = qs('[data-empty-sprint]');
  240. if (ea && available) { ea.style.display = available.querySelectorAll('li').length === 0 ? '' : 'none'; }
  241. if (es && inSprint) { es.style.display = inSprint.querySelectorAll('li').length === 0 ? '' : 'none'; }
  242. }
  243. refreshEmptyStates();
  244. // ----- Danger zone: type-the-name confirmation gate -----------------
  245. //
  246. // The submit button stays disabled until the input matches the sprint
  247. // name verbatim. SprintController::delete repeats the check server-side
  248. // — this is just a UX guard, not the authoritative one.
  249. (function () {
  250. const form = document.querySelector('[data-delete-sprint-form]');
  251. if (!form) { return; }
  252. const expected = String(form.getAttribute('data-confirm-name') || '');
  253. const input = form.querySelector('[data-delete-confirm-input]');
  254. const btn = form.querySelector('[data-delete-confirm-btn]');
  255. if (!input || !btn) { return; }
  256. function refresh() {
  257. btn.disabled = String(input.value) !== expected;
  258. }
  259. input.addEventListener('input', refresh);
  260. refresh();
  261. form.addEventListener('submit', function (ev) {
  262. if (String(input.value) !== expected) {
  263. ev.preventDefault();
  264. return;
  265. }
  266. // Final native confirm so a misclick on the now-enabled button
  267. // doesn't fire the destructive POST.
  268. if (!window.confirm('Delete sprint "' + expected + '" and all its data? This cannot be undone.')) {
  269. ev.preventDefault();
  270. }
  271. });
  272. })();
  273. })();