formlab-mcp 0.7.7 → 0.7.9

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.7",
3
+ "version": "0.7.9",
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.7",
5
+ "version": "0.7.9",
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.7",
11
+ "version": "0.7.9",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
@@ -36,7 +36,14 @@ 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
- return null;
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
+ return pk ? +(v / pk).toFixed(6) : null;
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%']);
43
+ function _pieceKg(i) {
44
+ const m = i && i.unitMass; const v = m ? Number(m.value) : NaN;
45
+ const f = m ? _MASS_TO_KG[String(m.unit || '').toLowerCase()] : null;
46
+ return isFinite(v) && v > 0 && f ? v * f : null;
40
47
  }
41
48
 
42
49
  function _trimIngredient(i) {
@@ -60,6 +67,8 @@ function _trimIngredient(i) {
60
67
  purity: i.purity != null && i.purity !== '' ? Number(i.purity) : null,
61
68
  density: i.density != null ? i.density : null,
62
69
  densityUnit: i.densityUnit || (i.density != null ? 'kg/L' : null),
70
+ // What one piece weighs (a wick): a recipe row counted in pieces converts through it (0.7.8).
71
+ ...(_pieceKg(i) ? { weightPerPiece: { value: Number(i.unitMass.value), unit: i.unitMass.unit } } : {}),
63
72
  cost: (cost && cost.value != null && cost.value !== '')
64
73
  ? { value: cost.value, currency: cost.currency || 'USD', unit: cost.unit || 'kg' } : null,
65
74
  costPerKg: _costPerKg(i),
package/vendor/cost.js CHANGED
@@ -170,7 +170,28 @@ function ensureUnitDatalists() {
170
170
  function getQuantityUnits() {
171
171
  const customCount = Object.entries((typeof db !== 'undefined' && db?.customUnits) || {})
172
172
  .filter(([_, v]) => v?.dimension === 'count').map(([k]) => k);
173
- return [...new Set([...Object.keys(getMassUnits()), ...Object.keys(getVolUnits()), 'units', 'each', ...customCount])];
173
+ return [...new Set([...Object.keys(getMassUnits()), ...Object.keys(getVolUnits()), 'units', 'each', ...customCount, ..._usedCountUnits(), ...FL_COUNT_UNITS_COMMON])];
174
+ }
175
+ // Everyday count units for finished goods, offered before anyone uses them (Jun, 2 Dec: "and remember pill?").
176
+ // Each one gets a Mass per unit on the batch or sample so cost and yield still work.
177
+ const FL_COUNT_UNITS_COMMON = ['piece', 'pill', 'tablet', 'capsule', 'softgel', 'gummy', 'lozenge', 'sachet', 'stick',
178
+ 'bar', 'candle', 'cookie', 'bottle', 'jar', 'tube', 'can', 'vial', 'ampoule', 'pouch', 'bag', 'box', 'pack', 'kit',
179
+ // Lab and R&D pieces (Jun, 2 Dec: "bottle? cell? etc"): test cells, coated panels, pressed pellets, specimens.
180
+ 'cell', 'wafer', 'panel', 'coupon', 'plate', 'slide', 'disc', 'pellet', 'sheet', 'roll', 'swatch', 'specimen', 'cartridge', 'pod'];
181
+ // Count units already used on batches and samples beyond the common ones (Jun, 2 Dec), most used first, so the
182
+ // list offers them next time. A unit differing only in case from one already listed is left out.
183
+ function _usedCountUnits() {
184
+ if (typeof db === 'undefined' || !db) return [];
185
+ const known = new Set([...Object.keys(getMassUnits()), ...Object.keys(getVolUnits()), 'units', 'each', ...FL_COUNT_UNITS_COMMON].map(u => u.toLowerCase()));
186
+ const n = new Map();
187
+ [...(db.batches || []), ...(db.samples || [])].forEach(r => {
188
+ const u = String((r && r.unit) || '').trim();
189
+ if (!u || u.length > 24 || known.has(u.toLowerCase()) || isMassUnit(u) || isVolUnit(u)) return;
190
+ n.set(u, (n.get(u) || 0) + 1);
191
+ });
192
+ const seen = new Set();
193
+ return [...n.entries()].sort((x, y) => y[1] - x[1]).map(([u]) => u)
194
+ .filter(u => { const k = u.toLowerCase(); if (seen.has(k)) return false; seen.add(k); return true; }).slice(0, 30);
174
195
  }
175
196
 
176
197
  // ============================================================
@@ -204,7 +225,13 @@ function getQuantityUnits() {
204
225
  }
205
226
  function isOpen() { var p = document.getElementById(POP_ID); return !!(p && p.style.display !== 'none'); }
206
227
  function optionsFor(input) {
207
- var dl = document.getElementById(input.getAttribute('data-unit-list') || '');
228
+ var id = input.getAttribute('data-unit-list') || '';
229
+ // The amount-made list is read live: a count unit saved a moment ago (candle) shows the next time it opens.
230
+ if (id === 'fl-units-qty' && typeof getQuantityUnits === 'function') {
231
+ countUnits = FL_COUNT_UNITS_COMMON.concat(_usedCountUnits()); // filed under Amount / count, not Other
232
+ return unitsCommonFirst(getQuantityUnits());
233
+ }
234
+ var dl = document.getElementById(id);
208
235
  return dl ? Array.prototype.map.call(dl.children, function (o) { return o.value; }) : [];
209
236
  }
210
237
  function listEl() { var p = document.getElementById(POP_ID); return p ? p.querySelector('.fl-unit-combo-list') : null; }
@@ -213,12 +240,13 @@ function getQuantityUnits() {
213
240
  // Classify a unit into a display group. Mirrors the formula picker's grouping
214
241
  // (Mass / Volume / Length …) and uses the same isMassUnit/isVolUnit helpers
215
242
  // so custom units land in the right bucket too.
243
+ var countUnits = []; // the amount-made list's count units, refreshed each time that list opens
216
244
  function classify(u) {
217
245
  if (['wt%', 'vol%', '%', 'ppm', 'ppb'].indexOf(u) !== -1) return 'frac';
218
246
  if (typeof isMassUnit === 'function' && isMassUnit(u)) return 'mass';
219
247
  if (typeof isVolUnit === 'function' && isVolUnit(u)) return 'vol';
220
248
  if (typeof isLengthUnit === 'function' && isLengthUnit(u)) return 'len';
221
- if (['mol', 'eq', 'each', 'pcs', 'unit', 'units'].indexOf(u) !== -1) return 'amt';
249
+ if (['mol', 'eq', 'each', 'pcs', 'unit', 'units'].indexOf(u) !== -1 || countUnits.indexOf(u) !== -1) return 'amt';
222
250
  return 'other';
223
251
  }
224
252
  var GROUP_ORDER = [['frac', 'Fraction'], ['mass', 'Mass'], ['vol', 'Volume'], ['len', 'Length'], ['amt', 'Amount / count'], ['other', 'Other']];
@@ -762,6 +790,13 @@ function amountConversions(amount, unit, ingredient, opts) {
762
790
  } else {
763
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.`;
764
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.';
765
800
  } else {
766
801
  res.note = 'No unit conversions available for this unit.';
767
802
  }
@@ -783,13 +818,49 @@ function _densityToKgPerL(value, unit) {
783
818
 
784
819
  // Convert an ing.cost to $/kg in the cost's own currency.
785
820
  // Returns null if conversion isn't possible (no density for vol→mass).
786
- function costPerKgInOwnCurrency(cost, density, densityUnit) {
821
+ // An ingredient's weight per piece (a wick, a jar, a label) in kg, from ing.unitMass {value, unit}; null when unset
822
+ // (Jun, 2 Dec: "Build it properly"). Pieces are any unit that isn't a mass, volume, length or a percent.
823
+ function flPieceMassKg(unitMass) {
824
+ const v = unitMass ? parseFloat(unitMass.value) : NaN;
825
+ return (isFinite(v) && v > 0 && unitMass.unit in MASS_TO_KG) ? v * MASS_TO_KG[unitMass.unit] : null;
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
+ }
835
+ function flIsPieceUnit(u) {
836
+ const raw = String(u || '').trim(), lower = raw.toLowerCase();
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;
840
+ const _cu = (typeof db !== 'undefined' && db && db.customUnits && Object.prototype.hasOwnProperty.call(db.customUnits, raw)) ? db.customUnits[raw] : null;
841
+ if (_cu) return _cu.dimension === 'count'; // a custom count unit ("wick") is a piece; other custom units convert by their own rule
842
+ const hit = t => Object.keys(t).some(k => k === raw || k.toLowerCase() === lower);
843
+ return !hit(MASS_TO_KG) && !hit(VOL_TO_L) && !(typeof LENGTH_TO_M !== 'undefined' && hit(LENGTH_TO_M));
844
+ }
845
+ // A recipe row counted in pieces ("1 wick"), as kg through its ingredient's weight per piece. Null for any other row,
846
+ // or a piece row whose ingredient has no weight per piece (it stays unpriced and unscaled, as before).
847
+ function flPieceRowKg(c) {
848
+ if (!c || !c.ingredientId || !flIsPieceUnit(c.unit)) return null;
849
+ const amt = parseFloat(c.amount);
850
+ if (!isFinite(amt) || amt < 0) return null;
851
+ const ing = (typeof flFindById === 'function') ? flFindById('ingredients', c.ingredientId) : (db.ingredients || []).find(i => i.id === c.ingredientId);
852
+ const per = ing ? flPieceMassKg(ing.unitMass) : null;
853
+ return per == null ? null : amt * per;
854
+ }
855
+ function costPerKgInOwnCurrency(cost, density, densityUnit, unitMass) {
787
856
  if (!cost || cost.value == null || cost.value === '') return null;
788
857
  const v = parseFloat(cost.value);
789
858
  if (!isFinite(v)) return null;
790
859
  const u = cost.unit || 'kg';
791
860
 
792
861
  if (u in MASS_TO_KG) return v / MASS_TO_KG[u];
862
+ // A price per piece ($0.12 per wick) through the weight per piece.
863
+ if (flIsPieceUnit(u)) { const per = flPieceMassKg(unitMass); return per ? v / per : null; }
793
864
 
794
865
  if (u in VOL_TO_L) {
795
866
  const d = _densityToKgPerL(density, densityUnit);
@@ -1113,10 +1184,13 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1113
1184
  return raw;
1114
1185
  };
1115
1186
 
1116
- const kinds = comp.map(c => classifyUnit(c.unit));
1187
+ // 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));
1117
1189
  const allWt = comp.length && kinds.every(k => k === 'wt-frac');
1118
1190
  const allVol = comp.length && kinds.every(k => k === 'vol-frac');
1119
- const allAbs = comp.length && kinds.every(k => k === 'mass-abs' || k === 'vol-abs');
1191
+ // 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
+ 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
+ && kinds.some(k => k === 'mass-abs' || k === 'vol-abs');
1120
1194
  const basis = allVol ? 'vol' : (allAbs ? 'abs' : 'wt');
1121
1195
 
1122
1196
  // === Vol-% recipe: derive formulation density from per-row densities ===
@@ -1162,8 +1236,9 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1162
1236
  d = _densityToKgPerL(ing.density, ing.densityUnit);
1163
1237
  }
1164
1238
  if (!isFinite(amt) || flBadAmount(c.amount, c.unit)) continue;
1165
- if (u in MASS_TO_KG) {
1166
- const m = amt * MASS_TO_KG[u];
1239
+ const _pk = flPieceRowKg(c);
1240
+ if (_pk != null || u in MASS_TO_KG) {
1241
+ const m = _pk != null ? _pk : amt * MASS_TO_KG[u];
1167
1242
  massKgPerRow.set(c, m);
1168
1243
  totalMassKg += m;
1169
1244
  if (d) { const v = m / d; volLPerRow.set(c, v); totalVolL += v; }
@@ -1191,8 +1266,10 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1191
1266
 
1192
1267
  const tryAutoPrice = (ing, c, unit, amount, kind) => {
1193
1268
  if (!ing.cost || ing.cost.value == null || ing.cost.value === '') return { ok: false, reason: 'no cost on file' };
1194
- const perKgOwn = costPerKgInOwnCurrency(ing.cost, ing.density, ing.densityUnit);
1195
- if (perKgOwn == null) return { ok: false, reason: 'could not convert price unit (needs density?)' };
1269
+ const perKgOwn = costPerKgInOwnCurrency(ing.cost, ing.density, ing.densityUnit, ing.unitMass);
1270
+ if (perKgOwn == null) return { ok: false, reason: FL_PACK_UNITS.has(String(ing.cost.unit || '').trim().toLowerCase())
1271
+ ? `price is per ${String(ing.cost.unit).trim()}: enter it per piece (with a weight per piece) or per kg`
1272
+ : 'could not convert price unit (needs density?)' };
1196
1273
  const perKgDisplay = convertCurrencySync(perKgOwn, ing.cost.currency || 'USD', displayCcy);
1197
1274
  if (perKgDisplay == null) return { ok: false, reason: 'unknown currency rate' };
1198
1275
 
@@ -1288,9 +1365,9 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1288
1365
  if (flBadAmount(c.amount, c.unit)) { missing.push({ reason: `bad amount (${flBadAmount(c.amount, c.unit)})`, ingredient: ing }); continue; }
1289
1366
  if (!isFinite(amount)) { missing.push({ reason: 'no amount', ingredient: ing }); continue; }
1290
1367
 
1291
- const kind = classifyUnit(unit);
1368
+ const kind = flPieceRowKg(c) != null ? 'mass-abs' : classifyUnit(unit);
1292
1369
  if (kind === 'unknown') {
1293
- missing.push({ reason: `unsupported composition unit "${c.unit}"`, ingredient: ing });
1370
+ 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 });
1294
1371
  continue;
1295
1372
  }
1296
1373
 
@@ -1490,9 +1567,11 @@ function computeCompositionFractions(formulation) {
1490
1567
  if (u.startsWith('wt') || u === '%') { out.kind = 'wt-frac'; return out; }
1491
1568
  if (u.startsWith('vol')) { out.kind = 'vol-frac'; return out; }
1492
1569
  const cu = canonUnit(rawU);
1493
- if (cu in MASS_TO_KG) {
1570
+ const _pk = flPieceRowKg(c);
1571
+ if (_pk != null || cu in MASS_TO_KG) {
1494
1572
  out.kind = 'mass-abs';
1495
- out.massKg = amount * MASS_TO_KG[cu];
1573
+ out.massKg = _pk != null ? _pk : amount * MASS_TO_KG[cu];
1574
+ if (_pk != null) out.pieces = true;
1496
1575
  out.volL = d ? out.massKg / d : null;
1497
1576
  return out;
1498
1577
  }
@@ -1664,7 +1743,12 @@ function scaleCompositionToBatch(formulation, batchAmount, batchUnit) {
1664
1743
  if (ok) partsSum += vol;
1665
1744
  byRow.set(comp[i], vol);
1666
1745
  });
1667
- return { unit: batchUnit, dim, byRow, anyNull, density: pd, totalMassKg, partsSum };
1746
+ const pieces = new Map();
1747
+ fr.rows.forEach((r, i) => {
1748
+ const c = comp[i], one = r.pieces ? flPieceRowKg(Object.assign({}, c, { amount: 1 })) : null;
1749
+ if (one && r.massFraction != null && isFinite(r.massFraction)) pieces.set(c, flPieceCount((r.massFraction * totalMassKg) / one));
1750
+ });
1751
+ return { unit: batchUnit, dim, byRow, anyNull, density: pd, totalMassKg, partsSum, pieces };
1668
1752
  }
1669
1753
  fr.rows.forEach((r, i) => {
1670
1754
  const frac = dim === 'mass' ? r.massFraction : r.volFraction;
@@ -1673,7 +1757,23 @@ function scaleCompositionToBatch(formulation, batchAmount, batchUnit) {
1673
1757
  byRow.set(comp[i], ok ? frac * amt : null);
1674
1758
  });
1675
1759
  const out = { unit: batchUnit, dim, byRow, anyNull };
1676
- if (dim === 'volume' && pd) { out.density = pd; out.totalMassKg = amt * VOL_TO_L[batchUnit] * pd.kgPerL; out.partsSum = amt; }
1760
+ // Piece rows (wicks) also as a count: their scaled mass over the weight per piece (2 Dec).
1761
+ if (dim === 'mass') {
1762
+ out.pieces = new Map();
1763
+ fr.rows.forEach((r, i) => {
1764
+ const c = comp[i], g = byRow.get(c), one = r.pieces ? flPieceRowKg(Object.assign({}, c, { amount: 1 })) : null;
1765
+ if (one && g != null && isFinite(g)) out.pieces.set(c, flPieceCount((g * MASS_TO_KG[batchUnit]) / one));
1766
+ });
1767
+ }
1768
+ if (dim === 'volume' && pd) {
1769
+ out.density = pd; out.totalMassKg = amt * VOL_TO_L[batchUnit] * pd.kgPerL; out.partsSum = amt;
1770
+ // A wick in a volume batch: no volume to scale, but still a count, from its mass share (2 Dec).
1771
+ out.pieces = new Map();
1772
+ fr.rows.forEach((r, i) => {
1773
+ const c = comp[i], one = r.pieces ? flPieceRowKg(Object.assign({}, c, { amount: 1 })) : null;
1774
+ if (one && r.massFraction != null && isFinite(r.massFraction)) out.pieces.set(c, flPieceCount((r.massFraction * out.totalMassKg) / one));
1775
+ });
1776
+ }
1677
1777
  return out;
1678
1778
  }
1679
1779
 
@@ -1832,6 +1932,8 @@ function sumActualRowsMassKg(rows, formula) {
1832
1932
  if (!isFinite(amt)) continue;
1833
1933
  const u = (c.unit || '').trim();
1834
1934
  if (u in MASS_TO_KG) { kg += amt * MASS_TO_KG[u]; n++; continue; }
1935
+ const _pk = flPieceRowKg(c); // 12 wicks, by their weight per piece (2 Dec)
1936
+ if (_pk != null) { kg += _pk; n++; continue; }
1835
1937
  if (u in VOL_TO_L) {
1836
1938
  let d = null;
1837
1939
  if (c.ingredientId) {
@@ -1914,6 +2016,11 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
1914
2016
  const fmt = n => (n == null || !isFinite(n)) ? '—' : _woDp(n);
1915
2017
  const sgn = n => (n == null || !isFinite(n)) ? '—' : (n > 0 ? '+' : '') + _woDp(n);
1916
2018
  if (!w || !w.available) {
2019
+ // A count unit (candle, tablet) needs its weight, not a different unit (2 Dec: the note told a 1-candle sample to
2020
+ // switch to g, when Mass per unit is the fix).
2021
+ const _wu = w ? String(w.unit || '').trim() : '';
2022
+ if (w && w.reason === 'bad-unit' && _wu && ['%', 'wt%', 'vol%', 'ppm', 'ppb'].indexOf(_wu) === -1 && !(typeof isMassUnit === 'function' && isMassUnit(_wu)) && !(typeof isVolUnit === 'function' && isVolUnit(_wu)))
2023
+ return `<div style="padding:8px 11px;margin-bottom:12px;background:var(--dk-amber-bg, #fffbeb);border:1px solid var(--dk-amber-line, #fde68a);border-radius:6px;color:var(--dk-amber-fg, #92400e);font-size:12px"><span class="fl-warn" aria-hidden="true"></span> Set a <strong>Mass per unit</strong> (how much one ${esc(_wu)} weighs) to get a weigh-out sheet.</div>`;
1917
2024
  if (w && w.reason === 'bad-unit')
1918
2025
  return `<div style="padding:8px 11px;margin-bottom:12px;background:var(--dk-amber-bg, #fffbeb);border:1px solid var(--dk-amber-line, #fde68a);border-radius:6px;color:var(--dk-amber-fg, #92400e);font-size:12px"><span class="fl-warn" aria-hidden="true"></span> Set the ${noun} quantity in a <strong>mass or volume unit</strong> (g, kg, mL, L…) to get a weigh-out sheet — currently <strong>${esc(w.unit || '—')}</strong>.</div>`;
1919
2026
  if (w && w.reason === 'no-qty')
@@ -1987,6 +2094,11 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
1987
2094
  const toUnit = (amt, from, key) => {
1988
2095
  if (amt == null || !isFinite(amt)) return null;
1989
2096
  if (!from || from === w.unit) return amt;
2097
+ // Wicks logged as "12 piece": through the ingredient's weight per piece into the sheet's mass unit (2 Dec).
2098
+ if (typeof key === 'string' && key.slice(0, 2) === 'i:' && flIsPieceUnit(from) && w.unit in MASS_TO_KG) {
2099
+ const kg = flPieceRowKg({ ingredientId: key.slice(2), amount: amt, unit: from });
2100
+ return kg == null ? null : kg / MASS_TO_KG[w.unit];
2101
+ }
1990
2102
  if (typeof convertQuantityAtDensity !== 'function') return null;
1991
2103
  const v = convertQuantityAtDensity(amt, from, w.unit, rowDensityKgPerL(key));
1992
2104
  return (v == null || !isFinite(v)) ? null : v;
@@ -1999,7 +2111,7 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
1999
2111
  if (a) { actInUnit = toUnit(a.amount, a.unit, r.key); if (actInUnit != null) actualTotal += actInUnit; }
2000
2112
  const delta = (hasActuals && planned != null && actInUnit != null) ? (actInUnit - planned) : null;
2001
2113
  const rel = (delta != null && planned > 0) ? Math.abs(delta) / planned : (delta != null && actInUnit > 0 ? 1 : null);
2002
- 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 };
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 || '' };
2003
2115
  });
2004
2116
  // Union in ingredients that were ADDED to the As-prepared table but aren't in
2005
2117
  // the recipe (a spike / colorant / q.s. carrier). Without this the weigh-out
@@ -2106,7 +2218,7 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
2106
2218
  : `<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>`;
2107
2219
  const body = rows.map((r, i) => `<tr data-wo-key="${esc(r.key)}" style="${hasActuals ? dRowBg(r.rel) : ''}">
2108
2220
  <td style="padding:4px 8px;color:var(--dk-faint, #94a3b8)">${i + 1}</td>
2109
- <td style="padding:4px 8px">${esc(r.name)}${purityWhy(r)}${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>
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>
2110
2222
  <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>
2111
2223
  ${hasActuals ? `<td style="padding:4px 8px;text-align:right;font-variant-numeric:tabular-nums">${
2112
2224
  r.actInUnit != null ? cv(r.actInUnit)
@@ -2419,11 +2531,11 @@ function computeProjectCost(projectId, displayCcy = getDisplayCurrency()) {
2419
2531
  // ============================================================
2420
2532
  function ingredientCostChangePct(ing) {
2421
2533
  if (!ing?.cost?.history?.length) return null;
2422
- const cur = costPerKgInOwnCurrency(ing.cost, ing.density, ing.densityUnit);
2534
+ const cur = costPerKgInOwnCurrency(ing.cost, ing.density, ing.densityUnit, ing.unitMass);
2423
2535
  // Walk back to oldest entry that has a comparable per-kg value
2424
2536
  for (let i = 0; i < ing.cost.history.length; i++) {
2425
2537
  const old = ing.cost.history[i];
2426
- const oldPerKg = costPerKgInOwnCurrency(old, ing.density, ing.densityUnit);
2538
+ const oldPerKg = costPerKgInOwnCurrency(old, ing.density, ing.densityUnit, ing.unitMass);
2427
2539
  // Convert to same currency for fair comparison
2428
2540
  const oldInCurCcy = convertCurrencySync(oldPerKg, old.currency || 'USD', ing.cost.currency || 'USD');
2429
2541
  if (cur != null && oldInCurCcy && oldInCurCcy > 0) {
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
 
@@ -277,6 +281,7 @@ function _rowWtFractionsWithin(f, unresolved) {
277
281
  if (lower.startsWith('vol')) return 'vol';
278
282
  if (typeof MASS_TO_KG !== 'undefined' && u in MASS_TO_KG) return 'mass';
279
283
  if (typeof VOL_TO_L !== 'undefined' && u in VOL_TO_L) return 'volabs';
284
+ if (typeof flPieceRowKg === 'function' && flPieceRowKg(c) != null) return 'piece'; // 1 wick, by its weight (2 Dec)
280
285
  return 'unknown';
281
286
  });
282
287
 
@@ -290,7 +295,7 @@ function _rowWtFractionsWithin(f, unresolved) {
290
295
  // the block or arrived by import. wt% WITH vol% is NOT this case — density
291
296
  // reconciles those, and they resolve through the branches below.
292
297
  const _hasFrac = kinds.some(k => k === 'wt' || k === 'vol');
293
- const _hasAbs = kinds.some(k => k === 'mass' || k === 'volabs');
298
+ const _hasAbs = kinds.some(k => k === 'mass' || k === 'volabs' || k === 'piece');
294
299
  if (_hasFrac && _hasAbs) {
295
300
  unresolved && unresolved.push({ reason: 'mixed-basis', formulationId: f ? f.id : null });
296
301
  return comp.map(_ => 0);
@@ -312,6 +317,7 @@ function _rowWtFractionsWithin(f, unresolved) {
312
317
  const amt = _usableAmount(c, unresolved);
313
318
  if (!amt) return 0;
314
319
  if (kinds[i] === 'mass') return amt * MASS_TO_KG[u];
320
+ if (kinds[i] === 'piece') return flPieceRowKg(c) || 0;
315
321
  if (kinds[i] === 'volabs') {
316
322
  if (c.ingredientId) {
317
323
  const ing = db.ingredients.find(x => x.id === c.ingredientId);