formlab-mcp 0.6.93 → 0.6.95

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/README.md CHANGED
@@ -41,8 +41,8 @@ Ask Claude (or another MCP client) things like:
41
41
  | `get_supplier` | One supplier in full: record, every ingredient it's an approved source for, every lot from it, and the **recall trace** (batches that consumed those lots → products, shipments, samples, sub-batches; lots on hold flagged) |
42
42
  | `list_documents` | The document register (same as the app's Documents page): ingredient SDS / PDS / CoA / other with lot, version, source and expiry; test and notebook attachments; per-record uploads and links (formulas, batches, samples, suppliers, equipment…). File **metadata** only, never the text inside a file, with who added each file (`addedBy`) and when. Filters: `type`, `record`, `linked`, `query`, `lot`, `format`, `expiry`, `expiring_within_days`, `without_expiry`, `uploaded_within_days`, `added_by`. A `summary` block carries the page's tile counts: expired, expiring in 30 days, SDS/CoA without expiry, ingredients missing an SDS (+ coverage %), lots in stock without a CoA, added last 7 days |
43
43
  | `list_inventory` | Portfolio stock rollup — one row per ingredient with on-hand qty, summed lot balance, nearest expiry, a low-stock flag (on-hand ≤ `reorderThreshold`, or zero), and stock on hold (`heldQty` plus `lotsOnHold`: lot number, quantity, reason, since; a held lot with stock left). Filters: `low_stock_only`, `expiring_within_days`, `on_hold_only`, `family` |
44
- | `list_batches` | Filtered list of production / lab-prep events; each row has **`bestBy`**; filter by `best_by_before` (past best-by = today) or `lots_expire_first`, `on_hold`, `made_with_lot` (batches that drew from a recalled lot), `held_lot` (drew from any lot now on hold) |
45
- | `get_batch` | Full record + **`lotsUsed`** (raw lots drawn, with each lot's status and hold reason now) + actual composition, measured/derived **actual volume** (mass ÷ density, never a sum of per-ingredient volumes) and **actual mass** (yield, else summed as-prepared inputs — mL rows through that ingredient's density — else measured volume × density), **estimatedVolume** (mass ÷ the formula's finished density when no actual exists, flagged `estimate: true`), **plannedMass** for volume-target batches (target × finished density) and **formulaFinishedDensity**, the **process** method + any **process-factor values** (DOE inputs), samples + blend lineage, and — as a finished-goods lot — its **`bestBy`** (the adjusted date with its change, reason, note and retest report, else prepared date + shelf life; `lotsExpiringFirst` = lots it drew from that expire sooner), its storage **`location`** + finished-goods **`stockLedger`** (shipments out + adjustments; `shippedQty` total), and its **theoretical parameters computed on the batch as made** (actual composition when logged — `basis: "actual"` — else the recipe; the batch's own parameter list when it overrides the formula's) |
44
+ | `list_batches` | Filtered list of production / lab-prep events; each row has **`bestBy`**; filter by `best_by_before` (past best-by = today) or `lots_expire_first`, `on_hold`, `made_with_lot`, `released_with_lot` (batches released together with a lot) (batches that drew from a recalled lot), `held_lot` (drew from any lot now on hold) |
45
+ | `get_batch` | Full record + **`lotsUsed`** (raw lots drawn, with each lot's status and hold reason now) + **`holdHistory`** (each hold with its release: when, by whom, "Released with lot X") + actual composition, measured/derived **actual volume** (mass ÷ density, never a sum of per-ingredient volumes) and **actual mass** (yield, else summed as-prepared inputs — mL rows through that ingredient's density — else measured volume × density), **estimatedVolume** (mass ÷ the formula's finished density when no actual exists, flagged `estimate: true`), **plannedMass** for volume-target batches (target × finished density) and **formulaFinishedDensity**, the **process** method + any **process-factor values** (DOE inputs), samples + blend lineage, and — as a finished-goods lot — its **`bestBy`** (the adjusted date with its change, reason, note and retest report, else prepared date + shelf life; `lotsExpiringFirst` = lots it drew from that expire sooner), its storage **`location`** + finished-goods **`stockLedger`** (shipments out + adjustments; `shippedQty` total), and its **theoretical parameters computed on the batch as made** (actual composition when logged — `basis: "actual"` — else the recipe; the batch's own parameter list when it overrides the formula's) |
46
46
  | `list_samples` | Filtered list of physical specimens |
47
47
  | `get_sample` | Full record + canonical variant + test reports + blend lineage + its stability pulls (next pull, or pulled at) |
48
48
  | `list_test_results` | Filtered list of test reports (by sample, parameter, **measured-value range** (`value_min`/`value_max` — a curve at its final point, a distribution at its spec's statistic or D50), **grade** (`min_grade`/`max_grade` on a ranked scale), **text value** (`value_equals`), **run condition** (`condition`), date, or lab) |
@@ -212,3 +212,5 @@ The wrapped form is the default since 2026; the legacy form is supported for old
212
212
  ## License
213
213
 
214
214
  The server code is MIT-licensed. It bundles FormLab's calculation engine (`vendor/`) under a proprietary license that allows use only as part of formlab-mcp; see LICENSE.
215
+
216
+ **Dates.** Stored times are UTC (`…Z`). The server tells the assistant this computer's time zone, so dates and times are given in local time; days the server works out (`asOf`, `lastReceived`, a report with no test date) are already local days. Plain dates (test, prepared, expiry) are calendar days as entered.
package/data.js CHANGED
@@ -201,3 +201,17 @@ export function flattenComposition(formulation, depth = 0) {
201
201
  });
202
202
  return { rows: [...merged.values()] };
203
203
  }
204
+
205
+ // 0.6.95: days in the lab's local time zone (Jun, 28 Nov). Stored times are UTC ("…Z"); a day cut from one with
206
+ // slice(0, 10) is the UTC day, which in the evening west of Greenwich is already tomorrow. The server runs on the
207
+ // lab's own computer, so its clock's zone is the lab's. A plain YYYY-MM-DD (test, prepared, expiry dates) is a
208
+ // calendar day as entered and stays as it is.
209
+ export const LOCAL_TZ = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch (_) { return 'UTC'; } })();
210
+ const _ymd = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
211
+ export function localDay(v) {
212
+ if (v == null || v === '') return '';
213
+ if (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v)) return v;
214
+ const d = v instanceof Date ? v : new Date(v);
215
+ return isNaN(d.getTime()) ? String(v).slice(0, 10) : _ymd(d);
216
+ }
217
+ export function localToday() { return _ymd(new Date()); }
package/index.js CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  ListToolsRequestSchema,
28
28
  } from '@modelcontextprotocol/sdk/types.js';
