formlab-mcp 0.6.86 → 0.6.88

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.86",
3
+ "version": "0.6.88",
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.86",
5
+ "version": "0.6.88",
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.86",
11
+ "version": "0.6.88",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
package/theoretical.js CHANGED
@@ -48,7 +48,7 @@ const EPILOGUE = `
48
48
  // The Label tab's numbers (js/views/nutrition-label.js, 0.6.83; the EU ingredient list 0.6.84). The app's allergen roll-up lives in a file that is not
49
49
  // vendored; this is the same walk over the flattened leaves.
50
50
  // The viewer's display-currency preference lives in the browser; here there is none, so costs read in USD unless the
51
- // formula's target price names a currency (0.6.86).
51
+ // formula's target price names a currency (0.6.86). Labor, overhead and EU reference intakes: 0.6.87.
52
52
  var localStorage = { getItem: function () { return null; }, setItem: function () {} };
53
53
  // The app's HTML escaper (js/utils.js, not vendored): the EU list builds its bold version with it.
54
54
  function esc(v) { return String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
@@ -80,7 +80,8 @@ function __nl(id) {
80
80
  nutritionFacts: decl(lines),
81
81
  perContainer: sim.servings > 1 ? decl(flNlLines(f, c, sim.servings)) : null,
82
82
  simplified: { eligible: sim.eligible, insignificantNutrients: sim.count, statement: sim.eligible ? strip(_nlNotSource(lines, sim)) : null },
83
- eu: { basis: 'per ' + eu.basis, portion: eu.portion, rows: eu.rows.map(function (r) { return { nutrient: r.label, per: r.per, perPortion: r.portion }; }),
83
+ eu: { basis: 'per ' + eu.basis, portion: eu.portion, rows: eu.rows.map(function (r) { return { nutrient: r.label, per: r.per, perPortion: r.portion, referenceIntakePct: r.ri }; }),
84
+ referenceIntake: eu.ri ? { of: eu.ri === 'portion' ? 'portion' : eu.basis, note: eu.riNote } : null,
84
85
  ingredientList: eus.text, allergens: eus.allergens },
85
86
  ingredientStatement: s.text, contains: s.contains,
86
87
  coverage: { ingredients: c.rows, withNutrition: c.withData, noData: c.noData, missing: c.missing, energyFromPartialMacros: c.partial },
@@ -89,10 +90,11 @@ function __nl(id) {
89
90
  if (!k.ok) return null;
90
91
  var r4 = function (v) { return v == null ? null : +(+v).toPrecision(4); };
91
92
  return { currency: k.currency, perServing: r4(k.perServing), packagingPerContainer: r4(k.pack), perServingWithPackaging: r4(k.perServingPacked),
93
+ laborPerBatch: r4(k.labor), laborPerServing: k.labor ? r4(k.laborServing) : null, overheadPct: k.overheadPct || null, overheadPerServing: k.overheadPct ? r4(k.overheadServing) : null, perServingTotal: r4(k.perServingFull),
92
94
  perContainer: r4(k.perContainer), perKgAsSold: r4(k.perKgSold), perKgAsMixed: r4(k.perKgMixed),
93
95
  sellPricePerServing: k.price ? r4(k.price.perServing) : null, sellPricePerContainer: k.price ? r4(k.price.perContainer) : null,
94
96
  marginPct: k.price ? +k.price.marginPct.toFixed(1) : null, unpricedRows: k.unpriced,
95
- basis: k.pack ? 'ingredients and packaging' : 'ingredients only' };
97
+ basis: k.basis.length > 1 ? _nlList(k.basis) : 'ingredients only' };
96
98
  })(),
97
99
  });
98
100
  }
@@ -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
 
@@ -191,7 +191,7 @@ const get_formulation = {
191
191
  const get_nutrition_label = {
192
192
  definition: {
193
193
  name: 'get_nutrition_label',
194
- description: 'A formulation\'s nutrition label as FormLab\'s Label tab computes it (Pro; live workspace only), from each ingredient\'s per-100 g nutrition fields × the composition (premixes rolled up, units converted). Returns: `serving` (amount in g or mL, its weight in grams, household measure, servings per container, the density used for a mL serving); `cookingYieldPct` when set (numbers are then "as sold" = as mixed ÷ yield); `per100g` unrounded; `nutritionFacts`, the US Nutrition Facts lines per serving with `declared` (FDA rounding, 21 CFR 101.9) and `percentDailyValue`; `perContainer` when servings per container is above 1 (the dual-column second column, rounded from its own total); `simplified` (whether the food qualifies for the simplified format and its "Not a significant source of…" line); `eu`, the EU nutrition declaration per 100 g or 100 ml (kJ and kcal by the EU factors, carbohydrate without fibre, salt = sodium × 2.5) with a per-portion column when a serving is typed, plus `eu.ingredientList`, the EU ingredient list (every ingredient by weight, the 14 EU allergens in CAPITALS, added in brackets where the name does not say it) and `eu.allergens`; `ingredientStatement` (by weight, 2% or less grouped) and `contains` (major US allergens); `coverage` (which ingredients have no nutrition data, which nutrients are missing on which, where calories came from partial macros). `cost` (null when the ingredients carry no prices): what one serving and one container cost to make, in `currency`, from the ingredient cost per kg, the weight of the serving and the cooking yield, plus `packagingPerContainer` when the user typed one; with a target sell price, `sellPricePerServing` and `marginPct`; `unpricedRows` count as 0; `basis` says what is in the number (never labor or overhead). `region` / `format` are what the user chose on the tab. A blank field counts as 0: check `coverage` before calling a nutrient absent. Calculated from ingredient data, not a regulatory review.',
194
+ description: 'A formulation\'s nutrition label as FormLab\'s Label tab computes it (Pro; live workspace only), from each ingredient\'s per-100 g nutrition fields × the composition (premixes rolled up, units converted). Returns: `serving` (amount in g or mL, its weight in grams, household measure, servings per container, the density used for a mL serving); `cookingYieldPct` when set (numbers are then "as sold" = as mixed ÷ yield); `per100g` unrounded; `nutritionFacts`, the US Nutrition Facts lines per serving with `declared` (FDA rounding, 21 CFR 101.9) and `percentDailyValue`; `perContainer` when servings per container is above 1 (the dual-column second column, rounded from its own total); `simplified` (whether the food qualifies for the simplified format and its "Not a significant source of…" line); `eu`, the EU nutrition declaration per 100 g or 100 ml (kJ and kcal by the EU factors, carbohydrate without fibre, salt = sodium × 2.5) with a per-portion column when a serving is typed and, when the user turned it on, `referenceIntakePct` on each row (`eu.referenceIntake` says of what), plus `eu.ingredientList`, the EU ingredient list (every ingredient by weight, the 14 EU allergens in CAPITALS, added in brackets where the name does not say it) and `eu.allergens`; `ingredientStatement` (by weight, 2% or less grouped) and `contains` (major US allergens); `coverage` (which ingredients have no nutrition data, which nutrients are missing on which, where calories came from partial macros). `cost` (null when the ingredients carry no prices): what one serving and one container cost to make, in `currency`, from the ingredient cost per kg, the weight of the serving and the cooking yield, plus `packagingPerContainer`, `laborPerBatch` / `laborPerServing` and `overheadPct` / `overheadPerServing` when the user typed them, with `perServingTotal` counting all of it; with a target sell price, `sellPricePerServing` and `marginPct`; `unpricedRows` count as 0; `basis` says what is in the number (never labor or overhead). `region` / `format` are what the user chose on the tab. A blank field counts as 0: check `coverage` before calling a nutrient absent. Calculated from ingredient data, not a regulatory review.',
195
195
  inputSchema: {
196
196
  type: 'object',
197
197
  properties: {
@@ -151,6 +151,9 @@ const _nlStr = (v) => (typeof v === 'string' || typeof v === 'number') ? String(
151
151
  // Packaging cost per container (1.16.20 11b): { value, currency } as typed, or null. One pack holds servings-per-container
152
152
  // servings, so it only counts when that number is set.
153
153
  const FL_NL_PACK_MAX = 1e6;
154
+ // Labor per batch is money like the pack ({ value, currency }), the batch is kg of mix, overhead a percent on top of
155
+ // everything else (1.16.20 11d).
156
+ const FL_NL_OVERHEAD_MAX = 500;
154
157
  function _nlPack(p) {
155
158
  const v = p && typeof p === 'object' ? parseFloat(p.value) : NaN;
156
159
  if (!Number.isFinite(v) || !(v > 0) || v > FL_NL_PACK_MAX) return null;
@@ -159,7 +162,9 @@ function _nlPack(p) {
159
162
  function _nlSettings(f) {
160
163
  const l = (f && f.label) || {};
161
164
  const s = parseFloat(l.serving), y = parseFloat(l.yield);
162
- return { yield: Number.isFinite(y) && y >= FL_NL_YIELD[0] && y <= FL_NL_YIELD[1] && y !== 100 ? y : null, serving: Number.isFinite(s) && s > 0 && s <= FL_NL_MAX_SERVING ? s : null, unit: l.unit === 'mL' ? 'mL' : 'g', region: l.region === 'eu' ? 'eu' : 'us', format: ['simplified', 'tabular', 'linear', 'dual'].includes(l.format) ? l.format : 'standard', household: _nlStr(l.household), servings: _nlStr(l.servings), pack: _nlPack(l.pack) };
165
+ return { yield: Number.isFinite(y) && y >= FL_NL_YIELD[0] && y <= FL_NL_YIELD[1] && y !== 100 ? y : null, serving: Number.isFinite(s) && s > 0 && s <= FL_NL_MAX_SERVING ? s : null, unit: l.unit === 'mL' ? 'mL' : 'g', region: l.region === 'eu' ? 'eu' : 'us', format: ['simplified', 'tabular', 'linear', 'dual'].includes(l.format) ? l.format : 'standard', household: _nlStr(l.household), servings: _nlStr(l.servings), pack: _nlPack(l.pack), goal: (g => Number.isFinite(g) && g >= 1 && g <= 99 ? g : null)(parseFloat(l.goal)),
166
+ labor: _nlPack(l.labor), batch: (b => Number.isFinite(b) && b >= 0.001 && b <= FL_NL_PACK_MAX ? b : null)(parseFloat(l.batch)),
167
+ overhead: (o => Number.isFinite(o) && o > 0 && o <= FL_NL_OVERHEAD_MAX ? o : null)(parseFloat(l.overhead)), ri: l.ri === true };
163
168
  }
164
169
  // A serving in grams. A drink's serving is in mL (61r): grams = mL × the formula's density, the finished density
165
170
  // when it has one, else the ideal-mix estimate; with neither, 1 g/mL and `noDensity` so the tab can say so.
@@ -246,6 +251,16 @@ function _nlEuRound(kind, v) {
246
251
  return v <= low ? '<' + low : v < 10 ? v.toFixed(1) : String(Math.round(v));
247
252
  }
248
253
  // → { basis: '100 g' | '100 ml', portion: text | null, rows: [{ key, label, indent, per, portion }] } (texts as declared)
254
+ // Reference intakes of an average adult (Annex XIII, Part B). Fibre has none. Shown per portion when a serving is
255
+ // typed, else per 100 g / 100 ml, with the statement the regulation asks for under the table (Art. 32(4), 33).
256
+ const FL_NL_EU_RI = { energy: 2000, fat: 70, sat_fat: 20, carb: 260, sugar: 90, protein: 50, salt: 6 };
257
+ const FL_NL_EU_RI_NOTE = 'Reference intake of an average adult (8 400 kJ / 2 000 kcal)';
258
+ function _nlEuRi(key, v) {
259
+ const ref = FL_NL_EU_RI[key];
260
+ if (!ref || !Number.isFinite(v)) return null;
261
+ const p = v / ref * 100;
262
+ return p <= 0 ? '0%' : p < 0.5 ? '<1%' : Math.round(p) + '%';
263
+ }
249
264
  function flNlEu(f, calc) {
250
265
  const c = calc || flNlCompute(f), st = _nlSettings(f), sv = flNlServing(f), p = c.per100 || {};
251
266
  const ml = sv.unit === 'mL';
@@ -257,20 +272,25 @@ function flNlEu(f, calc) {
257
272
  const kJ = macros ? 37 * fat + 17 * carb + 17 * prot + 8 * fib : m('energy') * 4.184;
258
273
  return { energy: `${Math.round(kJ)} kJ / ${Math.round(kcal)} kcal`, fat: _nlEuRound('g', fat) + ' g', sat_fat: _nlEuRound('sat', m('sat_fat')) + ' g',
259
274
  carb: _nlEuRound('g', carb) + ' g', sugar: _nlEuRound('g', m('sugar')) + ' g', fiber: _nlEuRound('g', fib) + ' g', protein: _nlEuRound('g', prot) + ' g',
260
- salt: _nlEuRound('salt', m('sodium') * 2.5 / 1000) + ' g' };
275
+ salt: _nlEuRound('salt', m('sodium') * 2.5 / 1000) + ' g',
276
+ raw: { energy: kcal, fat, sat_fat: m('sat_fat'), carb, sugar: m('sugar'), protein: prot, salt: m('sodium') * 2.5 / 1000 } };
261
277
  };
262
278
  const per = col(ml ? 100 * (sv.density || 1) : 100);
263
279
  const portion = st.serving != null ? col(sv.g) : null;
264
280
  const defs = [['energy', 'Energy'], ['fat', 'Fat'], ['sat_fat', 'of which saturates', 1], ['carb', 'Carbohydrate'], ['sugar', 'of which sugars', 1],
265
281
  ...(p.fiber > 0 ? [['fiber', 'Fibre']] : []), ['protein', 'Protein'], ['salt', 'Salt']];
282
+ const riOf = st.ri ? (portion || per) : null;
266
283
  return { basis: ml ? '100 ml' : '100 g', portion: portion ? `${_nlNum(sv.amount)} ${ml ? 'ml' : 'g'}` : null,
267
- rows: defs.map(([key, label, indent]) => ({ key, label, indent: indent || 0, per: per[key], portion: portion ? portion[key] : null })) };
284
+ ri: riOf ? (portion ? 'portion' : 'basis') : null, riNote: riOf ? FL_NL_EU_RI_NOTE : null,
285
+ rows: defs.map(([key, label, indent]) => ({ key, label, indent: indent || 0, per: per[key], portion: portion ? portion[key] : null, ri: riOf ? _nlEuRi(key, riOf.raw[key]) : null })) };
268
286
  }
269
287
  function flNlEuPanelHtml(f, calc) {
270
288
  const e = flNlEu(f, calc);
271
- return `<div class="nl-panel nl-eu" id="nl-panel" translate="no"><table>
272
- <thead><tr><th>Nutrition declaration</th><th>per ${e.basis}</th>${e.portion ? `<th>per portion (${esc(e.portion)})</th>` : ''}</tr></thead>
273
- <tbody>${e.rows.map(r => `<tr${r.indent ? ' class="nl-e-in"' : ''}><td>${r.label}</td><td>${r.per}</td>${e.portion ? `<td>${r.portion}</td>` : ''}</tr>`).join('')}</tbody>
289
+ const cols = 2 + (e.portion ? 1 : 0) + (e.ri ? 1 : 0);
290
+ const nb = (t) => !e.ri ? t : String(t).replace(/ (kJ|kcal|g)\b/g, '\u00a0$1'); // a narrow column breaks at the slash, never inside "359 kJ"
291
+ return `<div class="nl-panel nl-eu${e.ri ? ' nl-ri' : ''}" id="nl-panel" translate="no"><table>
292
+ <thead><tr><th>Nutrition declaration</th><th>per ${e.basis}</th>${e.portion ? `<th>per portion (${esc(e.portion)})</th>` : ''}${e.ri ? '<th class="nl-e-ri">%RI*</th>' : ''}</tr></thead>
293
+ <tbody>${e.rows.map(r => `<tr${r.indent ? ' class="nl-e-in"' : ''}><td>${r.label}</td><td>${nb(r.per)}</td>${e.portion ? `<td>${nb(r.portion)}</td>` : ''}${e.ri ? `<td>${r.ri || ''}</td>` : ''}</tr>`).join('')}${e.ri ? `<tr class="nl-e-note"><td colspan="${cols}">*${e.riNote}${e.ri === 'portion' ? `, per portion` : ''}</td></tr>` : ''}</tbody>
274
294
  </table></div>`;
