formlab-mcp 0.6.80 → 0.6.82
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 +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/tools/analytics.js +105 -9
- package/vendor/theoretical-params.js +83 -1
package/README.md
CHANGED
|
@@ -47,7 +47,7 @@ Ask Claude (or another MCP client) things like:
|
|
|
47
47
|
| `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 |
|
|
48
48
|
| `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 |
|
|
49
49
|
| `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 |
|
|
50
|
-
| `get_coverage_matrix` | TEST coverage by formulation, batch or sample (`grain`) × parameter. Each cell is the **latest** reading by test date (same-day reports averaged, any fail → fail) with its date and how many reports measured it; one column per **run condition** when a parameter was measured under two or more — same rollup as the app's Test Analytics → Coverage. A ranked scale shows its median grade (with its `rank`) when several readings share the date, a text result its most frequent value, a distribution with no D50 its bins; columns in the app's order (type groups, the test panel's order) |
|
|
50
|
+
| `get_coverage_matrix` | TEST coverage by formulation, batch or sample (`grain`) × parameter. Each cell is the **latest** reading by test date (same-day reports averaged, any fail → fail) with its date and how many reports measured it; one column per **run condition** when a parameter was measured under two or more — same rollup as the app's Test Analytics → Coverage. A ranked scale shows its median grade (with its `rank`) when several readings share the date, a text result its most frequent value, a distribution with no D50 its bins; columns in the app's order (type groups, the test panel's order). Per-row and per-column tested counts; the matrix's controls as options: `column_order` / `columns`, `row_order` or `sort_by` + `sort_dir` (untested last), `only_tested_for`, and a `totals` row (count, pass rate, mean, median, min, max) |
|
|
51
51
|
| `compare_test_results` | **Test results** side by side across 2+ formulas, batches, samples or reports — the app's Compare Results table. Parameters grouped by measurement type (Numbers, Curves, Distributions, Ranked scales, Text results) and, within a group, in the test panel's order (`order: method`, default) or `az`. One cell per item × parameter: `aggregation` `latest` (default; one value per test date, replicates averaged ± sd), `mean` (± sd between dates), `median` (min–max) or `trend` (change from the first date). Curves compare at their final point, distributions at D50; ranked scales and text show the latest reading (with its rank); a parameter measured under 2+ run conditions is split into `arms`, never averaged. `differs` flags a >5% spread across items, as the app highlights |
|
|
52
52
|
| `compare_batches` | Reproducibility of 2+ runs (ideally of one formula): each run's **yield %**, actual produced mass, cost/kg; per-ingredient **drift** across the runs vs the formula's proposed wt-%; and the biggest **outlier** run. `basis`: `wt_percent` (default) or `amount` |
|
|
53
53
|
| `get_batch_pivot` | Production analytics — aggregate batches by `group_by` (formula / status / month / prepared_by / project) × `metric` (count, avg_yield_pct, total_produced_kg, avg_cost_per_batch, total_samples, total_tests), with share + total for additive metrics. Optional `batch_uids` scope + `status` filter |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "formlab-mcp",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.82",
|
|
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.
|
|
5
|
+
"version": "0.6.82",
|
|
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.82",
|
|
12
12
|
"runtimeHint": "npx",
|
|
13
13
|
"transport": {
|
|
14
14
|
"type": "stdio"
|
package/tools/analytics.js
CHANGED
|
@@ -903,7 +903,7 @@ function _evalPassFail(m, templateId, db) {
|
|
|
903
903
|
const get_coverage_matrix = {
|
|
904
904
|
definition: {
|
|
905
905
|
name: 'get_coverage_matrix',
|
|
906
|
-
description: 'Coverage matrix matching the app\'s Test Analytics → Coverage: rows = sample, batch or formulation (grain), columns = parameters — one column per RUN CONDITION when a parameter was measured under two or more (e.g. "pH" and "pH · 40 °C"; the bare name is the base arm), never averaged together. Each cell is the LATEST reading by test date; readings from several reports on that same date are averaged and fail if any of them fails. Each cell also gives latestDate, reportsAveraged and nReports (how many reports measured it). A ranked scale shows its median grade when several readings share the date (with its rank on the scale), a text result its most frequent value, a distribution with no D50 its bins. Columns come in the same order as the app: grouped by measurement type, the test panel order within a group. Empty = never tested. Use for "what\'s untested", "what\'s the current value" and "what\'s been measured many times".',
|
|
906
|
+
description: 'Coverage matrix matching the app\'s Test Analytics → Coverage: rows = sample, batch or formulation (grain), columns = parameters — one column per RUN CONDITION when a parameter was measured under two or more (e.g. "pH" and "pH · 40 °C"; the bare name is the base arm), never averaged together. Each cell is the LATEST reading by test date; readings from several reports on that same date are averaged and fail if any of them fails. Each cell also gives latestDate, reportsAveraged and nReports (how many reports measured it). A ranked scale shows its median grade when several readings share the date (with its rank on the scale), a text result its most frequent value, a distribution with no D50 its bins. Columns come in the same order as the app: grouped by measurement type, the test panel order within a group. Empty = never tested. Each row also gives how many of the shown parameters it was tested for, and each column how many rows tested it. The app\'s matrix controls are options here, so you can match what the user sees: column_order / columns (column order), row_order or sort_by + sort_dir (row order; empty cells always last), only_tested_for (rows tested for one parameter) and totals (a total row: count, pass rate, mean, median, min or max). Use for "what\'s untested", "what\'s the current value" and "what\'s been measured many times".',
|
|
907
907
|
inputSchema: {
|
|
908
908
|
type: 'object',
|
|
909
909
|
properties: {
|
|
@@ -911,6 +911,13 @@ const get_coverage_matrix = {
|
|
|
911
911
|
parameter_filter: { type: 'string', description: 'Case-insensitive substring; restrict parameter columns.' },
|
|
912
912
|
grain: { type: 'string', enum: ['formulation', 'batch', 'sample'], description: 'Row level. Default formulation.' },
|
|
913
913
|
format: { type: 'string', enum: ['csv', 'json'], description: 'Output format. Default csv.' },
|
|
914
|
+
column_order: { type: 'string', enum: ['default', 'az', 'tested'], description: 'Column order, as the app\'s Columns menu: default (type groups, test panel order), az, or tested (most-tested first). Default default.' },
|
|
915
|
+
columns: { type: 'array', items: { type: 'string' }, description: 'A dragged order: these parameters first, in this order, the rest after in the default order. Overrides column_order.' },
|
|
916
|
+
row_order: { type: 'string', enum: ['az', 'tested'], description: 'Row order when sort_by is not given: az (numbers in labels in order, S-2 before S-10) or tested (most-tested first). Default az.' },
|
|
917
|
+
sort_by: { type: 'string', description: 'Sort rows by one column, as clicking its header: a parameter name, "label" or "tested". Numbers sort as numbers, a ranked scale by its rank, untested rows last either way.' },
|
|
918
|
+
sort_dir: { type: 'string', enum: ['asc', 'desc'], description: 'Direction for sort_by. Default asc.' },
|
|
919
|
+
only_tested_for: { type: 'string', description: 'Keep only the rows tested for this parameter, and only the columns those rows were tested for.' },
|
|
920
|
+
totals: { type: 'string', enum: ['count', 'pass', 'mean', 'median', 'min', 'max'], description: 'Add a total row: count of tested rows, pass rate (of rows with a verdict), or mean / median / min / max of the numbers (ranked scales and text are left out). No sum, as in the app.' },
|
|
914
921
|
},
|
|
915
922
|
},
|
|
916
923
|
},
|
|
@@ -945,13 +952,19 @@ const get_coverage_matrix = {
|
|
|
945
952
|
[...paramSet].filter(p => armOf.get(p) === b).sort((x, y) => x.localeCompare(y)).forEach(p => paramCols.push(p));
|
|
946
953
|
});
|
|
947
954
|
[...paramSet].forEach(p => { if (!paramCols.includes(p)) paramCols.push(p); });
|
|
948
|
-
const
|
|
955
|
+
const view = _mcpCovView([...rows.values()], paramCols, args);
|
|
956
|
+
const sorted = view.rows, shownCols = view.params;
|
|
949
957
|
const grainLabel = grain === 'formulation' ? 'Formulation' : grain === 'batch' ? 'Batch' : 'Sample';
|
|
958
|
+
const testedOf = (r) => shownCols.reduce((k, p) => k + (r.cells.has(p) ? 1 : 0), 0);
|
|
959
|
+
const foot = view.totals ? Object.fromEntries(shownCols.map(p => [p, _mcpCovFootVal(view.totals, sorted.map(r => r.cells.get(p)).filter(Boolean))])) : null;
|
|
950
960
|
if (fmt === 'json') {
|
|
951
961
|
return {
|
|
952
|
-
grain, rowCount: sorted.length, parameterCount:
|
|
962
|
+
grain, rowCount: sorted.length, parameterCount: shownCols.length, parameters: shownCols,
|
|
953
963
|
rule: 'cell = latest reading by test date; same-date reports averaged (any fail → fail); one column per run condition, never averaged across',
|
|
954
|
-
|
|
964
|
+
order: view.order, ...(view.notes.length ? { notes: view.notes } : {}),
|
|
965
|
+
columnCounts: Object.fromEntries(shownCols.map(p => [p, view.counts.get(p)])),
|
|
966
|
+
...(foot ? { totals: { kind: view.totals, label: _MCP_COV_FOOT[view.totals], values: foot } } : {}),
|
|
967
|
+
rows: sorted.map(r => ({ [grain]: r.label, id: r.uid, tested: testedOf(r), cells: Object.fromEntries(shownCols.filter(p => r.cells.has(p)).map(p => [p, r.cells.get(p)])) })),
|
|
955
968
|
};
|
|
956
969
|
}
|
|
957
970
|
const esc = (v) => /[",\n\r]/.test(String(v ?? '')) ? '"' + String(v).replace(/"/g, '""') + '"' : String(v ?? '');
|
|
@@ -963,12 +976,90 @@ const get_coverage_matrix = {
|
|
|
963
976
|
bits.push(`${c.nReports} report${c.nReports === 1 ? '' : 's'}`);
|
|
964
977
|
return `${v}${c.unit ? ' ' + c.unit : ''}${c.pf === 'fail' ? ' FAIL' : c.pf === 'pass' ? ' pass' : ''} (${bits.join(', ')})`;
|
|
965
978
|
};
|
|
966
|
-
const lines = [[grainLabel, ...
|
|
967
|
-
|
|
968
|
-
|
|
979
|
+
const lines = [[grainLabel, 'Tested', ...shownCols].map(esc).join(',')];
|
|
980
|
+
lines.push(['(rows tested)', '', ...shownCols.map(p => view.counts.get(p))].map(esc).join(','));
|
|
981
|
+
sorted.forEach(r => lines.push([r.label, `${testedOf(r)}/${shownCols.length}`, ...shownCols.map(p => fmtCell(r.cells.get(p)))].map(esc).join(',')));
|
|
982
|
+
if (foot) lines.push([_MCP_COV_FOOT[view.totals], '', ...shownCols.map(p => foot[p] == null ? '' : foot[p])].map(esc).join(','));
|
|
983
|
+
return `# Coverage Matrix · ${sorted.length} ${grain === 'batch' ? 'batches' : grain + 's'} × ${shownCols.length} parameters · cell = latest reading (same-day reports averaged) · ${view.order}\n`
|
|
984
|
+
+ view.notes.map(n => `# ${n}\n`).join('') + lines.join('\n');
|
|
969
985
|
},
|
|
970
986
|
};
|
|
971
987
|
|
|
988
|
+
// The Coverage Matrix's controls (app 58y–59f: _taCovShown, _taCovOrderCols, _taCovOrderRows, _taCovFootVal), so an
|
|
989
|
+
// agent can read the matrix in the order and with the total the user has on screen. The app keeps these as device
|
|
990
|
+
// prefs, so they come in as arguments. Held to the app's by test/mcp-coverage-order.test.js.
|
|
991
|
+
const _MCP_COV_FOOT = { count: 'Count', pass: 'Pass rate', mean: 'Mean', median: 'Median', min: 'Min', max: 'Max' };
|
|
992
|
+
const _mcpCovOrdinal = new WeakSet(); // cells of a ranked scale: sorted by rank, left out of mean/median/min/max
|
|
993
|
+
const _mcpCovByLabel = (a, b) => String(a.label || '').localeCompare(String(b.label || ''), undefined, { numeric: true, sensitivity: 'base' });
|
|
994
|
+
function _mcpCovView(rowList, allParams, args) {
|
|
995
|
+
const notes = [];
|
|
996
|
+
const own = (o, k) => typeof k === 'string' && Object.prototype.hasOwnProperty.call(o, k);
|
|
997
|
+
const findParam = (name) => {
|
|
998
|
+
if (typeof name !== 'string' || !name.trim()) return '';
|
|
999
|
+
const t = name.trim();
|
|
1000
|
+
return allParams.find(p => p === t) || allParams.find(p => p.toLowerCase() === t.toLowerCase()) || '';
|
|
1001
|
+
};
|
|
1002
|
+
let only = '';
|
|
1003
|
+
if (args.only_tested_for != null && args.only_tested_for !== '') {
|
|
1004
|
+
only = findParam(args.only_tested_for);
|
|
1005
|
+
if (!only) notes.push(`only_tested_for "${args.only_tested_for}" is not a column here; all rows kept`);
|
|
1006
|
+
}
|
|
1007
|
+
const kept = rowList.filter(r => !only || r.cells.has(only));
|
|
1008
|
+
const counts = new Map(allParams.map(p => [p, 0]));
|
|
1009
|
+
kept.forEach(r => allParams.forEach(p => { if (r.cells.has(p)) counts.set(p, counts.get(p) + 1); }));
|
|
1010
|
+
let cols = allParams.slice(), colWord = 'columns: default order';
|
|
1011
|
+
if (Array.isArray(args.columns) && args.columns.length) {
|
|
1012
|
+
const first = []; args.columns.forEach(c => { const p = findParam(c); if (p && !first.includes(p)) first.push(p); });
|
|
1013
|
+
cols = first.concat(allParams.filter(p => !first.includes(p)));
|
|
1014
|
+
colWord = 'columns: your order, the rest after';
|
|
1015
|
+
} else if (args.column_order === 'az') { cols.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })); colWord = 'columns: A–Z'; }
|
|
1016
|
+
else if (args.column_order === 'tested') { cols.sort((a, b) => counts.get(b) - counts.get(a)); colWord = 'columns: most tested first'; }
|
|
1017
|
+
const params = only ? cols.filter(p => counts.get(p) > 0) : cols;
|
|
1018
|
+
const tested = new Map(kept.map(r => [r, params.reduce((k, p) => k + (r.cells.has(p) ? 1 : 0), 0)]));
|
|
1019
|
+
const list = kept.slice();
|
|
1020
|
+
let rowWord;
|
|
1021
|
+
const key = args.sort_by == null || args.sort_by === '' ? '' : String(args.sort_by).trim();
|
|
1022
|
+
const sortKey = !key ? '' : /^(label|name|__label)$/i.test(key) ? '__label' : /^(tested|__tested)$/i.test(key) ? '__tested' : findParam(key);
|
|
1023
|
+
if (key && !sortKey) notes.push(`sort_by "${key}" is not a column here; rows in ${args.row_order === 'tested' ? 'most-tested' : 'A–Z'} order`);
|
|
1024
|
+
if (sortKey && (sortKey === '__label' || sortKey === '__tested' || params.includes(sortKey))) {
|
|
1025
|
+
const sign = args.sort_dir === 'desc' ? -1 : 1;
|
|
1026
|
+
rowWord = `rows: by ${sortKey === '__label' ? 'label' : sortKey === '__tested' ? 'tested count' : sortKey}, ${sign < 0 ? 'descending' : 'ascending'}${sortKey.startsWith('__') ? '' : ', untested last'}`;
|
|
1027
|
+
if (sortKey === '__label') list.sort((a, b) => sign * _mcpCovByLabel(a, b));
|
|
1028
|
+
else if (sortKey === '__tested') list.sort((a, b) => sign * (tested.get(a) - tested.get(b)) || _mcpCovByLabel(a, b));
|
|
1029
|
+
else {
|
|
1030
|
+
const val = (c) => !c ? null : (c.rank != null ? c.rank : c.value);
|
|
1031
|
+
const vals = new Map(list.map(r => [r, val(r.cells.get(sortKey))]));
|
|
1032
|
+
const empty = v => v == null || v === '' || v === '—';
|
|
1033
|
+
const num = v => (typeof v === 'number' ? v : (/^\s*[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?\s*$/i.test(String(v)) ? parseFloat(v) : NaN));
|
|
1034
|
+
list.sort((a, b) => {
|
|
1035
|
+
const va = vals.get(a), vb = vals.get(b), ea = empty(va), eb = empty(vb);
|
|
1036
|
+
if (ea || eb) return ea && eb ? _mcpCovByLabel(a, b) : ea ? 1 : -1;
|
|
1037
|
+
const na = num(va), nb = num(vb), ia = isFinite(na), ib = isFinite(nb);
|
|
1038
|
+
const c = ia && ib ? na - nb : ia ? -1 : ib ? 1 : String(va).localeCompare(String(vb), undefined, { numeric: true, sensitivity: 'base' });
|
|
1039
|
+
return sign * c || _mcpCovByLabel(a, b);
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
} else if (args.row_order === 'tested') { list.sort((a, b) => tested.get(b) - tested.get(a) || _mcpCovByLabel(a, b)); rowWord = 'rows: most tested first'; }
|
|
1043
|
+
else { list.sort(_mcpCovByLabel); rowWord = 'rows: A–Z'; }
|
|
1044
|
+
const totals = own(_MCP_COV_FOOT, args.totals) ? args.totals : '';
|
|
1045
|
+
return { rows: list, params, counts, only, totals, notes,
|
|
1046
|
+
order: [colWord, rowWord, only ? `only rows tested for ${only}` : ''].filter(Boolean).join('; ') };
|
|
1047
|
+
}
|
|
1048
|
+
// One column's total, unrounded past 12 digits; null = nothing to total (the app shows —).
|
|
1049
|
+
function _mcpCovFootVal(kind, cells) {
|
|
1050
|
+
if (kind === 'count') return cells.length;
|
|
1051
|
+
if (kind === 'pass') {
|
|
1052
|
+
const v = cells.filter(c => c.pf === 'pass' || c.pf === 'fail');
|
|
1053
|
+
return v.length ? Math.round(1000 * v.filter(c => c.pf !== 'fail').length / v.length) / 10 + '%' : null;
|
|
1054
|
+
}
|
|
1055
|
+
const xs = cells.filter(c => !_mcpCovOrdinal.has(c) && typeof c.value === 'number' && isFinite(c.value)).map(c => c.value).sort((a, b) => a - b);
|
|
1056
|
+
if (!xs.length) return null;
|
|
1057
|
+
const val = kind === 'mean' ? xs.reduce((a, b) => a + b, 0) / xs.length
|
|
1058
|
+
: kind === 'median' ? (xs.length % 2 ? xs[(xs.length - 1) / 2] : (xs[xs.length / 2 - 1] + xs[xs.length / 2]) / 2)
|
|
1059
|
+
: kind === 'min' ? xs[0] : xs[xs.length - 1];
|
|
1060
|
+
return +val.toPrecision(12);
|
|
1061
|
+
}
|
|
1062
|
+
|
|
972
1063
|
// Latest-date rollup (mirrors the app's _taCoverageRows).
|
|
973
1064
|
function _mcpCoverageRows(flat, grain, indexes) {
|
|
974
1065
|
// One column per run condition first (see _mcpArmNames), so "latest" never
|
|
@@ -1007,12 +1098,14 @@ function _mcpCoverageRows(flat, grain, indexes) {
|
|
|
1007
1098
|
// keeps every real value.
|
|
1008
1099
|
const tidy = (v) => (typeof v === 'number' && isFinite(v)) ? Number(v.toPrecision(12)) : v;
|
|
1009
1100
|
const pick = list.length === 1 ? list[0] : _mcpGraded(list[0]) ? _mcpGradedPick(list) : null;
|
|
1010
|
-
|
|
1101
|
+
const cell = {
|
|
1011
1102
|
value: tidy(pick ? _mcpCellValue(pick) : (mean != null ? mean : _mcpCellValue(list[0]))),
|
|
1012
1103
|
...(pick && pick.type === 'ordinal' && pick.rank != null ? { rank: pick.rank } : {}),
|
|
1013
1104
|
unit: list[0].unit, pf: (pf === 'pass' || pf === 'fail') ? pf : null,
|
|
1014
1105
|
latestDate: date || null, reportsAveraged: list.length, nReports: row.reports.get(param).size,
|
|
1015
|
-
}
|
|
1106
|
+
};
|
|
1107
|
+
if (list[0].type === 'ordinal') _mcpCovOrdinal.add(cell);
|
|
1108
|
+
row.cells.set(param, cell);
|
|
1016
1109
|
}
|
|
1017
1110
|
delete row.latest; delete row.reports;
|
|
1018
1111
|
}
|
|
@@ -1376,6 +1469,9 @@ const _PULLS_LONG = [1, 2, 3, 6, 9, 12, 18, 24, 36];
|
|
|
1376
1469
|
// whole months. key = days, for sorting.
|
|
1377
1470
|
function _tpBucket(days, weekDays = 21) {
|
|
1378
1471
|
if (days <= 3) return { key: 0, label: 'T₀' };
|
|
1472
|
+
// A week key already made (20 days → 21, "3 wk") must label the same when bucketed again (skipped time points,
|
|
1473
|
+
// the column headers): it read "1 mo" beside the real 1 mo column, so the header said "1 mo" twice (12 Nov).
|
|
1474
|
+
if (days % 7 === 0 && days <= weekDays) return { key: days, label: `${days / 7} wk` };
|
|
1379
1475
|
if (days < weekDays) { const w = Math.max(1, Math.round(days / 7)); return { key: w * 7, label: `${w} wk` }; }
|
|
1380
1476
|
const m = Math.max(1, Math.round(days / 30.4375));
|
|
1381
1477
|
return { key: Math.round(m * 30.4375), label: `${m} mo` };
|
|
@@ -694,8 +694,9 @@ function _tpHarmonizeUnits(rows) {
|
|
|
694
694
|
// with an amount has a number for it, in one unit: a premix with a solvent missing its solids is still "not
|
|
695
695
|
// counted", as before. Not rolled: density (by volume), Tg, HLB, purity, cost, text fields. Nested premixes roll up
|
|
696
696
|
// through _tpBuildRows; a cycle rolls up nothing.
|
|
697
|
-
const _TP_MASS_UNIT = /^(%|wt\s*%|%\s*w\/w|w\/w\s*%?|g\s*\/\s*100\s*g|mg\s*\/\s*100\s*g|g\s*\/\s*kg|mg\s*\/\s*kg|ppm|ppb|mg\s*koh\s*\/\s*g|meq\s*\/\s*g|mmol\s*\/\s*g)$/i;
|
|
697
|
+
const _TP_MASS_UNIT = /^(%|wt\s*%|%\s*w\/w|w\/w\s*%?|g\s*\/\s*100\s*g|mg\s*\/\s*100\s*g|[µu]g\s*\/\s*100\s*g|g\s*\/\s*kg|mg\s*\/\s*kg|ppm|ppb|mg\s*koh\s*\/\s*g|meq\s*\/\s*g|mmol\s*\/\s*g)$/i;
|
|
698
698
|
const _TP_MASS_NAMES = new Set(['solids', 'nv', 'nv %', 'nv%', 'non-volatiles', 'nonvolatiles', 'protein', 'fat', 'carb', 'carbs', 'carbohydrate', 'sugar', 'sugars', 'sodium', 'salt', 'fiber', 'fibre', 'ash', 'moisture',
|
|
699
|
+
'sat_fat', 'trans_fat', 'added_sugar', 'cholesterol', 'calcium', 'iron', 'potassium', 'vit_d', 'atwater',
|
|
699
700
|
'volume', 'pigmentvolume', 'dryvolume', 'volatileorganic', 'voc %']); // per gram, so they add by mass (PVC, VOC through a premix)
|
|
700
701
|
const _TP_NOT_ROLLED = new Set(['density', 'mw', 'cost', 'purity', 'stock', 'reorder', 'tg', 'hlb', 'taxonid']);
|
|
701
702
|
const _tpSubStack = new Set();
|
|
@@ -806,6 +807,12 @@ function _tpIngredientView(ing) {
|
|
|
806
807
|
// a solvent (function Solvent; water is not a VOC): all of it volatile, none dry
|
|
807
808
|
// anything else: dry by its solids (ing.solids or 'NV %'), volatile organic only by a 'VOC %' field
|
|
808
809
|
Object.assign(out, _tpPerGramFields(ing, out), Object.fromEntries(Object.entries(out).filter(([k]) => _TP_PER_GRAM.has(k))));
|
|
810
|
+
// Food factors (61i, food labels phase 2): ing.atwater is this ingredient's energy in kcal/100 g by ITS OWN calorie
|
|
811
|
+
// factors (kept from Look up in USDA as ing.fdc.factors), the general 4 / 9 / 4 where it has none; empty unless
|
|
812
|
+
// protein, fat and carb are all filled. ing.nFactor is its nitrogen-to-protein factor, 6.25 where it has none.
|
|
813
|
+
// Per mass, so ing.atwater rolls up through a premix. A custom field of the same name wins.
|
|
814
|
+
const _ff = _tpFoodFactorFields(ing);
|
|
815
|
+
Object.keys(_ff).forEach(k => { if (!Object.keys(out).some(o => o.toLowerCase() === k.toLowerCase())) out[k] = _ff[k]; });
|
|
809
816
|
// Wrap in a Proxy that does case-insensitive property reads. Bracket
|
|
810
817
|
// form `ing['Solids']` and dotted form `ing.Solids` both flow through
|
|
811
818
|
// here, so a single hook covers every access path the formula language
|
|
@@ -838,6 +845,42 @@ function _tpCiView(out) {
|
|
|
838
845
|
}
|
|
839
846
|
|
|
840
847
|
const _TP_FIELD_NEEDS = { volume: 'density', pigmentvolume: 'density', dryvolume: 'density or solids' };
|
|
848
|
+
const _TP_GENERAL_FACTORS = { protein: 4, fat: 9, carb: 4, nitrogen: 6.25 };
|
|
849
|
+
// The ingredient's factors: its own where Look up in USDA kept them, the general ones otherwise. `own` says which.
|
|
850
|
+
function _tpFoodFactors(ing) {
|
|
851
|
+
const f = (ing && ing.fdc && ing.fdc.factors) || {};
|
|
852
|
+
const ok = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
|
|
853
|
+
const kcalOwn = ok(f.protein) && ok(f.fat) && ok(f.carb); // all three or none: never a mix of the two systems
|
|
854
|
+
return {
|
|
855
|
+
protein: kcalOwn ? f.protein : _TP_GENERAL_FACTORS.protein,
|
|
856
|
+
fat: kcalOwn ? f.fat : _TP_GENERAL_FACTORS.fat,
|
|
857
|
+
carb: kcalOwn ? f.carb : _TP_GENERAL_FACTORS.carb,
|
|
858
|
+
nitrogen: ok(f.nitrogen) ? f.nitrogen : _TP_GENERAL_FACTORS.nitrogen,
|
|
859
|
+
own: kcalOwn, ownNitrogen: ok(f.nitrogen),
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
function _tpFoodFactorFields(ing) {
|
|
863
|
+
const fx = _tpFoodFactors(ing);
|
|
864
|
+
// The three macros in g/100 g, whatever unit the field carries (mg/100g, %, g/kg …).
|
|
865
|
+
const per100 = (name) => {
|
|
866
|
+
const cf = (ing.customFields || []).find(c => c && String(c.name || '').trim().toLowerCase() === name);
|
|
867
|
+
if (!cf || cf.value == null || cf.value === '') return null;
|
|
868
|
+
const v = typeof cf.value === 'number' ? cf.value : parseFloat(cf.value);
|
|
869
|
+
if (!Number.isFinite(v)) return null;
|
|
870
|
+
const u = String(cf.unit || '').trim();
|
|
871
|
+
if (!u) return v;
|
|
872
|
+
const fam = _tpUnitFactor(u);
|
|
873
|
+
return fam && fam[0] === 'm' ? v * fam[1] * 100 : null;
|
|
874
|
+
};
|
|
875
|
+
const p = per100('protein'), f = per100('fat'), c = per100('carb');
|
|
876
|
+
return {
|
|
877
|
+
atwater: (p != null && f != null && c != null) ? +(fx.protein * p + fx.fat * f + fx.carb * c).toPrecision(12) : null,
|
|
878
|
+
nFactor: fx.nitrogen,
|
|
879
|
+
// For Show calc's note (never read by the math; "_" fields don't roll up): the ingredient's own factors, if any.
|
|
880
|
+
_fxKcal: fx.own ? [fx.protein, fx.fat, fx.carb] : null,
|
|
881
|
+
_fxN: fx.ownNitrogen ? fx.nitrogen : null,
|
|
882
|
+
};
|
|
883
|
+
}
|
|
841
884
|
const _TP_PER_GRAM = new Set(['volume', 'pigmentVolume', 'dryVolume', 'volatileOrganic']); // a custom field of the same name wins
|
|
842
885
|
function _tpPerGramFields(ing, view) {
|
|
843
886
|
const d = (typeof _densityToKgPerL === 'function') ? _densityToKgPerL(ing.density, ing.densityUnit) : (parseFloat(ing.density) || null);
|
|
@@ -1030,6 +1073,23 @@ function _tpReplaceSpans(formula, spans, repl) {
|
|
|
1030
1073
|
spans.forEach((sp, k) => { out += formula.slice(cur, sp.start) + repl(k); cur = sp.end; });
|
|
1031
1074
|
return out + formula.slice(cur);
|
|
1032
1075
|
}
|
|
1076
|
+
// "Own factors: Whey protein 4.27 / 8.79 / 3.87 kcal/g · others 4 / 9 / 4" under Show calc, when the formula reads
|
|
1077
|
+
// ing.atwater or ing.nFactor (61i): which rows used their own USDA factors, and what the rest used.
|
|
1078
|
+
function _tpFactorNoteHtml(formula, rows) {
|
|
1079
|
+
const used = new Set(_tpFieldRefs(formula));
|
|
1080
|
+
const live = (rows || []).filter(r => r && r.ing && !r.ing._missing && !r.ing._isSubFormula && r.amount > 0);
|
|
1081
|
+
const f = (v) => String(+(+v).toFixed(2));
|
|
1082
|
+
const line = (label, own, general, fmt) => {
|
|
1083
|
+
const total = live.length;
|
|
1084
|
+
return `<div class="tp-factor-note" style="margin-top:6px;font-size:11.5px;color:var(--text-muted)">${label}: ${own.length
|
|
1085
|
+
? `${own.map(r => `${esc(r.ing.name || '(unnamed)')} ${fmt(r)}`).join(' · ')}${own.length < total ? ` · others ${general}` : ''}`
|
|
1086
|
+
: `${general} for every ingredient (none has USDA factors)`}</div>`;
|
|
1087
|
+
};
|
|
1088
|
+
let out = '';
|
|
1089
|
+
if (used.has('atwater')) out += line('Calorie factors (protein / fat / carb, kcal/g)', live.filter(r => Array.isArray(r.ing._fxKcal)), '4 / 9 / 4', r => r.ing._fxKcal.map(f).join(' / '));
|
|
1090
|
+
if (used.has('nfactor')) out += line('Nitrogen factors', live.filter(r => typeof r.ing._fxN === 'number'), '6.25', r => `× ${f(r.ing._fxN)}`);
|
|
1091
|
+
return out;
|
|
1092
|
+
}
|
|
1033
1093
|
// "sodium: 2 rows in g/100g read as mg/100g" under Show calc, for the fields this formula reads (49z).
|
|
1034
1094
|
function _tpConvNoteHtml(formula, rows) {
|
|
1035
1095
|
const conv = rows && rows.unitConversions;
|
|
@@ -1144,6 +1204,7 @@ function _tpCalcHtml(p, evalRows, valueMap) {
|
|
|
1144
1204
|
${refBits.length ? `<div style="font-size:11.5px;color:var(--text-muted);margin-bottom:6px">References: ${refBits.join(' · ')}</div>` : ''}
|
|
1145
1205
|
${tableHtml || (refBits.length ? '' : '<div style="color:var(--text-muted);font-size:11px">Value comes straight from the expression (no row aggregation).</div>')}
|
|
1146
1206
|
${_tpConvNoteHtml(formula, evalRows)}
|
|
1207
|
+
${_tpFactorNoteHtml(formula, evalRows)}
|
|
1147
1208
|
${resultHtml}
|
|
1148
1209
|
</div>`;
|
|
1149
1210
|
}
|
|
@@ -1882,6 +1943,27 @@ function _tpPresetCatalog() {
|
|
|
1882
1943
|
formula: 'SUM(row.amount * (17 * ing.protein + 17 * ing.carb + 37 * ing.fat)) / SUM(row.amount)',
|
|
1883
1944
|
description: 'Energy in kilojoules: 17 kJ/g protein, 17 kJ/g carbohydrate, 37 kJ/g fat. Needs ing.protein, ing.carb and ing.fat (g/100g).',
|
|
1884
1945
|
},
|
|
1946
|
+
{
|
|
1947
|
+
group: 'Food & nutrition',
|
|
1948
|
+
name: 'Energy (food factors)',
|
|
1949
|
+
unit: 'kcal/100g',
|
|
1950
|
+
formula: 'SUM(row.amount * ing.atwater) / SUM(row.amount)',
|
|
1951
|
+
description: 'Energy by each ingredient\u2019s own calorie factors from USDA (milk protein 4.27, not 4), the general 4 / 9 / 4 where it has none. Needs ing.protein, ing.fat and ing.carb; Look up in USDA keeps the factors.',
|
|
1952
|
+
},
|
|
1953
|
+
{
|
|
1954
|
+
group: 'Food & nutrition',
|
|
1955
|
+
name: 'Energy (food factors, kJ)',
|
|
1956
|
+
unit: 'kJ/100g',
|
|
1957
|
+
formula: '4.184 * SUM(row.amount * ing.atwater) / SUM(row.amount)',
|
|
1958
|
+
description: 'The same in kilojoules (1 kcal = 4.184 kJ).',
|
|
1959
|
+
},
|
|
1960
|
+
{
|
|
1961
|
+
group: 'Food & nutrition',
|
|
1962
|
+
name: 'Protein (from nitrogen)',
|
|
1963
|
+
unit: 'g/100g',
|
|
1964
|
+
formula: 'SUM(row.amount * ing.nitrogen * ing.nFactor) / SUM(row.amount)',
|
|
1965
|
+
description: 'Protein from measured nitrogen: N \u00d7 each ingredient\u2019s own factor from USDA (milk 6.38, wheat 5.83), 6.25 where it has none. Needs ing.nitrogen (g/100g).',
|
|
1966
|
+
},
|
|
1885
1967
|
{
|
|
1886
1968
|
group: 'Food & nutrition',
|
|
1887
1969
|
name: 'Protein',
|