formlab-mcp 0.6.86 → 0.6.87

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.87",
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.87",
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.87",
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
  }
@@ -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
 
@@ -304,15 +324,43 @@ function flNlCost(f) {
304
324
  const conv = st.pack.currency === c.currency ? st.pack.value : (typeof convertCurrencySync === 'function' ? convertCurrencySync(st.pack.value, st.pack.currency, c.currency) : null);
305
325
  if (n > 0 && Number.isFinite(conv)) out.pack = conv; else out.packIdle = true; // no servings per container (or no rate): not counted
306
326
  }
307
- out.perContainer = n > 0 ? out.perServing * n + (out.pack || 0) : null;
308
- out.perServingPacked = out.pack ? out.perContainer / n : null;
327
+ out.perServingPacked = out.pack ? out.perServing + out.pack / n : null;
328
+ // Labor: per batch of mix, so a serving's share is labor ÷ batch kg × the kg of mix a serving took. Overhead: a
329
+ // percent on top of ingredients, packaging and labor (1.16.20 11d).
330
+ const k1 = 100 / y * sv.g / 1000;
331
+ out.labor = null; out.laborIdle = false; out.laborServing = 0;
332
+ if (st.labor) {
333
+ const conv = st.labor.currency === c.currency ? st.labor.value : (typeof convertCurrencySync === 'function' ? convertCurrencySync(st.labor.value, st.labor.currency, c.currency) : null);
334
+ 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;
335
+ }
336
+ const before = out.perServing + (out.pack ? out.pack / n : 0) + out.laborServing;
337
+ out.overheadPct = st.overhead; out.overheadServing = st.overhead ? before * st.overhead / 100 : 0;
338
+ out.perServingFull = before + out.overheadServing; // everything counted: what the tiles, the margin and the goal use
339
+ out.perContainer = n > 0 ? out.perServingFull * n : null;
340
+ out.basis = ['ingredients', out.pack ? 'packaging' : '', out.labor ? 'labor' : '', st.overhead ? 'overhead' : ''].filter(Boolean);
341
+ // 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
342
+ // its size. A row's contribution is per kg of mix, so it scales the same way the total does.
343
+ const parts = [];
344
+ (c.breakdown || []).forEach(b => {
345
+ const v = (b && Number.isFinite(b.contribution) ? b.contribution : 0) * k1;
346
+ const name = b && ((b.ingredient && b.ingredient.name) || (b.subFormula && b.subFormula.name)) || '';
347
+ 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' }); }
348
+ });
349
+ if (out.pack) parts.push({ name: 'Packaging', perServing: out.pack / n, kind: 'pack' });
350
+ if (out.labor) parts.push({ name: 'Labor', perServing: out.laborServing, kind: 'labor' });
351
+ if (out.overheadServing > 0) parts.push({ name: 'Overhead', perServing: out.overheadServing, kind: 'over' });
352
+ const whole = parts.reduce((a, p) => a + p.perServing, 0);
353
+ parts.forEach(p => { p.share = whole > 0 ? p.perServing / whole * 100 : 0; });
354
+ out.parts = parts.sort((a, b) => b.perServing - a.perServing);
309
355
  out.unpriced = (c.missing || []).map(m => (m && ((m.ingredient && m.ingredient.name) || (m.subFormula && m.subFormula.name) || m.reason)) || '').filter(Boolean);
310
356
  if (hasPrice) {
311
357
  const basis = pr.basisUnit || 'kg';
312
358
  const perKg = basis === 'kg' ? target : (typeof convertPricePerBasis === 'function' ? convertPricePerBasis(target, basis, 'kg', sv.density || (typeof _rolledUpDensity === 'function' ? _rolledUpDensity(f) : null)) : null);
313
359
  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
360
+ const ps = perKg * sv.g / 1000, cs = out.perServingFull; // with packaging, labor and overhead
315
361
  out.price = { perKg, perServing: ps, perContainer: n > 0 ? ps * n : null, profitServing: ps - cs, marginPct: (ps - cs) / ps * 100 };
362
+ // The margin goal (1.16.20 11c): the most a serving may cost to keep it, and how far the serving is from that.
363
+ 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
364
  }
