formlab-mcp 0.6.85 → 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 +1 -1
- package/server.json +2 -2
- package/theoretical.js +16 -1
- package/tools/formulations.js +1 -1
- package/vendor/nutrition-label.js +229 -20
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "formlab-mcp",
|
|
3
|
-
"version": "0.6.
|
|
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.
|
|
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.
|
|
11
|
+
"version": "0.6.87",
|
|
12
12
|
"runtimeHint": "npx",
|
|
13
13
|
"transport": {
|
|
14
14
|
"type": "stdio"
|
package/theoretical.js
CHANGED
|
@@ -47,6 +47,9 @@ const EPILOGUE = `
|
|
|
47
47
|
}
|
|
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
|
+
// 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). Labor, overhead and EU reference intakes: 0.6.87.
|
|
52
|
+
var localStorage = { getItem: function () { return null; }, setItem: function () {} };
|
|
50
53
|
// The app's HTML escaper (js/utils.js, not vendored): the EU list builds its bold version with it.
|
|
51
54
|
function esc(v) { return String(v == null ? '' : v).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); }
|
|
52
55
|
function rollupFormulaAllergens(f) {
|
|
@@ -77,10 +80,22 @@ function __nl(id) {
|
|
|
77
80
|
nutritionFacts: decl(lines),
|
|
78
81
|
perContainer: sim.servings > 1 ? decl(flNlLines(f, c, sim.servings)) : null,
|
|
79
82
|
simplified: { eligible: sim.eligible, insignificantNutrients: sim.count, statement: sim.eligible ? strip(_nlNotSource(lines, sim)) : null },
|
|
80
|
-
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,
|
|
81
85
|
ingredientList: eus.text, allergens: eus.allergens },
|
|
82
86
|
ingredientStatement: s.text, contains: s.contains,
|
|
83
87
|
coverage: { ingredients: c.rows, withNutrition: c.withData, noData: c.noData, missing: c.missing, energyFromPartialMacros: c.partial },
|
|
88
|
+
cost: (function () {
|
|
89
|
+
var k = flNlCost(f);
|
|
90
|
+
if (!k.ok) return null;
|
|
91
|
+
var r4 = function (v) { return v == null ? null : +(+v).toPrecision(4); };
|
|
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),
|
|
94
|
+
perContainer: r4(k.perContainer), perKgAsSold: r4(k.perKgSold), perKgAsMixed: r4(k.perKgMixed),
|
|
95
|
+
sellPricePerServing: k.price ? r4(k.price.perServing) : null, sellPricePerContainer: k.price ? r4(k.price.perContainer) : null,
|
|
96
|
+
marginPct: k.price ? +k.price.marginPct.toFixed(1) : null, unpricedRows: k.unpriced,
|
|
97
|
+
basis: k.basis.length > 1 ? _nlList(k.basis) : 'ingredients only' };
|
|
98
|
+
})(),
|
|
84
99
|
});
|
|
85
100
|
}
|
|
86
101
|
function __theo(kind, id) {
|
package/tools/formulations.js
CHANGED
|
@@ -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). `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: {
|
|
@@ -148,10 +148,23 @@ function flNlHasFoodData(f) {
|
|
|
148
148
|
const FL_NL_MAX_SERVING = 5000; // g; a larger serving is a typo
|
|
149
149
|
// Typed text only: a stored object or array is not a household measure ("[object Object]"; QA, 17 Nov).
|
|
150
150
|
const _nlStr = (v) => (typeof v === 'string' || typeof v === 'number') ? String(v).trim() : '';
|
|
151
|
+
// Packaging cost per container (1.16.20 11b): { value, currency } as typed, or null. One pack holds servings-per-container
|
|
152
|
+
// servings, so it only counts when that number is set.
|
|
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;
|
|
157
|
+
function _nlPack(p) {
|
|
158
|
+
const v = p && typeof p === 'object' ? parseFloat(p.value) : NaN;
|
|
159
|
+
if (!Number.isFinite(v) || !(v > 0) || v > FL_NL_PACK_MAX) return null;
|
|
160
|
+
return { value: v, currency: typeof p.currency === 'string' && /^[A-Z]{3}$/.test(p.currency) ? p.currency : 'USD' };
|
|
161
|
+
}
|
|
151
162
|
function _nlSettings(f) {
|
|
152
163
|
const l = (f && f.label) || {};
|
|
153
164
|
const s = parseFloat(l.serving), y = parseFloat(l.yield);
|
|
154
|
-
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)
|
|
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 };
|
|
155
168
|
}
|
|
156
169
|
// A serving in grams. A drink's serving is in mL (61r): grams = mL × the formula's density, the finished density
|
|
157
170
|
// when it has one, else the ideal-mix estimate; with neither, 1 g/mL and `noDensity` so the tab can say so.
|
|
@@ -238,6 +251,16 @@ function _nlEuRound(kind, v) {
|
|
|
238
251
|
return v <= low ? '<' + low : v < 10 ? v.toFixed(1) : String(Math.round(v));
|
|
239
252
|
}
|
|
240
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
|
+
}
|
|
241
264
|
function flNlEu(f, calc) {
|
|
242
265
|
const c = calc || flNlCompute(f), st = _nlSettings(f), sv = flNlServing(f), p = c.per100 || {};
|
|
243
266
|
const ml = sv.unit === 'mL';
|
|
@@ -249,23 +272,187 @@ function flNlEu(f, calc) {
|
|
|
249
272
|
const kJ = macros ? 37 * fat + 17 * carb + 17 * prot + 8 * fib : m('energy') * 4.184;
|
|
250
273
|
return { energy: `${Math.round(kJ)} kJ / ${Math.round(kcal)} kcal`, fat: _nlEuRound('g', fat) + ' g', sat_fat: _nlEuRound('sat', m('sat_fat')) + ' g',
|
|
251
274
|
carb: _nlEuRound('g', carb) + ' g', sugar: _nlEuRound('g', m('sugar')) + ' g', fiber: _nlEuRound('g', fib) + ' g', protein: _nlEuRound('g', prot) + ' g',
|
|
252
|
-
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 } };
|
|
253
277
|
};
|
|
254
278
|
const per = col(ml ? 100 * (sv.density || 1) : 100);
|
|
255
279
|
const portion = st.serving != null ? col(sv.g) : null;
|
|
256
280
|
const defs = [['energy', 'Energy'], ['fat', 'Fat'], ['sat_fat', 'of which saturates', 1], ['carb', 'Carbohydrate'], ['sugar', 'of which sugars', 1],
|
|
257
281
|
...(p.fiber > 0 ? [['fiber', 'Fibre']] : []), ['protein', 'Protein'], ['salt', 'Salt']];
|
|
282
|
+
const riOf = st.ri ? (portion || per) : null;
|
|
258
283
|
return { basis: ml ? '100 ml' : '100 g', portion: portion ? `${_nlNum(sv.amount)} ${ml ? 'ml' : 'g'}` : null,
|
|
259
|
-
|
|
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 })) };
|
|
260
286
|
}
|
|
261
287
|
function flNlEuPanelHtml(f, calc) {
|
|
262
288
|
const e = flNlEu(f, calc);
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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>
|
|
266
294
|
</table></div>`;
|
|
267
295
|
}
|
|
268
296
|
|
|
297
|
+
// ── Cost per serving (project 20, 1.16.20 11a) ──────────────
|
|
298
|
+
// What one serving and one container cost to make, from the formula's ingredient cost per kg (computeFormulationCost,
|
|
299
|
+
// the number the Composition tab totals), the serving's weight and the cooking yield: a kilogram sold took 1 ÷ yield
|
|
300
|
+
// kilograms of mix. Ingredients only: no packaging, labor or overhead. With a target sell price on the Pricing &
|
|
301
|
+
// Margin panel, the same per serving, and the margin. Money is in the price's currency when one is set, else the
|
|
302
|
+
// viewer's display currency.
|
|
303
|
+
// → { ok, currency, perKgMixed, perKgSold, perServing, perContainer, servings, unpriced: [names],
|
|
304
|
+
// price: { perKg, perServing, perContainer, profitServing, marginPct } | null } ; ok false: why
|
|
305
|
+
function flNlCost(f) {
|
|
306
|
+
const out = { ok: false, why: 'nocost', unpriced: [], price: null };
|
|
307
|
+
if (!f || typeof computeFormulationCost !== 'function') return out;
|
|
308
|
+
const pr = (f.pricing && typeof f.pricing === 'object') ? f.pricing : {};
|
|
309
|
+
const target = parseFloat(pr.targetPrice);
|
|
310
|
+
const hasPrice = Number.isFinite(target) && target > 0;
|
|
311
|
+
let c = null;
|
|
312
|
+
try { c = computeFormulationCost(f, hasPrice && pr.currency ? pr.currency : undefined, 'kg'); } catch (_) { c = null; }
|
|
313
|
+
if (!c || !Number.isFinite(c.perKg) || !(c.perKg > 0)) return out;
|
|
314
|
+
const st = _nlSettings(f), sv = flNlServing(f), y = st.yield || 100, n = flNlServingsCount(f);
|
|
315
|
+
out.ok = true; delete out.why;
|
|
316
|
+
out.currency = c.currency;
|
|
317
|
+
out.perKgMixed = c.perKg;
|
|
318
|
+
out.perKgSold = c.perKg * 100 / y;
|
|
319
|
+
out.perServing = out.perKgSold * sv.g / 1000;
|
|
320
|
+
out.servings = n;
|
|
321
|
+
// Packaging: in the card's currency, added to the container; a serving's share is the container ÷ servings.
|
|
322
|
+
out.pack = null; out.packIdle = false;
|
|
323
|
+
if (st.pack) {
|
|
324
|
+
const conv = st.pack.currency === c.currency ? st.pack.value : (typeof convertCurrencySync === 'function' ? convertCurrencySync(st.pack.value, st.pack.currency, c.currency) : null);
|
|
325
|
+
if (n > 0 && Number.isFinite(conv)) out.pack = conv; else out.packIdle = true; // no servings per container (or no rate): not counted
|
|
326
|
+
}
|
|
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);
|
|
355
|
+
out.unpriced = (c.missing || []).map(m => (m && ((m.ingredient && m.ingredient.name) || (m.subFormula && m.subFormula.name) || m.reason)) || '').filter(Boolean);
|
|
356
|
+
if (hasPrice) {
|
|
357
|
+
const basis = pr.basisUnit || 'kg';
|
|
358
|
+
const perKg = basis === 'kg' ? target : (typeof convertPricePerBasis === 'function' ? convertPricePerBasis(target, basis, 'kg', sv.density || (typeof _rolledUpDensity === 'function' ? _rolledUpDensity(f) : null)) : null);
|
|
359
|
+
if (Number.isFinite(perKg) && perKg > 0) {
|
|
360
|
+
const ps = perKg * sv.g / 1000, cs = out.perServingFull; // with packaging, labor and overhead
|
|
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 }; }
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return out;
|
|
367
|
+
}
|
|
368
|
+
// Small amounts keep their cents: a serving often costs under a dollar ("$0.2351" reads better than "$0.24" when
|
|
369
|
+
// the next line multiplies it by twelve).
|
|
370
|
+
function _nlMoney(v, ccy) {
|
|
371
|
+
if (!Number.isFinite(v)) return '—';
|
|
372
|
+
if (v < 0) return '−' + _nlMoney(-v, ccy); // the sign before the symbol: −$0.17, not $-0.17
|
|
373
|
+
if (typeof formatMoney !== 'function') return (Math.abs(v) < 1 ? v.toFixed(4) : v.toFixed(2)) + ' ' + (ccy || '');
|
|
374
|
+
if (Math.abs(v) >= 1 || v === 0) return formatMoney(v, ccy);
|
|
375
|
+
const whole = formatMoney(1, ccy), digits = +v.toPrecision(3);
|
|
376
|
+
return whole.replace(/1([.,]0+)?/, String(digits));
|
|
377
|
+
}
|
|
378
|
+
const _nlList = (a) => a.length < 2 ? a.join('') : a.slice(0, -1).join(', ') + ' and ' + a[a.length - 1];
|
|
379
|
+
// The cost as lines of text, for the print and for the MCP tool's reader: [[label, value], …]; [] with no cost.
|
|
380
|
+
function flNlCostLines(f) {
|
|
381
|
+
const k = flNlCost(f);
|
|
382
|
+
if (!k.ok) return [];
|
|
383
|
+
const sv = flNlServing(f), st = _nlSettings(f), m = v => _nlMoney(v, k.currency);
|
|
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)]);
|
|
391
|
+
out.push([`Cost per kg${st.yield ? ` as sold (${_nlNum(st.yield)}% yield)` : ''}`, m(k.perKgSold)]);
|
|
392
|
+
if (k.price) {
|
|
393
|
+
out.push(['Sell price per serving', m(k.price.perServing)]);
|
|
394
|
+
if (k.price.perContainer != null) out.push(['Sell price per container', m(k.price.perContainer)]);
|
|
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`]);
|
|
397
|
+
}
|
|
398
|
+
if (k.unpriced.length) out.push(['Rows with no price (counted as 0)', k.unpriced.slice(0, 12).join(', ')]);
|
|
399
|
+
return out;
|
|
400
|
+
}
|
|
401
|
+
function _nlCostCardHtml(f) {
|
|
402
|
+
const k = flNlCost(f);
|
|
403
|
+
if (!k.ok) return `<div class="card">
|
|
404
|
+
<div class="card-header"><h2>Cost</h2></div>
|
|
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>
|
|
406
|
+
</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 & 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>` : '');
|
|
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>` : '';
|
|
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">
|
|
442
|
+
<div class="card-header"><h2>Cost</h2><span id="nl-cost-saved" class="fl-saved-tick" role="status"></span></div>
|
|
443
|
+
<div class="card-body">
|
|
444
|
+
${warn}${idle}
|
|
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>
|
|
448
|
+
</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>` : ''}`;
|
|
454
|
+
}
|
|
455
|
+
|
|
269
456
|
// ── Ingredient statement and Contains ───────────────────────
|
|
270
457
|
// Leaves in descending order by weight; those at 2 % or less may follow "Contains 2% or less of".
|
|
271
458
|
// The formula's leaves, heaviest first: [{ name (label_name when set), w, allergens }]
|
|
@@ -395,7 +582,11 @@ function flNlPanelHtml(f, calc, tease) {
|
|
|
395
582
|
const name = l.italicFirst ? l.label.replace(/^(\S+)/, '<i>$1</i>') : l.label;
|
|
396
583
|
return `<div class="nl-d-row${l.indent ? ' nl-in' + l.indent : ''}"><span class="nl-d-n">${l.includes ? 'Includes ' + name : l.bold ? `<b>${name}</b>` : name}</span>${cell(l)}${cell(C[l.key])}</div>`;
|
|
397
584
|
};
|
|
398
|
-
|
|
585
|
+
// The amount columns are as wide as their longest text: "less than 5mg" ran under the % beside it at the fixed
|
|
586
|
+
// 46px (Jun, 17 Nov). The panel grows by what the columns gain, so the names keep their room.
|
|
587
|
+
const colW = (ls, min) => Math.max(min, Math.ceil(Math.max(0, ...ls.filter(l => l.key !== 'energy').map(l => amt(l).length)) * 6.4) + 8);
|
|
588
|
+
const da = colW(lines, 46), dc = colW(Object.values(C), 52);
|
|
589
|
+
return `<div class="nl-panel nl-dual" id="nl-panel" translate="no" style="--da:${da}px;--dc:${dc}px;width:${380 + (da - 46) + (dc - 52)}px">
|
|
399
590
|
<div class="nl-title">Nutrition Facts</div>
|
|
400
591
|
<div class="nl-servings">${esc(st.servings)} servings per container</div>
|
|
401
592
|
<div class="nl-serving${_nlServingText(st).length > 38 ? ' nl-flow' : ''}"><span>Serving size</span> <span>${esc(_nlServingText(st))}</span></div>
|
|
@@ -434,7 +625,7 @@ function flNlPanelHtml(f, calc, tease) {
|
|
|
434
625
|
function flNlTabButtonHtml(f) {
|
|
435
626
|
if (!f || !flNlHasFoodData(f)) return '';
|
|
436
627
|
const pro = typeof hasFeature !== 'function' || hasFeature('formulations.nutritionLabel');
|
|
437
|
-
return `<div class="tab" data-tab="label" onclick="switchFormTab('label')"
|
|
628
|
+
return `<div class="tab" data-tab="label" onclick="switchFormTab('label')">Label${pro ? '' : ' <span class="asm-designer-pro-badge usda-pro">Pro</span>'}</div>`;
|
|
438
629
|
}
|
|
439
630
|
function _nlFmt(v) {
|
|
440
631
|
if (v == null || !Number.isFinite(v)) return '—';
|
|
@@ -471,6 +662,9 @@ function flNlTabHtml(f) {
|
|
|
471
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>`
|
|
472
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>`;
|
|
473
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();
|
|
474
668
|
// Insignificant only because no ingredient has the field: say so before anyone prints a simplified label on it.
|
|
475
669
|
const blank = lines.filter(l => sim.insignificant.includes(l.key) && (c.missing[l.key] || []).length >= c.withData).map(l => l.label);
|
|
476
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>`;
|
|
@@ -479,7 +673,7 @@ function flNlTabHtml(f) {
|
|
|
479
673
|
const eu = st.region === 'eu';
|
|
480
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>`;
|
|
481
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>`;
|
|
482
|
-
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>` : ''}`;
|
|
483
677
|
const by = c.yield ? null : flNlBatchYield(f);
|
|
484
678
|
const yld = c.yield
|
|
485
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>`
|
|
@@ -510,7 +704,8 @@ function flNlTabHtml(f) {
|
|
|
510
704
|
${dens}${yld}
|
|
511
705
|
</div>
|
|
512
706
|
</div>
|
|
513
|
-
<div class="
|
|
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">
|
|
514
709
|
<div class="card-header"><h2>Ingredient statement</h2>
|
|
515
710
|
<button class="btn btn-secondary btn-sm" onclick="flNlCopyStatement('${id}')">Copy</button></div>
|
|
516
711
|
<div class="card-body nl-stmt">
|
|
@@ -525,10 +720,10 @@ function flNlTabHtml(f) {
|
|
|
525
720
|
<div class="card-header"><h2>Numbers</h2></div>
|
|
526
721
|
<div class="card-body">
|
|
527
722
|
${cover}
|
|
528
|
-
${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>
|
|
529
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>`}
|
|
530
725
|
</div>
|
|
531
|
-
</div
|
|
726
|
+
</div>`}
|
|
532
727
|
</div>
|
|
533
728
|
<div class="nl-main">
|
|
534
729
|
<div class="card">
|
|
@@ -547,14 +742,29 @@ function flNlTabHtml(f) {
|
|
|
547
742
|
</div>`;
|
|
548
743
|
}
|
|
549
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
|
+
}
|
|
550
751
|
// Save one serving field on the formula, then redraw the tab.
|
|
551
752
|
function flNlSet(fid, key, value) {
|
|
552
753
|
const f = (db.formulations || []).find(x => x.id === fid);
|
|
553
|
-
if (!f || !['serving', 'unit', 'format', 'region', 'yield', 'household', 'servings'].includes(key)) return;
|
|
754
|
+
if (!f || !['serving', 'unit', 'format', 'region', 'yield', 'pack', 'goal', 'labor', 'batch', 'overhead', 'ri', 'household', 'servings'].includes(key)) return;
|
|
554
755
|
const l = { ...(f.label || {}) };
|
|
555
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 + '.'); } }
|
|
556
757
|
else if (key === 'format') { if (['simplified', 'tabular', 'linear', 'dual'].includes(value)) l.format = value; else delete l.format; }
|
|
557
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] + ' %.'); } }
|
|
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') {
|
|
764
|
+
const n = parseFloat(String(value).replace(',', '.'));
|
|
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() + '.'); }
|
|
767
|
+
}
|
|
558
768
|
else if (key === 'region') { if (value === 'eu') l.region = 'eu'; else delete l.region; }
|
|
559
769
|
else if (key === 'unit') { if (value === 'mL') l.unit = 'mL'; else delete l.unit; }
|
|
560
770
|
else { const t = String(value || '').trim().slice(0, key === 'household' ? 80 : 40); if (t) l[key] = t; else delete l[key]; }
|
|
@@ -562,10 +772,7 @@ function flNlSet(fid, key, value) {
|
|
|
562
772
|
const saved = typeof _fmlSyncSave === 'function' && _fmlSyncSave(f, ['label']);
|
|
563
773
|
const el = document.getElementById('tab-label');
|
|
564
774
|
if (el) el.innerHTML = flNlTabHtml(f);
|
|
565
|
-
|
|
566
|
-
// member exports off flashed enabled on every serving change; Jun, 17 Nov).
|
|
567
|
-
try { if (window.__flViewerGate && typeof window.__flViewerGate.refresh === 'function') window.__flViewerGate.refresh(); } catch (_) {}
|
|
568
|
-
if (saved && typeof flSavedTick === 'function') flSavedTick(key === 'format' || key === 'region' ? 'nl-fmt-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');
|
|
569
776
|
}
|
|
570
777
|
|
|
571
778
|
function _nlFile(f) { return 'nutrition-facts-' + String(f.uid || f.name || 'formula').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase(); }
|
|
@@ -634,12 +841,12 @@ const FL_NL_PANEL_CSS = `.nl-panel{box-sizing:border-box;width:280px;padding:4px
|
|
|
634
841
|
.nl-panel.nl-lin{width:430px;padding:5px 8px 6px;font-size:11px;line-height:1.3}
|
|
635
842
|
.nl-l-t{font-weight:900;font-size:19px;line-height:1;letter-spacing:-.3px;margin-right:2px}.nl-l-c{font-weight:900;font-size:13px}
|
|
636
843
|
.nl-panel.nl-dual{width:380px}
|
|
637
|
-
.nl-d-row{display:grid;grid-template-columns:minmax(0,1fr) 46px 40px 52px 40px;align-items:end;padding:2px 0;border-bottom:1px solid #000}
|
|
844
|
+
.nl-d-row{display:grid;grid-template-columns:minmax(0,1fr) var(--da,46px) 40px var(--dc,52px) 40px;align-items:end;padding:2px 0;border-bottom:1px solid #000}
|
|
638
845
|
.nl-d-row.nl-in1 .nl-d-n{padding-left:12px}.nl-d-row.nl-in2 .nl-d-n{padding-left:24px}
|
|
639
846
|
.nl-d-a,.nl-d-p{text-align:right;white-space:nowrap}.nl-d-a{border-left:1px solid #000;margin:-2px 0;padding:2px 0}.nl-d-p{padding-right:3px}
|
|
640
847
|
.nl-d-row .nl-d-p:last-child{padding-right:0}
|
|
641
848
|
.nl-d-h{font-weight:800;font-size:10px}
|
|
642
|
-
.nl-d-cal{grid-template-columns:minmax(0,1fr)
|
|
849
|
+
.nl-d-cal{grid-template-columns:minmax(0,1fr) calc(var(--da,46px) + 40px) calc(var(--dc,52px) + 40px);border-bottom:0;padding-bottom:1px}
|
|
643
850
|
.nl-d-cal .nl-d-n b{font-weight:900;font-size:24px;line-height:1}
|
|
644
851
|
.nl-d-k{display:flex;flex-direction:column;align-items:flex-end;border-left:1px solid #000;padding-right:3px}.nl-d-k:last-child{padding-right:0}
|
|
645
852
|
.nl-d-k small{font-weight:800;font-size:9.5px}.nl-d-k b{font-weight:900;font-size:30px;line-height:1}
|
|
@@ -650,7 +857,7 @@ const FL_NL_PANEL_CSS = `.nl-panel{box-sizing:border-box;width:280px;padding:4px
|
|
|
650
857
|
.nl-panel.nl-eu th,.nl-panel.nl-eu td{background:rgb(255,255,255)!important;color:#000!important}
|
|
651
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}
|
|
652
859
|
.nl-eu th + th,.nl-eu td + td{border-left:1px solid #000}
|
|
653
|
-
.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}`;
|
|
654
861
|
function flNlPrint(fid) {
|
|
655
862
|
if (!_nlGate()) return;
|
|
656
863
|
if (typeof flExportAllowed === 'function' && !flExportAllowed('single', 'a nutrition label print')) return; // what members can take out (0114)
|
|
@@ -661,12 +868,14 @@ function flNlPrint(fid) {
|
|
|
661
868
|
if (!win) { if (typeof toast === 'function') toast('Couldn’t open the print view. Try again.'); return; }
|
|
662
869
|
const css = `body{font:12px Helvetica,Arial,sans-serif;color:#000;margin:28px}h1{font-size:15px;margin:0 0 2px}.meta{font-size:11px;opacity:.65;margin-bottom:16px}
|
|
663
870
|
.stmt{max-width:420px;margin-top:16px;font-size:11.5px;line-height:1.4}.stmt div{margin-bottom:4px}
|
|
871
|
+
.cost{margin-top:14px;border-collapse:collapse;font-size:11.5px}.cost td{padding:2px 14px 2px 0}.cost td + td{text-align:right;font-weight:700}.cost caption{text-align:left;font-weight:700;padding-bottom:3px}
|
|
664
872
|
${FL_NL_PANEL_CSS}
|
|
665
873
|
${typeof flPrintPageCss === 'function' ? flPrintPageCss() : ''}`;
|
|
666
874
|
win.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${esc(f.name || 'Nutrition Facts')}</title><style>${css}</style></head><body>
|
|
667
875
|
<h1>${esc(f.name || '')}</h1><div class="meta">${esc([f.uid, 'calculated from ingredient data', 'printed ' + new Date().toLocaleDateString()].filter(Boolean).join(' · '))}</div>
|
|
668
876
|
${flNlPanelHtml(f)}
|
|
669
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>
|
|
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>` : ''; })()}
|
|
670
879
|
<script>window.onload=()=>setTimeout(()=>window.print(),250)<\/script></body></html>`);
|
|
671
880
|
win.document.close();
|
|
672
881
|
if (typeof flPreparePrintWindow === 'function') flPreparePrintWindow(win);
|