formlab-mcp 0.7.3 → 0.7.5
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/package.json +1 -1
- package/server.json +2 -2
- package/theoretical.js +28 -0
- package/tools/formulations.js +4 -2
- package/tools/ingredients.js +1 -1
- package/tools/lab.js +3 -2
- package/vendor/reactive.js +343 -48
- package/vendor/theoretical-params.js +16 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "formlab-mcp",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.5",
|
|
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.7.
|
|
5
|
+
"version": "0.7.5",
|
|
6
6
|
"websiteUrl": "https://formvix.com/mcp",
|
|
7
7
|
"packages": [
|
|
8
8
|
{
|
|
9
9
|
"registryType": "npm",
|
|
10
10
|
"identifier": "formlab-mcp",
|
|
11
|
-
"version": "0.7.
|
|
11
|
+
"version": "0.7.5",
|
|
12
12
|
"runtimeHint": "npx",
|
|
13
13
|
"transport": {
|
|
14
14
|
"type": "stdio"
|
package/theoretical.js
CHANGED
|
@@ -107,6 +107,25 @@ function __nl(id) {
|
|
|
107
107
|
})(),
|
|
108
108
|
});
|
|
109
109
|
}
|
|
110
|
+
// The Composition tab's balance strip (js/reactive.js flRxBalance, 0.7.4; flakes as weighed via flRxAsActive, 0.7.5): each reacting pair's index, and for soap the
|
|
111
|
+
// superfat, lye concentration and lye excess; a batch reads what was weighed, else the formula's recipe.
|
|
112
|
+
function __rb(kind, id) {
|
|
113
|
+
var coll = kind === 'batch' ? db.batches : db.formulations;
|
|
114
|
+
var e = (coll || []).find(function (x) { return x && x.id === id; });
|
|
115
|
+
if (!e) return 'null';
|
|
116
|
+
var f = kind === 'batch' ? (db.formulations || []).find(function (x) { return x && x.id === e.formulationId; }) : e;
|
|
117
|
+
var weighed = kind === 'batch' && Array.isArray(e.actualComposition) && e.actualComposition.length;
|
|
118
|
+
var comp = weighed ? flRxAsActive(e.actualComposition) : ((f && f.composition) || []); // flakes at 90 % → pure KOH
|
|
119
|
+
var b = flRxBalance(comp);
|
|
120
|
+
if (!Array.isArray(b)) return JSON.stringify(b);
|
|
121
|
+
if (!b.length) return 'null';
|
|
122
|
+
var targets = (f && f.reactiveTargets) || [];
|
|
123
|
+
return JSON.stringify({ basis: kind === 'batch' ? (weighed ? 'as weighed' : 'planned (nothing weighed yet)') : 'recipe', pairs: b.map(function (x) {
|
|
124
|
+
var t = targets.find(function (y) { return y && y.pair === x.pair; });
|
|
125
|
+
if (t) x.target = x.superfat !== undefined ? { superfat: +(100 - t.index).toFixed(2), tol: t.tol || 0, lyeConcentration: t.conc != null ? t.conc : null } : { index: t.index, tol: t.tol || 0 };
|
|
126
|
+
return x;
|
|
127
|
+
}) });
|
|
128
|
+
}
|
|
110
129
|
function __theo(kind, id) {
|
|
111
130
|
var coll = kind === 'batch' ? db.batches : db.formulations;
|
|
112
131
|
var e = (coll || []).find(function (x) { return x && x.id === id; });
|
|
@@ -159,6 +178,15 @@ export function reactiveGroups(db, id) {
|
|
|
159
178
|
} catch (e) { return []; }
|
|
160
179
|
}
|
|
161
180
|
|
|
181
|
+
// The reactive / soap balance as the app's Composition tab shows it: null when the record has no reacting pair.
|
|
182
|
+
export function reactiveBalance(db, kind, id) {
|
|
183
|
+
try {
|
|
184
|
+
const ctx = contextFor(db);
|
|
185
|
+
vm.runInContext('var __bid = ' + JSON.stringify(String(id)) + ', __bkind = ' + JSON.stringify(kind === 'batch' ? 'batch' : 'formulation') + ';', ctx);
|
|
186
|
+
return JSON.parse(vm.runInContext('__rb(__bkind, __bid)', ctx, { timeout: 2000 }));
|
|
187
|
+
} catch (e) { return null; }
|
|
188
|
+
}
|
|
189
|
+
|
|
162
190
|
// [{ name, value, unit, formula, error, warning, spec, pass, pinned, basis }] —
|
|
163
191
|
// value null when it can't be computed (error says why); warning is the Params
|
|
164
192
|
// tab's ⚠ note ("2 ingredients missing carb", "sugar in mixed units (…)");
|
package/tools/formulations.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import { reviewState } from '../attention.js';
|
|
10
10
|
import { getStore, resolveById, flattenComposition } from '../data.js';
|
|
11
|
-
import { theoreticalParams, nutritionLabel, fragranceCompliance } from '../theoretical.js';
|
|
11
|
+
import { reactiveBalance, theoreticalParams, nutritionLabel, fragranceCompliance } from '../theoretical.js';
|
|
12
12
|
|
|
13
13
|
// Strip db-internal noise (createdAt, updatedAt) for cleaner LLM output
|
|
14
14
|
// while keeping the human-facing fields the user cares about.
|
|
@@ -120,7 +120,7 @@ const list_formulations = {
|
|
|
120
120
|
const get_formulation = {
|
|
121
121
|
definition: {
|
|
122
122
|
name: 'get_formulation',
|
|
123
|
-
description: 'Get full details for a single formulation including its composition (raw rows AND flattened wt-% leaves with sub-formulas expanded), step procedure, any recorded process-factor values (cure temp, mix time, RPM, pH — DOE inputs), and recent batches. Accepts either internal id or UID (e.g. FORM-001). Also returns `theoreticalParameters`: values computed from the composition the way the app Params tab does (e.g. Energy kcal/100g, NV %, Cost/kg) — each with name, value (a number, or text when the formula is an IF that gives text), unit, formula, spec + pass (numbers only), and `warning` when ingredients lack a value the formula reads or carry mixed units (those rows are not counted). Quote these; do not recompute nutrition or NV yourself. `versionLabel` is the label the user types (e.g. 1.0); `versionHistory` is the automatic save history (v1, v2… one per save, newest first, up to 20, with the label each save had and its note) — two different things.',
|
|
123
|
+
description: 'Get full details for a single formulation including its composition (raw rows AND flattened wt-% leaves with sub-formulas expanded), step procedure, any recorded process-factor values (cure temp, mix time, RPM, pH — DOE inputs), and recent batches. Accepts either internal id or UID (e.g. FORM-001). Also returns `theoreticalParameters`: values computed from the composition the way the app Params tab does (e.g. Energy kcal/100g, NV %, Cost/kg) — each with name, value (a number, or text when the formula is an IF that gives text), unit, formula, spec + pass (numbers only), and `warning` when ingredients lack a value the formula reads or carry mixed units (those rows are not counted). Quote these; do not recompute nutrition or NV yourself. `reactiveBalance` (null when none): the Composition tab\'s balance strip, each reacting pair\'s index (100 = stoichiometric) with its target; for soap (pair base:ester) `superfat` % (= 100 − index), `lyeExcess` (true = more lye than the oils take: a safety problem) and `lyeConcentration` % (lye ÷ lye + water). Quote it; do not recompute lye from SAP values yourself. `versionLabel` is the label the user types (e.g. 1.0); `versionHistory` is the automatic save history (v1, v2… one per save, newest first, up to 20, with the label each save had and its note) — two different things.',
|
|
124
124
|
inputSchema: {
|
|
125
125
|
type: 'object',
|
|
126
126
|
properties: {
|
|
@@ -173,6 +173,8 @@ const get_formulation = {
|
|
|
173
173
|
processFactors: (f.factorValues || []).filter(x => x && x.name).map(x => ({ name: x.name, value: x.value != null ? x.value : '', unit: x.unit || '' })),
|
|
174
174
|
// Computed by the app's own engine (mcp/theoretical.js → mcp/vendor/).
|
|
175
175
|
theoreticalParameters: theoreticalParams(db, 'formulation', f.id),
|
|
176
|
+
// Epoxy / NCO indices and, for soap, superfat, lye concentration and lye excess (null: no reacting pair).
|
|
177
|
+
reactiveBalance: reactiveBalance(db, 'formulation', f.id),
|
|
176
178
|
// IFRA limits and EU fragrance allergens as the Fragrance tab computes them (see get_fragrance_compliance).
|
|
177
179
|
...(fr ? { fragranceCompliance: fr } : {}),
|
|
178
180
|
// Automatic history: one snapshot per save (v1, v2…), newest first,
|
package/tools/ingredients.js
CHANGED
|
@@ -181,7 +181,7 @@ const list_ingredients = {
|
|
|
181
181
|
const get_ingredient = {
|
|
182
182
|
definition: {
|
|
183
183
|
name: 'get_ingredient',
|
|
184
|
-
description: 'Get full details for a single ingredient: cost ($/kg), GHS safety (pictograms / H- / P-codes / signal word), per-jurisdiction regulatory status, approved sources (the suppliers/manufacturers qualified to supply this material — ASL/AML), inventory lots (balances + expiry + the source each was received from), recent stock movements, and the formulations using it, plus its `customFields` (name, value, unit — e.g. protein / carb / fat in g/100g, solids %; what theoretical parameters read) and `reactiveGroups` (EEW, AHEW, OH number, NCO %, acid / amine value, Si-H, vinyl, water: the datasheet value as entered, the same in the datasheet\'s own terms, and meq/g; rows the app ignores are listed with why). Accepts internal id or UID (e.g. ING-001).',
|
|
184
|
+
description: 'Get full details for a single ingredient: cost ($/kg), GHS safety (pictograms / H- / P-codes / signal word), per-jurisdiction regulatory status, approved sources (the suppliers/manufacturers qualified to supply this material — ASL/AML), inventory lots (balances + expiry + the source each was received from), recent stock movements, and the formulations using it, plus its `customFields` (name, value, unit — e.g. protein / carb / fat in g/100g, solids %; what theoretical parameters read) and `reactiveGroups` (EEW, AHEW, OH number, NCO %, acid / amine value, Si-H, vinyl, water, an oil\'s SAP value, lye; NaOH and KOH count as lye by CAS (a recipe amount is pure lye; a batch\'s weighed flakes count at their purity): the datasheet value as entered, the same in the datasheet\'s own terms, and meq/g; rows the app ignores are listed with why). Accepts internal id or UID (e.g. ING-001).',
|
|
185
185
|
inputSchema: {
|
|
186
186
|
type: 'object',
|
|
187
187
|
properties: {
|
package/tools/lab.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import { sampleOverdue } from '../attention.js';
|
|
10
10
|
import { getStore, resolveById } from '../data.js';
|
|
11
|
-
import { theoreticalParams } from '../theoretical.js';
|
|
11
|
+
import { reactiveBalance, theoreticalParams } from '../theoretical.js';
|
|
12
12
|
import { _mcpSamplePulls } from './analytics.js';
|
|
13
13
|
|
|
14
14
|
// --- Self-contained unit conversion + actual-volume derivation ---------------
|
|
@@ -394,7 +394,7 @@ const list_batches = {
|
|
|
394
394
|
const get_batch = {
|
|
395
395
|
definition: {
|
|
396
396
|
name: 'get_batch',
|
|
397
|
-
description: 'Get full details for a single batch including the raw lots it drew (lotsUsed: lot number, quantity, and the status of each lot now, with holdReason for a lot on hold), hold (now) and holdHistory (every hold with its release: when, by whom, and the note, e.g. "Released with lot ETH-1"), its actual composition (as-prepared, when logged), child samples, lineage (parent / sub-blend parents), and — treating the batch as a finished-goods lot — its storage `location` and finished-goods `stockLedger` (shipments out + adjustments; on-hand = produced − sample pulls − sub-batch draws + Σ ledger). Plus finished-product density + actual volume (measured directly or derived as actual mass ÷ measured density — never summed from per-ingredient volumes). Accepts internal id or UID. Also returns `theoreticalParameters` computed on the batch as made (its actual composition when logged — `basis: "actual"` — else the recipe of its formula), with the batch parameter list when it overrides the one on the formula; same fields as get_formulation.',
|
|
397
|
+
description: 'Get full details for a single batch including the raw lots it drew (lotsUsed: lot number, quantity, and the status of each lot now, with holdReason for a lot on hold), hold (now) and holdHistory (every hold with its release: when, by whom, and the note, e.g. "Released with lot ETH-1"), its actual composition (as-prepared, when logged), child samples, lineage (parent / sub-blend parents), and — treating the batch as a finished-goods lot — its storage `location` and finished-goods `stockLedger` (shipments out + adjustments; on-hand = produced − sample pulls − sub-batch draws + Σ ledger). Plus finished-product density + actual volume (measured directly or derived as actual mass ÷ measured density — never summed from per-ingredient volumes). Accepts internal id or UID. Also returns `theoreticalParameters` computed on the batch as made (its actual composition when logged — `basis: "actual"` — else the recipe of its formula), with the batch parameter list when it overrides the one on the formula; same fields as get_formulation. `reactiveBalance` is the same as get_formulation\'s, on what was weighed (basis "as weighed"), e.g. a soap batch\'s superfat and lye excess.',
|
|
398
398
|
inputSchema: {
|
|
399
399
|
type: 'object',
|
|
400
400
|
properties: {
|
|
@@ -452,6 +452,7 @@ const get_batch = {
|
|
|
452
452
|
// here ("status: hold" + holdReason) is why a recall reaches this batch, held or not.
|
|
453
453
|
lotsUsed: _batchLotsUsed(getStore().db, b.id),
|
|
454
454
|
theoreticalParameters: theoreticalParams(getStore().db, 'batch', b.id),
|
|
455
|
+
reactiveBalance: reactiveBalance(getStore().db, 'batch', b.id),
|
|
455
456
|
};
|
|
456
457
|
},
|
|
457
458
|
};
|
package/vendor/reactive.js
CHANGED
|
@@ -28,6 +28,14 @@ const FL_RX_BASES = {
|
|
|
28
28
|
ncopct: { label: 'NCO, %', short: 'NCO', unit: '%', toMeq: v => v * 10 / 42.02, fromMeq: m => m * 4.202 },
|
|
29
29
|
// Water: H2O + 2 NCO → urea + CO2, so 18.02 / 2 = 9.008 g/eq; 1 % water = 1.11 meq/g.
|
|
30
30
|
wpct: { label: 'Water content, %', short: 'Water', unit: '%', toMeq: v => v * 10 / 9.008, fromMeq: m => m * 0.9008 },
|
|
31
|
+
// Soap (1 Dec, Jun): an oil's saponification (SAP) value, as a datasheet gives it (mg KOH/g) or as soap calculators do
|
|
32
|
+
// (g of NaOH or KOH per g of oil). KOH = NaOH × 56.1 / 40.0. All three are the oil's ester equivalents per gram.
|
|
33
|
+
sap: { label: 'SAP value, mg KOH/g', short: 'SAP', unit: '', toMeq: v => v / 56.1, fromMeq: m => m * 56.1 },
|
|
34
|
+
sapnaoh: { label: 'NaOH SAP, g/g', short: 'NaOH SAP', unit: '', toMeq: v => v * 1000 / 40.0, fromMeq: m => m * 0.040 },
|
|
35
|
+
sapkoh: { label: 'KOH SAP, g/g', short: 'KOH SAP', unit: '', toMeq: v => v * 1000 / 56.1, fromMeq: m => m * 0.0561 },
|
|
36
|
+
// A lye given as its strength: flakes at 90 % KOH, a 50 % NaOH solution.
|
|
37
|
+
naohpct: { label: 'NaOH, %', short: 'NaOH', unit: '%', toMeq: v => v * 10 / 40.0, fromMeq: m => m * 4.0 },
|
|
38
|
+
kohpct: { label: 'KOH, %', short: 'KOH', unit: '%', toMeq: v => v * 10 / 56.1, fromMeq: m => m * 5.61 },
|
|
31
39
|
mmol: { label: 'mmol/g', short: '', unit: 'mmol/g', toMeq: v => v, fromMeq: m => m },
|
|
32
40
|
f: { label: 'MW + groups / molecule', short: '', unit: 'per molecule', toMeq: (v, mw) => (mw > 0 ? v * 1000 / mw : null) },
|
|
33
41
|
};
|
|
@@ -43,11 +51,14 @@ const FL_RX_GROUPS = {
|
|
|
43
51
|
vinyl: { label: 'Vinyl', bases: ['mmol', 'eqw', 'f'], term: 'mmol' },
|
|
44
52
|
// Water reacts with NCO (foams, moisture cure; Jun 27 Oct: "later preset", built 28 Oct). `h2o`, not `water`: food
|
|
45
53
|
// workspaces keep a custom field called water.
|
|
46
|
-
h2o: { label: 'Water
|
|
54
|
+
h2o: { label: 'Water', bases: ['wpct', 'mmol'], term: 'wpct' },
|
|
55
|
+
// Soap (1 Dec): oils, butters and waxes carry a SAP value; NaOH and KOH are known by CAS (recipe amounts are pure lye).
|
|
56
|
+
ester: { label: 'Oil / fat (SAP)', bases: ['sapnaoh', 'sap', 'sapkoh', 'mmol'], term: 'sap' },
|
|
57
|
+
base: { label: 'Lye (NaOH / KOH)', bases: ['naohpct', 'kohpct', 'mmol'], term: 'mmol' },
|
|
47
58
|
};
|
|
48
59
|
const FL_RX_GROUP_KEYS = Object.keys(FL_RX_GROUPS);
|
|
49
60
|
// The datasheet terms the ingredient view and Smart search expose (null when the ingredient has none).
|
|
50
|
-
const FL_RX_TERMS = { eew: 'epoxy', ahew: 'amineH', ohv: 'oh', ncoPct: 'nco', av: 'cooh', amineValue: 'amine' };
|
|
61
|
+
const FL_RX_TERMS = { eew: 'epoxy', ahew: 'amineH', ohv: 'oh', ncoPct: 'nco', av: 'cooh', amineValue: 'amine', sap: 'ester' };
|
|
51
62
|
|
|
52
63
|
// The pairs that react. index = 100 × Σ num eq / Σ den eq. `preset` names the Params preset with the same formula.
|
|
53
64
|
const FL_RX_PAIRS = [
|
|
@@ -56,6 +67,8 @@ const FL_RX_PAIRS = [
|
|
|
56
67
|
{ key: 'sih:vinyl', label: 'Si-H : vinyl', num: ['sih'], den: ['vinyl'], numLabel: 'Si-H', denLabel: 'vinyl', preset: 'Si-H : vinyl index' },
|
|
57
68
|
// Shown only when the formula holds water: the index foams and moisture-cure systems are set by.
|
|
58
69
|
{ key: 'nco:ohw', label: 'Isocyanate index (with water)', num: ['nco'], den: ['oh', 'amineH', 'cooh', 'h2o'], needs: ['h2o'], numLabel: 'NCO', denLabel: 'OH + NH + COOH + water', preset: 'Isocyanate index (with water)' },
|
|
70
|
+
// Soap: lye against the oils' SAP. Read as superfat = 100 − index (5 % superfat = index 95), the soap maker's number.
|
|
71
|
+
{ key: 'base:ester', label: 'Superfat', num: ['base'], den: ['ester'], numLabel: 'lye', denLabel: 'oils (SAP)', soap: true },
|
|
59
72
|
{ key: 'amine:cooh', label: 'Neutralization', num: ['amine'], den: ['cooh'], numLabel: 'amine', denLabel: 'COOH', preset: 'Degree of neutralization', unit: '%' },
|
|
60
73
|
];
|
|
61
74
|
|
|
@@ -79,8 +92,20 @@ function flRxMeq(entry, mw) {
|
|
|
79
92
|
}
|
|
80
93
|
// Every group of an ingredient in meq/g (absent groups left out). One row per group; a second is ignored.
|
|
81
94
|
const FL_RX_WATER_CAS = '7732-18-5';
|
|
95
|
+
// NaOH and KOH count as lye by CAS. A recipe amount is the active amount (the app's purity rule: the weigh-out grosses
|
|
96
|
+
// up for purity), so a recipe row counts at 100 %; a batch's weighed row is flakes, so flRxAsActive takes its purity
|
|
97
|
+
// off first. A stored Lye row (a 50 % solution) describes the material as weighed and still wins.
|
|
98
|
+
const FL_RX_LYE_CAS = { '1310-73-2': 40.0, '1310-58-3': 56.1 };
|
|
99
|
+
function flRxLyeKind(ing) {
|
|
100
|
+
const mw = ing && FL_RX_LYE_CAS[String(ing.cas || '').trim()];
|
|
101
|
+
return mw === 40.0 ? 'NaOH' : mw === 56.1 ? 'KOH' : '';
|
|
102
|
+
}
|
|
82
103
|
function flRxIngMeq(ing) {
|
|
83
104
|
const out = {};
|
|
105
|
+
const lyeMw = ing && FL_RX_LYE_CAS[String(ing.cas || '').trim()];
|
|
106
|
+
if (lyeMw && !((ing.reactiveGroups || []).some(g => g && g.group === 'base'))) {
|
|
107
|
+
out.base = 1000 / lyeMw;
|
|
108
|
+
}
|
|
84
109
|
// Water itself counts without being told (a foam's blowing water); a stored h2o row still wins.
|
|
85
110
|
if (ing && String(ing.cas || '').trim() === FL_RX_WATER_CAS && !((ing.reactiveGroups || []).some(g => g && g.group === 'h2o'))) out.h2o = FL_RX_BASES.wpct.toMeq(100);
|
|
86
111
|
((ing && ing.reactiveGroups) || []).forEach(g => {
|
|
@@ -91,17 +116,28 @@ function flRxIngMeq(ing) {
|
|
|
91
116
|
return out;
|
|
92
117
|
}
|
|
93
118
|
// The group in its datasheet's own terms: EEW 187 g/eq, OHV 112, NCO 21.8 %, Si-H 7.5 mmol/g.
|
|
94
|
-
function flRxTermText(group, meq) {
|
|
95
|
-
const g = FL_RX_GROUPS[group]
|
|
96
|
-
|
|
119
|
+
function flRxTermText(group, meq, basis) {
|
|
120
|
+
const g = FL_RX_GROUPS[group];
|
|
121
|
+
// A SAP value reads in the form it was entered: soap calculators' NaOH SAP 0.135, a datasheet's SAP 190.
|
|
122
|
+
const b = FL_RX_BASES[(basis && /^sap/.test(basis)) ? basis : (g && g.term)];
|
|
123
|
+
if (!g || !b || meq == null) return '';
|
|
124
|
+
if (group === 'base' && !basis) return `Lye ${flRxFmt(meq)} meq/g`;
|
|
97
125
|
const v = flRxFmt(b.fromMeq(meq));
|
|
98
126
|
if (g.term === 'mmol') return `${g.label} ${flRxFmt(meq)} mmol/g`;
|
|
99
127
|
return `${b.short} ${v}${b.unit ? ' ' + b.unit : ''}`;
|
|
100
128
|
}
|
|
101
129
|
// For the ingredient view: the meq/g fields (0 when absent) and the datasheet terms (null when absent).
|
|
102
|
-
function flRxViewFields(ing) { return _flRxFieldsFromMeq(flRxIngMeq(ing)); }
|
|
103
|
-
|
|
104
|
-
|
|
130
|
+
function flRxViewFields(ing) { return _flRxFieldsFromMeq(flRxIngMeq(ing), flRxLyeFrac(ing)); }
|
|
131
|
+
// Grams of pure lye per gram (soap's lye concentration counts pure NaOH / KOH, so a premixed 50 % lye solution reads
|
|
132
|
+
// right): a Lye row's NaOH % / KOH %, mmol/g as NaOH, else 1 for NaOH / KOH by CAS (active, see above). 0 for the rest.
|
|
133
|
+
function flRxLyeFrac(ing) {
|
|
134
|
+
if (!ing) return 0;
|
|
135
|
+
const e = (ing.reactiveGroups || []).find(g => g && g.group === 'base' && flRxMeq(g, ing.mw) != null);
|
|
136
|
+
if (e) return e.basis === 'naohpct' || e.basis === 'kohpct' ? Math.min(_flRxNum(e.value), 100) / 100 : flRxMeq(e, ing.mw) * 0.040;
|
|
137
|
+
return flRxLyeKind(ing) ? 1 : 0;
|
|
138
|
+
}
|
|
139
|
+
function _flRxFieldsFromMeq(meq, lyeFrac) {
|
|
140
|
+
const out = { lyeMass: lyeFrac > 0 ? lyeFrac : 0 };
|
|
105
141
|
FL_RX_GROUP_KEYS.forEach(k => { out[k] = meq[k] || 0; });
|
|
106
142
|
Object.entries(FL_RX_TERMS).forEach(([t, grp]) => {
|
|
107
143
|
const b = FL_RX_BASES[FL_RX_GROUPS[grp].term];
|
|
@@ -128,7 +164,9 @@ function flRxSubViewFields(sub) {
|
|
|
128
164
|
rows.forEach(r => { const m = r && r.ing ? _flRxNum(r.ing[g]) : null; if (m) t += r.amount * m; });
|
|
129
165
|
if (t > 0) meq[g] = t / total;
|
|
130
166
|
});
|
|
131
|
-
|
|
167
|
+
let lt = 0;
|
|
168
|
+
if (total > 0) rows.forEach(r => { const m = r && r.ing ? _flRxNum(r.ing.lyeMass) : null; if (m) lt += r.amount * m; });
|
|
169
|
+
const out = _flRxFieldsFromMeq(meq, total > 0 ? lt / total : 0);
|
|
132
170
|
_flRxSubCache.set(sub.id, out);
|
|
133
171
|
return { ...out };
|
|
134
172
|
} finally { _flRxSubStack.delete(sub.id); }
|
|
@@ -138,15 +176,37 @@ function flRxSubViewFields(sub) {
|
|
|
138
176
|
function flRxChipsHtml(ing) {
|
|
139
177
|
const meq = flRxIngMeq(ing);
|
|
140
178
|
const rows = ((ing && ing.reactiveGroups) || []).filter(g => g && meq[g.group] != null);
|
|
141
|
-
|
|
142
|
-
|
|
179
|
+
// NaOH / KOH count as lye by their CAS with nothing stored (soap, 1 Dec): say so on the page, or nothing would.
|
|
180
|
+
const lye = (meq.base != null && !rows.some(g => g.group === 'base')) ? _flRxLyeChip(ing, meq.base) : '';
|
|
181
|
+
if (!rows.length) return lye;
|
|
182
|
+
return lye + rows.map(g => {
|
|
143
183
|
const how = g.basis === 'f' ? `MW ${_flRxNum(ing.mw)} × ${_flRxNum(g.value)} per molecule · ` : ''; // the MW as recorded (170.3), not rounded
|
|
144
|
-
return `<span class="fl-rx-chip" title="${esc(FL_RX_GROUPS[g.group].label)}: ${esc(how)}${flRxFmt(meq[g.group])} meq/g">${esc(flRxTermText(g.group, meq[g.group]))}</span>`;
|
|
184
|
+
return `<span class="fl-rx-chip" title="${esc(FL_RX_GROUPS[g.group].label)}: ${esc(how)}${flRxFmt(meq[g.group])} meq/g">${esc(flRxTermText(g.group, meq[g.group], g.basis))}</span>`;
|
|
145
185
|
}).join('');
|
|
146
186
|
}
|
|
147
187
|
function flRxListText(ing) {
|
|
148
188
|
const meq = flRxIngMeq(ing);
|
|
149
|
-
|
|
189
|
+
const stored = (ing && ing.reactiveGroups) || [];
|
|
190
|
+
return Object.keys(meq).map(k => {
|
|
191
|
+
const e = stored.find(x => x && x.group === k);
|
|
192
|
+
if (k === 'base' && !e && flRxLyeKind(ing)) return `${flRxLyeKind(ing)} lye`;
|
|
193
|
+
return flRxTermText(k, meq[k], e && e.basis);
|
|
194
|
+
}).join(' · ');
|
|
195
|
+
}
|
|
196
|
+
function _flRxLyePurity(ing) { const p = _flRxNum(ing && ing.purity); return (p != null && p > 0 && p <= 100) ? p : 100; }
|
|
197
|
+
// A batch's weighed rows as active amounts: NaOH / KOH found by CAS (no stored Lye row) count at their purity, since
|
|
198
|
+
// 111 g of 90 % flakes is 100 g of KOH. Everything else passes through. A recipe is already active: never call it there.
|
|
199
|
+
function flRxAsActive(comp) {
|
|
200
|
+
return (comp || []).map(c => {
|
|
201
|
+
const ing = c && c.ingredientId && (db.ingredients || []).find(i => i.id === c.ingredientId);
|
|
202
|
+
if (!ing || !flRxLyeKind(ing) || (ing.reactiveGroups || []).some(g => g && g.group === 'base')) return c;
|
|
203
|
+
const p = _flRxLyePurity(ing), a = parseFloat(c.amount);
|
|
204
|
+
return p < 100 && Number.isFinite(a) ? { ...c, amount: a * p / 100 } : c;
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
function _flRxLyeChip(ing, meq) {
|
|
208
|
+
const kind = flRxLyeKind(ing), pur = _flRxLyePurity(ing);
|
|
209
|
+
return `<span class="fl-rx-chip" title="Counts as lye by its CAS number: ${flRxFmt(meq)} meq/g${pur < 100 ? `; recipe amounts are pure ${esc(kind)}, the weigh-out grosses up for ${pur} %` : ''}">${esc(kind)} lye</span>`;
|
|
150
210
|
}
|
|
151
211
|
|
|
152
212
|
// ---- A composition's pairs and index ----
|
|
@@ -161,6 +221,66 @@ function flRxEval(pair, rows) {
|
|
|
161
221
|
const num = _flRxSum(rows, pair.num), den = _flRxSum(rows, pair.den);
|
|
162
222
|
return { num, den, index: den > 0 ? 100 * num / den : null };
|
|
163
223
|
}
|
|
224
|
+
// ---- Soap (1 Dec, Jun): the lye pair reads as superfat, and the lye's share of lye + water ----
|
|
225
|
+
// Superfat = 100 − index: 5 % less lye than the oils take is index 95. Below 0 is lye excess, which burns skin, so it
|
|
226
|
+
// shows red with or without a target (the one exception to "no target, no color").
|
|
227
|
+
function flRxShown(pair, index) { return (pair && pair.soap && index != null) ? 100 - index : index; }
|
|
228
|
+
function flRxLyeExcess(pair, index) { return !!(pair && pair.soap && index != null && index > 100.05); }
|
|
229
|
+
// Lye concentration as weighed: the lye rows' mass over lye + water. Water counts by CAS, or by an ingredient's Water
|
|
230
|
+
// group (1 meq/g of h2o = 9.008 mg of water per g). null when there is no lye or no water.
|
|
231
|
+
function flRxLyeConc(rows) {
|
|
232
|
+
let lye = 0, water = 0;
|
|
233
|
+
(rows || []).forEach(r => {
|
|
234
|
+
if (!r || !r.ing || !(r.amount > 0)) return;
|
|
235
|
+
// Pure lye: the row's lyeMass (g per g); a row whose lye share is unknown counts whole.
|
|
236
|
+
if (_flRxNum(r.ing.base) > 0) lye += r.amount * (_flRxNum(r.ing.lyeMass) > 0 ? r.ing.lyeMass : 1);
|
|
237
|
+
const h = _flRxNum(r.ing.h2o);
|
|
238
|
+
if (h > 0) water += r.amount * h * 0.009008;
|
|
239
|
+
});
|
|
240
|
+
return lye > 0 && water > 0 ? 100 * lye / (lye + water) : null;
|
|
241
|
+
}
|
|
242
|
+
// Oils, butters and fats in a soap with no SAP value: left out of the lye, so the superfat reads wrong. Fragrance,
|
|
243
|
+
// essential, mineral and silicone oils don't saponify (or barely) and are not named.
|
|
244
|
+
function flRxMissingSap(comp, depth) {
|
|
245
|
+
const out = [], d = depth || 0;
|
|
246
|
+
if (d > 6) return out;
|
|
247
|
+
(comp || []).forEach(c => {
|
|
248
|
+
if (!c || !(parseFloat(c.amount) > 0)) return;
|
|
249
|
+
if (c.formulationId) { // an oil premix: its oils count too
|
|
250
|
+
const sub = (db.formulations || []).find(x => x.id === c.formulationId);
|
|
251
|
+
if (sub) flRxMissingSap(sub.composition, d + 1).forEach(n => { if (!out.includes(n)) out.push(n); });
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const ing = c.ingredientId && (db.ingredients || []).find(i => i.id === c.ingredientId);
|
|
255
|
+
const m = ing ? flRxIngMeq(ing) : null;
|
|
256
|
+
if (!ing || (m.ester || 0) > 0 || (m.base || 0) > 0) return; // has a SAP value, or is the lye itself
|
|
257
|
+
const name = String(ing.name || ''), cls = String(ing.ingredientClass || '').toLowerCase(), fn = String(ing.function || '');
|
|
258
|
+
if (/essential|fragrance|mineral|silicone|paraffin|petrolat|perfume/i.test(name + ' ' + fn) || cls === 'fragrance') return;
|
|
259
|
+
if ((cls === 'oil' || /\b(oil|butter|tallow|lard|fat)\b/i.test(name) || /saponif/i.test(fn)) && !out.includes(name || 'an oil')) out.push(name || 'an oil');
|
|
260
|
+
});
|
|
261
|
+
return out;
|
|
262
|
+
}
|
|
263
|
+
function _flRxPct(v) { return (v == null || !Number.isFinite(v)) ? '—' : String(Math.round(v * 10) / 10); }
|
|
264
|
+
// Every reacting pair of a composition as plain numbers (the AI context and the MCP server read this, so app, AI and
|
|
265
|
+
// MCP say the same): [{ pair, label, index, superfat?, lyeExcess?, lyeConcentration? }], or { error } for mixed units.
|
|
266
|
+
function flRxBalance(comp) {
|
|
267
|
+
const found = flRxPairsFor(comp);
|
|
268
|
+
if (!found.length) return [];
|
|
269
|
+
if (flRxMixedUnits(comp)) return { error: 'Rows in different units (% and g, or mL without a density): no index.' };
|
|
270
|
+
const rows = _flRxRows(comp);
|
|
271
|
+
return found.map(({ pair, index }) => {
|
|
272
|
+
const o = { pair: pair.key, label: pair.label, index: index == null ? null : +index.toFixed(2) };
|
|
273
|
+
if (pair.soap) {
|
|
274
|
+
o.superfat = index == null ? null : +(100 - index).toFixed(2);
|
|
275
|
+
o.lyeExcess = flRxLyeExcess(pair, index);
|
|
276
|
+
const c = flRxLyeConc(rows);
|
|
277
|
+
o.lyeConcentration = c == null ? null : +c.toFixed(2);
|
|
278
|
+
const miss = flRxMissingSap(comp);
|
|
279
|
+
if (miss.length) o.oilsWithoutSap = miss;
|
|
280
|
+
}
|
|
281
|
+
return o;
|
|
282
|
+
});
|
|
283
|
+
}
|
|
164
284
|
// One basis or the index means nothing: % rows next to grams, or mL without a density, don't share a unit.
|
|
165
285
|
function _flRxUnitBasis(u) { u = String(u || '').trim().toLowerCase(); return /^(wt\s*%|%|w\/w|%\s*w\/w|w\/w\s*%)$/.test(u) ? '%' : u; }
|
|
166
286
|
// Two checks: the rows as typed (% beside g, which _tpBuildRows turns into one wt% set), and as built (mL it couldn't
|
|
@@ -188,7 +308,24 @@ function flRxBand(index, t) {
|
|
|
188
308
|
if (!t || index == null || !Number.isFinite(_flRxNum(t.index))) return '';
|
|
189
309
|
return Math.abs(index - t.index) <= (_flRxNum(t.tol) || 0) + 1e-9 ? 'ok' : 'off';
|
|
190
310
|
}
|
|
191
|
-
function _flRxTargetText(t) {
|
|
311
|
+
function _flRxTargetText(t, pair) {
|
|
312
|
+
if (!t) return '';
|
|
313
|
+
if (pair && pair.soap) return `target ${_flRxPct(100 - +t.index)}${_flRxNum(t.tol) ? ' ± ' + flRxFmtIndex(+t.tol) : ''} %`;
|
|
314
|
+
return `target ${flRxFmtIndex(+t.index)}${_flRxNum(t.tol) ? ' ± ' + flRxFmtIndex(+t.tol) : ''}`;
|
|
315
|
+
}
|
|
316
|
+
function _flRxMissHtml(comp) {
|
|
317
|
+
const m = flRxMissingSap(comp);
|
|
318
|
+
if (!m.length) return '';
|
|
319
|
+
const names = m.length > 2 ? `${m.slice(0, 2).join(', ')} +${m.length - 2}` : m.join(' and ');
|
|
320
|
+
return `<span class="fl-rx-warn" title="Give each oil a SAP value (Reactive groups › Oil / fat (SAP)); until then it isn't counted in the lye">No SAP value: ${esc(names)}</span>`;
|
|
321
|
+
}
|
|
322
|
+
// The soap chip's lye concentration, with its target when one is set (amber more than half a point off).
|
|
323
|
+
function _flRxConcHtml(rows, t) {
|
|
324
|
+
const c = flRxLyeConc(rows), want = t ? _flRxNum(t.conc) : null;
|
|
325
|
+
if (c == null) return '';
|
|
326
|
+
const off = want != null && Math.abs(c - want) > 0.5;
|
|
327
|
+
return `<span class="fl-rx-dim" title="Lye ÷ (lye + water), as weighed">lye concentration <b class="${off ? 'fl-rx-off' : ''}">${_flRxPct(c)} %</b>${want != null ? ` (target ${_flRxPct(want)} %)` : ''}</span>`;
|
|
328
|
+
}
|
|
192
329
|
// A 2K kit: a formula whose rows are all sub-formulas (Part A, Part B …). Its mix ratio, the first part = 100: by
|
|
193
330
|
// weight, and by volume when every part has a density (the parts' planning densities).
|
|
194
331
|
function flRxKitRatio(comp) {
|
|
@@ -257,7 +394,7 @@ function flRxSubRowEq(sub, parentAmount, groups) {
|
|
|
257
394
|
flRxRowEq(sub.composition, groups).forEach((list, i) => out.set(i, list.map(x => ({ ...x, eq: x.eq * k, amount: x.amount * k }))));
|
|
258
395
|
return out;
|
|
259
396
|
}
|
|
260
|
-
const _FL_RX_SHORT = { epoxy: 'epoxy', amineH: 'amine H', oh: 'OH', nco: 'NCO', cooh: 'COOH', amine: 'amine', sih: 'Si-H', vinyl: 'vinyl', h2o: 'water' };
|
|
397
|
+
const _FL_RX_SHORT = { epoxy: 'epoxy', amineH: 'amine H', oh: 'OH', nco: 'NCO', cooh: 'COOH', amine: 'amine', sih: 'Si-H', vinyl: 'vinyl', h2o: 'water', ester: 'oil', base: 'lye' };
|
|
261
398
|
function flRxEqCellHtml(list) {
|
|
262
399
|
if (!list || !list.length) return '<span class="fl-rx-dim">—</span>';
|
|
263
400
|
// The arithmetic on hover (Jun, 28 Oct): 14.6 g × 23.5 meq/g = 0.343 eq (AHEW 42.6 g/eq). The TOTAL cell has no amount.
|
|
@@ -275,20 +412,27 @@ function flRxStripHtml(f) {
|
|
|
275
412
|
if (!found.length) return '';
|
|
276
413
|
const pro = typeof hasFeature !== 'function' || hasFeature('reactive.solve');
|
|
277
414
|
const kit = flRxKitHtml(f.composition, '');
|
|
278
|
-
|
|
415
|
+
const kicker = found.every(x => x.pair.soap) ? 'Soap' : 'Reactive balance';
|
|
416
|
+
if (flRxMixedUnits(f.composition)) return `<div class="fl-rx-strip" id="fl-rx-strip-${esc(f.id)}"><span class="fl-rx-kicker">${kicker}</span><span class="fl-rx-warn">Rows in different units (% and g, or mL without a density): put them on one basis for an index.</span></div>`;
|
|
417
|
+
const rows = _flRxRows(f.composition);
|
|
279
418
|
const chips = found.map(({ pair, num, den, index }) => {
|
|
280
|
-
const t = flRxTarget(f, pair.key), band = flRxBand(index, t);
|
|
281
|
-
|
|
419
|
+
const t = flRxTarget(f, pair.key), band = flRxBand(index, t), bad = flRxLyeExcess(pair, index);
|
|
420
|
+
const cls = bad ? ' is-bad' : band ? ' is-' + band : '';
|
|
421
|
+
const value = pair.soap
|
|
422
|
+
? `<span class="fl-rx-idx"><b>${_flRxPct(flRxShown(pair, index))}</b> %${bad ? ' <span class="fl-rx-bad">lye excess</span>' : ''}</span>`
|
|
423
|
+
: `<span class="fl-rx-idx">${/^nco:/.test(pair.key) ? '' : 'index '}<b>${flRxFmtIndex(index)}</b>${pair.unit ? ' ' + pair.unit : ''}</span>`;
|
|
424
|
+
return `<div class="fl-rx-pair${cls}" data-rx-pair="${esc(pair.key)}">
|
|
282
425
|
<span class="fl-rx-name">${esc(pair.label)}</span>
|
|
283
|
-
|
|
284
|
-
<span class="fl-rx-dim" title="Equivalents per 100 g of formula: ${esc(pair.numLabel)} / ${esc(pair.denLabel)}">${num.toFixed(3)} / ${den.toFixed(3)} eq</span>
|
|
285
|
-
|
|
286
|
-
<button type="button" class="
|
|
426
|
+
${value}
|
|
427
|
+
<span class="fl-rx-dim" title="Equivalents per 100 g of formula: ${esc(pair.numLabel)} / ${esc(pair.denLabel)}${pair.soap ? `; lye index ${flRxFmtIndex(index)}` : ''}">${num.toFixed(3)} / ${den.toFixed(3)} eq</span>
|
|
428
|
+
${pair.soap ? _flRxConcHtml(rows, t) + _flRxMissHtml(f.composition) : ''}
|
|
429
|
+
<button type="button" class="fl-rx-target${t ? ' is-set' : ''}" onclick="flRxOpenTarget('${escJsAttr(f.id)}','${escJsAttr(pair.key)}')" title="${t ? 'Change or clear the target' : pair.soap ? 'Set a target superfat; the strip turns green inside it, amber outside' : 'Set a target index; the strip turns green inside it, amber outside'}">${t ? esc(_flRxTargetText(t, pair)) : '+ target'}</button>
|
|
430
|
+
<button type="button" class="btn btn-secondary btn-sm fl-rx-solve-btn" onclick="${pro ? `flRxOpenSolve('${escJsAttr(f.id)}','${escJsAttr(pair.key)}')` : `proUpsell('reactive.solve')`}" title="${pair.soap ? 'Work out the lye for a target superfat, and the water for a lye concentration' : 'Work out the amount that hits a target index'}">Solve…${pro ? '' : ' <span class="fl-pro" aria-hidden="true"></span>'}</button>
|
|
287
431
|
</div>`;
|
|
288
432
|
}).join('');
|
|
289
433
|
const open = _flRxSolveOpen[f.id];
|
|
290
434
|
const solve = open && found.some(x => x.pair.key === open.pair) ? _flRxSolveRowHtml(f, open) : '';
|
|
291
|
-
return `<div class="fl-rx-strip" id="fl-rx-strip-${esc(f.id)}"><span class="fl-rx-kicker"
|
|
435
|
+
return `<div class="fl-rx-strip" id="fl-rx-strip-${esc(f.id)}"><span class="fl-rx-kicker">${kicker}</span>${chips}${kit}</div>${solve}`;
|
|
292
436
|
}
|
|
293
437
|
// formulations.js holds the strip in #fl-rx-wrap-<id>; a target or the Solve row redraws only that.
|
|
294
438
|
function flRxStripWrapHtml(f) { return f ? `<div class="fl-rx-wrap" id="fl-rx-wrap-${esc(f.id)}">${flRxStripHtml(f)}</div>` : ''; }
|
|
@@ -302,6 +446,18 @@ function flRxOpenTarget(fId, key) {
|
|
|
302
446
|
const f = getFormulation(fId), pair = FL_RX_PAIRS.find(p => p.key === key);
|
|
303
447
|
if (!f || !pair) return;
|
|
304
448
|
const t = flRxTarget(f, key);
|
|
449
|
+
if (pair.soap) {
|
|
450
|
+
showModal('Target · Superfat', `
|
|
451
|
+
<div class="form-grid" style="grid-template-columns:1fr 1fr 1fr;gap:12px">
|
|
452
|
+
<div class="form-group"><label for="fl-rx-t-index">Superfat, %</label><input id="fl-rx-t-index" type="number" step="any" value="${esc(t ? String(+(100 - t.index).toFixed(2)) : '5')}"></div>
|
|
453
|
+
<div class="form-group"><label for="fl-rx-t-tol">± band</label><input id="fl-rx-t-tol" type="number" step="any" min="0" value="${esc(t && t.tol != null ? String(t.tol) : '1')}"></div>
|
|
454
|
+
<div class="form-group"><label for="fl-rx-t-conc">Lye concentration, %</label><input id="fl-rx-t-conc" type="number" step="any" min="0" max="100" placeholder="e.g. 33" value="${esc(t && t.conc != null ? String(t.conc) : '')}"></div>
|
|
455
|
+
</div>
|
|
456
|
+
<p class="fl-rx-note">Green inside the band, amber outside; lye excess is always red. Batches of this formula use it too.</p>
|
|
457
|
+
${t ? `<button type="button" class="btn btn-secondary btn-sm" onclick="flRxSaveTarget('${escJsAttr(fId)}','${escJsAttr(key)}',true)">Clear target</button>` : ''}`,
|
|
458
|
+
() => flRxSaveTarget(fId, key, false), false, null, 'Save target');
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
305
461
|
showModal(`Target · ${pair.label}`, `
|
|
306
462
|
<div class="form-grid" style="grid-template-columns:1fr 1fr;gap:12px">
|
|
307
463
|
<div class="form-group"><label for="fl-rx-t-index">Index</label><input id="fl-rx-t-index" type="number" step="any" min="0" value="${esc(t ? String(t.index) : '100')}"></div>
|
|
@@ -315,12 +471,22 @@ function flRxSaveTarget(fId, key, clear) {
|
|
|
315
471
|
const f = getFormulation(fId);
|
|
316
472
|
if (!f) return false;
|
|
317
473
|
let list = ((f.reactiveTargets || []).filter(t => t && t.pair !== key));
|
|
474
|
+
const pair = FL_RX_PAIRS.find(p => p.key === key);
|
|
318
475
|
if (!clear) {
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
476
|
+
let idx = _flRxNum((document.getElementById('fl-rx-t-index') || {}).value);
|
|
477
|
+
const tol = _flRxNum((document.getElementById('fl-rx-t-tol') || {}).value);
|
|
478
|
+
const entry = { pair: key, tol: tol != null && tol >= 0 ? tol : 0 };
|
|
479
|
+
if (pair && pair.soap) {
|
|
480
|
+
// Typed as superfat, kept as the index (5 % → 95), so the band and batches read it like any other pair.
|
|
481
|
+
if (idx == null || idx >= 100 || idx < -50) { toast('Enter a superfat below 100 %.'); return false; }
|
|
482
|
+
idx = +(100 - idx).toFixed(4);
|
|
483
|
+
const conc = _flRxNum((document.getElementById('fl-rx-t-conc') || {}).value);
|
|
484
|
+
if (conc != null && (conc <= 0 || conc >= 100)) { toast('Enter a lye concentration between 0 and 100 %.'); return false; }
|
|
485
|
+
if (conc != null) entry.conc = conc;
|
|
486
|
+
} else if (idx == null || idx <= 0) { toast('Enter a target index above 0.'); return false; }
|
|
487
|
+
entry.index = idx;
|
|
488
|
+
list = list.concat([entry]);
|
|
322
489
|
}
|
|
323
|
-
const pair = FL_RX_PAIRS.find(p => p.key === key);
|
|
324
490
|
updateFormulation(fId, { reactiveTargets: list.length ? list : undefined, versionNote: `${clear ? 'Cleared' : 'Set'} the ${pair ? pair.label : 'reactive'} target` });
|
|
325
491
|
if (clear && typeof closeModal === 'function') closeModal();
|
|
326
492
|
_flRxRefreshStrip(fId);
|
|
@@ -365,6 +531,48 @@ function _flRxSolveCalc(comp, pairKey, rowIdx, target, keepQs) {
|
|
|
365
531
|
if (qs != null && qs < 0) return { error: 'qs' };
|
|
366
532
|
return { amount: a, from: a0, qsIdx: qi >= 0 && qi !== rowIdx ? qi : -1, qsAmount: qs, qsFrom: q0, index: _flRxIndexWith(withA(a), pair) };
|
|
367
533
|
}
|
|
534
|
+
// Soap: the amount of one water row at which the lye concentration is `conc` %. Concentration falls as water grows, so
|
|
535
|
+
// a bisection through the same rows the strip reads (units, densities, wt% basis).
|
|
536
|
+
function flRxSolveWater(comp, rowIdx, conc) {
|
|
537
|
+
const run = () => {
|
|
538
|
+
const row = (comp || [])[rowIdx];
|
|
539
|
+
if (!row || !(conc > 0 && conc < 100)) return { error: 'bad' };
|
|
540
|
+
const a0 = _flRxNum(row.amount) || 0;
|
|
541
|
+
const withA = a => comp.map((c, i) => (i === rowIdx ? { ...c, amount: a } : c));
|
|
542
|
+
const g = a => { const v = flRxLyeConc(_flRxRows(withA(a))); return v == null ? NaN : v - conc; };
|
|
543
|
+
let lo = 0, hi = Math.max(a0, 1) * 2, glo = g(lo), ghi = g(hi), grow = 0;
|
|
544
|
+
if (!Number.isFinite(glo)) { lo = Math.max(a0, 1) * 1e-6; glo = g(lo); }
|
|
545
|
+
while (Number.isFinite(glo) && Number.isFinite(ghi) && glo * ghi > 0 && grow++ < 40) { hi *= 2; ghi = g(hi); }
|
|
546
|
+
if (!(Number.isFinite(glo) && Number.isFinite(ghi)) || glo * ghi > 0) return { error: 'unreachable' };
|
|
547
|
+
for (let i = 0; i < 80; i++) { const mid = (lo + hi) / 2, gm = g(mid); if (!Number.isFinite(gm)) break; if (gm * glo > 0) { lo = mid; glo = gm; } else hi = mid; }
|
|
548
|
+
const mid = (lo + hi) / 2, sig = mid > 0 ? Math.min(6, Math.ceil(-Math.log10(mid)) + 2) : 0;
|
|
549
|
+
const dec = Math.max(2, ((String(row.amount).split('.')[1]) || '').length, sig);
|
|
550
|
+
const a = +mid.toFixed(dec);
|
|
551
|
+
return { amount: a, from: a0, conc: flRxLyeConc(_flRxRows(withA(a))) };
|
|
552
|
+
};
|
|
553
|
+
return typeof _tpWithSubMemo === 'function' ? _tpWithSubMemo(run) : run();
|
|
554
|
+
}
|
|
555
|
+
// The rows that hold water (by CAS or a Water group), by composition index.
|
|
556
|
+
function _flRxWaterRows(comp) {
|
|
557
|
+
const rows = _flRxRows(comp), out = [];
|
|
558
|
+
let k = 0;
|
|
559
|
+
(comp || []).forEach((c, i) => {
|
|
560
|
+
if (!c || !(c.ingredientId || c.formulationId)) return;
|
|
561
|
+
const r = rows[k++];
|
|
562
|
+
if (r && r.ing && _flRxNum(r.ing.h2o) > 0) out.push(i);
|
|
563
|
+
});
|
|
564
|
+
return out;
|
|
565
|
+
}
|
|
566
|
+
// A soap Solve: lye first (with the q.s. row when asked), then water on the result. Pure.
|
|
567
|
+
function flRxSolveSoap(comp, st) {
|
|
568
|
+
const r = flRxSolve(comp, st.pair, st.row, st.target, st.keepQs);
|
|
569
|
+
if (r.error) return { lye: r };
|
|
570
|
+
const comp1 = comp.map((c, i) => (i === st.row ? { ...c, amount: r.amount } : i === r.qsIdx ? { ...c, amount: r.qsAmount } : c));
|
|
571
|
+
if (st.conc == null || st.wrow == null || st.wrow < 0) return { lye: r, comp: comp1 };
|
|
572
|
+
const w = flRxSolveWater(comp1, st.wrow, st.conc);
|
|
573
|
+
if (w.error) return { lye: r, water: w, comp: comp1 };
|
|
574
|
+
return { lye: r, water: w, comp: comp1.map((c, i) => (i === st.wrow ? { ...c, amount: w.amount } : c)) };
|
|
575
|
+
}
|
|
368
576
|
function flRxOpenSolve(fId, key) {
|
|
369
577
|
const f = getFormulation(fId), pair = FL_RX_PAIRS.find(p => p.key === key);
|
|
370
578
|
if (!f || !pair) return;
|
|
@@ -374,7 +582,15 @@ function flRxOpenSolve(fId, key) {
|
|
|
374
582
|
const num = rows.find(i => (flRxRowEq(f.composition).get(i) || []).some(x => pair.num.includes(x.group)));
|
|
375
583
|
const row = num != null ? num : rows[0];
|
|
376
584
|
const t = flRxTarget(f, key);
|
|
377
|
-
_flRxSolveOpen[fId] = { pair: key, row, tag: typeof flRowTag === 'function' ? flRowTag(f.composition, row) : '', target: t ? +t.index : 100, keepQs: _flRxQsIdx(f.composition) >= 0 };
|
|
585
|
+
_flRxSolveOpen[fId] = { pair: key, row, tag: typeof flRowTag === 'function' ? flRowTag(f.composition, row) : '', target: t ? +t.index : (pair.soap ? 95 : 100), keepQs: _flRxQsIdx(f.composition) >= 0 };
|
|
586
|
+
if (pair.soap) {
|
|
587
|
+
const w = _flRxWaterRows(f.composition);
|
|
588
|
+
// Water by concentration when the formula holds water: the target's, else the 33 % most bars start from.
|
|
589
|
+
Object.assign(_flRxSolveOpen[fId], { wrow: w.length ? w[0] : -1, conc: w.length ? ((t && _flRxNum(t.conc)) || 33) : null,
|
|
590
|
+
// Setting the water by concentration and keeping the total from a water q.s. row pull against each other:
|
|
591
|
+
// the water wins, so "keep the total" starts off when the q.s. row is water.
|
|
592
|
+
keepQs: _flRxQsIdx(f.composition) >= 0 && !w.includes(_flRxQsIdx(f.composition)) });
|
|
593
|
+
}
|
|
378
594
|
_flRxRefreshStrip(fId);
|
|
379
595
|
}
|
|
380
596
|
function _flRxRowName(c) {
|
|
@@ -383,7 +599,9 @@ function _flRxRowName(c) {
|
|
|
383
599
|
return r ? (r.name || r.uid) : 'a row'; // a kit's Part A / Part B is a sub-formula row
|
|
384
600
|
}
|
|
385
601
|
function _flRxSolveRowHtml(f, st) {
|
|
386
|
-
const
|
|
602
|
+
const pair0 = FL_RX_PAIRS.find(p => p.key === st.pair);
|
|
603
|
+
if (pair0 && pair0.soap) return _flRxSoapSolveRowHtml(f, st);
|
|
604
|
+
const pair = pair0, comp = f.composition || [];
|
|
387
605
|
const rows = _flRxSolvableRows(f, pair), qi = _flRxQsFor(comp, st.row);
|
|
388
606
|
const r = flRxSolve(comp, st.pair, st.row, st.target, st.keepQs && qi >= 0);
|
|
389
607
|
const c = comp[st.row] || {}, unit = esc(c.unit || '');
|
|
@@ -416,10 +634,52 @@ function _flRxSolveRowHtml(f, st) {
|
|
|
416
634
|
</span>
|
|
417
635
|
</div>`;
|
|
418
636
|
}
|
|
637
|
+
// The soap Solve row: superfat by changing the lye, then lye concentration by changing a water row.
|
|
638
|
+
function _flRxSoapSolveRowHtml(f, st) {
|
|
639
|
+
const pair = FL_RX_PAIRS.find(p => p.key === st.pair), comp = f.composition || [];
|
|
640
|
+
const rows = _flRxSolvableRows(f, pair).filter(i => (flRxRowEq(comp).get(i) || []).some(x => x.group === 'base'));
|
|
641
|
+
const waters = _flRxWaterRows(comp), qi = _flRxQsFor(comp, st.row);
|
|
642
|
+
const res = flRxSolveSoap(comp, { ...st, keepQs: st.keepQs && qi >= 0 });
|
|
643
|
+
const r = res.lye, w = res.water, c = comp[st.row] || {}, sf = 100 - st.target;
|
|
644
|
+
const move = (name, from, to, unit) => `${esc(name)} ${+from} → <b>${esc(to)}</b> ${esc(unit || '')} <span class="fl-rx-dim">(${to - from >= 0 ? '+' : ''}${+(to - from).toFixed(4)})</span>`;
|
|
645
|
+
let out, ok = false;
|
|
646
|
+
if (r.error === 'unreachable') out = `<span class="fl-rx-warn">${esc(_flRxRowName(c))} alone can’t reach ${_flRxPct(sf)} % superfat.</span>`;
|
|
647
|
+
else if (r.error === 'qs') out = '<span class="fl-rx-warn">The q.s. row would go below 0.</span>';
|
|
648
|
+
else if (r.error) out = '<span class="fl-rx-warn">Enter a superfat below 100 %.</span>';
|
|
649
|
+
else {
|
|
650
|
+
const lo = _flRxNum(c.minAmount), hi = _flRxNum(c.maxAmount), outRange = (lo != null && r.amount < lo) || (hi != null && r.amount > hi);
|
|
651
|
+
const wc = st.wrow >= 0 ? comp[st.wrow] : null;
|
|
652
|
+
out = move(_flRxRowName(c), r.from, r.amount, c.unit)
|
|
653
|
+
+ (r.qsIdx >= 0 ? ` <span class="fl-rx-dim">· ${esc(_flRxRowName(comp[r.qsIdx]))} ${+r.qsFrom} → ${r.qsAmount}</span>` : '')
|
|
654
|
+
+ (w && !w.error && wc ? ` · ${move(_flRxRowName(wc), _flRxNum(wc.amount) || 0, w.amount, wc.unit)}` : '')
|
|
655
|
+
+ (w && w.error ? ` <span class="fl-rx-warn">${w.error === 'bad' ? 'Enter a lye concentration between 0 and 100 %.' : `${esc(_flRxRowName(wc))} alone can’t reach ${_flRxPct(st.conc)} %.`}</span>` : '')
|
|
656
|
+
+ (res.comp ? ` <span class="fl-rx-dim">· total ${+res.comp.reduce((s, x) => s + (_flRxNum(x.amount) || 0), 0).toFixed(2)}</span>` : '')
|
|
657
|
+
+ (outRange ? ` <span class="fl-rx-warn">outside its range (${lo ?? '…'}–${hi ?? '…'})</span>` : '');
|
|
658
|
+
ok = !outRange && !(w && w.error);
|
|
659
|
+
}
|
|
660
|
+
const opt = (i, cur) => `<option value="${i}"${i === cur ? ' selected' : ''}>${esc(_flRxRowName(comp[i]))}</option>`;
|
|
661
|
+
const fid = escJsAttr(f.id);
|
|
662
|
+
return `<div class="fl-rx-solve" id="fl-rx-solve-${esc(f.id)}">
|
|
663
|
+
<b>Solve</b>
|
|
664
|
+
<label>superfat <input type="number" step="any" value="${esc(String(+sf.toFixed(4)))}" oninput="_flRxSolveSet('${fid}','superfat',this.value)" onkeydown="if(event.key==='Enter'&&!event.isComposing)flRxApplySolve('${fid}')"> %</label>
|
|
665
|
+
<label>by changing <select onchange="_flRxSolveSet('${fid}','row',this.value)">${rows.map(i => opt(i, st.row)).join('')}</select></label>
|
|
666
|
+
${waters.length ? `<label>lye concentration <input type="number" step="any" min="0" max="100" placeholder="keep" value="${esc(st.conc == null ? '' : String(st.conc))}" oninput="_flRxSolveSet('${fid}','conc',this.value)" onkeydown="if(event.key==='Enter'&&!event.isComposing)flRxApplySolve('${fid}')"> %</label>
|
|
667
|
+
<label>by changing <select onchange="_flRxSolveSet('${fid}','wrow',this.value)">${waters.map(i => opt(i, st.wrow)).join('')}</select></label>` : ''}
|
|
668
|
+
<span class="fl-rx-result" id="fl-rx-result-${esc(f.id)}">${out}</span>
|
|
669
|
+
${qi >= 0 ? `<label class="fl-rx-check"><input type="checkbox"${st.keepQs ? ' checked' : ''} onchange="_flRxSolveSet('${fid}','keepQs',this.checked)"> keep the total (from the q.s. row)</label>` : ''}
|
|
670
|
+
<span class="fl-rx-solve-act">
|
|
671
|
+
<button type="button" class="btn btn-secondary btn-sm" onclick="flRxOpenSolve('${fid}','${escJsAttr(st.pair)}')">Cancel</button>
|
|
672
|
+
<button type="button" class="btn btn-primary btn-sm" onclick="flRxApplySolve('${fid}')"${ok ? '' : ' disabled'}>Apply</button>
|
|
673
|
+
</span>
|
|
674
|
+
</div>`;
|
|
675
|
+
}
|
|
419
676
|
function _flRxSolveSet(fId, k, v) {
|
|
420
677
|
const st = _flRxSolveOpen[fId], f = getFormulation(fId);
|
|
421
678
|
if (!st || !f) return;
|
|
422
|
-
if (k === '
|
|
679
|
+
if (k === 'superfat') { const n = _flRxNum(v); st.target = n == null ? 0 : 100 - n; k = 'target'; }
|
|
680
|
+
else if (k === 'conc') { const n = _flRxNum(v); st.conc = n; k = 'target'; }
|
|
681
|
+
else if (k === 'wrow') st.wrow = +v;
|
|
682
|
+
else if (k === 'target') st.target = _flRxNum(v) || 0;
|
|
423
683
|
else if (k === 'row') { st.row = +v; st.tag = typeof flRowTag === 'function' ? flRowTag(f.composition, st.row) : ''; }
|
|
424
684
|
else st.keepQs = !!v;
|
|
425
685
|
if (k === 'target') {
|
|
@@ -439,12 +699,22 @@ function flRxApplySolve(fId) {
|
|
|
439
699
|
if (!st || !f) return;
|
|
440
700
|
const at = typeof flRowAt === 'function' ? flRowAt(f.composition, st.row, st.tag, () => renderFormulationDetail(fId)) : st.row;
|
|
441
701
|
if (at < 0) return;
|
|
442
|
-
const r = flRxSolve(f.composition, st.pair, at, st.target, st.keepQs && _flRxQsFor(f.composition, at) >= 0);
|
|
443
|
-
if (r.error) return;
|
|
444
702
|
const pair = FL_RX_PAIRS.find(p => p.key === st.pair);
|
|
703
|
+
const keep = st.keepQs && _flRxQsFor(f.composition, at) >= 0;
|
|
704
|
+
let comp, label;
|
|
705
|
+
if (pair.soap) {
|
|
706
|
+
const res = flRxSolveSoap(f.composition, { ...st, row: at, keepQs: keep });
|
|
707
|
+
if (res.lye.error || !res.comp || (res.water && res.water.error)) return;
|
|
708
|
+
comp = res.comp;
|
|
709
|
+
label = `Solved superfat ${_flRxPct(100 - st.target)} %: ${_flRxRowName(f.composition[at])} ${+res.lye.from} → ${res.lye.amount}`
|
|
710
|
+
+ (res.water ? `; lye concentration ${_flRxPct(st.conc)} %: ${_flRxRowName(f.composition[st.wrow])} ${+(_flRxNum((f.composition[st.wrow] || {}).amount) || 0)} → ${res.water.amount}` : '');
|
|
711
|
+
} else {
|
|
712
|
+
const r = flRxSolve(f.composition, st.pair, at, st.target, keep);
|
|
713
|
+
if (r.error) return;
|
|
714
|
+
comp = f.composition.map((c, i) => (i === at ? { ...c, amount: r.amount } : i === r.qsIdx ? { ...c, amount: r.qsAmount } : c));
|
|
715
|
+
label = `Solved ${pair.label} ${flRxFmtIndex(st.target)}: ${_flRxRowName(f.composition[at])} ${+r.from} → ${r.amount}`;
|
|
716
|
+
}
|
|
445
717
|
const prev = JSON.parse(JSON.stringify(f.composition || []));
|
|
446
|
-
const comp = f.composition.map((c, i) => (i === at ? { ...c, amount: r.amount } : i === r.qsIdx ? { ...c, amount: r.qsAmount } : c));
|
|
447
|
-
const label = `Solved ${pair.label} ${flRxFmtIndex(st.target)}: ${_flRxRowName(f.composition[at])} ${+r.from} → ${r.amount}`;
|
|
448
718
|
delete _flRxSolveOpen[fId];
|
|
449
719
|
updateFormulation(fId, { composition: comp, versionNote: label });
|
|
450
720
|
renderFormulationDetail(fId);
|
|
@@ -457,25 +727,34 @@ function flRxBatchStripHtml(b) {
|
|
|
457
727
|
if (!b) return '';
|
|
458
728
|
const f = (typeof flBatchFormula === 'function' ? flBatchFormula(b) : db.formulations.find(x => x.id === b.formulationId));
|
|
459
729
|
const hasActual = Array.isArray(b.actualComposition) && b.actualComposition.length;
|
|
460
|
-
const comp = hasActual ? b.actualComposition : (f ? f.composition : []);
|
|
730
|
+
const comp = hasActual ? flRxAsActive(b.actualComposition) : (f ? f.composition : []);
|
|
461
731
|
const found = flRxPairsFor(comp);
|
|
462
732
|
if (!found.length) return '';
|
|
463
|
-
|
|
733
|
+
const kicker = found.every(x => x.pair.soap) ? 'Soap' : 'Reactive balance';
|
|
734
|
+
if (flRxMixedUnits(comp)) return `<div class="fl-rx-strip" id="fl-rx-bstrip-${esc(b.id)}"><span class="fl-rx-kicker">${kicker}</span><span class="fl-rx-warn">Rows in different units (% and g, or mL without a density): put them on one basis for an index.</span></div>`;
|
|
464
735
|
const pro = typeof hasFeature !== 'function' || hasFeature('reactive.solve');
|
|
465
736
|
const planned = f && hasActual && !flRxMixedUnits(f.composition) ? flRxPairsFor(f.composition) : [];
|
|
737
|
+
const rows = _flRxRows(comp);
|
|
466
738
|
const chips = found.map(({ pair, index }) => {
|
|
467
|
-
const t = flRxTarget(f, pair.key), band = flRxBand(index, t);
|
|
468
|
-
|
|
739
|
+
const t = flRxTarget(f, pair.key), band = flRxBand(index, t), bad = flRxLyeExcess(pair, index);
|
|
740
|
+
// Soap reads in superfat (%), everything else in index; the arrow follows the number shown.
|
|
741
|
+
const show = v => (pair.soap ? _flRxPct(flRxShown(pair, v)) + ' %' : flRxFmtIndex(v));
|
|
742
|
+
const p = planned.find(x => x.pair.key === pair.key);
|
|
743
|
+
const d = p && p.index != null && index != null ? (pair.soap ? +_flRxPct(flRxShown(pair, index)) - +_flRxPct(flRxShown(pair, p.index)) : +flRxFmtIndex(index) - +flRxFmtIndex(p.index)) : null; // the difference of the two numbers shown
|
|
469
744
|
const vs = !hasActual ? '<span class="fl-rx-dim">planned (nothing weighed yet)</span>'
|
|
470
|
-
: pro ? (p ? `<span class="fl-rx-dim">planned ${
|
|
471
|
-
: `as weighed <b>${
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
745
|
+
: pro ? (p ? `<span class="fl-rx-dim">planned ${show(p.index)}</span> · as weighed <b>${show(index)}</b>${d != null && Math.abs(d) >= 0.05 ? ` <span class="fl-rx-delta">${d < 0 ? '▼' : '▲'}${flRxFmtIndex(Math.abs(d))}</span>` : ''}` : `as weighed <b>${show(index)}</b>`)
|
|
746
|
+
: `as weighed <b>${show(index)}</b> <button type="button" class="fl-rx-target" onclick="proUpsell('reactive.solve')" title="Set it against the plan">vs planned <span class="fl-pro" aria-hidden="true"></span></button>`;
|
|
747
|
+
// Lye excess is red on every tier: it is a safety reading, not a comparison with the plan.
|
|
748
|
+
const cls = bad ? ' is-bad' : (band && (pro || !hasActual) ? ' is-' + band : '');
|
|
749
|
+
const below = pair.soap ? (index > t?.index ? 'below ' : 'above ') : (index < t?.index ? 'below ' : 'above ');
|
|
750
|
+
return `<div class="fl-rx-pair${cls}" data-rx-pair="${esc(pair.key)}">
|
|
751
|
+
<span class="fl-rx-name">${esc(pair.label)}</span>${!hasActual ? ` <span class="fl-rx-idx"><b>${show(index)}</b></span>` : ''}
|
|
752
|
+
<span class="fl-rx-idx">${vs}${bad ? ' <span class="fl-rx-bad">lye excess</span>' : ''}</span>
|
|
753
|
+
${pair.soap ? _flRxConcHtml(rows, t) + _flRxMissHtml(comp) : ''}
|
|
754
|
+
${t && (pro || !hasActual) ? `<span class="fl-rx-dim">${esc(band === 'off' ? below : '')}${esc(_flRxTargetText(t, pair))}</span>` : ''}
|
|
476
755
|
</div>`;
|
|
477
756
|
}).join('');
|
|
478
|
-
return `<div class="fl-rx-strip" id="fl-rx-bstrip-${esc(b.id)}"><span class="fl-rx-kicker"
|
|
757
|
+
return `<div class="fl-rx-strip" id="fl-rx-bstrip-${esc(b.id)}"><span class="fl-rx-kicker">${kicker}</span>${chips}${flRxKitHtml(comp, hasActual ? 'Mix as weighed' : 'Mix ratio')}</div>`;
|
|
479
758
|
}
|
|
480
759
|
function flRxRefreshBatchStrip(batchId) {
|
|
481
760
|
const el = document.getElementById('fl-rx-bwrap-' + batchId);
|
|
@@ -487,8 +766,10 @@ function flRxRefreshBatchStrip(batchId) {
|
|
|
487
766
|
// The form's picker names the value and the box beside it carries the unit (Jun, 28 Oct: "make this card prettier"),
|
|
488
767
|
// so the unit is said once: AHEW [42.6 g/eq], Amine value [660 mg KOH/g].
|
|
489
768
|
const _FL_RX_FORM_PICK = { eew: 'EEW', ahew: 'AHEW', eqw: 'Equivalent weight', ohv: 'OH number', av: 'Acid value', amv: 'Amine value',
|
|
769
|
+
sap: 'SAP value', sapnaoh: 'NaOH SAP', sapkoh: 'KOH SAP', naohpct: 'NaOH content', kohpct: 'KOH content',
|
|
490
770
|
ncopct: 'NCO content', wpct: 'Water content', mmol: 'Groups per gram', f: 'Groups per molecule' };
|
|
491
771
|
const _FL_RX_FORM_UNIT = { eew: 'g/eq', ahew: 'g/eq', eqw: 'g/eq', ohv: 'mg KOH/g', av: 'mg KOH/g', amv: 'mg KOH/g',
|
|
772
|
+
sap: 'mg KOH/g', sapnaoh: 'g NaOH/g', sapkoh: 'g KOH/g', naohpct: '%', kohpct: '%',
|
|
492
773
|
ncopct: '%', wpct: '%', mmol: 'mmol/g', f: 'per molecule' };
|
|
493
774
|
function _flRxBasisOpts(group, cur) {
|
|
494
775
|
return (FL_RX_GROUPS[group] || FL_RX_GROUPS.epoxy).bases.map(k => `<option value="${k}"${k === cur ? ' selected' : ''}>${esc(_FL_RX_FORM_PICK[k] || FL_RX_BASES[k].label)}</option>`).join('');
|
|
@@ -510,7 +791,7 @@ function flRxFormSectionHtml(ing) {
|
|
|
510
791
|
<div class="fl-rx-frows" id="fl-rx-frows">${list.map(_flRxFormRowHtml).join('')}</div>
|
|
511
792
|
<div class="fl-rx-fhead">
|
|
512
793
|
<button type="button" class="btn btn-secondary btn-sm" onclick="_flRxFormAdd()">+ Add group</button>
|
|
513
|
-
<span class="fl-rx-note" data-tip="EEW, AHEW, OH number, NCO %, acid or amine value; or groups per molecule (with the MW)
|
|
794
|
+
<span class="fl-rx-note" data-tip="EEW, AHEW, OH number, NCO %, acid or amine value, an oil's SAP value; or groups per molecule (with the MW). NaOH and KOH count as lye by CAS.">As the datasheet quotes it, or groups per molecule for a pure chemical.</span>
|
|
514
795
|
</div>
|
|
515
796
|
</div>`;
|
|
516
797
|
}
|
|
@@ -573,6 +854,8 @@ function _flRxFormCalc(el) {
|
|
|
573
854
|
else conv.textContent = '';
|
|
574
855
|
return;
|
|
575
856
|
}
|
|
857
|
+
// A soap calculator's 0.135 typed as mg KOH/g reads 0.0024 meq/g: almost no lye. Say so.
|
|
858
|
+
if (basis === 'sap' && _flRxNum(value.value) < 1) { conv.textContent = 'Looks like g/g: pick NaOH SAP'; conv.className = 'fl-rx-fconv is-warn'; conv.setAttribute('data-tip', 'A SAP value in mg KOH/g is about 130–260; 0.13–0.19 is grams of NaOH per gram of oil.'); return; }
|
|
576
859
|
// The chip: the result, and with groups per molecule the datasheet term it stands for. The arithmetic on hover.
|
|
577
860
|
conv.className = 'fl-rx-fconv is-on';
|
|
578
861
|
conv.textContent = basis === 'f' ? `${flRxTermText(group, meq)} · ${flRxFmt(meq)} meq/g` : `${flRxFmt(meq)} meq/g`;
|
|
@@ -602,10 +885,21 @@ const FL_RX_CSV = [
|
|
|
602
885
|
{ key: 'rx:nco', label: 'NCO %', group: 'nco', basis: 'ncopct', match: /^(nco\s*%?|nco\s*content|%\s*nco)\s*([(\[,].*)?$/i },
|
|
603
886
|
{ key: 'rx:av', label: 'Acid value (mg KOH/g)', group: 'cooh', basis: 'av', match: /^(av|acid\s*(value|number|no\.?))\s*([(\[,].*)?$/i },
|
|
604
887
|
{ key: 'rx:amv', label: 'Amine value (mg KOH/g)', group: 'amine', basis: 'amv', match: /^(amine\s*(value|number|no\.?))\s*([(\[,].*)?$/i },
|
|
888
|
+
// Soap: "SAP" / "Saponification value" is mg KOH/g on a datasheet; "NaOH SAP" / "KOH SAP" are a soap calculator's g/g.
|
|
889
|
+
{ key: 'rx:sapnaoh', label: 'NaOH SAP (g/g)', group: 'ester', basis: 'sapnaoh', match: /^(naoh\s*sap|sap\s*\(?naoh\)?)\s*([(\[,].*)?$/i },
|
|
890
|
+
{ key: 'rx:sapkoh', label: 'KOH SAP (g/g)', group: 'ester', basis: 'sapkoh', match: /^(koh\s*sap\s*([(\[,].*)?|sap\s*\(koh\))\s*$/i },
|
|
891
|
+
// Not "SAP number" / "SAP no.": an ERP's material number. A bare "SAP" column must hold a plausible value (below).
|
|
892
|
+
{ key: 'rx:sap', label: 'SAP value (mg KOH/g)', group: 'ester', basis: 'sap', match: /^(sap(\s*value)?|saponification\s*(value|number|no\.?))\s*([(\[,].*)?$/i },
|
|
605
893
|
];
|
|
606
894
|
// Moves rx:* fields of an import row into reactiveGroups, merged over the existing record's (same group replaced).
|
|
607
895
|
function flRxCsvFold(data, existing) {
|
|
608
|
-
const add = FL_RX_CSV.filter(c => typeof data[c.key] === 'number' && data[c.key] > 0).map(c =>
|
|
896
|
+
const add = FL_RX_CSV.filter(c => typeof data[c.key] === 'number' && data[c.key] > 0).map(c => {
|
|
897
|
+
const v = data[c.key];
|
|
898
|
+
// A SAP column: under 1 is a soap calculator's g NaOH per g; over 500 mg KOH/g is no oil (an ERP number): skipped.
|
|
899
|
+
if (c.basis === 'sap') return v < 1 ? { group: c.group, basis: 'sapnaoh', value: v } : v <= 500 ? { group: c.group, basis: 'sap', value: v } : null;
|
|
900
|
+
if ((c.basis === 'sapnaoh' || c.basis === 'sapkoh') && v >= 1) return null;
|
|
901
|
+
return { group: c.group, basis: c.basis, value: v };
|
|
902
|
+
}).filter(Boolean);
|
|
609
903
|
FL_RX_CSV.forEach(c => { delete data[c.key]; });
|
|
610
904
|
if (!add.length) return data;
|
|
611
905
|
const keep = ((existing && existing.reactiveGroups) || []).filter(g => g && !add.some(a => a.group === g.group));
|
|
@@ -614,5 +908,6 @@ function flRxCsvFold(data, existing) {
|
|
|
614
908
|
}
|
|
615
909
|
|
|
616
910
|
if (typeof module !== 'undefined' && module.exports) {
|
|
617
|
-
module.exports = { FL_RX_BASES, FL_RX_GROUPS, FL_RX_PAIRS, flRxSubViewFields, flRxKitRatio, flRxMeq, flRxIngMeq, flRxTermText, flRxViewFields, flRxEval, flRxSolve, flRxBand, flRxFmt, flRxCsvFold
|
|
911
|
+
module.exports = { FL_RX_BASES, FL_RX_GROUPS, FL_RX_PAIRS, flRxSubViewFields, flRxKitRatio, flRxMeq, flRxIngMeq, flRxTermText, flRxViewFields, flRxEval, flRxSolve, flRxBand, flRxFmt, flRxCsvFold,
|
|
912
|
+
flRxShown, flRxLyeExcess, flRxLyeConc, flRxBalance, flRxSolveWater, flRxSolveSoap, flRxLyeKind, flRxLyeFrac, flRxMissingSap, flRxAsActive };
|
|
618
913
|
}
|
|
@@ -1887,6 +1887,22 @@ function _tpPresetCatalog() {
|
|
|
1887
1887
|
formula: '100 * SUM(row.amount * ing.amine) / SUM(row.amount * ing.cooh)',
|
|
1888
1888
|
description: 'Amine equivalents per 100 acid equivalents, for waterborne resins. From amine value and acid value.',
|
|
1889
1889
|
},
|
|
1890
|
+
// Soap (1 Dec): lye against the oils' SAP values, read as superfat (the strip's number); lye concentration is the
|
|
1891
|
+
// lye's share of lye + water (water by CAS, or an ingredient's Water group: 1 meq/g of h2o = 9.008 mg of water).
|
|
1892
|
+
{
|
|
1893
|
+
group: 'Reactive',
|
|
1894
|
+
name: 'Superfat',
|
|
1895
|
+
unit: '%',
|
|
1896
|
+
formula: '100 - 100 * SUM(row.amount * ing.base) / SUM(row.amount * ing.ester)',
|
|
1897
|
+
description: 'Oil left unsaponified: 5 % means 5 % less lye than the oils take. Below 0 is lye excess. From SAP values; NaOH and KOH by CAS (recipe amounts are pure lye).',
|
|
1898
|
+
},
|
|
1899
|
+
{
|
|
1900
|
+
group: 'Reactive',
|
|
1901
|
+
name: 'Lye concentration',
|
|
1902
|
+
unit: '%',
|
|
1903
|
+
formula: '100 * SUM(row.amount * ing.lyeMass) / (SUM(row.amount * ing.lyeMass) + 0.009008 * SUM(row.amount * ing.h2o))',
|
|
1904
|
+
description: 'Pure lye as a share of lye + water. Water counts by CAS; give other ingredients (a lye solution, sodium lactate) a Water group.',
|
|
1905
|
+
},
|
|
1890
1906
|
{
|
|
1891
1907
|
group: 'Reactive',
|
|
1892
1908
|
name: 'Blend EEW',
|