formlab-mcp 0.7.14 → 0.7.16

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.14",
3
+ "version": "0.7.16",
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.14",
5
+ "version": "0.7.16",
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.14",
11
+ "version": "0.7.16",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
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"), 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; a voided one has voided, voidedAt, voidedBy, voidReason, and the shipment coaVoided), 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; a voided one has voided, voidedAt, voidedBy, voidReason, and the shipment coaVoided; a shipment sent a corrected CoA lists the voided ones it replaced in coaReplaced), 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: {
@@ -441,10 +441,14 @@ const get_batch = {
441
441
  stockLedger: (Array.isArray(b.stockLedger) ? b.stockLedger : []).map(e => ({
442
442
  date: e.ts || null, delta: e.delta ?? null, unit: e.unit || b.unit || '', kind: e.kind || '', note: e.note || '',
443
443
  ...(e.customer ? { customer: e.customer } : {}),
444
+ // 29i: a sample piece put back into stock (kind 'return', positive delta), and which sample.
445
+ ...(e.kind === 'return' && e.sampleId ? { returnedFromSample: ((samples || []).find(x => x && x.id === e.sampleId) || {}).uid || e.sampleId, ...(e.sampleQty != null ? { sampleQty: e.sampleQty, sampleUnit: e.sampleUnit || '' } : {}) } : {}),
444
446
  ...(Array.isArray(e.qcOpen) && e.qcOpen.length ? { shippedWithQcOpen: e.qcOpen, qcReason: e.qcReason || null } : {}),
445
447
  // 2 Dec: the CoA it went with (null = none issued), and no ingredient lots recorded. Older shipments carry neither.
446
448
  // 0.7.12: the saved certificate it went with (its number in certificates).
447
- ...(e.kind === 'shipment' && e.coaId ? (() => { const c = (Array.isArray(b.coas) ? b.coas : []).find(x => x && x.id === e.coaId) || {}; return { coaNumber: c.n ?? null, ...(c.voidedAt ? { coaVoided: true } : {}) }; })() : {}),
449
+ ...(e.kind === 'shipment' && e.coaId ? (() => { const c = (Array.isArray(b.coas) ? b.coas : []).find(x => x && x.id === e.coaId) || {}; return { coaNumber: c.n ?? null, ...(c.voidedAt ? { coaVoided: true } : {}),
450
+ // 0.7.15: the certificates this shipment's CoA replaced (voided ones), by number.
451
+ ...(Array.isArray(e.coaReplaced) && e.coaReplaced.length ? { coaReplaced: e.coaReplaced.map(p => ((b.coas || []).find(x => x && x.id === p.id) || {}).n ?? null) } : {}) }; })() : {}),
448
452
  ...(e.kind === 'shipment' && 'coaAt' in e ? { coaIssuedAt: e.coaAt || null, ...(e.coaCustomer ? { coaCustomer: e.coaCustomer } : {}), ...(e.coaPo ? { coaPo: e.coaPo } : {}), noLotsRecorded: !!e.noLots } : {}),
449
453
  })),
450
454
  shippedQty: (Array.isArray(b.stockLedger) ? b.stockLedger : []).reduce((s, e) => e.kind === 'shipment' ? s + Math.abs(parseFloat(e.delta) || 0) : s, 0),
package/vendor/cost.js CHANGED
@@ -194,6 +194,33 @@ function _usedCountUnits() {
194
194
  .filter(u => { const k = u.toLowerCase(); if (seen.has(k)) return false; seen.add(k); return true; }).slice(0, 30);
195
195
  }
196
196
 
197
+ // Unit groups, one place (5 Dec, Jun: "for stock unit, can we put picker choices in groups?"): the unit combobox
198
+ // below and every plain unit <select> (stock, lot, cost "per") file a unit under the same heading.
199
+ const FL_UNIT_GROUPS = [['frac', 'Fraction'], ['mass', 'Mass'], ['vol', 'Volume'], ['len', 'Length'], ['amt', 'Amount / count'], ['other', 'Other']];
200
+ function flUnitGroupOf(u, extraCount) {
201
+ u = String(u || '');
202
+ if (['wt%', 'vol%', '%', 'ppm', 'ppb'].indexOf(u) !== -1) return 'frac';
203
+ if (typeof isMassUnit === 'function' && isMassUnit(u)) return 'mass';
204
+ if (typeof isVolUnit === 'function' && isVolUnit(u)) return 'vol';
205
+ if (typeof isLengthUnit === 'function' && isLengthUnit(u)) return 'len';
206
+ if (['mol', 'eq', 'each', 'pcs', 'unit', 'units'].indexOf(u) !== -1 || (extraCount || []).indexOf(u) !== -1) return 'amt';
207
+ if (typeof FL_COUNT_UNITS_COMMON !== 'undefined' && FL_COUNT_UNITS_COMMON.indexOf(u) !== -1) return 'amt';
208
+ const cu = (typeof db !== 'undefined' && db && db.customUnits && db.customUnits[u]) || null;
209
+ if (cu && cu.dimension === 'count') return 'amt';
210
+ return 'other';
211
+ }
212
+ // <option>s for a unit <select>, in <optgroup>s (Mass, Volume, …). `cur` is selected, and added when the list lacks it
213
+ // (a stock unit of "candle" no longer shows as the list's first unit).
214
+ function flUnitOptionsHtml(units, cur) {
215
+ const e = v => String(v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
216
+ const list = [...new Set((units || []).map(String))];
217
+ if (cur && !list.includes(cur)) list.push(cur);
218
+ const by = {};
219
+ list.forEach(u => { const k = flUnitGroupOf(u); (by[k] = by[k] || []).push(u); });
220
+ return FL_UNIT_GROUPS.filter(g => by[g[0]]).map(g => `<optgroup label="${e(g[1])}">${by[g[0]].map(u =>
221
+ `<option value="${e(u)}"${u === cur ? ' selected' : ''}>${e(u)}</option>`).join('')}</optgroup>`).join('');
222
+ }
223
+
197
224
  // ============================================================
198
225
  // Unit combobox — replaces the native <datalist> popup.
199
226
  // ------------------------------------------------------------
@@ -241,15 +268,8 @@ function _usedCountUnits() {
241
268
  // (Mass / Volume / Length …) and uses the same isMassUnit/isVolUnit helpers
242
269
  // so custom units land in the right bucket too.
243
270
  var countUnits = []; // the amount-made list's count units, refreshed each time that list opens
244
- function classify(u) {
245
- if (['wt%', 'vol%', '%', 'ppm', 'ppb'].indexOf(u) !== -1) return 'frac';
246
- if (typeof isMassUnit === 'function' && isMassUnit(u)) return 'mass';
247
- if (typeof isVolUnit === 'function' && isVolUnit(u)) return 'vol';
248
- if (typeof isLengthUnit === 'function' && isLengthUnit(u)) return 'len';
249
- if (['mol', 'eq', 'each', 'pcs', 'unit', 'units'].indexOf(u) !== -1 || countUnits.indexOf(u) !== -1) return 'amt';
250
- return 'other';
251
- }
252
- var GROUP_ORDER = [['frac', 'Fraction'], ['mass', 'Mass'], ['vol', 'Volume'], ['len', 'Length'], ['amt', 'Amount / count'], ['other', 'Other']];
271
+ function classify(u) { return flUnitGroupOf(u, countUnits); } // shared with the unit <select>s (5 Dec)
272
+ var GROUP_ORDER = FL_UNIT_GROUPS;
253
273
  function groupUnits(units) {
254
274
  var by = {};
255
275
  units.forEach(function (u) { var k = classify(u); (by[k] = by[k] || []).push(u); });
@@ -842,6 +862,14 @@ function flIsPieceUnit(u) {
842
862
  const hit = t => Object.keys(t).some(k => k === raw || k.toLowerCase() === lower);
843
863
  return !hit(MASS_TO_KG) && !hit(VOL_TO_L) && !(typeof LENGTH_TO_M !== 'undefined' && hit(LENGTH_TO_M));
844
864
  }
865
+ // The word for one piece in "Weight per …" (5 Dec, Jun: "is per piece better or per unit better because piece itself is
866
+ // a unit"): the stock unit when it is one item (jar, wick, candle), else "piece". A pack (box, bag) holds many pieces and
867
+ // "each" / "unit" say nothing, so those read "piece"; so do mass and volume units.
868
+ function flPieceNoun(stockUnit) {
869
+ const u = String(stockUnit || '').trim();
870
+ if (!u || u.length > 24 || ['each', 'piece', 'pieces', 'pc', 'pcs', 'unit', 'units', 'ea'].includes(u.toLowerCase())) return 'piece';
871
+ return flIsPieceUnit(u) ? u : 'piece';
872
+ }
845
873
  // 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
874
  // 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
875
  // 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
@@ -873,6 +901,31 @@ function flProductUnits(f, batchKg, count) {
873
901
  }
874
902
  return 1;
875
903
  }
904
+ // Parts Not mixed in that sit inside sub-formulas (a gift set of two candles: two wicks), for fKg of formula f: each
905
+ // sub-formula's share of f by mass, over the weight of one of its pieces, × its counted rows; and on down (12-04). f's
906
+ // own counted rows are the caller's (flCountedAside). → { draws: [{ ingredientId, pieces, row, sub }], unresolved:
907
+ // [{ formulationId, name }] } — unresolved: a sub-formula with counted parts but no weight for one piece (no fill).
908
+ function flNestedCounted(f, fKg, _depth, _out, _path) {
909
+ const out = _out || { draws: [], unresolved: [] };
910
+ const depth = _depth || 0, path = _path || [f && f.id];
911
+ if (!f || !(fKg > 0) || depth > 6 || typeof _rowWtFractionsWithin !== 'function') return out;
912
+ const comp = (Array.isArray(f.composition) ? f.composition : []).filter(c => c && (c.ingredientId || c.formulationId));
913
+ const fr = _rowWtFractionsWithin(f, []);
914
+ comp.forEach((c, i) => {
915
+ if (!c.formulationId || c.ingredientId || !(fr[i] > 0) || path.includes(c.formulationId)) return;
916
+ const sub = (typeof flFindById === 'function') ? flFindById('formulations', c.formulationId) : (db.formulations || []).find(x => x.id === c.formulationId);
917
+ if (!sub || sub.deleted) return;
918
+ const subKg = fKg * fr[i];
919
+ const aside = flCountedAside(sub.composition || []);
920
+ if (aside.size) {
921
+ const g = flOnePieceGrams(sub);
922
+ if (!(g > 0)) out.unresolved.push({ formulationId: sub.id, name: sub.name || sub.uid || 'sub-formula' });
923
+ else aside.forEach(r => out.draws.push({ ingredientId: r.ingredientId, pieces: parseFloat(r.amount) * subKg / (g / 1000), row: r, sub }));
924
+ }
925
+ flNestedCounted(sub, subKg, depth + 1, out, path.concat(sub.id));
926
+ });
927
+ return out;
928
+ }
876
929
  // 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
930
  // mix (27f). All rows marked (a kit) keeps them all.
878
931
  function flMixRows(comp) {
@@ -898,8 +951,21 @@ function flOnePieceGrams(f) {
898
951
  }
899
952
  // A recipe row counted in pieces ("1 wick"), as kg through its ingredient's weight per piece. Null for any other row,
900
953
  // or a piece row whose ingredient has no weight per piece (it stays unpriced and unscaled, as before).
954
+ // A sub-formula row counted in pieces (2 candles in a gift set, 12 dough balls) weighs its sub-formula's one piece
955
+ // (flOnePieceGrams: the fill, or a recipe written by weight); null when that isn't known, or in a loop (12-04).
956
+ const _flPieceSubStack = new Set();
901
957
  function flPieceRowKg(c) {
902
- if (!c || !c.ingredientId || !flIsPieceUnit(c.unit)) return null;
958
+ if (!c || !flIsPieceUnit(c.unit)) return null;
959
+ if (c.formulationId && !c.ingredientId) {
960
+ const amt = parseFloat(c.amount);
961
+ if (!isFinite(amt) || amt < 0 || _flPieceSubStack.has(c.formulationId)) return null;
962
+ const sub = (typeof flFindById === 'function') ? flFindById('formulations', c.formulationId) : (db.formulations || []).find(f => f.id === c.formulationId);
963
+ if (!sub || sub.deleted || typeof flOnePieceGrams !== 'function') return null;
964
+ _flPieceSubStack.add(c.formulationId);
965
+ try { const g = flOnePieceGrams(sub); return (g != null && isFinite(g) && g > 0) ? amt * g / 1000 : null; }
966
+ finally { _flPieceSubStack.delete(c.formulationId); }
967
+ }
968
+ if (!c.ingredientId) return null;
903
969
  const amt = parseFloat(c.amount);
904
970
  if (!isFinite(amt) || amt < 0) return null;
905
971
  const ing = (typeof flFindById === 'function') ? flFindById('ingredients', c.ingredientId) : (db.ingredients || []).find(i => i.id === c.ingredientId);
@@ -1202,12 +1268,24 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1202
1268
  if (_seen.has(subF.id)) { missing.push({ reason: 'cycle detected', row: c }); continue; }
1203
1269
  const subRes = computeFormulationCost(subF, displayCcy, 'kg', _seen);
1204
1270
  const subDensity = (typeof _rolledUpDensity === 'function') ? _rolledUpDensity(subF) : null;
1271
+ // Its parts Not mixed in (a candle's wick) are priced per piece of it, outside its per-kg cost. Inside a parent
1272
+ // they go by mass: per piece ÷ the weight of one piece, so a gift set of two candles pays for two wicks (12-04).
1273
+ const subMissing = (subRes.missing || []).slice();
1274
+ let countedPerKg = 0;
1275
+ if (flCountedAside(subF.composition || []).size) {
1276
+ const g = typeof flOnePieceGrams === 'function' ? flOnePieceGrams(subF) : null;
1277
+ (subRes.countedUnpriced || []).forEach(ing => subMissing.push({ reason: 'no price per piece (counted per piece)', ingredient: ing }));
1278
+ if (!(g > 0)) subMissing.push({ reason: 'set a fill to count its parts per piece', subFormula: subF });
1279
+ else if (subRes.countedPerPiece != null) countedPerKg = subRes.countedPerPiece / (g / 1000);
1280
+ }
1281
+ const perKgAll = (subRes.perKg != null && isFinite(subRes.perKg)) ? subRes.perKg + countedPerKg : subRes.perKg;
1205
1282
  subResolve.set(c, {
1206
1283
  subFormula: subF,
1207
- perKgDisplay: subRes.perKg, // $/kg in displayCcy
1208
- perKgOwn: subRes.perKg, // already converted
1284
+ perKgDisplay: perKgAll, // $/kg in displayCcy, its counted parts included
1285
+ perKgOwn: perKgAll, // already converted
1286
+ countedPerKg, // of which its parts per piece
1209
1287
  density: subDensity, // kg/L, may be null
1210
- missing: subRes.missing || [],
1288
+ missing: subMissing,
1211
1289
  basisOk: subRes.basisOk,
1212
1290
  });
1213
1291
  }
@@ -1333,7 +1411,7 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1333
1411
  // 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
1412
  // the count, or a price per kg (or L) through the weight per piece. Null when it can't be priced (3 Dec).
1335
1413
  let countedPerPiece = 0;
1336
- const countedUnpriced = [];
1414
+ const countedUnpriced = [], countedRows = []; // countedRows: each counted row's cost per piece of product (the split, 12-04)
1337
1415
  const _countedRowCost = (ing, c) => {
1338
1416
  if (!ing.cost || ing.cost.value == null || ing.cost.value === '') return null;
1339
1417
  const v = parseFloat(ing.cost.value), n = parseFloat(c.amount);
@@ -1385,8 +1463,8 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1385
1463
  const amount = parseFloat(c.amount);
1386
1464
  if (flBadAmount(c.amount, c.unit)) { missing.push({ reason: `bad amount (${flBadAmount(c.amount, c.unit)})`, subFormula: sub.subFormula }); continue; }
1387
1465
  if (!isFinite(amount)) { missing.push({ reason: 'no amount', subFormula: sub.subFormula }); continue; }
1388
- const kind = classifyUnit((c.unit || 'wt%').toLowerCase());
1389
- if (kind === 'unknown') { missing.push({ reason: `unsupported composition unit "${c.unit}"`, subFormula: sub.subFormula }); continue; }
1466
+ const kind = flPieceRowKg(c) != null ? 'mass-abs' : classifyUnit((c.unit || 'wt%').toLowerCase());
1467
+ if (kind === 'unknown') { missing.push({ reason: flIsPieceUnit(c.unit) ? `set a fill (or a recipe by weight) on ${sub.subFormula.name || 'the sub-formula'} to cost "${c.unit}"` : `unsupported composition unit "${c.unit}"`, subFormula: sub.subFormula }); continue; }
1390
1468
  const perKgDisplay = sub.perKgDisplay;
1391
1469
  let contribution = null;
1392
1470
  if (kind === 'wt-frac') {
@@ -1413,7 +1491,7 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1413
1491
  }
1414
1492
  totalPerKg += contribution;
1415
1493
  totalPct += amount;
1416
- breakdown.push({
1494
+ breakdown.push({ row: c,
1417
1495
  subFormula: sub.subFormula, ingredient: null,
1418
1496
  amount, unit: c.unit || 'wt%',
1419
1497
  perKgOwn: sub.perKgOwn, perKgDisplay,
@@ -1446,7 +1524,7 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1446
1524
 
1447
1525
  if (_aside.has(c)) { // counted beside a % recipe: outside the per-kg cost (flCountedAside); priced per piece of product
1448
1526
  const cc = _countedRowCost(ing, c);
1449
- if (cc == null) countedUnpriced.push(ing); else countedPerPiece += cc;
1527
+ if (cc == null) countedUnpriced.push(ing); else { countedPerPiece += cc; countedRows.push({ row: c, ingredient: ing, perPiece: cc }); }
1450
1528
  continue;
1451
1529
  }
1452
1530
  const kind = flPieceRowKg(c) != null ? 'mass-abs' : classifyUnit(unit);
@@ -1459,7 +1537,7 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1459
1537
  if (auto.ok) {
1460
1538
  totalPerKg += auto.contribution;
1461
1539
  totalPct += amount;
1462
- breakdown.push({
1540
+ breakdown.push({ row: c,
1463
1541
  ingredient: ing, amount, unit: c.unit || 'wt%',
1464
1542
  perKgOwn: auto.perKgOwn, perKgDisplay: auto.perKgDisplay,
1465
1543
  contribution: auto.contribution,
@@ -1487,7 +1565,7 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1487
1565
  }
1488
1566
  }
1489
1567
  const stale = perBasisContribution == null;
1490
- breakdown.push({
1568
+ breakdown.push({ row: c,
1491
1569
  ingredient: ing, amount, unit: c.unit || 'wt%',
1492
1570
  perKgOwn: null, perKgDisplay: null,
1493
1571
  contribution: stale ? 0 : perBasisContribution,
@@ -1585,6 +1663,7 @@ function computeFormulationCost(formulation, displayCcy, basisUnit, _seen) {
1585
1663
  // when there are none, or one of them has no usable price (countedUnpriced names it).
1586
1664
  countedPerPiece: _aside.size && !countedUnpriced.length ? countedPerPiece : null,
1587
1665
  countedUnpriced,
1666
+ countedRows,
1588
1667
  };
1589
1668
  }
1590
1669
 
@@ -2548,13 +2627,16 @@ function computeBatchCost(batch, displayCcy = getDisplayCurrency()) {
2548
2627
  const sizeKg = quantityToKg(batch.targetQuantity, batch.unit, f, _umk);
2549
2628
  // Parts counted per piece (1 wick per candle) × the pieces the batch makes (3 Dec).
2550
2629
  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;
2630
+ const _pieces = perKg.countedPerPiece ? flProductUnits(f, sizeKg, _isCount ? batch.targetQuantity : null) : 0;
2631
+ const countedCost = perKg.countedPerPiece ? perKg.countedPerPiece * _pieces : 0;
2632
+ const _money = v => (typeof formatMoney === 'function') ? formatMoney(v, displayCcy) : String(v);
2552
2633
  return {
2553
2634
  formulation: f,
2554
2635
  perKg: perKg.perKg,
2555
2636
  sizeKg,
2556
2637
  total: sizeKg != null ? perKg.perKg * sizeKg + countedCost : null,
2557
2638
  counted: countedCost || null,
2639
+ countedText: countedCost ? flCountedPartsText(perKg, _pieces, countedCost, _money) : null, // "12 × $3,200.00 MacPro Book 2026"
2558
2640
  currency: displayCcy,
2559
2641
  missing: perKg.missing.concat((perKg.countedUnpriced || []).map(ing => ({ reason: 'no cost on file (counted per piece)', ingredient: ing }))),
2560
2642
  };
@@ -2788,21 +2870,37 @@ function quantityToKg(qty, unit, formula, unitMassKg) {
2788
2870
  }
2789
2871
 
2790
2872
  // Returns { perKg, kg, computed, ccy, convertible } in the display currency.
2873
+ // The counted parts spelled out (Jun, 5 Dec: "$38,400.00 counted parts" hid 12 × $3,200): "12 × $3,200.00 MacPro
2874
+ // Book 2026". Null when the rows don't add up to the counted cost (a sub-formula's own parts), so callers keep the sum.
2875
+ function flCountedPartsText(cost, pieces, counted, money) {
2876
+ const rows = cost && cost.countedRows;
2877
+ if (!rows || !rows.length || !(pieces > 0) || !(counted > 0)) return null;
2878
+ const items = rows.map(r => {
2879
+ const n = parseFloat(r.row && r.row.amount) || 1;
2880
+ const name = (r.ingredient && r.ingredient.name) || 'part';
2881
+ return { cost: r.perPiece * pieces, text: `${+(n * pieces).toFixed(3)} × ${money(r.perPiece / n)} ${name}` };
2882
+ });
2883
+ const sum = items.reduce((a, x) => a + x.cost, 0);
2884
+ if (!isFinite(sum) || Math.abs(sum - counted) > Math.max(0.01, counted * 1e-6)) return null;
2885
+ return items.length <= 2 ? items.map(x => x.text).join(' + ')
2886
+ : `${items[0].text} + ${items.length - 1} more parts (${money(sum - items[0].cost)})`;
2887
+ }
2791
2888
  function quantityCost(qty, unit, formula, displayCcy) {
2792
2889
  const ccy = displayCcy ||
2793
2890
  (typeof getDisplayCurrency === 'function' ? getDisplayCurrency() : null) ||
2794
2891
  (formula && formula.costCurrency) || 'USD';
2795
- let perKg = null, perPiece = null;
2892
+ let perKg = null, perPiece = null, c = null;
2796
2893
  try {
2797
- const c = formula && typeof computeFormulationCost === 'function' ? computeFormulationCost(formula, ccy) : null;
2894
+ c = formula && typeof computeFormulationCost === 'function' ? computeFormulationCost(formula, ccy) : null;
2798
2895
  if (c && isFinite(c.perKg)) perKg = c.perKg;
2799
2896
  if (c && c.countedPerPiece > 0) perPiece = c.countedPerPiece;
2800
2897
  } catch (_) { perKg = null; }
2801
2898
  const kg = quantityToKg(qty, unit, formula);
2802
2899
  // 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;
2900
+ const pieces = (perPiece != null && kg > 0 && typeof flProductUnits === 'function') ? flProductUnits(formula, kg, null) : 0;
2901
+ const counted = pieces ? perPiece * pieces : 0;
2804
2902
  const computed = (perKg != null && kg != null) ? perKg * kg + counted : null;
2805
- return { perKg, kg, computed, ccy, convertible: kg != null, counted };
2903
+ return { perKg, kg, computed, ccy, convertible: kg != null, counted, pieces, cost: c };
2806
2904
  }
2807
2905
 
2808
2906
  // Open the global Display-currency setting — Settings modal → Preferences tab
@@ -2889,7 +2987,7 @@ function entityCostCellHtml(summary, label) {
2889
2987
  // o = { kind:'sample'|'batch', id, qty, unit, formula, override }.
2890
2988
  function entityCostValueHtml(o) {
2891
2989
  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);
2990
+ const { perKg, computed, ccy, convertible, counted, pieces, cost } = quantityCost(o.qty, o.unit, o.formula);
2893
2991
  const money = v => (typeof formatMoney === 'function') ? formatMoney(v, ccy) : (ccy + ' ' + (+v).toFixed(2));
2894
2992
  const ovRaw = (o.override != null && o.override !== '' && isFinite(parseFloat(o.override))) ? parseFloat(o.override) : null;
2895
2993
  // The override was entered in o.overrideCcy (legacy values w/o a stamp are
@@ -2953,8 +3051,9 @@ function entityCostValueHtml(o) {
2953
3051
  const col = (why === 'needs-density') ? 'var(--dk-amber-fg, #b45309)' : 'var(--text-muted)';
2954
3052
  return `<span style="color:var(--text-muted)">—</span> <span style="font-size:11px;color:${col}">${msg}</span>${editBtn}`;
2955
3053
  }
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>`;
2957
- return `<strong>${money(computed)}</strong>${breakdown}${editBtn}${ccyLine}`;
3054
+ // Its own line under the total (Jun, 5 Dec: the breakdown wrapped beside it, splitting a part's name around Override).
3055
+ const breakdown = `<div class="fl-cost-breakdown" style="font-size:11px;color:var(--text-muted);margin-top:2px">${esc(String(o.qty))} ${esc(o.unit || '')} × ${money(perKg)}/kg${counted > 0 ? ` + ${esc(flCountedPartsText(cost, pieces, counted, money) || money(counted) + ' counted parts')}` : ''}</div>`;
3056
+ return `<strong>${money(computed)}</strong>${editBtn}${breakdown}${ccyLine}`;
2958
3057
  }
2959
3058
 
2960
3059
  function openCostOverrideModal(kind, id) {
@@ -930,6 +930,38 @@ function _frgDocSelectHtml(id, ing, picked, none) {
930
930
  : frag.concat(rest).map(opt).join('');
931
931
  return `<select id="${id}"${docs.length ? '' : ' disabled'}><option value="">${docs.length ? none : 'No documents yet'}</option>${body}</select>`;
932
932
  }
933
+ // Upload right where the certificate is picked (Jun, 5 Dec: "in class details card, when edit, it is unclear how to
934
+ // upload these docs"). The PDF is filed under Documents › Fragrance Compliance and picked here. A new ingredient has
935
+ // nowhere to file it yet: it says to save first.
936
+ // Quiet links beside the picker, as in the other form dialogs (Jun, 5 Dec: "maybe use subtle upload and Read in Class &
937
+ // Details?"): Upload · Read from PDF. The Documents tab keeps its buttons.
938
+ function _frgDocLinksHtml(ing, selId, which) {
939
+ const saved = !!(ing && ing.id && (db.ingredients || []).some(i => i && i.id === ing.id));
940
+ const link = (text, onclick, title, extra) => `<span class="fl-dq-link" role="button" tabindex="0"${extra || ''} onclick="${onclick}" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();this.click();}"${title ? ` title="${title}"` : ''}>${text}</span>`;
941
+ const up = saved ? link('Upload', `_frgUploadDoc('${escJsAttr(ing.id)}', '${selId}')`, 'Upload a PDF to Documents › Fragrance Compliance') : '';
942
+ const read = _frgCanRead() ? link('Read from PDF', `flFrReadDoc('${which}')`, '', ` id="f-fr-read-${which}"`)
943
+ : link('Read from PDF <span class="asm-designer-pro-badge usda-pro">Pro</span>', 'docProUpsell()', '');
944
+ return `<span class="fl-dq fr-doc-links">${up}${up ? '<span class="fl-dq-sep" aria-hidden="true">·</span>' : ''}${read}</span>${saved ? '' : '<span class="fr-dim fr-up-hint">Save the ingredient to upload its PDF here.</span>'}`;
945
+ }
946
+ function _frgUploadDoc(ingId, selId) {
947
+ const input = document.createElement('input');
948
+ input.type = 'file'; input.accept = 'application/pdf';
949
+ input.onchange = async e => {
950
+ const file = e.target.files && e.target.files[0];
951
+ if (!file || typeof docAttach !== 'function') return;
952
+ const res = await docAttach(ingId, 'FRAG', file);
953
+ if (!res || res.error) { if (typeof toast === 'function') toast((res && res.error) || 'Upload failed.', 'error'); return; }
954
+ const ing = (db.ingredients || []).find(i => i && i.id === ingId);
955
+ // Both pickers list the new file; this one takes it. What the other had picked stays.
956
+ ['f-fr-cert', 'f-fr-decl'].forEach(id => {
957
+ const sel = document.getElementById(id); if (!sel) return;
958
+ const keep = id === selId ? res.docId : sel.value;
959
+ sel.outerHTML = _frgDocSelectHtml(id, ing, keep, 'Choose\u2026');
960
+ });
961
+ if (typeof toast === 'function') toast(`${file.name} filed under Documents \u203a Fragrance Compliance`);
962
+ };
963
+ input.click();
964
+ }
933
965
  // The two blocks inside the ingredient form's Fragrance Details panel.
934
966
  function flFrIngFormHtml(ing) {
935
967
  const fd = (ing && ing.fragranceDetails) || {};
@@ -942,8 +974,7 @@ function flFrIngFormHtml(ing) {
942
974
  <div class="fr-dim fr-from">From the supplier\u2019s IFRA certificate.</div>
943
975
  <div class="fr-form-top">
944
976
  <label class="fr-f-short">Amendment<input id="f-fr-amend" maxlength="20" placeholder="51st" value="${_frgEsc(fd.ifraAmendment || '')}" /></label>
945
- <label class="fr-f-doc">Certificate${_frgDocSelectHtml('f-fr-cert', ing, fd.ifraCertDocId, 'Choose\u2026')}</label>
946
- ${_frgReadBtnHtml('limits')}
977
+ <label class="fr-f-doc">Certificate${_frgDocSelectHtml('f-fr-cert', ing, fd.ifraCertDocId, 'Choose\u2026')}</label>${_frgDocLinksHtml(ing, 'f-fr-cert', 'limits')}
947
978
  </div>
948
979
  <div class="fr-row fr-cols"${limits.length ? '' : ' hidden'}><span>Category</span><span>Limit</span><span class="num">Max</span><span></span></div>
949
980
  <div id="f-fr-limits">${limits.map(_frgLimitRowHtml).join('')}</div>
@@ -953,9 +984,8 @@ function flFrIngFormHtml(ing) {
953
984
  const allergensBody = `<div class="fr-block">
954
985
  <div class="fr-dim fr-from">% in this material, from the allergen declaration.</div>
955
986
  <div class="fr-form-top">
956
- <label class="fr-f-doc">Declaration${_frgDocSelectHtml('f-fr-decl', ing, ing && ing.allergenDeclDocId, 'Choose\u2026')}</label>
987
+ <label class="fr-f-doc">Declaration${_frgDocSelectHtml('f-fr-decl', ing, ing && ing.allergenDeclDocId, 'Choose\u2026')}</label>${_frgDocLinksHtml(ing, 'f-fr-decl', 'allergens')}
957
988
  <label class="fr-check"><input type="checkbox" id="f-fr-none"${declared && !al.length ? ' checked' : ''} onchange="_frgNoneTicked(this)" /> Declares none</label>
958
- ${_frgReadBtnHtml('allergens')}
959
989
  </div>
960
990
  ${auto ? '<div class="fr-dim" data-fr-auto>On the EU list by its CAS: counted as 100% of itself. Add rows only to say otherwise.</div>' : ''}
961
991
  <div class="fr-row fr-cols"${al.length ? '' : ' hidden'}><span>Allergen</span><span>CAS</span><span class="num">In material</span><span></span></div>
@@ -992,10 +1022,6 @@ function _frgAllergensHint(n, total, none, decl, auto) {
992
1022
  // left unsaved: the form is the review step, and Save is the person's own. Nothing is read without a document picked,
993
1023
  // so every row that arrives already has its source. A row already in the form is never replaced.
994
1024
  const _frgCanRead = () => typeof hasFeature !== 'function' || hasFeature('docs.extract');
995
- function _frgReadBtnHtml(which) {
996
- if (!_frgCanRead()) return `<button type="button" class="btn btn-secondary btn-sm fr-read" onclick="docProUpsell()">Read from PDF <span class="asm-designer-pro-badge usda-pro">Pro</span></button>`;
997
- return `<button type="button" class="btn btn-secondary btn-sm fr-read" id="f-fr-read-${which}" onclick="flFrReadDoc('${which}')">Read from PDF</button>`;
998
- }
999
1025
  function _frgReadPrompt(which, ing) {
1000
1026
  const name = _frgName(ing);
1001
1027
  if (which === 'limits') return [
@@ -1065,11 +1091,11 @@ async function flFrReadDoc(which) {
1065
1091
  if (!ap) return;
1066
1092
  const btn = document.getElementById('f-fr-read-' + which);
1067
1093
  _frgReading = true;
1068
- if (btn) { btn.disabled = true; btn.textContent = 'Reading…'; }
1094
+ if (btn) { btn.disabled = true; btn.setAttribute('aria-disabled', 'true'); btn.textContent = 'Reading…'; }
1069
1095
  let raw;
1070
1096
  try { raw = ap.provider === 'mock' ? _frgReadMock(which) : await _runPdfExtract(ap.provider, ap.key, _frgReadPrompt(which, ing), doc); }
1071
1097
  catch (e) { say('Could not read the document: ' + ((e && e.message) || e)); return; }
1072
- finally { _frgReading = false; const b = document.getElementById('f-fr-read-' + which); if (b) { b.disabled = false; b.textContent = 'Read from PDF'; } }
1098
+ finally { _frgReading = false; const b = document.getElementById('f-fr-read-' + which); if (b) { b.disabled = false; b.removeAttribute('aria-disabled'); b.textContent = 'Read from PDF'; } }
1073
1099
  // The form may have closed, or another document been picked, while the call was out.
1074
1100
  const list = document.getElementById(which === 'limits' ? 'f-fr-limits' : 'f-fr-allergens'), sel2 = document.getElementById(which === 'limits' ? 'f-fr-cert' : 'f-fr-decl');
1075
1101
  if (!list || !sel2 || sel2.value !== doc.id) return;
package/vendor/nesting.js CHANGED
@@ -351,6 +351,10 @@ function _rowWtFractionsWithin(f, unresolved) {
351
351
  if (kinds[i] === 'vol') return amt; // treat as relative volume (best-effort)
352
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
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
+ // A sub-formula counted in pieces with no weight for one (no fill, a % recipe) is named the same way (12-04).
355
+ if (kinds[i] === 'unknown' && c.formulationId && !c.ingredientId && typeof flIsPieceUnit === 'function' && flIsPieceUnit(c.unit)) {
356
+ unresolved && unresolved.push({ reason: 'no-weight', formulationId: c.formulationId, unit: c.unit || '' });
357
+ }
354
358
  if (kinds[i] === 'unknown' && c.ingredientId) {
355
359
  const pc = typeof flIsPieceUnit === 'function' && flIsPieceUnit(c.unit);
356
360
  const ing = db.ingredients.find(x => x.id === c.ingredientId);
@@ -680,9 +680,10 @@ function flNlTabHtml(f) {
680
680
  }
681
681
  const c = flNlCompute(f);
682
682
  if (!c.ok) {
683
- const who = (c.needsDensity || []).slice(0, 6).join(', ');
684
- // Pieces (12-04): a weight per piece, or Not mixed in for a part outside the food.
683
+ // Pieces (12-04): a weight per piece, or Not mixed in for a part outside the food. The advice says what to
684
+ // set, so the names drop their bracketed reason (Jun, 12-04: "shorten the label message").
685
685
  const pcs = typeof flNeedsPieceText === 'function' && flNeedsPieceText(c.needsDensity);
686
+ const who = [...new Set((c.needsDensity || []).map(n => pcs ? String(n).replace(/ \((?:no weight per piece|pieces in a % recipe)\)$/, '') : n))].slice(0, 6).join(', ');
686
687
  return `<div class="card"><div class="card-body"><div class="nl-note warn nl-keep">No label yet. ${pcs ? `Can't weigh ${esc(who)}: set a weight per piece, or tick Not mixed in.` : `Add a density to ${esc(who) || 'the rows measured by volume'}.`}</div></div></div>`;
687
688
  }
688
689
  const st = _nlSettings(f);
@@ -593,7 +593,10 @@ function _tpBuildRows(composition) {
593
593
  const rx = (sub && typeof flRxSubViewFields === 'function') ? flRxSubViewFields(sub) : {};
594
594
  // Per-field rules (Jun, 28 Oct): the fields that add up by mass roll up too (_tpSubRollup).
595
595
  const roll = sub ? _tpSubRollup(sub) : { fields: {}, units: {} };
596
- rows.push({ ...base, ing: _tpCiView({ _isSubFormula: true, ...roll.fields, ...rx }), _cfUnits: roll.units, _srcSub: c.formulationId, _subName: (sub && sub.name) || 'sub-formula' });
596
+ // Counted in pieces (2 candles): weighed through the sub-formula's one piece, like an ingredient's (12-04).
597
+ const pc = typeof flIsPieceUnit === 'function' && flIsPieceUnit(c.unit);
598
+ const pieceKg = pc && typeof flPieceRowKg === 'function' ? flPieceRowKg(c) : null;
599
+ rows.push({ ...base, ing: _tpCiView({ _isSubFormula: true, ...roll.fields, ...rx }), _cfUnits: roll.units, _srcSub: c.formulationId, _subName: (sub && sub.name) || 'sub-formula', ...(pc ? { _piece: true, _pieceKg: pieceKg } : {}) });
597
600
  }
598
601
  });
599
602
  // ABSOLUTE rows (a batch's as-prepared composition: 215.9 g water, 6.6 mL
@@ -614,9 +617,10 @@ function _tpBuildRows(composition) {
614
617
  const unweighed = [];
615
618
  if (pieces.length && pieces.length < rows.length) {
616
619
  const pct = rows.some(r => !r._piece && /^(wt\s*%|%|w\/w|vol\s*%)/i.test(String(r.unit || 'wt%').trim()));
620
+ const nm = r => (r.ing && r.ing._isSubFormula ? r._subName : r.ing && r.ing.name) || '(unnamed)';
617
621
  pieces.forEach(r => {
618
- if (pct) unweighed.push((r.ing && r.ing.name || '(unnamed)') + _TP_PIECE_PCT);
619
- else if (r._pieceKg == null) unweighed.push((r.ing && r.ing.name || '(unnamed)') + _TP_PIECE_NOWT);
622
+ if (pct) unweighed.push(nm(r) + _TP_PIECE_PCT);
623
+ else if (r._pieceKg == null) unweighed.push(nm(r) + _TP_PIECE_NOWT);
620
624
  });
621
625
  }
622
626
  const abs = rows.filter(r => isM(r.unit) || isV(r.unit) || (r._piece && r._pieceKg != null && !unweighed.length));
@@ -715,10 +719,12 @@ function _tpHarmonizeUnits(rows) {
715
719
  // with an amount has a number for it, in one unit: a premix with a solvent missing its solids is still "not
716
720
  // counted", as before. Not rolled: density (by volume), Tg, HLB, purity, cost, text fields. Nested premixes roll up
717
721
  // through _tpBuildRows; a cycle rolls up nothing.
718
- const _TP_MASS_UNIT = /^(%|wt\s*%|%\s*w\/w|w\/w\s*%?|g\s*\/\s*100\s*g|mg\s*\/\s*100\s*g|[µu]g\s*\/\s*100\s*g|g\s*\/\s*kg|mg\s*\/\s*kg|ppm|ppb|mg\s*koh\s*\/\s*g|meq\s*\/\s*g|mmol\s*\/\s*g)$/i;
722
+ const _TP_MASS_UNIT = /^(%|wt\s*%|%\s*w\/w|w\/w\s*%?|g\s*\/\s*100\s*g|mg\s*\/\s*100\s*g|[µu]g\s*\/\s*100\s*g|g\s*\/\s*kg|mg\s*\/\s*kg|ppm|ppb|mg\s*koh\s*\/\s*g|meq\s*\/\s*g|mmol\s*\/\s*g|k?(?:cal|j)\s*\/\s*(?:100\s*)?(?:g|kg))$/i;
723
+ // Energy per mass (kcal/100 g, kJ/100 g …) adds by mass too: a premix's calories reach the parent's label (12-04).
724
+ // Before, a cookie made 80 % from a dough premix lost the dough's calories, and the label rebuilt them from protein.
719
725
  const _TP_MASS_NAMES = new Set(['solids', 'nv', 'nv %', 'nv%', 'non-volatiles', 'nonvolatiles', 'protein', 'fat', 'carb', 'carbs', 'carbohydrate', 'sugar', 'sugars', 'sodium', 'salt', 'fiber', 'fibre', 'ash', 'moisture',
720
726
  'sat_fat', 'trans_fat', 'added_sugar', 'cholesterol', 'calcium', 'iron', 'potassium', 'vit_d', 'atwater',
721
- 'volume', 'pigmentvolume', 'dryvolume', 'volatileorganic', 'voc %']); // per gram, so they add by mass (PVC, VOC through a premix)
727
+ 'volume', 'pigmentvolume', 'dryvolume', 'volatileorganic', 'voc %', 'energy', 'calories', 'kcal']); // per gram, so they add by mass (PVC, VOC through a premix)
722
728
  const _TP_NOT_ROLLED = new Set(['density', 'mw', 'cost', 'purity', 'stock', 'reorder', 'tg', 'hlb', 'taxonid']);
723
729
  const _tpSubStack = new Set();
724
730
  // Inside _tpWithSubMemo each premix rolls up once: a Solve rebuilds the same rows ~80 times with only the top-level