formlab-mcp 0.6.92 → 0.6.94

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
@@ -36,13 +36,13 @@ Ask Claude (or another MCP client) things like:
36
36
  | `compare_formulations` | Pairwise side-by-side composition diff |
37
37
  | `list_ingredients` | Filtered list of raw materials. Filters: `family`, `supplier`, `name_contains`, `lot_number` (the ingredient a lot belongs to), `in_stock_only`, `ingredient_class` (small-molecule / surfactant / polymer / extract / fragrance / pigment / sequence / mixture), `sequence_contains` (e.g. `KTTKS` → Matrixyl), `taxon_contains` (e.g. `Centella`) |
38
38
  | `get_ingredient` | Full record + supplier / **cost ($/kg)** / stock / chemical name / molecular weight / storage / formulations using it, plus **GHS safety** (pictograms, H/P codes, signal word), **per-jurisdiction regulatory status**, **approved sources** (the suppliers / manufacturers qualified to supply this material — ASL/AML), and **inventory lots** (balances + expiry + the source each was received from). Returns every class-specific sub-object when present: `sequence` (peptide / oligo), `taxon` (NCBI ID + scientific name), `ingredientClass`, `extractDetails`, `sequenceDetails`, `polymerDetails`, `surfactantDetails`, `pigmentDetails`, `fragranceDetails`, and its **custom fields** with units (`customFields`: protein / carb / fat in g/100g, solids %… — what theoretical parameters read), and its **reactive groups** (EEW, AHEW, OH number, NCO %, acid / amine value: as entered, in the datasheet's terms and meq/g, with any row the app ignores and why) |
39
- | `list_lots` | Inventory lots across ingredients (each a received batch with its own remaining balance, supplier, expiry, **unit cost**, **status** — `active` / `hold` / `quarantine` / `rejected`; held lots are blocked from consumption, with a `holdReason` — and the **approved source** it was received from: `source.supplier` + `source.manufacturer`, where recalls hinge on the manufacturer). Each lot also reports its **Certificate of Analysis** (`coa`: linked, or matched by lot number) and `coaMissing` for an in-stock lot without one. Filters: `ingredient_id`, `lot_number`, `expiring_within_days`, `status` (e.g. `hold` to find lots held for a recall), `missing_coa` |
39
+ | `list_lots` | Inventory lots across ingredients (each a received batch with its own remaining balance, supplier, expiry, **unit cost**, **status** — `active` / `hold` / `quarantine` / `rejected`; held lots are blocked from consumption, with a `holdReason` and `holdAt` — and the **approved source** it was received from: `source.supplier` + `source.manufacturer`, where recalls hinge on the manufacturer). Each lot also reports its **Certificate of Analysis** (`coa`: linked, or matched by lot number) and `coaMissing` for an in-stock lot without one. Filters: `ingredient_id`, `lot_number`, `expiring_within_days`, `status` (e.g. `hold` to find lots held for a recall), `missing_coa` |
40
40
  | `list_suppliers` | Supplier / manufacturer records with roll-ups — ingredients approved, lots received / on hand (+ value at paid cost), qualified / trial / disqualified source counts, last receipt; lots count by supplier **and** by manufacturer |
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
- | `list_inventory` | Portfolio stock rollup — one row per ingredient with on-hand qty, summed lot balance, nearest expiry, and a low-stock flag (on-hand ≤ `reorderThreshold`, or zero). Filters: `low_stock_only`, `expiring_within_days`, `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) |
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`, `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) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.92",
3
+ "version": "0.6.94",
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.92",
5
+ "version": "0.6.94",
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.92",
11
+ "version": "0.6.94",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
@@ -220,6 +220,8 @@ const get_ingredient = {
220
220
  qtyRemaining: l.qtyRemaining, qtyReceived: l.qtyReceived, unit: l.unit || '',
221
221
  receivedDate: l.receivedDate || null, expiryDate: l.expiryDate || null,
222
222
  supplier: l.supplier || '', supplierId: l.supplierId || null, status: l.status || 'active',
223
+ // 0.6.93: why and since when a lot is on hold (QC / recall).
224
+ hold: l.status === 'hold' ? { reason: l.holdReason || '', since: l.holdAt || null } : null,
223
225
  sourceId: l.sourceId || null, source: _lotSourceInfo(l),
224
226
  ..._lotCoaInfo(l, ing),
225
227
  }));
@@ -398,6 +400,7 @@ const list_lots = {
398
400
  // 'hold' / 'quarantine' / 'rejected' lots are blocked from auto-consumption;
399
401
  // holdReason explains a manual hold (QC / recall).
400
402
  holdReason: l.holdReason || '',
403
+ holdAt: l.status === 'hold' ? (l.holdAt || null) : null, // 0.6.93: since when it is held
401
404
  // A disposed lot: when, why, how much was written off (status is then "disposed").
402
405
  disposal: l.status === 'disposed' ? { date: l.disposedAt || null, by: l.disposedBy || '', reason: l.disposeReason || '', note: l.disposeNote || '', qty: l.disposedQty ?? null } : null,
403
406
  unitCost: (l.unitCost != null && l.unitCost !== '') ? l.unitCost : null,
@@ -424,6 +427,7 @@ const list_inventory = {
424
427
  properties: {
425
428
  low_stock_only: { type: 'boolean', description: 'Only ingredients flagged low (on-hand ≤ reorderThreshold, or on-hand is 0).' },
426
429
  expiring_within_days: { type: 'number', description: 'Only ingredients with a lot expiring within this many days from now (already-expired lots always qualify).' },
430
+ on_hold_only: { type: 'boolean', description: 'Only ingredients with a lot on hold that still has stock (the app\'s Inventory "On hold" tile). heldQty says how much of the on-hand is held.' },
427
431
  family: { type: 'string', description: 'Filter by ingredient family. Case-insensitive substring.' },
428
432
  limit: { type: 'number', description: 'Max rows (default 200, max 1000).' },
429
433
  },
@@ -453,6 +457,9 @@ const list_inventory = {
453
457
  const expiries = lots.map(l => Date.parse(l.expiryDate)).filter(isFinite);
454
458
  const nearestExpiryMs = expiries.length ? Math.min(...expiries) : null;
455
459
  const lowStock = (onHand === 0) || (onHand != null && reorder != null && onHand <= reorder);
460
+ // 0.6.93: lots on hold with stock left. Held stock still counts in on-hand but can't be used until released.
461
+ const heldLots = lots.filter(l => l.status === 'hold' && Number(l.qtyRemaining) > 0);
462
+ const heldQty = heldLots.reduce((s, l) => s + Number(l.qtyRemaining), 0);
456
463
  return {
457
464
  id: i.id, uid: i.uid, name: i.name || '', family: i.family || '',
458
465
  stockOnHand: onHand, stockUnit: i.stockUnit || null,
@@ -462,9 +469,12 @@ const list_inventory = {
462
469
  nearestExpiry: nearestExpiryMs != null ? new Date(nearestExpiryMs).toISOString().slice(0, 10) : null,
463
470
  daysToNearestExpiry: nearestExpiryMs != null ? Math.floor((nearestExpiryMs - nowMs) / 86400000) : null,
464
471
  lowStock,
472
+ heldQty: heldLots.length ? +heldQty.toFixed(6) : 0,
473
+ lotsOnHold: heldLots.map(l => ({ lotNumber: l.lotNumber || l.uid || '', qty: Number(l.qtyRemaining), unit: l.unit || '', reason: l.holdReason || '', since: l.holdAt || null })),
465
474
  };
466
475
  }).filter(r => {
467
476
  if (args.low_stock_only && !r.lowStock) return false;
477
+ if (args.on_hold_only && !(r.heldQty > 0)) return false;
468
478
  if (args.expiring_within_days != null) {
469
479
  if (r.daysToNearestExpiry == null) return false;
470
480
  if (r.daysToNearestExpiry > args.expiring_within_days) return false;
@@ -480,6 +490,7 @@ const list_inventory = {
480
490
  totalMatching: rows.length,
481
491
  returned: Math.min(rows.length, limit),
482
492
  lowStockCount: rows.filter(r => r.lowStock).length,
493
+ onHoldCount: rows.filter(r => r.heldQty > 0).length,
483
494
  inventory: rows.slice(0, limit),
484
495
  };
485
496
  },
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),
@@ -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">