formlab-mcp 0.6.88 → 0.6.90

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
@@ -31,6 +31,7 @@ Ask Claude (or another MCP client) things like:
31
31
  | `list_formulations` | Filtered list of recipes, each with exact `batchCount` / `sampleCount` / `testReportCount`; `sort` (`batches`, `samples`, `test_reports`, `name`, `updated`) ranks every match before the limit — "which formulas have the most batch runs?" in one call |
32
32
  | `get_formulation` | Full record (incl. `versionLabel`, the label the user types, e.g. 1.0) + **version history** (`versionHistory`: one snapshot per save, v1, v2…, newest first, with the label each save had and its note) + flattened wt-% composition (sub-formulas expanded), the ordered **step procedure**, user **custom fields**, any **process-factor values** (DOE inputs — cure temp, mix time, RPM, pH…), the declared **finishedDensity** (g/mL of the mixed product; volume-targeted batches scale by it), and its **theoretical parameters computed** the way the app's Params tab does (Energy kcal/100g, NV %, Cost/kg…: value, unit, formula, spec pass/fail, and a `warning` when ingredients lack a value or carry mixed units) — the app's own engine, vendored in `mcp/vendor/` and run in an isolated `node:vm` context |
33
33
  | `get_nutrition_label` | The formula's **Label** tab (Pro, live workspace only): US Nutrition Facts lines per serving with FDA rounding and % Daily Value, the per-container column, whether the simplified format applies, the EU declaration (kJ / kcal, salt) and EU ingredient list with allergens in capitals, the ingredient statement with its Contains line, and which ingredients are missing nutrition data. |
34
+ | `get_fragrance_compliance` | The formula's **Fragrance** tab (Pro, live workspace only): each fragrance material's % in the finished product against its IFRA limit for the product category, the highest dosage that passes and the material that limits it, and the EU fragrance allergens to name on the label. Optional what-if `category`, `use`, `dosage` ("can this oil go into a body lotion at 2%?"). Limits come only from the certificates the lab has on file; anything missing makes the state `incomplete`. Not a certification. `get_formulation` carries the same summary as `fragranceCompliance`. |
34
35
  | `find_similar_formulations` | Find formulas using a given ingredient ≥ threshold % |
35
36
  | `compare_formulations` | Pairwise side-by-side composition diff |
36
37
  | `list_ingredients` | Filtered list of raw materials. Filters: `family`, `supplier`, `name_contains`, `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`) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.88",
3
+ "version": "0.6.90",
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.88",
5
+ "version": "0.6.90",
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.88",
11
+ "version": "0.6.90",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
package/theoretical.js CHANGED
@@ -16,7 +16,8 @@ import { readFileSync } from 'node:fs';
16
16
  import vm from 'node:vm';
17
17
 
18
18
  const VENDOR = new URL('./vendor/', import.meta.url);
19
- const FILES = ['safe-expr.js', 'cost.js', 'nesting.js', 'theoretical-params.js', 'reactive.js', 'nutrition-label.js']; // reactive.js: ing.epoxy … ing.vinyl for the Reactive presets
19
+ const FILES = ['safe-expr.js', 'cost.js', 'nesting.js', 'fragrance.js', 'theoretical-params.js', 'reactive.js', 'nutrition-label.js']; // fragrance.js: IFRA limits and EU allergens (0.6.90)
20
+ // // reactive.js: ing.epoxy … ing.vinyl for the Reactive presets
20
21
  let _source = null;
21
22
  function source() {
22
23
  if (!_source) _source = FILES.map(f => readFileSync(new URL(f, VENDOR), 'utf8')).join('\n;\n');
@@ -61,6 +62,14 @@ function rollupFormulaAllergens(f) {
61
62
  });
62
63
  return out;
63
64
  }
65
+ // Fragrance compliance as the app's Fragrance tab computes it (vendor/fragrance.js, 0.6.90): 'null' for a formula with
66
+ // no fragrance to check. opts: { category, use, dosage } to ask "what if" (never saved).
67
+ function __fr(id, optsJson) {
68
+ var f = (db.formulations || []).find(function (x) { return x && x.id === id; });
69
+ if (!f) return 'null';
70
+ var o = null; try { o = optsJson ? JSON.parse(optsJson) : null; } catch (e) { o = null; }
71
+ return JSON.stringify(flFrSummary(f, o || undefined));
72
+ }
64
73
  function __nl(id) {
65
74
  var f = (db.formulations || []).find(function (x) { return x && x.id === id; });
66
75
  if (!f) return 'null';
@@ -164,6 +173,18 @@ export function theoreticalParams(db, kind, id) {
164
173
  }
165
174
  }
