app.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Front-end for PDQ / vendor pages.
  2. //
  3. // Globals provided by the page via <script> before this file:
  4. // PDQ.actor 'ICG' or vendor slug
  5. // PDQ.audience 'ICG' or 'vendor'
  6. // PDQ.vendors [{slug, name}, ...] (ICG view only; vendor view: just its own)
  7. // PDQ.pollMs ms between auto-refresh
  8. (function () {
  9. if (typeof window.PDQ === 'undefined') window.PDQ = {};
  10. const PDQ = window.PDQ;
  11. const $ = (sel, root = document) => root.querySelector(sel);
  12. const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
  13. // Adds actor/vendor params to AJAX calls so the server can identify us.
  14. function authParams() {
  15. if (PDQ.audience === 'ICG') return { actor: 'ICG' };
  16. return { v: PDQ.actor };
  17. }
  18. function postForm(url, data) {
  19. const body = new URLSearchParams({ ...authParams(), ...data });
  20. return fetch(url, {
  21. method: 'POST',
  22. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  23. body,
  24. });
  25. }
  26. function get(url, params = {}) {
  27. const u = new URL(url, window.location.href);
  28. Object.entries({ ...authParams(), ...params })
  29. .forEach(([k, v]) => u.searchParams.set(k, v));
  30. return fetch(u.toString());
  31. }
  32. // -------- jobs table --------
  33. function reloadTable() {
  34. return get('bin/jobs_table.php')
  35. .then(r => r.text())
  36. .then(html => {
  37. $('#jobs-table').innerHTML = html;
  38. wireTable();
  39. stampSyncTime();
  40. });
  41. }
  42. function stampSyncTime() {
  43. const d = new Date();
  44. const el = $('#sync-time');
  45. if (!el) return;
  46. el.textContent = 'Last sync: ' + d.toLocaleTimeString();
  47. }
  48. function wireTable() {
  49. $$('#jobs-table .btn[data-action]').forEach(btn => {
  50. btn.addEventListener('click', onAction);
  51. });
  52. $$('#jobs-table .editable').forEach(el => {
  53. el.addEventListener('dblclick', beginEdit);
  54. el.addEventListener('keydown', e => {
  55. if (e.key === 'Enter') { e.preventDefault(); beginEdit.call(el, e); }
  56. });
  57. });
  58. }
  59. function onAction(e) {
  60. const btn = e.currentTarget;
  61. const row = btn.closest('tr');
  62. const jobId = row.dataset.jobId;
  63. const action = btn.dataset.action;
  64. if (action === 'partial_ship') return onPartialShip(btn, row, jobId);
  65. if (action === 'delete') return onDelete(btn, row, jobId);
  66. btn.disabled = true;
  67. postForm('bin/jobs_update.php', { job_id: jobId, action })
  68. .then(r => r.text().then(t => ({ ok: r.ok, body: t })))
  69. .then(res => {
  70. if (!res.ok || res.body.trim() !== 'Success') {
  71. alert('Update failed: ' + res.body);
  72. }
  73. return reloadTable();
  74. })
  75. .catch(err => alert('Network error: ' + err.message));
  76. }
  77. function onDelete(btn, row, jobId) {
  78. const jobCell = row.querySelector('[data-column="job"]');
  79. const label = jobCell ? (jobCell.textContent.trim() || '#' + jobId) : '#' + jobId;
  80. if (!window.confirm('Delete job ' + label + '? This cannot be undone from the UI.')) return;
  81. btn.disabled = true;
  82. postForm('bin/jobs_delete.php', { job_id: jobId })
  83. .then(r => r.text().then(t => ({ ok: r.ok, body: t })))
  84. .then(res => {
  85. if (!res.ok || res.body.trim() !== 'Success') {
  86. alert('Delete failed: ' + res.body);
  87. }
  88. return reloadTable();
  89. })
  90. .catch(err => alert('Network error: ' + err.message));
  91. }
  92. function onPartialShip(btn, row, jobId) {
  93. const currentQty = parseInt(btn.dataset.qty, 10);
  94. const raw = window.prompt(
  95. 'How many are shipping now?' + (currentQty ? ' (out of ' + currentQty + ')' : '')
  96. );
  97. if (raw === null) return;
  98. const partial = parseInt(String(raw).trim(), 10);
  99. if (!Number.isInteger(partial) || partial <= 0) {
  100. alert('Enter a whole number greater than zero.');
  101. return;
  102. }
  103. if (currentQty && partial >= currentQty) {
  104. alert('Partial quantity must be less than ' + currentQty + '. Use Mark Shipped to ship the whole job.');
  105. return;
  106. }
  107. btn.disabled = true;
  108. postForm('bin/jobs_partial_ship.php', { job_id: jobId, partial_qty: partial })
  109. .then(r => r.text().then(t => ({ ok: r.ok, body: t })))
  110. .then(res => {
  111. if (!res.ok || res.body.trim() !== 'Success') {
  112. alert('Partial ship failed: ' + res.body);
  113. }
  114. return reloadTable();
  115. })
  116. .catch(err => alert('Network error: ' + err.message));
  117. }
  118. function beginEdit(e) {
  119. const span = this;
  120. if (span.querySelector('input')) return;
  121. const col = span.dataset.column;
  122. const original = (span.dataset.raw !== undefined) ? span.dataset.raw : span.textContent.trim();
  123. const initial = original === '—' ? '' : original;
  124. const input = document.createElement('input');
  125. input.type = 'text';
  126. input.className = 'inline-edit';
  127. input.value = initial;
  128. span.innerHTML = '';
  129. span.appendChild(input);
  130. input.focus();
  131. input.select();
  132. let done = false;
  133. const commit = (save) => {
  134. if (done) return;
  135. done = true;
  136. const val = input.value;
  137. if (!save || val === initial) {
  138. renderValue(span, original, col);
  139. return;
  140. }
  141. span.classList.add('saving');
  142. const row = span.closest('tr');
  143. postForm('bin/jobs_update.php', {
  144. job_id: row.dataset.jobId,
  145. column: col,
  146. value: val,
  147. })
  148. .then(r => r.text().then(t => ({ ok: r.ok, body: t })))
  149. .then(res => {
  150. span.classList.remove('saving');
  151. if (!res.ok || res.body.trim() !== 'Success') {
  152. span.classList.add('error');
  153. alert('Save failed: ' + res.body);
  154. renderValue(span, original, col);
  155. } else {
  156. return reloadTable();
  157. }
  158. })
  159. .catch(err => {
  160. span.classList.remove('saving');
  161. span.classList.add('error');
  162. alert('Network error: ' + err.message);
  163. renderValue(span, original, col);
  164. });
  165. };
  166. input.addEventListener('blur', () => commit(true));
  167. input.addEventListener('keydown', ev => {
  168. if (ev.key === 'Enter') { ev.preventDefault(); input.blur(); }
  169. if (ev.key === 'Escape') { ev.preventDefault(); commit(false); }
  170. });
  171. }
  172. function renderValue(span, val, col) {
  173. if (col === 'due_date') span.dataset.raw = val;
  174. span.textContent = (val === '' || val === null) ? '—' : val;
  175. }
  176. // -------- messages --------
  177. function reloadAllThreads() {
  178. return Promise.all($$('.thread').map(reloadThread));
  179. }
  180. function reloadThread(thread) {
  181. const slug = thread.dataset.vendor;
  182. const list = thread.querySelector('.thread-list');
  183. const since = list.dataset.maxId || 0;
  184. return get('bin/messages_list.php', { vendor: slug, since })
  185. .then(r => r.text().then(html => ({
  186. html,
  187. maxId: r.headers.get('X-Max-Id') || since,
  188. })))
  189. .then(({ html, maxId }) => {
  190. if (html.trim()) {
  191. if (since === '0' || since === 0) list.innerHTML = '';
  192. list.insertAdjacentHTML('beforeend', html);
  193. list.scrollTop = list.scrollHeight;
  194. }
  195. list.dataset.maxId = maxId;
  196. const empty = list.querySelector('.msg-empty');
  197. if (empty && list.querySelector('.msg')) empty.remove();
  198. });
  199. }
  200. function wireCompose() {
  201. $$('.thread').forEach(thread => {
  202. const form = thread.querySelector('.thread-compose');
  203. if (!form) return;
  204. form.addEventListener('submit', e => {
  205. e.preventDefault();
  206. const input = form.querySelector('input[name=body]');
  207. const body = input.value.trim();
  208. if (!body) return;
  209. const slug = thread.dataset.vendor;
  210. input.disabled = true;
  211. postForm('bin/messages_post.php', { vendor: slug, body })
  212. .then(r => r.text().then(t => ({ ok: r.ok, body: t, maxId: r.headers.get('X-Msg-Id') })))
  213. .then(res => {
  214. input.disabled = false;
  215. if (!res.ok) { alert('Post failed: ' + res.body); return; }
  216. input.value = '';
  217. input.focus();
  218. const list = thread.querySelector('.thread-list');
  219. const empty = list.querySelector('.msg-empty');
  220. if (empty) empty.remove();
  221. list.insertAdjacentHTML('beforeend', res.body);
  222. list.dataset.maxId = res.maxId || list.dataset.maxId;
  223. list.scrollTop = list.scrollHeight;
  224. })
  225. .catch(err => {
  226. input.disabled = false;
  227. alert('Network error: ' + err.message);
  228. });
  229. });
  230. });
  231. }
  232. // -------- add job (ICG only) --------
  233. // While this is non-null, polling skips auto-reload so the in-progress
  234. // compose form isn't ripped out from under the user.
  235. let composeRowId = null;
  236. function wireAddJob() {
  237. const btn = $('#add-job');
  238. if (!btn) return;
  239. btn.addEventListener('click', () => {
  240. const select = $('#add-job-vendor');
  241. const vendor = select ? select.value : 'bill';
  242. postForm('bin/jobs_add.php', { vendor, ajax: '1' })
  243. .then(r => r.text().then(t => ({ ok: r.ok, body: t })))
  244. .then(res => {
  245. const newId = parseInt((res.body || '').trim(), 10);
  246. if (!res.ok || !Number.isInteger(newId) || newId <= 0) {
  247. alert('Add failed: ' + res.body);
  248. return;
  249. }
  250. return reloadTable().then(() => {
  251. const row = $('#jobs-table tr[data-job-id="' + newId + '"]');
  252. if (row) composeRow(row);
  253. });
  254. })
  255. .catch(err => alert('Network error: ' + err.message));
  256. });
  257. }
  258. // Open every editable cell of `rowEl` as an <input> simultaneously so the
  259. // user can Tab between them. Each input's initial value is captured; on
  260. // exit (Escape, Enter past the last cell, or focus leaving the row) only
  261. // the changed fields are saved in parallel, then the table reloads once.
  262. function composeRow(rowEl) {
  263. const jobId = parseInt(rowEl.dataset.jobId, 10);
  264. composeRowId = jobId;
  265. // Pull the row's delete button out of the tab order so Tab from the last
  266. // field doesn't land on it. (The table reload after finishCompose
  267. // rebuilds the row without this attribute, restoring normal tabbing.)
  268. const deleteBtn = rowEl.querySelector('.btn-delete');
  269. if (deleteBtn) deleteBtn.setAttribute('tabindex', '-1');
  270. const cells = Array.from(rowEl.querySelectorAll('.editable'));
  271. const inputs = cells.map(span => {
  272. const col = span.dataset.column;
  273. const raw = span.dataset.raw !== undefined ? span.dataset.raw : span.textContent.trim();
  274. const initial = raw === '—' ? '' : raw;
  275. const input = document.createElement('input');
  276. input.type = 'text';
  277. input.className = 'inline-edit';
  278. input.value = initial;
  279. input.dataset.column = col;
  280. input.dataset.initial = initial;
  281. // The span owns tabindex=0 so it can be entered from the keyboard, but
  282. // while it hosts a live input we want Tab to jump straight to the input.
  283. span.setAttribute('tabindex', '-1');
  284. span.innerHTML = '';
  285. span.appendChild(input);
  286. return input;
  287. });
  288. inputs.forEach((input, i) => {
  289. input.addEventListener('keydown', e => {
  290. if (e.key === 'Escape') {
  291. e.preventDefault();
  292. finishCompose(rowEl, /*save=*/false);
  293. } else if (e.key === 'Enter') {
  294. e.preventDefault();
  295. if (i + 1 < inputs.length) {
  296. inputs[i + 1].focus();
  297. inputs[i + 1].select();
  298. } else {
  299. finishCompose(rowEl, true);
  300. }
  301. } else if (e.key === 'Tab' && !e.shiftKey && i === inputs.length - 1) {
  302. // Tabbing forward off the last field (Due) commits the new row.
  303. e.preventDefault();
  304. finishCompose(rowEl, true);
  305. }
  306. });
  307. });
  308. // Detect focus genuinely leaving the row (not just hopping between its inputs).
  309. rowEl.addEventListener('focusout', () => {
  310. setTimeout(() => {
  311. if (composeRowId === jobId && !rowEl.contains(document.activeElement)) {
  312. finishCompose(rowEl, true);
  313. }
  314. }, 50);
  315. });
  316. if (inputs[0]) { inputs[0].focus(); inputs[0].select(); }
  317. }
  318. function finishCompose(rowEl, save) {
  319. if (composeRowId === null) return;
  320. const jobId = composeRowId;
  321. composeRowId = null;
  322. const inputs = Array.from(rowEl.querySelectorAll('input.inline-edit'));
  323. const dirty = save ? inputs.filter(i => i.value !== i.dataset.initial) : [];
  324. // Serialize the saves so they queue against the SQLite writer lock
  325. // politely instead of all racing at once.
  326. const failed = [];
  327. const runNext = (i) => {
  328. if (i >= dirty.length) return Promise.resolve();
  329. const input = dirty[i];
  330. return postForm('bin/jobs_update.php', {
  331. job_id: jobId,
  332. column: input.dataset.column,
  333. value: input.value,
  334. })
  335. .then(r => r.text().then(t => {
  336. if (!r.ok || t.trim() !== 'Success') {
  337. failed.push(input.dataset.column + ': ' + t);
  338. }
  339. }))
  340. .then(() => runNext(i + 1));
  341. };
  342. runNext(0)
  343. .then(() => {
  344. if (failed.length) alert('Some saves failed:\n' + failed.join('\n'));
  345. return reloadTable();
  346. })
  347. .catch(err => {
  348. alert('Network error: ' + err.message);
  349. reloadTable();
  350. });
  351. }
  352. // -------- polling --------
  353. function isUserBusy() {
  354. const a = document.activeElement;
  355. if (!a) return false;
  356. const tag = a.tagName;
  357. return tag === 'INPUT' || tag === 'TEXTAREA' || a.isContentEditable;
  358. }
  359. function tick() {
  360. if (isUserBusy()) return;
  361. reloadTable();
  362. reloadAllThreads();
  363. }
  364. document.addEventListener('DOMContentLoaded', () => {
  365. wireAddJob();
  366. wireCompose();
  367. reloadTable();
  368. reloadAllThreads();
  369. const interval = PDQ.pollMs || 180000;
  370. setInterval(tick, interval);
  371. });
  372. })();