formlab-mcp 0.7.15 → 0.7.17

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.15",
3
+ "version": "0.7.17",
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.15",
5
+ "version": "0.7.17",
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.15",
11
+ "version": "0.7.17",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
package/tools/lab.js CHANGED
@@ -441,6 +441,8 @@ 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).
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); });
@@ -366,6 +386,16 @@ function _usedCountUnits() {
366
386
  if (e.target.style.cursor !== c) e.target.style.cursor = c;
367
387
  });
368
388
  document.addEventListener('mouseout', function (e) { if (isCombo(e.target)) e.target.style.cursor = ''; });
389
+ // One highlight (.active) that the mouse moves as the arrow keys do (31c; hover lit a second row). Only a real pointer
390
+ // move counts, so rows the arrow keys scroll under a still pointer don't take it.
391
+ var lastXY = '';
392
+ document.addEventListener('mousemove', function (e) {
393
+ var xy = e.clientX + ',' + e.clientY; if (xy === lastXY) return; lastXY = xy;
394
+ var it = e.target && e.target.closest && e.target.closest('.fl-unit-combo-item');
395
+ if (!it) return;
396
+ var idx = items().indexOf(it);
397
+ if (idx >= 0 && idx !== activeIdx) highlight(idx);
398
+ });
369
399
  // A click on the field reopens the list after a pick (the field kept focus,
370
400
  // so no focusin fires). Capture phase: dialogs stop click propagation.