317
365
  }
318
366
  return out;
@@ -327,19 +375,25 @@ function _nlMoney(v, ccy) {
327
375
  const whole = formatMoney(1, ccy), digits = +v.toPrecision(3);
328
376
  return whole.replace(/1([.,]0+)?/, String(digits));
329
377
  }
378
+ const _nlList = (a) => a.length < 2 ? a.join('') : a.slice(0, -1).join(', ') + ' and ' + a[a.length - 1];
330
379
  // The cost as lines of text, for the print and for the MCP tool's reader: [[label, value], …]; [] with no cost.
331
380
  function flNlCostLines(f) {
332
381
  const k = flNlCost(f);
333
382
  if (!k.ok) return [];
334
383
  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)]);
384
+ const more = k.basis.length > 1;
385
+ const out = [[`Cost per serving (${_nlNum(sv.amount)} ${sv.unit})${more ? ', ingredients' : ''}`, m(k.perServing)]];
386
+ if (k.pack) out.push(['Packaging per container', m(k.pack)]);
387
+ if (k.labor) out.push([`Labor per batch (${_nlNum(st.batch)} kg)`, m(k.labor)], ['Labor per serving', m(k.laborServing)]);
388
+ if (k.overheadPct) out.push([`Overhead ${_nlNum(k.overheadPct)}% per serving`, m(k.overheadServing)]);
389
+ if (more) out.push([`Cost per serving with ${_nlList(k.basis.slice(1))}`, m(k.perServingFull)]);
390
+ if (k.perContainer != null) out.push([`Cost per container (${st.servings} servings)`, m(k.perContainer)]);
338
391
  out.push([`Cost per kg${st.yield ? ` as sold (${_nlNum(st.yield)}% yield)` : ''}`, m(k.perKgSold)]);
339
392
  if (k.price) {
340
393
  out.push(['Sell price per serving', m(k.price.perServing)]);
341
394
  if (k.price.perContainer != null) out.push(['Sell price per container', m(k.price.perContainer)]);
342
395
  out.push(['Margin', `${+k.price.marginPct.toFixed(1)}%`]);
396
+ 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
397
  }
344
398
  if (k.unpriced.length) out.push(['Rows with no price (counted as 0)', k.unpriced.slice(0, 12).join(', ')]);
345
399
  return out;
@@ -350,33 +404,53 @@ function _nlCostCardHtml(f) {
350
404
  <div class="card-header"><h2>Cost</h2></div>
351
405
  <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
406
  </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>` : '';
407
+ const sv = flNlServing(f), st = _nlSettings(f), m = v => esc(_nlMoney(v, k.currency)), id = esc(f.id), p = k.price;
408
+ const one = k.perServingFull, extras = k.basis.slice(1);
409
+ // Three numbers first, the working behind them under it (Jun, 17 Nov: "pretty and organized", not deep).
410
+ 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
+ const tiles = [
412
+ tile('Per serving', m(one), `${esc(_nlNum(sv.amount))} ${sv.unit}${extras.length ? ' · with ' + esc(_nlList(extras)) : ''}`),
413
+ k.perContainer != null ? tile('Per container', m(k.perContainer), `${esc(st.servings)} servings`) : tile('Per container', '—', 'Set Servings per container', 'off'),
414
+ p ? tile('Margin', `${esc(String(+p.marginPct.toFixed(1)))}%`, `${esc(_nlMoney(p.profitServing, k.currency))} per serving`, p.marginPct >= 0 ? 'good' : 'bad')
415
+ : tile('Margin', '—', 'Add a sell price in Pricing &amp; Margin', 'off'),
416
+ ].join('');
417
+ const kv = (label, val, tip) => `<div class="nl-kv-l"${tip ? ` data-tip="${esc(tip)}"` : ''}>${label}</div><div class="nl-kv-v">${val}</div>`;
418
+ const goalState = !st.goal ? '' : !p ? `<span class="nl-chip off">needs a sell price</span>`
419
+ : `<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>`;
420
+ const grid = [
421
+ kv('Ingredients per serving', `<strong>${m(k.perServing)}</strong>`),
422
+ 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>`),
423
+ 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>`),
424
+ 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>`),
425
+ 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>`),
426
+ kv('Labor and overhead per serving', k.labor || k.overheadPct ? `<strong>${m(k.laborServing + k.overheadServing)}</strong>` : '<span class="nl-dim">—</span>'),
427
+ 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.` : ''),
428
+ 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.` : ''),
429
+ 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>`),
430
+ kv('Against the goal', goalState || '<span class="nl-dim">—</span>'),
431
+ ].join('');
432
+ const idle = (k.packIdle ? `<div class="nl-note warn">Packaging needs Servings per container. Not counted.</div>` : '')
433
+ + (k.laborIdle ? `<div class="nl-note warn">Labor needs a batch size. Not counted.</div>` : '');
371
434
  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">
