formlab-mcp 0.7.8 → 0.7.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.7.8",
3
+ "version": "0.7.10",
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.8",
5
+ "version": "0.7.10",
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.8",
11
+ "version": "0.7.10",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
@@ -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; }) };
@@ -36,9 +36,10 @@ function _costPerKg(i) {
36
36
  const dens = _densityKgPerL(i);
37
37
  return dens ? +((v / _VOL_TO_L[unit]) / dens).toFixed(6) : null;
38
38
  }
39
- const pk = _pieceKg(i); // priced per piece (a wick): through the weight per piece (0.7.8)
39
+ const pk = _PACK_UNITS.has(unit) ? null : _pieceKg(i); // priced per piece (a wick): through the weight per piece (0.7.8); a box is many pieces
40
40
  return pk ? +(v / pk).toFixed(6) : null;
41
41
  }
42
+ const _PACK_UNITS = new Set(['box', 'boxes', 'pack', 'packs', 'package', 'case', 'cases', 'carton', 'cartons', 'bag', 'bags', 'pallet', 'pallets', 'dozen', 'doz', 'pair', 'pairs', 'set', 'sets', 'kit', 'kits', 'sleeve', 'tray', 'bundle', 'gross', 'ream', 'ppm', 'ppb', 'mol', 'mmol', 'eq', 'phr', '%', 'wt%', 'vol%']);
42
43
  function _pieceKg(i) {
43
44
  const m = i && i.unitMass; const v = m ? Number(m.value) : NaN;
44
45
  const f = m ? _MASS_TO_KG[String(m.unit || '').toLowerCase()] : null;
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 };
@@ -790,6 +790,13 @@ function amountConversions(amount, unit, ingredient, opts) {
790
790
  } else {
791
791
  res.note = `"${unit}" is a relative fraction — its absolute mass/volume depends on the batch size. Set a "Scale to batch" amount above to materialize.`;
792
792
  }
793
+ } else if (ingredient && flIsPieceUnit(unit) && flPieceMassKg(ingredient.unitMass) != null) {
794
+ // 1 wick → its weight, through the weight per piece (2 Dec).
795
+ const kg = amt * flPieceMassKg(ingredient.unitMass);
796
+ res.cross = { label: `by weight per piece (${ingredient.unitMass.value} ${ingredient.unitMass.unit})`,
797
+ rows: _AMT_VIEW_MASS.map(u => ({ unit: u, value: kg / MASS_TO_KG[u] })) };
798
+ } else if (ingredient && flIsPieceUnit(unit)) {
799
+ res.note = 'Set a Weight per piece on the ingredient to see this in grams.';
793
800
  } else {
794
801
  res.note = 'No unit conversions available for this unit.';
795
802
  }
@@ -817,9 +824,19 @@ function flPieceMassKg(unitMass) {
817
824
  const v = unitMass ? parseFloat(unitMass.value) : NaN;
818
825
  return (isFinite(v) && v > 0 && unitMass.unit in MASS_TO_KG) ? v * MASS_TO_KG[unitMass.unit] : null;
819
826
  }