29
29
 
30
- import { loadStore, watchStore, getStore } from './data.js';
30
+ import { loadStore, watchStore, getStore, LOCAL_TZ } from './data.js';
31
31
  import { startCloud } from './cloud.js';
32
32
  import * as formulations from './tools/formulations.js';
33
33
  import * as ingredients from './tools/ingredients.js';
@@ -144,9 +144,12 @@ const PKG_VERSION = (() => {
144
144
  }
145
145
  })();
146
146
 
147
+ // 0.6.95: the lab's time zone, so a stored UTC time ("…Z") is told as the local day and time (an evening time west of
148
+ // Greenwich is already tomorrow in UTC). Plain dates are calendar days as entered.
149
+ const INSTRUCTIONS = `Times ending in "Z" (createdAt, updatedAt, holdAt, releasedAt, issuedAt, shipment dates…) are UTC. This lab's time zone is ${LOCAL_TZ}: when you give a date or time from one, convert it to ${LOCAL_TZ} first (late evening there can already be the next day in UTC). Plain dates with no time (testDate, preparedDate, expiryDate, best-by) are calendar days as entered: give them as they are. Day fields the server works out (asOf, a report's day when it has no test date, a supplier's lastReceived) are already ${LOCAL_TZ} days.`;
147
150
  const server = new Server(
148
151
  { name: 'formlab-mcp', version: PKG_VERSION },
149
- { capabilities: { tools: {} } }
152
+ { capabilities: { tools: {} }, instructions: INSTRUCTIONS }
150
153
  );
151
154
 
152
155
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.93",
3
+ "version": "0.6.95",
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.93",
5
+ "version": "0.6.95",
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.93",
11
+ "version": "0.6.95",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
@@ -10,7 +10,7 @@
10
10
  // - get_stability (drift + I-chart + shelf-life, split by condition)
