formlab-mcp 0.6.97 → 0.6.99
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 +5 -5
- package/attention.js +55 -0
- package/calibration.js +2 -2
- package/package.json +2 -1
- package/server.json +2 -2
- package/tools/analytics.js +6 -1
- package/tools/formulations.js +4 -1
- package/tools/ingredients.js +10 -1
- package/tools/lab.js +3 -0
- package/vendor/equipment-calibration.js +64 -30
package/README.md
CHANGED
|
@@ -28,24 +28,24 @@ Ask Claude (or another MCP client) things like:
|
|
|
28
28
|
|
|
29
29
|
| Tool | Purpose |
|
|
30
30
|
|---|---|
|
|
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 |
|
|
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; `review` (`sent` = waiting for a reviewer, `returned`, `approved`, `none`) |
|
|
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
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`. |
|
|
35
35
|
| `find_similar_formulations` | Find formulas using a given ingredient ≥ threshold % |
|
|
36
36
|
| `compare_formulations` | Pairwise side-by-side composition diff |
|
|
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
|
+
| `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`), `docs_expiring`, `reg_stale`, `trial_sources` (the app's Needs Attention rows) |
|
|
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 `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` |
|
|
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`, `disqualified_source` |
|
|
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
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
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
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
|
-
| `list_samples` | Filtered list of physical specimens |
|
|
46
|
+
| `list_samples` | Filtered list of physical specimens; `overdue` = In Testing with no report in 30+ days (Needs Attention) |
|
|
47
47
|
| `get_sample` | Full record + canonical variant + test reports + blend lineage + its stability pulls (next pull, or pulled at) |
|
|
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) |
|
|
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; `in_doubt` (a reading's instrument failed calibration in its window or was Out of service; each row carries `readingsInDoubt`) and `review` state) |
|
|
49
49
|
| `get_test_result` | Full report: every measurement's value, spec, any per-measurement run **conditions**, and the **resolved instrument** (`instrumentSource`: row / method / run). Complex types carry a `representative` (time-series → final, distribution → D50; a distribution also its `bins` and, when its spec names a statistic, `judged` at it); a ranked grade carries its `scale` and `rank`; a time series adds `aggregated` (per-timestamp mean ± sd) and `pointReplicates` (repeat readings at one `t`). Report-level `seriesReplicates` lists parameters measured 2+ times as separate rows — point vs series replicates are distinct. Each measurement also gives its **effective spec** (`effectiveSpec`, `specSource`: override / template / parameter / none) and `passFail` — panel and Test Method specs apply exactly as in the app, and every pass/fail count across the tools uses the same rule |
|
|
50
50
|
| `get_doe_matrix` | Pivot matrix (CSV by default) — rows × ingredients × parameters. A parameter measured under two or more **run conditions** (storage 25 °C vs 40 °C) is one column per condition (`pH`, `pH · 40 °C`; the bare name is the base arm), never averaged together — same columns, in the same order (grouped by measurement type, the test panel's order within a group), as the app's DOE Matrix |
|
|
51
51
|
| `find_failures` | Parameters ranked by failure **rate** (failing ÷ all readings; replicates in one report count once), `lowN` flag under 5 readings, plus formulations ranked by share of failing reports — same numbers as the app's Test Analytics → Failures |
|
package/attention.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// =====================================================================
|
|
2
|
+
// Needs Attention states for the MCP list filters (0.6.98), each a copy of the app's own rule, so an MCP client
|
|
3
|
+
// finds what the app's Dashboard and its AI assistant find (Jun, 30 Nov: "make sure AI search is consistent").
|
|
4
|
+
// reviewState js/review.js flReviewState none | sent | approved | returned
|
|
5
|
+
// sampleOverdue js/views/dashboard.js stale samples In Testing, no report (or creation) for 30+ days
|
|
6
|
+
// docExpiring js/documents.js docExpiryStatus expired, or expiring within 30 days
|
|
7
|
+
// regStale js/regulatory.js regIsStale checked 12+ months ago (30.4375-day months)
|
|
8
|
+
// trialSources js/inventory-sources.js approved-source entries with status "trial"
|
|
9
|
+
// lotSource js/inventory-sources.js resolveLotSource by sourceId, else supplier / manufacturer name
|
|
10
|
+
// test/mcp-attention-30nov.test.js runs the app's functions beside these on the same records.
|
|
11
|
+
// =====================================================================
|
|
12
|
+
const REVIEW_STATES = new Set(['sent', 'approved', 'returned']);
|
|
13
|
+
export function reviewState(rec) { const s = rec && rec.review && rec.review.state; return REVIEW_STATES.has(s) ? s : 'none'; }
|
|
14
|
+
|
|
15
|
+
const DAY = 86400000;
|
|
16
|
+
export function sampleOverdue(s, tests, nowMs = Date.now()) {
|
|
17
|
+
if (!s || s.status !== 'In Testing') return false;
|
|
18
|
+
const dates = (tests || []).filter(t => t && t.sampleId === s.id).map(t => {
|
|
19
|
+
const d = t.testDate ? Date.parse(t.testDate) : (t.createdAt ? Date.parse(t.createdAt) : 0);
|
|
20
|
+
return Number.isFinite(d) ? d : 0;
|
|
21
|
+
}).filter(Boolean);
|
|
22
|
+
const last = dates.length ? Math.max(...dates) : (s.createdAt ? Date.parse(s.createdAt) : 0);
|
|
23
|
+
if (!last || last > nowMs) return false;
|
|
24
|
+
return Math.round((nowMs - last) / DAY) >= 30;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function docExpiry(doc, now = new Date()) {
|
|
28
|
+
if (!doc || !doc.expiryDate) return 'none';
|
|
29
|
+
const exp = new Date(doc.expiryDate + 'T00:00:00');
|
|
30
|
+
if (isNaN(exp.getTime())) return 'none';
|
|
31
|
+
const today = new Date(now); today.setHours(0, 0, 0, 0);
|
|
32
|
+
const days = Math.round((exp - today) / DAY);
|
|
33
|
+
return days < 0 ? 'expired' : days <= 30 ? 'soon' : 'current';
|
|
34
|
+
}
|
|
35
|
+
export function docsExpiring(ing, now) { return (ing && ing.documents || []).filter(d => { const s = docExpiry(d, now); return s === 'expired' || s === 'soon'; }).length; }
|
|
36
|
+
|
|
37
|
+
export function regStale(ing, nowMs = Date.now()) {
|
|
38
|
+
return (ing && ing.regulatory || []).some(r => {
|
|
39
|
+
if (!r || !r.status || !r.checkedDate) return false;
|
|
40
|
+
const t = Date.parse(r.checkedDate);
|
|
41
|
+
if (!isFinite(t)) return false;
|
|
42
|
+
return Math.max(0, Math.floor(((nowMs - t) / DAY) / 30.4375)) >= 12;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const _srcT = (v) => String(v == null ? '' : v).trim();
|
|
47
|
+
export function ingSources(ing) { return (ing && Array.isArray(ing.sources)) ? ing.sources : []; }
|
|
48
|
+
export function trialSources(ing) { return ingSources(ing).filter(s => s && s.status === 'trial').length; }
|
|
49
|
+
export function lotSource(lot, ing) {
|
|
50
|
+
if (!lot || !ing) return null;
|
|
51
|
+
if (lot.sourceId) { const s = ingSources(ing).find(x => x && x.id === lot.sourceId); if (s) return s; }
|
|
52
|
+
const name = _srcT(lot.supplier).toLowerCase();
|
|
53
|
+
if (!name) return null;
|
|
54
|
+
return ingSources(ing).find(s => _srcT(s.supplier).toLowerCase() === name || _srcT(s.manufacturer).toLowerCase() === name) || null;
|
|
55
|
+
}
|
package/calibration.js
CHANGED
|
@@ -28,7 +28,7 @@ function ctx() {
|
|
|
28
28
|
return _ctx;
|
|
29
29
|
}
|
|
30
30
|
const _today = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
|
|
31
|
-
const _slim = (e) => JSON.stringify({ status: e.status || '', calIntervalMonths: e.calIntervalMonths || null, calibrations: Array.isArray(e.calibrations) ? e.calibrations : [] });
|
|
31
|
+
const _slim = (e) => JSON.stringify({ status: e.status || '', calIntervalMonths: e.calIntervalMonths || null, calibrations: Array.isArray(e.calibrations) ? e.calibrations : [], calReviews: Array.isArray(e.calReviews) ? e.calReviews : [] });
|
|
32
32
|
|
|
33
33
|
// { state, due, last, lastResult, interval, daysToDue, count } — state: ok | soon | overdue | failed | never | none
|
|
34
34
|
export function calibrationStatus(e, today) { return JSON.parse(ctx().__calStatus(_slim(e), today || _today())); }
|
|
@@ -45,7 +45,7 @@ export function readingDoubts(db, resolveIns, today) {
|
|
|
45
45
|
const now = Date.now();
|
|
46
46
|
if (_doubtMemo && _doubtMemo.db === db && now - _doubtMemo.at < 5000) return _doubtMemo.out;
|
|
47
47
|
const equipment = (db.equipment || []).filter(Boolean).map(e => ({ id: e.id, uid: e.uid || '', name: e.name || '', status: e.status || '',
|
|
48
|
-
_trashed: !!e._trashed, calIntervalMonths: e.calIntervalMonths || null, calibrations: Array.isArray(e.calibrations) ? e.calibrations : [] }));
|
|
48
|
+
_trashed: !!e._trashed, calIntervalMonths: e.calIntervalMonths || null, calibrations: Array.isArray(e.calibrations) ? e.calibrations : [], calReviews: Array.isArray(e.calReviews) ? e.calReviews : [] }));
|
|
49
49
|
const tests = (db.testResults || []).filter(t => t && t.id).map(t => ({ id: t.id, testDate: t.testDate || '',
|
|
50
50
|
measurements: (t.measurements || []).map(m => { const r = resolveIns(m, t, db) || {}; return { instrument: r.instrument || '', equipmentId: r.equipmentId || '', ...(m && m.instrumentOos ? { instrumentOos: m.instrumentOos } : {}) }; }) }));
|
|
51
51
|
let out = {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "formlab-mcp",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.99",
|
|
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",
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
"data.js",
|
|
15
15
|
"cloud.js",
|
|
16
16
|
"calibration.js",
|
|
17
|
+
"attention.js",
|
|
17
18
|
"peptide.js",
|
|
18
19
|
"theoretical.js",
|
|
19
20
|
"tools/",
|
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.
|
|
5
|
+
"version": "0.6.99",
|
|
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.
|
|
11
|
+
"version": "0.6.99",
|
|
12
12
|
"runtimeHint": "npx",
|
|
13
13
|
"transport": {
|
|
14
14
|
"type": "stdio"
|
package/tools/analytics.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
import { getStore, resolveById, flattenComposition, localDay, localToday } from '../data.js';
|
|
14
14
|
import { readingDoubts } from '../calibration.js';
|
|
15
|
+
import { reviewState } from '../attention.js';
|
|
15
16
|
|
|
16
17
|
// Which instrument produced a measurement. Mirrors the app's _trMeasInstrument:
|
|
17
18
|
// a measurement's raw `instrument` is usually EMPTY because blank means inherit,
|
|
@@ -155,6 +156,8 @@ const list_test_results = {
|
|
|
155
156
|
since_date: { type: 'string', description: 'ISO date — only reports on/after this date.' },
|
|
156
157
|
until_date: { type: 'string', description: 'ISO date — only reports on/before this date.' },
|
|
157
158
|
lab: { type: 'string', description: 'Filter by lab name (case-insensitive substring).' },
|
|
159
|
+
in_doubt: { type: 'boolean', description: 'true = only reports with a reading in doubt (its instrument failed or was found out of tolerance at a calibration after its last good one, in that window, or was Out of service when the report was saved): the app\'s amber "In doubt". get_test_result gives each reading\'s reason.' },
|
|
160
|
+
review: { type: 'string', enum: ['none', 'sent', 'approved', 'returned'], description: 'Review state (FormLab Team): sent = waiting for a reviewer, returned = sent back with a note, approved, none.' },
|
|
158
161
|
limit: { type: 'number', description: 'Max rows (default 100, max 1000).' },
|
|
159
162
|
},
|
|
160
163
|
},
|
|
@@ -175,6 +178,8 @@ const list_test_results = {
|
|
|
175
178
|
if (args.since_date && (t.testDate || '') < args.since_date) return false;
|
|
176
179
|
if (args.until_date && (t.testDate || '') > args.until_date) return false;
|
|
177
180
|
if (args.lab && !norm(t.lab).includes(norm(args.lab))) return false;
|
|
181
|
+
if (args.review && reviewState(t) !== args.review) return false;
|
|
182
|
+
if (args.in_doubt === true && !readingDoubts(db, _resolveInstrument)[t.id]) return false;
|
|
178
183
|
const hasRange = args.value_min != null || args.value_max != null;
|
|
179
184
|
const hasGrade = !!(args.min_grade || args.max_grade);
|
|
180
185
|
if (args.parameter || hasRange || hasGrade || args.value_equals || args.condition) {
|
|
@@ -211,7 +216,7 @@ const list_test_results = {
|
|
|
211
216
|
return {
|
|
212
217
|
totalMatching: filtered.length,
|
|
213
218
|
returned: Math.min(filtered.length, limit),
|
|
214
|
-
testResults: filtered.slice(0, limit).map(t => { const dz = readingDoubts(getStore().db, _resolveInstrument)[t.id]; const n = dz ? Object.keys(dz).length : 0; return { ..._trimTest(t, indexes.samplesById), ...(n ? { readingsInDoubt: n } : {}) }; }),
|
|
219
|
+
testResults: filtered.slice(0, limit).map(t => { const dz = readingDoubts(getStore().db, _resolveInstrument)[t.id]; const n = dz ? Object.keys(dz).length : 0; return { ..._trimTest(t, indexes.samplesById), review: reviewState(t), ...(n ? { readingsInDoubt: n } : {}) }; }),
|
|
215
220
|
};
|
|
216
221
|
},
|
|
217
222
|
};
|
package/tools/formulations.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// - compare_formulations: pairwise composition diff
|
|
7
7
|
// ============================================================
|
|
8
8
|
|
|
9
|
+
import { reviewState } from '../attention.js';
|
|
9
10
|
import { getStore, resolveById, flattenComposition } from '../data.js';
|
|
10
11
|
import { theoreticalParams, nutritionLabel, fragranceCompliance } from '../theoretical.js';
|
|
11
12
|
|
|
@@ -69,6 +70,7 @@ const list_formulations = {
|
|
|
69
70
|
family: { type: 'string', description: 'Filter by formula family (e.g. "Acrylic Coating", "Skin Serum"). Case-insensitive substring.' },
|
|
70
71
|
tag: { type: 'string', description: 'Filter to formulas containing this tag.' },
|
|
71
72
|
name_contains: { type: 'string', description: 'Case-insensitive substring match on formula name.' },
|
|
73
|
+
review: { type: 'string', enum: ['none', 'sent', 'approved', 'returned'], description: 'Review state (FormLab Team): sent = waiting for a reviewer, returned = sent back to its maker with a note, approved, none = never sent (or changed since). Needs Attention "waiting for review" / "returned".' },
|
|
72
74
|
sort: { type: 'string', enum: ['batches', 'samples', 'test_reports', 'name', 'updated'], description: 'Order before the limit: batches / samples / test_reports = most first; name = A–Z; updated = most recently updated first. Default: database order.' },
|
|
73
75
|
limit: { type: 'number', description: 'Max rows to return (default 50, max 500).' },
|
|
74
76
|
},
|
|
@@ -89,6 +91,7 @@ const list_formulations = {
|
|
|
89
91
|
if (args.family && !norm(f.family).includes(norm(args.family))) return false;
|
|
90
92
|
if (args.tag && !(f.tags || []).some(t => norm(t) === norm(args.tag))) return false;
|
|
91
93
|
if (args.name_contains && !norm(f.name).includes(norm(args.name_contains))) return false;
|
|
94
|
+
if (args.review && reviewState(f) !== args.review) return false;
|
|
92
95
|
return true;
|
|
93
96
|
});
|
|
94
97
|
if (args.sort && Object.hasOwn(_SORTS, args.sort)) {
|
|
@@ -107,7 +110,7 @@ const list_formulations = {
|
|
|
107
110
|
totalMatching: filtered.length,
|
|
108
111
|
returned: Math.min(filtered.length, limit),
|
|
109
112
|
...(args.sort ? { sortedBy: args.sort } : {}),
|
|
110
|
-
formulations: filtered.slice(0, limit).map(_trimFormulation),
|
|
113
|
+
formulations: filtered.slice(0, limit).map(f => ({ ..._trimFormulation(f), review: reviewState(f) })),
|
|
111
114
|
};
|
|
112
115
|
},
|
|
113
116
|
};
|
package/tools/ingredients.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// - get_ingredient: full record incl. supplier, density, stock, cost
|
|
5
5
|
// ============================================================
|
|
6
6
|
|
|
7
|
+
import { docsExpiring, regStale, trialSources, lotSource } from '../attention.js';
|
|
7
8
|
import { getStore, resolveById } from '../data.js';
|
|
8
9
|
import { ingredientSmiles } from '../peptide.js';
|
|
9
10
|
import { reactiveGroups } from '../theoretical.js';
|
|
@@ -134,6 +135,9 @@ const list_ingredients = {
|
|
|
134
135
|
sequence_contains: { type: 'string', description: 'Case-insensitive substring match on peptide / oligo sequence (e.g. "KTTKS" matches Matrixyl).' },
|
|
135
136
|
taxon_contains: { type: 'string', description: 'Case-insensitive substring match on botanical scientific name (e.g. "Centella").' },
|
|
136
137
|
inchikey: { type: 'string', description: 'Exact match on the InChIKey identity hash. The first 14 characters are the connectivity hash; pass either the full 27-char key or just the first 14 to dedup-search across tautomers/salts.' },
|
|
138
|
+
docs_expiring: { type: 'boolean', description: 'true = only ingredients with a document (SDS, CoA, TDS…) expired or expiring within 30 days: the app\'s Needs Attention "documents expiring".' },
|
|
139
|
+
reg_stale: { type: 'boolean', description: 'true = only ingredients with a regulatory status last checked 12+ months ago: Needs Attention "regulatory re-check overdue".' },
|
|
140
|
+
trial_sources: { type: 'boolean', description: 'true = only ingredients with an approved-source entry still on trial: Needs Attention "trial source awaiting qualification".' },
|
|
137
141
|
limit: { type: 'number', description: 'Max rows (default 100, max 1000).' },
|
|
138
142
|
},
|
|
139
143
|
},
|
|
@@ -161,12 +165,15 @@ const list_ingredients = {
|
|
|
161
165
|
if (!have) return false;
|
|
162
166
|
if (want.length === 14 ? !have.startsWith(want) : have !== want) return false;
|
|
163
167
|
}
|
|
168
|
+
if (args.docs_expiring === true && !docsExpiring(i)) return false;
|
|
169
|
+
if (args.reg_stale === true && !regStale(i)) return false;
|
|
170
|
+
if (args.trial_sources === true && !trialSources(i)) return false;
|
|
164
171
|
return true;
|
|
165
172
|
});
|
|
166
173
|
return {
|
|
167
174
|
totalMatching: filtered.length,
|
|
168
175
|
returned: Math.min(filtered.length, limit),
|
|
169
|
-
ingredients: filtered.slice(0, limit).map(_trimIngredient),
|
|
176
|
+
ingredients: filtered.slice(0, limit).map(i => ({ ..._trimIngredient(i), ...(docsExpiring(i) ? { docsExpiring: docsExpiring(i) } : {}), ...(regStale(i) ? { regStale: true } : {}), ...(trialSources(i) ? { trialSources: trialSources(i) } : {}) })),
|
|
170
177
|
};
|
|
171
178
|
},
|
|
172
179
|
};
|
|
@@ -360,6 +367,7 @@ const list_lots = {
|
|
|
360
367
|
expiring_within_days: { type: 'number', description: 'Only lots whose expiryDate is within this many days from now (negative days = already expired are always included).' },
|
|
361
368
|
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).' },
|
|
362
369
|
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".' },
|
|
370
|
+
disqualified_source: { type: 'boolean', description: 'true = only lots whose approved source is disqualified (by the lot\'s source, else its supplier / manufacturer name). With stock left this is the app\'s Needs Attention "lot on hand from a disqualified source".' },
|
|
363
371
|
limit: { type: 'number', description: 'Max rows (default 200, max 1000).' },
|
|
364
372
|
},
|
|
365
373
|
},
|
|
@@ -381,6 +389,7 @@ const list_lots = {
|
|
|
381
389
|
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; }
|
|
382
390
|
if (args.missing_coa === true && !_lotCoaInfo(l, ingById.get(l.ingredientId)).coaMissing) return false;
|
|
383
391
|
if (args.status && String(l.status || 'active').toLowerCase() !== String(args.status).toLowerCase()) return false;
|
|
392
|
+
if (args.disqualified_source === true) { const src = lotSource(l, ingById.get(l.ingredientId)); if (!(src && src.status === 'disqualified')) return false; }
|
|
384
393
|
if (args.expiring_within_days != null) {
|
|
385
394
|
if (!l.expiryDate) return false;
|
|
386
395
|
const days = Math.floor((Date.parse(l.expiryDate) - nowMs) / 86400000);
|
package/tools/lab.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// - get_sample
|
|
7
7
|
// ============================================================
|
|
8
8
|
|
|
9
|
+
import { sampleOverdue } from '../attention.js';
|
|
9
10
|
import { getStore, resolveById } from '../data.js';
|
|
10
11
|
import { theoreticalParams } from '../theoretical.js';
|
|
11
12
|
import { _mcpSamplePulls } from './analytics.js';
|
|
@@ -464,6 +465,7 @@ const list_samples = {
|
|
|
464
465
|
formulation_id: { type: 'string', description: 'Filter to samples of this formulation (id or UID).' },
|
|
465
466
|
status: { type: 'string', description: 'Filter by status (case-insensitive substring).' },
|
|
466
467
|
is_blend_only: { type: 'boolean', description: 'When true, return only samples with sourceBlend lineage.' },
|
|
468
|
+
overdue: { type: 'boolean', description: 'true = only samples In Testing with no test report (or, with none, no creation) in 30+ days: the app\'s Needs Attention "samples overdue for testing".' },
|
|
467
469
|
limit: { type: 'number', description: 'Max rows (default 100, max 1000).' },
|
|
468
470
|
},
|
|
469
471
|
},
|
|
@@ -489,6 +491,7 @@ const list_samples = {
|
|
|
489
491
|
if (formId && s.formulationId !== formId) return false;
|
|
490
492
|
if (args.status && !norm(s.status).includes(norm(args.status))) return false;
|
|
491
493
|
if (args.is_blend_only && !(Array.isArray(s.sourceBlend) && s.sourceBlend.length)) return false;
|
|
494
|
+
if (args.overdue === true && !sampleOverdue(s, db.testResults)) return false;
|
|
492
495
|
return true;
|
|
493
496
|
});
|
|
494
497
|
return {
|
|
@@ -131,31 +131,54 @@ function eqCalSortKey(e) {
|
|
|
131
131
|
}
|
|
132
132
|
|
|
133
133
|
// Readings to doubt after a calibration found the unit out of tolerance (dogfooding 28 Nov: RV-1 failed and nothing
|
|
134
|
-
// said which of its 8 reports came after its last pass).
|
|
135
|
-
//
|
|
136
|
-
//
|
|
137
|
-
//
|
|
138
|
-
//
|
|
139
|
-
//
|
|
140
|
-
function
|
|
134
|
+
// said which of its 8 reports came after its last pass). Every Fail or Adjusted (out of tolerance as found) entry opens
|
|
135
|
+
// a window: reports dated after the last good calibration before it, up to the failure's repair (the first good entry
|
|
136
|
+
// after it), or to today while it still fails; an Adjusted one ends at the adjustment. A window stays open until someone
|
|
137
|
+
// closes its review with a reason (e.calReviews, Jun 30 Nov: "Yes, do that"); later calibrations never close it (it
|
|
138
|
+
// used to close "two entries on", and two passes logged the same day cleared every doubt). Retested readings leave it
|
|
139
|
+
// on their own (the retest replaces them). `tests` = the reports that used this unit.
|
|
140
|
+
function eqCalReviews(e) { return (e && Array.isArray(e.calReviews)) ? e.calReviews.filter(r => r && r.calId) : []; }
|
|
141
|
+
// The review on a bad calibration entry, if one is closed (the latest word on it: closed, or reopened).
|
|
142
|
+
function eqCalReviewOf(e, calId) {
|
|
143
|
+
const rs = eqCalReviews(e).filter(r => r.calId === calId).sort((x, y) => String(x.at || '').localeCompare(String(y.at || '')));
|
|
144
|
+
const last = rs[rs.length - 1];
|
|
145
|
+
return last && !last.reopened ? last : null;
|
|
146
|
+
}
|
|
147
|
+
// Every window, newest first: { calId, kind, at, since, until, fixedAt, review }.
|
|
148
|
+
function eqCalWindows(e, todayIso) {
|
|
141
149
|
const hist = eqCalHistory(e);
|
|
142
150
|
const res = (c) => String((c && c.result) || '').trim().toLowerCase();
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
151
|
+
const good = (c) => ['pass', 'adjusted'].includes(res(c));
|
|
152
|
+
const out = [];
|
|
153
|
+
hist.forEach((bad, i) => {
|
|
154
|
+
const kind = res(bad);
|
|
155
|
+
if (kind !== 'fail' && kind !== 'adjusted') return;
|
|
156
|
+
const before = hist.slice(i + 1).find(good);
|
|
157
|
+
let fixed = null; for (let j = i - 1; j >= 0; j--) { if (good(hist[j])) { fixed = hist[j]; break; } }
|
|
158
|
+
const until = kind === 'adjusted' ? (bad.date || '') : ((fixed && fixed.date) || todayIso || _eqCalToday());
|
|
159
|
+
out.push({ calId: bad.id || '', kind, at: bad.date || '', since: (before && before.date) || '', until, fixedAt: kind === 'fail' && fixed ? (fixed.date || '') : '', review: bad.id ? eqCalReviewOf(e, bad.id) : null });
|
|
160
|
+
});
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
function _eqCalWindowTests(w, tests) {
|
|
149
164
|
const day = (t) => String((t && t.testDate) || '').split('T')[0];
|
|
150
|
-
|
|
165
|
+
return (tests || []).filter(t => { const d = day(t); return d && (!w.since || d > w.since) && (!w.until || d <= w.until); })
|
|
151
166
|
.sort((a, b) => day(a).localeCompare(day(b)));
|
|
167
|
+
}
|
|
168
|
+
// The latest window still open (its review not closed), with its reports and batches; null when none is open.
|
|
169
|
+
// { calId, kind, at, since, until, fixedAt, tests, batches, open (how many windows are open) }
|
|
170
|
+
function eqCalSuspect(e, tests, todayIso) {
|
|
171
|
+
const open = eqCalWindows(e, todayIso).filter(w => !w.review);
|
|
172
|
+
if (!open.length) return null;
|
|
173
|
+
const w = open[0];
|
|
174
|
+
const hit = _eqCalWindowTests(w, tests);
|
|
152
175
|
const batches = [];
|
|
153
176
|
hit.forEach(t => {
|
|
154
177
|
const sm = (typeof db !== 'undefined' && db.samples || []).find(x => x && x.id === t.sampleId);
|
|
155
178
|
const b = sm && sm.batchId ? (db.batches || []).find(x => x && x.id === sm.batchId && !x._trashed) : null;
|
|
156
179
|
if (b && !batches.includes(b)) batches.push(b);
|
|
157
180
|
});
|
|
158
|
-
return { kind:
|
|
181
|
+
return { calId: w.calId, kind: w.kind, at: w.at, since: w.since, until: w.until, fixedAt: w.fixedAt, tests: hit, batches, open: open.length };
|
|
159
182
|
}
|
|
160
183
|
|
|
161
184
|
// ---- Readings in doubt (Jun, 30 Nov: "Flag doubtful readings"; shared with the MCP server) ----
|
|
@@ -165,24 +188,26 @@ function eqCalSuspect(e, tests, todayIso) {
|
|
|
165
188
|
// eqCalDoubtIndex: Map testId → [{ eqId, lname, why }]; eqCalReadingDoubt: { why } or null.
|
|
166
189
|
function eqCalDoubtIndex(equipment, tests, insOf, todayIso) {
|
|
167
190
|
const map = new Map();
|
|
168
|
-
const res = (c) => String((c && c.result) || '').trim().toLowerCase();
|
|
169
191
|
(equipment || []).forEach(e => {
|
|
170
192
|
if (!e || e._trashed) return;
|
|
171
|
-
|
|
193
|
+
const open = eqCalWindows(e, todayIso).filter(w => !w.review);
|
|
194
|
+
if (!open.length) return; // nothing to doubt
|
|
172
195
|
const lname = String(e.name || '').trim().toLowerCase();
|
|
173
196
|
const match = (m, t) => { const r = (insOf && insOf(m, t)) || {}; return r.equipmentId ? r.equipmentId === e.id : (!!lname && String(r.name || '').trim().toLowerCase() === lname); };
|
|
174
197
|
const used = (tests || []).filter(t => t && (t.measurements || []).some(m => match(m, t)));
|
|
175
|
-
const sus = eqCalSuspect(e, used, todayIso);
|
|
176
|
-
if (!sus || !sus.tests.length) return;
|
|
177
198
|
const name = e.name || e.uid || 'its instrument';
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
199
|
+
open.forEach(w => {
|
|
200
|
+
const hit = _eqCalWindowTests(w, used);
|
|
201
|
+
if (!hit.length) return;
|
|
202
|
+
const from = w.since ? `after its last good calibration (${w.since})` : 'before any good calibration on record';
|
|
203
|
+
const why = w.kind === 'adjusted' ? `Taken on ${name} ${from}; it was found out of tolerance on ${w.at}.`
|
|
204
|
+
: w.fixedAt ? `Taken on ${name} ${from} and before the repair passed on ${w.fixedAt}; it failed calibration on ${w.at}.`
|
|
205
|
+
: `Taken on ${name} ${from}; it failed calibration on ${w.at} and has not passed since.`;
|
|
206
|
+
// short: the same in a few words, for compact uses (the AI context).
|
|
207
|
+
const short = `${name} ${w.kind === 'adjusted' ? 'out of tolerance' : 'failed calibration'} ${w.at}`;
|
|
208
|
+
const d = { eqId: e.id, lname, why, short };
|
|
209
|
+
hit.forEach(t => { const l = map.get(t.id) || []; if (!l.some(x => x.eqId === d.eqId)) { l.push(d); map.set(t.id, l); } });
|
|
210
|
+
});
|
|
186
211
|
});
|
|
187
212
|
return map;
|
|
188
213
|
}
|
|
@@ -244,8 +269,14 @@ function eqCalCardHtml(e) {
|
|
|
244
269
|
// How many already are, once some are (dogfooding 30 Nov: after the hold the link just went away).
|
|
245
270
|
const onHold = sus.batches.filter(b => b.fgHold && b.fgHold.at && !b.fgHold.releasedAt).length;
|
|
246
271
|
const heldTxt = onHold ? ` · <span style="white-space:nowrap">${onHold} on hold</span>` : '';
|
|
247
|
-
return (open && typeof flEqHoldSuspectUI === 'function' ? ` · <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline;white-space:nowrap" onclick="flEqHoldSuspectUI('${_eqCalJs(e.id)}')">Put ${open} batch${open === 1 ? '' : 'es'} on hold</a>` : '') + heldTxt; })()}
|
|
272
|
+
return (open && typeof flEqHoldSuspectUI === 'function' ? ` · <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline;white-space:nowrap" onclick="flEqHoldSuspectUI('${_eqCalJs(e.id)}')">Put ${open} batch${open === 1 ? '' : 'es'} on hold</a>` : '') + heldTxt; })()}${
|
|
273
|
+
// Closing the review is a decision with a reason (Jun, 30 Nov): later calibrations no longer close it.
|
|
274
|
+
typeof flEqCloseReviewUI === 'function' && sus.calId ? ` · <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline;white-space:nowrap" onclick="flEqCloseReviewUI('${_eqCalJs(e.id)}','${_eqCalJs(sus.calId)}')">Close the review</a>` : ''}${
|
|
275
|
+
sus.open > 1 ? `<div style="margin-top:4px">${sus.open - 1} earlier ${sus.open - 1 === 1 ? 'failure is' : 'failures are'} still open too.</div>` : ''}</div>`;
|
|
248
276
|
})() : '';
|
|
277
|
+
// The latest closed review, when nothing is open: who closed it, why, and the way back.
|
|
278
|
+
const lastClosed = !sus ? eqCalWindows(e).find(w => w.review) : null;
|
|
279
|
+
const closedHtml = lastClosed ? `<div class="eq-cal-reviewed" style="margin-top:10px;font-size:12.5px;color:var(--text-muted)">Review of the ${esc(lastClosed.at)} ${lastClosed.kind === 'adjusted' ? 'out-of-tolerance finding' : 'failure'} closed${lastClosed.review.by ? ' by ' + esc(lastClosed.review.by) : ''}${lastClosed.review.at && typeof flLocalDay === 'function' ? ' on ' + esc(flLocalDay(lastClosed.review.at)) : ''}: ${esc(lastClosed.review.reason || '')}${typeof flEqReopenReviewUI === 'function' ? ` · <a style="cursor:pointer;color:var(--primary);white-space:nowrap" onclick="flEqReopenReviewUI('${_eqCalJs(e.id)}','${_eqCalJs(lastClosed.calId)}')">Reopen</a>` : ''}</div>` : '';
|
|
249
280
|
// Dates never wrap ("2026-11-/30" in a narrow window, 30 Nov Definition tab check).
|
|
250
281
|
const rows = hist.map(c => `<tr>
|
|
251
282
|
<td style="font-variant-numeric:tabular-nums;white-space:nowrap">${esc(c.date || '—')}</td>
|
|
@@ -262,7 +293,7 @@ function eqCalCardHtml(e) {
|
|
|
262
293
|
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>`;
|
|
263
294
|
return `<div class="card" id="eq-cal-card" style="margin-top:16px">
|
|
264
295
|
<div class="card-header" style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap"><h2>Calibration</h2>${editBtns}</div>
|
|
265
|
-
<div class="card-body">${summary}${susHtml}${table}${freeNote}</div></div>`;
|
|
296
|
+
<div class="card-body">${summary}${susHtml}${closedHtml}${table}${freeNote}</div></div>`;
|
|
266
297
|
}
|
|
267
298
|
|
|
268
299
|
// ---- Interval ----
|
|
@@ -358,7 +389,10 @@ function openEqCalLogModal(eqId, calId) {
|
|
|
358
389
|
// calibrator may set In service / Out of service (0186); Retired is left alone.
|
|
359
390
|
const outNow = !c && rec.result === 'fail' && (cur.status || 'In service') === 'In service';
|
|
360
391
|
if (outNow) patch.status = 'Out of service';
|
|
361
|
-
|
|
392
|
+
// The trail says why the status moved (30 Nov: an auditor saw "In service → Out of service" with no reason).
|
|
393
|
+
const _why = outNow ? `In service → Out of service: failed calibration on ${rec.date}` : '';
|
|
394
|
+
if (_why) { try { if (window.__pro && typeof window.__pro.setReason === 'function') window.__pro.setReason('equipment', eqId, _why); } catch (_) {} }
|
|
395
|
+
updateEquipment(eqId, patch, _why ? { auditNote: _why } : undefined);
|
|
362
396
|
if (typeof renderEquipmentDetail === 'function' && typeof currentView !== 'undefined' && currentView === 'equipment-detail') renderEquipmentDetail(eqId);
|
|
363
397
|
toast(c ? 'Calibration updated.' : (rec.result === 'fail' ? (outNow ? 'Calibration logged as failed. The instrument is now Out of service until it passes.' : 'Calibration logged as failed. Keep the instrument out of use until it passes.')
|
|
364
398
|
: (cur.status === 'Out of service' ? 'Calibration logged. The instrument is still Out of service.' : 'Calibration logged.')));
|