formlab-mcp 0.6.88 → 0.6.90

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.
@@ -0,0 +1,1061 @@
1
+ // ============================================================
2
+ // Fragrance compliance — IFRA limits and EU fragrance allergens (Jun, 23 Nov; docs/FRAGRANCE_COMPLIANCE_SCOPE.md)
3
+ // ------------------------------------------------------------
4
+ // Phase 1, the data (free): the product category on a formula, a material's IFRA limits per category and its
5
+ // allergen content, each tied to the supplier document it was read from. Phase 2, the checks (Pro): a formula's
6
+ // Fragrance tab with every material's % in the product against its limit, the highest dosage that passes, and the
7
+ // regulated allergens summed across materials with the ones to name on the label.
8
+ //
9
+ // Two rules hold everywhere here:
10
+ // 1. No bundled limits. Every limit is one the lab typed from a certificate; FL_FR_ALLERGENS below is the EU's
11
+ // list of names and CAS numbers (regulation text), with no limits in it.
12
+ // 2. Unknown is never a pass. A material with no limit row for the category, no allergen declaration, or a number
13
+ // with no document behind it is listed, and the verdict cannot be "conforms" while one remains.
14
+ //
15
+ // Saved on the shared records:
16
+ // formula.ifraCategory ('5A'), formula.productUse ('leave-on' | 'rinse-off'), formula.ifraDosagePct (2)
17
+ // ingredient.fragranceDetails.ifraLimits [{ category: '5A' | 'all', maxPct } | { …, prohibited: true } |
18
+ // { …, unrestricted: true }], .ifraAmendment ('51st'), .ifraCertDocId (one of ingredient.documents)
19
+ // ingredient.fragranceAllergens [{ substance, cas, pct }] ([] = "declares none"; absent = no declaration)
20
+ // ingredient.allergenDeclDocId
21
+ // ============================================================
22
+
23
+ // IFRA product categories (Amendment 49 onward). The words are a reminder, not the Standard's definitions.
24
+ const FL_FR_CATEGORIES = ['1', '2', '3', '4', '5A', '5B', '5C', '5D', '6', '7A', '7B', '8', '9', '10A', '10B', '11A', '11B', '12'];
25
+ const FL_FR_CAT_WORDS = {
26
+ '1': 'Lip products', '2': 'Deodorant, antiperspirant', '3': 'Eye and face products', '4': 'Fine fragrance',
27
+ '5A': 'Body lotion', '5B': 'Face moisturizer', '5C': 'Hand cream', '5D': 'Baby cream, oil, talc', '6': 'Oral care',
28
+ '7A': 'Rinse-off hair, hand contact', '7B': 'Leave-on hair', '8': 'Intimate and baby wipes', '9': 'Rinse-off soap, shampoo',
29
+ '10A': 'Household, hand contact', '10B': 'Household sprays', '11A': 'Diapers, pads', '11B': 'Scented clothing',
30
+ '12': 'No skin contact (candles, air care)',
31
+ };
32
+ const FL_FR_USES = { 'leave-on': 'Leave-on', 'rinse-off': 'Rinse-off' };
33
+ // Label when the allergen in the finished product is ABOVE this (% w/w): Annex III, column h.
34
+ const FL_FR_LABEL_OVER = { 'leave-on': 0.001, 'rinse-off': 0.01 };
35
+ // A stored or passed value is a use only when it is one of the two keys themselves: FL_FR_USES['constructor'] is truthy.
36
+ const _frgIsUse = (v) => typeof v === 'string' && Object.prototype.hasOwnProperty.call(FL_FR_USES, v);
37
+
38
+ // The individually labelled fragrance allergens: Annex III of Regulation (EC) No 1223/2009 as amended by Regulation
39
+ // (EU) 2023/1545. [Annex III reference number, the name to print on the label, CAS numbers, other names].
40
+ // Entries 45 to 324 (the 17 replaced) and 327 to 371 (the 45 added) are from the 2023 regulation's Annex; the 19
41
+ // others are the entries of 67 to 92 it left as they were. Entries 79 and 83 (HICC, BMHCA) are gone: both are banned.
42
+ const FL_FR_ALLERGENS = [
43
+ [45, 'Benzyl Alcohol', ['100-51-6']],
44
+ [46, '6-Methyl Coumarin', ['92-48-8'], ['6-Methylcoumarin']],
45
+ [67, 'Amyl Cinnamal', ['122-40-7']],
46
+ [69, 'Cinnamyl Alcohol', ['104-54-1']],
47
+ [70, 'Citral', ['5392-40-5', '141-27-5', '106-26-3'], ['Geranial', 'Neral']],
48
+ [71, 'Eugenol', ['97-53-0']],
49
+ [72, 'Hydroxycitronellal', ['107-75-5']],
50
+ [73, 'Isoeugenol', ['97-54-1', '5932-68-3', '5912-86-7'], ['trans-Isoeugenol', 'cis-Isoeugenol']],
51
+ [74, 'Amylcinnamyl Alcohol', ['101-85-9']],
52
+ [75, 'Benzyl Salicylate', ['118-58-1']],
53
+ [76, 'Cinnamal', ['104-55-2'], ['Cinnamaldehyde']],
54
+ [77, 'Coumarin', ['91-64-5']],
55
+ [78, 'Geraniol', ['106-24-1']],
56
+ [80, 'Anise Alcohol', ['105-13-5'], ['Anisyl Alcohol']],
57
+ [81, 'Benzyl Cinnamate', ['103-41-3']],
58
+ [82, 'Farnesol', ['4602-84-0']],
59
+ [84, 'Linalool', ['78-70-6']],
60
+ [85, 'Benzyl Benzoate', ['120-51-4']],
61
+ [86, 'Citronellol', ['106-22-9', '26489-01-0', '1117-61-9', '7540-51-4']],
62
+ [87, 'Hexyl Cinnamal', ['101-86-0']],
63
+ [88, 'Limonene', ['138-86-3', '7705-14-8', '5989-27-5', '5989-54-8'], ['d-Limonene', 'l-Limonene', 'dl-Limonene', 'Dipentene']],
64
+ [89, 'Methyl 2-Octynoate', ['111-12-6'], ['Methyl Heptine Carbonate']],
65
+ [90, 'Alpha-Isomethyl Ionone', ['127-51-5']],
66
+ [91, 'Evernia Prunastri Extract', ['90028-68-5'], ['Oakmoss Extract']],
67
+ [92, 'Evernia Furfuracea Extract', ['90028-67-4'], ['Treemoss Extract']],
68
+ [109, 'Pinus Mugo', ['90082-72-7'], ['Pinus Mugo Leaf Oil', 'Pinus Mugo Twig Leaf Extract', 'Pinus Mugo Twig Oil']],
69
+ [114, 'Pinus Pumila', ['97676-05-6'], ['Pinus Pumila Needle Extract', 'Pinus Pumila Twig Leaf Extract', 'Pinus Pumila Twig Leaf Oil']],
70
+ [122, 'Cedrus Atlantica Oil/Extract', ['92201-55-3', '8023-85-6'], ['Cedrus Atlantica Bark Extract', 'Cedrus Atlantica Bark Oil', 'Cedrus Atlantica Bark Water', 'Cedrus Atlantica Leaf Extract', 'Cedrus Atlantica Wood Extract', 'Cedrus Atlantica Wood Oil']],
71
+ [124, 'Turpentine', ['9005-90-7', '8006-64-2', '8052-14-0']],
72
+ [131, 'Alpha-Terpinene', ['99-86-5']],
73
+ [133, 'Terpinolene', ['586-62-9']],
74
+ [154, 'Myroxylon Pereirae Oil/Extract', ['8007-00-9'], ['Myroxylon Balsamum Pereirae Balsam Extract', 'Myroxylon Balsamum Pereirae Balsam Oil', 'Myroxylon Pereirae Oil', 'Myroxylon Pereirae Resin Extract', 'Myroxylon Pereirae Resin', 'Balsam Peru']],
75
+ [157, 'Rose Ketones', ['43052-87-5', '23726-94-5', '24720-09-0', '23696-85-7', '57378-68-4', '71048-82-3', '23726-92-3', '23726-91-2'], ['Alpha-Damascone', 'Beta-Damascone', 'Delta-Damascone', 'Damascenone', 'Rose Ketone 1', 'Rose Ketone 2', 'Rose Ketone 3', 'Rose Ketone 4']],
76
+ [175, '3-Propylidenephthalide', ['17369-59-4']],
77
+ [196, 'Lippia Citriodora Absolute', ['8024-12-2', '85116-63-8'], ['Verbena Absolute']],
78
+ [324, 'Methyl Salicylate', ['119-36-8']],
79
+ [327, 'Acetyl Cedrene', ['32388-55-9']],
80
+ [328, 'Amyl Salicylate', ['2050-08-0']],
81
+ [329, 'Anethole', ['104-46-1', '4180-23-8'], ['trans-Anethole']],
82
+ [330, 'Benzaldehyde', ['100-52-7']],
83
+ [331, 'Camphor', ['76-22-2', '21368-68-3', '464-49-3', '464-48-2']],
84
+ [332, 'Beta-Caryophyllene', ['87-44-5']],
85
+ [333, 'Carvone', ['99-49-0', '6485-40-1', '2244-16-8']],
86
+ [334, 'Dimethyl Phenethyl Acetate', ['151-05-3'], ['Dimethylbenzyl Carbinyl Acetate']],
87
+ [335, 'Hexadecanolactone', ['109-29-5']],
88
+ [336, 'Hexamethylindanopyran', ['1222-05-5']],
89
+ [337, 'Linalyl Acetate', ['115-95-7']],
90
+ [338, 'Menthol', ['89-78-1', '1490-04-6', '2216-51-5', '15356-60-2'], ['l-Menthol', 'd-Menthol', 'dl-Menthol']],
91
+ [339, 'Trimethylcyclopentenyl Methylisopentenol', ['67801-20-1']],
92
+ [340, 'Salicylaldehyde', ['90-02-8']],
93
+ [341, 'Santalol', ['11031-45-1', '115-71-9', '77-42-9'], ['Alpha-Santalol', 'Beta-Santalol']],
94
+ [342, 'Sclareol', ['515-03-7']],
95
+ [343, 'Terpineol', ['8000-41-7', '98-55-5', '138-87-4', '586-81-2'], ['Alpha-Terpineol', 'Beta-Terpineol', 'Gamma-Terpineol']],
96
+ [344, 'Tetramethyl Acetyloctahydronaphthalenes', ['54464-57-2', '54464-59-4', '68155-66-8', '68155-67-9']],
97
+ [345, 'Trimethylbenzenepropanol', ['103694-68-4']],
98
+ [346, 'Vanillin', ['121-33-5']],
99
+ [347, 'Cananga Odorata Oil/Extract', ['83863-30-3', '8006-81-3', '68606-83-7', '93686-30-7'], ['Cananga Odorata Flower Extract', 'Cananga Odorata Flower Oil', 'Ylang Ylang Oil']],
100
+ [348, 'Cinnamomum Cassia Leaf Oil', ['8007-80-5', '84961-46-6']],
101
+ [349, 'Cinnamomum Zeylanicum Bark Oil', ['8015-91-6', '84649-98-9']],
102
+ [350, 'Citrus Aurantium Flower Oil', ['72968-50-4', '8028-48-6', '8016-38-4'], ['Citrus Aurantium Amara Flower Oil', 'Citrus Aurantium Dulcis Flower Oil']],
103
+ [351, 'Citrus Aurantium Peel Oil', ['68916-04-1', '72968-50-4', '97766-30-8', '8028-48-6', '8008-57-9'], ['Citrus Aurantium Amara Peel Oil', 'Citrus Aurantium Dulcis Peel Oil', 'Citrus Sinensis Peel Oil']],
104
+ [352, 'Citrus Aurantium Bergamia Peel Oil', ['8007-75-8', '89957-91-5', '68648-33-9', '85049-52-1'], ['Bergamot Oil']],
105
+ [353, 'Citrus Limon Peel Oil', ['84929-31-7', '8008-56-8'], ['Lemon Oil']],
106
+ [354, 'Lemongrass Oil', ['8007-02-1', '89998-16-3', '91844-92-7'], ['Cymbopogon Schoenanthus Oil', 'Cymbopogon Flexuosus Oil', 'Cymbopogon Citratus Leaf Oil']],
107
+ [355, 'Eucalyptus Globulus Oil', ['97926-40-4', '8000-48-4'], ['Eucalyptus Globulus Leaf Oil', 'Eucalyptus Globulus Leaf/Twig Oil']],
108
+ [356, 'Eugenia Caryophyllus Oil', ['8000-34-8', '8015-97-2', '84961-50-2'], ['Eugenia Caryophyllus Leaf Oil', 'Eugenia Caryophyllus Flower Oil', 'Eugenia Caryophyllus Stem Oil', 'Eugenia Caryophyllus Bud Oil', 'Clove Oil']],
109
+ [357, 'Jasmine Oil/Extract', ['84776-64-7', '90045-94-6', '8022-96-6', '8024-43-9'], ['Jasminum Grandiflorum Flower Extract', 'Jasminum Officinale Oil', 'Jasminum Officinale Flower Extract']],
110
+ [358, 'Juniperus Virginiana Oil', ['8000-27-9', '85085-41-2'], ['Juniperus Virginiana Wood Oil']],
111
+ [359, 'Laurus Nobilis Leaf Oil', ['8002-41-3', '8007-48-5', '84603-73-6']],
112
+ [360, 'Lavandula Oil/Extract', ['91722-69-9', '8022-15-9', '93455-96-0', '93455-97-1', '92623-76-2', '84776-65-8', '8000-28-0', '90063-37-9'], ['Lavandula Hybrida Oil', 'Lavandula Hybrida Extract', 'Lavandula Hybrida Flower Extract', 'Lavandula Intermedia Oil', 'Lavandula Intermedia Flower/Leaf/Stem Extract', 'Lavandula Intermedia Flower/Leaf/Stem Oil', 'Lavandula Angustifolia Oil', 'Lavandula Angustifolia Flower/Leaf/Stem Extract']],
113
+ [361, 'Mentha Piperita Oil', ['8006-90-4', '84082-70-2'], ['Peppermint Oil']],
114
+ [362, 'Mentha Viridis Leaf Oil', ['8008-79-5', '84696-51-5'], ['Spearmint Oil', 'Mentha Spicata Oil']],
115
+ [363, 'Narcissus Extract', ['90064-26-9', '68917-12-4', '90064-27-0', '90064-25-8'], ['Narcissus Poeticus Extract', 'Narcissus Pseudonarcissus Flower Extract', 'Narcissus Jonquilla Extract', 'Narcissus Tazetta Extract']],
116
+ [364, 'Pelargonium Graveolens Flower Oil', ['90082-51-2', '8000-46-2'], ['Geranium Oil']],
117
+ [365, 'Pogostemon Cablin Oil', ['8014-09-3', '84238-39-1'], ['Patchouli Oil']],
118
+ [366, 'Rose Flower Oil/Extract', ['8007-01-0', '90106-38-0', '93334-48-6', '84696-47-9', '84604-12-6', '84604-13-7', '92347-25-6'], ['Rosa Damascena Flower Oil', 'Rosa Damascena Flower Extract', 'Rosa Alba Flower Oil', 'Rosa Alba Flower Extract', 'Rosa Canina Flower Oil', 'Rosa Centifolia Flower Oil', 'Rosa Centifolia Flower Extract', 'Rosa Gallica Flower Oil', 'Rosa Moschata Flower Oil', 'Rosa Rugosa Flower Oil']],
119
+ [367, 'Santalum Album Oil', ['8006-87-9', '84787-70-2'], ['Sandalwood Oil']],
120
+ [368, 'Eugenyl Acetate', ['93-28-7']],
121
+ [369, 'Geranyl Acetate', ['105-87-3']],
122
+ [370, 'Isoeugenyl Acetate', ['93-29-8']],
123
+ [371, 'Pinene', ['80-56-8', '7785-70-8', '127-91-3', '18172-67-3'], ['Alpha-Pinene', 'Beta-Pinene']],
124
+ ].map(([ref, name, cas, aka]) => ({ ref, name, cas, aka: aka || [] }));
125
+
126
+ const FL_FR_NAME_MAX = 120, FL_FR_ROWS_MAX = 200, FL_FR_PASTE_MAX = 20000; // a typed name, the rows of one table, a pasted table
127
+ const _frgKey = (s) => String(s == null ? '' : s).toLowerCase().replace(/[^a-z0-9]+/g, '');
128
+ const _frgCas = (s) => { const m = /\d{2,7}-\d{2}-\d/.exec(String(s == null ? '' : s)); return m ? m[0] : ''; };
129
+ let _frgByName = null, _frgByCas = null;
130
+ function _frgIndex() {
131
+ if (_frgByName) return;
132
+ _frgByName = new Map(); _frgByCas = new Map();
133
+ FL_FR_ALLERGENS.forEach(a => {
134
+ [a.name].concat(a.aka).forEach(n => { const k = _frgKey(n); if (k && !_frgByName.has(k)) _frgByName.set(k, a); });
135
+ a.cas.forEach(c => { if (!_frgByCas.has(c)) _frgByCas.set(c, a); }); // a CAS two entries share goes to the first
136
+ });
137
+ }
138
+ // The list entry a substance belongs to: by its name first (two citrus entries share CAS numbers), then by CAS.
139
+ function flFrAllergenFor(name, cas) {
140
+ _frgIndex();
141
+ return _frgByName.get(_frgKey(name)) || _frgByCas.get(_frgCas(cas)) || null;
142
+ }
143
+
144
+ // ── Reading an ingredient ───────────────────────────────────
145
+ const _frgNum = (v) => { const n = typeof v === 'number' ? v : parseFloat(String(v == null ? '' : v).replace(',', '.')); return Number.isFinite(n) ? n : NaN; };
146
+ // The limit rows that can be used: a known category, and a max of 0 to 100 unless the row says otherwise.
147
+ function flFrLimitRows(ing) {
148
+ const rows = ing && ing.fragranceDetails && Array.isArray(ing.fragranceDetails.ifraLimits) ? ing.fragranceDetails.ifraLimits : [];
149
+ return rows.map(r => {
150
+ if (!r || typeof r !== 'object') return null;
151
+ const raw = String(r.category == null ? '' : r.category).trim(), category = raw.toLowerCase() === 'all' ? 'all' : raw.toUpperCase();
152
+ if (category !== 'all' && !FL_FR_CATEGORIES.includes(category)) return null;
153
+ if (r.unrestricted === true) return { category, kind: 'unrestricted' };
154
+ const m = _frgNum(r.maxPct);
155
+ if (r.prohibited === true || m === 0) return { category, kind: 'prohibited', maxPct: 0 };
156
+ if (!(m > 0) || m > 100) return null;
157
+ return { category, kind: 'limit', maxPct: m };
158
+ }).filter(Boolean);
159
+ }
160
+ // This material's limit in a category: the row for that category, else its "all categories" row, else null (unknown).
161
+ function flFrIngLimit(ing, category) {
162
+ const rows = flFrLimitRows(ing);
163
+ return rows.find(r => r.category === category) || rows.find(r => r.category === 'all') || null;
164
+ }
165
+ // A material's allergen content. → { declared, auto, rows: [{ entry | null, name, cas, pct }] }
166
+ // declared: a declaration is on file (an empty one says "none"). auto: a single substance on the EU list, 100% itself.
167
+ function flFrIngAllergens(ing) {
168
+ if (ing && Array.isArray(ing.fragranceAllergens)) {
169
+ const rows = ing.fragranceAllergens.map(r => {
170
+ const pct = r ? _frgNum(r.pct) : NaN;
171
+ if (!r || !(pct > 0) || pct > 100) return null;
172
+ const entry = flFrAllergenFor(r.substance, r.cas);
173
+ return { entry, name: entry ? entry.name : (_frgText(r.substance) || _frgText(r.cas)).slice(0, FL_FR_NAME_MAX), cas: _frgCas(r.cas) || (entry ? entry.cas[0] : ''), pct };
174
+ }).filter(r => r && r.name);
175
+ return { declared: true, auto: false, rows };
176
+ }
177
+ _frgIndex();
178
+ const self = ing ? _frgByCas.get(_frgCas(ing.cas)) : null;
179
+ if (self) return { declared: true, auto: true, rows: [{ entry: self, name: self.name, cas: _frgCas(ing.cas), pct: 100 }] };
180
+ return { declared: false, auto: false, rows: [] };
181
+ }
182
+ // A fragrance material: its class or function says so, or it carries fragrance data. (A CAS on the EU list alone is
183
+ // not enough: see flFrIsListed.)
184
+ function flFrIsMaterial(ing) {
185
+ if (!ing) return false;
186
+ const fd = ing.fragranceDetails;
187
+ if ((fd && Array.isArray(fd.ifraLimits) && fd.ifraLimits.length) || Array.isArray(ing.fragranceAllergens)) return true;
188
+ // A food flavor shares the Fragrance class (the note pyramid) but is not an IFRA material until it carries IFRA data.
189
+ if (/^flavou?r/i.test(String(ing.function || '').trim())) return false;
190
+ if (ing.ingredientClass === 'fragrance' || /^fragrance$/i.test(String(ing.function || '').trim())) return true;
191
+ return !!fd;
192
+ }
193
+ // A substance on the EU list by its CAS that nothing else marks as a fragrance material: benzyl alcohol as an epoxy
194
+ // accelerator, limonene as a cleaner's solvent. It is checked only in a cosmetic or fragrance product, in a formula
195
+ // with an IFRA category, or inside a fragrance oil.
196
+ function flFrIsListed(ing) {
197
+ if (!ing) return false;
198
+ _frgIndex();
199
+ return _frgByCas.has(_frgCas(ing.cas));
200
+ }
201
+ // A cosmetic, personal-care or fragrance product, by what the formula says it is.
202
+ function flFrIsCosmetic(f) {
203
+ return !!f && /\b(cosmetics?|personal[ -]care|toiletr(?:y|ies)|fragrances?|perfume\w*|parfum|cologne|lotions?|creams?|shampoos?|conditioners?|soaps?|serums?|deodorants?|body wash|lip|makeup|skin ?care|hair ?care)\b/i
204
+ .test([f.regulatoryCategory, f.type, f.family, f.application].map(x => String(x || '')).join(' | '));
205
+ }
206
+ const _frgText = (v) => (typeof v === 'string' || typeof v === 'number') ? String(v).trim() : '';
207
+ const _frgName = (rec) => _frgText(rec && rec.name) || _frgText(rec && rec.uid) || 'Unnamed';
208
+ const _frgIng = (id) => (typeof db !== 'undefined' && db.ingredients || []).find(i => i && i.id === id) || null;
209
+ const _frgFormula = (id) => (typeof db !== 'undefined' && db.formulations || []).find(f => f && f.id === id && !f.deleted) || null;
210
+ const _frgRows = (f) => (f && Array.isArray(f.composition) ? f.composition : []).filter(c => c && (c.ingredientId || c.formulationId));
211
+ // A fragrance oil: its type or family says fragrance, or at least half of it by weight is fragrance materials added
212
+ // directly (a premix that holds an oil is not one; the oil inside it is). Every ingredient inside an oil is checked,
213
+ // its solvent included.
214
+ function flFrIsOil(f) {
215
+ if (!f) return false;
216
+ if (/fragrance|perfum|parfum|cologne|eau de/i.test(String(f.type || '') + ' ' + String(f.family || ''))) return true;
217
+ const rows = _frgRows(f);
218
+ if (!rows.length) return false;
219
+ const fr = _rowWtFractionsWithin(f, []);
220
+ let share = 0;
221
+ rows.forEach((c, i) => { if (!c.formulationId && flFrIsMaterial(_frgIng(c.ingredientId))) share += fr[i] || 0; });
222
+ return share >= 0.5 - 1e-9;
223
+ }
224
+
225
+ // ── A formula's settings ────────────────────────────────────
226
+ const FL_FR_DOSAGE_MAX = 100;
227
+ function _frgSettings(f) {
228
+ const cat = String((f && f.ifraCategory) || '').toUpperCase(), d = _frgNum(f && f.ifraDosagePct);
229
+ return {
230
+ category: FL_FR_CATEGORIES.includes(cat) ? cat : '',
231
+ use: f && _frgIsUse(f.productUse) ? f.productUse : '',
232
+ dosage: d > 0 && d <= FL_FR_DOSAGE_MAX ? d : 100,
233
+ };
234
+ }
235
+
236
+ // ── The check ───────────────────────────────────────────────
237
+ // Every leaf ingredient of the formula with its weight share of the whole, through sub-formulas. A leaf knows whether
238
+ // it sits inside a fragrance oil, and which oil (the outermost one below the formula itself) it came through.
239
+ function _frgWalk(root) {
240
+ const leaves = [], unresolved = [], oils = new Map();
241
+ const maxDepth = typeof MAX_NESTING_DEPTH !== 'undefined' ? MAX_NESTING_DEPTH : 5;
242
+ const rootOil = flFrIsOil(root);
243
+ const walk = (f, w, path, depth, inOil, oilId) => {
244
+ if (!f || !(w > 0)) return;
245
+ if (depth > maxDepth) { unresolved.push({ reason: 'depth-limit' }); return; }
246
+ const rows = _frgRows(f);
247
+ if (!rows.length) return;
248
+ const fr = _rowWtFractionsWithin(f, unresolved);
249
+ rows.forEach((c, i) => {
250
+ const x = fr[i] || 0;
251
+ if (!(x > 0)) return;
252
+ if (c.formulationId) {
253
+ if (path.includes(c.formulationId)) { unresolved.push({ reason: 'cycle' }); return; }
254
+ const child = _frgFormula(c.formulationId);
255
+ if (!child) { unresolved.push({ reason: 'deleted-subformula' }); return; }
256
+ const oil = inOil || flFrIsOil(child);
257
+ let id = oilId;
258
+ if (!id && !rootOil && oil) { id = child.id; const o = oils.get(id) || { id, name: _frgText(child.name) || _frgText(child.uid) || 'Fragrance oil', uid: _frgText(child.uid), share: 0 }; o.share += w * x; oils.set(id, o); }
259
+ walk(child, w * x, path.concat(child.id), depth + 1, oil, id);
260
+ } else leaves.push({ ingredientId: c.ingredientId, w: w * x, inOil, oilId });
261
+ });
262
+ };
263
+ walk(root, 1, [root.id], 0, rootOil, null);
264
+ return { leaves, unresolved, oils: [...oils.values()], rootOil };
265
+ }
266
+ const _FRG_EPS = 1e-9;
267
+ // → { has, category, use, dosage, rootOil, rows, others, noLimit, noDecl, noSource, unresolved, max, allergens,
268
+ // unlisted, toLabel, over, verdict: 'setup' | 'over' | 'unknown' | 'conforms', why: [text] }
269
+ // rows: one per fragrance material: { id, name, uid, pct (in the product), pctIn (in this formula), limit, status:
270
+ // 'pass' | 'over' | 'prohibited' | 'unrestricted' | 'unknown' | 'nocat', headroom, amendment, cert }
271
+ // max: [{ id | null, name, current, max, capped, limitedBy, partial }] the highest dosage that passes
272
+ // opts: { category, use, dosage } to ask "what if" without saving.
273
+ function flFrCompute(f, opts) {
274
+ const st = { ..._frgSettings(f), ...(opts || {}) };
275
+ // What-if values get the same checks as stored ones.
276
+ st.category = FL_FR_CATEGORIES.includes(String(st.category || '').toUpperCase()) ? String(st.category).toUpperCase() : '';
277
+ st.use = _frgIsUse(st.use) ? st.use : '';
278
+ st.dosage = _frgNum(st.dosage) > 0 && _frgNum(st.dosage) <= FL_FR_DOSAGE_MAX ? _frgNum(st.dosage) : 100;
279
+ const out = { has: false, category: st.category, use: st.use, dosage: st.dosage, rootOil: false, rows: [], others: [], noLimit: [], noDecl: [],
280
+ noSource: [], unresolved: 0, max: [], allergens: [], unlisted: [], toLabel: [], over: [], verdict: 'setup', why: [] };
281
+ if (!f) return out;
282
+ const wk = _frgWalk(f), k = st.dosage / 100;
283
+ out.rootOil = wk.rootOil; out.unresolved = wk.unresolved.length;
284
+ const mats = new Map(), others = new Set();
285
+ const listedCount = !!st.category || flFrIsCosmetic(f); // a listed substance counts here by its CAS alone
286
+ wk.leaves.forEach(l => {
287
+ const ing = _frgIng(l.ingredientId);
288
+ if (!ing) { out.unresolved++; return; }
289
+ if (!l.inOil && !flFrIsMaterial(ing) && !(listedCount && flFrIsListed(ing))) { others.add(_frgName(ing)); return; }
290
+ const m = mats.get(ing.id) || { ing, w: 0, byOil: new Map() };
291
+ m.w += l.w;
292
+ if (l.oilId) m.byOil.set(l.oilId, (m.byOil.get(l.oilId) || 0) + l.w);
293
+ mats.set(ing.id, m);
294
+ });
295
+ out.others = [...others].sort();
296
+ out.has = mats.size > 0;
297
+ const docOf = (ing, id) => (id && Array.isArray(ing.documents) ? ing.documents.find(d => d && d.id === id && !d.deleted) : null) || null;
298
+ const allergens = new Map(), unlisted = new Map();
299
+ mats.forEach(m => {
300
+ const ing = m.ing, name = _frgName(ing), fd = (ing.fragranceDetails && typeof ing.fragranceDetails === 'object') ? ing.fragranceDetails : {};
301
+ const pctIn = m.w * 100, pct = pctIn * k;
302
+ const limit = st.category ? flFrIngLimit(ing, st.category) : null;
303
+ const cert = docOf(ing, fd.ifraCertDocId);
304
+ let status = 'nocat', headroom = null;
305
+ if (st.category) {
306
+ if (!limit) { status = 'unknown'; out.noLimit.push(name); }
307
+ else if (limit.kind === 'unrestricted') status = 'unrestricted';
308
+ else if (limit.kind === 'prohibited') status = pct > 0 ? 'prohibited' : 'pass';
309
+ else { headroom = limit.maxPct - pct; if (Math.abs(headroom) < 1e-9) headroom = 0; status = pct <= limit.maxPct * (1 + _FRG_EPS) ? 'pass' : 'over'; }
310
+ if (limit && !cert) out.noSource.push({ name, what: 'IFRA certificate' });
311
+ }
312
+ if (status === 'over' || status === 'prohibited') out.over.push(name);
313
+ out.rows.push({ id: ing.id, name, uid: _frgText(ing.uid), pct, pctIn, limit, status, headroom, amendment: String(fd.ifraAmendment || '').trim(),
314
+ cert: cert ? { id: cert.id, name: _frgText(cert.filename) || _frgText(cert.name) || 'Certificate' } : null, byOil: m.byOil });
315
+ const al = flFrIngAllergens(ing);
316
+ if (!al.declared) { out.noDecl.push(name); return; }
317
+ const decl = docOf(ing, ing.allergenDeclDocId);
318
+ if (!al.auto && !decl) out.noSource.push({ name, what: 'allergen declaration' });
319
+ al.rows.forEach(r => {
320
+ const map = r.entry ? allergens : unlisted, key = r.entry ? r.entry.ref : _frgKey(r.name);
321
+ const a = map.get(key) || { ref: r.entry ? r.entry.ref : null, name: r.name, cas: r.cas, pct: 0, sources: [] };
322
+ const p = pct * r.pct / 100;
323
+ a.pct += p; a.sources.push({ name, pct: p, doc: decl ? (_frgText(decl.filename) || _frgText(decl.name) || 'Declaration') : al.auto ? 'the substance itself' : '' });
324
+ map.set(key, a);
325
+ });
326
+ });
327
+ // What needs attention first: over, then unknown, then the rest by how much there is.
328
+ const rank = { prohibited: 0, over: 0, unknown: 1 };
329
+ out.rows.sort((a, b) => (rank[a.status] ?? 2) - (rank[b.status] ?? 2) || b.pct - a.pct || a.name.localeCompare(b.name));
330
+ const thr = st.use ? FL_FR_LABEL_OVER[st.use] : null;
331
+ out.allergens = [...allergens.values()].map(a => ({ ...a, label: thr == null ? null : a.pct > thr * (1 + _FRG_EPS) })).sort((a, b) => b.pct - a.pct || a.name.localeCompare(b.name));
332
+ out.unlisted = [...unlisted.values()].sort((a, b) => b.pct - a.pct);
333
+ out.toLabel = out.allergens.filter(a => a.label).map(a => a.name);
334
+
335
+ // The highest dosage that passes. An oil on its own: scale the whole formula. A product holding oils: each oil's
336
+ // share, with everything else in the product left as it is.
337
+ const partial = out.noLimit.length > 0;
338
+ const best = (cands) => cands.reduce((lo, c) => (lo == null || c.max < lo.max ? c : lo), null);
339
+ if (st.category && out.has) {
340
+ if (wk.rootOil) {
341
+ const lo = best(out.rows.filter(r => r.limit && r.limit.kind !== 'unrestricted' && r.pctIn > 0).map(r => ({ max: r.limit.maxPct / r.pctIn * 100, name: r.name })));
342
+ out.max.push({ id: null, name: _frgText(f.name) || _frgText(f.uid) || 'This oil', current: st.dosage, max: lo ? Math.min(100, lo.max) : 100, capped: !lo || lo.max >= 100, limitedBy: lo && lo.max < 100 ? lo.name : '', partial });
343
+ } else wk.oils.forEach(o => {
344
+ const share = o.share * 100 * k;
345
+ const lo = best(out.rows.filter(r => r.limit && r.limit.kind !== 'unrestricted' && (r.byOil.get(o.id) || 0) > 0).map(r => {
346
+ const inOil = r.byOil.get(o.id) * 100 * k, outside = r.pct - inOil;
347
+ return { max: Math.max(0, r.limit.maxPct - outside) / (inOil / share), name: r.name };
348
+ }));
349
+ out.max.push({ id: o.id, name: o.name, uid: o.uid, current: share, max: lo ? Math.min(100, lo.max) : 100, capped: !lo || lo.max >= 100, limitedBy: lo && lo.max < 100 ? lo.name : '', partial });
350
+ });
351
+ }
352
+
353
+ const n = (a, one, many) => a.length + ' ' + (a.length === 1 ? one : many);
354
+ if (!st.category) out.why.push('Choose the product category.');
355
+ if (!st.use) out.why.push('Choose leave-on or rinse-off.');
356
+ if (out.over.length) out.why.push(n(out.over, 'material is', 'materials are') + ' over the limit.');
357
+ if (out.noLimit.length) out.why.push(n(out.noLimit, 'material has', 'materials have') + ' no limit on file for category ' + st.category + '.');
358
+ if (out.noDecl.length) out.why.push(n(out.noDecl, 'material has', 'materials have') + ' no allergen declaration.');
359
+ if (out.noSource.length) out.why.push(n(out.noSource, 'entry has', 'entries have') + ' no source document.');
360
+ if (out.unresolved) out.why.push('Part of the composition could not be weighed.');
361
+ out.verdict = !st.category ? 'setup' : out.over.length ? 'over'
362
+ : (!st.use || out.noLimit.length || out.noDecl.length || out.noSource.length || out.unresolved) ? 'unknown' : 'conforms';
363
+ return out;
364
+ }
365
+ // A food, drink or supplement: IFRA and the cosmetic allergen list do not apply to it.
366
+ function flFrIsFood(f) {
367
+ return !!f && /\b(food|foods|beverage|beverages|drink|drinks|supplement|supplements|nutrition|nutritional|confectionery|bakery|dairy)\b/i
368
+ .test([f.regulatoryCategory, f.type, f.family, f.application].map(x => String(x || '')).join(' | '));
369
+ }
370
+ // Shows the Fragrance tab: the formula already has a category, or it holds a fragrance material and is not a food.
371
+ function flFrHasData(f) {
372
+ try { return !!f && (!!_frgSettings(f).category || (!flFrIsFood(f) && flFrCompute(f).has)); } catch (_) { return false; }
373
+ }
374
+ // Any fragrance material in the workspace: the formula form offers the category then.
375
+ function flFrLabUsesFragrance() {
376
+ try { return (db.ingredients || []).some(i => i && !i.deleted && flFrIsMaterial(i)); } catch (_) { return false; }
377
+ }
378
+
379
+ // ── Phase 3: finding the sources ────────────────────────────
380
+ // The names an ingredient's allergen content goes by: the label names, for the list filter and the smart query.
381
+ function flFrIngAllergenNames(ing) {
382
+ try { return [...new Set(flFrIngAllergens(ing).rows.map(r => r.name).filter(Boolean))]; } catch (_) { return []; }
383
+ }
384
+ // Fields a smart query can use on the Ingredients list (js/views/theoretical-params.js _tpIngredientView):
385
+ // fragranceAllergens contains linalool ifra5A < 0.5 ifra4 == 0 (prohibited)
386
+ // An ifra field is the material's max % in that category; absent where it has no row or is not restricted.
387
+ function flFrViewFields(ing) {
388
+ const out = {};
389
+ try {
390
+ const names = flFrIngAllergenNames(ing);
391
+ if (names.length) out.fragranceAllergens = names.join(', ');
392
+ flFrLimitRows(ing).forEach(r => { if (r.category !== 'all' && r.kind !== 'unrestricted') out['ifra' + r.category] = r.kind === 'prohibited' ? 0 : r.maxPct; });
393
+ } catch (_) {}
394
+ return out;
395
+ }
396
+ // Every allergen named anywhere in the library, for the filter's chips.
397
+ function flFrLibraryAllergens() {
398
+ const out = new Set();
399
+ try { (db.ingredients || []).forEach(i => { if (i && !i.deleted) flFrIngAllergenNames(i).forEach(n => out.add(n)); }); } catch (_) {}
400
+ return [...out].sort((a, b) => a.localeCompare(b));
401
+ }
402
+ // The plain search box: "linalool" also finds the materials that contain it (by label name, another name, or CAS).
403
+ function flFrIngSearchHit(ing, q) {
404
+ const k = _frgKey(q);
405
+ if (k.length < 3) return false;
406
+ try {
407
+ return flFrIngAllergens(ing).rows.some(r => _frgKey(r.name).includes(k) || (r.cas && r.cas.replace(/-/g, '').includes(k))
408
+ || (r.entry && (r.entry.aka.some(a => _frgKey(a).includes(k)) || r.entry.cas.some(c => c === String(q).trim()))));
409
+ } catch (_) { return false; }
410
+ }
411
+ // From the Fragrance tab: open the Ingredients list filtered to the materials that contain this allergen.
412
+ function flFrFindSources(name) {
413
+ if (typeof _ingFilters === 'undefined' || !_ingFilters.frAllergen || typeof _ingFilters.frAllergen.add !== 'function') return;
414
+ if (typeof clearIngFilters === 'function') { try { clearIngFilters(); } catch (_) {} }
415
+ _ingFilters.frAllergen.add(String(name));
416
+ if (typeof _ingSearchQuery !== 'undefined') _ingSearchQuery = '';
417
+ if (typeof _persistIngFilters === 'function') _persistIngFilters();
418
+ if (typeof navigate === 'function') navigate('ingredients');
419
+ }
420
+
421
+ // ── Phase 3: the statement ──────────────────────────────────
422
+ // One plain object behind the report, the print sheet, the assistant and the MCP tool, so they cannot disagree with
423
+ // the tab. It is a conformity statement only when the verdict is "conforms"; otherwise it says what stands in the way.
424
+ // → null when the formula has no fragrance to check, else { state: 'conforms' | 'over' | 'incomplete', heading,
425
+ // statement, basis, category, categoryWords, use, dosage, asSold, amendments, maxDosage, materials, documents,
426
+ // reasons, allergens: { use, threshold, complete, toLabel, rows, missing } }
427
+ const FL_FR_BASIS = 'Based on the certificates and declarations on file. Not a certification.';
428
+ function flFrSummary(f, opts) {
429
+ if (!f || !flFrHasData(f)) return null;
430
+ const c = flFrCompute(f, opts);
431
+ if (!c.has) return null;
432
+ const name = _frgText(f.name) || _frgText(f.uid) || 'This formula';
433
+ const where = c.category ? `IFRA category ${c.category}${FL_FR_CAT_WORDS[c.category] ? ' (' + FL_FR_CAT_WORDS[c.category] + ')' : ''}` : '';
434
+ const at = c.rootOil ? ` at ${_frgPct(c.dosage)}% in the finished product` : '';
435
+ const state = c.verdict === 'conforms' ? 'conforms' : c.verdict === 'over' ? 'over' : 'incomplete';
436
+ const limitText = (r) => !r.limit ? 'No limit on file' : r.limit.kind === 'unrestricted' ? 'Not restricted' : r.limit.kind === 'prohibited' ? 'Prohibited' : _frgPct(r.limit.maxPct) + '%';
437
+ const statusText = { pass: 'Pass', over: 'Over', prohibited: 'Prohibited', unrestricted: 'Not restricted', unknown: 'No limit on file', nocat: 'Not checked' };
438
+ const materials = c.rows.map(r => ({ name: r.name, pctInProduct: +r.pct.toPrecision(6), limit: limitText(r), maxPct: r.limit && r.limit.kind !== 'unrestricted' ? r.limit.maxPct : null,
439
+ status: statusText[r.status], amendment: r.amendment || '', document: r.cert ? r.cert.name : '' }));
440
+ const amendments = [...new Set(c.rows.map(r => r.amendment).filter(Boolean))];
441
+ const documents = [...new Set(c.rows.filter(r => r.cert).map(r => `${r.name}: ${r.cert.name}`))];
442
+ const thr = c.use ? FL_FR_LABEL_OVER[c.use] : null;
443
+ return {
444
+ state,
445
+ heading: state === 'conforms' ? 'IFRA conformity statement' : state === 'over' ? 'IFRA check: does not conform' : 'IFRA check: incomplete',
446
+ statement: state === 'conforms' ? `${name} conforms to the IFRA limits on file for ${where}${at}.`
447
+ : state === 'over' ? `${name} does not conform in ${where}${at}: ${c.over.join(', ')} ${c.over.length === 1 ? 'is' : 'are'} over the limit.`
448
+ : `No conformity statement can be made for ${name}${where ? ' in ' + where + at : ''}. ${c.why.join(' ')}`,
449
+ basis: FL_FR_BASIS,
450
+ category: c.category, categoryWords: FL_FR_CAT_WORDS[c.category] || '', use: c.use, dosage: c.dosage, asSold: !c.rootOil || c.dosage === 100,
451
+ amendments,
452
+ maxDosage: c.max.map(m => ({ of: m.name, currentPct: +m.current.toPrecision(6), maxPct: +m.max.toPrecision(6), anyDosage: !!m.capped, limitedBy: m.limitedBy, partial: !!m.partial })),
453
+ materials, documents,
454
+ reasons: c.why.slice(),
455
+ unknown: { noLimit: c.noLimit.slice(), noDeclaration: c.noDecl.slice(), noSourceDocument: c.noSource.map(x => `${x.name} (${x.what})`), notChecked: c.others.slice() },
456
+ allergens: {
457
+ use: c.use, threshold: thr, complete: !c.noDecl.length && !!c.use,
458
+ toLabel: c.toLabel.slice(),
459
+ rows: c.allergens.map(a => ({ name: a.name, cas: a.cas, pctInProduct: +a.pct.toPrecision(6), label: a.label, from: a.sources.map(x => x.name) })),
460
+ notOnEuList: c.unlisted.map(a => ({ name: a.name, cas: a.cas, pctInProduct: +a.pct.toPrecision(6) })),
461
+ missing: c.noDecl.slice(),
462
+ },
463
+ };
464
+ }
465
+ // The two blocks as HTML for a printed page. `table(headers, rows)` draws a table in the page's own style.
466
+ function _frgStatementBlocks(f, table) {
467
+ const s = flFrSummary(f);
468
+ if (!s) return null;
469
+ const e = _frgEsc, p = (v) => _frgPct(v) + '%';
470
+ const max = s.maxDosage.map(m => m.maxPct <= 0 ? `${e(m.of)}: no dosage passes (limited by ${e(m.limitedBy)}).`
471
+ : m.anyDosage ? `${e(m.of)}: passes at any dosage.` : `${e(m.of)}: passes up to ${p(m.maxPct)}, limited by ${e(m.limitedBy)}.`).join(' ');
472
+ const ifra = `<p class="fr-st fr-st-${s.state}"><strong>${e(s.statement)}</strong></p>
473
+ <p class="muted">${e(s.basis)}${s.amendments.length ? ' IFRA amendment cited: ' + e(s.amendments.join(', ')) + '.' : ''}${s.use ? ' Product use: ' + e(FL_FR_USES[s.use].toLowerCase()) + '.' : ''}</p>
474
+ ${max ? `<p class="muted">Highest dosage${s.maxDosage.some(m => m.partial) ? ' (among the materials with a limit on file)' : ''}: ${max}</p>` : ''}
475
+ ${table([{ t: 'Material', i: 'name' }, { t: 'In product', i: 'pct', num: true }, { t: 'Limit', i: 'limit', num: true }, { t: 'Status', i: 'status' }, { t: 'Amendment', i: 'amendment' }, { t: 'Source document', i: 'document' }],
476
+ s.materials.map(m => ({ name: m.name, pct: p(m.pctInProduct), limit: m.limit, status: m.status, amendment: m.amendment || '—', document: m.document || 'None on file' })))}
477
+ ${s.unknown.notChecked.length ? `<p class="muted">Not fragrance materials, not checked: ${e(s.unknown.notChecked.join(', '))}.</p>` : ''}`;
478
+ const a = s.allergens;
479
+ const lead = !a.use ? 'Leave-on or rinse-off is not set on the formula, so the label column cannot be decided.'
480
+ : a.toLabel.length ? `To name on the label (above ${a.threshold}% in a ${a.use} product): ${a.toLabel.join(', ')}.` : `None above ${a.threshold}% in a ${a.use} product.`;
481
+ const rows = a.rows.map(r => ({ name: r.name, cas: r.cas || '—', pct: p(r.pctInProduct), label: r.label == null ? '—' : r.label ? 'Label' : 'Below', from: r.from.join(', ') }))
482
+ .concat(a.notOnEuList.map(r => ({ name: r.name, cas: r.cas || '—', pct: p(r.pctInProduct), label: 'Not on the EU list', from: '' })));
483
+ const allergens = `<p class="fr-st"><strong>${e(lead)}</strong></p>
484
+ ${a.missing.length ? `<p class="fr-st fr-st-incomplete"><strong>Incomplete:</strong> no allergen declaration on file for ${e(a.missing.join(', '))}.</p>` : ''}
485
+ ${rows.length ? table([{ t: 'Allergen', i: 'name' }, { t: 'CAS', i: 'cas' }, { t: 'In product', i: 'pct', num: true }, { t: 'Label', i: 'label' }, { t: 'From', i: 'from' }], rows) : '<p class="muted">No regulated allergens declared.</p>'}
486
+ <p class="muted">EU fragrance allergens: Annex III of Regulation (EC) No 1223/2009. ${e(s.basis)}</p>`;
487
+ return { s, ifra, allergens };
488
+ }
489
+ const _frgPlainTable = (cls) => (headers, rows) => `<table class="${cls}"><thead><tr>${headers.map(h => `<th${h.num ? ' class="num"' : ''}>${_frgEsc(h.t)}</th>`).join('')}</tr></thead><tbody>${rows.map(r => `<tr>${headers.map(h => `<td${h.num ? ' class="num"' : ''}>${_frgEsc(r[h.i] == null ? '—' : r[h.i])}</td>`).join('')}</tr>`).join('')}</tbody></table>`;
490
+ // Sections for the Formula Dossier (js/report-engine.js) and the print sheet (js/views/formulations-print.js). Pro,
491
+ // like the tab: [] on Free, and [] for a formula with no fragrance to check.
492
+ function flFrReportSections(f, which) {
493
+ if (!_frgPro()) return [];
494
+ let b = null;
495
+ try { b = _frgStatementBlocks(f, typeof _rTable === 'function' ? _rTable : _frgPlainTable('grid')); } catch (_) { return []; }
496
+ if (!b) return [];
497
+ const out = [];
498
+ if (!which || which.ifra) out.push({ title: b.s.heading, html: b.ifra });
499
+ if (!which || which.allergens) out.push({ title: 'Fragrance allergen declaration', html: b.allergens });
500
+ return out;
501
+ }
502
+ function flFrPrintSectionsHtml(f, which) {
503
+ if (!_frgPro()) return [];
504
+ const b = _frgStatementBlocks(f, _frgPlainTable('grid'));
505
+ if (!b) return [];
506
+ return [which.ifra ? { title: b.s.heading, html: b.ifra } : null, which.allergens ? { title: 'Fragrance allergen declaration', html: b.allergens } : null].filter(Boolean);
507
+ }
508
+ // One line for the assistant's context (js/gemini.js), under the formula. Pro, like the tab.
509
+ function flFrAiLine(f) {
510
+ try {
511
+ if (!_frgPro()) return '';
512
+ const s = flFrSummary(f);
513
+ if (!s) return '';
514
+ const max = s.maxDosage.map(m => `${m.of} max ${m.maxPct <= 0 ? '0 (no dosage passes)' : m.anyDosage ? 'any dosage' : _frgPct(m.maxPct) + '%'}${m.limitedBy ? ' limited by ' + m.limitedBy : ''}${s.asSold ? '' : ''}`).join('; ');
515
+ const mats = s.materials.slice(0, 12).map(m => `${m.name} ${_frgPct(m.pctInProduct)}% vs ${m.limit}${m.status === 'Pass' || m.status === 'Not restricted' ? '' : ' [' + m.status + ']'}`).join(', ');
516
+ const al = s.allergens;
517
+ return `${s.statement} ${max ? 'Max dosage: ' + max + '. ' : ''}Materials (% in product vs limit): ${mats}${s.materials.length > 12 ? ` (+${s.materials.length - 12} more)` : ''}.`
518
+ + (al.use ? ` Allergens to label (${al.use}, above ${al.threshold}%): ${al.toLabel.length ? al.toLabel.join(', ') : 'none'}${al.missing.length ? ` [incomplete: ${al.missing.length} without a declaration]` : ''}.` : ' Allergen labelling undecided: leave-on or rinse-off not set.')
519
+ + ` ${s.basis}`;
520
+ } catch (_) { return ''; }
521
+ }
522
+
523
+ // ── Pasted tables ───────────────────────────────────────────
524
+ // An IFRA certificate's category table: "Category 5A 0.50 %", "4: 1.2", "12 No restriction", "6 Prohibited".
525
+ // → { rows: [limit row], skipped: lines that looked like data but could not be read }
526
+ function flFrParseLimits(text) {
527
+ const rows = [], seen = new Set();
528
+ let skipped = 0;
529
+ String(text || '').slice(0, FL_FR_PASTE_MAX).split(/\r?\n/).forEach(line => {
530
+ if (!line.trim()) return;
531
+ const m = /^\s*(?:(?:IFRA\s+)?(?:cat(?:egory)?|class)\.?\s*)?(1[0-2]|[1-9])\s*([A-Da-d])?(?:\s*[:\-–|;\t]\s*|\s+)(.*)$/i.exec(line);
532
+ if (!m) { if (/\d/.test(line)) skipped++; return; }
533
+ const category = m[1] + (m[2] || '').toUpperCase(), rest = m[3];
534
+ if (!FL_FR_CATEGORIES.includes(category) || seen.has(category)) { skipped++; return; }
535
+ let row = null;
536
+ if (/prohibit|not permitted|not allowed|banned/i.test(rest)) row = { category, prohibited: true };
537
+ else if (/no restriction|not restricted|unrestricted|no limit|not limited/i.test(rest)) row = { category, unrestricted: true };
538
+ else { const v = /(\d+(?:[.,]\d+)?)\s*%?/.exec(rest), x = v ? _frgNum(v[1]) : NaN; if (x === 0) row = { category, prohibited: true }; else if (x > 0 && x <= 100) row = { category, maxPct: x }; }
539
+ if (!row) { skipped++; return; }
540
+ seen.add(category); rows.push(row);
541
+ });
542
+ return { rows, skipped };
543
+ }
544
+ // An allergen declaration's table: a name, a CAS number and a percent on each line, in any order.
545
+ function flFrParseAllergens(text) {
546
+ const rows = [];
547
+ let skipped = 0;
548
+ String(text || '').slice(0, FL_FR_PASTE_MAX).split(/\r?\n/).forEach(line => {
549
+ if (!line.trim() || rows.length >= FL_FR_ROWS_MAX) return;
550
+ const cas = _frgCas(line), rest = cas ? line.replace(cas, ' ') : line;
551
+ const nums = [...rest.matchAll(/(?:^|[\s|;:\t(<])(\d+(?:[.,]\d+)?)\s*%?(?=$|[\s|;)\t])/g)];
552
+ const last = nums[nums.length - 1], pct = last ? _frgNum(last[1]) : NaN;
553
+ const name = (last ? rest.slice(0, last.index) : rest).replace(/[|;\t]+/g, ' ').replace(/\s+/g, ' ').replace(/^[\s:,-]+|[\s:,-]+$/g, '');
554
+ if (!(pct > 0) || pct > 100 || !(name || cas)) { if (/\d/.test(line) && !/cas|%\s*$|percent/i.test(line)) skipped++; return; }
555
+ const entry = flFrAllergenFor(name, cas);
556
+ rows.push({ substance: entry ? entry.name : name.slice(0, FL_FR_NAME_MAX), cas: cas || (entry ? entry.cas[0] : ''), pct });
557
+ });
558
+ return { rows, skipped };
559
+ }
560
+
561
+ // ── Formatting ──────────────────────────────────────────────
562
+ function _frgPct(v) {
563
+ if (v == null || !Number.isFinite(v)) return '—';
564
+ if (v === 0) return '0';
565
+ const a = Math.abs(v);
566
+ const s = a >= 10 ? v.toFixed(1) : a >= 1 ? v.toFixed(2) : a >= 0.01 ? v.toFixed(3) : v.toFixed(Math.min(8, 1 - Math.floor(Math.log10(a))));
567
+ return s.includes('.') ? s.replace(/0+$/, '').replace(/\.$/, '') : s;
568
+ }
569
+ const _frgCatText = (c) => c ? c + (FL_FR_CAT_WORDS[c] ? ' · ' + FL_FR_CAT_WORDS[c] : '') : '';
570
+ const _frgPro = () => typeof hasFeature !== 'function' || hasFeature('formulations.fragranceCompliance');
571
+ const _frgEsc = (s) => typeof esc === 'function' ? esc(s) : String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
572
+
573
+ // ── The formula's Fragrance tab (Pro) ───────────────────────
574
+ function flFrTabButtonHtml(f) {
575
+ if (!f || !flFrHasData(f)) return '';
576
+ return `<div class="tab" data-tab="fragrance" onclick="switchFormTab('fragrance')">Fragrance${_frgPro() ? '' : ' <span class="asm-designer-pro-badge usda-pro">Pro</span>'}</div>`;
577
+ }
578
+ const _FRG_STATUS = { pass: ['green', 'Pass'], over: ['red', 'Over'], prohibited: ['red', 'Prohibited'], unrestricted: ['green', 'Not restricted'], unknown: ['amber', 'No limit on file'], nocat: ['gray', ''] };
579
+ function _frgVerdictHtml(c) {
580
+ const at = c.rootOil ? ` at ${_frgPct(c.dosage)}%` : '';
581
+ if (c.verdict === 'conforms') return `<div class="fr-verdict ok"><strong>Conforms in category ${_frgEsc(c.category)}${at}.</strong> Every material is within the limit on file.</div>`;
582
+ if (c.verdict === 'over') return `<div class="fr-verdict bad"><strong>Over the limit in category ${_frgEsc(c.category)}${at}.</strong> ${_frgEsc(c.over.slice(0, 4).join(', '))}${c.over.length > 4 ? ` and ${c.over.length - 4} more` : ''}.</div>`;
583
+ if (c.verdict === 'setup') return `<div class="fr-verdict warn"><strong>No verdict yet.</strong> ${_frgEsc(c.why.join(' '))}</div>`;
584
+ return `<div class="fr-verdict warn"><strong>Not confirmed${c.category ? ' in category ' + _frgEsc(c.category) + at : ''}.</strong> ${_frgEsc(c.why.join(' '))}</div>`;
585
+ }
586
+ function _frgMaxHtml(c) {
587
+ if (!c.max.length) return '';
588
+ return c.max.map(m => {
589
+ const part = m.partial ? ' <span class="fr-dim">Among the materials with a limit on file.</span>' : '';
590
+ const who = c.rootOil ? '' : `<span class="fr-max-who" translate="no">${_frgEsc(m.name)}</span> `;
591
+ const now = c.rootOil ? '' : ` Now ${_frgPct(m.current)}%.`;
592
+ const body = m.max <= 0 ? `${who}<strong>No dosage passes</strong> in category ${_frgEsc(c.category)}. Limited by ${_frgEsc(m.limitedBy)}.`
593
+ : m.capped ? `${who}<strong>Passes at any dosage</strong> in category ${_frgEsc(c.category)}.${now}`
594
+ : `${who}Passes in category ${_frgEsc(c.category)} up to <strong class="fl-val">${_frgPct(m.max)}%</strong>. Limited by ${_frgEsc(m.limitedBy)}.${now}`;
595
+ return `<div class="fr-max ${m.max + 1e-9 < m.current ? 'bad' : ''}">${body}${part}</div>`;
596
+ }).join('');
597
+ }
598
+ function _frgSourceHtml(r) {
599
+ if (!r.limit) return '<span class="fr-dim">—</span>';
600
+ const am = r.amendment ? _frgEsc(r.amendment) : ''; // the column is under the IFRA card: "51st" says enough
601
+ if (!r.cert) return `${am ? am + ' · ' : ''}<span class="fr-warn">no certificate</span>`;
602
+ return `${am ? am + ' · ' : ''}<a class="fr-doc" onclick="downloadIngredientDoc('${escJsAttr(r.id)}','${escJsAttr(r.cert.id)}',true)">${_frgEsc(r.cert.name)}</a>`;
603
+ }
604
+ function _frgIfraTableHtml(c) {
605
+ const body = c.rows.map(r => {
606
+ const [cls, word] = _FRG_STATUS[r.status];
607
+ const lim = !r.limit ? '—' : r.limit.kind === 'unrestricted' ? 'None' : r.limit.kind === 'prohibited' ? '0' : _frgPct(r.limit.maxPct) + '%';
608
+ return `<tr><td><a class="fr-name" translate="no" onclick="navigate('ingredient-detail','${escJsAttr(r.id)}')">${_frgEsc(r.name)}</a></td>
609
+ <td class="num">${_frgPct(r.pct)}%</td><td class="num">${lim}</td>
610
+ <td class="num">${r.headroom == null ? '' : (r.headroom < 0 ? '−' : '') + _frgPct(Math.abs(r.headroom)) + '%'}</td>
611
+ <td>${word ? `<span class="badge badge-${cls}">${word}</span>` : ''}</td><td class="fr-src fr-nw">${_frgSourceHtml(r)}</td></tr>`;
612
+ }).join('');
613
+ return `<div class="table-wrapper"><table class="fr-table fl-band"><thead><tr><th>Material</th><th class="num">In product</th><th class="num">Limit</th><th class="num">Headroom</th><th>Status</th><th>Source</th></tr></thead><tbody>${body}</tbody></table></div>`;
614
+ }
615
+ function _frgAllergenTableHtml(c) {
616
+ if (!c.allergens.length && !c.unlisted.length) return `<div class="fr-dim">${c.noDecl.length ? 'No allergens on the declarations on file.' : 'No regulated allergens declared.'}</div>`;
617
+ const src = (a) => a.sources.slice().sort((x, y) => y.pct - x.pct).map(s => `${_frgEsc(s.name)} ${_frgPct(s.pct)}%`).join(', ');
618
+ const row = (a, listed) => `<tr><td translate="no">${listed ? `<a class="fr-name" onclick="flFrFindSources('${escJsAttr(a.name)}')">${_frgEsc(a.name)}</a>` : _frgEsc(a.name)}</td><td class="fr-cas" translate="no">${_frgEsc(a.cas)}</td><td class="num">${_frgPct(a.pct)}%</td>
619
+ <td>${!listed ? '<span class="badge badge-gray">Not on the EU list</span>' : a.label == null ? '' : a.label ? '<span class="badge badge-amber">Label</span>' : '<span class="badge badge-gray">Below</span>'}</td><td class="fr-src">${src(a)}</td></tr>`;
620
+ return `<div class="table-wrapper"><table class="fr-table fl-band"><thead><tr><th>Allergen</th><th>CAS</th><th class="num">In product</th><th>${c.use ? _frgEsc(FL_FR_USES[c.use]) : 'Label'}</th><th>From</th></tr></thead>
621
+ <tbody>${c.allergens.map(a => row(a, true)).join('')}${c.unlisted.map(a => row(a, false)).join('')}</tbody></table></div>`;
622
+ }
623
+ function _frgUnknownsHtml(c) {
624
+ const list = (a) => `<span translate="no">${_frgEsc(a.slice(0, 12).join(', '))}${a.length > 12 ? ` and ${a.length - 12} more` : ''}</span>`;
625
+ const parts = [];
626
+ if (c.noLimit.length) parts.push(`<div><strong>No limit on file for category ${_frgEsc(c.category)}:</strong> ${list(c.noLimit)}</div>`);
627
+ if (c.noDecl.length) parts.push(`<div><strong>No allergen declaration:</strong> ${list(c.noDecl)}</div>`);
628
+ if (c.noSource.length) parts.push(`<div><strong>No source document:</strong> ${list(c.noSource.map(s => `${s.name} (${s.what})`))}</div>`);
629
+ 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>');
630
+ if (!parts.length) return '';
631
+ return `<div class="card"><div class="card-header"><h2>Unknown</h2></div><div class="card-body fr-unknowns">${parts.join('')}
632
+ <div class="fr-dim">Add the limits, the declaration, and their documents on each ingredient (Edit, Fragrance details).</div></div></div>`;
633
+ }
634
+ function _frgControlsHtml(f, c) {
635
+ const id = escJsAttr(f.id), st = _frgSettings(f); // inside '…' in an onclick: quotes and backslashes too
636
+ const seg = (u) => `<button type="button" class="fl-seg${c.use === u ? ' on' : ''}" aria-pressed="${c.use === u}" onclick="flFrSet('${id}','use','${u}')">${FL_FR_USES[u]}</button>`;
637
+ return `<div class="card"><div class="card-header"><h2>Product</h2><span id="fr-saved" class="fl-saved-tick" role="status"></span></div>
638
+ <div class="card-body nl-form fr-form-side">
639
+ <label>IFRA category<select id="fr-cat-in" onchange="flFrSet('${id}','category',this.value)"><option value="">Choose…</option>${FL_FR_CATEGORIES.map(k => `<option value="${k}"${c.category === k ? ' selected' : ''}>${_frgEsc(_frgCatText(k))}</option>`).join('')}</select></label>
640
+ <label>Product use<span class="nl-unit"><span class="fl-seg-group sm" role="group" aria-label="Product use">${seg('leave-on')}${seg('rinse-off')}</span></span></label>
641
+ ${c.rootOil ? `<label data-tip="How much of this oil goes into the finished product. 100 checks it as sold.">Dosage in the product<span class="nl-unit"><input id="fr-dose-in" type="number" min="0" max="100" step="any" inputmode="decimal" value="${st.dosage !== 100 ? _frgEsc(String(st.dosage)) : ''}" placeholder="100" onchange="flFrSet('${id}','dosage',this.value)"><em>%</em></span></label>` : ''}
642
+ ${c.others.length ? `<div class="fr-dim" data-tip="${_frgEsc(c.others.slice(0, 12).join(', ') + (c.others.length > 12 ? ` +${c.others.length - 12} more` : ''))}">${c.others.length} other ${c.others.length === 1 ? 'ingredient is' : 'ingredients are'} not fragrance materials. Not checked.</div>` : ''}
643
+ </div></div>`;
644
+ }
645
+ function flFrTabHtml(f) {
646
+ if (!f || !flFrHasData(f)) return '';
647
+ const c = flFrCompute(f);
648
+ if (!_frgPro()) {
649
+ return `<div class="card nl-tease"><div class="card-body"><div class="nl-tease-card">
650
+ <div class="nl-tease-t">Fragrance compliance <span class="asm-designer-pro-badge usda-pro">Pro</span></div>
651
+ <div class="nl-tease-s">${c.rows.length ? `${c.rows.length} fragrance ${c.rows.length === 1 ? 'material' : 'materials'} to check against IFRA.` : 'IFRA limits and allergens for this formula.'}</div>
652
+ <button class="btn btn-primary btn-sm" onclick="proUpsell('formulations.fragranceCompliance')">See what Pro adds</button>
653
+ </div></div></div>`;
654
+ }
655
+ if (!c.has) return `<div class="fr-wrap"><div class="fr-side">${_frgControlsHtml(f, c)}</div><div class="fr-main"><div class="card"><div class="card-body"><div class="fr-verdict warn"><strong>No fragrance materials on this formula.</strong> Add them on the Composition tab.</div></div></div></div></div>`;
656
+ return `<div class="fr-wrap">
657
+ <div class="fr-side">${_frgControlsHtml(f, c)}${_frgUnknownsHtml(c)}</div>
658
+ <div class="fr-main">
659
+ <div class="card"><div class="card-header"><h2>IFRA</h2></div>
660
+ <div class="card-body">${_frgVerdictHtml(c)}${_frgMaxHtml(c)}${_frgIfraTableHtml(c)}</div></div>
661
+ <div class="card"><div class="card-header"><h2>Allergens <span class="nl-sub">EU</span></h2></div>
662
+ <div class="card-body">${c.use ? `<div class="fr-dim fr-lead">${c.toLabel.length ? `<strong>${c.toLabel.length} to name on the label</strong> (above ${FL_FR_LABEL_OVER[c.use]}% ${c.use}).` : `None above ${FL_FR_LABEL_OVER[c.use]}% ${c.use}.`}${c.noDecl.length ? ' Incomplete: ' + c.noDecl.length + ' without a declaration.' : ''}</div>` : '<div class="fr-dim fr-lead">Choose leave-on or rinse-off to see which to label.</div>'}
663
+ ${_frgAllergenTableHtml(c)}
664
+ <div class="fr-dim fr-legal">Based on the certificates and declarations on file. Not a certification.</div></div></div>
665
+ </div>
666
+ </div>`;
667
+ }
668
+ function flFrRepaint() {
669
+ const el = document.getElementById('tab-fragrance'), f = el && _frgFormula(el.dataset.fid);
670
+ if (!f || !el || el.contains(document.activeElement)) return;
671
+ el.innerHTML = flFrTabHtml(f);
672
+ }
673
+ // Save the category, the use or the dosage on the formula, then redraw the tab.
674
+ function flFrSet(fid, key, value) {
675
+ const f = _frgFormula(fid);
676
+ if (!f || !['category', 'use', 'dosage'].includes(key)) return;
677
+ if (key === 'category') { const v = String(value || '').toUpperCase(); if (FL_FR_CATEGORIES.includes(v)) f.ifraCategory = v; else delete f.ifraCategory; }
678
+ else if (key === 'use') { if (_frgIsUse(value)) f.productUse = value; else delete f.productUse; }
679
+ else {
680
+ const n = _frgNum(value);
681
+ if (n > 0 && n < FL_FR_DOSAGE_MAX) f.ifraDosagePct = n;
682
+ else { delete f.ifraDosagePct; if (String(value == null ? '' : value).trim() && n !== 100 && typeof toast === 'function') toast('Dosage: above 0, up to 100 %.'); }
683
+ }
684
+ const saved = typeof _fmlSyncSave === 'function' && _fmlSyncSave(f, [key === 'category' ? 'ifraCategory' : key === 'use' ? 'productUse' : 'ifraDosagePct']);
685
+ const el = typeof document !== 'undefined' ? document.getElementById('tab-fragrance') : null;
686
+ if (el) el.innerHTML = flFrTabHtml(f);
687
+ const ov = typeof document !== 'undefined' ? document.getElementById('fr-overview') : null;
688
+ if (ov) ov.outerHTML = flFrOverviewHtml(f);
689
+ const tick = typeof document !== 'undefined' ? document.getElementById('fr-saved') : null;
690
+ if (tick && saved) { tick.textContent = 'Saved'; setTimeout(() => { const t = document.getElementById('fr-saved'); if (t) t.textContent = ''; }, 1500); }
691
+ }
692
+
693
+ // ── Formula: Overview fields and the edit form (free) ───────
694
+ function flFrOverviewHtml(f) {
695
+ const st = _frgSettings(f);
696
+ if (!st.category && !st.use && !(f && flFrHasData(f))) return '';
697
+ let line = '';
698
+ if (_frgPro() && flFrHasData(f)) {
699
+ const c = flFrCompute(f);
700
+ if (c.has) {
701
+ const [cls, word] = c.verdict === 'conforms' ? ['green', 'Conforms'] : c.verdict === 'over' ? ['red', `${c.over.length} over the limit`]
702
+ : c.verdict === 'setup' ? ['amber', 'Category not set'] : ['amber', 'Not confirmed'];
703
+ line = `<div class="detail-field"><div class="label">Fragrance compliance</div><div class="value"><a class="badge badge-${cls} fr-link" onclick="switchFormTab('fragrance')">${word}</a>${c.toLabel.length ? ` <span class="fr-dim">${c.toLabel.length} ${c.toLabel.length === 1 ? 'allergen' : 'allergens'} to label</span>` : ''}</div></div>`;
704
+ }
705
+ }
706
+ return `<div id="fr-overview" style="display:contents">
707
+ ${st.category ? `<div class="detail-field"><div class="label">IFRA category</div><div class="value">${_frgEsc(_frgCatText(st.category))}</div></div>` : ''}
708
+ ${st.use ? `<div class="detail-field"><div class="label">Product use</div><div class="value">${FL_FR_USES[st.use]}</div></div>` : ''}
709
+ ${st.dosage !== 100 ? `<div class="detail-field"><div class="label">Fragrance dosage</div><div class="value">${_frgPct(st.dosage)}% in the product</div></div>` : ''}
710
+ ${line}</div>`;
711
+ }
712
+ function flFrFormulaFieldsHtml(f) {
713
+ const st = _frgSettings(f);
714
+ if (!st.category && !st.use && !flFrLabUsesFragrance()) return '';
715
+ return `<div class="form-group">
716
+ <label data-tip="The finished product this formula is, or goes into. Each material's IFRA limit is read for it.">IFRA category</label>
717
+ <select id="ff-ifra-cat"><option value="">None</option>${FL_FR_CATEGORIES.map(k => `<option value="${k}"${st.category === k ? ' selected' : ''}>${_frgEsc(_frgCatText(k))}</option>`).join('')}</select>
718
+ </div>
719
+ <div class="form-group">
720
+ <label data-tip="Sets when a fragrance allergen must be named on the label: above 0.001% leave-on, 0.01% rinse-off.">Product use</label>
721
+ <select id="ff-product-use"><option value="">None</option>${Object.keys(FL_FR_USES).map(k => `<option value="${k}"${st.use === k ? ' selected' : ''}>${FL_FR_USES[k]}</option>`).join('')}</select>
722
+ </div>`;
723
+ }
724
+ // What the formula form saves: only when the fields were on the form.
725
+ function flFrFormulaCollect() {
726
+ const c = document.getElementById('ff-ifra-cat'), u = document.getElementById('ff-product-use');
727
+ if (!c || !u) return {};
728
+ return { ifraCategory: FL_FR_CATEGORIES.includes(c.value) ? c.value : null, productUse: _frgIsUse(u.value) ? u.value : null };
729
+ }
730
+
731
+ // ── Ingredient: the form (free) ─────────────────────────────
732
+ // Two small tables with fixed columns and a header row each, so a number always sits under its heading. Rows are
733
+ // checked as they are typed (_frgFormCheck): a category used twice, a percent outside 0 to 100, and the allergen total.
734
+ const _FRG_KINDS = [['limit', 'Max %'], ['prohibited', 'Prohibited'], ['unrestricted', 'Not restricted']];
735
+ const _frgCatRank = (c) => { const k = String(c || '').toLowerCase() === 'all' ? -1 : FL_FR_CATEGORIES.indexOf(String(c || '').toUpperCase()); return k === -1 && String(c || '').toLowerCase() !== 'all' ? 99 : k; };
736
+ const _frgX = '<button type="button" class="fr-x" onclick="_frgRemoveRow(this)" aria-label="Remove"><span class="fl-cross" aria-hidden="true"></span></button>';
737
+ function _frgLimitRowHtml(r) {
738
+ const kind = r && r.unrestricted ? 'unrestricted' : r && (r.prohibited || _frgNum(r.maxPct) === 0) ? 'prohibited' : 'limit';
739
+ const cat = r ? String(r.category || '').toLowerCase() === 'all' ? 'all' : String(r.category || '').toUpperCase() : '';
740
+ return `<div class="fr-row fr-limit-row">
741
+ <select class="fr-l-cat" aria-label="Category"><option value="">Choose…</option><option value="all"${cat === 'all' ? ' selected' : ''}>All categories</option>${FL_FR_CATEGORIES.map(k => `<option value="${k}"${cat === k ? ' selected' : ''}>${_frgEsc(_frgCatText(k))}</option>`).join('')}</select>
742
+ <select class="fr-l-kind" aria-label="Limit" onchange="_frgLimitKind(this)">${_FRG_KINDS.map(([k, t]) => `<option value="${k}"${kind === k ? ' selected' : ''}>${t}</option>`).join('')}</select>
743
+ <span class="fr-pct"><input class="fr-l-max" type="number" min="0" max="100" step="any" inputmode="decimal" aria-label="Max %" placeholder="${kind === 'limit' ? '0.00' : '—'}" value="${kind === 'limit' && r && r.maxPct != null ? _frgEsc(String(r.maxPct)) : ''}"${kind === 'limit' ? '' : ' disabled'} /><em>%</em></span>
744
+ ${_frgX}
745
+ </div>`;
746
+ }
747
+ function _frgLimitKind(sel) {
748
+ const i = sel.closest('.fr-row').querySelector('.fr-l-max');
749
+ i.disabled = sel.value !== 'limit'; i.placeholder = i.disabled ? '—' : '0.00';
750
+ if (i.disabled) i.value = ''; else i.focus();
751
+ _frgFormCheck();
752
+ }
753
+ function _frgAllergenRowHtml(r) {
754
+ return `<div class="fr-row fr-al-row">
755
+ <input class="fr-a-name" list="f-fr-al-list" maxlength="${FL_FR_NAME_MAX}" aria-label="Allergen" placeholder="Name, or pick from the EU list" value="${_frgEsc(r ? r.substance || '' : '')}" onchange="_frgAllergenPicked(this)" />
756
+ <input class="fr-a-cas" maxlength="20" aria-label="CAS" placeholder="000-00-0" value="${_frgEsc(r ? r.cas || '' : '')}" onchange="_frgAllergenPicked(this)" />
757
+ <span class="fr-pct"><input class="fr-a-pct" type="number" min="0" max="100" step="any" inputmode="decimal" aria-label="Percent in this material" placeholder="0.00" value="${r && r.pct != null ? _frgEsc(String(r.pct)) : ''}" /><em>%</em></span>
758
+ ${_frgX}
759
+ </div>`;
760
+ }
761
+ // A name picked fills its CAS; a CAS typed fills its name. Neither overwrites what is already there.
762
+ function _frgAllergenPicked(inp) {
763
+ const row = inp.closest('.fr-row'), name = row.querySelector('.fr-a-name'), cas = row.querySelector('.fr-a-cas');
764
+ const e = flFrAllergenFor(name.value, cas.value);
765
+ if (e && !cas.value.trim()) cas.value = e.cas[0];
766
+ if (e && !name.value.trim()) name.value = e.name;
767
+ _frgFormCheck();
768
+ }
769
+ function _frgRemoveRow(btn) { btn.closest('.fr-row').remove(); _frgFormCheck(); }
770
+ function _frgAddRow(listId, html) {
771
+ const list = document.getElementById(listId);
772
+ if (!list) return;
773
+ list.insertAdjacentHTML('beforeend', html);
774
+ const f = list.lastElementChild && list.lastElementChild.querySelector('select, input');
775
+ _frgFormCheck();
776
+ if (f) f.focus();
777
+ }
778
+ function _frgAddLimit() { _frgAddRow('f-fr-limits', _frgLimitRowHtml(null)); }
779
+ function _frgAddAllergen() { const n = document.getElementById('f-fr-none'); if (n) n.checked = false; _frgAddRow('f-fr-allergens', _frgAllergenRowHtml(null)); }
780
+ function _frgNoneTicked(box) { if (box.checked) document.getElementById('f-fr-allergens').innerHTML = ''; _frgFormCheck(); }
781
+ // Marks what Save would refuse, as it is typed, and keeps the two summary lines current.
782
+ function _frgFormCheck() {
783
+ const lim = document.getElementById('f-fr-limits'), al = document.getElementById('f-fr-allergens');
784
+ if (!lim || !al) return;
785
+ const bad = (el, on, why) => { el.classList.toggle('fr-bad', !!on); if (on) el.setAttribute('aria-invalid', 'true'); else el.removeAttribute('aria-invalid'); el.title = on ? why : ''; };
786
+ const pctBad = (inp, zeroOk) => { const raw = inp.value.trim(), n = _frgNum(raw); return !inp.disabled && raw !== '' && (!(zeroOk ? n >= 0 : n > 0) || n > 100); };
787
+ const seen = new Map();
788
+ lim.querySelectorAll('.fr-limit-row').forEach(row => { const c = row.querySelector('.fr-l-cat').value; if (c) seen.set(c, (seen.get(c) || 0) + 1); });
789
+ let nLim = 0;
790
+ lim.querySelectorAll('.fr-limit-row').forEach(row => {
791
+ const c = row.querySelector('.fr-l-cat'), m = row.querySelector('.fr-l-max');
792
+ bad(c, c.value && seen.get(c.value) > 1, 'This category is there twice.');
793
+ bad(m, pctBad(m, true), 'Between 0 and 100.');
794
+ if (c.value) nLim++;
795
+ });
796
+ let total = 0, nAl = 0;
797
+ al.querySelectorAll('.fr-al-row').forEach(row => {
798
+ const p = row.querySelector('.fr-a-pct'), n = _frgNum(p.value);
799
+ bad(p, pctBad(p, false), 'Above 0, up to 100.');
800
+ if (n > 0 && n <= 100) { total += n; nAl++; }
801
+ });
802
+ const heads = document.querySelectorAll('.fr-form .fr-cols');
803
+ if (heads[0]) heads[0].hidden = !lim.children.length;
804
+ if (heads[1]) heads[1].hidden = !al.children.length;
805
+ const as = document.getElementById('f-fr-al-sum');
806
+ const picked = (id) => { const e = document.getElementById(id), o = e && e.value ? e.selectedOptions[0] : null; return o ? o.textContent : ''; };
807
+ const hint = (id, text, warn) => { const h = document.querySelector('#' + id + ' > .fl-fold-h .fl-fold-hint'); if (h) { h.textContent = text; h.classList.toggle('fr-warn', !!warn); } };
808
+ const am = document.getElementById('f-fr-amend'), none = document.getElementById('f-fr-none');
809
+ const anyBad = (list) => !!list.querySelector('.fr-bad');
810
+ hint('f-fr-fold-limits', _frgLimitsHint(nLim, am ? am.value.trim() : '', picked('f-fr-cert')) + (anyBad(lim) ? ' · check a row' : ''), anyBad(lim) || (nLim && !picked('f-fr-cert')));
811
+ hint('f-fr-fold-allergens', _frgAllergensHint(nAl, total, !!(none && none.checked) && !al.children.length, picked('f-fr-decl'), !!document.querySelector('.fr-form [data-fr-auto]')) + (anyBad(al) ? ' · check a row' : ''), anyBad(al) || total > 100 + 1e-9 || ((nAl || (none && none.checked)) && !picked('f-fr-decl')));
812
+ if (as) { const over = total > 100 + 1e-9; as.classList.toggle('fr-warn', over); as.textContent = !al.children.length ? '' : nAl ? `Total ${_frgPct(total)}%${over ? ': more than the whole material' : ''}` : ''; }
813
+ }
814
+ function _frgPasteToggle(which) { const b = document.getElementById('f-fr-paste-' + which); if (b) { b.hidden = !b.hidden; if (!b.hidden) b.querySelector('textarea').focus(); } }
815
+ function _frgPasteRead(which) {
816
+ const box = document.getElementById('f-fr-paste-' + which), ta = box && box.querySelector('textarea');
817
+ if (!ta) return;
818
+ const res = which === 'limits' ? flFrParseLimits(ta.value) : flFrParseAllergens(ta.value);
819
+ const list = document.getElementById(which === 'limits' ? 'f-fr-limits' : 'f-fr-allergens');
820
+ if (!res.rows.length) { if (typeof toast === 'function') toast(which === 'limits' ? 'No rows read. One per line: category, then the max %.' : 'No rows read. One per line: name, CAS, %.'); return; }
821
+ list.insertAdjacentHTML('beforeend', res.rows.map(which === 'limits' ? _frgLimitRowHtml : _frgAllergenRowHtml).join(''));
822
+ if (which === 'allergens') { const n = document.getElementById('f-fr-none'); if (n) n.checked = false; }
823
+ ta.value = ''; box.hidden = true;
824
+ _frgFormCheck();
825
+ if (typeof toast === 'function') toast(`${res.rows.length} ${res.rows.length === 1 ? 'row' : 'rows'} read${res.skipped ? `, ${res.skipped} skipped` : ''}. Check them against the document.`);
826
+ }
827
+ function _frgDocSelectHtml(id, ing, picked, none) {
828
+ const docs = (ing && Array.isArray(ing.documents) ? ing.documents : []).filter(d => d && !d.deleted);
829
+ return `<select id="${id}"${docs.length ? '' : ' disabled'}><option value="">${docs.length ? none : 'No documents yet'}</option>${docs.map(d => `<option value="${_frgEsc(d.id)}"${d.id === picked ? ' selected' : ''}>${_frgEsc(d.filename || d.name || d.id)}</option>`).join('')}</select>`;
830
+ }
831
+ // The two blocks inside the ingredient form's Fragrance Details panel.
832
+ function flFrIngFormHtml(ing) {
833
+ const fd = (ing && ing.fragranceDetails) || {};
834
+ const limits = (Array.isArray(fd.ifraLimits) ? fd.ifraLimits.filter(r => r && typeof r === 'object') : []).slice().sort((x, y) => _frgCatRank(x.category) - _frgCatRank(y.category));
835
+ const declared = !!ing && Array.isArray(ing.fragranceAllergens), al = declared ? ing.fragranceAllergens.filter(r => r && typeof r === 'object') : [];
836
+ const auto = !declared && ing && flFrIngAllergens(ing).auto;
837
+ const hasDocs = !!(ing && Array.isArray(ing.documents) && ing.documents.some(d => d && !d.deleted));
838
+ const total = al.reduce((t, r) => t + (_frgNum(r.pct) > 0 ? _frgNum(r.pct) : 0), 0);
839
+ const limitsBody = `<div class="fr-block">
840
+ <div class="fr-dim fr-from">From the supplier\u2019s IFRA certificate.</div>
841
+ <div class="fr-form-top">
842
+ <label class="fr-f-short">Amendment<input id="f-fr-amend" maxlength="20" placeholder="51st" value="${_frgEsc(fd.ifraAmendment || '')}" /></label>
843
+ <label class="fr-f-doc">Certificate${_frgDocSelectHtml('f-fr-cert', ing, fd.ifraCertDocId, 'Choose\u2026')}</label>
844
+ ${_frgReadBtnHtml('limits')}
845
+ </div>
846
+ <div class="fr-row fr-cols"${limits.length ? '' : ' hidden'}><span>Category</span><span>Limit</span><span class="num">Max</span><span></span></div>
847
+ <div id="f-fr-limits">${limits.map(_frgLimitRowHtml).join('')}</div>
848
+ <div class="fr-form-act"><button type="button" class="btn btn-secondary btn-sm" onclick="_frgAddLimit()">+ Add limit</button><button type="button" class="btn btn-secondary btn-sm" onclick="_frgPasteToggle('limits')">Paste table</button></div>
849
+ <div id="f-fr-paste-limits" class="fr-paste" hidden><textarea rows="4" aria-label="Certificate table" placeholder="4 1.2&#10;5A 0.5&#10;9 No restriction"></textarea><button type="button" class="btn btn-secondary btn-sm" onclick="_frgPasteRead('limits')">Read rows</button></div>
850
+ </div>`;
851
+ const allergensBody = `<div class="fr-block">
852
+ <div class="fr-dim fr-from">% in this material, from the allergen declaration.</div>
853
+ <div class="fr-form-top">
854
+ <label class="fr-f-doc">Declaration${_frgDocSelectHtml('f-fr-decl', ing, ing && ing.allergenDeclDocId, 'Choose\u2026')}</label>
855
+ <label class="fr-check"><input type="checkbox" id="f-fr-none"${declared && !al.length ? ' checked' : ''} onchange="_frgNoneTicked(this)" /> Declares none</label>
856
+ ${_frgReadBtnHtml('allergens')}
857
+ </div>
858
+ ${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>' : ''}
859
+ <div class="fr-row fr-cols"${al.length ? '' : ' hidden'}><span>Allergen</span><span>CAS</span><span class="num">In material</span><span></span></div>
860
+ <div id="f-fr-allergens">${al.map(_frgAllergenRowHtml).join('')}</div>
861
+ <div class="fr-form-act"><button type="button" class="btn btn-secondary btn-sm" onclick="_frgAddAllergen()">+ Add allergen</button><button type="button" class="btn btn-secondary btn-sm" onclick="_frgPasteToggle('allergens')">Paste table</button><span id="f-fr-al-sum" class="fr-dim"></span></div>
862
+ <div id="f-fr-paste-allergens" class="fr-paste" hidden><textarea rows="4" aria-label="Declaration table" placeholder="Linalool 78-70-6 12.5&#10;Limonene 5989-27-5 3.1"></textarea><button type="button" class="btn btn-secondary btn-sm" onclick="_frgPasteRead('allergens')">Read rows</button></div>
863
+ </div>`;
864
+ // Both start folded (Jun, 23 Nov): one line each says what is inside, so the class details stay short for someone
865
+ // who only sets the family and the note. The lines are kept current by _frgFormCheck.
866
+ const certName = (id) => { const d = id && ing && Array.isArray(ing.documents) ? ing.documents.find(x => x && x.id === id && !x.deleted) : null; return d ? d.filename || d.name || '' : ''; };
867
+ const limHint = _frgLimitsHint(limits.length, String(fd.ifraAmendment || '').trim(), certName(fd.ifraCertDocId));
868
+ const alHint = _frgAllergensHint(al.length, total, declared && !al.length, certName(ing && ing.allergenDeclDocId), !!auto);
869
+ return `<div class="form-group span-2 fr-form" data-ing="${_frgEsc(ing && ing.id || '')}" oninput="_frgFormCheck()" onchange="_frgFormCheck()">
870
+ ${fd.ifraCategory ? `<div class="fr-legacy">Category on file (legacy): <strong class="fl-val">${_frgEsc(String(fd.ifraCategory))}</strong>. Not used in any check.</div>` : ''}
871
+ ${flFoldHtml('f-fr-fold-limits', 'IFRA limits', _frgEsc(limHint), false, limitsBody)}
872
+ ${flFoldHtml('f-fr-fold-allergens', 'Fragrance allergens', _frgEsc(alHint), false, allergensBody)}
873
+ <datalist id="f-fr-al-list">${FL_FR_ALLERGENS.map(a => `<option value="${_frgEsc(a.name)}"></option>`).join('')}</datalist>
874
+ ${hasDocs ? '' : '<div class="fr-dim">Attach the certificate and the declaration on the Documents tab, then choose them here.</div>'}
875
+ </div>`;
876
+ }
877
+ // The folded line of each block: what is inside, and what is missing.
878
+ function _frgLimitsHint(n, amendment, cert) {
879
+ if (!n) return 'None yet';
880
+ return [`${n} ${n === 1 ? 'category' : 'categories'}`, amendment, cert || 'no certificate chosen'].filter(Boolean).join(' · ');
881
+ }
882
+ function _frgAllergensHint(n, total, none, decl, auto) {
883
+ if (none) return ['Declares none', decl || 'no declaration chosen'].join(' · ');
884
+ if (!n) return auto ? '100% of itself, by its CAS' : 'None yet';
885
+ return [`${n} ${n === 1 ? 'allergen' : 'allergens'}`, `total ${_frgPct(total)}%`, decl || 'no declaration chosen'].join(' · ');
886
+ }
887
+ // ── Read the rows from the PDF (Pro, the lab's own AI key) ──
888
+ // The certificate or declaration picked above is sent to the AI provider the lab has set up (js/doc-extract.js: the
889
+ // same call, key and gate as Extract on the Documents tab) and the rows it returns are ADDED to the form, marked, and
890
+ // left unsaved: the form is the review step, and Save is the person's own. Nothing is read without a document picked,
891
+ // so every row that arrives already has its source. A row already in the form is never replaced.
892
+ const _frgCanRead = () => typeof hasFeature !== 'function' || hasFeature('docs.extract');
893
+ function _frgReadBtnHtml(which) {
894
+ 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>`;
895
+ return `<button type="button" class="btn btn-secondary btn-sm fr-read" id="f-fr-read-${which}" onclick="flFrReadDoc('${which}')">Read from PDF</button>`;
896
+ }
897
+ function _frgReadPrompt(which, ing) {
898
+ const name = _frgName(ing);
899
+ if (which === 'limits') return [
900
+ `The attached document is a supplier's IFRA certificate (or IFRA conformity statement) for the fragrance material "${name}".`,
901
+ 'Extract the maximum use level for each IFRA product category the document states.',
902
+ 'Return ONLY JSON: {"amendment": string|null, "limits": [{"category": string, "status": "limit"|"prohibited"|"not restricted", "maxPct": number|null}]}.',
903
+ 'category is the IFRA category exactly as printed: 1, 2, 3, 4, 5A, 5B, 5C, 5D, 6, 7A, 7B, 8, 9, 10A, 10B, 11A, 11B or 12. amendment is the IFRA amendment the certificate cites, such as "51st".',
904
+ 'maxPct is the percent in the finished product as a plain number (0.5, not "0.5%"). Use status "not restricted" with maxPct null when the document says no restriction applies in that category, and "prohibited" when it says not permitted.',
905
+ 'Include only categories the document states. Do NOT guess, interpolate, or fill a category from general knowledge of IFRA Standards: if the document gives no figure for a category, leave that category out.',
906
+ ].join('\n');
907
+ return [
908
+ `The attached document is a supplier's fragrance allergen declaration for the material "${name}".`,
909
+ 'Extract each declared fragrance allergen and its concentration in this material.',
910
+ 'Return ONLY JSON: {"none": boolean, "allergens": [{"name": string, "cas": string|null, "pct": number}]}.',
911
+ 'pct is the percent by weight in the material as a plain number; convert ppm to percent (1000 ppm = 0.1). Skip a substance given only as "not detected", "absent", or below a detection limit with no figure.',
912
+ 'Set "none" to true only when the document states that no regulated allergens are present. Do NOT add a substance the document does not list, and do NOT guess a concentration.',
913
+ ].join('\n');
914
+ }
915
+ // Canned answers for the "mock" AI key (no network, no tokens): made-up numbers, for trying the flow.
916
+ function _frgReadMock(which) {
917
+ if (which === 'limits') return { amendment: '51st', limits: [{ category: '4', status: 'limit', maxPct: 1.2 }, { category: '5A', status: 'limit', maxPct: 0.3 },
918
+ { category: '9', status: 'limit', maxPct: 2.5 }, { category: '12', status: 'not restricted', maxPct: null }, { category: '1', status: 'prohibited', maxPct: null }, { category: '5', status: 'limit', maxPct: 9 }] };
919
+ return { none: false, allergens: [{ name: 'Linalool', cas: '78-70-6', pct: 12.5 }, { name: 'd-Limonene', cas: '5989-27-5', pct: 3.1 }, { name: 'Geraniol', cas: null, pct: 0.4 }] };
920
+ }
921
+ // What the model returned → limit rows. Held to the same rules as a typed row; anything else is counted as skipped.
922
+ function flFrLimitsFromExtract(raw) {
923
+ const rows = [], seen = new Set();
924
+ let skipped = 0;
925
+ (raw && Array.isArray(raw.limits) ? raw.limits : []).slice(0, 60).forEach(r => {
926
+ if (!r || typeof r !== 'object') { skipped++; return; }
927
+ const category = String(_frgText(r.category)).replace(/^(?:ifra\s*)?(?:cat(?:egory)?|class)\.?\s*/i, '').replace(/\s+/g, '').toUpperCase();
928
+ if (!FL_FR_CATEGORIES.includes(category) || seen.has(category)) { skipped++; return; }
929
+ const status = _frgText(r.status).toLowerCase(), m = _frgNum(r.maxPct);
930
+ let row = null;
931
+ if (/prohibit|not permitted|banned/.test(status)) row = { category, maxPct: 0, prohibited: true };
932
+ else if (/not restricted|no restriction|unrestricted|no limit/.test(status)) row = { category, unrestricted: true };
933
+ else if (m === 0) row = { category, maxPct: 0, prohibited: true };
934
+ else if (m > 0 && m <= 100) row = { category, maxPct: m };
935
+ if (!row) { skipped++; return; }
936
+ seen.add(category); rows.push(row);
937
+ });
938
+ return { rows, skipped, amendment: _frgText(raw && raw.amendment).slice(0, 20) };
939
+ }
940
+ function flFrAllergensFromExtract(raw) {
941
+ const rows = [], seen = new Set();
942
+ let skipped = 0;
943
+ (raw && Array.isArray(raw.allergens) ? raw.allergens : []).slice(0, FL_FR_ROWS_MAX).forEach(r => {
944
+ if (!r || typeof r !== 'object') { skipped++; return; }
945
+ const name = _frgText(r.name).slice(0, FL_FR_NAME_MAX), cas = _frgCas(_frgText(r.cas)), p = _frgNum(r.pct);
946
+ const entry = flFrAllergenFor(name, cas), key = entry ? 'e' + entry.ref : _frgKey(name) || cas;
947
+ if (!(p > 0) || p > 100 || !key || seen.has(key)) { skipped++; return; }
948
+ seen.add(key); rows.push({ substance: entry ? entry.name : name, cas: cas || (entry ? entry.cas[0] : ''), pct: p });
949
+ });
950
+ return { rows, skipped, none: !!(raw && raw.none === true) && !rows.length };
951
+ }
952
+ let _frgReading = false;
953
+ async function flFrReadDoc(which) {
954
+ if (which !== 'limits' && which !== 'allergens') return;
955
+ if (!_frgCanRead()) { if (typeof docProUpsell === 'function') docProUpsell(); return; }
956
+ if (_frgReading) return;
957
+ const form = document.querySelector('.fr-form'), ing = form ? _frgIng(form.dataset.ing) : null;
958
+ const sel = document.getElementById(which === 'limits' ? 'f-fr-cert' : 'f-fr-decl');
959
+ const doc = ing && sel && Array.isArray(ing.documents) ? ing.documents.find(d => d && d.id === sel.value && !d.deleted) : null;
960
+ const say = (m, t) => { if (typeof toast === 'function') toast(m, t); };
961
+ if (!doc) { say(which === 'limits' ? 'Choose the certificate first.' : 'Choose the declaration first.'); if (sel) sel.focus(); return; }
962
+ const ap = typeof _aiKeyAndProvider === 'function' ? _aiKeyAndProvider() : null;
963
+ if (!ap) return;
964
+ const btn = document.getElementById('f-fr-read-' + which);
965
+ _frgReading = true;
966
+ if (btn) { btn.disabled = true; btn.textContent = 'Reading…'; }
967
+ let raw;
968
+ try { raw = ap.provider === 'mock' ? _frgReadMock(which) : await _runPdfExtract(ap.provider, ap.key, _frgReadPrompt(which, ing), doc); }
969
+ catch (e) { say('Could not read the document: ' + ((e && e.message) || e)); return; }
970
+ finally { _frgReading = false; const b = document.getElementById('f-fr-read-' + which); if (b) { b.disabled = false; b.textContent = 'Read from PDF'; } }
971
+ // The form may have closed, or another document been picked, while the call was out.
972
+ const list = document.getElementById(which === 'limits' ? 'f-fr-limits' : 'f-fr-allergens'), sel2 = document.getElementById(which === 'limits' ? 'f-fr-cert' : 'f-fr-decl');
973
+ if (!list || !sel2 || sel2.value !== doc.id) return;
974
+ const file = _frgText(doc.filename) || 'the document';
975
+ let added = 0, had = 0, res;
976
+ if (which === 'limits') {
977
+ res = flFrLimitsFromExtract(raw);
978
+ const have = new Set([...list.querySelectorAll('.fr-l-cat')].map(x => x.value));
979
+ res.rows.forEach(r => { if (have.has(r.category)) { had++; return; } list.insertAdjacentHTML('beforeend', _frgLimitRowHtml(r)); list.lastElementChild.classList.add('fr-new'); added++; });
980
+ const am = document.getElementById('f-fr-amend');
981
+ if (am && !am.value.trim() && res.amendment) am.value = res.amendment;
982
+ } else {
983
+ res = flFrAllergensFromExtract(raw);
984
+ const keyOf = (n, c) => { const e = flFrAllergenFor(n, c); return e ? 'e' + e.ref : _frgKey(n) || _frgCas(c); };
985
+ const have = new Set([...list.querySelectorAll('.fr-al-row')].map(x => keyOf(x.querySelector('.fr-a-name').value, x.querySelector('.fr-a-cas').value)));
986
+ 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++; });
987
+ const none = document.getElementById('f-fr-none');
988
+ if (none) { if (added) none.checked = false; else if (res.none && !list.children.length) none.checked = true; }
989
+ }
990
+ if (typeof flOpenFold === 'function') flOpenFold(which === 'limits' ? 'f-fr-fold-limits' : 'f-fr-fold-allergens');
991
+ _frgFormCheck();
992
+ if (added && typeof _ingMarkDirty === 'function') { try { _ingMarkDirty(); } catch (_) {} }
993
+ const what = which === 'limits' ? ['limit', 'limits'] : ['allergen', 'allergens'];
994
+ const bits = [added ? `${added} ${what[added === 1 ? 0 : 1]} read from ${file}` : (which === 'allergens' && res.none ? `${file} declares none` : `Nothing new read from ${file}`)];
995
+ if (had) bits.push(`${had} already here`);
996
+ if (res.skipped) bits.push(`${res.skipped} skipped`);
997
+ say(bits.join(', ') + (added ? '. Check each against the document, then Save.' : '.'), added ? 'info' : undefined);
998
+ }
999
+
1000
+ // What the ingredient form saves. → { error } | { details: fields for fragranceDetails, fragranceAllergens, allergenDeclDocId }
1001
+ // prev: the ingredient being edited (its legacy category is kept as it is).
1002
+ function flFrIngFormCollect(prev) {
1003
+ const q = (id) => document.getElementById(id), val = (id) => { const e = q(id); return e ? String(e.value || '').trim() : ''; };
1004
+ if (!q('f-fr-limits')) return null; // the panel is not on this form
1005
+ const limits = [], seen = new Set();
1006
+ let error = '';
1007
+ document.querySelectorAll('#f-fr-limits .fr-limit-row').forEach(row => {
1008
+ const category = row.querySelector('.fr-l-cat').value, kind = row.querySelector('.fr-l-kind').value, raw = row.querySelector('.fr-l-max').value.trim();
1009
+ if (!category && !raw && kind === 'limit') return; // an empty row
1010
+ if (!category || (category !== 'all' && !FL_FR_CATEGORIES.includes(category))) { error = error || 'IFRA limits: choose a category on each row.'; return; }
1011
+ if (!_FRG_KINDS.some(([k]) => k === kind)) { error = error || 'IFRA limits: choose a limit type on each row.'; return; }
1012
+ if (seen.has(category)) { error = error || `IFRA limits: ${category === 'all' ? 'All categories' : 'category ' + category} is there twice.`; return; }
1013
+ seen.add(category);
1014
+ if (kind === 'unrestricted') { limits.push({ category, unrestricted: true }); return; }
1015
+ if (kind === 'prohibited') { limits.push({ category, maxPct: 0, prohibited: true }); return; }
1016
+ const m = _frgNum(raw);
1017
+ if (!(m >= 0) || m > 100) { error = error || `IFRA limits: category ${category} needs a max between 0 and 100 %.`; return; }
1018
+ limits.push(m === 0 ? { category, maxPct: 0, prohibited: true } : { category, maxPct: m });
1019
+ });
1020
+ const allergens = [];
1021
+ document.querySelectorAll('#f-fr-allergens .fr-al-row').forEach(row => {
1022
+ const substance = row.querySelector('.fr-a-name').value.trim(), cas = row.querySelector('.fr-a-cas').value.trim(), raw = row.querySelector('.fr-a-pct').value.trim();
1023
+ if (!substance && !cas && !raw) return;
1024
+ const p = _frgNum(raw);
1025
+ if (!substance && !cas) { error = error || 'Fragrance allergens: name each row.'; return; }
1026
+ if (!(p > 0) || p > 100) { error = error || `Fragrance allergens: ${substance || cas} needs a percent above 0, up to 100.`; return; }
1027
+ const e = flFrAllergenFor(substance, cas);
1028
+ if (allergens.length >= FL_FR_ROWS_MAX) { error = error || `Fragrance allergens: ${FL_FR_ROWS_MAX} rows at most.`; return; }
1029
+ allergens.push({ substance: e ? e.name : substance.slice(0, FL_FR_NAME_MAX), cas: _frgCas(cas) || (e ? e.cas[0] : ''), pct: p });
1030
+ });
1031
+ if (error) { ['f-fr-fold-limits', 'f-fr-fold-allergens'].forEach(id => { if (typeof flOpenFold === 'function') flOpenFold(id); }); _frgFormCheck(); return { error }; }
1032
+ const none = !!(q('f-fr-none') && q('f-fr-none').checked);
1033
+ const legacy = prev && prev.fragranceDetails && prev.fragranceDetails.ifraCategory;
1034
+ // A document id is kept only when it is one of this ingredient's own documents.
1035
+ const mine = (id) => !!id && !!prev && Array.isArray(prev.documents) && prev.documents.some(d => d && d.id === id && !d.deleted);
1036
+ const amend = val('f-fr-amend'), cert = mine(val('f-fr-cert')) ? val('f-fr-cert') : '', decl = mine(val('f-fr-decl')) ? val('f-fr-decl') : '';
1037
+ return {
1038
+ details: { ...(legacy ? { ifraCategory: legacy } : {}), ...(limits.length ? { ifraLimits: limits } : {}), ...(amend ? { ifraAmendment: amend.slice(0, 20) } : {}), ...(cert ? { ifraCertDocId: cert } : {}) },
1039
+ fragranceAllergens: allergens.length ? allergens : none ? [] : undefined,
1040
+ allergenDeclDocId: decl || undefined,
1041
+ };
1042
+ }
1043
+
1044
+ // ── Ingredient: the detail page ─────────────────────────────
1045
+ function flFrIngDetailHtml(ing) {
1046
+ if (!ing) return '';
1047
+ const fd = ing.fragranceDetails || {}, rows = flFrLimitRows(ing), al = flFrIngAllergens(ing);
1048
+ const doc = (id, word) => { const d = id && Array.isArray(ing.documents) ? ing.documents.find(x => x && x.id === id && !x.deleted) : null;
1049
+ return d ? `<a class="fr-doc" onclick="downloadIngredientDoc('${escJsAttr(ing.id)}','${escJsAttr(d.id)}',true)">${_frgEsc(d.filename || d.name || word)}</a>` : `<span class="fr-warn">no ${word} attached</span>`; };
1050
+ const parts = [];
1051
+ if (fd.ifraCategory) parts.push(`<div class="fr-legacy">Category on file (legacy): <strong class="fl-val">${_frgEsc(String(fd.ifraCategory))}</strong>. Not used in any check.</div>`);
1052
+ if (rows.length || fd.ifraAmendment || fd.ifraCertDocId) {
1053
+ parts.push(`<div class="fr-d-h">IFRA limits <span>${fd.ifraAmendment ? 'IFRA ' + _frgEsc(String(fd.ifraAmendment)) + ' · ' : ''}${doc(fd.ifraCertDocId, 'certificate')}</span></div>
1054
+ ${rows.length ? `<div class="fr-d-chips">${rows.map(r => `<span class="fr-d-chip ${r.kind === 'prohibited' ? 'bad' : ''}" translate="no"><b>${r.category === 'all' ? 'All' : _frgEsc(r.category)}</b> ${r.kind === 'unrestricted' ? 'not restricted' : r.kind === 'prohibited' ? 'prohibited' : _frgPct(r.maxPct) + '%'}</span>`).join('')}</div>` : '<div class="fr-dim">No limits typed yet.</div>'}`);
1055
+ }
1056
+ if (al.declared || ing.allergenDeclDocId) {
1057
+ parts.push(`<div class="fr-d-h">Fragrance allergens <span>${al.auto ? 'on the EU list by its CAS' : doc(ing.allergenDeclDocId, 'declaration')}</span></div>
1058
+ ${al.rows.length ? `<div class="fr-d-chips">${al.rows.map(r => `<span class="fr-d-chip" translate="no"><b>${_frgEsc(r.name)}</b> ${_frgPct(r.pct)}%${r.entry ? '' : ' · not on the EU list'}</span>`).join('')}</div>` : `<div class="fr-dim">${al.declared ? 'Declares none.' : 'No rows typed yet.'}</div>`}`);
1059
+ }
1060
+ return parts.length ? `<div class="fr-detail">${parts.join('')}</div>` : '';
1061
+ }