11
11
  // ============================================================
12
12
 
13
- import { getStore, resolveById, flattenComposition } from '../data.js';
13
+ import { getStore, resolveById, flattenComposition, localDay, localToday } from '../data.js';
14
14
 
15
15
  // Which instrument produced a measurement. Mirrors the app's _trMeasInstrument:
16
16
  // a measurement's raw `instrument` is usually EMPTY because blank means inherit,
@@ -1887,7 +1887,7 @@ const get_stability = {
1887
1887
  // specs (two panels) → no band + `specVaries`, never an intersection.
1888
1888
  const specByKey = new Map();
1889
1889
  (db.testResults || []).filter(t => sampleIds.has(t.sampleId)).forEach(t => {
1890
- const dStr = t.testDate || (t.createdAt ? String(t.createdAt).slice(0, 10) : null);
1890
+ const dStr = t.testDate || (t.createdAt ? localDay(t.createdAt) : null); // 0.6.95: its local day
1891
1891
  if (!dStr) return;
1892
1892
  const date = new Date(dStr + (t.testTime && /^\d{4}-\d{2}-\d{2}$/.test(dStr) ? 'T' + t.testTime : ''));
1893
1893
  if (!Number.isFinite(date.getTime())) return;
@@ -2068,7 +2068,7 @@ const list_stability_pulls = {
2068
2068
  const mine = x => !f || x.formula.id === f.id;
2069
2069
  const pulls = r.due.filter(x => mine(x) && x.daysUntil <= within);
2070
2070
  return {
2071
- asOf: new Date(asOf).toISOString().slice(0, 10), withinDays: within,
2071
+ asOf: args.as_of && /^\d{4}-\d{2}-\d{2}$/.test(args.as_of) ? args.as_of : localToday(), withinDays: within, // 0.6.95: today is the local day
2072
2072
  ...(f ? { formulation: { uid: f.uid, name: f.name } } : {}),
2073
2073
  count: pulls.length, overdue: pulls.filter(x => x.overdue).length, pulls,
2074
2074
  later: r.due.filter(x => mine(x) && x.daysUntil > within).length,
@@ -7,7 +7,7 @@
7
7
  // none. Read-only; the server applies project walls and the owner's switch for restricted projects.
8
8
  // ============================================================
9
9
 
10
- import { getStore } from '../data.js';
10
+ import { getStore, localToday } from '../data.js';
11
11
 
12
12
  const _norm = (s) => String(s == null ? '' : s).toLowerCase();
13
13
  const _clampLimit = (n) => Math.min(1000, Math.max(1, n || 100));
@@ -115,7 +115,7 @@ const list_requests = {
115
115
  const { db } = getStore();
116
116
  const none = _notLive(db); if (none) return none;
117
117
  const limit = _clampLimit(args.limit);
118
- const today = new Date().toISOString().slice(0, 10);
118
+ const today = localToday(); // 0.6.95: the local day, not UTC
119
119
  const active = new Set(['open', 'in_progress', 'blocked']);
120
120
  const wantId = _resolveId(args.entity_type, args.entity_id, db);
121
121
  const order = { blocked: 0, open: 1, in_progress: 2, done: 3, cancelled: 4 };
package/tools/lab.js CHANGED
@@ -300,6 +300,19 @@ function _batchLotsUsed(db, batchId) {
300
300
  });
301
301
  }
302
302
 
303
+ // 0.6.94: a batch's holds, oldest first, each with its release. A release no longer clears the hold in the app: it
304
+ // stays with releasedAt / releasedBy / releaseNote ("Released with lot ETH-1 (signed by …)"), earlier ones in fgHold.log.
305
+ function _batchHoldHistory(db, b) {
306
+ const h = b && b.fgHold;
307
+ if (!h || !h.at) return [];
308
+ const lotNo = id => { const l = (db.lots || []).find(x => x && x.id === id); return l ? (l.lotNumber || l.uid || id) : id; };
309
+ const one = x => ({
310
+ held: x.at || null, by: x.by || '', reason: x.reason || '',
311
+ lots: Array.isArray(x.lots) ? x.lots.map(lotNo) : [],
312
+ released: x.releasedAt || null, releasedBy: x.releasedBy || '', releaseNote: x.releaseNote || '',
313
+ });
314
+ return [...(Array.isArray(h.log) ? h.log : []), h].filter(x => x && x.at).map(one);
315
+ }
303
316
  const list_batches = {
304
317
  definition: {
305
318
  name: 'list_batches',
@@ -317,6 +330,7 @@ const list_batches = {
317
330
  on_hold: { type: 'boolean', description: 'When true, only finished batches currently on hold (no shipment can be recorded until released).' },
318
331
  made_with_lot: { type: 'string', description: 'Only batches that drew from this raw lot: its lot number (e.g. "BIT-9912", from a supplier recall), lot UID, or internal id. Answers "which batches used the recalled lot?"; pair with on_hold to see which are not held yet.' },
319
332
  held_lot: { type: 'boolean', description: 'When true, only batches that drew from a raw lot now on hold, whether or not the batch itself is held.' },
333
+ released_with_lot: { type: 'string', description: 'Only batches whose hold was released together with this raw lot (its lot number, lot UID, or internal id): released when the lot was released from hold. Each batch\'s holdHistory (get_batch) shows when and by whom.' },
320
334
  limit: { type: 'number', description: 'Max rows (default 50, max 500).' },
321
335
  },
322
336
  },
@@ -339,6 +353,15 @@ const list_batches = {
339
353
  if (!lotIds.size) return { error: `No lot matched "${args.made_with_lot}" (lot number, lot UID, or id).` };
340
354
  lotBatches = new Set((db.stockMovements || []).filter(m => m && lotIds.has(m.lotId) && m.batchId && Number(m.delta) < 0).map(m => m.batchId));
341
355
  }
356
+ let relLot = null;
357
+ if (args.released_with_lot) {
358
+ const w = norm(args.released_with_lot).trim();
359
+ relLot = (db.lots || []).find(l => l && !l._trashed && (l.id === args.released_with_lot || norm(l.uid) === w || norm(l.lotNumber) === w));
360
+ if (!relLot) return { error: `No lot matched "${args.released_with_lot}" (lot number, lot UID, or id).` };
361
+ }
362
+ const relNo = relLot ? norm(relLot.lotNumber || relLot.uid) : '';
363
+ const releasedWith = b => _batchHoldHistory(db, b).some(x => x.released && norm(x.releaseNote).startsWith('released with lot ' + relNo)
364
+ && (norm(x.releaseNote).length === ('released with lot ' + relNo).length || /^[ (]/.test(norm(x.releaseNote).slice(('released with lot ' + relNo).length))));
342
365
  const heldBatches = args.held_lot ? (() => { const held = new Set((db.lots || []).filter(l => l && !l._trashed && l.status === 'hold').map(l => l.id)); return new Set((db.stockMovements || []).filter(m => m && held.has(m.lotId) && m.batchId && Number(m.delta) < 0).map(m => m.batchId)); })() : null;
343
366
  const filtered = (db.batches || []).filter(b => {
344
367
  if (!b || b._trashed) return false;
@@ -349,7 +372,8 @@ const list_batches = {
349
372
  if (args.origin_only && b.parentBatchId) return false;
350
373
  if (args.since_date && (b.preparedDate || '') < args.since_date) return false;
351
374
  if (args.shipped_to && !(Array.isArray(b.stockLedger) && b.stockLedger.some(e => e && e.kind === 'shipment' && norm(e.note).includes(norm(args.shipped_to))))) return false;
352
- if (args.on_hold && !(b.fgHold && b.fgHold.at)) return false;
375
+ if (args.on_hold && !(b.fgHold && b.fgHold.at && !b.fgHold.releasedAt)) return false;
376
+ if (relLot && !releasedWith(b)) return false;
353
377
  if (args.best_by_before || args.lots_expire_first) {
354
378
  const bb = _bestByInfo(b, b.formulationId ? indexes.formulationsById.get(b.formulationId) : null);
355
379
  if (!bb) return false;
@@ -369,7 +393,7 @@ const list_batches = {
369
393
  const get_batch = {
370
394
  definition: {
371
395
  name: 'get_batch',
372
- description: 'Get full details for a single batch including the raw lots it drew (lotsUsed: lot number, quantity, and the status of each lot now, with holdReason for a lot on hold), its actual composition (as-prepared, when logged), child samples, lineage (parent / sub-blend parents), and — treating the batch as a finished-goods lot — its storage `location` and finished-goods `stockLedger` (shipments out + adjustments; on-hand = produced − sample pulls − sub-batch draws + Σ ledger). Plus finished-product density + actual volume (measured directly or derived as actual mass ÷ measured density — never summed from per-ingredient volumes). Accepts internal id or UID. Also returns `theoreticalParameters` computed on the batch as made (its actual composition when logged — `basis: "actual"` — else the recipe of its formula), with the batch parameter list when it overrides the one on the formula; same fields as get_formulation.',
396
+ description: 'Get full details for a single batch including the raw lots it drew (lotsUsed: lot number, quantity, and the status of each lot now, with holdReason for a lot on hold), hold (now) and holdHistory (every hold with its release: when, by whom, and the note, e.g. "Released with lot ETH-1"), its actual composition (as-prepared, when logged), child samples, lineage (parent / sub-blend parents), and — treating the batch as a finished-goods lot — its storage `location` and finished-goods `stockLedger` (shipments out + adjustments; on-hand = produced − sample pulls − sub-batch draws + Σ ledger). Plus finished-product density + actual volume (measured directly or derived as actual mass ÷ measured density — never summed from per-ingredient volumes). Accepts internal id or UID. Also returns `theoreticalParameters` computed on the batch as made (its actual composition when logged — `basis: "actual"` — else the recipe of its formula), with the batch parameter list when it overrides the one on the formula; same fields as get_formulation.',
373
397
  inputSchema: {
374
398
  type: 'object',
375
399
  properties: {
@@ -418,7 +442,9 @@ const get_batch = {
418
442
  })),
419
443
  shippedQty: (Array.isArray(b.stockLedger) ? b.stockLedger : []).reduce((s, e) => e.kind === 'shipment' ? s + Math.abs(parseFloat(e.delta) || 0) : s, 0),
420
444
  // Finished-batch hold: while set, the app records no shipment of this batch (QA / complaint / recall).
421
- hold: (b.fgHold && b.fgHold.at) ? { since: b.fgHold.at, by: b.fgHold.by || '', reason: b.fgHold.reason || '' } : null,
445
+ hold: (b.fgHold && b.fgHold.at && !b.fgHold.releasedAt) ? { since: b.fgHold.at, by: b.fgHold.by || '', reason: b.fgHold.reason || '' } : null,
446
+ // 0.6.94: every hold this batch had, oldest first, with its release (when, by whom, the note: "Released with lot X").
447
+ holdHistory: _batchHoldHistory(getStore().db, b),
422
448
  // 0.6.92: the raw lots this batch drew (net of returns), each with its status now. A lot on hold
423
449
  // here ("status: hold" + holdReason) is why a recall reaches this batch, held or not.
424
450
  lotsUsed: _batchLotsUsed(getStore().db, b.id),
package/tools/library.js CHANGED
@@ -11,7 +11,7 @@
11
11
  // previously synced into the store but not queryable.
12
12
  // ============================================================
13
13
 
14
- import { getStore, resolveById } from '../data.js';
14
+ import { getStore, resolveById, localDay } from '../data.js';
15
15
  import { calibrationStatus, calibrationHistory } from '../calibration.js';
16
16
  import { _evalPassFail, _mcpRepNumber, _mcpMeasType, _resolveSpec, _mcpCondSig, _mcpCondLabel, _mcpCondTags, _mcpParamGroupsOf } from './analytics.js';
17
17
 
@@ -54,7 +54,7 @@ function _usageRollup(db, tests, measFilter) {
54
54
  const sById = new Map((db.samples || []).map(s => [s.id, s]));
55
55
  const bById = new Map((db.batches || []).map(b => [b.id, b]));
56
56
  const fById = new Map((db.formulations || []).map(f => [f.id, f]));
57
- const date = t => String(t.testDate || (t.createdAt || '').slice(0, 10) || '');
57
+ const date = t => String(t.testDate || localDay(t.createdAt) || ''); // 0.6.95: a report with no test date: its local day
58
58
  const byF = new Map(); const forms = new Set(), batches = new Set(), samples = new Set(), labs = new Set();
59
59
  let readings = 0, fails = 0, withSpec = 0, last = '';
60
60
  tests.forEach(t => {
@@ -7,7 +7,7 @@
7
7
  // names it as the manufacturer — a maker's recall must reach lots bought
8
8
  // through a distributor. Read-only, like every tool here.
9
9
  // =====================================================================
10
- import { getStore, resolveById } from '../data.js';
10
+ import { getStore, resolveById, localDay } from '../data.js';
11
11
 
12
12
  const SUFFIX_RE = /\b(inc|incorporated|ltd|limited|llc|gmbh|co|corp|corporation|company|ag|sa|plc|bv|nv|srl|s\.?a\.?|pty)\b\.?$/i;
13
13
  function norm(name) {
@@ -74,7 +74,7 @@ function rowOf(db, sup) {
74
74
  ingredientCount: refs.ingredients.length, lotCount: refs.lots.length, lotsOnHand: onHandLots,
75
75
  onHandValue: onHandValue == null ? null : +onHandValue.toFixed(2), onHandValueCcy: onHandValue == null ? null : valueCcy,
76
76
  qualifiedSources: qs.qualified, trialSources: qs.trial, disqualifiedSources: qs.disqualified,
77
- lastReceived: lastReceived ? lastReceived.slice(0, 10) : null,
77
+ lastReceived: lastReceived ? localDay(lastReceived) : null, // 0.6.95: local day
78
78
  _refs: refs,
79
79
  };
80
80
  }
@@ -123,6 +123,28 @@ function eqCalSortKey(e) {
123
123
  return `${rank}|${st.due || '9999'}`;
124
124
  }
125
125
 
126
+ // Readings to doubt after a calibration found the unit out of tolerance (dogfooding 28 Nov: RV-1 failed and nothing
127
+ // said which of its 8 reports came after its last pass). The latest entry must be a Fail or an Adjusted (out of
128
+ // tolerance as found). Suspect = reports dated after the last good calibration before it: up to today for a Fail
129
+ // (it may still be in use), up to the adjustment for Adjusted. `tests` = the reports that used this unit.
130
+ function eqCalSuspect(e, tests, todayIso) {
131
+ const hist = eqCalHistory(e), bad = hist[0];
132
+ 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());
136
+ const day = (t) => String((t && t.testDate) || '').split('T')[0];
137
+ const hit = (tests || []).filter(t => { const d = day(t); return d && (!since || d > since) && (!until || d <= until); })
138
+ .sort((a, b) => day(a).localeCompare(day(b)));
139
+ const batches = [];
140
+ hit.forEach(t => {
141
+ const sm = (typeof db !== 'undefined' && db.samples || []).find(x => x && x.id === t.sampleId);
142
+ const b = sm && sm.batchId ? (db.batches || []).find(x => x && x.id === sm.batchId && !x._trashed) : null;
143
+ if (b && !batches.includes(b)) batches.push(b);
144
+ });
145
+ return { kind: res(bad), at: bad.date || '', since, until, tests: hit, batches };
146
+ }
147
+
126
148
  // ---- The Calibration card on the equipment page ----
127
149
  function eqCalCardHtml(e) {
128
150
  const on = eqCalOn();
@@ -155,11 +177,19 @@ function eqCalCardHtml(e) {
155
177
  // Dogfooding, 22 Nov (pH meter back in service): the card read "OK · due 2027-11-22" under an Out of service
156
178
  // badge and said nothing, where a failed calibration says to take the unit out. The way back is said too.
157
179
  (st.lastResult === 'pass' || st.lastResult === 'adjusted') && e.status === 'Out of service' ? `<div style="margin-top:10px;font-size:12.5px;color:var(--dk-amber-fg, #92400e)">The latest calibration passed, and the instrument is still <strong>Out of service</strong>. Set it <strong>In service</strong> (the status beside its name) when it is back in use.</div>` : ''}`;
180
+ const sus = typeof _eqUsageTests === 'function' ? eqCalSuspect(e, _eqUsageTests(e)) : null;
181
+ const susHtml = sus && sus.tests.length ? (() => {
182
+ 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}` : '');
184
+ 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>`;
187
+ })() : '';
158
188
  const rows = hist.map(c => `<tr>
159
189
  <td style="font-variant-numeric:tabular-nums">${esc(c.date || '—')}</td>
160
190
  <td>${esc(c.by || '—')}</td>
161
191
  <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>
162
- <td style="font-variant-numeric:tabular-nums">${esc(c.nextDue || '—')}</td>
192
+ <td style="font-variant-numeric:tabular-nums">${esc((String(c.result || '').toLowerCase() === 'fail' ? '' : c.nextDue) || '—')}</td>
163
193
  <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>
164
194
  <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>
165
195
  <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>
@@ -170,7 +200,7 @@ function eqCalCardHtml(e) {
170
200
  const freeNote = on ? '' : `<div style="margin-top:10px;font-size:12px;color:var(--text-muted)">Read-only on Free: your calibration records are kept. Logging and due-date alerts are Pro.</div>`;
171
201
  return `<div class="card" id="eq-cal-card" style="margin-top:16px">
172
202
  <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap"><h2>Calibration</h2>${editBtns}</div>
173
- <div class="card-body">${summary}${table}${freeNote}</div></div>`;
203
+ <div class="card-body">${summary}${susHtml}${table}${freeNote}</div></div>`;
174
204
  }
175
205
 
176
206
  // ---- Interval ----
@@ -197,6 +227,14 @@ function openEqCalIntervalModal(eqId) {
197
227
  function _eqCalMe() {
198
228
  try { const p = (typeof window !== 'undefined') ? window.__pro : null; const me = (p && p.getCurrentUser) ? p.getCurrentUser() : null; return me ? (me.displayName || me.email || '') : ''; } catch (_) { return ''; }
199
229
  }
230
+ // Fail clears and locks Next due; another result brings the interval's date back.
231
+ function _eqCalResultDue(sel, interval) {
232
+ const d = document.getElementById('eq-cal-due'); if (!d || !sel) return;
233
+ const fail = sel.value === 'fail';
234
+ d.disabled = fail;
235
+ if (fail) { d.dataset.was = d.value; d.value = ''; d.placeholder = 'After it passes'; }
236
+ else if (!d.value) d.value = d.dataset.was || _eqCalAddMonths((document.getElementById('eq-cal-date') || {}).value || _eqCalToday(), interval) || '';
237
+ }
200
238
  function openEqCalLogModal(eqId, calId) {
201
239
  if (!eqCalOn()) { proUpsell('equipment.calibration'); return; }
202
240
  const e = typeof getEquipment === 'function' ? getEquipment(eqId) : (db.equipment || []).find(x => x.id === eqId);
@@ -217,10 +255,10 @@ function openEqCalLogModal(eqId, calId) {
217
255
  <div class="form-group"><label>Date calibrated *</label><input id="eq-cal-date" type="date" value="${esc(date)}" max="${_eqCalToday()}" onchange="_eqCalAutoDue(${interval})"></div>
218
256
  <div class="form-group"><label>Performed by</label><input id="eq-cal-by" value="${esc(c ? (c.by || '') : _eqCalMe())}" placeholder="Name, or the service provider" data-fl-person="equipment.calibrations[].by testResults.performedBy equipment.owner"></div>
219
257
  <div class="form-group span-2"><label>Result *</label>
220
- <select id="eq-cal-result">${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>
258
+ <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>
221
259
  </div>
222
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>
223
- <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'">
261
+ <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"' : ''}>
224
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.')}
225
263
  </div>
226
264
  <div class="form-group"><label>Certificate</label>
@@ -234,7 +272,9 @@ function openEqCalLogModal(eqId, calId) {
234
272
  const rec = {
235
273
  id: c ? c.id : (typeof uid === 'function' ? uid() : 'cal' + Date.now()),
236
274
  date: v('eq-cal-date'), by: v('eq-cal-by'), result: v('eq-cal-result') || 'pass',
237
- nextDue: v('eq-cal-due'), notes: v('eq-cal-notes'),
275
+ // A failed unit has no next due: it needs a passing calibration first (eqCalStatus says the same; 28 Nov the row
276
+ // still read 2027-05-28 under a header that said Next due —).
277
+ nextDue: v('eq-cal-result') === 'fail' ? '' : v('eq-cal-due'), notes: v('eq-cal-notes'),
238
278
  certificateId: v('eq-cal-cert') || undefined, certificateRef: v('eq-cal-certref') || undefined,
239
279
  loggedAt: c ? (c.loggedAt || new Date().toISOString()) : new Date().toISOString(),
240
280
  loggedBy: c ? (c.loggedBy || '') : _eqCalMe(),
@@ -719,15 +719,28 @@ function _frgControlsHtml(f, c) {
719
719
  ${c.others.length ? `<div class="fr-dim" data-tip="${_frgEsc(c.others.slice(0, 12).join(', ') + (c.others.length > 12 ? ` +${c.others.length - 12} more` : ''))}">${c.others.length} other ${c.others.length === 1 ? 'ingredient is not a fragrance material' : 'ingredients are not fragrance materials'}. Not checked.</div>` : ''}
720
720
  </div></div>`;
721
721
  }
722
+ // The Free teaser's backdrop: a sample, not the formula's data. Same table markup as the real tab, sorting off.
723
+ const _FRG_TEASE_ROWS = [
724
+ ['Citrus oil blend', 0.42, '0.60%', '0.18%', 'pass'], ['Rose absolute', 0.15, '0.10%', '−0.05%', 'over'],
725
+ ['Vanilla extract', 0.30, 'None', '', 'unrestricted'], ['Woody accord', 0.22, '—', '', 'unknown'],
726
+ ['Lavender oil', 0.38, '1.20%', '0.82%', 'pass'],
727
+ ];
728
+ function _frgTeaseSampleHtml() {
729
+ const rows = _FRG_TEASE_ROWS.map(([name, pct, lim, head, st]) => { const [cls, word] = _FRG_STATUS[st];
730
+ return `<tr><td>${name}</td><td class="num">${pct.toFixed(2)}%</td><td class="num">${lim}</td><td class="num">${head}</td><td><span class="badge badge-${cls}">${word}</span></td><td class="fr-src">IFRA certificate</td></tr>`; }).join('');
731
+ return `<div class="fr-tease-sample" aria-hidden="true" inert><div class="fr-verdict bad"><strong>Over the limit in category 5A at 1%.</strong> Rose absolute.</div>
732
+ <div class="table-wrapper"><table class="fr-table fl-band"><thead><tr><th>Material</th><th class="num">In product</th><th class="num">Limit</th><th class="num">Headroom</th><th>Status</th><th>Source</th></tr></thead><tbody>${rows}</tbody></table></div></div>`;
733
+ }
722
734
  function flFrTabHtml(f) {
723
735
  if (!f || !flFrHasData(f)) return '';
724
736
  const c = flFrCompute(f);
725
737
  if (!_frgPro()) {
726
- return `<div class="card nl-tease"><div class="card-body"><div class="nl-tease-card">
738
+ // A made-up IFRA check, faded under the offer (Jun, 28 Nov): shows the shape of the tab, none of this formula's results.
739
+ return `<div class="card nl-tease"><div class="card-body nl-tease-stage"><div class="nl-tease-wrap">${_frgTeaseSampleHtml()}<div class="nl-tease-card">
727
740
  <div class="nl-tease-t">Fragrance compliance <span class="asm-designer-pro-badge usda-pro">Pro</span></div>
728
741
  <div class="nl-tease-s">${c.rows.length ? `${c.rows.length} fragrance ${c.rows.length === 1 ? 'material' : 'materials'} to check against IFRA.` : 'IFRA limits and allergens for this formula.'}</div>
729
742
  <button class="btn btn-primary btn-sm" onclick="proUpsell('formulations.fragranceCompliance')">See what Pro adds</button>
730
- </div></div></div>`;
743
+ </div></div></div></div>`;
731
744
  }
732
745
  if (!c.has) return `<div class="fr-wrap"><div class="fr-side">${_frgControlsHtml(f, c)}</div><div class="fr-main"><div class="card"><div class="card-body"><div class="fr-verdict warn"><strong>No fragrance materials on this formula.</strong> Add them on the Composition tab.</div></div></div></div></div>`;
733
746
  return `<div class="fr-wrap">