formlab-mcp 0.6.87 → 0.6.89

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.6.87",
3
+ "version": "0.6.89",
4
4
  "mcpName": "io.github.juliu1980/formlab-mcp",
5
5
  "description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
6
6
  "homepage": "https://formvix.com/mcp",
package/server.json CHANGED
@@ -2,13 +2,13 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.juliu1980/formlab-mcp",
4
4
  "description": "Read-only MCP server for FormLab formulation data: a local export file or your live cloud workspace.",
5
- "version": "0.6.87",
5
+ "version": "0.6.89",
6
6
  "websiteUrl": "https://formvix.com/mcp",
7
7
  "packages": [
8
8
  {
9
9
  "registryType": "npm",
10
10
  "identifier": "formlab-mcp",
11
- "version": "0.6.87",
11
+ "version": "0.6.89",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
@@ -1813,11 +1813,15 @@ async function _mcpAllParameters(entity, entityType, sampleIds, args, db) {
1813
1813
  const shelf = graded ? [] : r.series.filter(se => se.shelfLife && se.shelfLife._pointTotal != null)
1814
1814
  .sort((a, b) => a.shelfLife._pointTotal - b.shelfLife._pointTotal);
1815
1815
  const first = shelf[0] || null;
1816
+ // The app's Control limits on All parameters (12j): points beyond ±3σ per condition (rule 1 only here).
1817
+ const ooc = graded ? [] : r.series.filter(se => se.controlChart && (se.controlChart.outOfControlPoints || []).length)
1818
+ .map(se => ({ condition: se.condition, points: se.controlChart.outOfControlPoints.length }));
1816
1819
  rows.push({
1817
1820
  parameter: p.name, kind: graded ? r.kind : 'numeric', ...(r.unit ? { unit: r.unit } : {}),
1818
1821
  spec: graded ? r.spec : ((r.spec && (r.spec.min != null || r.spec.max != null)) ? { min: r.spec.min, max: r.spec.max } : null),
1819
1822
  conditions: r.series.map(se => se.condition), testDates: r.pointCount,
1820
1823
  outOfSpecNow: failing.length > 0, ...(failing.length ? { outOfSpecConditions: failing } : {}),
1824
+ ...(ooc.length ? { outOfControl: ooc } : {}),
1821
1825
  shelfLife: first ? { condition: first.condition, fromT0Months: first.shelfLife.fromT0Months, ci95FromT0Months: first.shelfLife.ci95FromT0Months,
1822
1826
  verdict: first.shelfLife.verdict, headingToward: first.shelfLife.headingToward } : null,
1823
1827
  _t: first ? first.shelfLife._pointTotal : Infinity,
@@ -1839,7 +1843,7 @@ async function _mcpAllParameters(entity, entityType, sampleIds, args, db) {
1839
1843
  then: ranked.slice(1, 3).map(r => ({ parameter: r.parameter, condition: r.shelfLife.condition, fromT0Months: r.shelfLife.fromT0Months })),
1840
1844
  targetShelfLife: target,
1841
1845
  parameters: rows.map(({ _t, ...r }) => r),
1842
- note: 'Every parameter the entity was tested for, as the app\'s All parameters plot: each judged on its own spec, out of spec now first (the latest test date of any condition failed), then by months to spec. shelfLife = the earliest-crossing condition\'s projection from T0 (point estimate and 95% bound, verdict against targetShelfLife), null = no reportable projection or a ranked / text parameter (those have no regression). limitingParameter = the first to cross spec: it sets the shelf life; then = the next two. For one parameter\'s full analysis (series, drift, control chart, time points, Arrhenius) call get_stability with that parameter.',
1846
+ note: 'Every parameter the entity was tested for, as the app\'s All parameters plot: each judged on its own spec, out of spec now first (the latest test date of any condition failed), then by months to spec. shelfLife = the earliest-crossing condition\'s projection from T0 (point estimate and 95% bound, verdict against targetShelfLife), null = no reportable projection or a ranked / text parameter (those have no regression). limitingParameter = the first to cross spec: it sets the shelf life; then = the next two. outOfControl (when present) = per condition, how many test dates sit beyond that series\' own ±3σ control limits (the app\'s Control limits checkbox on All parameters, which also applies its run and trend rules); it does not change the order. For one parameter\'s full analysis (series, drift, control chart, time points, Arrhenius) call get_stability with that parameter.',
1843
1847
  };
1844
1848
  }
1845
1849
 
@@ -393,6 +393,8 @@ const list_lots = {
393
393
  // 'hold' / 'quarantine' / 'rejected' lots are blocked from auto-consumption;
394
394
  // holdReason explains a manual hold (QC / recall).
395
395
  holdReason: l.holdReason || '',
396
+ // A disposed lot: when, why, how much was written off (status is then "disposed").
397
+ disposal: l.status === 'disposed' ? { date: l.disposedAt || null, by: l.disposedBy || '', reason: l.disposeReason || '', note: l.disposeNote || '', qty: l.disposedQty ?? null } : null,
396
398
  unitCost: (l.unitCost != null && l.unitCost !== '') ? l.unitCost : null,
397
399
  unitCostCcy: l.unitCostCcy || null,
398
400
  ..._lotCoaInfo(l, ingById.get(l.ingredientId)),
package/tools/lab.js CHANGED
@@ -297,6 +297,8 @@ const list_batches = {
297
297
  since_date: { type: 'string', description: 'ISO date (YYYY-MM-DD). Only batches prepared on/after this date.' },
298
298
  best_by_before: { type: 'string', description: 'ISO date (YYYY-MM-DD). Only batches whose best-by falls before this date (today = past best-by). Batches with no best-by are left out.' },
299
299
  lots_expire_first: { type: 'boolean', description: 'When true, only batches that drew from an ingredient lot expiring before the batch\'s best-by (the app\'s ⚠ on Best by).' },
300
+ shipped_to: { type: 'string', description: 'Only batches with a shipment whose note (customer / destination / PO) contains this text, case-insensitive. Use it to find which batch went to a customer.' },
301
+ on_hold: { type: 'boolean', description: 'When true, only finished batches currently on hold (no shipment can be recorded until released).' },
300
302
  limit: { type: 'number', description: 'Max rows (default 50, max 500).' },
301
303
  },
302
304
  },
@@ -318,6 +320,8 @@ const list_batches = {
318
320
  if (args.status && !norm(b.status).includes(norm(args.status))) return false;
319
321
  if (args.origin_only && b.parentBatchId) return false;
320
322
  if (args.since_date && (b.preparedDate || '') < args.since_date) return false;
323
+ if (args.shipped_to && !(Array.isArray(b.stockLedger) && b.stockLedger.some(e => e && e.kind === 'shipment' && norm(e.note).includes(norm(args.shipped_to))))) return false;
324
+ if (args.on_hold && !(b.fgHold && b.fgHold.at)) return false;
321
325
  if (args.best_by_before || args.lots_expire_first) {
322
326
  const bb = _bestByInfo(b, b.formulationId ? indexes.formulationsById.get(b.formulationId) : null);
323
327
  if (!bb) return false;
@@ -385,6 +389,8 @@ const get_batch = {
385
389
  date: e.ts || null, delta: e.delta ?? null, unit: e.unit || b.unit || '', kind: e.kind || '', note: e.note || '',
386
390
  })),
387
391
  shippedQty: (Array.isArray(b.stockLedger) ? b.stockLedger : []).reduce((s, e) => e.kind === 'shipment' ? s + Math.abs(parseFloat(e.delta) || 0) : s, 0),
392
+ // Finished-batch hold: while set, the app records no shipment of this batch (QA / complaint / recall).
393
+ hold: (b.fgHold && b.fgHold.at) ? { since: b.fgHold.at, by: b.fgHold.by || '', reason: b.fgHold.reason || '' } : null,
388
394
  theoreticalParameters: theoreticalParams(getStore().db, 'batch', b.id),
389
395
  };
390
396
  },
package/vendor/cost.js CHANGED
@@ -1716,24 +1716,32 @@ function deviationLegendHtml() {
1716
1716
  // Used by the batch AND sample weigh-outs so both correct identically. This is
1717
1717
  // a bench/weigh-out concept only — composition, cost, and property math keep
1718
1718
  // using the as-declared amounts.
1719
- function effectivePurity(ing) {
1719
+ function effectivePurity(ing, pinLotId) {
1720
1720
  if (!ing) return null;
1721
1721
  const nom = parseFloat(ing.purity);
1722
1722
  if (isFinite(nom) && nom > 0) return nom < 100 ? nom : null;
1723
- // No usable nominal → fall back to a representative active lot with purity.
1723
+ // LP1 (19 Nov): a batch that pins a lot for this ingredient draws that lot first, so its purity is the one weighed.
1724
+ if (pinLotId && typeof db !== 'undefined' && Array.isArray(db.lots)) {
1725
+ const pl = db.lots.find(l => l && l.id === pinLotId && l.ingredientId === ing.id);
1726
+ if (pl && (parseFloat(pl.qtyRemaining) || 0) > 0 && (typeof _lotIsUsable !== 'function' || _lotIsUsable(pl))) {
1727
+ const pp = parseFloat(pl.purity);
1728
+ return (isFinite(pp) && pp > 0 && pp < 100) ? pp : null;
1729
+ }
1730
+ }
1731
+ // No usable nominal → the purity of the lot the next draw takes (the lab's FEFO / FIFO rule over every usable lot),
1732
+ // if that lot has one. It used to pick the first lot WITH a purity, so a trial drum's 68.5% grossed up a batch that
1733
+ // drew a different supplier's lot with none (supplier-swap sim, 19 Nov: +46% SLES). No lot rule (off) → no fallback.
1724
1734
  const lots = (typeof db !== 'undefined' && Array.isArray(db.lots))
1725
- ? db.lots.filter(l => l.ingredientId === ing.id
1726
- && (parseFloat(l.qtyRemaining) || 0) > 0
1727
- && (!l.status || l.status === 'active')
1728
- && l.purity != null && isFinite(parseFloat(l.purity)) && parseFloat(l.purity) > 0)
1735
+ ? db.lots.filter(l => l.ingredientId === ing.id && (parseFloat(l.qtyRemaining) || 0) > 0
1736
+ && (typeof _lotIsUsable === 'function' ? _lotIsUsable(l) : (!l.status || l.status === 'active')))
1729
1737
  : [];
1730
1738
  if (!lots.length) return null;
1731
- lots.sort((a, b) => {
1732
- const ax = a.expiryDate || '9999-12-31', bx = b.expiryDate || '9999-12-31';
1733
- if (ax !== bx) return ax < bx ? -1 : 1;
1734
- return (a.receivedDate || '').localeCompare(b.receivedDate || '');
1735
- });
1736
- const p = parseFloat(lots[0].purity);
1739
+ const strat = (typeof _lotStrategy === 'function') ? _lotStrategy() : 'fefo';
1740
+ if (strat === 'off') return null;
1741
+ const ordered = (typeof sortLotsForConsumption === 'function') ? sortLotsForConsumption(lots, strat === 'fifo' ? 'fifo' : 'fefo')
1742
+ : lots.slice().sort((a, b) => { const ax = a.expiryDate || '9999-12-31', bx = b.expiryDate || '9999-12-31';
1743
+ return ax !== bx ? (ax < bx ? -1 : 1) : (a.receivedDate || '').localeCompare(b.receivedDate || ''); });
1744
+ const p = parseFloat((ordered[0] || {}).purity);
1737
1745
  return (isFinite(p) && p > 0 && p < 100) ? p : null;
1738
1746
  }
1739
1747
 
@@ -1773,12 +1781,12 @@ function lotPurityDeviation(ing, opts) {
1773
1781
  // model — other rows are NOT rebalanced). Returns the amount technicians
1774
1782
  // weigh, the purity used, and the active amount it delivers. Sub-formula rows
1775
1783
  // and rows with no purity data pass through unchanged.
1776
- function correctAmountForPurity(comp, amt) {
1784
+ function correctAmountForPurity(comp, amt, pins) {
1777
1785
  const passthrough = { amount: amt, purity: null, activeAmount: amt };
1778
1786
  if (!comp || !comp.ingredientId || amt == null || !isFinite(amt)) return passthrough;
1779
1787
  const ing = (typeof db !== 'undefined' && Array.isArray(db.ingredients))
1780
1788
  ? db.ingredients.find(i => i.id === comp.ingredientId) : null;
1781
- const p = effectivePurity(ing);
1789
+ const p = effectivePurity(ing, pins && ing ? pins[ing.id] : null);
1782
1790
  if (p == null || !(p > 0) || p >= 100) return passthrough;
1783
1791
  return { amount: amt / (p / 100), purity: p, activeAmount: amt };
1784
1792
  }
@@ -2092,7 +2100,7 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
2092
2100
  return (inAlt != null && isFinite(inAlt)) ? `<strong>${fmt(inAlt)}</strong> <span translate="no" style="color:var(--dk-faint, #94a3b8);font-size:10px">${esc(altUnit)}</span>` : null;
2093
2101
  })();
2094
2102
  const tfoot = `<tr style="border-top:1px solid #dbeafe">
2095
- <td></td><td style="padding:5px 8px;font-weight:600">Total${_volTarget ? ` <span style="font-weight:400;color:var(--dk-faint, #94a3b8);font-size:10.5px" title="Sum of the pure-ingredient volumes in the Planned column. Not a lab quantity — the finished batch is ${esc(w.qty)} ${esc(w.unit)}; the mass in the ≈ column is what the batch weighs.">(pure-ingredient volumes)</span>` : ''}</td>
2103
+ <td></td><td style="padding:5px 8px;font-weight:600">Total${_volTarget ? ` <span style="font-weight:400;color:var(--dk-faint, #94a3b8);font-size:10.5px" title="Sum of ingredient volumes in the Planned column. The finished batch is ${esc(w.qty)} ${esc(w.unit)}.">(pure-ingredient volumes)</span>` : ''}</td>
2096
2104
  <td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;font-weight:${_volTarget ? 400 : 700};color:${_volTarget ? 'var(--dk-faint, #94a3b8)' : 'inherit'}" title="${_volTarget ? `Volumes aren't additive on mixing — this sum has no bench meaning. Finished batch: ${esc(w.qty)} ${esc(w.unit)}.` : ''}">${cv(w.total)}</td>
2097
2105
  ${hasActuals ? `<td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;font-weight:700">${cv(actualTotal)}</td>
2098
2106
  <td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;color:var(--dk-muted, #64748b)">${cvs(totalDelta)}</td>` : ''}
@@ -2243,7 +2251,7 @@ function defaultPercentBasis(formulation, costSummary) {
2243
2251
  // Approximate kg conversion for batch.targetQuantity.unit. If
2244
2252
  // volume, falls back to *assume kg* unless density is known.
2245
2253
  function computeBatchCost(batch, displayCcy = getDisplayCurrency()) {
2246
- const f = db.formulations.find(x => x.id === batch.formulationId);
2254
+ const f = (typeof flBatchFormula === 'function' ? flBatchFormula(batch) : db.formulations.find(x => x.id === batch.formulationId));
2247
2255
  if (!f) return null;
2248
2256
  const perKg = computeFormulationCost(f, displayCcy);
2249
2257
  // Batch size in kg via the shared quantityToKg (mass units convert directly;
@@ -298,18 +298,26 @@ function flNlEuPanelHtml(f, calc) {
298
298
  // What one serving and one container cost to make, from the formula's ingredient cost per kg (computeFormulationCost,
299
299
  // the number the Composition tab totals), the serving's weight and the cooking yield: a kilogram sold took 1 ÷ yield
300
300
  // kilograms of mix. Ingredients only: no packaging, labor or overhead. With a target sell price on the Pricing &
301
- // Margin panel, the same per serving, and the margin. Money is in the price's currency when one is set, else the
302
- // viewer's display currency.
301
+ // Margin panel, the same per serving, and the margin. Money is in the viewer's display currency (the MCP server: the price's
302
+ // currency when one is set).
303
303
  // → { ok, currency, perKgMixed, perKgSold, perServing, perContainer, servings, unpriced: [names],
304
304
  // price: { perKg, perServing, perContainer, profitServing, marginPct } | null } ; ok false: why
305
+ const FL_NL_MAIN = ['energy', 'fat', 'carb', 'protein', 'sodium'];
305
306
  function flNlCost(f) {
306
307
  const out = { ok: false, why: 'nocost', unpriced: [], price: null };
307
308
  if (!f || typeof computeFormulationCost !== 'function') return out;
308
309
  const pr = (f.pricing && typeof f.pricing === 'object') ? f.pricing : {};
309
- const target = parseFloat(pr.targetPrice);
310
- const hasPrice = Number.isFinite(target) && target > 0;
311
- let c = null;
312
- try { c = computeFormulationCost(f, hasPrice && pr.currency ? pr.currency : undefined, 'kg'); } catch (_) { c = null; }
310
+ const target0 = parseFloat(pr.targetPrice);
311
+ const hasPrice = Number.isFinite(target0) && target0 > 0;
312
+ // In the app the card follows the viewer's display currency, the price converted to it (Jun, 17 Nov, 11j: it stayed
313
+ // in the price's USD whatever Settings said). No viewer (the MCP server) or no rate: the price's own currency.
314
+ let c = null, ccy = hasPrice && pr.currency ? pr.currency : undefined, target = target0;
315
+ const disp = typeof window !== 'undefined' && typeof getDisplayCurrency === 'function' ? getDisplayCurrency() : null;
316
+ if (ccy && disp && disp !== ccy) {
317
+ const conv = typeof convertCurrencySync === 'function' ? convertCurrencySync(target0, ccy, disp) : null;
318
+ if (Number.isFinite(conv) && conv > 0) { ccy = disp; target = conv; }
319
+ }
320
+ try { c = computeFormulationCost(f, ccy, 'kg'); } catch (_) { c = null; }
313
321
  if (!c || !Number.isFinite(c.perKg) || !(c.perKg > 0)) return out;
314
322
  const st = _nlSettings(f), sv = flNlServing(f), y = st.yield || 100, n = flNlServingsCount(f);
315
323
  out.ok = true; delete out.why;
@@ -409,7 +417,7 @@ function _nlCostCardHtml(f) {
409
417
  // Three numbers first, the working behind them under it (Jun, 17 Nov: "pretty and organized", not deep).
410
418
  const tile = (label, val, sub, cls) => `<div class="nl-tile${cls ? ' ' + cls : ''}"><div class="nl-tile-l">${label}</div><div class="nl-tile-v">${val}</div><div class="nl-tile-s">${sub}</div></div>`;
411
419
  const tiles = [
412
- tile('Per serving', m(one), `${esc(_nlNum(sv.amount))} ${sv.unit}${extras.length ? ' · with ' + esc(_nlList(extras)) : ''}`),
420
+ tile('Per serving', m(one), `${esc(_nlNum(sv.amount))} ${sv.unit}${extras.length > 1 ? ' · all in' : extras.length ? ' · with ' + esc(extras[0]) : ''}`),
413
421
  k.perContainer != null ? tile('Per container', m(k.perContainer), `${esc(st.servings)} servings`) : tile('Per container', '—', 'Set Servings per container', 'off'),
414
422
  p ? tile('Margin', `${esc(String(+p.marginPct.toFixed(1)))}%`, `${esc(_nlMoney(p.profitServing, k.currency))} per serving`, p.marginPct >= 0 ? 'good' : 'bad')
415
423
  : tile('Margin', '—', 'Add a sell price in Pricing &amp; Margin', 'off'),
@@ -441,9 +449,9 @@ function _nlCostCardHtml(f) {
441
449
  return `<div class="card nl-costcard">
442
450
  <div class="card-header"><h2>Cost</h2><span id="nl-cost-saved" class="fl-saved-tick" role="status"></span></div>
443
451
  <div class="card-body">
444
- ${warn}${idle}
445
452
  <div class="nl-tiles">${tiles}</div>
446
453
  <div class="nl-kv">${grid}</div>
454
+ ${warn}${idle}
447
455
  <div class="nl-dim nl-hint" data-tip="From each ingredient’s price and the amounts in the Composition tab${extras.length ? `, plus the ${_nlList(extras)} you typed` : ''}.${p ? '' : ' Set a target sell price on the Composition tab’s Pricing & Margin panel to see the margin per serving.'}">${extras.length ? esc(_nlList(k.basis).replace(/^i/, 'I')) + '.' : 'Ingredients only.'}</div>
448
456
  </div>
449
457
  </div>
@@ -506,6 +514,28 @@ function flNlEuStatement(f) {
506
514
  return { html: html ? html + '.' : '', text: text ? text + '.' : '', allergens: found, count: items.length };
507
515
  }
508
516
 
517
+ // An ingredient whose NAME says an allergen its chips don't carry (17 Nov: a shake with whey and soy lecithin read "No
518
+ // major US allergens", because neither ingredient had its allergens set). The statement still comes only from the chips;
519
+ // this asks the person to check, and the all-clear line is not shown while any remain.
520
+ const FL_NL_ALLERGEN_WORDS = {
521
+ milk: /\b(milk|whey|casein(ate)?|lactose|butter(milk)?|cream|cheese|yog(h)?urt|ghee|lactalbumin)\b/i,
522
+ eggs: /\b(eggs?|albumen|ovalbumin|egg yolk)\b/i, fish: /\b(fish|anchov(y|ies)|cod|salmon|tuna)\b/i,
523
+ shellfish: /\b(shrimps?|prawns?|crabs?|lobsters?|crayfish|krill)\b/i,
524
+ 'tree-nuts': /\b(almonds?|hazelnuts?|walnuts?|cashews?|pecans?|pistachios?|macadamias?|brazil nuts?|coconut)\b/i,
525
+ peanuts: /\b(peanuts?|groundnuts?|arachis)\b/i, wheat: /\b(wheat|spelt|durum|semolina|farina)\b/i,
526
+ soy: /\b(soy|soya|soybeans?|edamame|tofu)\b/i, sesame: /\b(sesame|tahini)\b/i,
527
+ };
528
+ function flNlAllergenSuspects(f) {
529
+ return _nlStatementItems(f).map(it => {
530
+ const miss = Object.keys(FL_NL_ALLERGEN_WORDS).filter(k => FL_NL_ALLERGEN_WORDS[k].test(it.name) && !it.allergens.includes(k));
531
+ return miss.length ? { name: it.name, miss: miss.map(k => FL_NL_US_ALLERGENS[k] || k) } : null;
532
+ }).filter(Boolean);
533
+ }
534
+ function _nlSuspectHtml(f) {
535
+ const sus = flNlAllergenSuspects(f);
536
+ if (!sus.length) return '';
537
+ return `<div class="nl-note warn nl-keep nl-allergen-check">Check the allergens on ${esc(sus.map(x => `${x.name} (${x.miss.join(', ').toLowerCase()}?)`).join(', '))}. Their names suggest one, but their allergen chips don't have it, so it isn't in the statement. Set it on the ingredient.</div>`;
538
+ }
509
539
  function flNlStatement(f) {
510
540
  const items = _nlStatementItems(f);
511
541
  const major = items.filter(x => x.w > 0.02), minor = items.filter(x => x.w <= 0.02);
@@ -650,7 +680,7 @@ function flNlTabHtml(f) {
650
680
  const c = flNlCompute(f);
651
681
  if (!c.ok) {
652
682
  const who = (c.needsDensity || []).slice(0, 6).join(', ');
653
- return `<div class="card"><div class="card-body"><div class="nl-note warn">No label yet. Add a density to ${esc(who) || 'the rows measured by volume'}.</div></div></div>`;
683
+ return `<div class="card"><div class="card-body"><div class="nl-note warn nl-keep">No label yet. Add a density to ${esc(who) || 'the rows measured by volume'}.</div></div></div>`;
654
684
  }
655
685
  const st = _nlSettings(f);
656
686
  const lines = flNlLines(f, c);
@@ -679,9 +709,14 @@ function flNlTabHtml(f) {
679
709
  ? `<div class="nl-dim nl-dens" data-tip="Only water is lost or gained in cooking, so each nutrient per 100 g is the mixed figure ÷ yield. The Params tab stays as mixed.">As sold: ${_nlNum(c.yield)}% of the mixed weight. Nutrients × ${+(100 / c.yield).toFixed(2)}.</div>`
680
710
  : by ? `<div class="nl-dim nl-dens">${by.n === 1 ? '1 batch' : by.n + ' batches'} yielded ${by.pct}%. <a href="#" onclick="flNlSet('${id}','yield',${by.pct});return false">Use ${by.pct}%</a></div>` : '';
681
711
  const tipList = (a) => esc(a.slice(0, 12).join(', ') + (a.length > 12 ? ` +${a.length - 12} more` : ''));
712
+ // Every ingredient has some nutrition, yet one lacks calories, fat, carbohydrate, protein or sodium: not "all good"
713
+ // (17 Nov: a USDA food with only minerals and sugars sat under a green note).
714
+ const gaps = [...new Set(FL_NL_MAIN.flatMap(k => c.missing[k] || []))];
682
715
  const cover = c.noData.length
683
716
  ? `<div class="nl-note warn" data-tip="${tipList(c.noData)}">${c.withData} of ${c.rows} ingredients have nutrition. The rest count as 0.</div>`
684
- : `<div class="nl-note ok">All ${c.rows} ingredients have nutrition.</div>`;
717
+ : gaps.length
718
+ ? `<div class="nl-note warn" data-tip="${tipList(gaps)}">All ${c.rows} ingredients have nutrition. ${gaps.length} ${gaps.length === 1 ? 'has' : 'have'} a main line blank.</div>`
719
+ : `<div class="nl-note ok">All ${c.rows} ingredients have nutrition.</div>`;
685
720
  const E = eu ? flNlEu(f, c) : null;
686
721
  const tbl = eu ? '' : lines.map(l => {
687
722
  const miss = c.missing[l.key];
@@ -692,27 +727,27 @@ function flNlTabHtml(f) {
692
727
  <td class="num"><strong>${l.text}</strong> <span class="u">${esc(l.unit)}</span></td>
693
728
  <td class="num">${l.pct == null ? '' : l.pct + '%'}</td></tr>`;
694
729
  }).join('');
695
- return `<div class="nl-wrap${!eu && ['tabular', 'linear', 'dual'].includes(sim.use) ? ' nl-wide' : ''}">
730
+ return _nlNotesWrap(`<div class="nl-wrap${!eu && ['tabular', 'linear', 'dual'].includes(sim.use) ? ' nl-wide' : ''}">
696
731
  <div class="nl-side">
697
732
  <div class="card">
698
733
  <div class="card-header"><h2>Serving</h2><span id="nl-saved" class="fl-saved-tick" role="status"></span></div>
699
734
  <div class="card-body nl-form">
700
- <label>Serving size<span class="nl-unit"><input type="number" min="0" step="any" value="${st.serving != null ? esc(String(st.serving)) : ''}" placeholder="100" onchange="flNlSet('${id}','serving',this.value)"><span class="fl-seg-group sm" role="group" aria-label="Serving unit">${seg('g')}${seg('mL')}</span></span></label>
701
- <label class="nl-hh${st.household.length > FL_NL_HH_LONG ? ' nl-long' : ''}">Household measure<input type="text" maxlength="80" oninput="this.parentElement.classList.toggle('nl-long', this.value.length > ${FL_NL_HH_LONG})" value="${esc(st.household)}" placeholder="2/3 cup" onchange="flNlSet('${id}','household',this.value)"></label>
735
+ <label>Serving size<span class="nl-unit"><input id="nl-serving-in" type="number" min="0" step="any" value="${st.serving != null ? esc(String(st.serving)) : ''}" placeholder="100" onchange="flNlSet('${id}','serving',this.value)"><span class="fl-seg-group sm" role="group" aria-label="Serving unit">${seg('g')}${seg('mL')}</span></span></label>
736
+ <label class="nl-hh${st.household.length > FL_NL_HH_LONG ? ' nl-long' : ''}">Household measure<input id="nl-hh-in" type="text" maxlength="80" oninput="this.parentElement.classList.toggle('nl-long', this.value.length > ${FL_NL_HH_LONG})" value="${esc(st.household)}" placeholder="2/3 cup" onchange="flNlSet('${id}','household',this.value)"></label>
702
737
  <label>Servings per container<input id="nl-servings-in" type="text" maxlength="20" value="${esc(st.servings)}" placeholder="8, or about 8" onchange="flNlSet('${id}','servings',this.value)"></label>
703
- <label data-tip="Finished weight ÷ mixed weight. Under 100 when baking or drying drives water off.">Cooking yield<span class="nl-unit"><input type="number" min="${FL_NL_YIELD[0]}" max="${FL_NL_YIELD[1]}" step="any" value="${st.yield != null ? esc(String(st.yield)) : ''}" placeholder="100" onchange="flNlSet('${id}','yield',this.value)"><em>%</em></span></label>
738
+ <label data-tip="Finished weight ÷ mixed weight. Under 100 when baking or drying drives water off.">Cooking yield<span class="nl-unit"><input id="nl-yield-in" type="number" min="${FL_NL_YIELD[0]}" max="${FL_NL_YIELD[1]}" step="any" value="${st.yield != null ? esc(String(st.yield)) : ''}" placeholder="100" onchange="flNlSet('${id}','yield',this.value)"><em>%</em></span></label>
704
739
  ${dens}${yld}
705
740
  </div>
706
741
  </div>
707
- <div class="nl-view"><span class="fl-seg-group" role="group" aria-label="Show">${['nutrition', 'cost'].map(v => `<button type="button" class="fl-seg${view === v ? ' on' : ''}" aria-pressed="${view === v}" onclick="flNlSetView('${id}','${v}')">${v === 'cost' ? 'Cost' : 'Nutrition'}</button>`).join('')}</span></div>
742
+ <div class="nl-view"><button type="button" class="btn btn-secondary btn-sm nl-notes-btn" aria-pressed="${flNlNotesOn()}" onclick="flNlSetNotes('${id}', ${!flNlNotesOn()})" data-tip="The amber notes about missing data. Your choice, on every formula; the allergen check always shows. Nothing on the label itself changes.">Notes: ${flNlNotesOn() ? 'on' : 'off'}</button><span class="fl-seg-group" role="group" aria-label="Show">${['nutrition', 'cost'].map(v => `<button type="button" class="fl-seg${view === v ? ' on' : ''}" aria-pressed="${view === v}" onclick="flNlSetView('${id}','${v}')">${v === 'cost' ? 'Cost' : 'Nutrition'}</button>`).join('')}</span></div>
708
743
  ${view === 'cost' ? _nlCostCardHtml(f) : `<div class="card">
709
744
  <div class="card-header"><h2>Ingredient statement</h2>
710
745
  <button class="btn btn-secondary btn-sm" onclick="flNlCopyStatement('${id}')">Copy</button></div>
711
746
  <div class="card-body nl-stmt">
712
747
  ${eu ? (() => { const es = flNlEuStatement(f); return `<div class="nl-eu-stmt"><strong>INGREDIENTS:</strong> ${es.html || '<span class="nl-dim">No ingredients yet.</span>'}</div>
713
- ${es.allergens.length ? '' : '<div class="nl-dim">No EU allergens on the ingredients.</div>'}
714
- <div class="nl-dim nl-hint" data-tip="The 14 EU allergens, from each ingredient’s allergen chips. A name that doesn’t say the allergen gets it added in brackets. Copy gives them in CAPITALS. Add a custom field named label_name to an ingredient to print another name.">By weight, most first. Allergens in bold.</div>`; })() : `<div><strong>INGREDIENTS:</strong> ${esc(s.text) || '<span class="nl-dim">No ingredients yet.</span>'}</div>
715
- ${s.contains.length ? `<div class="nl-contains"><strong>CONTAINS:</strong> ${esc(s.contains.join(', '))}.</div>` : '<div class="nl-dim">No major US allergens on the ingredients.</div>'}
748
+ ${_nlSuspectHtml(f) || (es.allergens.length ? '' : '<div class="nl-dim">No EU allergens on the ingredients.</div>')}
749
+ <div class="nl-dim nl-hint" data-tip="The 14 EU allergens from each ingredient’s chips, in CAPITALS on Copy. A label_name custom field prints another name.">By weight, most first. Allergens in bold.</div>`; })() : `<div><strong>INGREDIENTS:</strong> ${esc(s.text) || '<span class="nl-dim">No ingredients yet.</span>'}</div>
750
+ ${s.contains.length ? `<div class="nl-contains"><strong>CONTAINS:</strong> ${esc(s.contains.join(', '))}.</div>` : ''}${_nlSuspectHtml(f) || (s.contains.length ? '' : '<div class="nl-dim">No major US allergens on the ingredients.</div>')}
716
751
  <div class="nl-dim nl-hint" data-tip="Add a custom field named label_name to an ingredient to print another name here.">By weight, most first. 2% or less grouped.</div>`}
717
752
  </div>
718
753
  </div>
@@ -739,15 +774,38 @@ function flNlTabHtml(f) {
739
774
  </div>
740
775
  </div>
741
776
  </div>
742
- </div>`;
777
+ </div>`, id);
743
778
  }
744
779
 
780
+ // Amber notes on or off (Jun, 17 Nov: "a global switch to hide/unhide amber warnings in Label tab"). Per person, every
781
+ // formula, synced with the other view preferences. Off hides the notes about missing data; the allergen check and the
782
+ // "no label yet" note (the tab's only content then) always show, and a quiet line says how many are hidden.
783
+ function flNlNotesOn() { try { return localStorage.getItem('formlab_nl_notes') !== 'off'; } catch (_) { return true; } }
784
+ function flNlSetNotes(fid, on) {
785
+ if (typeof saveViewPref === 'function') saveViewPref('formlab_nl_notes', on ? 'on' : 'off');
786
+ else try { localStorage.setItem('formlab_nl_notes', on ? 'on' : 'off'); } catch (_) {}
787
+ const f = (db.formulations || []).find(x => x.id === fid), el = document.getElementById('tab-label');
788
+ if (f && el) el.innerHTML = flNlTabHtml(f);
789
+ }
790
+ function _nlNotesWrap(html, id) {
791
+ if (flNlNotesOn()) return html;
792
+ const n = (html.match(/class="nl-note warn(?![^"]*\bnl-keep\b)/g) || []).length;
793
+ const line = n ? `<div class="nl-notes-hidden">${n} note${n === 1 ? '' : 's'} hidden. <a onclick="flNlSetNotes('${id}', true)">Show</a></div>` : '';
794
+ return `<div class="nl-notes-off">${line}${html}</div>`;
795
+ }
745
796
  function flNlView() { try { return localStorage.getItem('formlab_nl_view') === 'cost' ? 'cost' : 'nutrition'; } catch (_) { return 'nutrition'; } }
746
797
  function flNlSetView(fid, v) {
747
798
  try { localStorage.setItem('formlab_nl_view', v === 'cost' ? 'cost' : 'nutrition'); } catch (_) {}
748
799
  const f = (db.formulations || []).find(x => x.id === fid), el = document.getElementById('tab-label');
749
800
  if (f && el) el.innerHTML = flNlTabHtml(f);
750
801
  }
802
+ // Redraw the tab from the formula as it is now, e.g. on coming back from Composition after a sell price changed (11h).
803
+ // Not while a field in it has the focus: that would throw away what is being typed.
804
+ function flNlRepaint() {
805
+ const el = document.getElementById('tab-label'), f = el && (db.formulations || []).find(x => x.id === el.dataset.fid);
806
+ if (!f || !el || el.contains(document.activeElement)) return;
807
+ el.innerHTML = flNlTabHtml(f);
808
+ }
751
809
  // Save one serving field on the formula, then redraw the tab.
752
810
  function flNlSet(fid, key, value) {
753
811
  const f = (db.formulations || []).find(x => x.id === fid);
@@ -770,9 +828,20 @@ function flNlSet(fid, key, value) {
770
828
  else { const t = String(value || '').trim().slice(0, key === 'household' ? 80 : 40); if (t) l[key] = t; else delete l[key]; }
771
829
  f.label = l;
772
830
  const saved = typeof _fmlSyncSave === 'function' && _fmlSyncSave(f, ['label']);
773
- const el = document.getElementById('tab-label');
774
- if (el) el.innerHTML = flNlTabHtml(f);
831
+ // The redraw replaces every field. From a typed field it waits one tick, so the focus has already moved to the field
832
+ // the person tabbed or clicked to, and then puts the focus back there (11h: "make sure cost input boxes are steady").
833
+ const paint = () => {
834
+ const el = document.getElementById('tab-label');
835
+ const aid = el && document.activeElement && el.contains(document.activeElement) ? document.activeElement.id : '';
836
+ if (el) el.innerHTML = flNlTabHtml(f);
837
+ if (aid) { const n = document.getElementById(aid); if (n && typeof n.focus === 'function') { n.focus({ preventScroll: true }); if (n.tagName === 'INPUT' && typeof n.select === 'function') n.select(); } }
838
+ _nlTick();
839
+ };
840
+ const _nlTick = () => {
775
841
  if (saved && typeof flSavedTick === 'function') flSavedTick(key === 'format' || key === 'region' || key === 'ri' ? 'nl-fmt-saved' : ['pack', 'goal', 'labor', 'batch', 'overhead'].includes(key) ? 'nl-cost-saved' : 'nl-saved');
842
+ };
843
+ const ev = typeof window !== 'undefined' ? window.event : null;
844
+ if (ev && ev.type === 'change' && typeof setTimeout === 'function') setTimeout(paint, 0); else paint();
776
845
  }
777
846
 
778
847
  function _nlFile(f) { return 'nutrition-facts-' + String(f.uid || f.name || 'formula').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase(); }
@@ -455,7 +455,7 @@ function flRxApplySolve(fId) {
455
455
  // ---- A batch: as weighed, and (Pro) against the plan ----
456
456
  function flRxBatchStripHtml(b) {
457
457
  if (!b) return '';
458
- const f = (db.formulations || []).find(x => x.id === b.formulationId);
458
+ const f = (typeof flBatchFormula === 'function' ? flBatchFormula(b) : db.formulations.find(x => x.id === b.formulationId));
459
459
  const hasActual = Array.isArray(b.actualComposition) && b.actualComposition.length;
460
460
  const comp = hasActual ? b.actualComposition : (f ? f.composition : []);
461
461
  const found = flRxPairsFor(comp);
@@ -510,7 +510,7 @@ function flRxFormSectionHtml(ing) {
510
510
  <div class="fl-rx-frows" id="fl-rx-frows">${list.map(_flRxFormRowHtml).join('')}</div>
511
511
  <div class="fl-rx-fhead">
512
512
  <button type="button" class="btn btn-secondary btn-sm" onclick="_flRxFormAdd()">+ Add group</button>
513
- <span class="fl-rx-note" data-tip="EEW for a resin, AHEW for a hardener, OH number for a polyol, NCO % for an isocyanate, acid or amine value; groups per molecule (with the MW) for a pure chemical.">As the datasheet quotes it, or groups per molecule for a pure chemical.</span>
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>
514
514
  </div>
515
515
  </div>`;
516
516
  }