435
+ // Where it goes: the six largest, the rest as one line.
436
+ const TOP = 6, parts = k.parts || [], head = parts.slice(0, TOP), rest = parts.slice(TOP);
437
+ const most = head.length ? head[0].perServing : 0;
438
+ 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>`;
439
+ const bars = head.map(x => bar(x.name, x.perServing, x.share, x.kind)).join('')
440
+ + (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(', ')) : '');
441
+ return `<div class="card nl-costcard">
373
442
  <div class="card-header"><h2>Cost</h2><span id="nl-cost-saved" class="fl-saved-tick" role="status"></span></div>
374
443
  <div class="card-body">
375
444
  ${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>
445
+ <div class="nl-tiles">${tiles}</div>
446
+ <div class="nl-kv">${grid}</div>
447
+ <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
448
  </div>
379
- </div>`;
449
+ </div>
450
+ ${parts.length > 1 ? `<div class="card">
451
+ <div class="card-header"><h2>Where a serving’s cost goes</h2></div>
452
+ <div class="card-body"><div class="nl-bars">${bars}</div></div>
453
+ </div>` : ''}`;
380
454
  }
381
455
 
382
456
  // ── Ingredient statement and Contains ───────────────────────
@@ -551,7 +625,7 @@ function flNlPanelHtml(f, calc, tease) {
551
625
  function flNlTabButtonHtml(f) {
552
626
  if (!f || !flNlHasFoodData(f)) return '';
553
627
  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>`;
628
+ return `<div class="tab" data-tab="label" onclick="switchFormTab('label')">Label${pro ? '' : ' <span class="asm-designer-pro-badge usda-pro">Pro</span>'}</div>`;
555
629
  }
556
630
  function _nlFmt(v) {
557
631
  if (v == null || !Number.isFinite(v)) return '—';
@@ -588,6 +662,9 @@ function flNlTabHtml(f) {
588
662
  ? `<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
663
  : `<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
664
  const sim = flNlSimplified(f, lines);
665
+ // The left column shows one of two sets under Serving, so the tab stays short: the label's text and numbers, or
666
+ // what it costs (1.16.20 11c). A viewer's own choice, kept in the browser; nothing is saved on the formula.
667
+ const view = flNlView();
591
668
  // Insignificant only because no ingredient has the field: say so before anyone prints a simplified label on it.
592
669
  const blank = lines.filter(l => sim.insignificant.includes(l.key) && (c.missing[l.key] || []).length >= c.withData).map(l => l.label);
593
670
  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,7 +673,7 @@ function flNlTabHtml(f) {
596
673
  const eu = st.region === 'eu';
597
674
  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
675
  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>` : ''}`;
676
+ 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
677
  const by = c.yield ? null : flNlBatchYield(f);
601
678
  const yld = c.yield
602
679
  ? `<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>`
@@ -627,8 +704,8 @@ function flNlTabHtml(f) {
627
704
  ${dens}${yld}
628
705
  </div>
629
706
  </div>
630
- ${_nlCostCardHtml(f)}
631
- <div class="card">
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>
708
+ ${view === 'cost' ? _nlCostCardHtml(f) : `<div class="card">
632
709
  <div class="card-header"><h2>Ingredient statement</h2>
633
710
  <button class="btn btn-secondary btn-sm" onclick="flNlCopyStatement('${id}')">Copy</button></div>
634
711
  <div class="card-body nl-stmt">
@@ -643,10 +720,10 @@ function flNlTabHtml(f) {
643
720
  <div class="card-header"><h2>Numbers</h2></div>
644
721
  <div class="card-body">
645
722
  ${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>
723
+ ${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
724
  <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
725
  </div>
649
- </div>
726
+ </div>`}
650
727
  </div>
651
728
  <div class="nl-main">
652
729
  <div class="card">
@@ -665,18 +742,28 @@ function flNlTabHtml(f) {
665
742
  </div>`;
666
743
  }
667
744
 
745
+ function flNlView() { try { return localStorage.getItem('formlab_nl_view') === 'cost' ? 'cost' : 'nutrition'; } catch (_) { return 'nutrition'; } }
746
+ function flNlSetView(fid, v) {
747
+ try { localStorage.setItem('formlab_nl_view', v === 'cost' ? 'cost' : 'nutrition'); } catch (_) {}
748
+ const f = (db.formulations || []).find(x => x.id === fid), el = document.getElementById('tab-label');
749
+ if (f && el) el.innerHTML = flNlTabHtml(f);
750
+ }
668
751
  // Save one serving field on the formula, then redraw the tab.
669
752
  function flNlSet(fid, key, value) {
670
753
  const f = (db.formulations || []).find(x => x.id === fid);
671
- if (!f || !['serving', 'unit', 'format', 'region', 'yield', 'pack', 'household', 'servings'].includes(key)) return;
754
+ if (!f || !['serving', 'unit', 'format', 'region', 'yield', 'pack', 'goal', 'labor', 'batch', 'overhead', 'ri', 'household', 'servings'].includes(key)) return;
672
755
  const l = { ...(f.label || {}) };
673
756
  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
757
  else if (key === 'format') { if (['simplified', 'tabular', 'linear', 'dual'].includes(value)) l.format = value; else delete l.format; }
675
758
  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') {
759
+ 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 %.'); } }
760
+ else if (key === 'ri') { if (value === 'on') l.ri = true; else delete l.ri; }
761
+ 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.'); } }
762
+ 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 + ' %.'); } }
763
+ else if (key === 'pack' || key === 'labor') {
677
764
  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() + '.'); }