827
+ const FL_PACK_UNITS = new Set(['box', 'boxes', 'pack', 'packs', 'package', 'case', 'cases', 'carton', 'cartons', 'bag', 'bags', 'pallet', 'pallets', 'dozen', 'doz', 'pair', 'pairs', 'set', 'sets', 'kit', 'kits', 'sleeve', 'tray', 'bundle', 'gross', 'ream']);
828
+ // A count of pieces as people take them off the shelf: within 2% of a whole number it is that number (12 candles at
829
+ // 226.8 g against a 227.3 g recipe ask for 11.97 wicks, which means 12). Anything further off stays as computed.
830
+ function flPieceCount(n) {
831
+ if (n == null || !isFinite(n)) return n;
832
+ const r = Math.round(n);
833
+ return (r > 0 && Math.abs(n - r) <= 0.02 * r) ? r : +n.toFixed(3);
834
+ }
820
835
  function flIsPieceUnit(u) {
821
836
  const raw = String(u || '').trim(), lower = raw.toLowerCase();
822
837
  if (!raw || raw === '%' || lower.startsWith('wt') || lower.startsWith('vol') || ['ppm', 'ppb', 'mol', 'mmol', 'eq', 'phr'].includes(lower)) return false;
838
+ // Packs hold many pieces (a box of wicks): never one piece, so never priced or weighed as one.
839
+ if (FL_PACK_UNITS.has(lower)) return false;
823
840
  const _cu = (typeof db !== 'undefined' && db && db.customUnits && Object.prototype.hasOwnProperty.call(db.customUnits, raw)) ? db.customUnits[raw] : null;
824
841
  if (_cu) return _cu.dimension === 'count'; // a custom count unit ("wick") is a piece; other custom units convert by their own rule
825
842
  const hit = t => Object.keys(t).some(k => k === raw || k.toLowerCase() === lower);
@@ -836,7 +853,7 @@ function flPieceRowKg(c) {
836
853
  return per == null ? null : amt * per;
837
854
  }
838
855
  function costPerKgInOwnCurrency(cost, density, densityUnit, unitMass) {
839
- if (!cost || cost.value == null || cost.value === '') return null;
856
+ if (!cost || cost.value == null || cost.value === '' || (typeof flCostHidden === 'function' && flCostHidden())) return null;
840
857
  const v = parseFloat(cost.value);
841
858
  if (!isFinite(v)) return null;
842
859
  const u = cost.unit || 'kg';
@@ -1020,13 +1037,20 @@ function setDisplayCostUnit(u) {
1020
1037
  // Convert an ing.cost to price-per-`unit` in the cost's OWN currency.
1021
1038
  // mass↔mass and vol↔vol are exact; mass↔vol needs the ingredient's density.
1022
1039
  // Returns null when the conversion isn't possible (no density, unknown unit).
1023
- function costPerUnitInOwnCurrency(cost, unit, density, densityUnit) {
1024
- if (!cost || cost.value == null || cost.value === '' || !unit) return null;
1040
+ function costPerUnitInOwnCurrency(cost, unit, density, densityUnit, unitMass) {
1041
+ if (!cost || cost.value == null || cost.value === '' || !unit || (typeof flCostHidden === 'function' && flCostHidden())) return null;
1025
1042
  const v = parseFloat(cost.value);
1026
1043
  if (!isFinite(v)) return null;
1027
1044
  const from = cost.unit || 'kg';
1028
1045
  if (from === unit) return v;
1029
1046
  const kgPerL = _densityToKgPerL(density, densityUnit);
1047
+ // A counted ingredient (wicks): $5/kg ↔ $/piece through the weight per piece (2 Dec).
1048
+ if (typeof flIsPieceUnit === 'function' && (flIsPieceUnit(from) || flIsPieceUnit(unit))) {
1049
+ const perKg = costPerKgInOwnCurrency(cost, density, densityUnit, unitMass);
1050
+ if (perKg == null) return null;
1051
+ if (flIsPieceUnit(unit)) { const pk = flPieceMassKg(unitMass); return pk != null ? perKg * pk : null; }
1052
+ return convertPricePerBasis(perKg, 'kg', unit, kgPerL || null);
1053
+ }
1030
1054
  return convertPricePerBasis(v, from, unit, kgPerL || null);
1031
1055
  }
1032
1056
 
@@ -1075,7 +1099,7 @@ function formatMoney(amount, currency) {
1075
1099
  }
1076
1100
 
1077
1101
  function formatCostPerUnit(cost) {
1078
- if (!cost || cost.value == null || cost.value === '') return '—';
1102
+ if (!cost || cost.value == null || cost.value === '' || (typeof flCostHidden === 'function' && flCostHidden())) return '—';
1079
1103
  const v = parseFloat(cost.value);
1080
1104
  if (!isFinite(v)) return '—';
1081
1105
  return `${formatMoney(v, cost.currency || 'USD')} / ${cost.unit || 'kg'}`;
@@ -1098,6 +1122,8 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1098
1122
  // workspace each viewer should always see costs in their own preferred currency.
1099
1123
  displayCcy = displayCcy || getDisplayCurrency() || formulation.costCurrency || 'USD';
1100
1124
  basisUnit = basisUnit || formulation.costBasisUnit || 'kg';
1125
+ // 0267: cost hidden from this Viewer: an unpriced result (every caller already shows "—" for one), flagged hidden.
1126
+ 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 };
1101
1127
  const overrides = formulation.costOverrides || {};
1102
1128
  const breakdown = [];
1103
1129
  const missing = [];
@@ -1171,7 +1197,9 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1171
1197
  const kinds = comp.map(c => flPieceRowKg(c) != null ? 'mass-abs' : classifyUnit(c.unit));
1172
1198
  const allWt = comp.length && kinds.every(k => k === 'wt-frac');
1173
1199
  const allVol = comp.length && kinds.every(k => k === 'vol-frac');
1174
- const allAbs = comp.length && kinds.every(k => k === 'mass-abs' || k === 'vol-abs');
1200
+ // 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.
1201
+ const allAbs = comp.length && kinds.every((k, i) => k === 'mass-abs' || k === 'vol-abs' || (k !== 'wt-frac' && k !== 'vol-frac' && flIsPieceUnit(comp[i].unit)))
1202
+ && kinds.some(k => k === 'mass-abs' || k === 'vol-abs');
1175
1203
  const basis = allVol ? 'vol' : (allAbs ? 'abs' : 'wt');
1176
1204
 
1177
1205
  // === Vol-% recipe: derive formulation density from per-row densities ===
@@ -1248,7 +1276,9 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1248
1276
  const tryAutoPrice = (ing, c, unit, amount, kind) => {
1249
1277
  if (!ing.cost || ing.cost.value == null || ing.cost.value === '') return { ok: false, reason: 'no cost on file' };
1250
1278
  const perKgOwn = costPerKgInOwnCurrency(ing.cost, ing.density, ing.densityUnit, ing.unitMass);
1251
- if (perKgOwn == null) return { ok: false, reason: 'could not convert price unit (needs density?)' };
1279
+ if (perKgOwn == null) return { ok: false, reason: FL_PACK_UNITS.has(String(ing.cost.unit || '').trim().toLowerCase())
1280
+ ? `price is per ${String(ing.cost.unit).trim()}: enter it per piece (with a weight per piece) or per kg`
1281
+ : 'could not convert price unit (needs density?)' };
1252
1282
  const perKgDisplay = convertCurrencySync(perKgOwn, ing.cost.currency || 'USD', displayCcy);
1253
1283
  if (perKgDisplay == null) return { ok: false, reason: 'unknown currency rate' };
1254
1284
 
@@ -1485,10 +1515,18 @@ const COST_BASIS_UNITS = ['kg', 'g', 'lb', 'oz', 'ton', 'L', 'mL', 'gal'];
1485
1515
  // volume↔volume are direct; mass↔volume needs formulationKgPerL (derived
1486
1516
  // by computeFormulationCost when possible). Returns null if a needed
1487
1517
  // density is missing.
1488
- function convertPricePerBasis(price, fromBasis, toBasis, formulationKgPerL) {
1518
+ // '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.
1519
+ function convertPricePerBasis(price, fromBasis, toBasis, formulationKgPerL, fill) {
1489
1520
  if (price == null || !isFinite(price)) return null;
1490
1521
  if (fromBasis === toBasis) return price;
1491
1522
  const scaleFromKg = u => {
1523
+ if (u === 'each') {
1524
+ const v = fill ? parseFloat(fill.value) : NaN;
1525
+ if (!(isFinite(v) && v > 0)) return null;
1526
+ if (fill.unit in MASS_TO_KG) return v * MASS_TO_KG[fill.unit];
1527
+ if (fill.unit in VOL_TO_L && formulationKgPerL) return v * VOL_TO_L[fill.unit] * formulationKgPerL;
1528
+ return null;
1529
+ }
1492
1530
  if (u === 'kg') return 1;
1493
1531
  if (u in MASS_TO_KG) return MASS_TO_KG[u];
1494
1532
  if (u in VOL_TO_L) {
@@ -1722,7 +1760,12 @@ function scaleCompositionToBatch(formulation, batchAmount, batchUnit) {
1722
1760
  if (ok) partsSum += vol;
1723
1761
  byRow.set(comp[i], vol);
1724
1762
  });
1725
- return { unit: batchUnit, dim, byRow, anyNull, density: pd, totalMassKg, partsSum };
1763
+ const pieces = new Map();
1764
+ fr.rows.forEach((r, i) => {
1765
+ const c = comp[i], one = r.pieces ? flPieceRowKg(Object.assign({}, c, { amount: 1 })) : null;
1766
+ if (one && r.massFraction != null && isFinite(r.massFraction)) pieces.set(c, flPieceCount((r.massFraction * totalMassKg) / one));
1767
+ });
1768
+ return { unit: batchUnit, dim, byRow, anyNull, density: pd, totalMassKg, partsSum, pieces };
1726
1769
  }
1727
1770
  fr.rows.forEach((r, i) => {
1728
1771
  const frac = dim === 'mass' ? r.massFraction : r.volFraction;
@@ -1736,10 +1779,18 @@ function scaleCompositionToBatch(formulation, batchAmount, batchUnit) {
1736
1779
  out.pieces = new Map();
1737
1780
  fr.rows.forEach((r, i) => {
1738
1781
  const c = comp[i], g = byRow.get(c), one = r.pieces ? flPieceRowKg(Object.assign({}, c, { amount: 1 })) : null;
1739
- if (one && g != null && isFinite(g)) out.pieces.set(c, +((g * MASS_TO_KG[batchUnit]) / one).toFixed(3));
1782
+ if (one && g != null && isFinite(g)) out.pieces.set(c, flPieceCount((g * MASS_TO_KG[batchUnit]) / one));
1783
+ });
1784
+ }
1785
+ if (dim === 'volume' && pd) {
1786
+ out.density = pd; out.totalMassKg = amt * VOL_TO_L[batchUnit] * pd.kgPerL; out.partsSum = amt;
1787
+ // A wick in a volume batch: no volume to scale, but still a count, from its mass share (2 Dec).
1788
+ out.pieces = new Map();
1789
+ fr.rows.forEach((r, i) => {
1790
+ const c = comp[i], one = r.pieces ? flPieceRowKg(Object.assign({}, c, { amount: 1 })) : null;
1791
+ if (one && r.massFraction != null && isFinite(r.massFraction)) out.pieces.set(c, flPieceCount((r.massFraction * out.totalMassKg) / one));
1740
1792
  });
1741
1793
  }
1742
- if (dim === 'volume' && pd) { out.density = pd; out.totalMassKg = amt * VOL_TO_L[batchUnit] * pd.kgPerL; out.partsSum = amt; }
1743
1794
  return out;
1744
1795
  }
1745
1796
 
@@ -1898,6 +1949,8 @@ function sumActualRowsMassKg(rows, formula) {
1898
1949
  if (!isFinite(amt)) continue;
1899
1950
  const u = (c.unit || '').trim();
1900
1951
  if (u in MASS_TO_KG) { kg += amt * MASS_TO_KG[u]; n++; continue; }
1952
+ const _pk = flPieceRowKg(c); // 12 wicks, by their weight per piece (2 Dec)
1953
+ if (_pk != null) { kg += _pk; n++; continue; }
1901
1954
  if (u in VOL_TO_L) {
1902
1955
  let d = null;
1903
1956
  if (c.ingredientId) {
@@ -2058,6 +2111,11 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
2058
2111
  const toUnit = (amt, from, key) => {
2059
2112
  if (amt == null || !isFinite(amt)) return null;
2060
2113
  if (!from || from === w.unit) return amt;
2114
+ // Wicks logged as "12 piece": through the ingredient's weight per piece into the sheet's mass unit (2 Dec).
2115
+ if (typeof key === 'string' && key.slice(0, 2) === 'i:' && flIsPieceUnit(from) && w.unit in MASS_TO_KG) {
2116
+ const kg = flPieceRowKg({ ingredientId: key.slice(2), amount: amt, unit: from });
2117
+ return kg == null ? null : kg / MASS_TO_KG[w.unit];
2118
+ }
2061
2119
  if (typeof convertQuantityAtDensity !== 'function') return null;
2062
2120
  const v = convertQuantityAtDensity(amt, from, w.unit, rowDensityKgPerL(key));
2063
2121
  return (v == null || !isFinite(v)) ? null : v;
@@ -2356,7 +2414,7 @@ function defaultPercentBasis(formulation, costSummary) {
2356
2414
  // up the chain. Null for a batch with no parent, or when the parent has no cost.
2357
2415
  let _flDerivedDepth = 0;
2358
2416
  function flDerivedBatchCost(batch, displayCcy) {
2359
- if (!batch || !batch.parentBatchId || _flDerivedDepth > 10) return null;
2417
+ if (!batch || !batch.parentBatchId || _flDerivedDepth > 10 || (typeof flCostHidden === 'function' && flCostHidden())) return null;
2360
2418
  const p = (db.batches || []).find(x => x && x.id === batch.parentBatchId);
2361
2419
  if (!p) return null;
2362
2420
  const ccy = displayCcy || (typeof getDisplayCurrency === 'function' ? getDisplayCurrency() : 'USD');
@@ -2377,6 +2435,7 @@ function flDerivedBatchCost(batch, displayCcy) {
2377
2435
  } finally { _flDerivedDepth--; }
2378
2436
  }
2379
2437
  function computeBatchCost(batch, displayCcy = getDisplayCurrency()) {
2438
+ if (typeof flCostHidden === 'function' && flCostHidden()) return null; // 0267
2380
2439
  const f = (typeof flBatchFormula === 'function' ? flBatchFormula(batch) : db.formulations.find(x => x.id === batch.formulationId));
2381
2440
  if (!f) return null;
2382
2441
  const der = flDerivedBatchCost(batch, displayCcy);
@@ -2464,6 +2523,7 @@ function shelfLifeBadgeHtml(iso) {
2464
2523
  }
2465
2524
 
2466
2525
  function computeProjectCost(projectId, displayCcy = getDisplayCurrency()) {
2526
+ if (typeof flCostHidden === 'function' && flCostHidden()) return null; // 0267
2467
2527
  const project = db.projects.find(p => p.id === projectId);
2468
2528
  if (!project) return null;
2469
2529
  const formulations = db.formulations.filter(f => f.projectId === projectId);
@@ -2489,7 +2549,7 @@ function computeProjectCost(projectId, displayCcy = getDisplayCurrency()) {
2489
2549
  // $/kg so different units don't distort the comparison.
2490
2550
  // ============================================================
2491
2551
  function ingredientCostChangePct(ing) {
2492
- if (!ing?.cost?.history?.length) return null;
2552
+ if (!ing?.cost?.history?.length || (typeof flCostHidden === 'function' && flCostHidden())) return null;
2493
2553
  const cur = costPerKgInOwnCurrency(ing.cost, ing.density, ing.densityUnit, ing.unitMass);
2494
2554
  // Walk back to oldest entry that has a comparable per-kg value
2495
2555
  for (let i = 0; i < ing.cost.history.length; i++) {
@@ -2534,6 +2594,25 @@ function convertQuantity(value, fromUnit, toUnit, formula) {
2534
2594
  // Same conversion with an EXPLICIT density (kg/L === g/mL). Use this for a
2535
2595
  // single ingredient row — 41.86 g of sucrose is 26.3 mL at sucrose's 1.59,
2536
2596
  // not 40 mL at the formula's 1.0465. Mass↔volume without a density → null.
2597
+ // A quantity in a batch's own unit when either side counts (pouch, candle, piece): through the mass per unit,
2598
+ // the drawn record's own (fromUnitMass) and the batch's (Jun, 2 Dec: 100 g pulled from a pouch batch, or 2
2599
+ // pouches from a gram batch, came off nothing). Same unit, any case, is itself. null when it can't be resolved.
2600
+ function flQtyToBatchUnit(val, fromUnit, batch, formula, fromUnitMass) {
2601
+ const v = parseFloat(val); if (!isFinite(v)) return null;
2602
+ const to = String((batch && batch.unit) || '').trim(), from = String(fromUnit || to).trim();
2603
+ if (!to) return null;
2604
+ if (from.toLowerCase() === to.toLowerCase()) return v;
2605
+ const direct = convertQuantity(v, from, to, formula); if (direct != null) return direct;
2606
+ 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; };
2607
+ const counts = u => !isMassUnit(u) && !isVolUnit(u);
2608
+ let kg;
2609
+ if (counts(from)) { const pk = umKg(fromUnitMass); if (pk == null) return null; kg = v * pk; }
2610
+ else kg = convertQuantity(v, from, 'kg', formula);
2611
+ if (kg == null) return null;
2612
+ if (counts(to)) { const pk = umKg(batch.unitMass); return pk != null ? kg / pk : null; }
2613
+ return convertQuantity(kg, 'kg', to, formula);
2614
+ }
2615
+
2537
2616
  function convertQuantityAtDensity(value, fromUnit, toUnit, dens) {
2538
2617
  const v = parseFloat(value);
2539
2618
  if (!isFinite(v)) return null;
@@ -2649,6 +2728,7 @@ function goToDisplayCurrencySetting() {
2649
2728
  // total is null only when there's neither an override nor a computable cost.
2650
2729
  function entityEffectiveCost(qty, unit, formula, override, overrideCcy, note) {
2651
2730
  const { computed, ccy } = quantityCost(qty, unit, formula);
2731
+ if (typeof flCostHidden === 'function' && flCostHidden()) return { total: null, computed: null, currency: ccy, overridden: false, note: '', driftPct: null, hidden: true }; // 0267: not the override either
2652
2732
  const ovRaw = (override != null && override !== '' && isFinite(parseFloat(override))) ? parseFloat(override) : null;
2653
2733
  const ovCcy = overrideCcy || ccy;
2654
2734
  let ov = ovRaw;
@@ -2678,6 +2758,7 @@ const COST_DRIFT_PCT = 10;
2678
2758
  // unpriceable. `label` names the value in the non-override tooltip.
2679
2759
  function entityCostCellHtml(summary, label) {
2680
2760
  const lbl = label || 'Cost';
2761
+ if (typeof flCostHidden === 'function' && flCostHidden()) return '<span style="color:var(--dk-faint, #94a3b8)">—</span>'; // 0267
2681
2762
  if (!summary || summary.total == null) {
2682
2763
  return `<span title="${esc(lbl)}, not priced (no ingredient prices, or a volume amount with no density)" style="color:var(--dk-faint, #94a3b8)">—</span>`;
2683
2764
  }
@@ -2703,6 +2784,7 @@ function entityCostCellHtml(summary, label) {
2703
2784
  // set — the override + a divergence warning vs the live computed value.
2704
2785
  // o = { kind:'sample'|'batch', id, qty, unit, formula, override }.
2705
2786
  function entityCostValueHtml(o) {
2787
+ if (typeof flCostHidden === 'function' && flCostHidden()) return '<span style="color:var(--dk-faint, #94a3b8)">—</span>'; // 0267: cost hidden from Viewers
2706
2788
  const { perKg, computed, ccy, convertible } = quantityCost(o.qty, o.unit, o.formula);
2707
2789
  const money = v => (typeof formatMoney === 'function') ? formatMoney(v, ccy) : (ccy + ' ' + (+v).toFixed(2));
2708
2790
  const ovRaw = (o.override != null && o.override !== '' && isFinite(parseFloat(o.override))) ? parseFloat(o.override) : null;
package/vendor/nesting.js CHANGED
@@ -243,16 +243,20 @@ function _idealMixDensity(formulation) {
243
243
  if (!formulation) return null;
244
244
  const flat = _flattenComposition(formulation);
245
245
  if (!flat.rows.length) return null;
246
- let invSum = 0;
246
+ let invSum = 0, pieceW = 0;
247
247
  for (const r of flat.rows) {
248
248
  if (r._weight <= 0) continue;
249
249
  const ing = db.ingredients.find(i => i.id === r.ingredientId);
250
250
  if (!ing) return null;
251
251
  const d = (typeof _densityToKgPerL === 'function')
252
252
  ? _densityToKgPerL(ing.density, ing.densityUnit) : null;
253
+ // A counted item with no density (a wick: weight per piece only) adds its mass and next to no volume,
254
+ // so a candle's density stays that of its wax. Only while such items stay a small share (2 Dec).
255
+ if (!d && typeof flPieceMassKg === 'function' && flPieceMassKg(ing.unitMass) != null) { pieceW += r._weight; continue; }
253
256
  if (!d) return null;
254
257
  invSum += r._weight / d;
255
258
  }
259
+ if (pieceW > 0.05) return null;
256
260
  return invSum > 0 ? 1 / invSum : null;
257
261
  }
258
262
 
@@ -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)