166
175
 
176
+ // A formula's fragrance compliance summary (IFRA limits, max dosage, EU allergens) as the app's Fragrance tab computes
177
+ // it: null when there is no such formula or it has no fragrance to check. whatIf: { category, use, dosage }.
178
+ export function fragranceCompliance(db, id, whatIf) {
179
+ try {
180
+ const ctx = contextFor(db);
181
+ const o = {};
182
+ if (whatIf && typeof whatIf === 'object') ['category', 'use', 'dosage'].forEach(k => { if (whatIf[k] != null && whatIf[k] !== '') o[k] = whatIf[k]; });
183
+ vm.runInContext('var __fid = ' + JSON.stringify(String(id)) + ', __fo = ' + JSON.stringify(JSON.stringify(o)) + ';', ctx);
184
+ return JSON.parse(vm.runInContext('__fr(__fid, __fo)', ctx, { timeout: 2000 }));
185
+ } catch (e) { return { state: 'error', error: 'could not compute: ' + ((e && e.message) || e) }; }
186
+ }
187
+
167
188
  // A formula's nutrition label as the app's Label tab computes it (vendor/nutrition-label.js): null when there is no such
168
189
  // formula; { ok: false, why } when it has no label ('nodata', 'empty', or 'density' with the rows that need one).
169
190
  export function nutritionLabel(db, id) {
@@ -7,7 +7,7 @@
7
7
  // ============================================================
8
8
 
9
9
  import { getStore, resolveById, flattenComposition } from '../data.js';
10
- import { theoreticalParams, nutritionLabel } from '../theoretical.js';
10
+ import { theoreticalParams, nutritionLabel, fragranceCompliance } from '../theoretical.js';
11
11
 
12
12
  // Strip db-internal noise (createdAt, updatedAt) for cleaner LLM output
13
13
  // while keeping the human-facing fields the user cares about.
@@ -125,9 +125,11 @@ const get_formulation = {
125
125
  },
126
126
  },
