formlab-mcp 0.7.9 → 0.7.12

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/data.js CHANGED
@@ -8,6 +8,7 @@
8
8
 
9
9
  import { readFileSync, watch } from 'node:fs';
10
10
  import { resolve } from 'node:path';
11
+ import { appFlatten } from './theoretical.js';
11
12
 
12
13
  // Module-level mutable store — re-assigned on hot-reload when the
13
14
  // watched file changes. Tools read from getStore() to always see
@@ -144,6 +145,12 @@ export function resolveById(collection, idOrUid) {
144
145
  // Walks sub-formula rows recursively (cap depth to break cycles).
145
146
  // Mirrors the algorithm in FormLab's js/nesting.js _flattenComposition.
146
147
  export function flattenComposition(formulation, depth = 0) {
148
+ // 27q: the app's own engine first, so pieces and "Not mixed in" parts read as the app shows them (a candle's
149
+ // 1 wick beside 92 % wax and 8 % fragrance is not 1 g of 101). The code below is the fallback.
150
+ if (depth === 0 && formulation && Array.isArray(formulation.composition)) {
151
+ const app = appFlatten(getStore().db, formulation);
152
+ if (app && Array.isArray(app.rows)) return app;
153
+ }
147
154
  const MAX_DEPTH = 5;
148
155
  if (!formulation || !Array.isArray(formulation.composition) || depth > MAX_DEPTH) {
149
156
  return { rows: [] };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.7.9",
3
+ "version": "0.7.12",
4
4
  "mcpName": "io.github.juliu1980/formlab-mcp",
5
5
  "description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
6
6
  "homepage": "https://formvix.com/mcp",
package/server.json CHANGED
@@ -2,13 +2,13 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.juliu1980/formlab-mcp",
4
4
  "description": "Read-only MCP server for FormLab formulation data: a local export file or your live cloud workspace.",
5
- "version": "0.7.9",
5
+ "version": "0.7.12",
6
6
  "websiteUrl": "https://formvix.com/mcp",
7
7
  "packages": [
8
8
  {
9
9
  "registryType": "npm",
10
10
  "identifier": "formlab-mcp",
11
- "version": "0.7.9",
11
+ "version": "0.7.12",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
package/theoretical.js CHANGED
@@ -50,6 +50,23 @@ const EPILOGUE = `
50
50
  // vendored; this is the same walk over the flattened leaves.
51
51
  // The viewer's display-currency preference lives in the browser; here there is none, so costs read in USD unless the
52
52
  // formula's target price names a currency (0.6.86). Labor, overhead and EU reference intakes: 0.6.87.
53
+ function __flat(fj) {
54
+ var f = JSON.parse(fj);
55
+ var name = function (id) { var i = (db.ingredients || []).find(function (x) { return x && x.id === id; }); return (i && i.name) || id; };
56
+ var r = _flattenComposition(f);
57
+ var merged = {}, order = [];
58
+ (r.rows || []).forEach(function (x) {
59
+ if (!x || !x.ingredientId || !(x._weight > 0)) return;
60
+ if (merged[x.ingredientId]) { merged[x.ingredientId].weightFraction += x._weight; return; }
61
+ merged[x.ingredientId] = { ingredientId: x.ingredientId, ingredientName: name(x.ingredientId), weightFraction: x._weight, role: x.role || '' };
62
+ order.push(x.ingredientId);
63
+ });
64
+ var comp = (f.composition || []).filter(function (c) { return c && (c.ingredientId || c.formulationId); });
65
+ var aside = typeof flCountedAside === 'function' ? flCountedAside(comp) : new Set();
66
+ var counted = comp.filter(function (c) { return aside.has(c); }).map(function (c) { return { ingredientId: c.ingredientId, ingredientName: name(c.ingredientId), amount: c.amount, unit: c.unit || '' }; });
67
+ var unresolved = (r.unresolved || []).filter(function (u) { return u && u.ingredientId; }).map(function (u) { return { ingredientId: u.ingredientId, ingredientName: name(u.ingredientId), reason: u.reason, unit: u.unit || '' }; });
68
+ return JSON.stringify({ rows: order.map(function (k) { return merged[k]; }), countedAside: counted, unresolved: unresolved });
69
+ }
53
70
  var localStorage = { getItem: function () { return null; }, setItem: function () {} };
54
71
  // The app's HTML escaper (js/utils.js, not vendored): the EU list builds its bold version with it.
55
72
  function esc(v) { return String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
@@ -168,6 +185,17 @@ function contextFor(db) {
168
185
  return ctx;
169
186
  }
170
187
 
188
+ // A formula's leaf wt-fractions by the app's own engine (js/nesting.js _flattenComposition, 27q): rows counted in
189
+ // pieces convert through the ingredient's weight per piece, and a part marked "Not mixed in" beside % rows (1 wick)
190
+ // sits outside the 100% (countedAside) instead of reading as 1 g or 1 %. null when the engine can't run.
191
+ export function appFlatten(db, formulation) {
192
+ try {
193
+ const ctx = contextFor(db);
194
+ vm.runInContext('var __fj = ' + JSON.stringify(JSON.stringify(formulation)) + ';', ctx);
195
+ return JSON.parse(vm.runInContext('__flat(__fj)', ctx, { timeout: 2000 }));
196
+ } catch (_) { return null; }
197
+ }
198
+
171
199
  // An ingredient's reactive groups as the app reads them (js/reactive.js): [{ group, label, datasheet ("AHEW 42.6
172
200
  // g/eq"), meqPerG, entered: { basis, value } }], plus the rows it ignores and why (ignored: true, why).
173
201
  export function reactiveGroups(db, id) {
@@ -1500,6 +1500,12 @@ function _tpBucket(days, weekDays = 21) {
1500
1500
  // A pull on a schedule: a number of months, or "<n>w" for weeks (Jun, 1 Nov: short accelerated and freeze-thaw
1501
1501
  // studies pull at 1, 2, 4 weeks).
1502
1502
  function _pullWeeks(e) { const w = typeof e === 'string' && /^(\d*\.?\d+)w$/.exec(e); return w ? +w[1] : null; }
1503
+ // Whole calendar days from today (the lab's local day) to a pull's due day: the app's _stabDaysUntil.
1504
+ function _tpDaysUntil(due, now) {
1505
+ const n = new Date(now);
1506
+ const today = Date.UTC(n.getFullYear(), n.getMonth(), n.getDate()) / _MS_PER_DAY;
1507
+ return Math.floor(due / _MS_PER_DAY) - today;
1508
+ }
1503
1509
  function _pullDays(e) { const w = _pullWeeks(e); return w != null ? w * 7 : +e * 30.4375; }
1504
1510
  function _pullLabel(e) { const w = _pullWeeks(e); return w != null ? `${w} wk` : `${+e} mo`; }
1505
1511
  // Valid pulls, one per day count, in time order.
@@ -1566,7 +1572,7 @@ function _tpCond(ps, t0, tC, targetMonths, plan, now) {
1566
1572
  const nextE = ladder.find(e => keyOf(e) > lastKey);
1567
1573
  const next = nextE == null ? null : (() => {
1568
1574
  const due = t0 + _pullDays(nextE) * _MS_PER_DAY;
1569
- return { label: _pullLabel(nextE), due: new Date(due), days: Math.floor((due - now) / _MS_PER_DAY) };
1575
+ return { label: _pullLabel(nextE), due: new Date(due), days: _tpDaysUntil(due, now) };
1570
1576
  })();
1571
1577
  return { cells, lastKey, weekDays, ladderKeys: ladder.map(keyOf), own: !!_tpOwnPulls(plan, tC), next };
1572
1578
  }
@@ -1692,7 +1698,7 @@ function _mcpPullsDue(db, now, perSample) {
1692
1698
  const last = r.cells.get(r.lastKey);
1693
1699
  // Every pull still ahead on this schedule, the next and each one after it: the app's pull calendar (47k).
1694
1700
  const ahead = _tpLadder(tC, target, plan).filter(e => _tpBucket(_pullDays(e), r.weekDays).key > r.lastKey)
1695
- .map(e => { const due = t0 + _pullDays(e) * _MS_PER_DAY; return _nextOut({ label: _pullLabel(e), due: new Date(due), days: Math.floor((due - now) / _MS_PER_DAY) }); });
1701
+ .map(e => { const due = t0 + _pullDays(e) * _MS_PER_DAY; return _nextOut({ label: _pullLabel(e), due: new Date(due), days: _tpDaysUntil(due, now) }); });
1696
1702
  const row = { formula: { id: f.id, uid: f.uid || null, name: f.name || f.uid || 'Formula' }, condition: cond, temperatureC: _round(tC, 1),
1697
1703
  schedule: r.own ? 'formula' : 'standard', t0: _dayOf(t0), lastTimePoint: last ? last.label : null, ..._nextOut(r.next), parameter: param, ahead,
1698
1704
  samples: sampleIds.map(id => { const x = (db.samples || []).find(y => y && y.id === id); return x ? (x.uid || x.id) : id; }) };
@@ -154,6 +154,10 @@ const get_formulation = {
154
154
  role: c.role || '',
155
155
  })),
156
156
  compositionFlattenedWtPct: flatRows,
157
+ // Counted beside a % recipe, outside its 100 % (a wick marked "Not mixed in"): per piece of product (27q).
158
+ ...(flat.countedAside && flat.countedAside.length ? { countedAside: flat.countedAside.map(c => ({ ingredientId: c.ingredientId, ingredient: c.ingredientName, amount: c.amount, unit: c.unit })) } : {}),
159
+ // Rows the wt-% can't place: a piece with no weight per piece, a volume with no density.
160
+ ...(flat.unresolved && flat.unresolved.length ? { compositionUnresolved: flat.unresolved.map(u => ({ ingredient: u.ingredientName, unit: u.unit, reason: u.reason === 'no-weight' ? 'counted in pieces with no weight per piece' : u.reason })) } : {}),
157
161
  stepCount: (f.steps || []).length,
158
162
  // The actual procedure — the tool description promises "step procedure",
159
163
  // so return the ordered steps, not just the count. Keep only the
@@ -69,6 +69,8 @@ function _trimIngredient(i) {
69
69
  densityUnit: i.densityUnit || (i.density != null ? 'kg/L' : null),
70
70
  // What one piece weighs (a wick): a recipe row counted in pieces converts through it (0.7.8).
71
71
  ...(_pieceKg(i) ? { weightPerPiece: { value: Number(i.unitMass.value), unit: i.unitMass.unit } } : {}),
72
+ // A part per unit (a wick, a jar) left out of a recipe's 100 % and counted per piece (27q).
73
+ ...(i.notMixedIn ? { notMixedIn: true } : {}),
72
74
  cost: (cost && cost.value != null && cost.value !== '')
73
75
  ? { value: cost.value, currency: cost.currency || 'USD', unit: cost.unit || 'kg' } : null,
74
76
  costPerKg: _costPerKg(i),
package/tools/lab.js CHANGED
@@ -394,7 +394,7 @@ const list_batches = {
394
394
  const get_batch = {
395
395
  definition: {
396
396
  name: 'get_batch',
397
- description: 'Get full details for a single batch including the raw lots it drew (lotsUsed: lot number, quantity, and the status of each lot now, with holdReason for a lot on hold), hold (now) and holdHistory (every hold with its release: when, by whom, and the note, e.g. "Released with lot ETH-1"), its actual composition (as-prepared, when logged), child samples, lineage (parent / sub-blend parents), and — treating the batch as a finished-goods lot — its storage `location` and finished-goods `stockLedger` (shipments out + adjustments; on-hand = produced − sample pulls − sub-batch draws + Σ ledger). Plus finished-product density + actual volume (measured directly or derived as actual mass ÷ measured density — never summed from per-ingredient volumes). Accepts internal id or UID. Also returns `theoreticalParameters` computed on the batch as made (its actual composition when logged — `basis: "actual"` — else the recipe of its formula), with the batch parameter list when it overrides the one on the formula; same fields as get_formulation. `reactiveBalance` is the same as get_formulation\'s, on what was weighed (basis "as weighed"), e.g. a soap batch\'s superfat and lye excess.',
397
+ description: 'Get full details for a single batch including the raw lots it drew (lotsUsed: lot number, quantity, and the status of each lot now, with holdReason for a lot on hold), hold (now) and holdHistory (every hold with its release: when, by whom, and the note, e.g. "Released with lot ETH-1"), certificates (each Certificate of Analysis as issued and saved: number, when, by whom, customer, PO, verdict, override reason, the results it printed; a shipment\'s coaNumber names the one it went with), its actual composition (as-prepared, when logged), child samples, lineage (parent / sub-blend parents), and — treating the batch as a finished-goods lot — its storage `location` and finished-goods `stockLedger` (shipments out + adjustments; on-hand = produced − sample pulls − sub-batch draws + Σ ledger). Plus finished-product density + actual volume (measured directly or derived as actual mass ÷ measured density — never summed from per-ingredient volumes). Accepts internal id or UID. Also returns `theoreticalParameters` computed on the batch as made (its actual composition when logged — `basis: "actual"` — else the recipe of its formula), with the batch parameter list when it overrides the one on the formula; same fields as get_formulation. `reactiveBalance` is the same as get_formulation\'s, on what was weighed (basis "as weighed"), e.g. a soap batch\'s superfat and lye excess.',
398
398
  inputSchema: {
399
399
  type: 'object',
400
400
  properties: {
@@ -443,6 +443,8 @@ const get_batch = {
443
443
  ...(e.customer ? { customer: e.customer } : {}),
444
444
  ...(Array.isArray(e.qcOpen) && e.qcOpen.length ? { shippedWithQcOpen: e.qcOpen, qcReason: e.qcReason || null } : {}),
445
445
  // 2 Dec: the CoA it went with (null = none issued), and no ingredient lots recorded. Older shipments carry neither.
446
+ // 0.7.12: the saved certificate it went with (its number in certificates).
447
+ ...(e.kind === 'shipment' && e.coaId ? { coaNumber: ((Array.isArray(b.coas) ? b.coas : []).find(c => c && c.id === e.coaId) || {}).n ?? null } : {}),
446
448
  ...(e.kind === 'shipment' && 'coaAt' in e ? { coaIssuedAt: e.coaAt || null, ...(e.coaCustomer ? { coaCustomer: e.coaCustomer } : {}), ...(e.coaPo ? { coaPo: e.coaPo } : {}), noLotsRecorded: !!e.noLots } : {}),
447
449
  })),
448
450
  shippedQty: (Array.isArray(b.stockLedger) ? b.stockLedger : []).reduce((s, e) => e.kind === 'shipment' ? s + Math.abs(parseFloat(e.delta) || 0) : s, 0),
@@ -450,6 +452,14 @@ const get_batch = {
450
452
  hold: (b.fgHold && b.fgHold.at && !b.fgHold.releasedAt) ? { since: b.fgHold.at, by: b.fgHold.by || '', reason: b.fgHold.reason || '' } : null,
451
453
  // 0.6.94: every hold this batch had, oldest first, with its release (when, by whom, the note: "Released with lot X").
452
454
  holdHistory: _batchHoldHistory(getStore().db, b),
455
+ // 0.7.12: each Certificate of Analysis as issued (saved on the batch; a reprint shows the same document), oldest first.
456
+ certificates: (Array.isArray(b.coas) ? b.coas : []).filter(c => c && c.id).map(c => ({
457
+ number: c.n ?? null, issuedAt: c.issuedAt || null, issuedBy: c.issuedBy || '', product: c.product || '', customer: c.customer || '', po: c.po || '',
458
+ resultsUpTo: c.upTo || null, verdict: c.conforms === false ? 'does not conform' : c.untested ? 'not tested (override)' : c.conforms === true ? 'conforms' : 'reported',
459
+ ...(c.override ? { overrideReason: c.override } : {}), ...(Array.isArray(c.notTested) && c.notTested.length ? { notTested: c.notTested } : {}),
460
+ results: (c.rows || []).map(r => ({ parameter: r.name, ...(r.cond ? { conditions: r.cond } : {}), value: r.value, unit: r.unit || '', spec: r.spec || null, status: r.status || 'reported', testReport: r.testUid || null, testDate: r.testDate || null, ...(r.doubt ? { inDoubt: r.doubt } : {}) })),
461
+ sourceReports: c.sources || [],
462
+ })),
453
463
  // 0.6.92: the raw lots this batch drew (net of returns), each with its status now. A lot on hold
454
464
  // here ("status: hold" + holdReason) is why a recall reaches this batch, held or not.
455
465
  lotsUsed: _batchLotsUsed(getStore().db, b.id),
package/vendor/cost.js CHANGED
@@ -565,7 +565,7 @@ const COST_ESTIMATES = {
565
565
  // Currency is always USD for now. Match is case-insensitive and tries
566
566
  // the full name first, then any whole-word substring match.
567
567
  function lookupIngredientCost(name) {
568
- if (!name) return null;
568
+ if (!name || (typeof flCostHidden === 'function' && flCostHidden())) return null; // 0267: no price, not even an estimate, for a Viewer with cost hidden
569
569
  const key = String(name).toLowerCase().trim();
570
570
  if (key in COST_ESTIMATES) {
571
571
  return { ...COST_ESTIMATES[key], currency: 'USD', source: 'estimate', matchedKey: key };
@@ -842,6 +842,60 @@ function flIsPieceUnit(u) {
842
842
  const hit = t => Object.keys(t).some(k => k === raw || k.toLowerCase() === lower);
843
843
  return !hit(MASS_TO_KG) && !hit(VOL_TO_L) && !(typeof LENGTH_TO_M !== 'undefined' && hit(LENGTH_TO_M));
844
844
  }
845
+ // A row counted in pieces whose ingredient is marked "Not mixed in" (a wick, a jar: a part per unit, not a share of the
846
+ // mix) sits outside the mix (Jun, 3 Dec): not a share of the whole, not part of the total, the mixed-basis check or the
847
+ // per-kg cost; it goes into the batch as counted, and its price per piece of product. In a wt% or vol% recipe and, since
848
+ // 27c ("Yes, everywhere"), in a recipe by weight too. Half an apple is mixed in: it stays in. Returns the set of such
849
+ // rows; empty when nothing else is mixed (a kit of a jar, a lid and a label stays as written).
850
+ function flCountedAside(comp) {
851
+ comp = (comp || []).filter(c => c && (c.ingredientId || c.formulationId));
852
+ const frac = c => { const u = String(c.unit || 'wt%').trim().toLowerCase(); return u === '%' || u.startsWith('wt') || u.startsWith('vol'); };
853
+ const notMixed = c => { const ing = (typeof db !== 'undefined' && db && db.ingredients || []).find(i => i.id === c.ingredientId); return !!(ing && ing.notMixedIn); };
854
+ const aside = comp.filter(c => !c.formulationId && c.ingredientId && !frac(c) && flIsPieceUnit(c.unit) && notMixed(c));
855
+ return aside.length && aside.length < comp.length ? new Set(aside) : new Set();
856
+ }
857
+ // How many pieces of product a batch makes, for parts counted per piece beside a % recipe (1 wick per candle): the
858
+ // batch's own count (12 candles), else its mass over the formula's fill (Pricing per piece: 226.8 g), else 1 (3 Dec).
859
+ function flProductUnits(f, batchKg, count) {
860
+ const n = parseFloat(count);
861
+ if (isFinite(n) && n > 0) return n;
862
+ const fl = f && f.pricing && f.pricing.fill, v = fl ? parseFloat(fl.value) : NaN;
863
+ if (batchKg > 0 && isFinite(v) && v > 0) {
864
+ let fillKg = null;
865
+ if (fl.unit in MASS_TO_KG) fillKg = v * MASS_TO_KG[fl.unit];
866
+ else if (fl.unit in VOL_TO_L) { const d = typeof _rolledUpDensity === 'function' ? _rolledUpDensity(f) : null; if (d) fillKg = v * VOL_TO_L[fl.unit] * d; }
867
+ if (fillKg > 0) return batchKg / fillKg;
868
+ }
869
+ // A recipe by weight is one piece of product (226.8 g of candle, 1 wick): 2,721.6 g makes 12 (27c).
870
+ if (batchKg > 0 && f && typeof computeCompositionFractions === 'function') {
871
+ const fr = computeCompositionFractions(f);
872
+ if (fr && !fr.allWt && !fr.allVol && !fr.mixedBasis && fr.totalMassKg > 0) return batchKg / fr.totalMassKg;
873
+ }
874
+ return 1;
875
+ }
876
+ // A recipe's rows without its Not mixed in parts, in any unit: an as-prepared "0.5 g" of wick is still not part of the
877
+ // mix (27f). All rows marked (a kit) keeps them all.
878
+ function flMixRows(comp) {
879
+ comp = Array.isArray(comp) ? comp : [];
880
+ const marked = c => { const ing = c && !c.formulationId && c.ingredientId ? (typeof db !== 'undefined' && db && db.ingredients || []).find(i => i.id === c.ingredientId) : null; return !!(ing && ing.notMixedIn); };
881
+ const keep = comp.filter(c => !marked(c));
882
+ return keep.length && keep.length < comp.length ? keep : comp;
883
+ }
884
+ // The mass of one piece of product, in g: the formula's fill by mass (or volume × density), else a recipe written by
885
+ // weight (226.8 g of candle, 1 wick). Null when neither says. A piece batch prefills its mass per unit with it (27e).
886
+ function flOnePieceGrams(f) {
887
+ if (!f) return null;
888
+ const fl = f.pricing && f.pricing.fill, v = fl ? parseFloat(fl.value) : NaN;
889
+ if (isFinite(v) && v > 0) {
890
+ if (fl.unit in MASS_TO_KG) return v * MASS_TO_KG[fl.unit] * 1000;
891
+ if (fl.unit in VOL_TO_L) { const d = typeof _rolledUpDensity === 'function' ? _rolledUpDensity(f) : null; if (d) return v * VOL_TO_L[fl.unit] * d * 1000; }
892
+ }
893
+ if (typeof computeCompositionFractions === 'function') {
894
+ const fr = computeCompositionFractions(f);
895
+ if (fr && !fr.allWt && !fr.allVol && !fr.mixedBasis && fr.totalMassKg > 0) return fr.totalMassKg * 1000;
896
+ }
897
+ return null;
898
+ }
845
899
  // A recipe row counted in pieces ("1 wick"), as kg through its ingredient's weight per piece. Null for any other row,
846
900
  // or a piece row whose ingredient has no weight per piece (it stays unpriced and unscaled, as before).
847
901
  function flPieceRowKg(c) {
@@ -853,7 +907,7 @@ function flPieceRowKg(c) {
853
907
  return per == null ? null : amt * per;
854
908
  }
855
909
  function costPerKgInOwnCurrency(cost, density, densityUnit, unitMass) {
856
- if (!cost || cost.value == null || cost.value === '') return null;
910
+ if (!cost || cost.value == null || cost.value === '' || (typeof flCostHidden === 'function' && flCostHidden())) return null;
857
911
  const v = parseFloat(cost.value);
858
912
  if (!isFinite(v)) return null;
859
913
  const u = cost.unit || 'kg';
@@ -1037,13 +1091,20 @@ function setDisplayCostUnit(u) {
1037
1091
  // Convert an ing.cost to price-per-`unit` in the cost's OWN currency.
1038
1092
  // mass↔mass and vol↔vol are exact; mass↔vol needs the ingredient's density.
1039
1093
  // Returns null when the conversion isn't possible (no density, unknown unit).
1040
- function costPerUnitInOwnCurrency(cost, unit, density, densityUnit) {
1041
- if (!cost || cost.value == null || cost.value === '' || !unit) return null;
1094
+ function costPerUnitInOwnCurrency(cost, unit, density, densityUnit, unitMass) {
1095
+ if (!cost || cost.value == null || cost.value === '' || !unit || (typeof flCostHidden === 'function' && flCostHidden())) return null;
1042
1096
  const v = parseFloat(cost.value);
1043
1097
  if (!isFinite(v)) return null;
1044
1098
  const from = cost.unit || 'kg';
1045
1099
  if (from === unit) return v;
1046
1100
  const kgPerL = _densityToKgPerL(density, densityUnit);
1101
+ // A counted ingredient (wicks): $5/kg ↔ $/piece through the weight per piece (2 Dec).
1102
+ if (typeof flIsPieceUnit === 'function' && (flIsPieceUnit(from) || flIsPieceUnit(unit))) {
1103
+ const perKg = costPerKgInOwnCurrency(cost, density, densityUnit, unitMass);
1104
+ if (perKg == null) return null;
1105
+ if (flIsPieceUnit(unit)) { const pk = flPieceMassKg(unitMass); return pk != null ? perKg * pk : null; }
1106
+ return convertPricePerBasis(perKg, 'kg', unit, kgPerL || null);
1107
+ }
1047
1108
  return convertPricePerBasis(v, from, unit, kgPerL || null);
1048
1109
  }
1049
1110
 
@@ -1092,7 +1153,7 @@ function formatMoney(amount, currency) {
1092
1153
  }
1093
1154
 
1094
1155
  function formatCostPerUnit(cost) {
1095
- if (!cost || cost.value == null || cost.value === '') return '—';
1156
+ if (!cost || cost.value == null || cost.value === '' || (typeof flCostHidden === 'function' && flCostHidden())) return '—';
1096
1157
  const v = parseFloat(cost.value);
1097
1158
  if (!isFinite(v)) return '—';
1098
1159
  return `${formatMoney(v, cost.currency || 'USD')} / ${cost.unit || 'kg'}`;
@@ -1115,6 +1176,8 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1115
1176
  // workspace each viewer should always see costs in their own preferred currency.
1116
1177
  displayCcy = displayCcy || getDisplayCurrency() || formulation.costCurrency || 'USD';
1117
1178
  basisUnit = basisUnit || formulation.costBasisUnit || 'kg';
1179
+ // 0267: cost hidden from this Viewer: an unpriced result (every caller already shows "—" for one), flagged hidden.
1180
+ if (typeof flCostHidden === 'function' && flCostHidden()) return { perKg: null, perBasis: null, basisUnit, basisOk: false, coveragePct: 0, currency: displayCcy, breakdown: [], missing: [], basis: 'wt', formulationKgPerL: null, hidden: true };
1118
1181
  const overrides = formulation.costOverrides || {};
1119
1182
  const breakdown = [];
1120
1183
  const missing = [];
@@ -1185,9 +1248,10 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1185
1248
  };
1186
1249
 
1187
1250
  // A piece row with a weight per piece counts as mass (2 Dec).
1188
- const kinds = comp.map(c => flPieceRowKg(c) != null ? 'mass-abs' : classifyUnit(c.unit));
1189
- const allWt = comp.length && kinds.every(k => k === 'wt-frac');
1190
- const allVol = comp.length && kinds.every(k => k === 'vol-frac');
1251
+ const _aside = flCountedAside(comp);
1252
+ const kinds = comp.map(c => _aside.has(c) ? 'counted' : (flPieceRowKg(c) != null ? 'mass-abs' : classifyUnit(c.unit)));
1253
+ const allWt = comp.length && kinds.every(k => k === 'wt-frac' || k === 'counted') && kinds.includes('wt-frac');
1254
+ const allVol = comp.length && kinds.every(k => k === 'vol-frac' || k === 'counted') && kinds.includes('vol-frac');
1191
1255
  // A counted row still missing its weight per piece is reported on its own; it must not knock the gram rows off the absolute basis.
1192
1256
  const allAbs = comp.length && kinds.every((k, i) => k === 'mass-abs' || k === 'vol-abs' || (k !== 'wt-frac' && k !== 'vol-frac' && flIsPieceUnit(comp[i].unit)))
1193
1257
  && kinds.some(k => k === 'mass-abs' || k === 'vol-abs');
@@ -1199,6 +1263,7 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1199
1263
  if (allVol) {
1200
1264
  let sumKg = 0, ok = true;
1201
1265
  for (const c of comp) {
1266
+ if (_aside.has(c)) continue;
1202
1267
  let d = null;
1203
1268
  if (c.formulationId) {
1204
1269
  d = subResolve.get(c)?.density || null;
@@ -1236,6 +1301,7 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1236
1301
  d = _densityToKgPerL(ing.density, ing.densityUnit);
1237
1302
  }
1238
1303
  if (!isFinite(amt) || flBadAmount(c.amount, c.unit)) continue;
1304
+ if (_aside.has(c)) continue; // not mixed in: outside the recipe's mass (27c)
1239
1305
  const _pk = flPieceRowKg(c);
1240
1306
  if (_pk != null || u in MASS_TO_KG) {
1241
1307
  const m = _pk != null ? _pk : amt * MASS_TO_KG[u];
@@ -1264,6 +1330,19 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1264
1330
  let totalPerKg = 0;
1265
1331
  let totalPct = 0;
1266
1332
 
1333
+ // A counted part's cost for one piece of product (1 wick at $0.12), in the display currency: a price per piece times
1334
+ // the count, or a price per kg (or L) through the weight per piece. Null when it can't be priced (3 Dec).
1335
+ let countedPerPiece = 0;
1336
+ const countedUnpriced = [];
1337
+ const _countedRowCost = (ing, c) => {
1338
+ if (!ing.cost || ing.cost.value == null || ing.cost.value === '') return null;
1339
+ const v = parseFloat(ing.cost.value), n = parseFloat(c.amount);
1340
+ if (!isFinite(v) || !isFinite(n)) return null;
1341
+ let own = null;
1342
+ if (flIsPieceUnit(ing.cost.unit || '')) own = v * n;
1343
+ else { const pk = costPerKgInOwnCurrency(ing.cost, ing.density, ing.densityUnit, ing.unitMass), kg = flPieceRowKg(c); if (pk != null && kg != null) own = pk * kg; }
1344
+ return own == null ? null : convertCurrencySync(own, ing.cost.currency || 'USD', displayCcy);
1345
+ };
1267
1346
  const tryAutoPrice = (ing, c, unit, amount, kind) => {
1268
1347
  if (!ing.cost || ing.cost.value == null || ing.cost.value === '') return { ok: false, reason: 'no cost on file' };
1269
1348
  const perKgOwn = costPerKgInOwnCurrency(ing.cost, ing.density, ing.densityUnit, ing.unitMass);
@@ -1365,6 +1444,11 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1365
1444
  if (flBadAmount(c.amount, c.unit)) { missing.push({ reason: `bad amount (${flBadAmount(c.amount, c.unit)})`, ingredient: ing }); continue; }
1366
1445
  if (!isFinite(amount)) { missing.push({ reason: 'no amount', ingredient: ing }); continue; }
1367
1446
 
1447
+ if (_aside.has(c)) { // counted beside a % recipe: outside the per-kg cost (flCountedAside); priced per piece of product
1448
+ const cc = _countedRowCost(ing, c);
1449
+ if (cc == null) countedUnpriced.push(ing); else countedPerPiece += cc;
1450
+ continue;
1451
+ }
1368
1452
  const kind = flPieceRowKg(c) != null ? 'mass-abs' : classifyUnit(unit);
1369
1453
  if (kind === 'unknown') {
1370
1454
  missing.push({ reason: flIsPieceUnit(c.unit) ? `set a weight per piece on ${ing.name || 'the ingredient'} to cost "${c.unit}"` : `unsupported composition unit "${c.unit}"`, ingredient: ing });
@@ -1435,6 +1519,7 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1435
1519
  // Sub-formula rows use their rolled-up density.
1436
1520
  let sumA = 0, sumW = 0;
1437
1521
  for (const c of comp) {
1522
+ if (_aside.has(c)) continue;
1438
1523
  let d = null;
1439
1524
  if (c.formulationId) {
1440
1525
  d = subResolve.get(c)?.density || null;
@@ -1496,6 +1581,10 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1496
1581
  missing,
1497
1582
  basis, // 'wt' or 'vol' (recipe basis, not display basis)
1498
1583
  formulationKgPerL, // only meaningful when basis === 'vol'
1584
+ // Parts counted per piece of product beside a % recipe (1 wick): their cost for one piece, outside perKg; null
1585
+ // when there are none, or one of them has no usable price (countedUnpriced names it).
1586
+ countedPerPiece: _aside.size && !countedUnpriced.length ? countedPerPiece : null,
1587
+ countedUnpriced,
1499
1588
  };
1500
1589
  }
1501
1590
 
@@ -1506,10 +1595,18 @@ const COST_BASIS_UNITS = ['kg', 'g', 'lb', 'oz', 'ton', 'L', 'mL', 'gal'];
1506
1595
  // volume↔volume are direct; mass↔volume needs formulationKgPerL (derived
1507
1596
  // by computeFormulationCost when possible). Returns null if a needed
1508
1597
  // density is missing.
1509
- function convertPricePerBasis(price, fromBasis, toBasis, formulationKgPerL) {
1598
+ // 'each' is a price per piece of product; fill {value, unit} is how much goes in one (250 g, 50 mL), on f.pricing.fill.
1599
+ function convertPricePerBasis(price, fromBasis, toBasis, formulationKgPerL, fill) {
1510
1600
  if (price == null || !isFinite(price)) return null;
1511
1601
  if (fromBasis === toBasis) return price;
1512
1602
  const scaleFromKg = u => {
1603
+ if (u === 'each') {
1604
+ const v = fill ? parseFloat(fill.value) : NaN;
1605
+ if (!(isFinite(v) && v > 0)) return null;
1606
+ if (fill.unit in MASS_TO_KG) return v * MASS_TO_KG[fill.unit];
1607
+ if (fill.unit in VOL_TO_L && formulationKgPerL) return v * VOL_TO_L[fill.unit] * formulationKgPerL;
1608
+ return null;
1609
+ }
1513
1610
  if (u === 'kg') return 1;
1514
1611
  if (u in MASS_TO_KG) return MASS_TO_KG[u];
1515
1612
  if (u in VOL_TO_L) {
@@ -1535,6 +1632,7 @@ function convertPricePerBasis(price, fromBasis, toBasis, formulationKgPerL) {
1535
1632
  // ============================================================
1536
1633
  function computeCompositionFractions(formulation) {
1537
1634
  const comp = formulation.composition || [];
1635
+ const _aside = flCountedAside(comp);
1538
1636
 
1539
1637
  const canonUnit = u => {
1540
1638
  const raw = String(u || '').trim();
@@ -1564,6 +1662,7 @@ function computeCompositionFractions(formulation) {
1564
1662
  const out = { composition: c, ingredient: ing, subFormula, amount, unit: rawU, density: d };
1565
1663
  const resolved = !!(ing || subFormula);
1566
1664
  if (!isFinite(amount) || !resolved || flBadAmount(c.amount, c.unit)) { out.kind = 'invalid'; return out; }
1665
+ if (_aside.has(c)) { out.kind = 'counted'; out.pieces = true; return out; } // outside the 100% (flCountedAside)
1567
1666
  if (u.startsWith('wt') || u === '%') { out.kind = 'wt-frac'; return out; }
1568
1667
  if (u.startsWith('vol')) { out.kind = 'vol-frac'; return out; }
1569
1668
  const cu = canonUnit(rawU);
@@ -1597,22 +1696,22 @@ function computeCompositionFractions(formulation) {
1597
1696
  if (r.volL != null) totalVolL += r.volL;
1598
1697
  if (r.lengthM != null) totalLengthM += r.lengthM;
1599
1698
  });
1600
- const allWt = rows.length && rows.every(r => r.kind === 'wt-frac');
1601
- const allVol = rows.length && rows.every(r => r.kind === 'vol-frac');
1699
+ const allWt = rows.length && rows.every(r => r.kind === 'wt-frac' || r.kind === 'counted') && rows.some(r => r.kind === 'wt-frac');
1700
+ const allVol = rows.length && rows.every(r => r.kind === 'vol-frac' || r.kind === 'counted') && rows.some(r => r.kind === 'vol-frac');
1602
1701
  const allLen = rows.length && rows.every(r => r.kind === 'length-abs');
1603
1702
 
1604
1703
  // For pure wt% / vol% recipes, derive formulation density from densities
1605
1704
  // so we can also compute the *other* fraction (vol for wt%, mass for vol%).
1606
1705
  let wtFormKgPerL = null;
1607
1706
  let volFormKgPerL = null;
1608
- if (allWt && rows.every(r => r.density)) {
1707
+ if (allWt && rows.every(r => r.density || r.kind === 'counted')) {
1609
1708
  let invSum = 0; // sum over rows of (wt_frac / density)
1610
- rows.forEach(r => { invSum += (r.amount / 100) / r.density; });
1709
+ rows.forEach(r => { if (r.kind === 'counted') return; invSum += (r.amount / 100) / r.density; });
1611
1710
  if (invSum > 0) wtFormKgPerL = 1 / invSum;
1612
1711
  }
1613
- if (allVol && rows.every(r => r.density)) {
1712
+ if (allVol && rows.every(r => r.density || r.kind === 'counted')) {
1614
1713
  let sum = 0;
1615
- rows.forEach(r => { sum += (r.amount / 100) * r.density; });
1714
+ rows.forEach(r => { if (r.kind === 'counted') return; sum += (r.amount / 100) * r.density; });
1616
1715
  if (sum > 0) volFormKgPerL = sum;
1617
1716
  }
1618
1717
 
@@ -1718,7 +1817,7 @@ function smartScaleAmount(value, unit) {
1718
1817
  // • no finished density → ideal-mix estimate, exactly as before: row volume
1719
1818
  // fractions × target (parts add up, which is the assumption).
1720
1819
  // Mass targets are unaffected either way.
1721
- function scaleCompositionToBatch(formulation, batchAmount, batchUnit) {
1820
+ function scaleCompositionToBatch(formulation, batchAmount, batchUnit, opts) {
1722
1821
  const amt = parseFloat(batchAmount);
1723
1822
  if (!isFinite(amt) || amt <= 0) return null;
1724
1823
  const dim = (batchUnit in MASS_TO_KG) ? 'mass'
@@ -1731,10 +1830,19 @@ function scaleCompositionToBatch(formulation, batchAmount, batchUnit) {
1731
1830
  let anyNull = false;
1732
1831
  const pd = (typeof formulaPlanningDensity === 'function') ? formulaPlanningDensity(formulation) : null;
1733
1832
  const useFinished = dim === 'volume' && pd && pd.source === 'finished';
1833
+ // A counted row beside the % rows (1 wick, flCountedAside) goes in as counted, not scaled: its count, and in a mass
1834
+ // batch its weight when the ingredient has a weight per piece.
1835
+ // Counted per piece of product: × the pieces the batch makes (opts.count: a count batch's own count; flProductUnits).
1836
+ const _bKg = dim === 'mass' ? amt * MASS_TO_KG[batchUnit] : (pd ? amt * VOL_TO_L[batchUnit] * pd.kgPerL : null);
1837
+ const units = fr.rows.some(r => r.kind === 'counted') ? flProductUnits(formulation, _bKg, opts && opts.count) : 1;
1838
+ const counted = new Set(comp.filter((c, i) => fr.rows[i] && fr.rows[i].kind === 'counted'));
1839
+ const _cntAmt = c => { if (dim !== 'mass') return null; const kg = flPieceRowKg(c); return kg != null ? kg * units / MASS_TO_KG[batchUnit] : null; };
1840
+ const _cntPieces = (out) => fr.rows.forEach((r, i) => { if (r.kind === 'counted') out.set(comp[i], flPieceCount(parseFloat(comp[i].amount) * units)); });
1734
1841
  if (useFinished) {
1735
1842
  const totalMassKg = amt * VOL_TO_L[batchUnit] * pd.kgPerL;
1736
1843
  let partsSum = 0;
1737
1844
  fr.rows.forEach((r, i) => {
1845
+ if (r.kind === 'counted') { byRow.set(comp[i], null); return; }
1738
1846
  const mf = r.massFraction;
1739
1847
  const rowD = (r.density != null && isFinite(r.density) && r.density > 0) ? r.density : null; // kg/L
1740
1848
  const ok = (mf != null && isFinite(mf) && rowD != null);
@@ -1748,15 +1856,17 @@ function scaleCompositionToBatch(formulation, batchAmount, batchUnit) {
1748
1856
  const c = comp[i], one = r.pieces ? flPieceRowKg(Object.assign({}, c, { amount: 1 })) : null;
1749
1857
  if (one && r.massFraction != null && isFinite(r.massFraction)) pieces.set(c, flPieceCount((r.massFraction * totalMassKg) / one));
1750
1858
  });
1751
- return { unit: batchUnit, dim, byRow, anyNull, density: pd, totalMassKg, partsSum, pieces };
1859
+ _cntPieces(pieces);
1860
+ return { unit: batchUnit, dim, byRow, anyNull, density: pd, totalMassKg, partsSum, pieces, units, counted };
1752
1861
  }
1753
1862
  fr.rows.forEach((r, i) => {
1863
+ if (r.kind === 'counted') { byRow.set(comp[i], _cntAmt(comp[i])); return; }
1754
1864
  const frac = dim === 'mass' ? r.massFraction : r.volFraction;
1755
1865
  const ok = (frac != null && isFinite(frac));
1756
1866
  if (!ok) anyNull = true;
1757
1867
  byRow.set(comp[i], ok ? frac * amt : null);
1758
1868
  });
1759
- const out = { unit: batchUnit, dim, byRow, anyNull };
1869
+ const out = { unit: batchUnit, dim, byRow, anyNull, units, counted };
1760
1870
  // Piece rows (wicks) also as a count: their scaled mass over the weight per piece (2 Dec).
1761
1871
  if (dim === 'mass') {
1762
1872
  out.pieces = new Map();
@@ -1764,6 +1874,7 @@ function scaleCompositionToBatch(formulation, batchAmount, batchUnit) {
1764
1874
  const c = comp[i], g = byRow.get(c), one = r.pieces ? flPieceRowKg(Object.assign({}, c, { amount: 1 })) : null;
1765
1875
  if (one && g != null && isFinite(g)) out.pieces.set(c, flPieceCount((g * MASS_TO_KG[batchUnit]) / one));
1766
1876
  });
1877
+ _cntPieces(out.pieces);
1767
1878
  }
1768
1879
  if (dim === 'volume' && pd) {
1769
1880
  out.density = pd; out.totalMassKg = amt * VOL_TO_L[batchUnit] * pd.kgPerL; out.partsSum = amt;
@@ -1773,6 +1884,7 @@ function scaleCompositionToBatch(formulation, batchAmount, batchUnit) {
1773
1884
  const c = comp[i], one = r.pieces ? flPieceRowKg(Object.assign({}, c, { amount: 1 })) : null;
1774
1885
  if (one && r.massFraction != null && isFinite(r.massFraction)) out.pieces.set(c, flPieceCount((r.massFraction * out.totalMassKg) / one));
1775
1886
  });
1887
+ _cntPieces(out.pieces);
1776
1888
  }
1777
1889
  return out;
1778
1890
  }
@@ -1926,8 +2038,9 @@ const QS_ROLE = 'Balance (q.s.)';
1926
2038
  function sumActualRowsMassKg(rows, formula) {
1927
2039
  if (!Array.isArray(rows)) return null;
1928
2040
  let kg = 0, n = 0;
2041
+ const _aside = typeof flCountedAside === 'function' ? flCountedAside(rows) : new Set(); // 10 wicks: counted, not in the mass (27e)
1929
2042
  for (const c of rows) {
1930
- if (!c || !(c.ingredientId || c.formulationId)) continue;
2043
+ if (!c || !(c.ingredientId || c.formulationId) || _aside.has(c)) continue;
1931
2044
  const amt = parseFloat(c.amount);
1932
2045
  if (!isFinite(amt)) continue;
1933
2046
  const u = (c.unit || '').trim();
@@ -1962,7 +2075,7 @@ function applyQsBalance(rows, targetQty) {
1962
2075
  const bi = rows.findIndex(r => r && r.comp && r.comp.role === QS_ROLE);
1963
2076
  if (bi < 0) return out;
1964
2077
  let others = 0;
1965
- rows.forEach((r, i) => { if (i !== bi && r.amount != null && isFinite(r.amount)) others += r.amount; });
2078
+ rows.forEach((r, i) => { if (i !== bi && !r.counted && r.amount != null && isFinite(r.amount)) others += r.amount; }); // a counted wick is not in the batch mass (3 Dec)
1966
2079
  let bal = targetQty - others;
1967
2080
  out.qsApplied = true;
1968
2081
  out.qsShort = bal < -1e-9;
@@ -2036,7 +2149,8 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
2036
2149
  const key = c.formulationId ? ('f:' + c.formulationId) : (c.ingredientId ? ('i:' + c.ingredientId) : '');
2037
2150
  const amt = parseFloat(c.amount);
2038
2151
  const u = c.unit || '';
2039
- const comparable = (typeof isMassUnit === 'function' && isMassUnit(u)) || (typeof isVolUnit === 'function' && isVolUnit(u));
2152
+ const comparable = (typeof isMassUnit === 'function' && isMassUnit(u)) || (typeof isVolUnit === 'function' && isVolUnit(u))
2153
+ || (key.slice(0, 2) === 'i:' && typeof flIsPieceUnit === 'function' && flIsPieceUnit(u)); // "10 piece" of wick compares through its weight (27e)
2040
2154
  if (key && comparable && isFinite(amt)) actMap.set(key, { amount: amt, unit: u });
2041
2155
  });
2042
2156
  const hasActuals = actMap.size > 0;
@@ -2108,10 +2222,10 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
2108
2222
  const a = actMap.get(r.key);
2109
2223
  const planned = (r.amount != null && isFinite(r.amount)) ? r.amount : null;
2110
2224
  let actInUnit = null;
2111
- if (a) { actInUnit = toUnit(a.amount, a.unit, r.key); if (actInUnit != null) actualTotal += actInUnit; }
2225
+ if (a) { actInUnit = toUnit(a.amount, a.unit, r.key); if (actInUnit != null && !r.counted) actualTotal += actInUnit; } // a wick: not in the total (27e)
2112
2226
  const delta = (hasActuals && planned != null && actInUnit != null) ? (actInUnit - planned) : null;
2113
2227
  const rel = (delta != null && planned > 0) ? Math.abs(delta) / planned : (delta != null && actInUnit > 0 ? 1 : null);
2114
- return { key: r.key, name: r.name, planned, actInUnit, actRaw: a, delta, rel, purity: r.purity, activeAmount: r.activeAmount, qs: r.qs, lotDev: r.lotDev || null, lotBasis: r.lotBasis || null, pieces: r.pieces != null ? r.pieces : null, pieceUnit: r.pieceUnit || '' };
2228
+ return { key: r.key, name: r.name, planned, actInUnit, actRaw: a, delta, rel, purity: r.purity, activeAmount: r.activeAmount, qs: r.qs, lotDev: r.lotDev || null, lotBasis: r.lotBasis || null, pieces: r.pieces != null ? r.pieces : null, pieceUnit: r.pieceUnit || '', counted: !!r.counted };
2115
2229
  });
2116
2230
  // Union in ingredients that were ADDED to the As-prepared table but aren't in
2117
2231
  // the recipe (a spike / colorant / q.s. carrier). Without this the weigh-out
@@ -2218,7 +2332,7 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
2218
2332
  : `<div class="fl-wo-why" style="font-size:11px;color:var(--dk-muted, #64748b);margin-top:1px;font-variant-numeric:tabular-nums">${cv(r.activeAmount)} ${esc(displayUnit)} active ÷ ${esc(String(+r.purity))}% ${r.lotBasis ? `(lot <span translate="no">${esc(String(r.lotBasis.lotNumber))}</span> assay)` : '(nominal)'} = <strong style="color:var(--dk-text-2, #334155)">${cv(r.planned)} ${esc(displayUnit)}</strong></div>`;
2219
2333
  const body = rows.map((r, i) => `<tr data-wo-key="${esc(r.key)}" style="${hasActuals ? dRowBg(r.rel) : ''}">
2220
2334
  <td style="padding:4px 8px;color:var(--dk-faint, #94a3b8)">${i + 1}</td>
2221
- <td style="padding:4px 8px">${esc(r.name)}${purityWhy(r)}${r.pieces != null ? `<div class="fl-wo-why" style="font-size:11px;color:var(--dk-muted, #64748b);margin-top:1px">${esc(String(r.pieces))} ${esc(r.pieceUnit === 'piece' && r.pieces !== 1 ? 'pieces' : r.pieceUnit)} by count</div>` : ''}${r._added ? ` <span style="font-size:9.5px;color:var(--dk-red-fg, #b91c1c);font-weight:600;background:var(--dk-red-bg, #fef2f2);border:1px solid var(--dk-red-line, #fecaca);border-radius:4px;padding:0 4px;vertical-align:middle;white-space:nowrap" title="Added to the as-prepared batch — not part of the linked recipe">+ not in recipe</span>` : ''}</td>
2335
+ <td style="padding:4px 8px">${esc(r.name)}${purityWhy(r)}${r.pieces != null ? `<div class="fl-wo-why" style="font-size:11px;color:var(--dk-muted, #64748b);margin-top:1px">${esc(String(r.pieces))} ${esc(r.pieceUnit === 'piece' && r.pieces !== 1 ? 'pieces' : r.pieceUnit)} by count${r.counted ? ' · not in the total' : ''}</div>` : ''}${r._added ? ` <span style="font-size:9.5px;color:var(--dk-red-fg, #b91c1c);font-weight:600;background:var(--dk-red-bg, #fef2f2);border:1px solid var(--dk-red-line, #fecaca);border-radius:4px;padding:0 4px;vertical-align:middle;white-space:nowrap" title="Added to the as-prepared batch — not part of the linked recipe">+ not in recipe</span>` : ''}</td>
2222
2336
  <td style="padding:4px 8px;text-align:right;font-variant-numeric:tabular-nums;font-weight:600;color:var(--dk-text, #0f172a)">${r.planned != null ? `${cv(r.planned)}${purityTag(r)}${qsTag(r)}` : '<span style="color:var(--dk-dim, #cbd5e1)">—</span>'}</td>
2223
2337
  ${hasActuals ? `<td style="padding:4px 8px;text-align:right;font-variant-numeric:tabular-nums">${
2224
2338
  r.actInUnit != null ? cv(r.actInUnit)
@@ -2397,7 +2511,7 @@ function defaultPercentBasis(formulation, costSummary) {
2397
2511
  // up the chain. Null for a batch with no parent, or when the parent has no cost.
2398
2512
  let _flDerivedDepth = 0;
2399
2513
  function flDerivedBatchCost(batch, displayCcy) {
2400
- if (!batch || !batch.parentBatchId || _flDerivedDepth > 10) return null;
2514
+ if (!batch || !batch.parentBatchId || _flDerivedDepth > 10 || (typeof flCostHidden === 'function' && flCostHidden())) return null;
2401
2515
  const p = (db.batches || []).find(x => x && x.id === batch.parentBatchId);
2402
2516
  if (!p) return null;
2403
2517
  const ccy = displayCcy || (typeof getDisplayCurrency === 'function' ? getDisplayCurrency() : 'USD');
@@ -2418,6 +2532,7 @@ function flDerivedBatchCost(batch, displayCcy) {
2418
2532
  } finally { _flDerivedDepth--; }
2419
2533
  }
2420
2534
  function computeBatchCost(batch, displayCcy = getDisplayCurrency()) {
2535
+ if (typeof flCostHidden === 'function' && flCostHidden()) return null; // 0267
2421
2536
  const f = (typeof flBatchFormula === 'function' ? flBatchFormula(batch) : db.formulations.find(x => x.id === batch.formulationId));
2422
2537
  if (!f) return null;
2423
2538
  const der = flDerivedBatchCost(batch, displayCcy);
@@ -2431,13 +2546,17 @@ function computeBatchCost(batch, displayCcy = getDisplayCurrency()) {
2431
2546
  // every volume-unit batch silently reported no total.)
2432
2547
  const _umk = (typeof _batchUnitMassKg === 'function') ? _batchUnitMassKg(batch) : null;
2433
2548
  const sizeKg = quantityToKg(batch.targetQuantity, batch.unit, f, _umk);
2549
+ // Parts counted per piece (1 wick per candle) × the pieces the batch makes (3 Dec).
2550
+ const _isCount = _umk != null && !(batch.unit in MASS_TO_KG) && !(batch.unit in VOL_TO_L);
2551
+ const countedCost = perKg.countedPerPiece ? perKg.countedPerPiece * flProductUnits(f, sizeKg, _isCount ? batch.targetQuantity : null) : 0;
2434
2552
  return {
2435
2553
  formulation: f,
2436
2554
  perKg: perKg.perKg,
2437
2555
  sizeKg,
2438
- total: sizeKg != null ? perKg.perKg * sizeKg : null,
2556
+ total: sizeKg != null ? perKg.perKg * sizeKg + countedCost : null,
2557
+ counted: countedCost || null,
2439
2558
  currency: displayCcy,
2440
- missing: perKg.missing,
2559
+ missing: perKg.missing.concat((perKg.countedUnpriced || []).map(ing => ({ reason: 'no cost on file (counted per piece)', ingredient: ing }))),
2441
2560
  };
2442
2561
  }
2443
2562
 
@@ -2505,6 +2624,7 @@ function shelfLifeBadgeHtml(iso) {
2505
2624
  }
2506
2625
 
2507
2626
  function computeProjectCost(projectId, displayCcy = getDisplayCurrency()) {
2627
+ if (typeof flCostHidden === 'function' && flCostHidden()) return null; // 0267
2508
2628
  const project = db.projects.find(p => p.id === projectId);
2509
2629
  if (!project) return null;
2510
2630
  const formulations = db.formulations.filter(f => f.projectId === projectId);
@@ -2530,7 +2650,7 @@ function computeProjectCost(projectId, displayCcy = getDisplayCurrency()) {
2530
2650
  // $/kg so different units don't distort the comparison.
2531
2651
  // ============================================================
2532
2652
  function ingredientCostChangePct(ing) {
2533
- if (!ing?.cost?.history?.length) return null;
2653
+ if (!ing?.cost?.history?.length || (typeof flCostHidden === 'function' && flCostHidden())) return null;
2534
2654
  const cur = costPerKgInOwnCurrency(ing.cost, ing.density, ing.densityUnit, ing.unitMass);
2535
2655
  // Walk back to oldest entry that has a comparable per-kg value
2536
2656
  for (let i = 0; i < ing.cost.history.length; i++) {
@@ -2575,6 +2695,25 @@ function convertQuantity(value, fromUnit, toUnit, formula) {
2575
2695
  // Same conversion with an EXPLICIT density (kg/L === g/mL). Use this for a
2576
2696
  // single ingredient row — 41.86 g of sucrose is 26.3 mL at sucrose's 1.59,
2577
2697
  // not 40 mL at the formula's 1.0465. Mass↔volume without a density → null.
2698
+ // A quantity in a batch's own unit when either side counts (pouch, candle, piece): through the mass per unit,
2699
+ // the drawn record's own (fromUnitMass) and the batch's (Jun, 2 Dec: 100 g pulled from a pouch batch, or 2
2700
+ // pouches from a gram batch, came off nothing). Same unit, any case, is itself. null when it can't be resolved.
2701
+ function flQtyToBatchUnit(val, fromUnit, batch, formula, fromUnitMass) {
2702
+ const v = parseFloat(val); if (!isFinite(v)) return null;
2703
+ const to = String((batch && batch.unit) || '').trim(), from = String(fromUnit || to).trim();
2704
+ if (!to) return null;
2705
+ if (from.toLowerCase() === to.toLowerCase()) return v;
2706
+ const direct = convertQuantity(v, from, to, formula); if (direct != null) return direct;
2707
+ const umKg = um => { if (!um) return null; const x = parseFloat(um.value), f = isMassUnit(um.unit) ? massToKg(um.unit) : null; return (isFinite(x) && x > 0 && f) ? x * f : null; };
2708
+ const counts = u => !isMassUnit(u) && !isVolUnit(u);
2709
+ let kg;
2710
+ if (counts(from)) { const pk = umKg(fromUnitMass); if (pk == null) return null; kg = v * pk; }
2711
+ else kg = convertQuantity(v, from, 'kg', formula);
2712
+ if (kg == null) return null;
2713
+ if (counts(to)) { const pk = umKg(batch.unitMass); return pk != null ? kg / pk : null; }
2714
+ return convertQuantity(kg, 'kg', to, formula);
2715
+ }
2716
+
2578
2717
  function convertQuantityAtDensity(value, fromUnit, toUnit, dens) {
2579
2718
  const v = parseFloat(value);
2580
2719
  if (!isFinite(v)) return null;
@@ -2653,14 +2792,17 @@ function quantityCost(qty, unit, formula, displayCcy) {
2653
2792
  const ccy = displayCcy ||
2654
2793
  (typeof getDisplayCurrency === 'function' ? getDisplayCurrency() : null) ||
2655
2794
  (formula && formula.costCurrency) || 'USD';
2656
- let perKg = null;
2795
+ let perKg = null, perPiece = null;
2657
2796
  try {
2658
2797
  const c = formula && typeof computeFormulationCost === 'function' ? computeFormulationCost(formula, ccy) : null;
2659
2798
  if (c && isFinite(c.perKg)) perKg = c.perKg;
2799
+ if (c && c.countedPerPiece > 0) perPiece = c.countedPerPiece;
2660
2800
  } catch (_) { perKg = null; }
2661
2801
  const kg = quantityToKg(qty, unit, formula);
2662
- const computed = (perKg != null && kg != null) ? perKg * kg : null;
2663
- return { perKg, kg, computed, ccy, convertible: kg != null };
2802
+ // A wick, priced per piece of product (27f: a candle sample read $1.72 without its $0.12 wick).
2803
+ const counted = (perPiece != null && kg > 0 && typeof flProductUnits === 'function') ? perPiece * flProductUnits(formula, kg, null) : 0;
2804
+ const computed = (perKg != null && kg != null) ? perKg * kg + counted : null;
2805
+ return { perKg, kg, computed, ccy, convertible: kg != null, counted };
2664
2806
  }
2665
2807
 
2666
2808
  // Open the global Display-currency setting — Settings modal → Preferences tab
@@ -2690,6 +2832,7 @@ function goToDisplayCurrencySetting() {
2690
2832
  // total is null only when there's neither an override nor a computable cost.
2691
2833
  function entityEffectiveCost(qty, unit, formula, override, overrideCcy, note) {
2692
2834
  const { computed, ccy } = quantityCost(qty, unit, formula);
2835
+ if (typeof flCostHidden === 'function' && flCostHidden()) return { total: null, computed: null, currency: ccy, overridden: false, note: '', driftPct: null, hidden: true }; // 0267: not the override either
2693
2836
  const ovRaw = (override != null && override !== '' && isFinite(parseFloat(override))) ? parseFloat(override) : null;
2694
2837
  const ovCcy = overrideCcy || ccy;
2695
2838
  let ov = ovRaw;
@@ -2719,6 +2862,7 @@ const COST_DRIFT_PCT = 10;
2719
2862
  // unpriceable. `label` names the value in the non-override tooltip.
2720
2863
  function entityCostCellHtml(summary, label) {
2721
2864
  const lbl = label || 'Cost';
2865
+ if (typeof flCostHidden === 'function' && flCostHidden()) return '<span style="color:var(--dk-faint, #94a3b8)">—</span>'; // 0267
2722
2866
  if (!summary || summary.total == null) {
2723
2867
  return `<span title="${esc(lbl)}, not priced (no ingredient prices, or a volume amount with no density)" style="color:var(--dk-faint, #94a3b8)">—</span>`;
2724
2868
  }
@@ -2744,7 +2888,8 @@ function entityCostCellHtml(summary, label) {
2744
2888
  // set — the override + a divergence warning vs the live computed value.
2745
2889
  // o = { kind:'sample'|'batch', id, qty, unit, formula, override }.
2746
2890
  function entityCostValueHtml(o) {
2747
- const { perKg, computed, ccy, convertible } = quantityCost(o.qty, o.unit, o.formula);
2891
+ if (typeof flCostHidden === 'function' && flCostHidden()) return '<span style="color:var(--dk-faint, #94a3b8)">—</span>'; // 0267: cost hidden from Viewers
2892
+ const { perKg, computed, ccy, convertible, counted } = quantityCost(o.qty, o.unit, o.formula);
2748
2893
  const money = v => (typeof formatMoney === 'function') ? formatMoney(v, ccy) : (ccy + ' ' + (+v).toFixed(2));
2749
2894
  const ovRaw = (o.override != null && o.override !== '' && isFinite(parseFloat(o.override))) ? parseFloat(o.override) : null;
2750
2895
  // The override was entered in o.overrideCcy (legacy values w/o a stamp are
@@ -2808,7 +2953,7 @@ function entityCostValueHtml(o) {
2808
2953
  const col = (why === 'needs-density') ? 'var(--dk-amber-fg, #b45309)' : 'var(--text-muted)';
2809
2954
  return `<span style="color:var(--text-muted)">—</span> <span style="font-size:11px;color:${col}">${msg}</span>${editBtn}`;
2810
2955
  }
2811
- const breakdown = `<span style="font-size:11px;color:var(--text-muted);margin-left:6px">${esc(String(o.qty))} ${esc(o.unit || '')} × ${money(perKg)}/kg</span>`;
2956
+ const breakdown = `<span style="font-size:11px;color:var(--text-muted);margin-left:6px">${esc(String(o.qty))} ${esc(o.unit || '')} × ${money(perKg)}/kg${counted > 0 ? ` + ${money(counted)} counted parts` : ''}</span>`;
2812
2957
  return `<strong>${money(computed)}</strong>${breakdown}${editBtn}${ccyLine}`;
2813
2958
  }
2814
2959
 
package/vendor/nesting.js CHANGED
@@ -274,7 +274,11 @@ function _rowWtFractionsWithin(f, unresolved) {
274
274
  const comp = raw.filter(c => c && (c.ingredientId || c.formulationId));
275
275
  if (!comp.length) return [];
276
276
 
277
+ // A counted part marked "Not mixed in" beside % rows (1 wick, flCountedAside) is outside the 100%: no share of the
278
+ // mix here, and not a mixed basis (3 Dec).
279
+ const _aside = typeof flCountedAside === 'function' ? flCountedAside(comp) : new Set();
277
280
  const kinds = comp.map(c => {
281
+ if (_aside.has(c)) return 'aside';
278
282
  const u = String(c.unit || 'wt%').trim();
279
283
  const lower = u.toLowerCase();
280
284
  if (lower.startsWith('wt') || u === '%') return 'wt';
@@ -301,9 +305,9 @@ function _rowWtFractionsWithin(f, unresolved) {
301
305
  return comp.map(_ => 0);
302
306
  }
303
307
 
304
- const allWt = kinds.every(k => k === 'wt');
308
+ const allWt = kinds.every(k => k === 'wt' || k === 'aside');
305
309
  if (allWt) {
306
- const nums = comp.map(c => _usableAmount(c, unresolved));
310
+ const nums = comp.map((c, i) => kinds[i] === 'aside' ? 0 : _usableAmount(c, unresolved));
307
311
  const sum = nums.reduce((a, b) => a + b, 0);
308
312
  if (sum <= 0) return nums.map(_ => 0);
309
313
  return nums.map(n => n / sum);
@@ -345,6 +349,13 @@ function _rowWtFractionsWithin(f, unresolved) {
345
349
  }
346
350
  if (kinds[i] === 'wt') return amt; // treat as relative weight
347
351
  if (kinds[i] === 'vol') return amt; // treat as relative volume (best-effort)
352
+ // A row that can't be weighed (a piece with no weight per piece, an unknown unit) is named, not dropped in silence:
353
+ // the rest would otherwise read as 100% (3 Dec, Designer). A part not mixed in (a wick) is no share of the mix.
354
+ if (kinds[i] === 'unknown' && c.ingredientId) {
355
+ const pc = typeof flIsPieceUnit === 'function' && flIsPieceUnit(c.unit);
356
+ const ing = db.ingredients.find(x => x.id === c.ingredientId);
357
+ if (!(pc && ing && ing.notMixedIn)) unresolved && unresolved.push({ reason: pc ? 'no-weight' : 'unknown-unit', ingredientId: c.ingredientId, unit: c.unit || '' });
358
+ }
348
359
  return 0;
349
360
  });
350
361
  const sum = kgPerRow.reduce((a, b) => a + b, 0);
@@ -305,7 +305,7 @@ function flNlEuPanelHtml(f, calc) {
305
305
  const FL_NL_MAIN = ['energy', 'fat', 'carb', 'protein', 'sodium'];
306
306
  function flNlCost(f) {
307
307
  const out = { ok: false, why: 'nocost', unpriced: [], price: null };
308
- if (!f || typeof computeFormulationCost !== 'function') return out;
308
+ if (!f || typeof computeFormulationCost !== 'function' || (typeof flCostHidden === 'function' && flCostHidden())) return out; // 0267: no cost, price or margin for a Viewer with cost hidden
309
309
  const pr = (f.pricing && typeof f.pricing === 'object') ? f.pricing : {};
310
310
  const target0 = parseFloat(pr.targetPrice);
311
311
  const hasPrice = Number.isFinite(target0) && target0 > 0;
@@ -363,7 +363,7 @@ function flNlCost(f) {
363
363
  out.unpriced = (c.missing || []).map(m => (m && ((m.ingredient && m.ingredient.name) || (m.subFormula && m.subFormula.name) || m.reason)) || '').filter(Boolean);
364
364
  if (hasPrice) {
365
365
  const basis = pr.basisUnit || 'kg';
366
- const perKg = basis === 'kg' ? target : (typeof convertPricePerBasis === 'function' ? convertPricePerBasis(target, basis, 'kg', sv.density || (typeof _rolledUpDensity === 'function' ? _rolledUpDensity(f) : null)) : null);
366
+ const perKg = basis === 'kg' ? target : (typeof convertPricePerBasis === 'function' ? convertPricePerBasis(target, basis, 'kg', sv.density || (typeof _rolledUpDensity === 'function' ? _rolledUpDensity(f) : null), pr.fill) : null);
367
367
  if (Number.isFinite(perKg) && perKg > 0) {
368
368
  const ps = perKg * sv.g / 1000, cs = out.perServingFull; // with packaging, labor and overhead
369
369
  out.price = { perKg, perServing: ps, perContainer: n > 0 ? ps * n : null, profitServing: ps - cs, marginPct: (ps - cs) / ps * 100 };
@@ -407,6 +407,7 @@ function flNlCostLines(f) {
407
407
  return out;
408
408
  }
409
409
  function _nlCostCardHtml(f) {
410
+ if ((typeof flCostHidden === 'function' && flCostHidden())) return ''; // 0267
410
411
  const k = flNlCost(f);
411
412
  if (!k.ok) return `<div class="card">
412
413
  <div class="card-header"><h2>Cost</h2></div>
@@ -739,7 +740,7 @@ function flNlTabHtml(f) {
739
740
  ${dens}${yld}
740
741
  </div>
741
742
  </div>
742
- <div class="nl-view"><button type="button" class="btn btn-secondary btn-sm nl-notes-btn" aria-pressed="${flNlNotesOn()}" onclick="flNlSetNotes('${id}', ${!flNlNotesOn()})" data-tip="The amber notes about missing data. Your choice, on every formula; the allergen check always shows. Nothing on the label itself changes.">Notes: ${flNlNotesOn() ? 'on' : 'off'}</button><span class="fl-seg-group" role="group" aria-label="Show">${['nutrition', 'cost'].map(v => `<button type="button" class="fl-seg${view === v ? ' on' : ''}" aria-pressed="${view === v}" onclick="flNlSetView('${id}','${v}')">${v === 'cost' ? 'Cost' : 'Nutrition'}</button>`).join('')}</span></div>
743
+ <div class="nl-view"><button type="button" class="btn btn-secondary btn-sm nl-notes-btn" aria-pressed="${flNlNotesOn()}" onclick="flNlSetNotes('${id}', ${!flNlNotesOn()})" data-tip="The amber notes about missing data. Your choice, on every formula; the allergen check always shows. Nothing on the label itself changes.">Notes: ${flNlNotesOn() ? 'on' : 'off'}</button><span class="fl-seg-group fl-cost" role="group" aria-label="Show">${['nutrition', 'cost'].map(v => `<button type="button" class="fl-seg${view === v ? ' on' : ''}" aria-pressed="${view === v}" onclick="flNlSetView('${id}','${v}')">${v === 'cost' ? 'Cost' : 'Nutrition'}</button>`).join('')}</span></div>
743
744
  ${view === 'cost' ? _nlCostCardHtml(f) : `<div class="card">
744
745
  <div class="card-header"><h2>Ingredient statement</h2>
745
746
  <button class="btn btn-secondary btn-sm" onclick="flNlCopyStatement('${id}')">Copy</button></div>
@@ -793,7 +794,7 @@ function _nlNotesWrap(html, id) {
793
794
  const line = n ? `<div class="nl-notes-hidden">${n} note${n === 1 ? '' : 's'} hidden. <a onclick="flNlSetNotes('${id}', true)">Show</a></div>` : '';
794
795
  return `<div class="nl-notes-off">${line}${html}</div>`;
795
796
  }
796
- function flNlView() { try { return localStorage.getItem('formlab_nl_view') === 'cost' ? 'cost' : 'nutrition'; } catch (_) { return 'nutrition'; } }
797
+ function flNlView() { try { return localStorage.getItem('formlab_nl_view') === 'cost' && !(typeof flCostHidden === 'function' && flCostHidden()) ? 'cost' : 'nutrition'; } catch (_) { return 'nutrition'; } }
797
798
  function flNlSetView(fid, v) {
798
799
  try { localStorage.setItem('formlab_nl_view', v === 'cost' ? 'cost' : 'nutrition'); } catch (_) {}
799
800
  const f = (db.formulations || []).find(x => x.id === fid), el = document.getElementById('tab-label');
@@ -784,7 +784,8 @@ function _tpIngredientView(ing) {
784
784
  };
785
785
  out.density = num(ing.density);
786
786
  out.mw = num(ing.mw);
787
- out.cost = num(ing.cost && typeof ing.cost === 'object' ? ing.cost.value : ing.cost);
787
+ out.cost = (typeof flCostHidden === 'function' && flCostHidden()) ? null // 0267: a Viewer with cost hidden
788
+ : num(ing.cost && typeof ing.cost === 'object' ? ing.cost.value : ing.cost);
788
789
  out.purity = num(ing.purity); // % active — filterable (purity < 90) + usable in theo formulas (ing.purity)
789
790
  out.stock = num(ing.stockOnHand); // on-hand — filterable (stock < 100) [also on the Inventory view]
790
791
  out.reorder = num(ing.reorderThreshold); // reorder point — filterable (stock <= reorder)