formlab-mcp 0.6.96 → 0.6.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/calibration.js CHANGED
@@ -17,7 +17,13 @@ function ctx() {
17
17
  vm.createContext(sandbox);
18
18
  vm.runInContext(src + `
19
19
  ;function __calStatus(json, today) { return JSON.stringify(eqCalStatus(JSON.parse(json), today)); }
20
- ;function __calHistory(json) { return JSON.stringify(eqCalHistory(JSON.parse(json))); }`, sandbox, { timeout: 1000 });
20
+ ;function __calHistory(json) { return JSON.stringify(eqCalHistory(JSON.parse(json))); }
21
+ ;function __doubt(json, today) {
22
+ const p = JSON.parse(json), insOf = (m) => ({ name: m.instrument || '', equipmentId: m.equipmentId || '' });
23
+ const idx = eqCalDoubtIndex(p.equipment, p.tests, insOf, today), out = {};
24
+ p.tests.forEach(t => t.measurements.forEach((m, i) => { const d = eqCalReadingDoubt(m, t, idx, insOf); if (d) { out[t.id] = out[t.id] || {}; out[t.id][i] = d.why; } }));
25
+ return JSON.stringify(out);
26
+ }`, sandbox, { timeout: 1000 });
21
27
  _ctx = sandbox;
22
28
  return _ctx;
23
29
  }
@@ -28,3 +34,22 @@ const _slim = (e) => JSON.stringify({ status: e.status || '', calIntervalMonths:
28
34
  export function calibrationStatus(e, today) { return JSON.parse(ctx().__calStatus(_slim(e), today || _today())); }
29
35
  // Newest first.
30
36
  export function calibrationHistory(e) { return JSON.parse(ctx().__calHistory(_slim(e))); }
37
+
38
+ // Readings in doubt, the app's own rule (eqCalDoubtIndex / eqCalReadingDoubt in the vendored file): a reading taken on an
39
+ // instrument after its last good calibration and up to a failed or out-of-tolerance one, or saved while the instrument
40
+ // was Out of service. resolveIns(m, t) gives { instrument, equipmentId } (analytics.js _resolveInstrument).
41
+ // Returns { [testId]: { [measurementIndex]: why } }. Memoized per loaded store for a few seconds.
42
+ let _doubtMemo = null;
43
+ export function readingDoubts(db, resolveIns, today) {
44
+ if (!db) return {};
45
+ const now = Date.now();
46
+ if (_doubtMemo && _doubtMemo.db === db && now - _doubtMemo.at < 5000) return _doubtMemo.out;
47
+ const equipment = (db.equipment || []).filter(Boolean).map(e => ({ id: e.id, uid: e.uid || '', name: e.name || '', status: e.status || '',
48
+ _trashed: !!e._trashed, calIntervalMonths: e.calIntervalMonths || null, calibrations: Array.isArray(e.calibrations) ? e.calibrations : [] }));
49
+ const tests = (db.testResults || []).filter(t => t && t.id).map(t => ({ id: t.id, testDate: t.testDate || '',
50
+ measurements: (t.measurements || []).map(m => { const r = resolveIns(m, t, db) || {}; return { instrument: r.instrument || '', equipmentId: r.equipmentId || '', ...(m && m.instrumentOos ? { instrumentOos: m.instrumentOos } : {}) }; }) }));
51
+ let out = {};
52
+ try { out = JSON.parse(ctx().__doubt(JSON.stringify({ equipment, tests }), today || _today())); } catch (_) { out = {}; }
53
+ _doubtMemo = { db, at: now, out };
54
+ return out;
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.96",
3
+ "version": "0.6.97",
4
4
  "mcpName": "io.github.juliu1980/formlab-mcp",
5
5
  "description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
6
6
  "homepage": "https://formvix.com/mcp",
package/server.json CHANGED
@@ -2,13 +2,13 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.juliu1980/formlab-mcp",
4
4
  "description": "Read-only MCP server for FormLab formulation data: a local export file or your live cloud workspace.",
5
- "version": "0.6.96",
5
+ "version": "0.6.97",
6
6
  "websiteUrl": "https://formvix.com/mcp",
7
7
  "packages": [
8
8
  {
9
9
  "registryType": "npm",
10
10
  "identifier": "formlab-mcp",
11
- "version": "0.6.96",
11
+ "version": "0.6.97",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
@@ -11,6 +11,7 @@
11
11
  // ============================================================
12
12
 
13
13
  import { getStore, resolveById, flattenComposition, localDay, localToday } from '../data.js';
14
+ import { readingDoubts } from '../calibration.js';
14
15
 
15
16
  // Which instrument produced a measurement. Mirrors the app's _trMeasInstrument:
16
17
  // a measurement's raw `instrument` is usually EMPTY because blank means inherit,
@@ -139,7 +140,7 @@ function _trimMeasurement(m, t, db) {
139
140
  const list_test_results = {
140
141
  definition: {
141
142
  name: 'list_test_results',
142
- description: 'List test result reports, optionally filtered by sample, parameter, measured-value range, grade, text value, run condition, date range, or lab. Combine parameter + value_min/value_max to find reports whose measurement is in range (the "find by results" query, e.g. parameter="Viscosity", value_min=800, value_max=3000). The number a range filter reads: a scalar as recorded, a curve at its final point, a distribution at the statistic its spec names (D90) or else D50; a ranked scale or text result has no number — use min_grade / max_grade (positions on the reading\'s own scale, e.g. parameter="Pencil hardness", min_grade="HB") or value_equals (a text result, case-insensitive). condition narrows to readings under a run condition (substring of e.g. "Storage 40 °C"; "none" = readings with no condition). Returns metadata (incl. the run-level instrument and controlSample flag) + parameters tested; use get_test_result for per-measurement values and their resolved instruments.',
143
+ description: 'List test result reports, optionally filtered by sample, parameter, measured-value range, grade, text value, run condition, date range, or lab. Combine parameter + value_min/value_max to find reports whose measurement is in range (the "find by results" query, e.g. parameter="Viscosity", value_min=800, value_max=3000). The number a range filter reads: a scalar as recorded, a curve at its final point, a distribution at the statistic its spec names (D90) or else D50; a ranked scale or text result has no number — use min_grade / max_grade (positions on the reading\'s own scale, e.g. parameter="Pencil hardness", min_grade="HB") or value_equals (a text result, case-insensitive). condition narrows to readings under a run condition (substring of e.g. "Storage 40 °C"; "none" = readings with no condition). Returns metadata (incl. the run-level instrument and controlSample flag) + parameters tested, and readingsInDoubt (count) when some readings are in doubt; use get_test_result for per-measurement values, their resolved instruments and inDoubt reasons.',
143
144
  inputSchema: {
144
145
  type: 'object',
145
146
  properties: {
@@ -210,7 +211,7 @@ const list_test_results = {
210
211
  return {
211
212
  totalMatching: filtered.length,
212
213
  returned: Math.min(filtered.length, limit),
213
- testResults: filtered.slice(0, limit).map(t => _trimTest(t, indexes.samplesById)),
214
+ testResults: filtered.slice(0, limit).map(t => { const dz = readingDoubts(getStore().db, _resolveInstrument)[t.id]; const n = dz ? Object.keys(dz).length : 0; return { ..._trimTest(t, indexes.samplesById), ...(n ? { readingsInDoubt: n } : {}) }; }),
214
215
  };
215
216
  },
216
217
  };
@@ -218,7 +219,7 @@ const list_test_results = {
218
219
  const get_test_result = {
219
220
  definition: {
220
221
  name: 'get_test_result',
221
- description: 'Get full details for a single test result report: every measurement\'s value, unit, type, acceptance criteria, captured run CONDITIONS (e.g. {Storage:"40 °C / 75% RH"} — the storage/temp/RPM the reading was measured under, so it is self-describing and comparable across runs; present only when captured), and the INSTRUMENT that produced it. instrument is RESOLVED (measurement override → the parameter\'s Test Method equipment → the report default) with instrumentSource telling you which — treat source "run" as an inherited assumption, not evidence. For complex measurements a `representative` value is included (time_series → final point, distribution → D50); a time_series also carries `aggregated` (per-timestamp mean ± sd) and `pointReplicates` (true when a timestamp has repeat readings — POINT replicates, averaged per t). The report-level `seriesReplicates` lists parameters measured 2+ times as SEPARATE rows (SERIES replicates). These two notions are different: point replicates are within one run, series replicates are repeated runs. Accepts internal id or UID.',
222
+ description: 'Get full details for a single test result report: every measurement\'s value, unit, type, acceptance criteria, captured run CONDITIONS (e.g. {Storage:"40 °C / 75% RH"} — the storage/temp/RPM the reading was measured under, so it is self-describing and comparable across runs; present only when captured), and the INSTRUMENT that produced it. instrument is RESOLVED (measurement override → the parameter\'s Test Method equipment → the report default) with instrumentSource telling you which — treat source "run" as an inherited assumption, not evidence. For complex measurements a `representative` value is included (time_series → final point, distribution → D50); a time_series also carries `aggregated` (per-timestamp mean ± sd) and `pointReplicates` (true when a timestamp has repeat readings — POINT replicates, averaged per t). The report-level `seriesReplicates` lists parameters measured 2+ times as SEPARATE rows (SERIES replicates). These two notions are different: point replicates are within one run, series replicates are repeated runs. A measurement carries `inDoubt` (the reason) when its instrument failed (or was found out of tolerance at) a calibration after its last good one and the reading falls in that window, or the instrument was Out of service when the report was saved; the value and passFail are unchanged, but say so and recommend a retest before relying on it. Accepts internal id or UID.',
222
223
  inputSchema: {
223
224
  type: 'object',
224
225
  properties: {
@@ -250,7 +251,9 @@ const get_test_result = {
250
251
  // Parameters measured 2+ times as separate rows (series replicates). Empty
251
252
  // when none. Point replicates live on each measurement (`pointReplicates`).
252
253
  seriesReplicates,
253
- measurements: (t.measurements || []).map(m => _trimMeasurement(m, t, getStore().db)),
254
+ // inDoubt (the app's amber "In doubt"): why this reading is suspect: its instrument failed calibration in its
255
+ // window, or was Out of service when the report was saved. Value and passFail are unchanged.
256
+ measurements: (t.measurements || []).map((m, i) => { const dz = readingDoubts(getStore().db, _resolveInstrument)[t.id]; return { ..._trimMeasurement(m, t, getStore().db), ...(dz && dz[i] ? { inDoubt: dz[i] } : {}) }; }),
254
257
  };
255
258
  },
256
259
  };
@@ -112,8 +112,15 @@ function eqCalStatusText(st) {
112
112
  if (st.state === 'soon') return d === 0 ? `Due today` : `Due in ${d} d · ${st.due}`;
113
113
  return st.due ? `OK · due ${st.due}` : 'OK';
114
114
  }
115
- function eqCalChipHtml(st) {
115
+ // short: the state alone, for the Calibration card, whose row goes on to say Next due (30 Nov: "OK · due 2027-11-30"
116
+ // sat right before "Next due 2027-11-30"). The Equipment list keeps the date in its chip.
117
+ function eqCalChipHtml(st, short) {
116
118
  if (!st || st.state === 'none') return '<span style="color:var(--dk-dim, #cbd5e1)">—</span>';
119
+ if (short) {
120
+ const d = st.daysToDue;
121
+ const t = { ok: 'OK', never: 'Never calibrated', failed: 'Failed calibration', overdue: `Overdue ${-d} d`, soon: d === 0 ? 'Due today' : `Due in ${d} d` }[st.state] || eqCalStatusText(st);
122
+ return `<span class="badge eq-cal-chip" style="${_EQ_CAL_TONE[st.state] || ''};font-size:11px">${esc(t)}</span>`;
123
+ }
117
124
  return `<span class="badge eq-cal-chip" style="${_EQ_CAL_TONE[st.state] || ''};font-size:11px" title="${esc(st.last ? `Last calibrated ${st.last}${st.lastResult ? ' (' + (_EQ_CAL_RESULT_LABEL[st.lastResult] || st.lastResult) + ')' : ''}` : 'No calibration logged yet')}">${esc(eqCalStatusText(st))}</span>`;
118
125
  }
119
126
  // Sort key for the list column: most urgent first when ascending.
@@ -127,12 +134,18 @@ function eqCalSortKey(e) {
127
134
  // said which of its 8 reports came after its last pass). The latest entry must be a Fail or an Adjusted (out of
128
135
  // tolerance as found). Suspect = reports dated after the last good calibration before it: up to today for a Fail
129
136
  // (it may still be in use), up to the adjustment for Adjusted. `tests` = the reports that used this unit.
137
+ // A pass logged after the repair does not clear them (30 Nov, Jun: "Yes, keep it"; the banner vanished while the 28 Aug -
138
+ // 30 Nov readings were still in doubt): the bad entry may be the latest, or the one just before the repair's pass. The
139
+ // window for a Fail then ends at that pass. The next routine calibration after that (two entries on) closes it.
130
140
  function eqCalSuspect(e, tests, todayIso) {
131
- const hist = eqCalHistory(e), bad = hist[0];
141
+ const hist = eqCalHistory(e);
132
142
  const res = (c) => String((c && c.result) || '').trim().toLowerCase();
133
- if (!bad || !['fail', 'adjusted'].includes(res(bad))) return null;
134
- const good = hist.slice(1).find(c => ['pass', 'adjusted'].includes(res(c)));
135
- const since = (good && good.date) || '', until = res(bad) === 'adjusted' ? (bad.date || '') : (todayIso || _eqCalToday());
143
+ const i = hist.findIndex(c => ['fail', 'adjusted'].includes(res(c)));
144
+ if (i < 0 || i > 1) return null;
145
+ const bad = hist[i], fixed = i === 1 ? hist[0] : null;
146
+ if (fixed && !['pass', 'adjusted'].includes(res(fixed))) return null;
147
+ const good = hist.slice(i + 1).find(c => ['pass', 'adjusted'].includes(res(c)));
148
+ const since = (good && good.date) || '', until = res(bad) === 'adjusted' ? (bad.date || '') : ((fixed && fixed.date) || todayIso || _eqCalToday());
136
149
  const day = (t) => String((t && t.testDate) || '').split('T')[0];
137
150
  const hit = (tests || []).filter(t => { const d = day(t); return d && (!since || d > since) && (!until || d <= until); })
138
151
  .sort((a, b) => day(a).localeCompare(day(b)));
@@ -142,7 +155,47 @@ function eqCalSuspect(e, tests, todayIso) {
142
155
  const b = sm && sm.batchId ? (db.batches || []).find(x => x && x.id === sm.batchId && !x._trashed) : null;
143
156
  if (b && !batches.includes(b)) batches.push(b);
144
157
  });
145
- return { kind: res(bad), at: bad.date || '', since, until, tests: hit, batches };
158
+ return { kind: res(bad), at: bad.date || '', since, until, fixedAt: fixed ? (fixed.date || '') : '', tests: hit, batches };
159
+ }
160
+
161
+ // ---- Readings in doubt (Jun, 30 Nov: "Flag doubtful readings"; shared with the MCP server) ----
162
+ // A reading is in doubt when it was saved while its instrument was Out of service (m.instrumentOos, stamped by the app's
163
+ // test save) or it falls in a failed / out-of-tolerance calibration's window (eqCalSuspect). insOf(m, t) resolves a
164
+ // reading's instrument to { name, equipmentId } (the app's _trMeasInstrument; the MCP server passes it resolved).
165
+ // eqCalDoubtIndex: Map testId → [{ eqId, lname, why }]; eqCalReadingDoubt: { why } or null.
166
+ function eqCalDoubtIndex(equipment, tests, insOf, todayIso) {
167
+ const map = new Map();
168
+ const res = (c) => String((c && c.result) || '').trim().toLowerCase();
169
+ (equipment || []).forEach(e => {
170
+ if (!e || e._trashed) return;
171
+ if (!eqCalHistory(e).slice(0, 2).some(c => res(c) === 'fail' || res(c) === 'adjusted')) return; // nothing to doubt
172
+ const lname = String(e.name || '').trim().toLowerCase();
173
+ const match = (m, t) => { const r = (insOf && insOf(m, t)) || {}; return r.equipmentId ? r.equipmentId === e.id : (!!lname && String(r.name || '').trim().toLowerCase() === lname); };
174
+ const used = (tests || []).filter(t => t && (t.measurements || []).some(m => match(m, t)));
175
+ const sus = eqCalSuspect(e, used, todayIso);
176
+ if (!sus || !sus.tests.length) return;
177
+ const name = e.name || e.uid || 'its instrument';
178
+ const from = sus.since ? `after its last good calibration (${sus.since})` : 'before any good calibration on record';
179
+ const why = sus.kind === 'adjusted' ? `Taken on ${name} ${from}; it was found out of tolerance on ${sus.at}.`
180
+ : sus.fixedAt ? `Taken on ${name} ${from} and before the repair passed on ${sus.fixedAt}; it failed calibration on ${sus.at}.`
181
+ : `Taken on ${name} ${from}; it failed calibration on ${sus.at} and has not passed since.`;
182
+ // short: the same in a few words, for compact uses (the AI context).
183
+ const short = `${name} ${sus.kind === 'adjusted' ? 'out of tolerance' : 'failed calibration'} ${sus.at}`;
184
+ const d = { eqId: e.id, lname, why, short };
185
+ sus.tests.forEach(t => { if (!map.has(t.id)) map.set(t.id, []); map.get(t.id).push(d); });
186
+ });
187
+ return map;
188
+ }
189
+ function eqCalReadingDoubt(m, t, index, insOf) {
190
+ if (!m) return null;
191
+ if (m.instrumentOos) return { why: `Measured while ${m.instrumentOos.name || 'its instrument'} was Out of service${m.instrumentOos.at ? ' (' + m.instrumentOos.at + ')' : ''}.`,
192
+ short: `${m.instrumentOos.name || 'instrument'} Out of service${m.instrumentOos.at ? ' ' + m.instrumentOos.at : ''}` };
193
+ const list = t && index ? index.get(t.id) : null;
194
+ if (!list) return null;
195
+ const r = (insOf && insOf(m, t)) || {};
196
+ const nm = String(r.name || '').trim().toLowerCase();
197
+ const hit = list.find(d => r.equipmentId ? r.equipmentId === d.eqId : (!!nm && nm === d.lname));
198
+ return hit ? { why: hit.why, short: hit.short } : null;
146
199
  }
147
200
 
148
201
  // ---- The Calibration card on the equipment page ----
@@ -169,10 +222,9 @@ function eqCalCardHtml(e) {
169
222
  const summary = st.state === 'none'
170
223
  ? `<div style="color:var(--text-muted);font-size:13px">Not tracked yet. Set how often it is calibrated, or log its last calibration.</div>`
171
224
  : `<div style="display:flex;flex-wrap:wrap;gap:10px 22px;align-items:center;font-size:13px">
172
- ${eqCalChipHtml(st)}
225
+ ${eqCalChipHtml(st, true)}
173
226
  <span><span style="color:var(--text-muted)">Last</span> <strong>${esc(st.last || '—')}</strong>${st.lastResult ? ` · ${esc(_EQ_CAL_RESULT_LABEL[st.lastResult] || st.lastResult)}` : ''}</span>
174
227
  <span><span style="color:var(--text-muted)">Next due</span> <strong>${esc(st.due || '—')}</strong></span>
175
- <span><span style="color:var(--text-muted)">Interval</span> <strong>${interval ? interval + ' month' + (interval === 1 ? '' : 's') : '—'}</strong></span>
176
228
  </div>${st.state === 'failed' && e.status !== 'Out of service' ? `<div style="margin-top:10px;font-size:12.5px;color:var(--dk-red-fg, #b91c1c)">The latest calibration failed. Set the instrument <strong>Out of service</strong> (the status beside its name) until it passes again.</div>` : ''}${
177
229
  // Dogfooding, 22 Nov (pH meter back in service): the card read "OK · due 2027-11-22" under an Out of service
178
230
  // badge and said nothing, where a failed calibration says to take the unit out. The way back is said too.
@@ -180,16 +232,26 @@ function eqCalCardHtml(e) {
180
232
  const sus = typeof _eqUsageTests === 'function' ? eqCalSuspect(e, _eqUsageTests(e)) : null;
181
233
  const susHtml = sus && sus.tests.length ? (() => {
182
234
  const uids = sus.tests.map(t => t.uid).filter(Boolean);
183
- const bl = sus.batches.slice(0, 8).map(b => `<a style="cursor:pointer;color:inherit;text-decoration:underline" onclick="navigate('batch-detail','${_eqCalJs(b.id)}')">${esc(b.uid || '')}</a>`).join(', ') + (sus.batches.length > 8 ? ` +${sus.batches.length - 8}` : '');
235
+ // Counts, not a run of eight batch links and "+79" (30 Nov layout check): the Equipment report and Test Reports list them.
184
236
  const when = sus.since ? `since its last good calibration (${esc(sus.since)})` : 'before any good calibration on record';
185
- const head = sus.kind === 'adjusted' ? `Found out of tolerance on ${esc(sus.at)}: <strong>${sus.tests.length} test report${sus.tests.length === 1 ? '' : 's'}</strong> used it ${when}.` : `<strong>${sus.tests.length} test report${sus.tests.length === 1 ? '' : 's'}</strong> used it ${when}.`;
186
- return `<div class="eq-cal-suspect" style="margin-top:10px;padding:8px 10px;border-radius:8px;font-size:12.5px;background:var(--dk-amber-bg2, #fef3c7);color:var(--dk-amber-fg, #92400e)">${head}${sus.batches.length ? ` Batches: ${bl}.` : ''} Check whether to retest. <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline" onclick="openRecordsInList('test','${_eqCalJs(uids.join(','))}')">Open ${uids.length === 1 ? 'it' : 'them'} in Test Reports</a></div>`;
237
+ const n = `<strong>${sus.tests.length} test report${sus.tests.length === 1 ? '' : 's'}</strong>${sus.batches.length ? ` and <strong>${sus.batches.length} batch${sus.batches.length === 1 ? '' : 'es'}</strong>` : ''}`;
238
+ const head = sus.kind === 'adjusted' ? `Found out of tolerance on ${esc(sus.at)}: ${n} used it ${when}.`
239
+ : sus.fixedAt ? `Failed on ${esc(sus.at)}, passed again on ${esc(sus.fixedAt)}: ${n} used it ${when} until then.`
240
+ : `${n} used it ${when}.`;
241
+ return `<div class="eq-cal-suspect" style="margin-top:10px;padding:8px 10px;border-radius:8px;font-size:12.5px;background:var(--dk-amber-bg2, #fef3c7);color:var(--dk-amber-fg, #92400e)">${head} Check whether to retest. <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline;white-space:nowrap" onclick="openRecordsInList('test','${_eqCalJs(uids.join(','))}')">Open ${uids.length === 1 ? 'it' : 'them'} in Test Reports</a>${(() => { const open = sus.batches.filter(b => !(b.fgHold && b.fgHold.at && !b.fgHold.releasedAt) && !['Planned', 'Cancelled', 'Failed'].includes(b.status)).length;
242
+ // One step to hold what these readings went into (30 Nov, Jun: "Yes, add it"; 81 batches had to be held one by one).
243
+ // A link like "Open them in Test Reports" beside it (Jun: the button "looks ugly").
244
+ // How many already are, once some are (dogfooding 30 Nov: after the hold the link just went away).
245
+ const onHold = sus.batches.filter(b => b.fgHold && b.fgHold.at && !b.fgHold.releasedAt).length;
246
+ const heldTxt = onHold ? ` · <span style="white-space:nowrap">${onHold} on hold</span>` : '';
247
+ return (open && typeof flEqHoldSuspectUI === 'function' ? ` · <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline;white-space:nowrap" onclick="flEqHoldSuspectUI('${_eqCalJs(e.id)}')">Put ${open} batch${open === 1 ? '' : 'es'} on hold</a>` : '') + heldTxt; })()}</div>`;
187
248
  })() : '';
249
+ // Dates never wrap ("2026-11-/30" in a narrow window, 30 Nov Definition tab check).
188
250
  const rows = hist.map(c => `<tr>
189
- <td style="font-variant-numeric:tabular-nums">${esc(c.date || '—')}</td>
251
+ <td style="font-variant-numeric:tabular-nums;white-space:nowrap">${esc(c.date || '—')}</td>
190
252
  <td>${esc(c.by || '—')}</td>
191
253
  <td>${c.result ? `<span class="badge" style="${_EQ_CAL_TONE[c.result === 'fail' ? 'failed' : c.result === 'adjusted' ? 'soon' : 'ok']};font-size:11px">${esc(_EQ_CAL_RESULT_LABEL[c.result] || c.result)}</span>` : '—'}</td>
192
- <td style="font-variant-numeric:tabular-nums">${esc((String(c.result || '').toLowerCase() === 'fail' ? '' : c.nextDue) || '—')}</td>
254
+ <td style="font-variant-numeric:tabular-nums;white-space:nowrap">${esc((String(c.result || '').toLowerCase() === 'fail' ? '' : c.nextDue) || '—')}</td>
193
255
  <td>${c.certificateId && certName(c.certificateId) ? `<a style="color:var(--primary);cursor:pointer" onclick="attachOpenInTab('${_eqCalJs(c.certificateId)}')">${esc(certName(c.certificateId))}</a>` : (c.certificateRef ? esc(c.certificateRef) : '<span style="color:var(--dk-dim, #cbd5e1)">—</span>')}</td>
194
256
  <td style="color:var(--text-muted);max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${esc(c.notes || '')}">${esc(c.notes || '')}</td>
195
257
  <td style="text-align:right;white-space:nowrap">${on ? `<button class="btn btn-secondary btn-sm" onclick="openEqCalLogModal('${_eqCalJs(e.id)}','${_eqCalJs(c.id)}')" title="Edit this calibration">${typeof ICON !== 'undefined' && ICON.edit ? ICON.edit : 'Edit'}</button>` : ''}</td>
@@ -232,6 +294,13 @@ function _eqCalResultDue(sel, interval) {
232
294
  const d = document.getElementById('eq-cal-due'); if (!d || !sel) return;
233
295
  const fail = sel.value === 'fail';
234
296
  d.disabled = fail;
297
+ // The +6 mo / +1 yr / +2 yr shortcuts sit in the label, on the box's top-right corner like every other date field (30
298
+ // Nov, Jun: "+xx month should be on top of the date box like everywhere else"; the label line is the box's width in styles.css),
299
+ // and go with it when a Fail leaves nothing to set.
300
+ const q = document.getElementById('eq-cal-due-quick'); if (q) q.style.display = fail ? 'none' : '';
301
+ // The hint says why the box is empty (dogfooding 30 Nov: "No interval set: enter it here" stayed under a locked box).
302
+ const h = document.getElementById('eq-cal-due-hint');
303
+ if (h) { if (!h.dataset.base) h.dataset.base = h.textContent; h.textContent = fail ? 'None while it fails: log a passing calibration after the repair.' : h.dataset.base; }
235
304
  if (fail) { d.dataset.was = d.value; d.value = ''; d.placeholder = 'After it passes'; }
236
305
  else if (!d.value) d.value = d.dataset.was || _eqCalAddMonths((document.getElementById('eq-cal-date') || {}).value || _eqCalToday(), interval) || '';
237
306
  }
@@ -248,8 +317,6 @@ function openEqCalLogModal(eqId, calId) {
248
317
  }
249
318
  const interval = eqCalInterval(e);
250
319
  const date = c ? (c.date || '') : _eqCalToday();
251
- const files = Array.isArray(e.fileAttachments) ? e.fileAttachments : [];
252
- const certOpts = `<option value="">— None —</option>` + files.map(a => `<option value="${esc(a.id)}"${c && c.certificateId === a.id ? ' selected' : ''}>${esc(a.name || a.title || a.url || a.id)}</option>`).join('');
253
320
  const hint = (t) => `<div style="font-size:11.5px;color:var(--text-muted);margin-top:4px;line-height:1.4">${t}</div>`;
254
321
  const body = `<div class="form-grid">
255
322
  <div class="form-group"><label>Date calibrated *</label><input id="eq-cal-date" type="date" value="${esc(date)}" max="${_eqCalToday()}" onchange="_eqCalAutoDue(${interval})"></div>
@@ -257,14 +324,11 @@ function openEqCalLogModal(eqId, calId) {
257
324
  <div class="form-group span-2"><label>Result *</label>
258
325
  <select id="eq-cal-result" onchange="_eqCalResultDue(this, ${interval})">${EQ_CAL_RESULTS.map(r => `<option value="${r.value}"${(c ? c.result : 'pass') === r.value ? ' selected' : ''}>${esc(r.label)} — ${esc(r.hint)}</option>`).join('')}</select>
259
326
  </div>
260
- <div class="form-group"><label>Next due ${typeof flDateQuickHtml === 'function' ? flDateQuickHtml('eq-cal-due', { from: 'eq-cal-date', fromLabel: 'calibration date', add: [[6, 'm'], [1, 'y'], [2, 'y']] }) : ''}</label>
327
+ <div class="form-group"><label>Next due<span id="eq-cal-due-quick"${c && c.result === 'fail' ? ' style="display:none"' : ''}>${typeof flDateQuickHtml === 'function' ? flDateQuickHtml('eq-cal-due', { from: 'eq-cal-date', fromLabel: 'calibration date', add: [[6, 'm'], [1, 'y'], [2, 'y']] }) : ''}</span></label>
261
328
  <input id="eq-cal-due" type="date" value="${esc(c ? (c.nextDue || '') : _eqCalAddMonths(date, interval))}" data-auto="${c && c.nextDue ? '0' : '1'}" oninput="this.dataset.auto='0'"${c && c.result === 'fail' ? ' disabled placeholder="After it passes"' : ''}>
262
- ${hint(interval ? `From the interval (every ${interval} month${interval === 1 ? '' : 's'}); change it for this one if needed.` : 'No interval set: enter it here, or set one on the Calibration card.')}
263
- </div>
264
- <div class="form-group"><label>Certificate</label>
265
- ${files.length ? `<select id="eq-cal-cert">${certOpts}</select>` : `<input id="eq-cal-certref" value="${esc(c ? (c.certificateRef || '') : '')}" placeholder="Certificate no.">`}
266
- ${hint(files.length ? 'One of this instrument\'s files. Upload more on its Attachments card.' : 'Or upload the certificate on this instrument\'s Attachments card to pick it here.')}
329
+ <div id="eq-cal-due-hint" style="font-size:11.5px;color:var(--text-muted);margin-top:4px;line-height:1.4">${c && c.result === 'fail' ? 'None while it fails: log a passing calibration after the repair.' : interval ? `From the interval (every ${interval} month${interval === 1 ? '' : 's'}); change it for this one if needed.` : 'No interval set: enter it here, or set one on the Calibration card.'}</div>
267
330
  </div>
331
+ <div class="form-group" id="eq-cal-cert-wrap">${_eqCalCertFieldHtml(e, c)}</div>
268
332
  <div class="form-group span-2"><label>Notes</label><textarea id="eq-cal-notes" style="min-height:56px" placeholder="As-found / as-left readings, standards used, provider…">${esc(c ? (c.notes || '') : '')}</textarea></div>
269
333
  </div>`;
270
334
  showModal(c ? 'Edit calibration' : 'Log calibration', body, () => {
@@ -289,12 +353,17 @@ function openEqCalLogModal(eqId, calId) {
289
353
  const list = (cur.calibrations || []).filter(x => x && x.id !== rec.id);
290
354
  list.push(rec);
291
355
  const patch = { calibrations: list };
356
+ // A new Fail takes an In-service instrument out of service in the same save (dogfooding 30 Nov: the result reads
357
+ // "Fail — out of tolerance; take it out of service", yet Tara had to open the status dialog as a second step). A
358
+ // calibrator may set In service / Out of service (0186); Retired is left alone.
359
+ const outNow = !c && rec.result === 'fail' && (cur.status || 'In service') === 'In service';
360
+ if (outNow) patch.status = 'Out of service';
292
361
  updateEquipment(eqId, patch);
293
362
  if (typeof renderEquipmentDetail === 'function' && typeof currentView !== 'undefined' && currentView === 'equipment-detail') renderEquipmentDetail(eqId);
294
- toast(c ? 'Calibration updated.' : (rec.result === 'fail' ? 'Calibration logged as failed. Set the instrument Out of service until it passes.'
363
+ toast(c ? 'Calibration updated.' : (rec.result === 'fail' ? (outNow ? 'Calibration logged as failed. The instrument is now Out of service until it passes.' : 'Calibration logged as failed. Keep the instrument out of use until it passes.')
295
364
  : (cur.status === 'Out of service' ? 'Calibration logged. The instrument is still Out of service.' : 'Calibration logged.')));
296
365
  return true;
297
- }, true, null, c ? 'Save' : 'Log calibration');
366
+ }, false, null, c ? 'Save' : 'Log calibration'); // the standard width (30 Nov: "this modal view is too wide")
298
367
  if (c) {
299
368
  // Delete sits in the dialog's footer, left of the buttons.
300
369
  setTimeout(() => {
@@ -303,6 +372,42 @@ function openEqCalLogModal(eqId, calId) {
303
372
  }, 0);
304
373
  }
305
374
  }
375
+ // The Certificate field of Log calibration, with Upload on its label line (30 Nov, Jun: "should we add a button to
376
+ // upload certificate or failure report?" → "Yes, add it"). The file lands on the instrument's Attachments, as one
377
+ // uploaded there would, and is picked here. Adding a file here asks equipment.calibrate, as logging does (0266, Jun
378
+ // 30 Nov: a Technician attaches the certificate too; the server lets a calibrator add files, never change or remove one).
379
+ function _eqCalCertFieldHtml(e, c, pickId) {
380
+ const files = Array.isArray(e.fileAttachments) ? e.fileAttachments : [];
381
+ const sel = pickId || (c && c.certificateId) || '';
382
+ const hint = (t) => `<div style="font-size:11.5px;color:var(--text-muted);margin-top:4px;line-height:1.4">${t}</div>`;
383
+ const may = !(typeof flFileCapMissing === 'function' && flFileCapMissing('equipment', 'equipment.calibrate'));
384
+ // A quiet link on the label line, like the date shortcuts (30 Nov, Jun: the documents' button above the field "is
385
+ // ugly, maybe go back and make it subtle"; and no "…"). A span, not a button: a <label> adopts a button inside it.
386
+ const up = may && typeof attachAdd === 'function' ? `<span class="fl-dq"><span class="fl-dq-link" role="button" tabindex="0" onclick="_eqCalUploadCert('${_eqCalJs(e.id)}')" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();this.click();}">Upload</span></span>` : '';
387
+ const opts = `<option value="">— None —</option>` + files.map(a => `<option value="${esc(a.id)}"${sel === a.id ? ' selected' : ''}>${esc(a.name || a.title || a.url || a.id)}</option>`).join('');
388
+ return `<label>Certificate${up}</label>
389
+ ${files.length ? `<select id="eq-cal-cert">${opts}</select>` : `<input id="eq-cal-certref" value="${esc(c ? (c.certificateRef || '') : '')}" placeholder="Certificate no.">`}
390
+ ${hint(may ? 'Upload the certificate or the failure report: it is kept on this instrument\'s Attachments.' : 'A lab manager or a formulator can attach the certificate to this instrument; then pick it here.')}`;
391
+ }
392
+ function _eqCalUploadCert(eqId) {
393
+ const inp = document.createElement('input');
394
+ inp.type = 'file'; inp.accept = '.pdf,image/*,.doc,.docx,.xlsx,.csv,.txt';
395
+ inp.onchange = async () => {
396
+ const file = inp.files && inp.files[0]; if (!file) return;
397
+ const v = typeof attachValidateFile === 'function' ? attachValidateFile(file) : { ok: true };
398
+ if (!v.ok) { toast(v.reason); return; }
399
+ const wrap = document.getElementById('eq-cal-cert-wrap');
400
+ if (wrap) wrap.style.opacity = '.6';
401
+ try {
402
+ const id = await attachAdd('equipment', eqId, 'upload', { name: file.name, mime: file.type, size: file.size, blob: file, cap: 'equipment.calibrate' });
403
+ const e = (typeof getEquipment === 'function' ? getEquipment(eqId) : null) || (db.equipment || []).find(x => x.id === eqId);
404
+ if (wrap && e) wrap.innerHTML = _eqCalCertFieldHtml(e, null, id);
405
+ toast(`Attached "${file.name}" to this instrument.`);
406
+ } catch (err) { toast(err && err.message ? err.message : 'Could not attach the file.'); }
407
+ finally { if (wrap) wrap.style.opacity = ''; }
408
+ };
409
+ inp.click();
410
+ }
306
411
  // Keep "Next due" following the date while it hasn't been typed over.
307
412
  function _eqCalAutoDue(interval) {
308
413
  const due = document.getElementById('eq-cal-due'), d = document.getElementById('eq-cal-date');
@@ -1575,16 +1575,19 @@ function _tpFieldPaletteHtml(evalRows, params, currentParamId) {
1575
1575
  const numNote = `<span style="font-size:11px;color:var(--dk-amber-fg, #b45309)">No numeric fields on these ingredients yet — add values like density, or a custom field such as “solids”, on the Ingredients page to use them here.</span>`;
1576
1576
 
1577
1577
  return `
1578
+ <details class="tp-palette-fold" style="margin-top:6px">
1579
+ <summary style="cursor:pointer;font-size:12px;color:var(--primary);list-style:none;width:fit-content">Show fields</summary>
1578
1580
  <div style="margin-top:6px;padding:9px 11px;background:var(--dk-subtle, #f8fafc);border:1px solid var(--border);border-radius:6px">
1579
1581
  <div style="font-size:11.5px;color:var(--text-muted);margin-bottom:7px;line-height:1.55">
1580
- <strong style="color:var(--text)">Click to build.</strong> A formula runs across every ingredient row, so wrap fields in an aggregation like <code>SUM()</code> or <code>AVG()</code>. Try: click <code>AVG()</code>, then (cursor inside the brackets) click <code>ing.density</code>.
1582
+ Wrap fields in an aggregation: click <code>AVG()</code>, then <code>ing.density</code>.
1581
1583
  </div>
1582
1584
  ${group('Aggregations', aggs)}
1583
1585
  ${group('Row fields', rowChips)}
1584
1586
  ${group('Ingredient numbers', numChips || numNote)}
1585
1587
  ${group('Ingredient text', txtChips)}
1586
1588
  ${group('Other parameters', paramChips)}
1587
- </div>`;
1589
+ </div>
1590
+ </details>`;
1588
1591
  }
1589
1592
 
1590
1593
  function openTheoreticalParamModal(entityType, entityId, paramId) {
@@ -1614,7 +1617,7 @@ function openTheoreticalParamModal(entityType, entityId, paramId) {
1614
1617
  <div class="form-group span-2">
1615
1618
  <label>Formula *</label>
1616
1619
  <textarea id="tp-formula" style="min-height:60px;font-family:ui-monospace,monospace;font-size:13px"
1617
- placeholder="AVG(ing.density) — or click the chips below to build one"
1620
+ placeholder="e.g. AVG(ing.density)"
1618
1621
  oninput="_tpRefreshPreview('${entityType}','${entityId}')">${esc(initialFormula)}</textarea>
1619
1622
  ${_tpFieldPaletteHtml(evalRows, params, p?.id)}
1620
1623
  </div>
@@ -1627,11 +1630,11 @@ function openTheoreticalParamModal(entityType, entityId, paramId) {
1627
1630
  <input id="tp-unit" value="${esc(initialUnit)}" placeholder="%, mg KOH/g, g/L, kcal/100g, …" />
1628
1631
  </div>
1629
1632
  <div class="form-group">
1630
- <label>Spec min <span style="font-weight:400;color:var(--text-muted);text-transform:none;letter-spacing:0">(optional)</span></label>
1633
+ <label>Spec min</label>
1631
1634
  <input id="tp-spec-min" type="number" step="any" value="${esc(initialSpecMin)}" oninput="_tpRefreshPreview('${entityType}','${entityId}')" />
1632
1635
  </div>
1633
1636
  <div class="form-group">
1634
- <label>Spec max <span style="font-weight:400;color:var(--text-muted);text-transform:none;letter-spacing:0">(optional)</span></label>
1637
+ <label>Spec max</label>
1635
1638
  <input id="tp-spec-max" type="number" step="any" value="${esc(initialSpecMax)}" oninput="_tpRefreshPreview('${entityType}','${entityId}')" />
1636
1639
  </div>
1637
1640
  <div class="form-group span-2">
@@ -1641,7 +1644,7 @@ function openTheoreticalParamModal(entityType, entityId, paramId) {
1641
1644
  <div class="form-group span-2">
1642
1645
  <label style="display:flex;align-items:flex-start;gap:8px;cursor:pointer;text-transform:none;letter-spacing:0;font-weight:500">
1643
1646
  <input id="tp-pinned" type="checkbox" ${initialPinned ? 'checked' : ''} style="width:auto;margin:0" />
1644
- Pin to summary<br><span style="font-weight:400;color:var(--text-muted)">Shows this value as a chip on the formula &amp; batch summary, not just the parameters tab</span>
1647
+ <span>Pin to summary<span style="display:block;font-weight:400;font-size:12px;color:var(--text-muted)">Shows this value as a chip on the formula and batch summary</span></span>
1645
1648
  </label>
1646
1649
  </div>
1647
1650
  </div>
@@ -1681,9 +1684,8 @@ function openTheoreticalParamModal(entityType, entityId, paramId) {
1681
1684
  else renderFormulationDetail(entityId);
1682
1685
  });
1683
1686
 
1684
- // A touch wider than the default modal — the formula, click-to-build palette
1685
- // and the result card breathe better with the extra room (chips wrap less).
1686
- document.querySelector('#modal-backdrop > .modal')?.classList.add('tp-modal-wide');
1687
+ // Standard 640 (Jun, 30 Nov: Add dialogs review): the chip palette folds
1688
+ // behind "Show fields", so the 780 "tp-modal-wide" is gone.
1687
1689
  // Fire an initial preview render
1688
1690
  setTimeout(() => _tpRefreshPreview(entityType, entityId), 0);
1689
1691
  }