127
127
  handler: async (args) => {
128
- const { db } = getStore();
128
+ const { db, meta } = getStore();
129
129
  const f = resolveById('formulations', args.id);
130
130
  if (!f) return { error: `No formulation found for id "${args.id}".` };
131
+ // 0.6.90: the Fragrance tab's summary (Pro, so a live workspace only), on a formula with fragrance to check.
132
+ const fr = (meta && meta.source === 'cloud') ? fragranceCompliance(db, f.id) : null;
131
133
  const flat = flattenComposition(f);
132
134
  const flatRows = flat.rows.map(r => ({
133
135
  ingredientId: r.ingredientId,
@@ -166,6 +168,8 @@ const get_formulation = {
166
168
  processFactors: (f.factorValues || []).filter(x => x && x.name).map(x => ({ name: x.name, value: x.value != null ? x.value : '', unit: x.unit || '' })),
167
169
  // Computed by the app's own engine (mcp/theoretical.js → mcp/vendor/).
168
170
  theoreticalParameters: theoreticalParams(db, 'formulation', f.id),
171
+ // IFRA limits and EU fragrance allergens as the Fragrance tab computes them (see get_fragrance_compliance).
172
+ ...(fr ? { fragranceCompliance: fr } : {}),
169
173
  // Automatic history: one snapshot per save (v1, v2…), newest first,
170
174
  // with the Version label each save had. Independent of versionLabel.
171
175
  versionHistory: (() => {
@@ -186,6 +190,35 @@ const get_formulation = {
186
190
  },
187
191
  };
188
192
 
193
+ // 0.6.90: the formula's Fragrance tab (Pro), with an optional what-if. "Can this oil go into a body lotion at 2%?" is
194
+ // get_fragrance_compliance { id, category: '5A', dosage: 2 }. Nothing is saved.
195
+ const get_fragrance_compliance = {
196
+ definition: {
197
+ name: 'get_fragrance_compliance',
198
+ description: 'A formulation\'s fragrance compliance as FormLab\'s Fragrance tab computes it (Pro; live workspace only): each fragrance material\'s % in the finished product against its IFRA limit for the product category (through sub-formulas), the highest dosage that passes and the material that limits it, and the EU fragrance allergens summed across materials with the ones to name on the label (above 0.001% leave-on, 0.01% rinse-off). Every limit is one the lab typed from a supplier\'s IFRA certificate; FormLab holds no IFRA limits of its own, so a material with no limit or declaration on file is reported as unknown and state is then "incomplete", never "conforms". Optional what-if inputs (not saved): category (IFRA product category, e.g. "5A" body lotion, "4" fine fragrance), use ("leave-on" | "rinse-off"), dosage (percent of a fragrance oil in the finished product). The result is based on the certificates on file and is not a certification: say so when you report it.',
199
+ inputSchema: {
200
+ type: 'object',
201
+ properties: {
202
+ id: { type: 'string', description: 'Internal id or UID (FORM-001) of the formulation.' },
203
+ category: { type: 'string', description: 'What-if IFRA product category: 1, 2, 3, 4, 5A, 5B, 5C, 5D, 6, 7A, 7B, 8, 9, 10A, 10B, 11A, 11B or 12. Default: the one set on the formula.' },
204
+ use: { type: 'string', enum: ['leave-on', 'rinse-off'], description: 'What-if product use, for the allergen labelling threshold. Default: the one set on the formula.' },
205
+ dosage: { type: 'number', description: 'What-if percent of this fragrance oil in the finished product (above 0, up to 100). Only meaningful when the formula is a fragrance oil. Default: the one set on the formula, else 100.' },
206
+ },
207
+ required: ['id'],
208
+ },
209
+ },
210
+ handler: async (args) => {
211
+ const { db, meta } = getStore();
212
+ if (!meta || meta.source !== 'cloud') return { error: 'Fragrance compliance is a FormLab Pro feature, read from a live workspace (cloud mode). This data source is an export file.' };
213
+ const f = resolveById('formulations', args.id);
214
+ if (!f) return { error: `No formulation found for id "${args.id}".` };
215
+ const r = fragranceCompliance(db, f.id, { category: args.category, use: args.use, dosage: args.dosage });
216
+ if (!r) return { id: f.id, uid: f.uid || '', name: f.name || '', state: 'none', reason: 'No fragrance to check: this formula holds no fragrance material (class or function Fragrance, or one with IFRA limits or an allergen declaration), or it is a food.' };
217
+ if (r.state === 'error') return { error: r.error };
218
+ return { id: f.id, uid: f.uid || '', name: f.name || '', whatIf: { category: args.category || null, use: args.use || null, dosage: args.dosage != null ? args.dosage : null }, ...r };
219
+ },
220
+ };
221
+
189
222
  // 0.6.83: the formula's Label tab (Pro). Jun, 15 Nov: new food features are Pro, so this reads a live workspace only
190
223
  // (cloud mode is Pro); an export file gets the reason.
191
224
  const get_nutrition_label = {
@@ -316,6 +349,7 @@ export const tools = {
316
349
  list_formulations,
317
350
  get_formulation,
318
351
  get_nutrition_label,
352
+ get_fragrance_compliance,
319
353
  find_similar_formulations,
320
354
  compare_formulations,
321
355
  };
@@ -393,6 +393,8 @@ const list_lots = {
393
393
  // 'hold' / 'quarantine' / 'rejected' lots are blocked from auto-consumption;
394
394
  // holdReason explains a manual hold (QC / recall).
395
395
  holdReason: l.holdReason || '',
396
+ // A disposed lot: when, why, how much was written off (status is then "disposed").
397
+ disposal: l.status === 'disposed' ? { date: l.disposedAt || null, by: l.disposedBy || '', reason: l.disposeReason || '', note: l.disposeNote || '', qty: l.disposedQty ?? null } : null,
396
398
  unitCost: (l.unitCost != null && l.unitCost !== '') ? l.unitCost : null,
397
399
  unitCostCcy: l.unitCostCcy || null,
398
400
  ..._lotCoaInfo(l, ingById.get(l.ingredientId)),
package/tools/lab.js CHANGED
@@ -297,6 +297,8 @@ const list_batches = {
297
297
  since_date: { type: 'string', description: 'ISO date (YYYY-MM-DD). Only batches prepared on/after this date.' },
298
298
  best_by_before: { type: 'string', description: 'ISO date (YYYY-MM-DD). Only batches whose best-by falls before this date (today = past best-by). Batches with no best-by are left out.' },
299
299
  lots_expire_first: { type: 'boolean', description: 'When true, only batches that drew from an ingredient lot expiring before the batch\'s best-by (the app\'s ⚠ on Best by).' },
300
+ shipped_to: { type: 'string', description: 'Only batches with a shipment whose note (customer / destination / PO) contains this text, case-insensitive. Use it to find which batch went to a customer.' },
301
+ on_hold: { type: 'boolean', description: 'When true, only finished batches currently on hold (no shipment can be recorded until released).' },
300
302
  limit: { type: 'number', description: 'Max rows (default 50, max 500).' },
301
303
  },
302
304
  },
@@ -318,6 +320,8 @@ const list_batches = {
318
320
  if (args.status && !norm(b.status).includes(norm(args.status))) return false;
319
321
  if (args.origin_only && b.parentBatchId) return false;
320
322
  if (args.since_date && (b.preparedDate || '') < args.since_date) return false;
323
+ 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;
324
+ if (args.on_hold && !(b.fgHold && b.fgHold.at)) return false;
321
325
  if (args.best_by_before || args.lots_expire_first) {
322
326
  const bb = _bestByInfo(b, b.formulationId ? indexes.formulationsById.get(b.formulationId) : null);
323
327
  if (!bb) return false;
@@ -385,6 +389,8 @@ const get_batch = {
385
389
  date: e.ts || null, delta: e.delta ?? null, unit: e.unit || b.unit || '', kind: e.kind || '', note: e.note || '',
386
390
  })),
387
391
  shippedQty: (Array.isArray(b.stockLedger) ? b.stockLedger : []).reduce((s, e) => e.kind === 'shipment' ? s + Math.abs(parseFloat(e.delta) || 0) : s, 0),
392
+ // Finished-batch hold: while set, the app records no shipment of this batch (QA / complaint / recall).
393
+ hold: (b.fgHold && b.fgHold.at) ? { since: b.fgHold.at, by: b.fgHold.by || '', reason: b.fgHold.reason || '' } : null,
388
394
  theoreticalParameters: theoreticalParams(getStore().db, 'batch', b.id),
389
395
  };
390
396
  },
package/vendor/cost.js CHANGED
@@ -1716,24 +1716,32 @@ function deviationLegendHtml() {
1716
1716
  // Used by the batch AND sample weigh-outs so both correct identically. This is
1717
1717
  // a bench/weigh-out concept only — composition, cost, and property math keep
1718
1718
  // using the as-declared amounts.
1719
- function effectivePurity(ing) {
1719
+ function effectivePurity(ing, pinLotId) {
1720
1720
  if (!ing) return null;
1721
1721
  const nom = parseFloat(ing.purity);
1722
1722
  if (isFinite(nom) && nom > 0) return nom < 100 ? nom : null;
1723
- // No usable nominal → fall back to a representative active lot with purity.
1723
+ // LP1 (19 Nov): a batch that pins a lot for this ingredient draws that lot first, so its purity is the one weighed.
1724
+ if (pinLotId && typeof db !== 'undefined' && Array.isArray(db.lots)) {
1725
+ const pl = db.lots.find(l => l && l.id === pinLotId && l.ingredientId === ing.id);
1726
+ if (pl && (parseFloat(pl.qtyRemaining) || 0) > 0 && (typeof _lotIsUsable !== 'function' || _lotIsUsable(pl))) {
1727
+ const pp = parseFloat(pl.purity);
1728
+ return (isFinite(pp) && pp > 0 && pp < 100) ? pp : null;
1729
+ }
1730
+ }
1731
+ // No usable nominal → the purity of the lot the next draw takes (the lab's FEFO / FIFO rule over every usable lot),
1732
+ // if that lot has one. It used to pick the first lot WITH a purity, so a trial drum's 68.5% grossed up a batch that
1733
+ // drew a different supplier's lot with none (supplier-swap sim, 19 Nov: +46% SLES). No lot rule (off) → no fallback.
1724
1734
  const lots = (typeof db !== 'undefined' && Array.isArray(db.lots))
1725
- ? db.lots.filter(l => l.ingredientId === ing.id
1726
- && (parseFloat(l.qtyRemaining) || 0) > 0
1727
- && (!l.status || l.status === 'active')
1728
- && l.purity != null && isFinite(parseFloat(l.purity)) && parseFloat(l.purity) > 0)
1735
+ ? db.lots.filter(l => l.ingredientId === ing.id && (parseFloat(l.qtyRemaining) || 0) > 0
1736
+ && (typeof _lotIsUsable === 'function' ? _lotIsUsable(l) : (!l.status || l.status === 'active')))
1729
1737
  : [];
1730
1738
  if (!lots.length) return null;
1731
- lots.sort((a, b) => {
1732
- const ax = a.expiryDate || '9999-12-31', bx = b.expiryDate || '9999-12-31';
1733
- if (ax !== bx) return ax < bx ? -1 : 1;
1734
- return (a.receivedDate || '').localeCompare(b.receivedDate || '');
1735
- });
1736
- const p = parseFloat(lots[0].purity);
1739
+ const strat = (typeof _lotStrategy === 'function') ? _lotStrategy() : 'fefo';
1740
+ if (strat === 'off') return null;
1741
+ const ordered = (typeof sortLotsForConsumption === 'function') ? sortLotsForConsumption(lots, strat === 'fifo' ? 'fifo' : 'fefo')
1742
+ : lots.slice().sort((a, b) => { const ax = a.expiryDate || '9999-12-31', bx = b.expiryDate || '9999-12-31';
1743
+ return ax !== bx ? (ax < bx ? -1 : 1) : (a.receivedDate || '').localeCompare(b.receivedDate || ''); });
1744
+ const p = parseFloat((ordered[0] || {}).purity);
1737
1745
  return (isFinite(p) && p > 0 && p < 100) ? p : null;
1738
1746
  }
1739
1747
 
@@ -1773,12 +1781,12 @@ function lotPurityDeviation(ing, opts) {
1773
1781
  // model — other rows are NOT rebalanced). Returns the amount technicians
1774
1782
  // weigh, the purity used, and the active amount it delivers. Sub-formula rows
1775
1783
  // and rows with no purity data pass through unchanged.
1776
- function correctAmountForPurity(comp, amt) {
1784
+ function correctAmountForPurity(comp, amt, pins) {
1777
1785
  const passthrough = { amount: amt, purity: null, activeAmount: amt };
1778
1786
  if (!comp || !comp.ingredientId || amt == null || !isFinite(amt)) return passthrough;
1779
1787
  const ing = (typeof db !== 'undefined' && Array.isArray(db.ingredients))
1780
1788
  ? db.ingredients.find(i => i.id === comp.ingredientId) : null;
1781
- const p = effectivePurity(ing);
1789
+ const p = effectivePurity(ing, pins && ing ? pins[ing.id] : null);
1782
1790
  if (p == null || !(p > 0) || p >= 100) return passthrough;
1783
1791
  return { amount: amt / (p / 100), purity: p, activeAmount: amt };
1784
1792
  }
@@ -2092,7 +2100,7 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
2092
2100
  return (inAlt != null && isFinite(inAlt)) ? `<strong>${fmt(inAlt)}</strong> <span translate="no" style="color:var(--dk-faint, #94a3b8);font-size:10px">${esc(altUnit)}</span>` : null;
2093
2101
  })();
2094
2102
  const tfoot = `<tr style="border-top:1px solid #dbeafe">
2095
- <td></td><td style="padding:5px 8px;font-weight:600">Total${_volTarget ? ` <span style="font-weight:400;color:var(--dk-faint, #94a3b8);font-size:10.5px" title="Sum of the pure-ingredient volumes in the Planned column. Not a lab quantity — the finished batch is ${esc(w.qty)} ${esc(w.unit)}; the mass in the ≈ column is what the batch weighs.">(pure-ingredient volumes)</span>` : ''}</td>
2103
+ <td></td><td style="padding:5px 8px;font-weight:600">Total${_volTarget ? ` <span style="font-weight:400;color:var(--dk-faint, #94a3b8);font-size:10.5px" title="Sum of ingredient volumes in the Planned column. The finished batch is ${esc(w.qty)} ${esc(w.unit)}.">(pure-ingredient volumes)</span>` : ''}</td>
2096
2104
  <td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;font-weight:${_volTarget ? 400 : 700};color:${_volTarget ? 'var(--dk-faint, #94a3b8)' : 'inherit'}" title="${_volTarget ? `Volumes aren't additive on mixing — this sum has no bench meaning. Finished batch: ${esc(w.qty)} ${esc(w.unit)}.` : ''}">${cv(w.total)}</td>
2097
2105
  ${hasActuals ? `<td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;font-weight:700">${cv(actualTotal)}</td>
2098
2106
  <td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;color:var(--dk-muted, #64748b)">${cvs(totalDelta)}</td>` : ''}
@@ -2243,7 +2251,7 @@ function defaultPercentBasis(formulation, costSummary) {
2243
2251
  // Approximate kg conversion for batch.targetQuantity.unit. If
2244
2252
  // volume, falls back to *assume kg* unless density is known.
2245
2253
  function computeBatchCost(batch, displayCcy = getDisplayCurrency()) {
2246
- const f = db.formulations.find(x => x.id === batch.formulationId);
2254
+ const f = (typeof flBatchFormula === 'function' ? flBatchFormula(batch) : db.formulations.find(x => x.id === batch.formulationId));
2247
2255
  if (!f) return null;
2248
2256
  const perKg = computeFormulationCost(f, displayCcy);
2249
2257
  // Batch size in kg via the shared quantityToKg (mass units convert directly;
@@ -2607,6 +2615,15 @@ function entityCostValueHtml(o) {
2607
2615
  if (!o.formula) {
2608
2616
  const rec = ((typeof db !== 'undefined' && db && db[o.kind === 'batch' ? 'batches' : 'samples']) || []).find(x => x && x.id === o.id);
2609
2617
  const fid = rec && rec.formulationId;
2618
+ // A sample taken from a material lot has no formula: it costs what the lot costs (replacement-lot sim, 21 Nov).
2619
+ const lot = rec && rec.lotId ? ((db.lots || []).find(l => l && l.id === rec.lotId)) : null;
2620
+ if (lot) {
2621
+ const uc = parseFloat(lot.unitCost), q = parseFloat(o.qty), lc = lot.unitCostCcy || 'USD';
2622
+ const own = (isFinite(uc) && isFinite(q) && (o.unit || '') === (lot.unit || '')) ? q * uc : null;
2623
+ const v = own == null ? null : (lc !== ccy && typeof convertCurrencySync === 'function') ? convertCurrencySync(own, lc, ccy) : own;
2624
+ if (v != null && isFinite(v)) return `<strong>${money(v)}</strong><span style="font-size:11px;color:var(--text-muted);margin-left:6px">${esc(String(o.qty))} ${esc(o.unit || '')} × ${typeof formatMoney === 'function' ? formatMoney(uc, lc) : uc}/${esc(lot.unit || '')} · lot <span translate="no">${esc(lot.lotNumber || lot.uid || '')}</span></span>${editBtn}`;
2625
+ return `<span style="color:var(--text-muted)">—</span> <span style="font-size:11px;color:var(--text-muted)">material sample, lot has no cost</span>${editBtn}`;
2626
+ }
2610
2627
  const why = !fid ? 'no formula' : (typeof flTrashEntryFor === 'function' && flTrashEntryFor('formulation', fid)) ? 'formula is in Trash' : 'formula deleted';
2611
2628
  return `<span style="color:var(--text-muted)">—</span> <span style="font-size:11px;color:var(--text-muted)">${why}</span>${editBtn}`;
2612
2629
  }
@@ -151,7 +151,10 @@ function eqCalCardHtml(e) {
151
151
  <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>
152
152
  <span><span style="color:var(--text-muted)">Next due</span> <strong>${esc(st.due || '—')}</strong></span>
153
153
  <span><span style="color:var(--text-muted)">Interval</span> <strong>${interval ? interval + ' month' + (interval === 1 ? '' : 's') : '—'}</strong></span>
154
- </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>` : ''}`;
154
+ </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>` : ''}${
155
+ // Dogfooding, 22 Nov (pH meter back in service): the card read "OK · due 2027-11-22" under an Out of service
156
+ // badge and said nothing, where a failed calibration says to take the unit out. The way back is said too.
157
+ (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>` : ''}`;
155
158
  const rows = hist.map(c => `<tr>
156
159
  <td style="font-variant-numeric:tabular-nums">${esc(c.date || '—')}</td>
157
160
  <td>${esc(c.by || '—')}</td>
@@ -248,7 +251,8 @@ function openEqCalLogModal(eqId, calId) {
248
251
  const patch = { calibrations: list };
249
252
  updateEquipment(eqId, patch);
250
253
  if (typeof renderEquipmentDetail === 'function' && typeof currentView !== 'undefined' && currentView === 'equipment-detail') renderEquipmentDetail(eqId);
251
- toast(c ? 'Calibration updated.' : (rec.result === 'fail' ? 'Calibration logged as failed. Set the instrument Out of service until it passes.' : 'Calibration logged.'));
254
+ toast(c ? 'Calibration updated.' : (rec.result === 'fail' ? 'Calibration logged as failed. Set the instrument Out of service until it passes.'
255
+ : (cur.status === 'Out of service' ? 'Calibration logged. The instrument is still Out of service.' : 'Calibration logged.')));
252
256
  return true;
253
257
  }, true, null, c ? 'Save' : 'Log calibration');
254
258
  if (c) {