formlab-mcp 0.7.2 → 0.7.4

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
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.2",
5
+ "version": "0.7.4",
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.2",
11
+ "version": "0.7.4",
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): 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 ? e.actualComposition : ((f && f.composition) || []);
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 (…)");
@@ -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,
@@ -200,7 +202,7 @@ const get_formulation = {
200
202
  const get_fragrance_compliance = {
201
203
  definition: {
202
204
  name: 'get_fragrance_compliance',
203
- description: 'A formulation\'s fragrance compliance as FormLab\'s Fragrance tab computes it (Pro; live workspace only): each fragrance material\'s % in the finished product against its IFRA limit for the product category (through sub-formulas), the highest dosage that passes and the material that limits it, and the EU fragrance allergens summed across materials with the ones to name on the label (above 0.001% leave-on, 0.01% rinse-off). Every limit is one the lab typed from a supplier\'s IFRA certificate; FormLab holds no IFRA limits of its own, so a material with no limit or declaration on file is reported as unknown and state is then "incomplete", never "conforms". Optional what-if inputs (not saved): category (IFRA product category, e.g. "5A" body lotion, "4" fine fragrance), use ("leave-on" | "rinse-off"), dosage (percent of a fragrance oil in the finished product). The result is based on the certificates on file and is not a certification: say so when you report it.',
205
+ description: 'A formulation\'s fragrance compliance as FormLab\'s Fragrance tab computes it (Pro; live workspace only): each fragrance material\'s % in the finished product against its IFRA limit for the product category (through sub-formulas), the highest dosage that passes and the material that limits it, and the EU fragrance allergens summed across materials with the ones to name on the label (above 0.001% leave-on, 0.01% rinse-off; category 12, candles and air care with no skin contact, needs no product use: allergens.applies is false there). Every limit is one the lab typed from a supplier\'s IFRA certificate; FormLab holds no IFRA limits of its own, so a material with no limit or declaration on file is reported as unknown and state is then "incomplete", never "conforms". Optional what-if inputs (not saved): category (IFRA product category, e.g. "5A" body lotion, "4" fine fragrance), use ("leave-on" | "rinse-off"), dosage (percent of a fragrance oil in the finished product). The result is based on the certificates on file and is not a certification: say so when you report it.',
204
206
  inputSchema: {
205
207
  type: 'object',
206
208
  properties: {
@@ -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 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
  };
@@ -33,6 +33,8 @@ const FL_FR_USES = { 'leave-on': 'Leave-on', 'rinse-off': 'Rinse-off' };
33
33
  // Label when the allergen in the finished product is ABOVE this (% w/w): Annex III, column h.
34
34
  const FL_FR_LABEL_OVER = { 'leave-on': 0.001, 'rinse-off': 0.01 };
35
35
  // A stored or passed value is a use only when it is one of the two keys themselves: FL_FR_USES['constructor'] is truthy.
36
+ // Category 12 (candles, air care) has no skin contact: the cosmetic leave-on / rinse-off labelling does not apply.
37
+ const _frgUseApplies = (cat) => String(cat || '').toUpperCase() !== '12';
36
38
  const _frgIsUse = (v) => typeof v === 'string' && Object.prototype.hasOwnProperty.call(FL_FR_USES, v);
37
39
 
38
40
  // The individually labelled fragrance allergens: Annex III of Regulation (EC) No 1223/2009 as amended by Regulation
@@ -279,7 +281,7 @@ function flFrCompute(f, opts) {
279
281
  st.use = _frgIsUse(st.use) ? st.use : '';
280
282
  st.dosage = _frgNum(st.dosage) > 0 && _frgNum(st.dosage) <= FL_FR_DOSAGE_MAX ? _frgNum(st.dosage) : 100;
281
283
  const out = { has: false, category: st.category, use: st.use, dosage: st.dosage, rootOil: false, rows: [], others: [], noLimit: [], noDecl: [],
282
- noSource: [], unresolved: 0, max: [], allergens: [], unlisted: [], toLabel: [], over: [], verdict: 'setup', why: [] };
284
+ noSource: [], unresolved: 0, max: [], allergens: [], unlisted: [], toLabel: [], over: [], verdict: 'setup', why: [], useApplies: _frgUseApplies(st.category) };
283
285
  if (!f) return out;
284
286
  const wk = _frgWalk(f), k = st.dosage / 100;
285
287
  out.rootOil = wk.rootOil; out.unresolved = wk.unresolved.length;
@@ -372,14 +374,14 @@ function flFrCompute(f, opts) {
372
374
 
373
375
  const n = (a, one, many) => a.length + ' ' + (a.length === 1 ? one : many);
374
376
  if (!st.category) out.why.push('Choose the product category.');
375
- if (!st.use) out.why.push('Choose leave-on or rinse-off.');
377
+ if (!st.use && out.useApplies) out.why.push('Choose leave-on or rinse-off.');
376
378
  if (out.over.length) out.why.push(n(out.over, 'material is', 'materials are') + ' over the limit.');
377
379
  if (out.noLimit.length) out.why.push(n(out.noLimit, 'material has', 'materials have') + ' no limit on file for category ' + st.category + '.');
378
380
  if (out.noDecl.length) out.why.push(n(out.noDecl, 'material has', 'materials have') + ' no allergen declaration.');
379
381
  if (out.noSource.length) out.why.push(n(out.noSource, 'entry has', 'entries have') + ' no source document.');
380
382
  if (out.unresolved) out.why.push('Part of the composition could not be weighed.');
381
383
  out.verdict = !st.category ? 'setup' : out.over.length ? 'over'
382
- : (!st.use || out.noLimit.length || out.noDecl.length || out.noSource.length || out.unresolved) ? 'unknown' : 'conforms';
384
+ : ((!st.use && out.useApplies) || out.noLimit.length || out.noDecl.length || out.noSource.length || out.unresolved) ? 'unknown' : 'conforms';
383
385
  return out;
384
386
  }
385
387
  // A food, drink or supplement: IFRA and the cosmetic allergen list do not apply to it.
@@ -477,7 +479,7 @@ function flFrSummary(f, opts) {
477
479
  reasons: c.why.slice(),
478
480
  unknown: { noLimit: c.noLimit.slice(), noDeclaration: c.noDecl.slice(), noSourceDocument: c.noSource.map(x => `${x.name} (${x.what})`), notChecked: c.others.slice() },
479
481
  allergens: {
480
- use: c.use, threshold: thr, complete: !c.noDecl.length && !!c.use,
482
+ use: c.use, applies: c.useApplies !== false, threshold: thr, complete: !c.noDecl.length && (!!c.use || c.useApplies === false),
481
483
  toLabel: c.toLabel.slice(),
482
484
  rows: c.allergens.map(a => ({ name: a.name, cas: a.cas, pctInProduct: +a.pct.toPrecision(6), label: a.label, from: a.sources.map(x => x.name) })),
483
485
  notOnEuList: c.unlisted.map(a => ({ name: a.name, cas: a.cas, pctInProduct: +a.pct.toPrecision(6) })),
@@ -502,7 +504,8 @@ function _frgStatementBlocks(f, table) {
502
504
  s.materials.map(m => ({ name: m.name, pct: p(m.pctInProduct), limit: m.limit, status: m.status, amendment: m.amendment || '—', document: m.document || 'None on file' })))}
503
505
  ${s.unknown.notChecked.length ? `<p class="muted">Not fragrance materials, not checked: ${e(s.unknown.notChecked.join(', '))}.</p>` : ''}`;
504
506
  const a = s.allergens;
505
- const lead = !a.use ? 'Leave-on or rinse-off is not set on the formula, so the label column cannot be decided.'
507
+ const lead = !a.use && !a.applies ? 'Cosmetic allergen labelling (leave-on or rinse-off) does not apply to category 12, no skin contact.'
508
+ : !a.use ? 'Leave-on or rinse-off is not set on the formula, so the label column cannot be decided.'
506
509
  : a.toLabel.length ? `To name on the label (above ${a.threshold}% in a ${a.use} product): ${a.toLabel.join(', ')}.` : `None above ${a.threshold}% in a ${a.use} product.`;
507
510
  const rows = a.rows.map(r => ({ name: r.name, cas: r.cas || '—', pct: p(r.pctInProduct), label: r.label == null ? '—' : r.label ? 'Label' : 'Below', from: r.from.join(', ') }))
508
511
  .concat(a.notOnEuList.map(r => ({ name: r.name, cas: r.cas || '—', pct: p(r.pctInProduct), label: 'Not on the EU list', from: '' })));
@@ -541,7 +544,7 @@ function flFrAiLine(f) {
541
544
  const mats = s.materials.slice(0, 12).map(m => `${m.name} ${_frgPct(m.pctInProduct)}% vs ${m.limit}${m.status === 'Pass' || m.status === 'Not restricted' ? '' : ' [' + m.status + ']'}`).join(', ');
542
545
  const al = s.allergens;
543
546
  return `${s.statement} ${max ? 'Max dosage: ' + max + '. ' : ''}Materials (% in product vs limit): ${mats}${s.materials.length > 12 ? ` (+${s.materials.length - 12} more)` : ''}.`
544
- + (al.use ? ` Allergens to label (${al.use}, above ${al.threshold}%): ${al.toLabel.length ? al.toLabel.join(', ') : 'none'}${al.missing.length ? ` [incomplete: ${al.missing.length} without a declaration]` : ''}.` : ' Allergen labelling undecided: leave-on or rinse-off not set.')
547
+ + (al.use ? ` Allergens to label (${al.use}, above ${al.threshold}%): ${al.toLabel.length ? al.toLabel.join(', ') : 'none'}${al.missing.length ? ` [incomplete: ${al.missing.length} without a declaration]` : ''}.` : al.applies ? ' Allergen labelling undecided: leave-on or rinse-off not set.' : ' Cosmetic allergen labelling does not apply (category 12, no skin contact).')
545
548
  + ` ${s.basis}`;
546
549
  } catch (_) { return ''; }
547
550
  }
@@ -714,7 +717,7 @@ function _frgControlsHtml(f, c) {
714
717
  return `<div class="card"><div class="card-header"><h2>Product</h2><span id="fr-saved" class="fl-saved-tick" role="status"></span></div>
715
718
  <div class="card-body nl-form fr-form-side">
716
719
  <label>IFRA category<select id="fr-cat-in" onchange="flFrSet('${id}','category',this.value)"><option value="">Choose…</option>${FL_FR_CATEGORIES.map(k => `<option value="${k}"${c.category === k ? ' selected' : ''}>${_frgEsc(_frgCatText(k))}</option>`).join('')}</select></label>
717
- <label>Product use<span class="nl-unit"><span class="fl-seg-group sm" role="group" aria-label="Product use">${seg('leave-on')}${seg('rinse-off')}</span></span></label>
720
+ ${c.useApplies || c.use ? `<label>Product use<span class="nl-unit"><span class="fl-seg-group sm" role="group" aria-label="Product use">${seg('leave-on')}${seg('rinse-off')}</span></span></label>` : ''}
718
721
  ${c.rootOil ? `<label data-tip="How much of this oil goes into the finished product. 100 checks it as sold.">Dosage in the product<span class="nl-unit"><input id="fr-dose-in" type="number" min="0" max="100" step="any" inputmode="decimal" value="${st.dosage !== 100 ? _frgEsc(String(st.dosage)) : ''}" placeholder="100" onchange="flFrSet('${id}','dosage',this.value)"><em>%</em></span></label>` : ''}
719
722
  ${c.others.length ? `<div class="fr-dim" data-tip="${_frgEsc(c.others.slice(0, 12).join(', ') + (c.others.length > 12 ? ` +${c.others.length - 12} more` : ''))}">${c.others.length} other ${c.others.length === 1 ? 'ingredient is not a fragrance material' : 'ingredients are not fragrance materials'}. Not checked.</div>` : ''}
720
723
  </div></div>`;
@@ -749,7 +752,7 @@ function flFrTabHtml(f) {
749
752
  <div class="card"><div class="card-header"><h2>IFRA</h2></div>
750
753
  <div class="card-body">${_frgVerdictHtml(c)}${_frgMaxHtml(c)}${_frgIfraTableHtml(c)}</div></div>
751
754
  <div class="card"><div class="card-header"><h2>Allergens <span class="nl-sub">EU</span></h2></div>
752
- <div class="card-body">${c.use ? `<div class="fr-dim fr-lead">${c.toLabel.length ? `<strong>${c.toLabel.length} to name on the label</strong> (above ${FL_FR_LABEL_OVER[c.use]}% ${c.use}).` : `None above ${FL_FR_LABEL_OVER[c.use]}% ${c.use}.`}${c.noDecl.length ? ' Incomplete: ' + c.noDecl.length + ' without a declaration.' : ''}</div>` : '<div class="fr-dim fr-lead">Choose leave-on or rinse-off to see which to label.</div>'}
755
+ <div class="card-body">${c.use ? `<div class="fr-dim fr-lead">${c.toLabel.length ? `<strong>${c.toLabel.length} to name on the label</strong> (above ${FL_FR_LABEL_OVER[c.use]}% ${c.use}).` : `None above ${FL_FR_LABEL_OVER[c.use]}% ${c.use}.`}${c.noDecl.length ? ' Incomplete: ' + c.noDecl.length + ' without a declaration.' : ''}</div>` : `<div class="fr-dim fr-lead">${c.useApplies ? 'Choose leave-on or rinse-off to see which to label.' : 'Cosmetic allergen labelling does not apply to category 12 (no skin contact).'}</div>`}
753
756
  ${_frgAllergenTableHtml(c)}
754
757
  <div class="fr-dim fr-legal">Based on the certificates and declarations on file. Not a certification.</div></div></div>
755
758
  </div>
@@ -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
  };
@@ -44,10 +52,13 @@ const FL_RX_GROUPS = {
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
54
  h2o: { label: 'Water (reacts with NCO)', bases: ['wpct', 'mmol'], term: 'wpct' },
55
+ // Soap (1 Dec): oils, butters and waxes carry a SAP value; NaOH and KOH are known by CAS (times their purity).
56
+ ester: { label: 'Saponifiable (SAP value)', 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,19 @@ 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, at the ingredient's purity (% active; 100 when blank). A stored Lye row still wins.
96
+ const FL_RX_LYE_CAS = { '1310-73-2': 40.0, '1310-58-3': 56.1 };
97
+ function flRxLyeKind(ing) {
98
+ const mw = ing && FL_RX_LYE_CAS[String(ing.cas || '').trim()];
99
+ return mw === 40.0 ? 'NaOH' : mw === 56.1 ? 'KOH' : '';
100
+ }
82
101
  function flRxIngMeq(ing) {
83
102
  const out = {};
103
+ const lyeMw = ing && FL_RX_LYE_CAS[String(ing.cas || '').trim()];
104
+ if (lyeMw && !((ing.reactiveGroups || []).some(g => g && g.group === 'base'))) {
105
+ const pur = _flRxNum(ing.purity);
106
+ out.base = (1000 / lyeMw) * ((pur != null && pur > 0 && pur <= 100) ? pur / 100 : 1);
107
+ }
84
108
  // Water itself counts without being told (a foam's blowing water); a stored h2o row still wins.
85
109
  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
110
  ((ing && ing.reactiveGroups) || []).forEach(g => {
@@ -91,9 +115,12 @@ function flRxIngMeq(ing) {
91
115
  return out;
92
116
  }
93
117
  // 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], b = g && FL_RX_BASES[g.term];
96
- if (!b || meq == null) return '';
118
+ function flRxTermText(group, meq, basis) {
119
+ const g = FL_RX_GROUPS[group];
120
+ // A SAP value reads in the form it was entered: soap calculators' NaOH SAP 0.135, a datasheet's SAP 190.
121
+ const b = FL_RX_BASES[(basis && /^sap/.test(basis)) ? basis : (g && g.term)];
122
+ if (!g || !b || meq == null) return '';
123
+ if (group === 'base' && !basis) return `Lye ${flRxFmt(meq)} meq/g`;
97
124
  const v = flRxFmt(b.fromMeq(meq));
98
125
  if (g.term === 'mmol') return `${g.label} ${flRxFmt(meq)} mmol/g`;
99
126
  return `${b.short} ${v}${b.unit ? ' ' + b.unit : ''}`;
@@ -141,12 +168,13 @@ function flRxChipsHtml(ing) {
141
168
  if (!rows.length) return '';
142
169
  return rows.map(g => {
143
170
  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>`;
171
+ 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
172
  }).join('');
146
173
  }
147
174
  function flRxListText(ing) {
148
175
  const meq = flRxIngMeq(ing);
149
- return Object.keys(meq).map(k => flRxTermText(k, meq[k])).join(' · ');
176
+ const stored = (ing && ing.reactiveGroups) || [];
177
+ return Object.keys(meq).map(k => { const e = stored.find(x => x && x.group === k); return flRxTermText(k, meq[k], e && e.basis); }).join(' · ');
150
178
  }
151
179
 
152
180
  // ---- A composition's pairs and index ----
@@ -161,6 +189,42 @@ function flRxEval(pair, rows) {
161
189
  const num = _flRxSum(rows, pair.num), den = _flRxSum(rows, pair.den);
162
190
  return { num, den, index: den > 0 ? 100 * num / den : null };
163
191
  }
192
+ // ---- Soap (1 Dec, Jun): the lye pair reads as superfat, and the lye's share of lye + water ----
193
+ // Superfat = 100 − index: 5 % less lye than the oils take is index 95. Below 0 is lye excess, which burns skin, so it
194
+ // shows red with or without a target (the one exception to "no target, no color").
195
+ function flRxShown(pair, index) { return (pair && pair.soap && index != null) ? 100 - index : index; }
196
+ function flRxLyeExcess(pair, index) { return !!(pair && pair.soap && index != null && index > 100.05); }
197
+ // Lye concentration as weighed: the lye rows' mass over lye + water. Water counts by CAS, or by an ingredient's Water
198
+ // group (1 meq/g of h2o = 9.008 mg of water per g). null when there is no lye or no water.
199
+ function flRxLyeConc(rows) {
200
+ let lye = 0, water = 0;
201
+ (rows || []).forEach(r => {
202
+ if (!r || !r.ing || !(r.amount > 0)) return;
203
+ if (_flRxNum(r.ing.base) > 0) lye += r.amount;
204
+ const h = _flRxNum(r.ing.h2o);
205
+ if (h > 0) water += r.amount * h * 0.009008;
206
+ });
207
+ return lye > 0 && water > 0 ? 100 * lye / (lye + water) : null;
208
+ }
209
+ function _flRxPct(v) { return (v == null || !Number.isFinite(v)) ? '—' : String(Math.round(v * 10) / 10); }
210
+ // Every reacting pair of a composition as plain numbers (the AI context and the MCP server read this, so app, AI and
211
+ // MCP say the same): [{ pair, label, index, superfat?, lyeExcess?, lyeConcentration? }], or { error } for mixed units.
212
+ function flRxBalance(comp) {
213
+ const found = flRxPairsFor(comp);
214
+ if (!found.length) return [];
215
+ if (flRxMixedUnits(comp)) return { error: 'Rows in different units (% and g, or mL without a density): no index.' };
216
+ const rows = _flRxRows(comp);
217
+ return found.map(({ pair, index }) => {
218
+ const o = { pair: pair.key, label: pair.label, index: index == null ? null : +index.toFixed(2) };
219
+ if (pair.soap) {
220
+ o.superfat = index == null ? null : +(100 - index).toFixed(2);
221
+ o.lyeExcess = flRxLyeExcess(pair, index);
222
+ const c = flRxLyeConc(rows);
223
+ o.lyeConcentration = c == null ? null : +c.toFixed(2);
224
+ }
225
+ return o;
226
+ });
227
+ }
164
228
  // One basis or the index means nothing: % rows next to grams, or mL without a density, don't share a unit.
165
229
  function _flRxUnitBasis(u) { u = String(u || '').trim().toLowerCase(); return /^(wt\s*%|%|w\/w|%\s*w\/w|w\/w\s*%)$/.test(u) ? '%' : u; }
166
230
  // Two checks: the rows as typed (% beside g, which _tpBuildRows turns into one wt% set), and as built (mL it couldn't
@@ -188,7 +252,18 @@ function flRxBand(index, t) {
188
252
  if (!t || index == null || !Number.isFinite(_flRxNum(t.index))) return '';
189
253
  return Math.abs(index - t.index) <= (_flRxNum(t.tol) || 0) + 1e-9 ? 'ok' : 'off';
190
254
  }
191
- function _flRxTargetText(t) { return t ? `target ${flRxFmtIndex(+t.index)}${_flRxNum(t.tol) ? ' ± ' + flRxFmtIndex(+t.tol) : ''}` : ''; }
255
+ function _flRxTargetText(t, pair) {
256
+ if (!t) return '';
257
+ if (pair && pair.soap) return `target ${_flRxPct(100 - +t.index)}${_flRxNum(t.tol) ? ' ± ' + flRxFmtIndex(+t.tol) : ''} %`;
258
+ return `target ${flRxFmtIndex(+t.index)}${_flRxNum(t.tol) ? ' ± ' + flRxFmtIndex(+t.tol) : ''}`;
259
+ }
260
+ // The soap chip's lye concentration, with its target when one is set (amber more than half a point off).
261
+ function _flRxConcHtml(rows, t) {
262
+ const c = flRxLyeConc(rows), want = t ? _flRxNum(t.conc) : null;
263
+ if (c == null) return '';
264
+ const off = want != null && Math.abs(c - want) > 0.5;
265
+ 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>`;
266
+ }
192
267
  // A 2K kit: a formula whose rows are all sub-formulas (Part A, Part B …). Its mix ratio, the first part = 100: by
193
268
  // weight, and by volume when every part has a density (the parts' planning densities).
194
269
  function flRxKitRatio(comp) {
@@ -257,7 +332,7 @@ function flRxSubRowEq(sub, parentAmount, groups) {
257
332
  flRxRowEq(sub.composition, groups).forEach((list, i) => out.set(i, list.map(x => ({ ...x, eq: x.eq * k, amount: x.amount * k }))));
258
333
  return out;
259
334
  }
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' };
335
+ 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
336
  function flRxEqCellHtml(list) {
262
337
  if (!list || !list.length) return '<span class="fl-rx-dim">—</span>';
263
338
  // 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 +350,27 @@ function flRxStripHtml(f) {
275
350
  if (!found.length) return '';
276
351
  const pro = typeof hasFeature !== 'function' || hasFeature('reactive.solve');
277
352
  const kit = flRxKitHtml(f.composition, '');
278
- if (flRxMixedUnits(f.composition)) return `<div class="fl-rx-strip" id="fl-rx-strip-${esc(f.id)}"><span class="fl-rx-kicker">Reactive balance</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>`;
353
+ const kicker = found.every(x => x.pair.soap) ? 'Soap' : 'Reactive balance';
354
+ 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>`;
355
+ const rows = _flRxRows(f.composition);
279
356
  const chips = found.map(({ pair, num, den, index }) => {
280
- const t = flRxTarget(f, pair.key), band = flRxBand(index, t);
281
- return `<div class="fl-rx-pair${band ? ' is-' + band : ''}" data-rx-pair="${esc(pair.key)}">
357
+ const t = flRxTarget(f, pair.key), band = flRxBand(index, t), bad = flRxLyeExcess(pair, index);
358
+ const cls = bad ? ' is-bad' : band ? ' is-' + band : '';
359
+ const value = pair.soap
360
+ ? `<span class="fl-rx-idx"><b>${_flRxPct(flRxShown(pair, index))}</b> %${bad ? ' <span class="fl-rx-bad">lye excess</span>' : ''}</span>`
361
+ : `<span class="fl-rx-idx">${/^nco:/.test(pair.key) ? '' : 'index '}<b>${flRxFmtIndex(index)}</b>${pair.unit ? ' ' + pair.unit : ''}</span>`;
362
+ return `<div class="fl-rx-pair${cls}" data-rx-pair="${esc(pair.key)}">
282
363
  <span class="fl-rx-name">${esc(pair.label)}</span>
283
- <span class="fl-rx-idx">${/^nco:/.test(pair.key) ? '' : 'index '}<b>${flRxFmtIndex(index)}</b>${pair.unit ? ' ' + pair.unit : ''}</span>
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
- <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' : 'Set a target index; the strip turns green inside it, amber outside'}">${t ? esc(_flRxTargetText(t)) : '+ target'}</button>
286
- <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="Work out the amount that hits a target index">Solve…${pro ? '' : ' <span class="fl-pro" aria-hidden="true"></span>'}</button>
364
+ ${value}
365
+ <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>
366
+ ${pair.soap ? _flRxConcHtml(rows, t) : ''}
367
+ <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>
368
+ <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
369
  </div>`;
288
370
  }).join('');
289
371
  const open = _flRxSolveOpen[f.id];
290
372
  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">Reactive balance</span>${chips}${kit}</div>${solve}`;
373
+ 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
374
  }
293
375
  // formulations.js holds the strip in #fl-rx-wrap-<id>; a target or the Solve row redraws only that.
294
376
  function flRxStripWrapHtml(f) { return f ? `<div class="fl-rx-wrap" id="fl-rx-wrap-${esc(f.id)}">${flRxStripHtml(f)}</div>` : ''; }
@@ -302,6 +384,18 @@ function flRxOpenTarget(fId, key) {
302
384
  const f = getFormulation(fId), pair = FL_RX_PAIRS.find(p => p.key === key);
303
385
  if (!f || !pair) return;
304
386
  const t = flRxTarget(f, key);
387
+ if (pair.soap) {
388
+ showModal('Target · Superfat', `
389
+ <div class="form-grid" style="grid-template-columns:1fr 1fr 1fr;gap:12px">
390
+ <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>
391
+ <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>
392
+ <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>
393
+ </div>
394
+ <p class="fl-rx-note">Green inside the band, amber outside; lye excess is always red. Batches of this formula use it too.</p>
395
+ ${t ? `<button type="button" class="btn btn-secondary btn-sm" onclick="flRxSaveTarget('${escJsAttr(fId)}','${escJsAttr(key)}',true)">Clear target</button>` : ''}`,
396
+ () => flRxSaveTarget(fId, key, false), false, null, 'Save target');
397
+ return;
398
+ }
305
399
  showModal(`Target · ${pair.label}`, `
306
400
  <div class="form-grid" style="grid-template-columns:1fr 1fr;gap:12px">
307
401
  <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 +409,22 @@ function flRxSaveTarget(fId, key, clear) {
315
409
  const f = getFormulation(fId);
316
410
  if (!f) return false;
317
411
  let list = ((f.reactiveTargets || []).filter(t => t && t.pair !== key));
412
+ const pair = FL_RX_PAIRS.find(p => p.key === key);
318
413
  if (!clear) {
319
- const idx = _flRxNum((document.getElementById('fl-rx-t-index') || {}).value), tol = _flRxNum((document.getElementById('fl-rx-t-tol') || {}).value);
320
- if (idx == null || idx <= 0) { toast('Enter a target index above 0.'); return false; }
321
- list = list.concat([{ pair: key, index: idx, tol: tol != null && tol >= 0 ? tol : 0 }]);
414
+ let idx = _flRxNum((document.getElementById('fl-rx-t-index') || {}).value);
415
+ const tol = _flRxNum((document.getElementById('fl-rx-t-tol') || {}).value);
416
+ const entry = { pair: key, tol: tol != null && tol >= 0 ? tol : 0 };
417
+ if (pair && pair.soap) {
418
+ // Typed as superfat, kept as the index (5 % → 95), so the band and batches read it like any other pair.
419
+ if (idx == null || idx >= 100 || idx < -50) { toast('Enter a superfat below 100 %.'); return false; }
420
+ idx = +(100 - idx).toFixed(4);
421
+ const conc = _flRxNum((document.getElementById('fl-rx-t-conc') || {}).value);
422
+ if (conc != null && (conc <= 0 || conc >= 100)) { toast('Enter a lye concentration between 0 and 100 %.'); return false; }
423
+ if (conc != null) entry.conc = conc;
424
+ } else if (idx == null || idx <= 0) { toast('Enter a target index above 0.'); return false; }
425
+ entry.index = idx;
426
+ list = list.concat([entry]);
322
427
  }
323
- const pair = FL_RX_PAIRS.find(p => p.key === key);
324
428
  updateFormulation(fId, { reactiveTargets: list.length ? list : undefined, versionNote: `${clear ? 'Cleared' : 'Set'} the ${pair ? pair.label : 'reactive'} target` });
325
429
  if (clear && typeof closeModal === 'function') closeModal();
326
430
  _flRxRefreshStrip(fId);
@@ -365,6 +469,48 @@ function _flRxSolveCalc(comp, pairKey, rowIdx, target, keepQs) {
365
469
  if (qs != null && qs < 0) return { error: 'qs' };
366
470
  return { amount: a, from: a0, qsIdx: qi >= 0 && qi !== rowIdx ? qi : -1, qsAmount: qs, qsFrom: q0, index: _flRxIndexWith(withA(a), pair) };
367
471
  }
472
+ // Soap: the amount of one water row at which the lye concentration is `conc` %. Concentration falls as water grows, so
473
+ // a bisection through the same rows the strip reads (units, densities, wt% basis).
474
+ function flRxSolveWater(comp, rowIdx, conc) {
475
+ const run = () => {
476
+ const row = (comp || [])[rowIdx];
477
+ if (!row || !(conc > 0 && conc < 100)) return { error: 'bad' };
478
+ const a0 = _flRxNum(row.amount) || 0;
479
+ const withA = a => comp.map((c, i) => (i === rowIdx ? { ...c, amount: a } : c));
480
+ const g = a => { const v = flRxLyeConc(_flRxRows(withA(a))); return v == null ? NaN : v - conc; };
481
+ let lo = 0, hi = Math.max(a0, 1) * 2, glo = g(lo), ghi = g(hi), grow = 0;
482
+ if (!Number.isFinite(glo)) { lo = Math.max(a0, 1) * 1e-6; glo = g(lo); }
483
+ while (Number.isFinite(glo) && Number.isFinite(ghi) && glo * ghi > 0 && grow++ < 40) { hi *= 2; ghi = g(hi); }
484
+ if (!(Number.isFinite(glo) && Number.isFinite(ghi)) || glo * ghi > 0) return { error: 'unreachable' };
485
+ 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; }
486
+ const mid = (lo + hi) / 2, sig = mid > 0 ? Math.min(6, Math.ceil(-Math.log10(mid)) + 2) : 0;
487
+ const dec = Math.max(2, ((String(row.amount).split('.')[1]) || '').length, sig);
488
+ const a = +mid.toFixed(dec);
489
+ return { amount: a, from: a0, conc: flRxLyeConc(_flRxRows(withA(a))) };
490
+ };
491
+ return typeof _tpWithSubMemo === 'function' ? _tpWithSubMemo(run) : run();
492
+ }
493
+ // The rows that hold water (by CAS or a Water group), by composition index.
494
+ function _flRxWaterRows(comp) {
495
+ const rows = _flRxRows(comp), out = [];
496
+ let k = 0;
497
+ (comp || []).forEach((c, i) => {
498
+ if (!c || !(c.ingredientId || c.formulationId)) return;
499
+ const r = rows[k++];
500
+ if (r && r.ing && _flRxNum(r.ing.h2o) > 0) out.push(i);
501
+ });
502
+ return out;
503
+ }
504
+ // A soap Solve: lye first (with the q.s. row when asked), then water on the result. Pure.
505
+ function flRxSolveSoap(comp, st) {
506
+ const r = flRxSolve(comp, st.pair, st.row, st.target, st.keepQs);
507
+ if (r.error) return { lye: r };
508
+ const comp1 = comp.map((c, i) => (i === st.row ? { ...c, amount: r.amount } : i === r.qsIdx ? { ...c, amount: r.qsAmount } : c));
509
+ if (st.conc == null || st.wrow == null || st.wrow < 0) return { lye: r, comp: comp1 };
510
+ const w = flRxSolveWater(comp1, st.wrow, st.conc);
511
+ if (w.error) return { lye: r, water: w, comp: comp1 };
512
+ return { lye: r, water: w, comp: comp1.map((c, i) => (i === st.wrow ? { ...c, amount: w.amount } : c)) };
513
+ }
368
514
  function flRxOpenSolve(fId, key) {
369
515
  const f = getFormulation(fId), pair = FL_RX_PAIRS.find(p => p.key === key);
370
516
  if (!f || !pair) return;
@@ -374,7 +520,15 @@ function flRxOpenSolve(fId, key) {
374
520
  const num = rows.find(i => (flRxRowEq(f.composition).get(i) || []).some(x => pair.num.includes(x.group)));
375
521
  const row = num != null ? num : rows[0];
376
522
  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 };
523
+ _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 };
524
+ if (pair.soap) {
525
+ const w = _flRxWaterRows(f.composition);
526
+ // Water by concentration when the formula holds water: the target's, else the 33 % most bars start from.
527
+ Object.assign(_flRxSolveOpen[fId], { wrow: w.length ? w[0] : -1, conc: w.length ? ((t && _flRxNum(t.conc)) || 33) : null,
528
+ // Setting the water by concentration and keeping the total from a water q.s. row pull against each other:
529
+ // the water wins, so "keep the total" starts off when the q.s. row is water.
530
+ keepQs: _flRxQsIdx(f.composition) >= 0 && !w.includes(_flRxQsIdx(f.composition)) });
531
+ }
378
532
  _flRxRefreshStrip(fId);
379
533
  }
380
534
  function _flRxRowName(c) {
@@ -383,7 +537,9 @@ function _flRxRowName(c) {
383
537
  return r ? (r.name || r.uid) : 'a row'; // a kit's Part A / Part B is a sub-formula row
384
538
  }
385
539
  function _flRxSolveRowHtml(f, st) {
386
- const pair = FL_RX_PAIRS.find(p => p.key === st.pair), comp = f.composition || [];
540
+ const pair0 = FL_RX_PAIRS.find(p => p.key === st.pair);
541
+ if (pair0 && pair0.soap) return _flRxSoapSolveRowHtml(f, st);
542
+ const pair = pair0, comp = f.composition || [];
387
543
  const rows = _flRxSolvableRows(f, pair), qi = _flRxQsFor(comp, st.row);
388
544
  const r = flRxSolve(comp, st.pair, st.row, st.target, st.keepQs && qi >= 0);
389
545
  const c = comp[st.row] || {}, unit = esc(c.unit || '');
@@ -416,10 +572,52 @@ function _flRxSolveRowHtml(f, st) {
416
572
  </span>
417
573
  </div>`;
418
574
  }
575
+ // The soap Solve row: superfat by changing the lye, then lye concentration by changing a water row.
576
+ function _flRxSoapSolveRowHtml(f, st) {
577
+ const pair = FL_RX_PAIRS.find(p => p.key === st.pair), comp = f.composition || [];
578
+ const rows = _flRxSolvableRows(f, pair).filter(i => (flRxRowEq(comp).get(i) || []).some(x => x.group === 'base'));
579
+ const waters = _flRxWaterRows(comp), qi = _flRxQsFor(comp, st.row);
580
+ const res = flRxSolveSoap(comp, { ...st, keepQs: st.keepQs && qi >= 0 });
581
+ const r = res.lye, w = res.water, c = comp[st.row] || {}, sf = 100 - st.target;
582
+ 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>`;
583
+ let out, ok = false;
584
+ if (r.error === 'unreachable') out = `<span class="fl-rx-warn">${esc(_flRxRowName(c))} alone can’t reach ${_flRxPct(sf)} % superfat.</span>`;
585
+ else if (r.error === 'qs') out = '<span class="fl-rx-warn">The q.s. row would go below 0.</span>';
586
+ else if (r.error) out = '<span class="fl-rx-warn">Enter a superfat below 100 %.</span>';
587
+ else {
588
+ const lo = _flRxNum(c.minAmount), hi = _flRxNum(c.maxAmount), outRange = (lo != null && r.amount < lo) || (hi != null && r.amount > hi);
589
+ const wc = st.wrow >= 0 ? comp[st.wrow] : null;
590
+ out = move(_flRxRowName(c), r.from, r.amount, c.unit)
591
+ + (r.qsIdx >= 0 ? ` <span class="fl-rx-dim">· ${esc(_flRxRowName(comp[r.qsIdx]))} ${+r.qsFrom} → ${r.qsAmount}</span>` : '')
592
+ + (w && !w.error && wc ? ` · ${move(_flRxRowName(wc), _flRxNum(wc.amount) || 0, w.amount, wc.unit)}` : '')
593
+ + (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>` : '')
594
+ + (res.comp ? ` <span class="fl-rx-dim">· total ${+res.comp.reduce((s, x) => s + (_flRxNum(x.amount) || 0), 0).toFixed(2)}</span>` : '')
595
+ + (outRange ? ` <span class="fl-rx-warn">outside its range (${lo ?? '…'}–${hi ?? '…'})</span>` : '');
596
+ ok = !outRange && !(w && w.error);
597
+ }
598
+ const opt = (i, cur) => `<option value="${i}"${i === cur ? ' selected' : ''}>${esc(_flRxRowName(comp[i]))}</option>`;
599
+ const fid = escJsAttr(f.id);
600
+ return `<div class="fl-rx-solve" id="fl-rx-solve-${esc(f.id)}">
601
+ <b>Solve</b>
602
+ <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>
603
+ <label>by changing <select onchange="_flRxSolveSet('${fid}','row',this.value)">${rows.map(i => opt(i, st.row)).join('')}</select></label>
604
+ ${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>
605
+ <label>by changing <select onchange="_flRxSolveSet('${fid}','wrow',this.value)">${waters.map(i => opt(i, st.wrow)).join('')}</select></label>` : ''}
606
+ <span class="fl-rx-result" id="fl-rx-result-${esc(f.id)}">${out}</span>
607
+ ${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>` : ''}
608
+ <span class="fl-rx-solve-act">
609
+ <button type="button" class="btn btn-secondary btn-sm" onclick="flRxOpenSolve('${fid}','${escJsAttr(st.pair)}')">Cancel</button>
610
+ <button type="button" class="btn btn-primary btn-sm" onclick="flRxApplySolve('${fid}')"${ok ? '' : ' disabled'}>Apply</button>
611
+ </span>
612
+ </div>`;
613
+ }
419
614
  function _flRxSolveSet(fId, k, v) {
420
615
  const st = _flRxSolveOpen[fId], f = getFormulation(fId);
421
616
  if (!st || !f) return;
422
- if (k === 'target') st.target = _flRxNum(v) || 0;
617
+ if (k === 'superfat') { const n = _flRxNum(v); st.target = n == null ? 0 : 100 - n; k = 'target'; }
618
+ else if (k === 'conc') { const n = _flRxNum(v); st.conc = n; k = 'target'; }
619
+ else if (k === 'wrow') st.wrow = +v;
620
+ else if (k === 'target') st.target = _flRxNum(v) || 0;
423
621
  else if (k === 'row') { st.row = +v; st.tag = typeof flRowTag === 'function' ? flRowTag(f.composition, st.row) : ''; }
424
622
  else st.keepQs = !!v;
425
623
  if (k === 'target') {
@@ -439,12 +637,22 @@ function flRxApplySolve(fId) {
439
637
  if (!st || !f) return;
440
638
  const at = typeof flRowAt === 'function' ? flRowAt(f.composition, st.row, st.tag, () => renderFormulationDetail(fId)) : st.row;
441
639
  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
640
  const pair = FL_RX_PAIRS.find(p => p.key === st.pair);
641
+ const keep = st.keepQs && _flRxQsFor(f.composition, at) >= 0;
642
+ let comp, label;
643
+ if (pair.soap) {
644
+ const res = flRxSolveSoap(f.composition, { ...st, row: at, keepQs: keep });
645
+ if (res.lye.error || !res.comp || (res.water && res.water.error)) return;
646
+ comp = res.comp;
647
+ label = `Solved superfat ${_flRxPct(100 - st.target)} %: ${_flRxRowName(f.composition[at])} ${+res.lye.from} → ${res.lye.amount}`
648
+ + (res.water ? `; lye concentration ${_flRxPct(st.conc)} %: ${_flRxRowName(f.composition[st.wrow])} ${+(_flRxNum((f.composition[st.wrow] || {}).amount) || 0)} → ${res.water.amount}` : '');
649
+ } else {
650
+ const r = flRxSolve(f.composition, st.pair, at, st.target, keep);
651
+ if (r.error) return;
652
+ comp = f.composition.map((c, i) => (i === at ? { ...c, amount: r.amount } : i === r.qsIdx ? { ...c, amount: r.qsAmount } : c));
653
+ label = `Solved ${pair.label} ${flRxFmtIndex(st.target)}: ${_flRxRowName(f.composition[at])} ${+r.from} → ${r.amount}`;
654
+ }
445
655
  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
656
  delete _flRxSolveOpen[fId];
449
657
  updateFormulation(fId, { composition: comp, versionNote: label });
450
658
  renderFormulationDetail(fId);
@@ -460,22 +668,31 @@ function flRxBatchStripHtml(b) {
460
668
  const comp = hasActual ? b.actualComposition : (f ? f.composition : []);
461
669
  const found = flRxPairsFor(comp);
462
670
  if (!found.length) return '';
463
- if (flRxMixedUnits(comp)) return `<div class="fl-rx-strip" id="fl-rx-bstrip-${esc(b.id)}"><span class="fl-rx-kicker">Reactive balance</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>`;
671
+ const kicker = found.every(x => x.pair.soap) ? 'Soap' : 'Reactive balance';
672
+ 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
673
  const pro = typeof hasFeature !== 'function' || hasFeature('reactive.solve');
465
674
  const planned = f && hasActual && !flRxMixedUnits(f.composition) ? flRxPairsFor(f.composition) : [];
675
+ const rows = _flRxRows(comp);
466
676
  const chips = found.map(({ pair, index }) => {
467
- const t = flRxTarget(f, pair.key), band = flRxBand(index, t);
468
- const p = planned.find(x => x.pair.key === pair.key), d = p && p.index != null && index != null ? +flRxFmtIndex(index) - +flRxFmtIndex(p.index) : null; // the difference of the two numbers shown
677
+ const t = flRxTarget(f, pair.key), band = flRxBand(index, t), bad = flRxLyeExcess(pair, index);
678
+ // Soap reads in superfat (%), everything else in index; the arrow follows the number shown.
679
+ const show = v => (pair.soap ? _flRxPct(flRxShown(pair, v)) + ' %' : flRxFmtIndex(v));
680
+ const p = planned.find(x => x.pair.key === pair.key);
681
+ 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
682
  const vs = !hasActual ? '<span class="fl-rx-dim">planned (nothing weighed yet)</span>'
470
- : pro ? (p ? `<span class="fl-rx-dim">planned ${flRxFmtIndex(p.index)}</span> · as weighed <b>${flRxFmtIndex(index)}</b>${d != null && Math.abs(d) >= 0.05 ? ` <span class="fl-rx-delta">${d < 0 ? '▼' : '▲'}${flRxFmtIndex(Math.abs(d))}</span>` : ''}` : `as weighed <b>${flRxFmtIndex(index)}</b>`)
471
- : `as weighed <b>${flRxFmtIndex(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>`;
472
- return `<div class="fl-rx-pair${band && (pro || !hasActual) ? ' is-' + band : ''}" data-rx-pair="${esc(pair.key)}">
473
- <span class="fl-rx-name">${esc(pair.label)}</span>${!hasActual ? ` <span class="fl-rx-idx"><b>${flRxFmtIndex(index)}</b></span>` : ''}
474
- <span class="fl-rx-idx">${vs}</span>
475
- ${t && (pro || !hasActual) ? `<span class="fl-rx-dim">${esc(band === 'off' ? (index < t.index ? 'below ' : 'above ') : '')}${esc(_flRxTargetText(t))}</span>` : ''}
683
+ : 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>`)
684
+ : `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>`;
685
+ // Lye excess is red on every tier: it is a safety reading, not a comparison with the plan.
686
+ const cls = bad ? ' is-bad' : (band && (pro || !hasActual) ? ' is-' + band : '');
687
+ const below = pair.soap ? (index > t?.index ? 'below ' : 'above ') : (index < t?.index ? 'below ' : 'above ');
688
+ return `<div class="fl-rx-pair${cls}" data-rx-pair="${esc(pair.key)}">
689
+ <span class="fl-rx-name">${esc(pair.label)}</span>${!hasActual ? ` <span class="fl-rx-idx"><b>${show(index)}</b></span>` : ''}
690
+ <span class="fl-rx-idx">${vs}${bad ? ' <span class="fl-rx-bad">lye excess</span>' : ''}</span>
691
+ ${pair.soap ? _flRxConcHtml(rows, t) : ''}
692
+ ${t && (pro || !hasActual) ? `<span class="fl-rx-dim">${esc(band === 'off' ? below : '')}${esc(_flRxTargetText(t, pair))}</span>` : ''}
476
693
  </div>`;
477
694
  }).join('');
478
- return `<div class="fl-rx-strip" id="fl-rx-bstrip-${esc(b.id)}"><span class="fl-rx-kicker">Reactive balance</span>${chips}${flRxKitHtml(comp, hasActual ? 'Mix as weighed' : 'Mix ratio')}</div>`;
695
+ 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
696
  }
480
697
  function flRxRefreshBatchStrip(batchId) {
481
698
  const el = document.getElementById('fl-rx-bwrap-' + batchId);
@@ -487,8 +704,10 @@ function flRxRefreshBatchStrip(batchId) {
487
704
  // The form's picker names the value and the box beside it carries the unit (Jun, 28 Oct: "make this card prettier"),
488
705
  // so the unit is said once: AHEW [42.6 g/eq], Amine value [660 mg KOH/g].
489
706
  const _FL_RX_FORM_PICK = { eew: 'EEW', ahew: 'AHEW', eqw: 'Equivalent weight', ohv: 'OH number', av: 'Acid value', amv: 'Amine value',
707
+ sap: 'SAP value', sapnaoh: 'NaOH SAP', sapkoh: 'KOH SAP', naohpct: 'NaOH content', kohpct: 'KOH content',
490
708
  ncopct: 'NCO content', wpct: 'Water content', mmol: 'Groups per gram', f: 'Groups per molecule' };
491
709
  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',
710
+ sap: 'mg KOH/g', sapnaoh: 'g NaOH/g', sapkoh: 'g KOH/g', naohpct: '%', kohpct: '%',
492
711
  ncopct: '%', wpct: '%', mmol: 'mmol/g', f: 'per molecule' };
493
712
  function _flRxBasisOpts(group, cur) {
494
713
  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 +729,7 @@ function flRxFormSectionHtml(ing) {
510
729
  <div class="fl-rx-frows" id="fl-rx-frows">${list.map(_flRxFormRowHtml).join('')}</div>
511
730
  <div class="fl-rx-fhead">
512
731
  <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) for a pure chemical.">As the datasheet quotes it, or groups per molecule for a pure chemical.</span>
732
+ <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
733
  </div>
515
734
  </div>`;
516
735
  }
@@ -602,6 +821,10 @@ const FL_RX_CSV = [
602
821
  { key: 'rx:nco', label: 'NCO %', group: 'nco', basis: 'ncopct', match: /^(nco\s*%?|nco\s*content|%\s*nco)\s*([(\[,].*)?$/i },
603
822
  { key: 'rx:av', label: 'Acid value (mg KOH/g)', group: 'cooh', basis: 'av', match: /^(av|acid\s*(value|number|no\.?))\s*([(\[,].*)?$/i },
604
823
  { key: 'rx:amv', label: 'Amine value (mg KOH/g)', group: 'amine', basis: 'amv', match: /^(amine\s*(value|number|no\.?))\s*([(\[,].*)?$/i },
824
+ // Soap: "SAP" / "Saponification value" is mg KOH/g on a datasheet; "NaOH SAP" / "KOH SAP" are a soap calculator's g/g.
825
+ { key: 'rx:sapnaoh', label: 'NaOH SAP (g/g)', group: 'ester', basis: 'sapnaoh', match: /^(naoh\s*sap|sap\s*\(?naoh\)?)\s*([(\[,].*)?$/i },
826
+ { key: 'rx:sapkoh', label: 'KOH SAP (g/g)', group: 'ester', basis: 'sapkoh', match: /^(koh\s*sap\s*([(\[,].*)?|sap\s*\(koh\))\s*$/i },
827
+ { key: 'rx:sap', label: 'SAP value (mg KOH/g)', group: 'ester', basis: 'sap', match: /^(sap(\s*(value|number|no\.?))?|saponification\s*(value|number|no\.?))\s*([(\[,].*)?$/i },
605
828
  ];
606
829
  // Moves rx:* fields of an import row into reactiveGroups, merged over the existing record's (same group replaced).
607
830
  function flRxCsvFold(data, existing) {
@@ -614,5 +837,6 @@ function flRxCsvFold(data, existing) {
614
837
  }
615
838
 
616
839
  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 };
840
+ module.exports = { FL_RX_BASES, FL_RX_GROUPS, FL_RX_PAIRS, flRxSubViewFields, flRxKitRatio, flRxMeq, flRxIngMeq, flRxTermText, flRxViewFields, flRxEval, flRxSolve, flRxBand, flRxFmt, flRxCsvFold,
841
+ flRxShown, flRxLyeExcess, flRxLyeConc, flRxBalance, flRxSolveWater, flRxSolveSoap, flRxLyeKind };
618
842
  }
@@ -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 and purity.',
1898
+ },
1899
+ {
1900
+ group: 'Reactive',
1901
+ name: 'Lye concentration',
1902
+ unit: '%',
1903
+ formula: '100 * SUM(row.amount WHERE ing.base > 0) / (SUM(row.amount WHERE ing.base > 0) + 0.009008 * SUM(row.amount * ing.h2o))',
1904
+ description: 'Lye as a share of lye + water, as weighed. Water counts by CAS; give other ingredients a Water group for their water.',
1905
+ },
1890
1906
  {
1891
1907
  group: 'Reactive',
1892
1908
  name: 'Blend EEW',