371
401
  document.addEventListener('click', function (e) {
@@ -842,6 +872,25 @@ function flIsPieceUnit(u) {
842
872
  const hit = t => Object.keys(t).some(k => k === raw || k.toLowerCase() === lower);
843
873
  return !hit(MASS_TO_KG) && !hit(VOL_TO_L) && !(typeof LENGTH_TO_M !== 'undefined' && hit(LENGTH_TO_M));
844
874
  }
875
+ // A count unit read with its number (dogfood 6 Dec: "24 jar of 24 jar", "2 candle returned"): 24 jars, 1 jar, 2 boxes.
876
+ // Only words people count (a piece unit or a pack); mass, volume, %, "each", codes and words already plural stay as written.
877
+ const FL_UNIT_NO_PLURAL = new Set(['each', 'ea', 'pc', 'pcs', 'unit', 'units', 'eq', 'mol', 'dozen', 'doz', 'gross', 'ream']);
878
+ function flUnitN(n, unit) {
879
+ const u = String(unit == null ? '' : unit), x = Math.abs(parseFloat(n));
880
+ if (!u || !isFinite(x) || x === 1 || u.length > 20 || !/^[a-z]+$/.test(u) || /s$/.test(u) || FL_UNIT_NO_PLURAL.has(u)) return u;
881
+ if (!(flIsPieceUnit(u) || FL_PACK_UNITS.has(u))) return u;
882
+ if (/(x|z|ch|sh)$/.test(u)) return u + 'es';
883
+ if (/[^aeiou]y$/.test(u)) return u.slice(0, -1) + 'ies';
884
+ return u + 's';
885
+ }
886
+ // The word for one piece in "Weight per …" (5 Dec, Jun: "is per piece better or per unit better because piece itself is
887
+ // a unit"): the stock unit when it is one item (jar, wick, candle), else "piece". A pack (box, bag) holds many pieces and
888
+ // "each" / "unit" say nothing, so those read "piece"; so do mass and volume units.
889
+ function flPieceNoun(stockUnit) {
890
+ const u = String(stockUnit || '').trim();
891
+ if (!u || u.length > 24 || ['each', 'piece', 'pieces', 'pc', 'pcs', 'unit', 'units', 'ea'].includes(u.toLowerCase())) return 'piece';
892
+ return flIsPieceUnit(u) ? u : 'piece';
893
+ }
845
894
  // 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
895
  // 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
896
  // 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
@@ -2599,13 +2648,16 @@ function computeBatchCost(batch, displayCcy = getDisplayCurrency()) {
2599
2648
  const sizeKg = quantityToKg(batch.targetQuantity, batch.unit, f, _umk);
2600
2649
  // Parts counted per piece (1 wick per candle) × the pieces the batch makes (3 Dec).
2601
2650
  const _isCount = _umk != null && !(batch.unit in MASS_TO_KG) && !(batch.unit in VOL_TO_L);
2602
- const countedCost = perKg.countedPerPiece ? perKg.countedPerPiece * flProductUnits(f, sizeKg, _isCount ? batch.targetQuantity : null) : 0;
2651
+ const _pieces = perKg.countedPerPiece ? flProductUnits(f, sizeKg, _isCount ? batch.targetQuantity : null) : 0;
2652
+ const countedCost = perKg.countedPerPiece ? perKg.countedPerPiece * _pieces : 0;
2653
+ const _money = v => (typeof formatMoney === 'function') ? formatMoney(v, displayCcy) : String(v);
2603
2654
  return {
2604
2655
  formulation: f,
2605
2656
  perKg: perKg.perKg,
2606
2657
  sizeKg,
2607
2658
  total: sizeKg != null ? perKg.perKg * sizeKg + countedCost : null,
2608
2659
  counted: countedCost || null,
2660
+ countedText: countedCost ? flCountedPartsText(perKg, _pieces, countedCost, _money) : null, // "12 × $3,200.00 MacPro Book 2026"
2609
2661
  currency: displayCcy,
2610
2662
  missing: perKg.missing.concat((perKg.countedUnpriced || []).map(ing => ({ reason: 'no cost on file (counted per piece)', ingredient: ing }))),
2611
2663
  };
@@ -2839,21 +2891,37 @@ function quantityToKg(qty, unit, formula, unitMassKg) {
2839
2891
  }
2840
2892
 
2841
2893
  // Returns { perKg, kg, computed, ccy, convertible } in the display currency.
2894
+ // The counted parts spelled out (Jun, 5 Dec: "$38,400.00 counted parts" hid 12 × $3,200): "12 × $3,200.00 MacPro
2895
+ // 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.
2896
+ function flCountedPartsText(cost, pieces, counted, money) {
2897
+ const rows = cost && cost.countedRows;
2898
+ if (!rows || !rows.length || !(pieces > 0) || !(counted > 0)) return null;
2899
+ const items = rows.map(r => {
2900
+ const n = parseFloat(r.row && r.row.amount) || 1;
2901
+ const name = (r.ingredient && r.ingredient.name) || 'part';
2902
+ return { cost: r.perPiece * pieces, text: `${+(n * pieces).toFixed(3)} × ${money(r.perPiece / n)} ${name}` };
2903
+ });
2904
+ const sum = items.reduce((a, x) => a + x.cost, 0);
2905
+ if (!isFinite(sum) || Math.abs(sum - counted) > Math.max(0.01, counted * 1e-6)) return null;
2906
+ return items.length <= 2 ? items.map(x => x.text).join(' + ')
2907
+ : `${items[0].text} + ${items.length - 1} more parts (${money(sum - items[0].cost)})`;
2908
+ }
2842
2909
  function quantityCost(qty, unit, formula, displayCcy) {
2843
2910
  const ccy = displayCcy ||
2844
2911
  (typeof getDisplayCurrency === 'function' ? getDisplayCurrency() : null) ||
2845
2912
  (formula && formula.costCurrency) || 'USD';
2846
- let perKg = null, perPiece = null;
2913
+ let perKg = null, perPiece = null, c = null;
2847
2914
  try {
2848
- const c = formula && typeof computeFormulationCost === 'function' ? computeFormulationCost(formula, ccy) : null;
2915
+ c = formula && typeof computeFormulationCost === 'function' ? computeFormulationCost(formula, ccy) : null;
2849
2916
  if (c && isFinite(c.perKg)) perKg = c.perKg;
2850
2917
  if (c && c.countedPerPiece > 0) perPiece = c.countedPerPiece;
2851
2918
  } catch (_) { perKg = null; }
2852
2919
  const kg = quantityToKg(qty, unit, formula);
2853
2920
  // A wick, priced per piece of product (27f: a candle sample read $1.72 without its $0.12 wick).
2854
- const counted = (perPiece != null && kg > 0 && typeof flProductUnits === 'function') ? perPiece * flProductUnits(formula, kg, null) : 0;
2921
+ const pieces = (perPiece != null && kg > 0 && typeof flProductUnits === 'function') ? flProductUnits(formula, kg, null) : 0;
2922
+ const counted = pieces ? perPiece * pieces : 0;
2855
2923
  const computed = (perKg != null && kg != null) ? perKg * kg + counted : null;
2856
- return { perKg, kg, computed, ccy, convertible: kg != null, counted };
2924
+ return { perKg, kg, computed, ccy, convertible: kg != null, counted, pieces, cost: c };
2857
2925
  }
2858
2926
 
2859
2927
  // Open the global Display-currency setting — Settings modal → Preferences tab
@@ -2940,7 +3008,7 @@ function entityCostCellHtml(summary, label) {
2940
3008
  // o = { kind:'sample'|'batch', id, qty, unit, formula, override }.
2941
3009
  function entityCostValueHtml(o) {
2942
3010
  if (typeof flCostHidden === 'function' && flCostHidden()) return '<span style="color:var(--dk-faint, #94a3b8)">—</span>'; // 0267: cost hidden from Viewers
2943
- const { perKg, computed, ccy, convertible, counted } = quantityCost(o.qty, o.unit, o.formula);
3011
+ const { perKg, computed, ccy, convertible, counted, pieces, cost } = quantityCost(o.qty, o.unit, o.formula);
2944
3012
  const money = v => (typeof formatMoney === 'function') ? formatMoney(v, ccy) : (ccy + ' ' + (+v).toFixed(2));
2945
3013
  const ovRaw = (o.override != null && o.override !== '' && isFinite(parseFloat(o.override))) ? parseFloat(o.override) : null;
2946
3014
  // The override was entered in o.overrideCcy (legacy values w/o a stamp are
@@ -3004,8 +3072,9 @@ function entityCostValueHtml(o) {
3004
3072
  const col = (why === 'needs-density') ? 'var(--dk-amber-fg, #b45309)' : 'var(--text-muted)';
3005
3073
  return `<span style="color:var(--text-muted)">—</span> <span style="font-size:11px;color:${col}">${msg}</span>${editBtn}`;
3006
3074
  }
3007
- 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>`;
3008
- return `<strong>${money(computed)}</strong>${breakdown}${editBtn}${ccyLine}`;
3075
+ // Its own line under the total (Jun, 5 Dec: the breakdown wrapped beside it, splitting a part's name around Override).
3076
+ 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>`;
3077
+ return `<strong>${money(computed)}</strong>${editBtn}${breakdown}${ccyLine}`;
3009
3078
  }
3010
3079
 
3011
3080
  function openCostOverrideModal(kind, id) {
@@ -286,11 +286,14 @@ function flFrCompute(f, opts) {
286
286
  if (!f) return out;
287
287
  const wk = _frgWalk(f), k = st.dosage / 100;
288
288
  out.rootOil = wk.rootOil; out.unresolved = wk.unresolved.length;
289
+ // What could not be weighed, by name (dogfood 6 Dec: a lotion read "check the units and densities" when its xanthan
290
+ // row pointed at an ingredient in Trash).
291
+ out.unresolvedWhy = wk.unresolved.map(_frgUnresolvedText).filter(Boolean);
289
292
  const mats = new Map(), others = new Set();
290
293
  const listedCount = !!st.category || flFrIsCosmetic(f); // a listed substance counts here by its CAS alone
291
294
  wk.leaves.forEach(l => {
292
295
  const ing = _frgIng(l.ingredientId);
293
- if (!ing) { out.unresolved++; return; }
296
+ if (!ing) { out.unresolved++; out.unresolvedWhy.push(_frgUnresolvedText({ reason: 'missing-ingredient', ingredientId: l.ingredientId })); return; }
294
297
  if (!l.inOil && !flFrIsMaterial(ing) && !(listedCount && flFrIsListed(ing))) { others.add(_frgName(ing)); return; }
295
298
  const m = mats.get(ing.id) || { ing, w: 0, byOil: new Map() };
296
299
  m.w += l.w;
@@ -701,13 +704,33 @@ function _frgAllergenTableHtml(c) {
701
704
  return `<div class="table-wrapper"><table class="fr-table fl-band" id="fr-table-${v}"><thead><tr>${_frgTh(v, 'name', 'Allergen')}${_frgTh(v, 'cas', 'CAS')}${_frgTh(v, 'pct', 'In product', true)}${_frgTh(v, 'label', c.use ? _frgEsc(FL_FR_USES[c.use]) : 'Label')}${_frgTh(v, 'from', 'From')}</tr></thead>
702
705
  <tbody>${_frgSorted(all, v, _frgAllergenSortVal).map(row).join('')}</tbody></table></div>`;
703
706
  }
707
+ // One unweighable row in words: "Xanthan Gum is in Trash", "Glycerin: no density".
708
+ function _frgUnresolvedText(u) {
709
+ if (!u) return '';
710
+ const ingName = id => { const i = _frgIng(id); if (i) return _frgName(i); const t = typeof flTrashEntryFor === 'function' ? flTrashEntryFor('ingredient', id) : null; return t && t.item ? t.item.name : ''; };
711
+ const formName = id => { const f = (db.formulations || []).find(x => x && x.id === id); if (f) return f.name || f.uid; const t = typeof flTrashEntryFor === 'function' ? flTrashEntryFor('formulation', id) : null; return t && t.item ? t.item.name : ''; };
712
+ switch (u.reason) {
713
+ case 'missing-ingredient': { const n = ingName(u.ingredientId); return n ? `${n} is in Trash` : 'an ingredient that is no longer here'; }
714
+ case 'deleted-subformula': { const n = formName(u.formulationId); return n ? `${n} is in Trash` : 'a sub-formula that is no longer here'; }
715
+ case 'no-density': return `${ingName(u.ingredientId) || 'an ingredient'}: no density`;
716
+ case 'no-subformula-density': return `${formName(u.formulationId) || 'a sub-formula'}: no density`;
717
+ case 'no-weight': return `${u.ingredientId ? ingName(u.ingredientId) : formName(u.formulationId) || 'a row'}: no weight per piece`;
718
+ case 'unknown-unit': return `${ingName(u.ingredientId) || 'a row'}: unit "${u.unit || ''}"`;
719
+ case 'mixed-basis': return 'percent rows mixed with weight rows';
720
+ case 'cycle': return 'a sub-formula that contains itself';
721
+ case 'bad-amount': return `${u.ingredientId ? ingName(u.ingredientId) : formName(u.formulationId) || 'a row'}: amount "${u.amount}"`;
722
+ default: return '';
723
+ }
724
+ }
704
725
  function _frgUnknownsHtml(c) {
705
726
  const list = (a) => `<span translate="no">${_frgEsc(a.slice(0, 12).join(', '))}${a.length > 12 ? ` and ${a.length - 12} more` : ''}</span>`;
706
727
  const parts = [];
707
728
  if (c.noLimit.length) parts.push(`<div><strong>No limit on file for category ${_frgEsc(c.category)}:</strong> ${list(c.noLimit)}</div>`);
708
729
  if (c.noDecl.length) parts.push(`<div><strong>No allergen declaration:</strong> ${list(c.noDecl)}</div>`);
709
730
  if (c.noSource.length) parts.push(`<div><strong>No source document:</strong> ${list(c.noSource.map(s => `${s.name} (${s.what})`))}</div>`);
710
- if (c.unresolved) parts.push('<div><strong>Composition:</strong> part of it could not be weighed. Check the units and densities on the Composition tab.</div>');
731
+ if (c.unresolved) parts.push(c.unresolvedWhy && c.unresolvedWhy.length
732
+ ? `<div><strong>Composition:</strong> part of it could not be weighed: ${list([...new Set(c.unresolvedWhy)])}.</div>`
733
+ : '<div><strong>Composition:</strong> part of it could not be weighed. Check the units and densities on the Composition tab.</div>');
711
734
  if (!parts.length) return '';
712
735
  return `<div class="card"><div class="card-header"><h2>Unknown</h2></div><div class="card-body fr-unknowns">${parts.join('')}
713
736
  <div class="fr-dim">Add the limits, the declaration, and their documents on each ingredient (Edit, Fragrance details).</div></div></div>`;
@@ -930,6 +953,38 @@ function _frgDocSelectHtml(id, ing, picked, none) {
930
953
  : frag.concat(rest).map(opt).join('');
931
954
  return `<select id="${id}"${docs.length ? '' : ' disabled'}><option value="">${docs.length ? none : 'No documents yet'}</option>${body}</select>`;
932
955
  }
956
+ // Upload right where the certificate is picked (Jun, 5 Dec: "in class details card, when edit, it is unclear how to
957
+ // upload these docs"). The PDF is filed under Documents › Fragrance Compliance and picked here. A new ingredient has
958
+ // nowhere to file it yet: it says to save first.
959
+ // Quiet links beside the picker, as in the other form dialogs (Jun, 5 Dec: "maybe use subtle upload and Read in Class &
960
+ // Details?"): Upload · Read from PDF. The Documents tab keeps its buttons.
961
+ function _frgDocLinksHtml(ing, selId, which) {
962
+ const saved = !!(ing && ing.id && (db.ingredients || []).some(i => i && i.id === ing.id));
963
+ 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>`;
964
+ const up = saved ? link('Upload', `_frgUploadDoc('${escJsAttr(ing.id)}', '${selId}')`, 'Upload a PDF to Documents › Fragrance Compliance') : '';
965
+ const read = _frgCanRead() ? link('Read from PDF', `flFrReadDoc('${which}')`, '', ` id="f-fr-read-${which}"`)
966
+ : link('Read from PDF <span class="asm-designer-pro-badge usda-pro">Pro</span>', 'docProUpsell()', '');
967
+ 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>'}`;
968
+ }
969
+ function _frgUploadDoc(ingId, selId) {
970
+ const input = document.createElement('input');
971
+ input.type = 'file'; input.accept = 'application/pdf';
972
+ input.onchange = async e => {
973
+ const file = e.target.files && e.target.files[0];
974
+ if (!file || typeof docAttach !== 'function') return;
975
+ const res = await docAttach(ingId, 'FRAG', file);
976
+ if (!res || res.error) { if (typeof toast === 'function') toast((res && res.error) || 'Upload failed.', 'error'); return; }
977
+ const ing = (db.ingredients || []).find(i => i && i.id === ingId);
978
+ // Both pickers list the new file; this one takes it. What the other had picked stays.
979
+ ['f-fr-cert', 'f-fr-decl'].forEach(id => {
980
+ const sel = document.getElementById(id); if (!sel) return;
981
+ const keep = id === selId ? res.docId : sel.value;
982
+ sel.outerHTML = _frgDocSelectHtml(id, ing, keep, 'Choose\u2026');
983
+ });
984
+ if (typeof toast === 'function') toast(`${file.name} filed under Documents \u203a Fragrance Compliance`);
985
+ };
986
+ input.click();
987
+ }
933
988
  // The two blocks inside the ingredient form's Fragrance Details panel.
934
989
  function flFrIngFormHtml(ing) {
935
990
  const fd = (ing && ing.fragranceDetails) || {};
@@ -942,8 +997,7 @@ function flFrIngFormHtml(ing) {
942
997
  <div class="fr-dim fr-from">From the supplier\u2019s IFRA certificate.</div>
943
998
  <div class="fr-form-top">
944
999
  <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')}
1000
+ <label class="fr-f-doc">Certificate${_frgDocSelectHtml('f-fr-cert', ing, fd.ifraCertDocId, 'Choose\u2026')}</label>${_frgDocLinksHtml(ing, 'f-fr-cert', 'limits')}
947
1001
  </div>
948
1002
  <div class="fr-row fr-cols"${limits.length ? '' : ' hidden'}><span>Category</span><span>Limit</span><span class="num">Max</span><span></span></div>
949
1003
  <div id="f-fr-limits">${limits.map(_frgLimitRowHtml).join('')}</div>
@@ -953,9 +1007,8 @@ function flFrIngFormHtml(ing) {
953
1007
  const allergensBody = `<div class="fr-block">
954
1008
  <div class="fr-dim fr-from">% in this material, from the allergen declaration.</div>
955
1009
  <div class="fr-form-top">
956
- <label class="fr-f-doc">Declaration${_frgDocSelectHtml('f-fr-decl', ing, ing && ing.allergenDeclDocId, 'Choose\u2026')}</label>
1010
+ <label class="fr-f-doc">Declaration${_frgDocSelectHtml('f-fr-decl', ing, ing && ing.allergenDeclDocId, 'Choose\u2026')}</label>${_frgDocLinksHtml(ing, 'f-fr-decl', 'allergens')}
957
1011
  <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
1012
  </div>
960
1013
  ${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
1014
  <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 +1045,6 @@ function _frgAllergensHint(n, total, none, decl, auto) {
992
1045
  // left unsaved: the form is the review step, and Save is the person's own. Nothing is read without a document picked,
993
1046
  // so every row that arrives already has its source. A row already in the form is never replaced.
994
1047
  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
1048
  function _frgReadPrompt(which, ing) {
1000
1049
  const name = _frgName(ing);
1001
1050
  if (which === 'limits') return [
@@ -1065,38 +1114,62 @@ async function flFrReadDoc(which) {
1065
1114
  if (!ap) return;
1066
1115
  const btn = document.getElementById('f-fr-read-' + which);
1067
1116
  _frgReading = true;
1068
- if (btn) { btn.disabled = true; btn.textContent = 'Reading…'; }
1117
+ if (btn) { btn.disabled = true; btn.setAttribute('aria-disabled', 'true'); btn.textContent = 'Reading…'; }
1069
1118
  let raw;
1070
1119
  try { raw = ap.provider === 'mock' ? _frgReadMock(which) : await _runPdfExtract(ap.provider, ap.key, _frgReadPrompt(which, ing), doc); }
1071
1120
  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'; } }
1121
+ 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
1122
  // The form may have closed, or another document been picked, while the call was out.
1074
1123
  const list = document.getElementById(which === 'limits' ? 'f-fr-limits' : 'f-fr-allergens'), sel2 = document.getElementById(which === 'limits' ? 'f-fr-cert' : 'f-fr-decl');
1075
1124
  if (!list || !sel2 || sel2.value !== doc.id) return;
1076
1125
  const file = _frgText(doc.filename) || 'the document';
1126
+ // A row already here that the document says otherwise is updated and marked (dogfood 6 Dec: a 52nd Amendment
1127
+ // certificate read over the 51st kept 5A at 0.15 % where it said 0.40 %, and "2 already here" hid it).
1077
1128
  let added = 0, had = 0, res;
1129
+ const changed = [];
1078
1130
  if (which === 'limits') {
1079
1131
  res = flFrLimitsFromExtract(raw);
1080
- const have = new Set([...list.querySelectorAll('.fr-l-cat')].map(x => x.value));
1081
- res.rows.forEach(r => { if (have.has(r.category)) { had++; return; } list.insertAdjacentHTML('beforeend', _frgLimitRowHtml(r)); list.lastElementChild.classList.add('fr-new'); added++; });
1132
+ const kindOf = r => r.unrestricted ? 'unrestricted' : (r.prohibited || _frgNum(r.maxPct) === 0) ? 'prohibited' : 'limit';
1133
+ const textOf = (kind, m) => kind === 'limit' ? `${m} %` : kind === 'prohibited' ? 'prohibited' : 'not restricted';
1134
+ const byCat = new Map([...list.querySelectorAll('.fr-limit-row')].map(x => [x.querySelector('.fr-l-cat').value, x]));
1135
+ res.rows.forEach(r => {
1136
+ const old = byCat.get(r.category);
1137
+ if (!old) { list.insertAdjacentHTML('beforeend', _frgLimitRowHtml(r)); list.lastElementChild.classList.add('fr-new'); added++; return; }
1138
+ const k0 = old.querySelector('.fr-l-kind').value, m0 = _frgNum(old.querySelector('.fr-l-max').value), k1 = kindOf(r), m1 = _frgNum(r.maxPct);
1139
+ if (k0 === k1 && (k1 !== 'limit' || m0 === m1)) { had++; return; }
1140
+ old.insertAdjacentHTML('afterend', _frgLimitRowHtml(r));
1141
+ const nw = old.nextElementSibling; old.remove(); nw.classList.add('fr-new');
1142
+ changed.push(`${r.category} ${textOf(k0, m0)} → ${textOf(k1, m1)}`);
1143
+ });
1082
1144
  const am = document.getElementById('f-fr-amend');
1083
- if (am && !am.value.trim() && res.amendment) am.value = res.amendment;
1145
+ if (am && res.amendment && am.value.trim() !== res.amendment) {
1146
+ if (am.value.trim()) changed.push(`amendment ${am.value.trim()} → ${res.amendment}`);
1147
+ am.value = res.amendment;
1148
+ }
1084
1149
  } else {
1085
1150
  res = flFrAllergensFromExtract(raw);
1086
1151
  const keyOf = (n, c) => { const e = flFrAllergenFor(n, c); return e ? 'e' + e.ref : _frgKey(n) || _frgCas(c); };
1087
- const have = new Set([...list.querySelectorAll('.fr-al-row')].map(x => keyOf(x.querySelector('.fr-a-name').value, x.querySelector('.fr-a-cas').value)));
1088
- res.rows.forEach(r => { if (have.has(keyOf(r.substance, r.cas))) { had++; return; } list.insertAdjacentHTML('beforeend', _frgAllergenRowHtml(r)); list.lastElementChild.classList.add('fr-new'); added++; });
1152
+ const byKey = new Map([...list.querySelectorAll('.fr-al-row')].map(x => [keyOf(x.querySelector('.fr-a-name').value, x.querySelector('.fr-a-cas').value), x]));
1153
+ res.rows.forEach(r => {
1154
+ const old = byKey.get(keyOf(r.substance, r.cas));
1155
+ if (!old) { list.insertAdjacentHTML('beforeend', _frgAllergenRowHtml(r)); list.lastElementChild.classList.add('fr-new'); added++; return; }
1156
+ const pin = old.querySelector('.fr-a-pct'), p0 = _frgNum(pin.value), p1 = _frgNum(r.pct);
1157
+ if (p0 === p1) { had++; return; }
1158
+ pin.value = String(r.pct); old.classList.add('fr-new');
1159
+ changed.push(`${old.querySelector('.fr-a-name').value || r.substance} ${pin.defaultValue || '?'} → ${r.pct} %`);
1160
+ });
1089
1161
  const none = document.getElementById('f-fr-none');
1090
1162
  if (none) { if (added) none.checked = false; else if (res.none && !list.children.length) none.checked = true; }
1091
1163
  }
1092
1164
  if (typeof flOpenFold === 'function') flOpenFold(which === 'limits' ? 'f-fr-fold-limits' : 'f-fr-fold-allergens');
1093
1165
  _frgFormCheck();
1094
- if (added && typeof _ingMarkDirty === 'function') { try { _ingMarkDirty(); } catch (_) {} }
1166
+ if ((added || changed.length) && typeof _ingMarkDirty === 'function') { try { _ingMarkDirty(); } catch (_) {} }
1095
1167
  const what = which === 'limits' ? ['limit', 'limits'] : ['allergen', 'allergens'];
1096
- const bits = [added ? `${added} ${what[added === 1 ? 0 : 1]} read from ${file}` : (which === 'allergens' && res.none ? `${file} declares none` : `Nothing new read from ${file}`)];
1097
- if (had) bits.push(`${had} already here`);
1168
+ const bits = [added ? `${added} ${what[added === 1 ? 0 : 1]} read from ${file}` : changed.length ? `Read from ${file}` : (which === 'allergens' && res.none ? `${file} declares none` : `Nothing new read from ${file}`)];
1169
+ if (changed.length) bits.push(`${changed.length} changed (${changed.slice(0, 3).join('; ')}${changed.length > 3 ? '; …' : ''})`);
1170
+ if (had) bits.push(`${had} unchanged`);
1098
1171
  if (res.skipped) bits.push(`${res.skipped} skipped`);
1099
- say(bits.join(', ') + (added ? '. Check each against the document, then Save.' : '.'), added ? 'info' : undefined);
1172
+ say(bits.join(', ') + (added || changed.length ? '. Check each against the document, then Save.' : '.'), added || changed.length ? 'info' : undefined);
1100
1173
  }
1101
1174
 
1102
1175
  // What the ingredient form saves. → { error } | { details: fields for fragranceDetails, fragranceAllergens, allergenDeclDocId }