formlab-mcp 0.6.89 → 0.6.91

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,11 +31,12 @@ 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
- | `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`) |
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`) |
37
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) |
38
- | `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`, `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 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
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 |
40
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) |
41
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 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.89",
3
+ "version": "0.6.91",
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.89",
5
+ "version": "0.6.91",
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.89",
11
+ "version": "0.6.91",
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) {
@@ -125,7 +125,7 @@ const list_documents = {
125
125
  inputSchema: {
126
126
  type: 'object',
127
127
  properties: {
128
- type: { type: 'array', items: { type: 'string' }, description: 'Document types to include: SDS, PDS, COA, OTHER (ingredient documents), TEST, NOTE, FILE (upload), LINK.' },
128
+ type: { type: 'array', items: { type: 'string' }, description: 'Document types to include: SDS, PDS, COA, FRAG, OTHER (ingredient documents; FRAG = IFRA certificates and fragrance allergen declarations), TEST, NOTE, FILE (upload), LINK.' },
129
129
  record: { type: 'string', description: 'Kind of record the file is attached to: ingredient, formulation, batch, sample, test, notebook, project, supplier, equipment, template, procedureTemplate, parameter.' },
130
130
  linked: { type: 'string', description: 'Case-insensitive substring of the linked record\'s name / UID.' },
131
131
  query: { type: 'string', description: 'Case-insensitive substring over file name, linked record, lot and source.' },
@@ -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
  };
@@ -121,13 +121,14 @@ function _lotSourceInfo(l) {
121
121
  const list_ingredients = {
122
122
  definition: {
123
123
  name: 'list_ingredients',
124
- description: 'List ingredients (raw materials) in the FormLab library, optionally filtered by family, supplier, or name pattern. Returns metadata; use get_ingredient for full details.',
124
+ description: 'List ingredients (raw materials) in the FormLab library, optionally filtered by family, supplier, name pattern, or lot number (lot_number finds the ingredient a recalled lot belongs to). Returns metadata; use get_ingredient for full details.',
125
125
  inputSchema: {
126
126
  type: 'object',
127
127
  properties: {
128
128
  family: { type: 'string', description: 'Filter by family (e.g. "Pigment", "Surfactant"). Case-insensitive substring.' },
129
129
  supplier: { type: 'string', description: 'Filter by supplier name. Case-insensitive substring.' },
130
130
  name_contains: { type: 'string', description: 'Case-insensitive substring on ingredient name.' },
131
+ lot_number: { type: 'string', description: 'Only ingredients with a lot whose lot number or lot UID contains this (case-insensitive), e.g. "BIT-9912" from a supplier recall. Disposed lots count.' },
131
132
  in_stock_only: { type: 'boolean', description: 'When true, return only ingredients with stockOnHand > 0.' },
132
133
  ingredient_class: { type: 'string', description: 'Filter by symbolic class: small-molecule, surfactant, polymer, extract, fragrance, pigment, sequence, mixture.' },
133
134
  sequence_contains: { type: 'string', description: 'Case-insensitive substring match on peptide / oligo sequence (e.g. "KTTKS" matches Matrixyl).' },
@@ -141,8 +142,10 @@ const list_ingredients = {
141
142
  const { db } = getStore();
142
143
  const limit = Math.min(1000, Math.max(1, args.limit || 100));
143
144
  const norm = (s) => String(s || '').toLowerCase();
145
+ const lotIngs = args.lot_number ? new Set((db.lots || []).filter(l => l && !l._trashed && !l.deletedAt && (norm(l.lotNumber).includes(norm(args.lot_number)) || norm(l.uid).includes(norm(args.lot_number)))).map(l => l.ingredientId)) : null;
144
146
  const filtered = (db.ingredients || []).filter(i => {
145
147
  if (!i || i._trashed) return false;
148
+ if (lotIngs && !lotIngs.has(i.id)) return false;
146
149
  if (args.family && !norm(i.family).includes(norm(args.family))) return false;
147
150
  if (args.supplier && !norm(i.supplier).includes(norm(args.supplier))) return false;
148
151
  if (args.name_contains && !norm(i.name).includes(norm(args.name_contains))) return false;
@@ -346,11 +349,12 @@ const find_by_smarts = {
346
349
  const list_lots = {
347
350
  definition: {
348
351
  name: 'list_lots',
349
- description: 'List inventory lots (received batches of an ingredient, each with its own remaining balance, supplier, expiry, and unit cost). Each lot also carries the approved source it was received from (source.supplier + source.manufacturer; recalls hinge on the manufacturer), or null for lots predating sources. Optionally filter by ingredient, expiring-within-days, or status. A lot\'s status can be "active", "hold" (a manual QC / recall hold — see holdReason), "quarantine", or "rejected"; the last three are blocked from auto-consumption. For one ingredient\'s full lots + traceability, use get_ingredient.',
352
+ description: 'List inventory lots (received batches of an ingredient, each with its own remaining balance, supplier, expiry, and unit cost). Each lot also carries the approved source it was received from (source.supplier + source.manufacturer; recalls hinge on the manufacturer), or null for lots predating sources. Optionally filter by ingredient, lot number, expiring-within-days, or status. A lot\'s status can be "active", "hold" (a manual QC / recall hold — see holdReason), "quarantine", or "rejected"; the last three are blocked from auto-consumption. For one ingredient\'s full lots + traceability, use get_ingredient.',
350
353
  inputSchema: {
351
354
  type: 'object',
352
355
  properties: {
353
356
  ingredient_id: { type: 'string', description: 'Only lots for this ingredient (internal id or UID, e.g. ING-001).' },
357
+ lot_number: { type: 'string', description: 'Only lots whose lot number or lot UID contains this (case-insensitive), e.g. "BIT-9912" from a supplier recall.' },
354
358
  expiring_within_days: { type: 'number', description: 'Only lots whose expiryDate is within this many days from now (negative days = already expired are always included).' },
355
359
  status: { type: 'string', description: 'Filter by lot status: "active", "hold", "quarantine", or "rejected". Held/quarantined/rejected lots are blocked from auto-consumption (use "hold" to find lots put on hold for a QC / recall).' },
356
360
  missing_coa: { type: 'boolean', description: 'true = only lots still in stock (not rejected) that have no Certificate of Analysis — neither linked nor a CoA on the ingredient with the same lot number. Same list as the app\'s Documents → "Lots in stock without CoA".' },
@@ -372,6 +376,7 @@ const list_lots = {
372
376
  const rows = (db.lots || []).filter(l => {
373
377
  if (!l || l._trashed) return false;
374
378
  if (ing && l.ingredientId !== ing.id) return false;
379
+ if (args.lot_number) { const w = String(args.lot_number).toLowerCase(); if (!String(l.lotNumber || '').toLowerCase().includes(w) && !String(l.uid || '').toLowerCase().includes(w)) return false; }
375
380
  if (args.missing_coa === true && !_lotCoaInfo(l, ingById.get(l.ingredientId)).coaMissing) return false;
376
381
  if (args.status && String(l.status || 'active').toLowerCase() !== String(args.status).toLowerCase()) return false;
377
382
  if (args.expiring_within_days != null) {
package/vendor/cost.js CHANGED
@@ -316,7 +316,13 @@ function getQuantityUnits() {
316
316
  var its = items();
317
317
  var pick = activeIdx >= 0 ? its[activeIdx] : (its.length === 1 ? its[0] : null);
318
318
  if (pick) { choose(pick.getAttribute('data-val')); e.preventDefault(); }
319
- } else if (e.key === 'Escape') { hide(); if (activeInput) try { activeInput.focus(); } catch (_) {} }
319
+ } else if (e.key === 'Escape') {
320
+ // Esc closes the list only (dogfooding 26 Nov: in New Batch it also closed the dialog, and the refocus below
321
+ // reopened the list, left floating over the page). Marked as handled, so the dialog's Esc leaves it be.
322
+ e.preventDefault(); e.stopPropagation();
323
+ hide();
324
+ if (activeInput) { refocusing = true; try { activeInput.focus(); } catch (_) {} refocusing = false; }
325
+ }
320
326
  }
321
327
 
322
328
  document.addEventListener('focusin', function (e) { if (isCombo(e.target) && !refocusing) open(e.target); });
@@ -1707,27 +1713,37 @@ function deviationLegendHtml() {
1707
1713
 
1708
1714
  // Effective % active for grossing up a weigh-out amount of a technical
1709
1715
  // (impure) ingredient. Precedence:
1710
- // 1. the ingredient's nominal `purity` (the stable spec / override), else
1711
- // 2. the purity of the active lot we'd draw next (soonest expiry, then
1716
+ // 1. a lot the batch / sample PINS (lotPins, LP1) whose CoA assay is set:
1717
+ // that lot is the one weighed, so its assay is the basis (Jun, 25 Nov:
1718
+ // the remade batch weighs at the new lot's 94.1%, nominal stays 97%), else
1719
+ // 2. the ingredient's nominal `purity` (the stable spec / design basis), else
1720
+ // 3. a pinned lot with no assay → no correction (it is the lot drawn), else
1721
+ // 4. the purity of the active lot we'd draw next (soonest expiry, then
1712
1722
  // oldest received) — so lot data entered on the CoA is used even with no
1713
1723
  // nominal set, else
1714
- // 3. null → treat as 100% (no correction).
1715
- // A nominal (or lot) value of ≥100 means "pure" → returns null (no correction).
1724
+ // 5. null → treat as 100% (no correction).
1725
+ // A value of ≥100 means "pure" → returns null (no correction).
1716
1726
  // Used by the batch AND sample weigh-outs so both correct identically. This is
1717
1727
  // a bench/weigh-out concept only — composition, cost, and property math keep
1718
- // using the as-declared amounts.
1719
- function effectivePurity(ing, pinLotId) {
1720
- if (!ing) return null;
1728
+ // using the as-declared amounts. _purityBasis also names the pinned lot when
1729
+ // its assay is the one used, so the weigh-out row can say so.
1730
+ function _purityBasis(ing, pinLotId) {
1731
+ const none = { purity: null, lot: null };
1732
+ if (!ing) return none;
1733
+ const ok = v => (isFinite(v) && v > 0 && v < 100) ? v : null;
1721
1734
  const nom = parseFloat(ing.purity);
1722
- if (isFinite(nom) && nom > 0) return nom < 100 ? nom : null;
1723
- // LP1 (19 Nov): a batch that pins a lot for this ingredient draws that lot first, so its purity is the one weighed.
1735
+ const hasNom = isFinite(nom) && nom > 0;
1736
+ let pinned = null;
1724
1737
  if (pinLotId && typeof db !== 'undefined' && Array.isArray(db.lots)) {
1725
1738
  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
- }
1739
+ if (pl && (parseFloat(pl.qtyRemaining) || 0) > 0 && (typeof _lotIsUsable !== 'function' || _lotIsUsable(pl))) pinned = pl;
1730
1740
  }
1741
+ if (pinned) {
1742
+ const pp = parseFloat(pinned.purity);
1743
+ if (isFinite(pp) && pp > 0) return { purity: ok(pp), lot: pinned };
1744
+ }
1745
+ if (hasNom) return { purity: ok(nom), lot: null };
1746
+ if (pinned) return none;
1731
1747
  // No usable nominal → the purity of the lot the next draw takes (the lab's FEFO / FIFO rule over every usable lot),
1732
1748
  // 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
1749
  // drew a different supplier's lot with none (supplier-swap sim, 19 Nov: +46% SLES). No lot rule (off) → no fallback.
@@ -1735,17 +1751,17 @@ function effectivePurity(ing, pinLotId) {
1735
1751
  ? db.lots.filter(l => l.ingredientId === ing.id && (parseFloat(l.qtyRemaining) || 0) > 0
1736
1752
  && (typeof _lotIsUsable === 'function' ? _lotIsUsable(l) : (!l.status || l.status === 'active')))
1737
1753
  : [];
1738
- if (!lots.length) return null;
1754
+ if (!lots.length) return none;
1739
1755
  const strat = (typeof _lotStrategy === 'function') ? _lotStrategy() : 'fefo';
1740
- if (strat === 'off') return null;
1756
+ if (strat === 'off') return none;
1741
1757
  const ordered = (typeof sortLotsForConsumption === 'function') ? sortLotsForConsumption(lots, strat === 'fifo' ? 'fifo' : 'fefo')
1742
1758
  : lots.slice().sort((a, b) => { const ax = a.expiryDate || '9999-12-31', bx = b.expiryDate || '9999-12-31';
1743
1759
  return ax !== bx ? (ax < bx ? -1 : 1) : (a.receivedDate || '').localeCompare(b.receivedDate || ''); });
1744
- const p = parseFloat((ordered[0] || {}).purity);
1745
- return (isFinite(p) && p > 0 && p < 100) ? p : null;
1760
+ return { purity: ok(parseFloat((ordered[0] || {}).purity)), lot: null };
1746
1761
  }
1762
+ function effectivePurity(ing, pinLotId) { return _purityBasis(ing, pinLotId).purity; }
1747
1763
 
1748
- // Lot-assay deviation warning. The weigh-out is grossed up on the ingredient's
1764
+ // Lot-assay deviation warning. An unpinned weigh-out is grossed up on the ingredient's
1749
1765
  // NOMINAL purity (the design basis — see effectivePurity); a delivered lot may
1750
1766
  // assay differently. When the lot this row will draw from (the batch's consumed
1751
1767
  // lots, else the FIFO front lot) deviates from the nominal by ≥ PURITY_DEVIATION_WARN
@@ -1786,9 +1802,13 @@ function correctAmountForPurity(comp, amt, pins) {
1786
1802
  if (!comp || !comp.ingredientId || amt == null || !isFinite(amt)) return passthrough;
1787
1803
  const ing = (typeof db !== 'undefined' && Array.isArray(db.ingredients))
1788
1804
  ? db.ingredients.find(i => i.id === comp.ingredientId) : null;
1789
- const p = effectivePurity(ing, pins && ing ? pins[ing.id] : null);
1805
+ const basis = _purityBasis(ing, pins && ing ? pins[ing.id] : null);
1806
+ const p = basis.purity;
1790
1807
  if (p == null || !(p > 0) || p >= 100) return passthrough;
1791
- return { amount: amt / (p / 100), purity: p, activeAmount: amt };
1808
+ // lotBasis: the pinned lot whose assay this row weighs at (null = nominal / next-lot basis).
1809
+ const nom = parseFloat(ing.purity);
1810
+ const lotBasis = basis.lot ? { lotId: basis.lot.id, lotNumber: basis.lot.lotNumber || basis.lot.uid || '', nominal: (isFinite(nom) && nom > 0) ? nom : null } : null;
1811
+ return { amount: amt / (p / 100), purity: p, activeAmount: amt, lotBasis };
1792
1812
  }
1793
1813
 
1794
1814
  // A composition row carrying this role is the "balance / q.s." ingredient:
@@ -1848,6 +1868,7 @@ function applyQsBalance(rows, targetQty) {
1848
1868
  rows[bi].amount = bal;
1849
1869
  rows[bi].qs = true; // panel shows a q.s. tag
1850
1870
  rows[bi].purity = null; // the balance row isn't purity-corrected
1871
+ rows[bi].lotBasis = null;
1851
1872
  rows[bi].activeAmount = bal;
1852
1873
  return out;
1853
1874
  }
@@ -1887,8 +1908,11 @@ function _weighoutDensityLineHtml(w) {
1887
1908
  }
1888
1909
 
1889
1910
  function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
1890
- const fmt = n => (n == null || !isFinite(n)) ? '—' : parseFloat(n.toFixed(4)).toString();
1891
- const sgn = n => (n == null || !isFinite(n)) ? '—' : (n > 0 ? '+' : '') + parseFloat(n.toFixed(4)).toString();
1911
+ // Two decimals from 10 up (53.13 kg, 46.87 g: what a balance at that scale reads); smaller amounts keep four
1912
+ // so a 0.0583 g trace active still shows (Jun, 25 Nov, film 10).
1913
+ const _woDp = n => parseFloat(n.toFixed(Math.abs(n) >= 10 ? 2 : 4)).toString();
1914
+ const fmt = n => (n == null || !isFinite(n)) ? '—' : _woDp(n);
1915
+ const sgn = n => (n == null || !isFinite(n)) ? '—' : (n > 0 ? '+' : '') + _woDp(n);
1892
1916
  if (!w || !w.available) {
1893
1917
  if (w && w.reason === 'bad-unit')
1894
1918
  return `<div style="padding:8px 11px;margin-bottom:12px;background:var(--dk-amber-bg, #fffbeb);border:1px solid var(--dk-amber-line, #fde68a);border-radius:6px;color:var(--dk-amber-fg, #92400e);font-size:12px"><span class="fl-warn" aria-hidden="true"></span> Set the ${noun} quantity in a <strong>mass or volume unit</strong> (g, kg, mL, L…) to get a weigh-out sheet — currently <strong>${esc(w.unit || '—')}</strong>.</div>`;
@@ -1975,7 +1999,7 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
1975
1999
  if (a) { actInUnit = toUnit(a.amount, a.unit, r.key); if (actInUnit != null) actualTotal += actInUnit; }
1976
2000
  const delta = (hasActuals && planned != null && actInUnit != null) ? (actInUnit - planned) : null;
1977
2001
  const rel = (delta != null && planned > 0) ? Math.abs(delta) / planned : (delta != null && actInUnit > 0 ? 1 : null);
1978
- return { key: r.key, name: r.name, planned, actInUnit, actRaw: a, delta, rel, purity: r.purity, activeAmount: r.activeAmount, qs: r.qs, lotDev: r.lotDev || null };
2002
+ return { key: r.key, name: r.name, planned, actInUnit, actRaw: a, delta, rel, purity: r.purity, activeAmount: r.activeAmount, qs: r.qs, lotDev: r.lotDev || null, lotBasis: r.lotBasis || null };
1979
2003
  });
1980
2004
  // Union in ingredients that were ADDED to the As-prepared table but aren't in
1981
2005
  // the recipe (a spike / colorant / q.s. carrier). Without this the weigh-out
@@ -1994,9 +2018,10 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
1994
2018
  rows.push({ key, name, planned: null, actInUnit, actRaw: a, delta: actInUnit, rel: (actInUnit > 0 ? 1 : null), purity: null, activeAmount: null, qs: false, _added: true });
1995
2019
  });
1996
2020
  }
1997
- const _rNumFmt = v => (typeof _fmpNum === 'function') ? _fmpNum(v) : (Math.abs(v) >= 100 ? (+v).toFixed(1) : (+v).toFixed(3)).replace(/\.?0+$/, '');
1998
- const _purityTagBase = r => (r.purity == null) ? '' :
1999
- ` <span style="font-size:9.5px;color:var(--dk-violet-fg, #6d28d9);font-weight:600;background:var(--dk-violet-bg, #f5f3ff);border:1px solid var(--dk-violet-line, #ddd6fe);border-radius:4px;padding:0 3px;vertical-align:middle;white-space:nowrap" title="Grossed up for ${esc(String(+r.purity))}% purity, delivers ${cv(r.activeAmount)} ${esc(displayUnit)} of active">↑${esc(String(+r.purity))}%</span>`;
2021
+ const _rNumFmt = v => cv(v); // the badge's corrected amount reads like the row: same unit, same decimals
2022
+ const _purityTagBase = r => (r.purity == null) ? '' : r.lotBasis
2023
+ ? ` <span style="font-size:9.5px;color:var(--dk-violet-fg, #6d28d9);font-weight:600;background:var(--dk-violet-bg, #f5f3ff);border:1px solid var(--dk-violet-line, #ddd6fe);border-radius:4px;padding:0 3px;vertical-align:middle;white-space:nowrap" title="Weighed at the assay of pinned lot ${esc(String(r.lotBasis.lotNumber))}, ${esc(String(+r.purity))}%${r.lotBasis.nominal != null ? ` (nominal ${esc(String(+r.lotBasis.nominal))}%)` : ''}. Delivers ${cv(r.activeAmount)} ${esc(displayUnit)} of active">↑ at lot <span translate="no">${esc(String(r.lotBasis.lotNumber))}</span> ${esc(String(+r.purity))}%</span>`
2024
+ : ` <span style="font-size:9.5px;color:var(--dk-violet-fg, #6d28d9);font-weight:600;background:var(--dk-violet-bg, #f5f3ff);border:1px solid var(--dk-violet-line, #ddd6fe);border-radius:4px;padding:0 3px;vertical-align:middle;white-space:nowrap" title="Grossed up for ${esc(String(+r.purity))}% purity, delivers ${cv(r.activeAmount)} ${esc(displayUnit)} of active">↑${esc(String(+r.purity))}%</span>`;
2000
2025
  // Lot-assay deviation: the lot this row draws from assays away from the nominal.
2001
2026
  const purityTag = r => _purityTagBase(r) + (!r.lotDev ? '' :
2002
2027
  ` <span style="font-size:9.5px;color:var(--dk-amber-fg, #b45309);font-weight:600;background:var(--dk-amber-bg, #fffbeb);border:1px solid var(--dk-amber-line, #fde68a);border-radius:4px;padding:0 3px;vertical-align:middle;white-space:nowrap" title="Lot ${esc(String(r.lotDev.lotNumber))} assays ${esc(String(+r.lotDev.lotPurity))}% but the weigh-out is grossed up on the nominal ${esc(String(+r.lotDev.nominal))}%. ${r.lotDev.consumed ? 'This batch drew from that lot.' : 'FIFO will draw from that lot next.'} To deliver the spec active at the lot's assay, weigh ${r.lotDev.correctedAmount != null ? esc(_rNumFmt(r.lotDev.correctedAmount)) + ' ' + esc(String(displayUnit || w.unit || '')) : 'the corrected amount'} instead.">⚠ lot ${esc(String(+r.lotDev.lotPurity))}% vs ${esc(String(+r.lotDev.nominal))}%${r.lotDev.correctedAmount != null ? ' → ' + esc(_rNumFmt(r.lotDev.correctedAmount)) : ''}</span>`);
@@ -2075,9 +2100,13 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
2075
2100
  ${th('Unit', 'text-align:left')}
2076
2101
  ${_altAny ? `<th style="padding:5px 8px;color:var(--dk-text-3, #475569);font-weight:400;text-align:right" title="Approx. ${esc(_altDim || '')} equivalent, derived per-ingredient from its own density. Reference only — not additive, so no total.">≈ ${esc(altUnit)}</th>` : ''}
2077
2102
  </tr>`;
2103
+ // The gross-up's arithmetic under the ingredient name, so the sheet shows why a row weighs more than the recipe
2104
+ // (Jun, 26 Nov, film 10: "the reasoning behind 106.27"). Basis = the pinned lot's assay, else the nominal.
2105
+ const purityWhy = r => (r.purity == null || r._added || r.planned == null || r.activeAmount == null || !isFinite(r.activeAmount)) ? ''
2106
+ : `<div class="fl-wo-why" style="font-size:11px;color:var(--dk-muted, #64748b);margin-top:1px;font-variant-numeric:tabular-nums">${cv(r.activeAmount)} ${esc(displayUnit)} active ÷ ${esc(String(+r.purity))}% ${r.lotBasis ? `(lot <span translate="no">${esc(String(r.lotBasis.lotNumber))}</span> assay)` : '(nominal)'} = <strong style="color:var(--dk-text-2, #334155)">${cv(r.planned)} ${esc(displayUnit)}</strong></div>`;
2078
2107
  const body = rows.map((r, i) => `<tr data-wo-key="${esc(r.key)}" style="${hasActuals ? dRowBg(r.rel) : ''}">
2079
2108
  <td style="padding:4px 8px;color:var(--dk-faint, #94a3b8)">${i + 1}</td>
2080
- <td style="padding:4px 8px">${esc(r.name)}${r._added ? ` <span style="font-size:9.5px;color:var(--dk-red-fg, #b91c1c);font-weight:600;background:var(--dk-red-bg, #fef2f2);border:1px solid var(--dk-red-line, #fecaca);border-radius:4px;padding:0 4px;vertical-align:middle;white-space:nowrap" title="Added to the as-prepared batch — not part of the linked recipe">+ not in recipe</span>` : ''}</td>
2109
+ <td style="padding:4px 8px">${esc(r.name)}${purityWhy(r)}${r._added ? ` <span style="font-size:9.5px;color:var(--dk-red-fg, #b91c1c);font-weight:600;background:var(--dk-red-bg, #fef2f2);border:1px solid var(--dk-red-line, #fecaca);border-radius:4px;padding:0 4px;vertical-align:middle;white-space:nowrap" title="Added to the as-prepared batch — not part of the linked recipe">+ not in recipe</span>` : ''}</td>
2081
2110
  <td style="padding:4px 8px;text-align:right;font-variant-numeric:tabular-nums;font-weight:600;color:var(--dk-text, #0f172a)">${r.planned != null ? `${cv(r.planned)}${purityTag(r)}${qsTag(r)}` : '<span style="color:var(--dk-dim, #cbd5e1)">—</span>'}</td>
2082
2111
  ${hasActuals ? `<td style="padding:4px 8px;text-align:right;font-variant-numeric:tabular-nums">${
2083
2112
  r.actInUnit != null ? cv(r.actInUnit)
@@ -2615,6 +2644,15 @@ function entityCostValueHtml(o) {
2615
2644
  if (!o.formula) {
2616
2645
  const rec = ((typeof db !== 'undefined' && db && db[o.kind === 'batch' ? 'batches' : 'samples']) || []).find(x => x && x.id === o.id);
2617
2646
  const fid = rec && rec.formulationId;
2647
+ // A sample taken from a material lot has no formula: it costs what the lot costs (replacement-lot sim, 21 Nov).
2648
+ const lot = rec && rec.lotId ? ((db.lots || []).find(l => l && l.id === rec.lotId)) : null;
2649
+ if (lot) {
2650
+ const uc = parseFloat(lot.unitCost), q = parseFloat(o.qty), lc = lot.unitCostCcy || 'USD';
2651
+ const own = (isFinite(uc) && isFinite(q) && (o.unit || '') === (lot.unit || '')) ? q * uc : null;
2652
+ const v = own == null ? null : (lc !== ccy && typeof convertCurrencySync === 'function') ? convertCurrencySync(own, lc, ccy) : own;
2653
+ 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}`;
2654
+ 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}`;
2655
+ }
2618
2656
  const why = !fid ? 'no formula' : (typeof flTrashEntryFor === 'function' && flTrashEntryFor('formulation', fid)) ? 'formula is in Trash' : 'formula deleted';
2619
2657
  return `<span style="color:var(--text-muted)">—</span> <span style="font-size:11px;color:var(--text-muted)">${why}</span>${editBtn}`;
2620
2658
  }
@@ -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) {