765
+ 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' }; }
766
+ 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
767
  }
681
768
  else if (key === 'region') { if (value === 'eu') l.region = 'eu'; else delete l.region; }
682
769
  else if (key === 'unit') { if (value === 'mL') l.unit = 'mL'; else delete l.unit; }
@@ -685,7 +772,7 @@ function flNlSet(fid, key, value) {
685
772
  const saved = typeof _fmlSyncSave === 'function' && _fmlSyncSave(f, ['label']);
686
773
  const el = document.getElementById('tab-label');
687
774
  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');
775
+ 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');
689
776
  }
690
777
 
691
778
  function _nlFile(f) { return 'nutrition-facts-' + String(f.uid || f.name || 'formula').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase(); }
@@ -770,7 +857,7 @@ const FL_NL_PANEL_CSS = `.nl-panel{box-sizing:border-box;width:280px;padding:4px
770
857
  .nl-panel.nl-eu th,.nl-panel.nl-eu td{background:rgb(255,255,255)!important;color:#000!important}
771
858
  .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
859
  .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}`;
860
+ .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
861
  function flNlPrint(fid) {
775
862
  if (!_nlGate()) return;
776
863
  if (typeof flExportAllowed === 'function' && !flExportAllowed('single', 'a nutrition label print')) return; // what members can take out (0114)
@@ -788,7 +875,7 @@ function flNlPrint(fid) {
788
875
  <h1>${esc(f.name || '')}</h1><div class="meta">${esc([f.uid, 'calculated from ingredient data', 'printed ' + new Date().toLocaleDateString()].filter(Boolean).join(' · '))}</div>
789
876
  ${flNlPanelHtml(f)}
790
877
  <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>` : ''; })()}
878
+ ${(() => { 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
879
  <script>window.onload=()=>setTimeout(()=>window.print(),250)<\/script></body></html>`);
793
880
  win.document.close();
794
881
  if (typeof flPreparePrintWindow === 'function') flPreparePrintWindow(win);