275
295
  }
276
296
 
@@ -278,18 +298,26 @@ function flNlEuPanelHtml(f, calc) {
278
298
  // What one serving and one container cost to make, from the formula's ingredient cost per kg (computeFormulationCost,
279
299
  // the number the Composition tab totals), the serving's weight and the cooking yield: a kilogram sold took 1 ÷ yield
280
300
  // kilograms of mix. Ingredients only: no packaging, labor or overhead. With a target sell price on the Pricing &
281
- // Margin panel, the same per serving, and the margin. Money is in the price's currency when one is set, else the
282
- // 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).
283
303
  // → { ok, currency, perKgMixed, perKgSold, perServing, perContainer, servings, unpriced: [names],
284
304
  // price: { perKg, perServing, perContainer, profitServing, marginPct } | null } ; ok false: why
305
+ const FL_NL_MAIN = ['energy', 'fat', 'carb', 'protein', 'sodium'];
285
306
  function flNlCost(f) {
286
307
  const out = { ok: false, why: 'nocost', unpriced: [], price: null };
287
308
  if (!f || typeof computeFormulationCost !== 'function') return out;
288
309
  const pr = (f.pricing && typeof f.pricing === 'object') ? f.pricing : {};
289
- const target = parseFloat(pr.targetPrice);
290
- const hasPrice = Number.isFinite(target) && target > 0;
291
- let c = null;
292
- 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; }
293
321
  if (!c || !Number.isFinite(c.perKg) || !(c.perKg > 0)) return out;
294
322
  const st = _nlSettings(f), sv = flNlServing(f), y = st.yield || 100, n = flNlServingsCount(f);
295
323
  out.ok = true; delete out.why;
@@ -304,15 +332,43 @@ function flNlCost(f) {
304
332
  const conv = st.pack.currency === c.currency ? st.pack.value : (typeof convertCurrencySync === 'function' ? convertCurrencySync(st.pack.value, st.pack.currency, c.currency) : null);
305
333
  if (n > 0 && Number.isFinite(conv)) out.pack = conv; else out.packIdle = true; // no servings per container (or no rate): not counted
306
334
  }
307
- out.perContainer = n > 0 ? out.perServing * n + (out.pack || 0) : null;
308
- out.perServingPacked = out.pack ? out.perContainer / n : null;
335
+ out.perServingPacked = out.pack ? out.perServing + out.pack / n : null;
336
+ // Labor: per batch of mix, so a serving's share is labor ÷ batch kg × the kg of mix a serving took. Overhead: a
337
+ // percent on top of ingredients, packaging and labor (1.16.20 11d).
338
+ const k1 = 100 / y * sv.g / 1000;
339
+ out.labor = null; out.laborIdle = false; out.laborServing = 0;
340
+ if (st.labor) {
341
+ const conv = st.labor.currency === c.currency ? st.labor.value : (typeof convertCurrencySync === 'function' ? convertCurrencySync(st.labor.value, st.labor.currency, c.currency) : null);
342
+ if (st.batch && Number.isFinite(conv) && Number.isFinite(conv / st.batch * k1)) { out.labor = conv; out.laborServing = conv / st.batch * k1; } else out.laborIdle = true;
343
+ }
344
+ const before = out.perServing + (out.pack ? out.pack / n : 0) + out.laborServing;
345
+ out.overheadPct = st.overhead; out.overheadServing = st.overhead ? before * st.overhead / 100 : 0;
346
+ out.perServingFull = before + out.overheadServing; // everything counted: what the tiles, the margin and the goal use
347
+ out.perContainer = n > 0 ? out.perServingFull * n : null;
348
+ out.basis = ['ingredients', out.pack ? 'packaging' : '', out.labor ? 'labor' : '', st.overhead ? 'overhead' : ''].filter(Boolean);
349
+ // Where a serving's cost goes (1.16.20 11c): each priced row's share, largest first, the pack's share last in the list of
350
+ // its size. A row's contribution is per kg of mix, so it scales the same way the total does.
351
+ const parts = [];
352
+ (c.breakdown || []).forEach(b => {
353
+ const v = (b && Number.isFinite(b.contribution) ? b.contribution : 0) * k1;
354
+ const name = b && ((b.ingredient && b.ingredient.name) || (b.subFormula && b.subFormula.name)) || '';
355
+ if (v > 0 && name) { const hit = parts.find(p => p.name === name && p.kind === 'row'); if (hit) hit.perServing += v; else parts.push({ name, perServing: v, kind: 'row' }); }
356
+ });
357
+ if (out.pack) parts.push({ name: 'Packaging', perServing: out.pack / n, kind: 'pack' });
358
+ if (out.labor) parts.push({ name: 'Labor', perServing: out.laborServing, kind: 'labor' });
359
+ if (out.overheadServing > 0) parts.push({ name: 'Overhead', perServing: out.overheadServing, kind: 'over' });
360
+ const whole = parts.reduce((a, p) => a + p.perServing, 0);
361
+ parts.forEach(p => { p.share = whole > 0 ? p.perServing / whole * 100 : 0; });
362
+ out.parts = parts.sort((a, b) => b.perServing - a.perServing);
309
363
  out.unpriced = (c.missing || []).map(m => (m && ((m.ingredient && m.ingredient.name) || (m.subFormula && m.subFormula.name) || m.reason)) || '').filter(Boolean);
310
364
  if (hasPrice) {
311
365
  const basis = pr.basisUnit || 'kg';
312
366
  const perKg = basis === 'kg' ? target : (typeof convertPricePerBasis === 'function' ? convertPricePerBasis(target, basis, 'kg', sv.density || (typeof _rolledUpDensity === 'function' ? _rolledUpDensity(f) : null)) : null);
313
367
  if (Number.isFinite(perKg) && perKg > 0) {
314
- const ps = perKg * sv.g / 1000, cs = out.perServingPacked != null ? out.perServingPacked : out.perServing; // with its share of the pack
368
+ const ps = perKg * sv.g / 1000, cs = out.perServingFull; // with packaging, labor and overhead
315
369
  out.price = { perKg, perServing: ps, perContainer: n > 0 ? ps * n : null, profitServing: ps - cs, marginPct: (ps - cs) / ps * 100 };
370
+ // The margin goal (1.16.20 11c): the most a serving may cost to keep it, and how far the serving is from that.
371
+ if (st.goal) { const cap = ps * (1 - st.goal / 100); out.goal = { pct: st.goal, costCap: cap, gap: cs - cap, met: cs <= cap + 1e-12 }; }
316
372
  }
317
373
  }
318
374
  return out;
@@ -327,19 +383,25 @@ function _nlMoney(v, ccy) {
327
383
  const whole = formatMoney(1, ccy), digits = +v.toPrecision(3);
328
384
  return whole.replace(/1([.,]0+)?/, String(digits));
329
385
  }
386
+ const _nlList = (a) => a.length < 2 ? a.join('') : a.slice(0, -1).join(', ') + ' and ' + a[a.length - 1];
330
387
  // The cost as lines of text, for the print and for the MCP tool's reader: [[label, value], …]; [] with no cost.
331
388
  function flNlCostLines(f) {
332
389
  const k = flNlCost(f);
333
390
  if (!k.ok) return [];
334
391
  const sv = flNlServing(f), st = _nlSettings(f), m = v => _nlMoney(v, k.currency);
335
- const out = [[`Cost per serving (${_nlNum(sv.amount)} ${sv.unit})${k.pack ? ', ingredients' : ''}`, m(k.perServing)]];
336
- if (k.pack) out.push(['Packaging per container', m(k.pack)], ['Cost per serving with packaging', m(k.perServingPacked)]);
337
- if (k.perContainer != null) out.push([`Cost per container (${st.servings} servings${k.pack ? ' + packaging' : ''})`, m(k.perContainer)]);
392
+ const more = k.basis.length > 1;
393
+ const out = [[`Cost per serving (${_nlNum(sv.amount)} ${sv.unit})${more ? ', ingredients' : ''}`, m(k.perServing)]];
394
+ if (k.pack) out.push(['Packaging per container', m(k.pack)]);
395
+ if (k.labor) out.push([`Labor per batch (${_nlNum(st.batch)} kg)`, m(k.labor)], ['Labor per serving', m(k.laborServing)]);
396
+ if (k.overheadPct) out.push([`Overhead ${_nlNum(k.overheadPct)}% per serving`, m(k.overheadServing)]);
397
+ if (more) out.push([`Cost per serving with ${_nlList(k.basis.slice(1))}`, m(k.perServingFull)]);
398
+ if (k.perContainer != null) out.push([`Cost per container (${st.servings} servings)`, m(k.perContainer)]);
338
399
  out.push([`Cost per kg${st.yield ? ` as sold (${_nlNum(st.yield)}% yield)` : ''}`, m(k.perKgSold)]);
339
400
  if (k.price) {
340
401
  out.push(['Sell price per serving', m(k.price.perServing)]);
341
402
  if (k.price.perContainer != null) out.push(['Sell price per container', m(k.price.perContainer)]);
342
403
  out.push(['Margin', `${+k.price.marginPct.toFixed(1)}%`]);
404
+ if (k.goal) out.push([`Margin goal ${_nlNum(k.goal.pct)}%`, `${m(Math.abs(k.goal.gap))} ${k.goal.met ? 'under' : 'over'} per serving`]);
343
405
  }
344
406
  if (k.unpriced.length) out.push(['Rows with no price (counted as 0)', k.unpriced.slice(0, 12).join(', ')]);
345
407
  return out;
@@ -350,33 +412,53 @@ function _nlCostCardHtml(f) {
350
412
  <div class="card-header"><h2>Cost</h2></div>
351
413
  <div class="card-body"><div class="nl-dim" data-tip="Set a price on the ingredients (Ingredient › Cost & Pricing), then the cost per serving shows here.">No ingredient prices yet.</div></div>
352
414
  </div>`;
353
- const sv = flNlServing(f), st = _nlSettings(f), m = v => esc(_nlMoney(v, k.currency));
354
- const row = (label, val, sub, tip) => `<tr${tip ? ` data-tip="${esc(tip)}"` : ''}><td>${label}${sub ? ` <span class="u">${esc(sub)}</span>` : ''}</td><td class="num"><strong>${val}</strong></td></tr>`;
355
- const id = esc(f.id);
356
- const packIn = `<tr><td><label for="nl-pack-in">Packaging per container</label> <span class="u">${esc(k.currency)}</span></td><td class="num"><input id="nl-pack-in" type="number" min="0" step="any" value="${st.pack ? esc(String(st.pack.currency === k.currency ? st.pack.value : +(+k.pack || st.pack.value).toFixed(4))) : ''}" placeholder="0" onchange="flNlSet('${id}','pack',this.value)"></td></tr>`;
357
- const rows = [
358
- row('Per serving', m(k.perServing), `${_nlNum(sv.amount)} ${sv.unit}${k.pack ? ', ingredients' : ''}`),
359
- packIn,
360
- k.perServingPacked != null ? row('Per serving with packaging', m(k.perServingPacked)) : '',
361
- k.perContainer != null ? row('Per container', m(k.perContainer), `${st.servings} servings${k.pack ? ' + packaging' : ''}`) : '',
362
- row('Per kg', m(k.perKgSold), st.yield ? `as sold, ${_nlNum(st.yield)}% yield` : '', st.yield ? `As mixed: ${_nlMoney(k.perKgMixed, k.currency)} / kg.` : ''),
363
- ];
364
- const p = k.price;
365
- const priceRows = p ? [
366
- row('Sell price per serving', m(p.perServing)),
367
- p.perContainer != null ? row('Sell price per container', m(p.perContainer)) : '',
368
- row('Margin', `<span style="color:var(${p.marginPct >= 0 ? '--success' : '--danger'})">${esc(String(+p.marginPct.toFixed(1)))}%</span>`, `${_nlMoney(p.profitServing, k.currency)} per serving`),
369
- ] : [];
370
- const idle = k.packIdle ? `<div class="nl-note warn">Packaging needs Servings per container. Not counted.</div>` : '';
415
+ const sv = flNlServing(f), st = _nlSettings(f), m = v => esc(_nlMoney(v, k.currency)), id = esc(f.id), p = k.price;
416
+ const one = k.perServingFull, extras = k.basis.slice(1);
417
+ // Three numbers first, the working behind them under it (Jun, 17 Nov: "pretty and organized", not deep).
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>`;
419
+ const tiles = [
420
+ tile('Per serving', m(one), `${esc(_nlNum(sv.amount))} ${sv.unit}${extras.length > 1 ? ' · all in' : extras.length ? ' · with ' + esc(extras[0]) : ''}`),
421
+ k.perContainer != null ? tile('Per container', m(k.perContainer), `${esc(st.servings)} servings`) : tile('Per container', '—', 'Set Servings per container', 'off'),
422
+ p ? tile('Margin', `${esc(String(+p.marginPct.toFixed(1)))}%`, `${esc(_nlMoney(p.profitServing, k.currency))} per serving`, p.marginPct >= 0 ? 'good' : 'bad')
423
+ : tile('Margin', '—', 'Add a sell price in Pricing &amp; Margin', 'off'),
424
+ ].join('');
425
+ const kv = (label, val, tip) => `<div class="nl-kv-l"${tip ? ` data-tip="${esc(tip)}"` : ''}>${label}</div><div class="nl-kv-v">${val}</div>`;
426
+ const goalState = !st.goal ? '' : !p ? `<span class="nl-chip off">needs a sell price</span>`
427
+ : `<span class="nl-chip ${k.goal.met ? 'good' : 'bad'}" data-tip="${esc(`To keep ${_nlNum(st.goal)}%, a serving may cost up to ${_nlMoney(k.goal.costCap, k.currency)}. It costs ${_nlMoney(one, k.currency)}.`)}">${esc(_nlMoney(Math.abs(k.goal.gap), k.currency))} ${k.goal.met ? 'under' : 'over'}</span>`;
428
+ const grid = [
429
+ kv('Ingredients per serving', `<strong>${m(k.perServing)}</strong>`),
430
+ kv(`<label for="nl-pack-in">Packaging per container</label>`, `<span class="nl-kv-in"><input id="nl-pack-in" type="number" min="0" step="any" value="${st.pack ? esc(String(st.pack.currency === k.currency ? st.pack.value : +(+k.pack || st.pack.value).toFixed(4))) : ''}" placeholder="0" onchange="flNlSet('${id}','pack',this.value)"><em>${esc(k.currency)}</em></span>`),
431
+ kv(`<label for="nl-labor-in" data-tip="What one batch costs in wages.">Labor per batch</label>`, `<span class="nl-kv-in"><input id="nl-labor-in" type="number" min="0" step="any" value="${st.labor ? esc(String(st.labor.currency === k.currency ? st.labor.value : +(+k.labor || st.labor.value).toFixed(4))) : ''}" placeholder="0" onchange="flNlSet('${id}','labor',this.value)"><em>${esc(k.currency)}</em></span>`),
432
+ kv(`<label for="nl-batch-in" data-tip="The weight of mix one batch makes.">Batch size</label>`, `<span class="nl-kv-in"><input id="nl-batch-in" type="number" min="0" step="any" value="${st.batch != null ? esc(String(st.batch)) : ''}" placeholder="0" onchange="flNlSet('${id}','batch',this.value)"><em>kg</em></span>`),
433
+ kv(`<label for="nl-over-in" data-tip="Rent, energy and the rest, as a percent on top of ingredients, packaging and labor.">Overhead</label>`, `<span class="nl-kv-in"><input id="nl-over-in" type="number" min="0" max="${FL_NL_OVERHEAD_MAX}" step="any" value="${st.overhead != null ? esc(String(st.overhead)) : ''}" placeholder="0" onchange="flNlSet('${id}','overhead',this.value)"><em>%</em></span>`),
434
+ kv('Labor and overhead per serving', k.labor || k.overheadPct ? `<strong>${m(k.laborServing + k.overheadServing)}</strong>` : '<span class="nl-dim">—</span>'),
435
+ kv(`Per kg${st.yield ? ' as sold' : ''}`, `<strong>${m(k.perKgSold)}</strong>`, st.yield ? `As mixed: ${_nlMoney(k.perKgMixed, k.currency)} / kg, at ${_nlNum(st.yield)}% yield.` : ''),
436
+ kv('Sell price per serving', p ? `<strong>${m(p.perServing)}</strong>` : '<span class="nl-dim">—</span>', p && p.perContainer != null ? `${_nlMoney(p.perContainer, k.currency)} per container.` : ''),
437
+ kv(`<label for="nl-goal-in" data-tip="The margin you want to keep. The chip says how far a serving’s cost is from it.">Margin goal</label>`, `<span class="nl-kv-in"><input id="nl-goal-in" type="number" min="1" max="99" step="any" value="${st.goal != null ? esc(String(st.goal)) : ''}" placeholder="60" onchange="flNlSet('${id}','goal',this.value)"><em>%</em></span>`),
438
+ kv('Against the goal', goalState || '<span class="nl-dim">—</span>'),
439
+ ].join('');
440
+ const idle = (k.packIdle ? `<div class="nl-note warn">Packaging needs Servings per container. Not counted.</div>` : '')
441
+ + (k.laborIdle ? `<div class="nl-note warn">Labor needs a batch size. Not counted.</div>` : '');
371
442
  const warn = k.unpriced.length ? `<div class="nl-note warn" data-tip="${esc(k.unpriced.slice(0, 12).join(', '))}">${k.unpriced.length} ${k.unpriced.length === 1 ? 'row has' : 'rows have'} no price. Counted as 0.</div>` : '';
372
- return `<div class="card">
443
+ // Where it goes: the six largest, the rest as one line.
444
+ const TOP = 6, parts = k.parts || [], head = parts.slice(0, TOP), rest = parts.slice(TOP);
445
+ const most = head.length ? head[0].perServing : 0;
446
+ const bar = (name, v, share, kind, tip) => `<div class="nl-bar-n"${tip ? ` data-tip="${esc(tip)}"` : ' data-tip-cropped data-tip="' + esc(name) + '"'}>${esc(name)}</div><div class="nl-bar-t"><span class="nl-bar-f${kind === 'pack' || kind === 'labor' || kind === 'over' ? ' pack' : kind === 'rest' ? ' rest' : ''}" style="width:${Math.max(2, Math.round(v / (most || 1) * 100))}%"></span></div><div class="nl-bar-v">${m(v)}</div><div class="nl-bar-p">${esc(String(share >= 10 ? Math.round(share) : +share.toFixed(1)))}%</div>`;
447
+ const bars = head.map(x => bar(x.name, x.perServing, x.share, x.kind)).join('')
448
+ + (rest.length ? bar(`${rest.length} more`, rest.reduce((a, x) => a + x.perServing, 0), rest.reduce((a, x) => a + x.share, 0), 'rest', rest.map(x => `${x.name} ${_nlMoney(x.perServing, k.currency)}`).join(', ')) : '');
449
+ return `<div class="card nl-costcard">
373
450
  <div class="card-header"><h2>Cost</h2><span id="nl-cost-saved" class="fl-saved-tick" role="status"></span></div>
374
451
  <div class="card-body">
452
+ <div class="nl-tiles">${tiles}</div>
453
+ <div class="nl-kv">${grid}</div>
375
454
  ${warn}${idle}
376
- <div class="table-wrapper"><table class="nl-table nl-cost"><tbody>${rows.join('')}${priceRows.length ? `<tr class="nl-cost-gap"><td colspan="2"></td></tr>${priceRows.join('')}` : ''}</tbody></table></div>
377
- <div class="nl-dim nl-hint" data-tip="From each ingredient’s price and the amounts in the Composition tab${k.pack ? ', plus the packaging you typed' : ''}. Labor and overhead are not in it.${p ? '' : ' Set a target sell price on the Composition tab’s Pricing & Margin panel to see the margin per serving.'}">${k.pack ? 'Ingredients and packaging.' : 'Ingredients only.'}${p ? '' : ' Add a sell price in Pricing &amp; Margin for the margin.'}</div>
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>
378
456
  </div>
379
- </div>`;
457
+ </div>
458
+ ${parts.length > 1 ? `<div class="card">
459
+ <div class="card-header"><h2>Where a serving’s cost goes</h2></div>
460
+ <div class="card-body"><div class="nl-bars">${bars}</div></div>
461
+ </div>` : ''}`;
380
462
  }
381
463
 
382
464
  // ── Ingredient statement and Contains ───────────────────────
@@ -432,6 +514,28 @@ function flNlEuStatement(f) {
432
514
  return { html: html ? html + '.' : '', text: text ? text + '.' : '', allergens: found, count: items.length };
433
515
  }
434
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
+ }
435
539
  function flNlStatement(f) {
436
540
  const items = _nlStatementItems(f);
437
541
  const major = items.filter(x => x.w > 0.02), minor = items.filter(x => x.w <= 0.02);
@@ -551,7 +655,7 @@ function flNlPanelHtml(f, calc, tease) {
551
655
  function flNlTabButtonHtml(f) {
552
656
  if (!f || !flNlHasFoodData(f)) return '';
553
657
  const pro = typeof hasFeature !== 'function' || hasFeature('formulations.nutritionLabel');
554
- return `<div class="tab" data-tab="label" onclick="switchFormTab('label')" title="Nutrition Facts, ingredient statement and allergens for this formula">Label${pro ? '' : ' <span class="asm-designer-pro-badge usda-pro">Pro</span>'}</div>`;
658
+ return `<div class="tab" data-tab="label" onclick="switchFormTab('label')">Label${pro ? '' : ' <span class="asm-designer-pro-badge usda-pro">Pro</span>'}</div>`;
555
659
  }
556
660
  function _nlFmt(v) {
557
661
  if (v == null || !Number.isFinite(v)) return '—';
@@ -576,7 +680,7 @@ function flNlTabHtml(f) {
576
680
  const c = flNlCompute(f);
577
681
  if (!c.ok) {
578
682
  const who = (c.needsDensity || []).slice(0, 6).join(', ');
579
- 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>`;
580
684
  }
581
685
  const st = _nlSettings(f);
582
686
  const lines = flNlLines(f, c);
@@ -588,6 +692,9 @@ function flNlTabHtml(f) {
588
692
  ? `<div class="nl-note warn nl-dens" data-tip="Set Finished Density on the formula (Edit), or a density on every ingredient.">No density on this formula. Counted as 1 g/mL.</div>`
589
693
  : `<div class="nl-dim nl-dens"${sv.source === 'ideal' ? ' data-tip="Estimated from the ingredients’ densities. Set Finished Density on the formula (Edit) to use a measured one."' : ''}>${_nlNum(sv.amount)} mL = ${_nlFmt(sv.g)} g at ${+sv.density.toFixed(4)} g/mL (${sv.source === 'finished' ? 'finished density' : 'estimated'}).</div>`;
590
694
  const sim = flNlSimplified(f, lines);
695
+ // The left column shows one of two sets under Serving, so the tab stays short: the label's text and numbers, or
696
+ // what it costs (1.16.20 11c). A viewer's own choice, kept in the browser; nothing is saved on the formula.
697
+ const view = flNlView();
591
698
  // Insignificant only because no ingredient has the field: say so before anyone prints a simplified label on it.
592
699
  const blank = lines.filter(l => sim.insignificant.includes(l.key) && (c.missing[l.key] || []).length >= c.withData).map(l => l.label);
593
700
  const fseg = (k, t, tip) => `<button type="button" class="fl-seg${sim.use === k ? ' on' : ''}" aria-pressed="${sim.use === k}" data-tip="${tip}" onclick="flNlSet('${id}','format','${k}')">${t}</button>`;
@@ -596,15 +703,20 @@ function flNlTabHtml(f) {
596
703
  const eu = st.region === 'eu';
597
704
  const rseg = (k, t, tip) => `<button type="button" class="fl-seg${st.region === k ? ' on' : ''}" aria-pressed="${st.region === k}" data-tip="${tip}" onclick="flNlSet('${id}','region','${k}')">${t}</button>`;
598
705
  const region = `<span class="fl-seg-group sm" role="group" aria-label="Label region">${rseg('us', 'US', 'Nutrition Facts (FDA).')}${rseg('eu', 'EU', 'Nutrition declaration per 100 g: kJ and kcal, salt.')}</span>`;
599
- const fmt = eu ? `<div class="nl-fmt">${region}<span id="nl-fmt-saved" class="fl-saved-tick" role="status"></span></div>` : `<div class="nl-fmt">${region}<span class="fl-seg-group sm" role="group" aria-label="Label format">${fseg('standard', 'Standard', 'The vertical panel.')}${fseg('tabular', 'Tabular', 'Horizontal, for a package without the height.')}${fseg('linear', 'Linear', 'One paragraph, for a small package where Tabular won’t fit.')}${sim.servings > 1 ? fseg('dual', 'Dual', 'Per serving beside the whole container.') : `<button type="button" class="fl-seg nl-seg-off" aria-disabled="true" data-tip="Needs Servings per container above 1." onclick="var e=document.getElementById('nl-servings-in');if(e)e.focus()">Dual</button>`}${sim.eligible ? fseg('simplified', 'Simplified', sim.count + ' of 15 nutrients are insignificant here; 8 or more allow it.') : ''}</span><span id="nl-fmt-saved" class="fl-saved-tick" role="status"></span></div>${blank.length && sim.use === 'simplified' ? `<div class="nl-note warn nl-fmt-warn" data-tip="${esc(blank.join(', '))}">${blank.length === sim.count ? 'All ' + sim.count : blank.length + ' of the ' + sim.count} have no data. Blank is not zero.</div>` : ''}`;
706
+ const fmt = eu ? `<div class="nl-fmt">${region}<span class="fl-seg-group sm" role="group" aria-label="Reference intake"><button type="button" class="fl-seg${st.ri ? '' : ' on'}" aria-pressed="${!st.ri}" data-tip="The values only." onclick="flNlSet('${id}','ri','')">Plain</button><button type="button" class="fl-seg${st.ri ? ' on' : ''}" aria-pressed="${st.ri}" data-tip="Adds the percent of an adult’s reference intake${st.serving != null ? ', per portion' : ''}." onclick="flNlSet('${id}','ri','on')">% RI</button></span><span id="nl-fmt-saved" class="fl-saved-tick" role="status"></span></div>` : `<div class="nl-fmt">${region}<span class="fl-seg-group sm" role="group" aria-label="Label format">${fseg('standard', 'Standard', 'The vertical panel.')}${fseg('tabular', 'Tabular', 'Horizontal, for a package without the height.')}${fseg('linear', 'Linear', 'One paragraph, for a small package where Tabular won’t fit.')}${sim.servings > 1 ? fseg('dual', 'Dual', 'Per serving beside the whole container.') : `<button type="button" class="fl-seg nl-seg-off" aria-disabled="true" data-tip="Needs Servings per container above 1." onclick="var e=document.getElementById('nl-servings-in');if(e)e.focus()">Dual</button>`}${sim.eligible ? fseg('simplified', 'Simplified', sim.count + ' of 15 nutrients are insignificant here; 8 or more allow it.') : ''}</span><span id="nl-fmt-saved" class="fl-saved-tick" role="status"></span></div>${blank.length && sim.use === 'simplified' ? `<div class="nl-note warn nl-fmt-warn" data-tip="${esc(blank.join(', '))}">${blank.length === sim.count ? 'All ' + sim.count : blank.length + ' of the ' + sim.count} have no data. Blank is not zero.</div>` : ''}`;
600
707
  const by = c.yield ? null : flNlBatchYield(f);
601
708
  const yld = c.yield
602
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>`
603
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>` : '';
604
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] || []))];
605
715
  const cover = c.noData.length
606
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>`
607
- : `<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>`;
608
720
  const E = eu ? flNlEu(f, c) : null;
609
721
  const tbl = eu ? '' : lines.map(l => {
610
722
  const miss = c.missing[l.key];
@@ -615,27 +727,27 @@ function flNlTabHtml(f) {
615
727
  <td class="num"><strong>${l.text}</strong> <span class="u">${esc(l.unit)}</span></td>
616
728
  <td class="num">${l.pct == null ? '' : l.pct + '%'}</td></tr>`;
617
729
  }).join('');
618
- 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' : ''}">
619
731
  <div class="nl-side">
620
732
  <div class="card">
621
733
  <div class="card-header"><h2>Serving</h2><span id="nl-saved" class="fl-saved-tick" role="status"></span></div>
622
734
  <div class="card-body nl-form">
623
- <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>
624
- <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>
625
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>
626
- <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>
627
739
  ${dens}${yld}
628
740
  </div>
629
741
  </div>
630
- ${_nlCostCardHtml(f)}
631
- <div class="card">
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>
743
+ ${view === 'cost' ? _nlCostCardHtml(f) : `<div class="card">
632
744
  <div class="card-header"><h2>Ingredient statement</h2>
633
745
  <button class="btn btn-secondary btn-sm" onclick="flNlCopyStatement('${id}')">Copy</button></div>
634
746
  <div class="card-body nl-stmt">
635
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>
636
- ${es.allergens.length ? '' : '<div class="nl-dim">No EU allergens on the ingredients.</div>'}
748
+ ${_nlSuspectHtml(f) || (es.allergens.length ? '' : '<div class="nl-dim">No EU allergens on the ingredients.</div>')}
637
749
  <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>
638
- ${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>'}
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>')}
639
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>`}
640
752
  </div>
641
753
  </div>
@@ -643,10 +755,10 @@ function flNlTabHtml(f) {
643
755
  <div class="card-header"><h2>Numbers</h2></div>
644
756
  <div class="card-body">
645
757
  ${cover}
646
- ${eu ? `<div class="table-wrapper"><table class="nl-table"><thead><tr><th>Nutrient</th><th class="num">Per ${E.basis}</th>${E.portion ? `<th class="num">Per portion (${esc(E.portion)})</th>` : ''}</tr></thead><tbody>${E.rows.map(r => `<tr><td class="${r.indent ? 'nl-t-in1' : ''}">${r.label}</td><td class="num"><strong>${r.per}</strong></td>${E.portion ? `<td class="num"><strong>${r.portion}</strong></td>` : ''}</tr>`).join('')}</tbody></table></div>
758
+ ${eu ? `<div class="table-wrapper"><table class="nl-table"><thead><tr><th>Nutrient</th><th class="num">Per ${E.basis}</th>${E.portion ? `<th class="num">Per portion (${esc(E.portion)})</th>` : ''}${E.ri ? '<th class="num">% RI</th>' : ''}</tr></thead><tbody>${E.rows.map(r => `<tr><td class="${r.indent ? 'nl-t-in1' : ''}">${r.label}</td><td class="num"><strong>${r.per}</strong></td>${E.portion ? `<td class="num"><strong>${r.portion}</strong></td>` : ''}${E.ri ? `<td class="num">${r.ri || ''}</td>` : ''}</tr>`).join('')}</tbody></table></div>
647
759
  <div class="nl-dim nl-hint" data-tip="Energy from the EU factors (fat 37 kJ / 9 kcal, carbohydrate and protein 17 / 4, fibre 8 / 2). Carbohydrate leaves the fibre out. Salt = sodium × 2.5.">As declared. Carbohydrate without fibre; salt from sodium.</div>` : `<div class="table-wrapper"><table class="nl-table"><thead><tr><th>Nutrient</th><th class="num">Per 100 g${c.yield ? ' sold' : ''}</th><th class="num">Per ${per}</th><th class="num">On label</th><th class="num">% DV</th></tr></thead><tbody>${tbl}</tbody></table></div>`}
648
760
  </div>
649
- </div>
761
+ </div>`}
650
762
  </div>
651
763
  <div class="nl-main">
652
764
  <div class="card">
@@ -662,30 +774,74 @@ function flNlTabHtml(f) {
662
774
  </div>
663
775
  </div>
664
776
  </div>
665
- </div>`;
777
+ </div>`, id);
666
778
  }
667
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
+ }
796
+ function flNlView() { try { return localStorage.getItem('formlab_nl_view') === 'cost' ? 'cost' : 'nutrition'; } catch (_) { return 'nutrition'; } }
797
+ function flNlSetView(fid, v) {
798
+ try { localStorage.setItem('formlab_nl_view', v === 'cost' ? 'cost' : 'nutrition'); } catch (_) {}
799
+ const f = (db.formulations || []).find(x => x.id === fid), el = document.getElementById('tab-label');
800
+ if (f && el) el.innerHTML = flNlTabHtml(f);
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
+ }
668
809
  // Save one serving field on the formula, then redraw the tab.
669
810
  function flNlSet(fid, key, value) {
670
811
  const f = (db.formulations || []).find(x => x.id === fid);
671
- if (!f || !['serving', 'unit', 'format', 'region', 'yield', 'pack', 'household', 'servings'].includes(key)) return;
812
+ if (!f || !['serving', 'unit', 'format', 'region', 'yield', 'pack', 'goal', 'labor', 'batch', 'overhead', 'ri', 'household', 'servings'].includes(key)) return;
672
813
  const l = { ...(f.label || {}) };
673
814
  if (key === 'serving') { const n = parseFloat(String(value).replace(',', '.')); if (Number.isFinite(n) && n > 0 && n <= FL_NL_MAX_SERVING) l.serving = n; else { delete l.serving; if (String(value).trim() && typeof toast === 'function') toast('Serving size: 0 to ' + FL_NL_MAX_SERVING + '.'); } }
674
815
  else if (key === 'format') { if (['simplified', 'tabular', 'linear', 'dual'].includes(value)) l.format = value; else delete l.format; }
675
816
  else if (key === 'yield') { const n = parseFloat(String(value).replace(',', '.')); if (Number.isFinite(n) && n >= FL_NL_YIELD[0] && n <= FL_NL_YIELD[1] && n !== 100) l.yield = n; else { delete l.yield; if (String(value).trim() && n !== 100 && typeof toast === 'function') toast('Cooking yield: ' + FL_NL_YIELD[0] + ' to ' + FL_NL_YIELD[1] + ' %.'); } }
676
- else if (key === 'pack') {
817
+ else if (key === 'goal') { const n = parseFloat(String(value).replace(',', '.')); if (Number.isFinite(n) && n >= 1 && n <= 99) l.goal = n; else { delete l.goal; if (String(value).trim() && typeof toast === 'function') toast('Margin goal: 1 to 99 %.'); } }
818
+ else if (key === 'ri') { if (value === 'on') l.ri = true; else delete l.ri; }
819
+ else if (key === 'batch') { const n = parseFloat(String(value).replace(',', '.')); if (Number.isFinite(n) && n >= 0.001 && n <= FL_NL_PACK_MAX) l.batch = n; else { delete l.batch; if (String(value).trim() && n !== 0 && typeof toast === 'function') toast('Batch size: 0.001 to ' + FL_NL_PACK_MAX.toLocaleString() + ' kg.'); } }
820
+ else if (key === 'overhead') { const n = parseFloat(String(value).replace(',', '.')); if (Number.isFinite(n) && n > 0 && n <= FL_NL_OVERHEAD_MAX) l.overhead = n; else { delete l.overhead; if (String(value).trim() && n !== 0 && typeof toast === 'function') toast('Overhead: 0 to ' + FL_NL_OVERHEAD_MAX + ' %.'); } }
821
+ else if (key === 'pack' || key === 'labor') {
677
822
  const n = parseFloat(String(value).replace(',', '.'));
678
- if (Number.isFinite(n) && n > 0 && n <= FL_NL_PACK_MAX) { const k0 = flNlCost(f); l.pack = { value: n, currency: (k0.ok && k0.currency) || (typeof getDisplayCurrency === 'function' && getDisplayCurrency()) || 'USD' }; }
679
- else { delete l.pack; if (String(value).trim() && n !== 0 && typeof toast === 'function') toast('Packaging: 0 to ' + FL_NL_PACK_MAX.toLocaleString() + '.'); }
823
+ if (Number.isFinite(n) && n > 0 && n <= FL_NL_PACK_MAX) { const k0 = flNlCost(f); l[key] = { value: n, currency: (k0.ok && k0.currency) || (typeof getDisplayCurrency === 'function' && getDisplayCurrency()) || 'USD' }; }
824
+ else { delete l[key]; if (String(value).trim() && n !== 0 && typeof toast === 'function') toast((key === 'labor' ? 'Labor' : 'Packaging') + ': 0 to ' + FL_NL_PACK_MAX.toLocaleString() + '.'); }
680
825
  }
681
826
  else if (key === 'region') { if (value === 'eu') l.region = 'eu'; else delete l.region; }
682
827
  else if (key === 'unit') { if (value === 'mL') l.unit = 'mL'; else delete l.unit; }
683
828
  else { const t = String(value || '').trim().slice(0, key === 'household' ? 80 : 40); if (t) l[key] = t; else delete l[key]; }
684
829
  f.label = l;
685
830
  const saved = typeof _fmlSyncSave === 'function' && _fmlSyncSave(f, ['label']);
686
- const el = document.getElementById('tab-label');
687
- if (el) el.innerHTML = flNlTabHtml(f);
688
- if (saved && typeof flSavedTick === 'function') flSavedTick(key === 'format' || key === 'region' ? 'nl-fmt-saved' : key === 'pack' ? 'nl-cost-saved' : 'nl-saved');
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 = () => {
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();
689
845
  }
690
846
 
691
847
  function _nlFile(f) { return 'nutrition-facts-' + String(f.uid || f.name || 'formula').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase(); }
@@ -770,7 +926,7 @@ const FL_NL_PANEL_CSS = `.nl-panel{box-sizing:border-box;width:280px;padding:4px
770
926
  .nl-panel.nl-eu th,.nl-panel.nl-eu td{background:rgb(255,255,255)!important;color:#000!important}
771
927
  .nl-eu th{font-weight:700;border-bottom-width:1.5px;white-space:normal}.nl-eu th:first-child{width:38%}.nl-eu th:first-child,.nl-eu td:first-child{text-align:left}
772
928
  .nl-eu th + th,.nl-eu td + td{border-left:1px solid #000}
773
- .nl-eu tr:last-child td{border-bottom:0}.nl-eu .nl-e-in td:first-child{padding-left:16px}`;
929
+ .nl-eu tr:last-child td{border-bottom:0}.nl-ri th:first-child{width:37%}.nl-eu th.nl-e-ri{width:13%}.nl-eu.nl-ri td{white-space:normal}.nl-eu.nl-ri .nl-e-in td:first-child{padding-left:12px}.nl-eu .nl-e-note td{text-align:left;font-size:9.5px;white-space:normal}.nl-eu .nl-e-note td + td{border-left:0}.nl-eu .nl-e-in td:first-child{padding-left:16px}`;
774
930
  function flNlPrint(fid) {
775
931
  if (!_nlGate()) return;
776
932
  if (typeof flExportAllowed === 'function' && !flExportAllowed('single', 'a nutrition label print')) return; // what members can take out (0114)
@@ -788,7 +944,7 @@ function flNlPrint(fid) {
788
944
  <h1>${esc(f.name || '')}</h1><div class="meta">${esc([f.uid, 'calculated from ingredient data', 'printed ' + new Date().toLocaleDateString()].filter(Boolean).join(' · '))}</div>
789
945
  ${flNlPanelHtml(f)}
790
946
  <div class="stmt">${_nlSettings(f).region === 'eu' ? (() => { const es = flNlEuStatement(f); return es.html ? `<div><b>INGREDIENTS:</b> ${es.html}</div>` : ''; })() : `${s.text ? `<div><b>INGREDIENTS:</b> ${esc(s.text)}</div>` : ''}${s.contains.length ? `<div><b>CONTAINS:</b> ${esc(s.contains.join(', '))}.</div>` : ''}`}</div>
791
- ${(() => { const cl = flNlCostLines(f); return cl.length ? `<table class="cost"><caption>Cost to make (${flNlCost(f).pack ? 'ingredients and packaging' : 'ingredients only'})</caption>${cl.map(([a, b]) => `<tr><td>${esc(a)}</td><td>${esc(b)}</td></tr>`).join('')}</table>` : ''; })()}
947
+ ${(() => { const cl = flNlCostLines(f); return cl.length ? `<table class="cost"><caption>Cost to make (${(b => b.length > 1 ? _nlList(b) : 'ingredients only')(flNlCost(f).basis)})</caption>${cl.map(([a, b]) => `<tr><td>${esc(a)}</td><td>${esc(b)}</td></tr>`).join('')}</table>` : ''; })()}
792
948
  <script>window.onload=()=>setTimeout(()=>window.print(),250)<\/script></body></html>`);
793
949
  win.document.close();
794
950
  if (typeof flPreparePrintWindow === 'function') flPreparePrintWindow(win);