jupiter-dynamic-forms 1.20.5 → 1.20.6
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/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +21 -1
- package/dist/index.mjs.map +1 -1
- package/dist/utils/formula-variable-resolver.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -19,7 +19,7 @@ const I={attribute:!0,type:String,converter:y,reflect:!1,hasChanged:x},$=(e=I,t,
|
|
|
19
19
|
* @license
|
|
20
20
|
* Copyright 2017 Google LLC
|
|
21
21
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
22
|
-
*/function S(e){return w({...e,state:!0,attribute:!1})}class C{static validateField(e,t,i,o,r,n=[]){const a=[];for(const s of n){const n=this.validateRule(e,t,i,o,r,s);n&&a.push(n)}return a}static validateRule(e,t,i,o,r,n){const a=null==o||""===o;switch(n.type){case"required":if(a)return this.createError(e,t,i,n);break;case"min":if(!a&&"number"==typeof o&&o<n.value)return this.createError(e,t,i,n);break;case"max":if(!a&&"number"==typeof o&&o>n.value)return this.createError(e,t,i,n);break;case"minLength":if(!a&&"string"==typeof o&&o.length<n.value)return this.createError(e,t,i,n);break;case"maxLength":if(!a&&"string"==typeof o&&o.length>n.value)return this.createError(e,t,i,n);break;case"pattern":if(!a&&"string"==typeof o){if(!new RegExp(n.value).test(o))return this.createError(e,t,i,n)}break;case"email":if(!a&&"string"==typeof o){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o))return this.createError(e,t,i,n)}break;case"url":if(!a&&"string"==typeof o)try{new URL(o)}catch{return this.createError(e,t,i,n)}break;case"custom":break;default:console.warn(`Unknown validation rule type: ${n.type}`)}return null}static createError(e,t,i,o){return{fieldId:e,conceptId:t,columnId:i,message:o.message,severity:o.severity||"error",rule:o}}static validateDataType(e,t){if(null==e||""===e)return{valid:!0,convertedValue:e};switch(t){case"number":case"decimal":case"currency":case"percentage":{const t=Number(e);return isNaN(t)?{valid:!1,error:"Invalid number format"}:{valid:!0,convertedValue:t}}case"date":{const t=new Date(e);return isNaN(t.getTime())?{valid:!1,error:"Invalid date format"}:{valid:!0,convertedValue:t.toISOString().split("T")[0]}}case"datetime":{const t=new Date(e);return isNaN(t.getTime())?{valid:!1,error:"Invalid datetime format"}:{valid:!0,convertedValue:t.toISOString()}}case"boolean":if("boolean"==typeof e)return{valid:!0,convertedValue:e};if("string"==typeof e){const t=e.toLowerCase();if("true"===t||"1"===t)return{valid:!0,convertedValue:!0};if("false"===t||"0"===t)return{valid:!0,convertedValue:!1}}return{valid:!1,error:"Invalid boolean format"};case"text":case"textarea":case"email":case"url":case"tel":return{valid:!0,convertedValue:String(e)};default:return{valid:!0,convertedValue:e}}}static formatValue(e,t,i="en-US"){if(null==e)return"";switch(t){case"number":return new Intl.NumberFormat(i).format(Number(e));case"decimal":return new Intl.NumberFormat(i,{minimumFractionDigits:2,maximumFractionDigits:2}).format(Number(e));case"currency":return new Intl.NumberFormat(i,{style:"currency",currency:"USD"}).format(Number(e));case"percentage":return new Intl.NumberFormat(i,{style:"percent",minimumFractionDigits:2}).format(Number(e)/100);case"date":return new Date(e).toLocaleDateString(i);case"datetime":return new Date(e).toLocaleString(i);default:return String(e)}}}class F{static formatPeriodDisplay(e,t){if(!e||!t)return`${e} / ${t}`;const i=e.substring(0,4);return i===t.substring(0,4)?i:`${e} / ${t}`}static createUniqueConceptId(e,t){let i=e.id;if(e.preferredLabel&&""!==e.preferredLabel.trim()){const t=e.preferredLabel.match(/\/([^\/]+)$/),o=t?t[1]:e.preferredLabel.replace(/[^a-zA-Z0-9]/g,"_");i=`${e.id}_${o}`}if(t){return`${i}__${this.createSectionHash(t)}`}return i}static createSectionHash(e){let t=0;for(let i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t&=t}return Math.abs(t).toString(36).substr(0,6)}static _extractDocumentationLabels(e){const t={};return e.filter(e=>"http://www.xbrl.org/2003/role/documentation"===e.role).forEach(e=>{t[e.lang]=e.label}),t}static buildFormSchema(e,t,i,o="en",r){var n,a;if(!e.presentation||0===e.presentation.length)throw new Error("XBRL presentation data is required");const s=e.presentation[0],l=null==(n=e.hypercubes)?void 0:n[0],d=Array.isArray(e.datatypes)?e.datatypes:(null==(a=e.datatypes)?void 0:a.concepts)||[],c=[];return s.roles.forEach(e=>{const n=this.buildSectionFromRole(e,t,i,l,o,r);d&&d.length>0?(n.datatypes=d,console.log(`✅ [buildFormSchema] Attached ${d.length} datatypes to section ${n.id}`)):console.warn(`⚠️ [buildFormSchema] No datatypes available for section ${n.id}`),this.assignFieldColumnIds(n),c.push(n)}),{formId:`xbrl-form-${Date.now()}`,title:`XBRL Form - ${this.extractEntityName(s.entrypoint)}`,description:"Dynamic form generated from XBRL taxonomy data",version:"1.0.0",sections:c}}static buildSectionFromRole(e,t,i,o,r="en",n){var a,s;let l;if(e.labels&&e.labels.length>0){const t=e.labels.find(e=>e.lang===r),i=e.labels.find(e=>"en"===e.lang)||e.labels[0];l=(t||i).label}else l=this.extractRoleTitle(e.role||e.id||"Unknown Role");const d=this.getAllNonAbstractConcepts(e),c=new Set(d.filter(e=>e.periodType).map(e=>e.periodType));let p=null==o?void 0:o.roles.find(t=>t.roleId===e.id);const u=null==n?void 0:n[e.id];p&&(null==u?void 0:u.dimensionSelections)&&u.dimensionSelections.length>0&&(console.log(`🔍 Filtering dimensions for role ${e.id} based on user selections`),p=this.filterHypercubeDimensionsBySelection(p,u.dimensionSelections));const h=this.generateDefaultColumnsForRole(e,t||"2025-01-01",i||"2025-12-31",p,d,c,u,r),m={periodTypes:c,availableColumnIds:h.map(e=>e.id),availableColumns:h},f=[],g=new Map;return(null==(a=e.presentationLinkbase)?void 0:a.concepts)&&e.presentationLinkbase.concepts.forEach(o=>{const n=this.buildConceptTree(o,0,t,i,m,e.id,r,g);n&&f.push(n)}),p&&(null==(s=p.items)?void 0:s.length)||!o||f.forEach(t=>this.applyCrossRoleDimensions(t,e.id,o,r)),{id:e.id,title:l,description:e.description||`Section for ${l}`,concepts:f,columns:h,expanded:!1,metadata:{roleURI:e.roleURI,originalRole:e.role},showPeriodControl:c.size>1,showPreviousYear:!0===e.showPreviousYear,instant:!0===e.instant,duration:!0===e.duration}}static buildConceptTree(e,t,i,o,r,n,a="en",s,l){var d,c;const p=this.getPreferredLabel(e.labels,a,e.preferredLabel),u=(null==(d=e.preferredLabel)?void 0:d.includes("periodStartLabel"))?"start":(null==(c=e.preferredLabel)?void 0:c.includes("periodEndLabel"))?"end":l,h="start"===u?"periodStartLabel":"end"===u?"periodEndLabel":void 0,m=[];if(!e.elementAbstract){let t=[];t=(null==r?void 0:r.availableColumnIds)&&r.availableColumnIds.length>0?r.availableColumnIds:["duration"],t.forEach(t=>{var n;const s=null==(n=null==r?void 0:r.availableColumns)?void 0:n.find(e=>e.id===t),d=(null==s?void 0:s.periodStartDate)||i,c=(null==s?void 0:s.periodEndDate)||o,p=this.createFieldFromConcept(e,d,c,t,l,a);p&&m.push(p)})}const f=[];e.children&&e.children.length>0&&e.children.forEach(e=>{const l=this.buildConceptTree(e,t+1,i,o,r,n,a,s,u);l&&f.push(l)});if(!(m.length>0||f.length>0))return null;let g=this.createUniqueConceptId(e,n);if(s){const e=s.get(g)??0;s.set(g,e+1),e>0&&(g=`${g}__occ${e+1}`)}const b={conceptName:e.conceptName,type:e.type,substitutionGroup:e.substitutionGroup,periodType:e.periodType,balance:e.balance,documentationLabels:this._extractDocumentationLabels(e.labels)};return{id:g,originalConceptId:e.id,name:e.conceptName,label:p,description:`${e.conceptName} (${e.type})`,type:e.type,level:t,children:f,fields:m,conceptMetadata:b,facts:e.facts||[],collapsed:t>0,abstract:e.elementAbstract,periodType:e.periodType,balance:e.balance,preferredLabel:e.preferredLabel,effectivePeriodRole:h}}static createFieldFromConcept(e,t,i,o,r,n="en"){var a;const s=this.mapXBRLTypeToFieldType(e.type),l=this.getPreferredLabel(e.labels,n,e.preferredLabel);let d;d=o||"duration";const c={id:`${e.id}_${d}_field`,conceptId:e.id,columnId:d,type:s,label:l,placeholder:`Enter ${l.toLowerCase()}`,required:!1,disabled:e.elementAbstract,defaultValue:null,periodType:"instant"===e.periodType||"duration"===e.periodType?e.periodType:void 0,periodStartDate:t||"2025-01-01",periodEndDate:i||"2025-12-31",periodInstantDate:"instant"===e.periodType?(null==(a=e.preferredLabel)?void 0:a.includes("periodStartLabel"))||"start"===r?this.subtractOneDay(t||"2025-01-01"):i||t||"2025-01-01":void 0};return"nl-cd_DescriptionLocationNL__a64trl"===e.id&&console.log(`🏗️ [Field Creation] Concept: ${e.id}, periodType from concept: ${e.periodType}, Field periodType: ${c.periodType}, ColumnId: ${d}`),c}static mapXBRLTypeToFieldType(e){return{"xbrli:stringItemType":"text","xbrli:monetaryItemType":"currency","xbrli:integerItemType":"number","xbrli:decimalItemType":"decimal","xbrli:percentItemType":"percentage","xbrli:dateItemType":"date","xbrli:booleanItemType":"boolean","dtr-types:domainItemType":"select","bw2-titel9:chamberOfCommerceRegistrationNumberItemType":"text"}[e]||"text"}static getPreferredLabel(e,t="en",i){if(!e||0===e.length)return"Unnamed Concept";const o=e.filter(e=>e.lang===t),r=o.length>0?o:e;if(i){const t=o.find(e=>e.role===i);if(t)return t.label;const r=e.find(e=>e.role===i);if(r)return r.label}const n=r.find(e=>e.preferredLabel);if(n)return n.label;const a=r.find(e=>"http://www.xbrl.org/2003/role/label"===e.role);if(a)return a.label;const s=r.find(e=>"http://www.xbrl.org/2003/role/terseLabel"===e.role);return s?s.label:r.length>0?r[0].label:e[0].label}static assignFieldColumnIds(e){if(!e.columns||0===e.columns.length)return;const t=e.columns.map(e=>e.id);e.concepts.forEach(e=>{this.assignColumnIdsToConceptFields(e,t)})}static assignColumnIdsToConceptFields(e,t){e.fields=e.fields.filter(e=>t.includes(e.columnId)),e.children&&e.children.forEach(e=>{this.assignColumnIdsToConceptFields(e,t)})}static countFieldsInTree(e){let t=e.fields.length;return e.children&&e.children.forEach(e=>{t+=this.countFieldsInTree(e)}),t}static getAllNonAbstractConcepts(e){var t;const i=[];return(null==(t=e.presentationLinkbase)?void 0:t.concepts)&&e.presentationLinkbase.concepts.forEach(e=>{this.collectNonAbstractConcepts(e,i)}),i}static collectNonAbstractConcepts(e,t){e.elementAbstract||t.push(e),e.children&&e.children.length>0&&e.children.forEach(e=>{this.collectNonAbstractConcepts(e,t)})}static filterHypercubeDimensionsBySelection(e,t){const i=JSON.parse(JSON.stringify(e));return i.items&&0!==i.items.length?(i.items.forEach(e=>{e.dimensions&&(e.dimensions=e.dimensions.map(e=>{var i,o;const r=t.find(t=>t.dimensionId===e.id);if(!r||!r.selectedMemberIds||0===r.selectedMemberIds.length)return e;const n={...e};return n.members=this.filterMembersBySelection(e.members,r.selectedMemberIds),console.log(` ✅ Filtered dimension ${e.id}: ${(null==(i=e.members)?void 0:i.length)||0} → ${(null==(o=n.members)?void 0:o.length)||0} members`),n}))}),i):i}static filterMembersBySelection(e,t){if(!e||!Array.isArray(e))return[];const i=[];return e.forEach(e=>{if(t.includes(e.id)&&i.push({...e,children:[]}),e.children&&e.children.length>0){const o=this.filterMembersBySelection(e.children,t);i.push(...o)}}),i}static findCrossRoleDimensions(e,t,i,o="en"){var r,n;const a=[];for(const d of i.roles)if(d.roleId!==t)for(const t of d.items)if((null==(r=t.conceptIds)?void 0:r.includes(e))&&(null==(n=t.dimensions)?void 0:n.some(e=>e.typedMember))){a.push(d);break}if(1!==a.length)return null;const s=a[0].items.find(t=>{var i;return null==(i=t.conceptIds)?void 0:i.includes(e)});if(!s)return null;const l=[];for(const d of s.dimensions){if(!d.typedMember)continue;const e=d.labels.find(e=>e.lang===o)||d.labels.find(e=>"en"===e.lang)||d.labels[0],t=(null==e?void 0:e.label)||d.id;l.push({axisId:d.id,axisLabel:t,typedMemberId:d.typedMember.id,memberLabel:t})}return l.length>0?l:null}static applyCrossRoleDimensions(e,t,i,o){var r;if(!e.abstract&&e.fields&&e.fields.length>0){const r=this.findCrossRoleDimensions(e.originalConceptId,t,i,o);r&&e.fields.forEach(e=>{e.crossRoleTypedMembers=r})}null==(r=e.children)||r.forEach(e=>this.applyCrossRoleDimensions(e,t,i,o))}static generateDefaultColumnsForRole(e,t,i,o,r,n,a,s="en"){var l,d;const c=r||this.getAllNonAbstractConcepts(e),p=n||new Set(c.filter(e=>e.periodType).map(e=>e.periodType));if(0===c.length)return[{id:"default",title:"Value",description:"Default value column",type:"base",order:0,removable:!1}];let u=[];if(1===(null==(l=null==o?void 0:o.items)?void 0:l.length)){const e=o.items[0];1===e.dimensions.length?u=this.generateSingleDimensionColumns(e.dimensions[0],t,i,p,s):e.dimensions.length>1&&(u=this.generateMultiDimensionColumns(e.dimensions,t,i,p,s)),a&&(u=this.filterColumnsByPeriodPreferences(u,a))}else(null==(d=null==o?void 0:o.items)?void 0:d.length)&&o.items.length;const h=[];u.length>0?h.push(...u):0===p.size?h.push({id:"default",title:this.formatPeriodDisplay(t,i),description:"",type:"base",order:0,removable:!1,periodStartDate:t,periodEndDate:i}):h.push({id:"duration",title:this.formatPeriodDisplay(t,i),description:"",type:"base",order:0,removable:!1,periodStartDate:t,periodEndDate:i});let m=h;if(a&&(m=this.filterColumnsByPeriodPreferences(h,a)),null==a?void 0:a.showPreviousYear){const e=this.generatePreviousYearColumns(m,t,i);m=[...m,...e]}return m}static getPreviousYearDate(e){try{const t=new Date(e);return t.setFullYear(t.getFullYear()-1),t.toISOString().split("T")[0]}catch(t){return console.error(`Error calculating previous year for date ${e}:`,t),e}}static subtractOneDay(e){try{const t=new Date(e);return t.setDate(t.getDate()-1),t.toISOString().split("T")[0]}catch(t){return console.error(`Error subtracting one day from date ${e}:`,t),e}}static generatePreviousYearColumns(e,t,i){const o=[],r=this.getPreviousYearDate(t),n=this.getPreviousYearDate(i);return e.forEach((e,t)=>{let i=e.title,a="",s="";e.dimensionData?(i=e.title,a=this.formatPeriodDisplay(r,n),s=`${e.id}_prev`):(i=this.formatPeriodDisplay(r,n),a="",s=`duration_prev_${t}`),o.push({...e,id:s,title:i,description:a,order:e.order+100,removable:!1,periodStartDate:r,periodEndDate:n,dimensionData:e.dimensionData?{...e.dimensionData,dimensionId:`${e.dimensionData.dimensionId}_prev`}:void 0})}),o}static filterColumnsByPeriodPreferences(e,t){return e.filter(e=>{var i,o,r,n;const a=e.id.includes("duration")||(null==(o=null==(i=e.dimensionData)?void 0:i.dimensionId)?void 0:o.includes("duration")),s=e.id.includes("instant")||(null==(n=null==(r=e.dimensionData)?void 0:r.dimensionId)?void 0:n.includes("instant"));return!a&&!s||!(a&&!t.showDuration)&&!(s&&!t.showInstant)})}static generateSingleDimensionColumns(e,t,i,o,r="en"){if(e.typedMember&&(!e.members||0===e.members.length)){const n=this.getPreferredLabel(e.labels,r)||e.conceptName,a={axisId:e.id,axisLabel:n,typedMemberId:e.typedMember.id,dimensionKey:`${n} | [Typed Input]`,dimensionIdKey:`${e.id}|[typed]`},s=[];return 0===o.size?s.push({id:"typed-default",title:n,description:"Typed dimension input column",type:"dimension",dimensionData:{dimensionId:"typed-default",axisId:a.axisId,memberId:"[typed]",memberValue:"Typed Input",memberLabel:"Typed Input",axis:a.axisLabel,axisLabel:a.axisLabel,memberKey:a.dimensionKey,dimensionIdKey:a.dimensionIdKey,hasTypedMembers:!0,typedMemberId:a.typedMemberId,typedMembers:[{axisId:a.axisId,axisLabel:a.axisLabel,typedMemberId:a.typedMemberId,memberLabel:a.axisLabel}]},order:0,removable:!1,periodStartDate:t,periodEndDate:i}):1===o.size&&o.has("instant")?s.push({id:"typed-instant",title:`${n} `,description:i,type:"dimension",dimensionData:{dimensionId:"typed-instant",axisId:a.axisId,memberId:"[typed]",memberValue:"Typed Input",memberLabel:"Typed Input",axis:a.axisLabel,axisLabel:a.axisLabel,memberKey:a.dimensionKey,dimensionIdKey:a.dimensionIdKey,hasTypedMembers:!0,typedMemberId:a.typedMemberId,typedMembers:[{axisId:a.axisId,axisLabel:a.axisLabel,typedMemberId:a.typedMemberId,memberLabel:a.axisLabel}]},order:0,removable:!1,periodStartDate:i,periodEndDate:i}):(1===o.size&&o.has("duration"),s.push({id:"typed-duration",title:`${n} `,description:this.formatPeriodDisplay(t,i),type:"dimension",dimensionData:{dimensionId:"typed-duration",axisId:a.axisId,memberId:"[typed]",memberValue:"Typed Input",memberLabel:"Typed Input",axis:a.axisLabel,axisLabel:a.axisLabel,memberKey:a.dimensionKey,dimensionIdKey:a.dimensionIdKey,hasTypedMembers:!0,typedMemberId:a.typedMemberId,typedMembers:[{axisId:a.axisId,axisLabel:a.axisLabel,typedMemberId:a.typedMemberId,memberLabel:a.axisLabel}]},order:0,removable:!1,periodStartDate:t,periodEndDate:i})),s}if(!e.members||!Array.isArray(e.members))return[];if(0===e.members.length)return[];const n=this.getPreferredLabel(e.labels,r)||e.conceptName,a=e.members[0],s=this.getPreferredLabel(a.labels,r)||a.conceptName,l={axisId:e.id,axisLabel:n,memberId:a.id,memberLabel:s,dimensionKey:`${n} | ${s}`,dimensionIdKey:`${e.id} | ${a.id}`},d=[];return 0===o.size?d.push({id:"default",title:l.memberLabel,description:"Default value column",type:"dimension",dimensionData:{dimensionId:"default",axisId:l.axisId,memberId:l.memberId,memberValue:l.memberLabel,memberLabel:l.memberLabel,axis:l.axisLabel,axisLabel:l.axisLabel,memberKey:l.dimensionKey,dimensionIdKey:l.dimensionIdKey},order:0,removable:!1,periodStartDate:t,periodEndDate:i}):1===o.size&&o.has("instant")?d.push({id:"instant",title:`${l.memberLabel}`,description:i,type:"dimension",dimensionData:{dimensionId:"instant",axisId:l.axisId,memberId:l.memberId,memberValue:l.memberLabel,memberLabel:l.memberLabel,axis:l.axisLabel,axisLabel:l.axisLabel,memberKey:l.dimensionKey,dimensionIdKey:l.dimensionIdKey},order:0,removable:!1,periodStartDate:i,periodEndDate:i}):1===o.size&&o.has("duration")?d.push({id:"duration",title:`${l.memberLabel}`,description:`${t} / ${i}`,type:"dimension",dimensionData:{dimensionId:"duration",axisId:l.axisId,memberId:l.memberId,memberValue:l.memberLabel,memberLabel:l.memberLabel,axis:l.axisLabel,axisLabel:l.axisLabel,memberKey:l.dimensionKey,dimensionIdKey:l.dimensionIdKey},order:0,removable:!1,periodStartDate:t,periodEndDate:i}):d.push({id:"duration",title:`${l.memberLabel}`,description:this.formatPeriodDisplay(t,i),type:"dimension",dimensionData:{dimensionId:"duration",axisId:l.axisId,memberId:l.memberId,memberValue:l.memberLabel,memberLabel:l.memberLabel,axis:l.axisLabel,axisLabel:l.axisLabel,memberKey:l.dimensionKey,dimensionIdKey:l.dimensionIdKey},order:0,removable:!1,periodStartDate:t,periodEndDate:i}),d}static generateMultiDimensionColumns(e,t,i,o,r="en"){e.some(e=>e.typedMember);const n=e.filter(e=>!!e.typedMember||!!(e.members&&Array.isArray(e.members)&&e.members.length>0));if(0===n.length)return[];const a=n.map(e=>{const t=this.getPreferredLabel(e.labels,r)||e.conceptName;if(e.typedMember)return{id:e.id,axisLabel:t,isTyped:!0,typedMemberId:e.typedMember.id,members:[{id:"[typed]",label:`${t}`}]};const i=this.getAllDimensionMembers(e.members);return{id:e.id,axisLabel:t,isTyped:!1,members:i.map(e=>({id:e.id,label:this.getPreferredLabel(e.labels,r)||e.conceptName}))}}),s=this.generateDimensionCombinations(a),l=[];return s.forEach((e,o)=>{const r=e.map(e=>e.memberLabel).join(" | "),n=e.filter(e=>e.isTyped),a=e.filter(e=>!e.isTyped),s={dimensionId:`multi_${o}`,memberValue:r,memberLabel:r,combinations:a.map(e=>({axisId:e.axisId,axisLabel:e.axisLabel,memberId:e.memberId,memberLabel:e.memberLabel})),typedMembers:n.map(e=>({axisId:e.axisId,axisLabel:e.axisLabel,typedMemberId:e.typedMemberId,memberLabel:e.memberLabel})),hasTypedMembers:n.length>0,memberKey:r,dimensionIdKey:[...a.map(e=>`${e.axisId}|${e.memberId}`),...n.map(e=>`${e.axisId}|[typed]`)].join("::")};l.push({id:`duration_${o}`,title:`${r}`,description:this.formatPeriodDisplay(t,i),type:"dimension",dimensionData:{...s,dimensionId:`duration_${o}`},order:o,removable:!1,periodStartDate:t,periodEndDate:i})}),l}static getAllDimensionMembers(e){if(!e||!Array.isArray(e))return[];const t=[];return e.forEach(e=>{t.push(e),e.children&&e.children.length>0&&t.push(...this.getAllDimensionMembers(e.children))}),t}static generateDimensionCombinations(e){if(0===e.length)return[];if(1===e.length)return e[0].members.map(t=>[{axisId:e[0].id,axisLabel:e[0].axisLabel,memberId:t.id,memberLabel:t.label,isTyped:e[0].isTyped||!1,typedMemberId:e[0].typedMemberId}]);const[t,...i]=e,o=this.generateDimensionCombinations(i),r=[];return t.members.forEach(e=>{0===o.length?r.push([{axisId:t.id,axisLabel:t.axisLabel,memberId:e.id,memberLabel:e.label,isTyped:t.isTyped||!1,typedMemberId:t.typedMemberId}]):o.forEach(i=>{r.push([{axisId:t.id,axisLabel:t.axisLabel,memberId:e.id,memberLabel:e.label,isTyped:t.isTyped||!1,typedMemberId:t.typedMemberId},...i])})}),r}static formatDateForDisplay(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}catch{return e}}static extractEntityName(e){try{const t=new URL(e).pathname.split("/");return t[t.length-1].replace(".xsd","").replace(/[^a-zA-Z0-9]/g," ").trim()||"Entity"}catch{return"Entity"}}static extractRoleTitle(e){if(!e)return"Unnamed Section";const t=e.match(/^\[[\d]+\]\s*(.+)$/);if(t)return t[1].trim();if(e.match(/^[a-z]+:[^:]*$/i)||e.match(/^urn:[^:]+:[^:]+/i)){const t=e.split(/[:\-]/);return t[t.length-1].replace(/[_\-]/g," ").replace(/\b\w/g,e=>e.toUpperCase())}return e.trim()||"Unnamed Section"}static extractRoleOrder(e){const t=e.match(/^\[([\d]+)\]/);return t?parseInt(t[1],10):0}static buildColumnsFromHypercubes(){return[{id:"default",label:"Values",type:"data"}]}}const k={en:{conceptInfo:{title:"Concept Information",conceptName:"Concept name",type:"Type",substitutionGroup:"Substitution group",periodType:"Period type",balance:"Balance",documentation:"Documentation",instant:"Instant",duration:"Duration",close:"Close"},form:{markAsComplete:"Mark as Complete",loading:"Loading form...",submit:"Validate",save:"Save",saveDraft:"Save Draft",savingDraft:"Saving draft",errors:"Errors",modified:"Modified",valid:"Valid",yes:"Yes",no:"No",noRoleSelected:"No Role Selected",pleaseSelectRole:"Please select a role from the list on the left.",expandPanel:"Expand side panel",collapsePanel:"Collapse side panel",validate:"Validate",preview:"Preview",download:"Download",cancelValidation:"Cancel Validation",lastValidationResults:"Last Validation Results",validationInProgress:"Validation In Progress",quickValidate:"Quick Validate"},filter:{selectRoles:"Select Roles",filterRoles:"Filter Roles",title:"Filter Roles",description:"Select the roles you want to display in the form. You can search and choose specific roles to focus on or manage all available roles.",searchPlaceholder:"Search..",clearSearch:"Clear search",showingResults:"Showing",of:"of",roles:"roles",matching:"matching",selectAll:"Select All",selectNone:"Select None",selectFiltered:"Select Filtered",deselectFiltered:"Deselect Filtered",deselectAll:"Deselect All",reset:"Reset",noRolesFound:"No roles found matching",tryDifferentSearch:"Try a different search term or clear the search.",noRolesAvailable:"No roles available.",cancel:"Cancel",applyFilter:"Apply Filter",showPeriodColumn:"Show Period Column:",additionalOptions:"Additional Options:",showPreviousYear:"Show previous year",duration:"Duration",instant:"Instant",uri:"URI",dimensionMemberSelection:"Dimension Member Selection",selectAllMembers:"Select All",clearMembers:"Clear",availableRoles:"Available Roles",chosenRoles:"Chosen Roles",roleCount:"role(s)",rolesSelected:"role(s) selected",addSelectedRole:"Add selected role",addAllRoles:"Add all roles",removeSelectedRole:"Remove selected role",removeAllRoles:"Remove all roles",advancedFilter:"Advanced Filter",backToFilterRoles:"← Back",showFactsOnly:"Show facts only",showFactsOnlyDescription:"Hide all blank rows and sections. Only roles and rows with at least one filled value will be shown.",searchByConcept:"Search by concept",searchByConceptDescription:"Type concept name or label to filter roles and rows. Press Apply Filter to apply.",searchByConceptPlaceholder:"Type concept name or label and press Apply Filter...",clearFilters:"Clear Filters",resetFilter:"Reset"},column:{addColumn:"Add Column",columnOptions:"Column Options",columnType:"Column Type",instantSingleDate:"Instant (single date)",durationDates:"Duration (start and end dates)",instantDate:"Instant Date",startPeriodDate:"Start Period Date",endPeriodDate:"End Period Date",availableDimensions:"Available Dimensions",dimensionsDescription:"Select dimensions to include in the column. Domain members can be selected here, while typed dimension values will be entered directly in the column header.",enterValue:"Enter value for",enterValuePlaceholder:"Enter value...",selectMember:"Select member:",noMembersAvailable:"No members available for this dimension",cancel:"Cancel",removeColumn:"Remove column",hideColumn:"Hide column",showColumn:"Double-click to show column",required:"required"},section:{enterPlaceholder:"Enter"},field:{selectOption:"Select an option...",select:"Select...",enterDetailedExplanation:"Enter detailed explanation...",enterAmountNoDecimals:"Enter amount (no decimals)",enterCurrency:"0.00",enterText:"Enter text",enterWholeNumber:"Enter whole number",enterPositiveNumber:"Enter positive number",enterDecimalValue:"Enter decimal value",enterNumberOfShares:"Enter number of shares",yearFormat:"YYYY",enterPercentage:"e.g. 0.25 for 25% or 0.2550 for 25.50%",emailPlaceholder:"email@example.com",urlPlaceholder:"https://example.com",phonePlaceholder:"+1 (555) 000-0000",enterValue:"Enter value",enterDetailedInformation:"Enter detailed information...",scale:"Scale",addText:"Add text",editText:"Edit",save:"Save",cancel:"Cancel",characters:"characters",editPeriod:"Edit Period",from:"From",to:"To",date:"Date",unit:"Unit",selectUnit:"Select Unit",leaveBlankForInf:"Leave blank for INF"},admin:{title:"Configure Roles",description:"Select which roles should display the 'Show Previous Year' checkbox and configure period type columns."},validation:{summary:"Please fix the following errors before submitting:",errorsFound:"errors found",unitRequired:"Unit is required. Please select a unit via the period icon."},xbrlValidation:{patternMismatch:"Value does not match required pattern: {{pattern}}",invalidPattern:"Invalid pattern configuration: {{pattern}}",exactLength:"Value must be exactly {{required}} characters (current: {{current}})",minLength:"Value must be at least {{required}} characters (current: {{current}})",maxLength:"Value must not exceed {{required}} characters (current: {{current}})",totalDigits:"Value must not exceed {{required}} total digits (current: {{current}})",ruleSummaryPattern:"Must match pattern: {{pattern}}",ruleSummaryExactLength:"Must be exactly {{required}} characters",ruleSummaryMinLength:"Minimum {{required}} characters",ruleSummaryMaxLength:"Maximum {{required}} characters",ruleSummaryTotalDigits:"Maximum {{required}} total digits"},error:{popup:{title:"Validation Errors",message:"Please fix the following validation errors before saving:",field:"Field:",value:"Value:",errors:"Errors:",clickToFocus:"Click to focus this field",ok:"OK"}},calculationWarning:{title:"Calculation warning",summaryLine:'Total "{{label}}" should equal {{calculated}}, but you entered {{entered}}.',childrenPrefix:"Children:",childAdded:"{{label}} = {{value}} (added)",childSubtracted:"{{label}} = {{value}} (subtracted, opposite balance)",added:"Added",subtracted:"Subtracted (opposite balance)"},formulaValidation:{dialogTitle:"Formula check results",allPassed:"All formula checks passed",summaryCount:"{{failed}} of {{total}} checks failed",summaryCountBreakdown:"{{warnings}} warnings, {{errors}} errors",severityWarning:"Warning",severityError:"Error",close:"Close"}},nl:{conceptInfo:{title:"Conceptinformatie",conceptName:"Conceptnaam",type:"Type",substitutionGroup:"Substitutiegroep",periodType:"Periodetype",balance:"Saldo",documentation:"Documentatie",instant:"Moment",duration:"Periode",close:"Sluiten"},form:{markAsComplete:"Markeren als volledig behandeld",loading:"Formulier laden...",submit:"Valideren",save:"Opslaan",saveDraft:"Concept opslaan",savingDraft:"Concept opslaan...",errors:"Fouten",modified:"Gewijzigd",valid:"Geldig",yes:"Ja",no:"Nee",noRoleSelected:"Geen rol geselecteerd",pleaseSelectRole:"Selecteer een rol uit de lijst aan de linkerkant.",expandPanel:"Zijpaneel uitvouwen",collapsePanel:"Zijpaneel inklappen",validate:"Valideren",preview:"Voorbeeld",download:"Downloaden",cancelValidation:"Validatie annuleren",lastValidationResults:"Laatste validatieresultaten",validationInProgress:"Validatie bezig",quickValidate:"Snel valideren"},filter:{selectRoles:"Rollen selecteren",filterRoles:"Rollen filteren",title:"Rollen filteren",description:"Selecteer de rollen die u in het formulier wilt weergeven. U kunt zoeken en specifieke rollen kiezen om op te focussen of alle beschikbare rollen beheren.",searchPlaceholder:"Zoek rollen op naam, ID of URI...",clearSearch:"Zoekopdracht wissen",showingResults:"Weergeven",of:"van",roles:"rollen",matching:"overeenkomend met",selectAll:"Alles selecteren",selectNone:"Niets selecteren",selectFiltered:"Gefilterd selecteren",deselectFiltered:"Gefilterd deselecteren",deselectAll:"Alles deselecteren",reset:"Resetten",noRolesFound:"Geen rollen gevonden die overeenkomen met",tryDifferentSearch:"Probeer een andere zoekterm of wis de zoekopdracht.",noRolesAvailable:"Geen rollen beschikbaar.",cancel:"Annuleren",applyFilter:"Filter toepassen",showPeriodColumn:"Periodekolom weergeven:",additionalOptions:"Aanvullende opties:",showPreviousYear:"Vorig jaar weergeven",duration:"Duur",instant:"Moment",uri:"URI",dimensionMemberSelection:"Dimensieleden selectie",selectAllMembers:"Alles selecteren",clearMembers:"Wissen",availableRoles:"Beschikbare rollen",chosenRoles:"Gekozen rollen",roleCount:"rol(len)",rolesSelected:"rol(len) geselecteerd",addSelectedRole:"Geselecteerde rol toevoegen",addAllRoles:"Alle rollen toevoegen",removeSelectedRole:"Geselecteerde rol verwijderen",removeAllRoles:"Alle rollen verwijderen",advancedFilter:"Geavanceerd filter",backToFilterRoles:"← Terug",showFactsOnly:"Alleen feiten weergeven",showFactsOnlyDescription:"Verberg alle lege rijen en secties. Alleen rollen en rijen met minimaal één ingevulde waarde worden weergegeven.",searchByConcept:"Zoeken op concept",searchByConceptDescription:"Typ een conceptnaam of label om rollen en rijen te filteren. Druk op Filter toepassen om te activeren.",searchByConceptPlaceholder:"Typ conceptnaam of label en druk op Filter toepassen...",clearFilters:"Filters wissen",resetFilter:"Resetten"},column:{addColumn:"Kolom toevoegen",columnOptions:"Kolomopties",columnType:"Kolomtype",instantSingleDate:"Moment (enkele datum)",durationDates:"Duur (begin- en einddatum)",instantDate:"Momentdatum",startPeriodDate:"Startdatum periode",endPeriodDate:"Einddatum periode",availableDimensions:"Beschikbare dimensies",dimensionsDescription:"Selecteer dimensies om in de kolom op te nemen. Domeinleden kunnen hier worden geselecteerd, terwijl getypte dimensiewaarden direct in de kolomkop worden ingevoerd.",enterValue:"Voer waarde in voor",enterValuePlaceholder:"Voer waarde in...",selectMember:"Selecteer lid:",noMembersAvailable:"Geen leden beschikbaar voor deze dimensie",cancel:"Annuleren",removeColumn:"Kolom verwijderen",hideColumn:"Kolom verbergen",showColumn:"Dubbelklik om kolom te tonen",required:"verplicht"},section:{enterPlaceholder:"Invoeren"},field:{selectOption:"Selecteer een optie...",select:"Selecteer...",enterDetailedExplanation:"Voer gedetailleerde uitleg in...",enterAmountNoDecimals:"Voer bedrag in (geen decimalen)",enterCurrency:"0,00",enterText:"Voer tekst in",enterWholeNumber:"Voer geheel getal in",enterPositiveNumber:"Voer positief getal in",enterDecimalValue:"Voer decimale waarde in",enterNumberOfShares:"Voer aantal aandelen in",yearFormat:"JJJJ",enterPercentage:"bijv. 0,25 voor 25% of 0,2550 voor 25,50%",emailPlaceholder:"email@voorbeeld.nl",urlPlaceholder:"https://voorbeeld.nl",phonePlaceholder:"+31 (0)20 123 4567",enterValue:"Voer waarde in",enterDetailedInformation:"Voer gedetailleerde informatie in...",scale:"Schaal",addText:"Tekst toevoegen",editText:"Bewerken",save:"Opslaan",cancel:"Annuleren",characters:"tekens",editPeriod:"Periode bewerken",from:"Van",to:"Tot",date:"Datum",unit:"Eenheid",selectUnit:"Selecteer eenheid",leaveBlankForInf:"Leeg laten voor INF"},admin:{title:"Rollen configureren",description:"Selecteer welke rollen het selectievakje 'Vorig jaar weergeven' moeten weergeven en configureer periodetype kolommen."},validation:{summary:"Corrigeer de volgende fouten voordat u indient:",errorsFound:"fouten gevonden",unitRequired:"Eenheid is verplicht. Selecteer een eenheid via het periodeicoon."},xbrlValidation:{patternMismatch:"Waarde voldoet niet aan het vereiste patroon: {{pattern}}",invalidPattern:"Ongeldige patternconfiguratie: {{pattern}}",exactLength:"Waarde moet exact {{required}} tekens bevatten (huidig: {{current}})",minLength:"Waarde moet minimaal {{required}} tekens bevatten (huidig: {{current}})",maxLength:"Waarde mag niet meer dan {{required}} tekens bevatten (huidig: {{current}})",totalDigits:"Waarde mag niet meer dan {{required}} cijfers bevatten (huidig: {{current}})",ruleSummaryPattern:"Moet overeenkomen met patroon: {{pattern}}",ruleSummaryExactLength:"Moet exact {{required}} tekens bevatten",ruleSummaryMinLength:"Minimaal {{required}} tekens",ruleSummaryMaxLength:"Maximaal {{required}} tekens",ruleSummaryTotalDigits:"Maximaal {{required}} cijfers"},error:{popup:{title:"Validatiefouten",message:"Corrigeer de volgende validatiefouten voordat u opslaat:",field:"Veld:",value:"Waarde:",errors:"Fouten:",clickToFocus:"Klik om dit veld te focussen",ok:"OK"}},calculationWarning:{title:"Berekeningswaarschuwing",summaryLine:'Totaal "{{label}}" zou {{calculated}} moeten zijn, maar u heeft {{entered}} ingevoerd.',childrenPrefix:"Onderdelen:",childAdded:"{{label}} = {{value}} (opgeteld)",childSubtracted:"{{label}} = {{value}} (afgetrokken, tegengestelde balans)",added:"Opgeteld",subtracted:"Afgetrokken (tegengestelde balans)"},formulaValidation:{dialogTitle:"Resultaten formulecontrole",allPassed:"Alle formulecontroles geslaagd",summaryCount:"{{failed}} van {{total}} controles mislukt",summaryCountBreakdown:"{{warnings}} waarschuwingen, {{errors}} fouten",severityWarning:"Waarschuwing",severityError:"Fout",close:"Sluiten"}}};class T{static setLanguage(e){k[e]?this.currentLanguage=e:(console.warn(`Language '${e}' not supported, falling back to 'en'`),this.currentLanguage="en")}static getLanguage(){return this.currentLanguage}static t(e,t){const i=e.split(".");let o=k[this.currentLanguage];for(const r of i){if(!o||"object"!=typeof o||!(r in o))return console.warn(`Translation key '${e}' not found for language '${this.currentLanguage}'`),e;o=o[r]}return t&&"string"==typeof o?this.interpolate(o,t):o}static interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,i)=>i in t?String(t[i]):e)}static has(e){const t=e.split(".");let i=k[this.currentLanguage];for(const o of t){if(!i||"object"!=typeof i||!(o in i))return!1;i=i[o]}return void 0!==i}static getAvailableLanguages(){return Object.keys(k)}}function E(e){return!!(null==e?void 0:e.toLowerCase().includes("totallabel"))}T.currentLanguage="en";class R{constructor(e=!1){this.DRAFT_DATA_KEY="jupiter-form-draft-data",this.DRAFT_METADATA_KEY="jupiter-form-draft-metadata",this.STORAGE_VERSION="1.0",this._storage=e?sessionStorage:localStorage,console.log(`💾 DraftStorageService initialized (using ${e?"sessionStorage":"localStorage"})`)}saveDraft(e,t){try{const i={formData:e,metadata:{...t,savedAt:(new Date).toISOString()},version:this.STORAGE_VERSION};return this._storage.setItem(this.DRAFT_DATA_KEY,JSON.stringify(i.formData)),this._storage.setItem(this.DRAFT_METADATA_KEY,JSON.stringify(i.metadata)),console.log("✅ Draft saved successfully",{entries:e.length,timestamp:i.metadata.savedAt,roles:t.selectedRoleIds.length,customColumns:t.customColumns.length}),!0}catch(i){return console.error("❌ Failed to save draft:",i),!1}}loadDraft(){try{const e=this._storage.getItem(this.DRAFT_DATA_KEY),t=this._storage.getItem(this.DRAFT_METADATA_KEY);if(!e||!t)return console.log("ℹ️ No saved draft found"),null;const i=JSON.parse(e),o=JSON.parse(t);return console.log("✅ Draft loaded successfully",{entries:i.length,savedAt:o.savedAt,roles:o.selectedRoleIds.length,customColumns:o.customColumns.length}),{formData:i,metadata:o,version:this.STORAGE_VERSION}}catch(e){return console.error("❌ Failed to load draft:",e),null}}hasDraft(){return null!==this._storage.getItem(this.DRAFT_DATA_KEY)&&null!==this._storage.getItem(this.DRAFT_METADATA_KEY)}getDraftMetadata(){try{const e=this._storage.getItem(this.DRAFT_METADATA_KEY);return e?JSON.parse(e):null}catch(e){return console.error("❌ Failed to load draft metadata:",e),null}}clearDraft(){try{return this._storage.removeItem(this.DRAFT_DATA_KEY),this._storage.removeItem(this.DRAFT_METADATA_KEY),console.log("🗑️ Draft cleared successfully"),!0}catch(e){return console.error("❌ Failed to clear draft:",e),!1}}getDraftAge(){const e=this.getDraftMetadata();if(!e)return null;const t=new Date(e.savedAt);return(new Date).getTime()-t.getTime()}isDraftStale(e){const t=this.getDraftAge();return null!==t&&t>e}extractCustomColumns(e){const t=[];return e.forEach(e=>{e.columns&&Array.isArray(e.columns)&&e.columns.forEach(i=>{t.push({sectionId:e.id,columnId:i.id,label:i.title,description:i.description,periodType:this._inferPeriodTypeFromColumn(i),date:i.periodStartDate,startDate:i.periodStartDate,endDate:i.periodEndDate,dimensionData:i.dimensionData})})}),t}_inferPeriodTypeFromColumn(e){return e.periodStartDate&&e.periodEndDate?"duration":"instant"}createMetadataSnapshot(e,t,i,o,r,n,a,s,l,d="en",c,p,u,h,m){return{periodStartDate:e,periodEndDate:t,language:i,reportingLanguage:d,selectedRoleIds:o,customColumns:this.extractCustomColumns(r),typedMemberData:n,periodPreferences:a,periodData:s,unitData:l,decimalsData:p,repeatCounts:c,roleCompletedStates:u,hiddenColumns:h,totalManuallyEditedData:m,schemaVersion:this.STORAGE_VERSION}}validateDraftCompatibility(e,t,i){const o=[];e.metadata.periodStartDate!==t&&o.push(`Draft period start (${e.metadata.periodStartDate}) differs from current (${t})`),e.metadata.periodEndDate!==i&&o.push(`Draft period end (${e.metadata.periodEndDate}) differs from current (${i})`);const r=this.getDraftAge();r&&r>6048e5&&o.push(`Draft is ${Math.floor(r/864e5)} days old`);return{compatible:0===o.length,warnings:o}}}class M extends Error{constructor(e,t,i="unsupported-syntax"){super(e),this.test=t,this.reason=i,this.name="FormulaExpressionError"}}const A=/\s*(?:(\$[A-Za-z_][\w-]*)|(-?\d+(?:\.\d+)?)|([A-Za-z][\w:-]*)|('[^']*')|(\()|(\))|(\+)|(-)|(=))/y;class j{constructor(e,t){this.tokens=e,this.test=t,this.pos=0}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}expect(e){const t=this.next();if(t.type!==e)throw new M(`Expected ${e} but got ${t.type} ("${t.value}")`,this.test,"parse-error");return t}parseBoolExpr(){const e=this.parseOrExpr();if("EOF"!==this.peek().type)throw new M(`Unexpected trailing token "${this.peek().value}"`,this.test,"unsupported-syntax");return e}parseOrExpr(){const e=[this.parseAndExpr()];for(;"IDENT"===this.peek().type&&"or"===this.peek().value;)this.next(),e.push(this.parseAndExpr());return 1===e.length?e[0]:{kind:"or",terms:e}}parseAndExpr(){const e=[this.parseBoolTerm()];for(;"IDENT"===this.peek().type&&"and"===this.peek().value;)this.next(),e.push(this.parseBoolTerm());return 1===e.length?e[0]:{kind:"and",terms:e}}parseBoolTerm(){const e=this.peek();if("IDENT"===e.type&&"not"===e.value){this.next(),this.expect("LPAREN");const e=this.parseOrExpr();return this.expect("RPAREN"),{kind:"not",arg:e}}if("IDENT"===e.type&&"empty"===e.value){this.next(),this.expect("LPAREN");const e=this.expect("VARIABLE").value;return this.expect("RPAREN"),{kind:"empty",variable:e}}if("IDENT"===e.type&&"xff:has-fallback-value"===e.value){this.next(),this.expect("LPAREN");const e=this.next();if("IDENT"!==e.type||"xs:QName"!==e.value)throw new M(`Expected xs:QName(...) inside xff:has-fallback-value(...), got "${e.value}"`,this.test,"unsupported-syntax");this.expect("LPAREN");const t=this.expect("STRING").value;return this.expect("RPAREN"),this.expect("RPAREN"),{kind:"hasFallbackValue",variableName:t}}const t=this.parseValueExpr(),i=this.peek();if("EQUALS"===i.type)return this.next(),{kind:"comparison",op:"=",left:t,right:this.parseValueExpr()};if("IDENT"===i.type&&"eq"===i.value)return this.next(),{kind:"comparison",op:"eq",left:t,right:this.parseValueExpr()};throw new M(`Expected a comparison operator ("=" or "eq") after value expression, got "${i.value}"`,this.test,"unsupported-syntax")}parseValueExpr(){const e=[];let t=1;for("PLUS"===this.peek().type?this.next():"MINUS"===this.peek().type&&(this.next(),t=-1),e.push({sign:t,term:this.parseValueTerm()});"PLUS"===this.peek().type||"MINUS"===this.peek().type;){const t="PLUS"===this.next().type?1:-1;e.push({sign:t,term:this.parseValueTerm()})}return 1===e.length&&1===e[0].sign?e[0].term:{kind:"additive",terms:e}}parseValueTerm(){const e=this.peek();if("NUMBER"===e.type)return this.next(),{kind:"number",value:Number(e.value)};if("STRING"===e.type)return this.next(),{kind:"string",value:e.value};if("VARIABLE"===e.type)return this.next(),{kind:"variable",name:e.value};if("IDENT"===e.type&&"sum"===e.value){this.next(),this.expect("LPAREN");const e=this.expect("VARIABLE").value;return this.expect("RPAREN"),{kind:"sum",variable:e}}if("LPAREN"===e.type){this.next();const e=this.parseValueExpr();return this.expect("RPAREN"),e}throw new M(`Expected a number, variable, sum(...), or parenthesized expression, got "${e.value}"`,this.test,"unsupported-syntax")}}function P(e,t){return e.get(t)}function L(e,t,i){switch(e.kind){case"number":case"string":return e.value;case"sum":return function(e,t,i){const o=P(t,e);return void 0===o?0:(Array.isArray(o)?o:[o]).reduce((t,o)=>{if("string"==typeof o)throw new M(`Variable "$${e}" resolved to a non-numeric value ("${o}") and cannot be used in sum(...)`,i,"unsupported-syntax");return t+o},0)}(e.variable,t,i);case"variable":{const o=P(t,e.name);if(void 0===o)throw new M(`Variable "$${e.name}" has no bound fact and cannot be evaluated directly (only sum()/empty() tolerate an unbound variable)`,i,"unbound-variable");if(Array.isArray(o))throw new M(`Variable "$${e.name}" is a sequence and must be wrapped in sum(...) to be used in arithmetic`,i,"unsupported-syntax");return o}case"additive":return e.terms.reduce((e,{sign:o,term:r})=>{const n=L(r,t,i);if("string"==typeof n)throw new M(`Non-numeric value ("${n}") cannot be used in arithmetic (+ / -)`,i,"unsupported-syntax");return e+o*n},0)}}function N(e,t,i,o){switch(e.kind){case"or":return e.terms.some(e=>N(e,t,i,o));case"and":return e.terms.every(e=>N(e,t,i,o));case"not":return!N(e.arg,t,i,o);case"empty":{const i=P(t,e.variable);return void 0===i||Array.isArray(i)&&0===i.length}case"hasFallbackValue":{const t=o.get(e.variableName);if(void 0===t)throw new M(`xff:has-fallback-value(xs:QName('${e.variableName}')) could not be evaluated — no fallback-usage tracked for this variable (either not one of this assertion's FACT_VARIABLEs, or it matched zero facts with no fallbackValue declared)`,i,"unbound-variable");return t}case"comparison":{const o=L(e.left,t,i),r=L(e.right,t,i);return"string"==typeof o||"string"==typeof r?String(o)===String(r):Math.abs(o-r)<.01}}}function O(e,t,i=new Map){const o=function(e){const t=[];A.lastIndex=0;let i=0;for(;i<e.length;){A.lastIndex=i;const o=A.exec(e);if(!o||o.index!==i){if(/^\s*$/.test(e.slice(i)))break;throw new M(`Unrecognized token at position ${i}: "${e.slice(i,i+10)}..."`,e,"unsupported-syntax")}const[r,n,a,s,l,d,c,p,u,h]=o;n?t.push({type:"VARIABLE",value:n.slice(1)}):a?t.push({type:"NUMBER",value:a}):s?t.push({type:"IDENT",value:s}):l?t.push({type:"STRING",value:l.slice(1,-1)}):d?t.push({type:"LPAREN",value:d}):c?t.push({type:"RPAREN",value:c}):p?t.push({type:"PLUS",value:p}):u?t.push({type:"MINUS",value:u}):h&&t.push({type:"EQUALS",value:h}),i+=r.length}return t.push({type:"EOF",value:""}),t}(e);return N(new j(o,e).parseBoolExpr(),t,e,i)}const V=/^\.\s*(eq|ne|gt|lt|ge|le)\s+(-?\d+(?:\.\d+)?)$/;function z(e){return!!(null==e?void 0:e.toLowerCase().includes("totallabel"))}function U(e){return!!(null==e?void 0:e.toLowerCase().includes("negatedtotallabel"))}function J(e,t,i=0){if(!t.isAbstract(e))return e;if(i>5)return null;const o=t.getChildren(e).find(e=>z(t.getPreferredLabel(e)));return o?J(o,t,i+1):null}function B(e,t,i,o,r){if(i<0)return o;const n=e[t];if(U(r.getPreferredLabel(n)))return o.length>0?o:[e[i]];if(o.length>0)return[e[i],...o];if(U(r.getPreferredLabel(e[i]))){let t=-1;for(let o=i-1;o>=0;o--)if(z(r.getPreferredLabel(e[o]))){t=o;break}return t>=0?[e[t],e[i]]:[e[i]]}return[e[i]]}function q(e){return null!=e&&""!==e}function H(e){const t=[];for(const i of Object.keys(e)){const o=e[i]||{};for(const e of Object.keys(o))q(o[e])&&t.push({conceptId:i,columnId:e})}return t}function Y(e,t,i,o,r,n){const a={conceptId:e.id,qname:e.name,balance:e.balance,effectivePeriodRole:e.effectivePeriodRole};i.set(e.id,a),(t.get(e.name)??t.set(e.name,[]).get(e.name)).push(a);const s=e.children||[],l=s.length>0,d=!0===r.get(e.name);(!o.has(e.name)||l&&!d)&&(o.set(e.name,e.id),r.set(e.name,l)),n.set(e.id,s.map(e=>e.id)),s.forEach(e=>Y(e,t,i,o,r,n))}function K(e,t,i){t.has(e.conceptName)||t.set(e.conceptName,e.id),i.has(e.conceptName)||i.set(e.conceptName,(e.children||[]).map(e=>e.id)),(e.children||[]).forEach(e=>K(e,t,i))}const W={getId:e=>e.id,getPreferredLabel:e=>e.preferredLabel,isAbstract:e=>!0===e.abstract,getChildren:e=>e.children||[]};function G(e,t,i,o,r,n,a){const s=new Map,l=new Map,d=new Map,c=new Map,p=new Map,u=new Map,h=new Map;i.forEach(e=>{const t=new Map,i=new Map,o=new Map;e.concepts.forEach(e=>Y(e,s,l,i,o,t)),c.set(e.roleURI,t),d.set(e.roleURI,i),p.set(e.roleURI,function(e,t){const i=new Map;function o(e,o){const r=[];for(const i of o){const e=J(i,t);e&&r.push(t.getId(e))}0!==r.length&&i.set(t.getId(e),r)}return function e(i){for(let r=0;r<i.length;r++){const n=i[r];if(z(t.getPreferredLabel(n))&&0===t.getChildren(n).length){let e=-1;for(let o=r-1;o>=0;o--)if(z(t.getPreferredLabel(i[o]))){e=o;break}const a=i.slice(e+1,r),s=B(i,r,e,a,t);s.length>0&&o(n,s)}const a=t.getChildren(n);a.length>0&&e(a)}}(e),i}(e.concepts,W));for(const r of t.keys())h.set(r,e.roleURI);e.columns&&u.set(e.roleURI,e.columns)});const m=new Map,f=new Map,g=new Map;return(o||[]).forEach(e=>{e.items.forEach(e=>{e.dimensions.forEach(e=>{m.has(e.conceptName)||m.set(e.conceptName,e.id),(e.members||[]).forEach(e=>K(e,f,g))})})}),{formData:e,columns:t,periodStartDate:r,periodEndDate:n,conceptByQName:s,conceptById:l,conceptIdByQNamePerRole:d,childrenByRole:c,totalGroupChildrenByRole:p,dimensionQNameToId:m,memberQNameToId:f,memberChildrenByQName:g,columnsByRole:u,roleURIByConceptId:h,allCandidates:H(e),typedMemberData:a??{}}}function Q(e){return`${e.conceptId}::${e.columnId}`}function X(e,t){return re(e.filters.map(i=>oe(i,t.allCandidates,t,e.filters)))}function Z(e,t){var i;const o=e.roleURIByConceptId.get(t.conceptId);return(o?null==(i=e.columnsByRole.get(o))?void 0:i.find(e=>e.id===t.columnId):void 0)??e.columns.find(e=>e.id===t.columnId)}function ee(e,t,i){if(!(null==e?void 0:e.dimensionData))return!1;return!(e.dimensionData.axisId!==t||void 0!==i&&e.dimensionData.memberId!==i)||(e.dimensionData.combinations||[]).some(e=>e.axisId===t&&(void 0===i||e.memberId===i))}function te(e,t){return{start:(null==e?void 0:e.periodStartDate)??t.periodStartDate,end:(null==e?void 0:e.periodEndDate)??t.periodEndDate}}function ie(e,t,i,o){var r,n;switch(e.type){case"CONCEPT_NAME":{const o=e.attributes["concept.qname"],r=o?i.conceptByQName.get(o):void 0;if(!r||0===r.length)return[];const n=new Set(r.map(e=>e.conceptId));return t.filter(e=>n.has(e.conceptId))}case"CONCEPT_BALANCE":{const o=e.attributes.balance;return t.filter(e=>{var t;return(null==(t=i.conceptById.get(e.conceptId))?void 0:t.balance)===o})}case"CONCEPT_RELATION":{const o=e.attributes.qname,a=e.attributes.linkrole,s=e.attributes.axis,l=o&&a?null==(r=i.conceptIdByQNamePerRole.get(a))?void 0:r.get(o):void 0,d=a?i.childrenByRole.get(a):void 0;if(!l||!d)return[];let c;if("descendant"===s)c=function(e,t){const i=[],o=[...e.get(t)||[]],r=new Set;for(;o.length>0;){const t=o.pop();r.has(t)||(r.add(t),i.push(t),o.push(...e.get(t)||[]))}return i}(d,l);else{const e=d.get(l)||[];c=e.length>0?e:(null==(n=i.totalGroupChildrenByRole.get(a??""))?void 0:n.get(l))||[]}const p=new Set(c);return t.filter(e=>p.has(e.conceptId))}case"EXPLICIT_DIMENSION":{const r=e.attributes["dimension.qname"],n=e.attributes["member.qname"],a=r?i.dimensionQNameToId.get(r):void 0;if(!a)return[];if(n&&"child"===e.attributes["member.axis"])return function(e,t,i,o,r){var n,a;const s=o.memberChildrenByQName.get(e)||[];if(s.length>0){const e=i.filter(e=>s.some(i=>ee(Z(o,e),t,i)));if(e.length>0)return e}const l=r.find(e=>"CONCEPT_RELATION"===e.type&&"descendant"===e.attributes.axis),d=null==l?void 0:l.attributes.linkrole,c=null==l?void 0:l.attributes.qname,p=c&&d?null==(n=o.conceptIdByQNamePerRole.get(d))?void 0:n.get(c):void 0,u=new Set(p&&d&&(null==(a=o.childrenByRole.get(d))?void 0:a.get(p))||[]);return 0===u.size?[]:i.filter(e=>!u.has(e.conceptId))}(n,a,t,i,o);const s=n?i.memberQNameToId.get(n):void 0;return t.filter(e=>ee(Z(i,e),a,s))}case"TYPED_DIMENSION":{const o=e.attributes["dimension.qname"],r=o?i.dimensionQNameToId.get(o):void 0;return r?t.filter(e=>function(e,t,i){if(!function(e,t){return!!(null==e?void 0:e.dimensionData)&&(void 0!==e.dimensionData.typedMemberId&&e.dimensionData.axisId===t||(e.dimensionData.typedMembers||[]).some(e=>e.axisId===t))}(Z(e,t),i))return!1;const o=e.typedMemberData[t.columnId];return void 0===o||!!o[i]}(i,e,r)):[]}case"PERIOD_INSTANT":case"PERIOD_END":{const o=e.attributes.date;return t.filter(e=>function(e,t,i){const o=function(e){if(e)return e.startsWith("$")?e.slice(1):e}(t);if(!o)return!1;const r=function(e,t){const i=e.includes("StartDate"),o=e.includes("EndDate")||"FinancialReportingPeriodCurrentEndDateParam"===e;if(e.startsWith("FinancialReportingPeriodCurrent"))return i?{start:t.periodStartDate}:o?{end:t.periodEndDate}:void 0;if(e.startsWith("FinancialReportingPeriodPrePrevious")||e.startsWith("FinancialReportingPeriodPrevious")){const e=function(e){return e.columns.find(t=>void 0!==t.periodEndDate&&t.periodEndDate<e.periodEndDate)}(t);if(!e)return;return i?{start:e.periodStartDate}:o?{end:e.periodEndDate}:void 0}}(o,i);if(!r)return!1;const n=te(e,i),a=r.end??r.start;return n.end===a}(Z(i,e),o,i))}case"OR_FILTER":return function(e){const t=new Map;return e.forEach(e=>e.forEach(e=>t.set(Q(e),e))),Array.from(t.values())}(e.children.map(e=>oe(e,t,i,o)));case"ASPECT_COVER":case"UNKNOWN":return t;default:return[]}}function oe(e,t,i,o){const r=ie(e,t,i,o);if(!e.complement)return r;const n=new Set(r.map(Q));return t.filter(e=>!n.has(Q(e)))}function re(e){return 0===e.length?[]:e.reduce((e,t)=>{const i=new Set(t.map(Q));return e.filter(e=>i.has(Q(e)))})}function ne(e){return e.some(e=>"PERIOD_INSTANT"===e.type||"PERIOD_END"===e.type||"OR_FILTER"===e.type&&ne(e.children))}function ae(e,t,i){if(e.length<=1||ne(t.filters))return e;const o=e.filter(e=>te(Z(i,e),i).end===i.periodEndDate);return o.length>0?o:e}function se(e,t){const i=function(e,t){const i=new Map;e.forEach(e=>{var o;const r=(null==(o=t.conceptById.get(e.conceptId))?void 0:o.qname)??e.conceptId,n=`${e.columnId}::${r}`,a=i.get(n);a?a.push(e):i.set(n,[e])});const o=[];return i.forEach(e=>{if(e.length<=1)return void o.push(...e);const i=e.map(e=>{var i;return null==(i=t.conceptById.get(e.conceptId))?void 0:i.effectivePeriodRole}),r=e.filter((e,t)=>"periodEndLabel"===i[t]),n=new Set(i).size>1;o.push(...n&&r.length>0?r:e)}),o}(ae(X(e,t),e,t),t),o=i.map(e=>{var i;return function(e){if(null==e||""===e)return;const t=parseFloat(String(e));return Number.isNaN(t)?String(e):t}(null==(i=t.formData[e.conceptId])?void 0:i[e.columnId])}).filter(e=>void 0!==e);if(e.bindAsSequence){if(0===o.length&&"()"===e.fallbackValue)return[];if(0===o.length)return;return o}if(0!==o.length)return o.length>1&&console.warn(`[formula-variable-resolver] Variable "${e.name}" is scalar (bindAsSequence: false) but matched ${o.length} facts; using the first match by column order. This can legitimately happen when filters under-constrain the candidate set.`),o[0]}function le(e,t){return X(e,t).length}function de(e,t){return!(le(e,t)>0)&&(void 0!==e.fallbackValue||void 0)}function ce(e){const t=[];for(const i of e)if("CONCEPT_NAME"===i.type){const e=i.attributes["concept.qname"];e&&t.push(e)}else"OR_FILTER"===i.type&&t.push(...ce(i.children));return t}function pe(e){return ce(e.filters)}function ue(e,t,i){const o=i.columns.map(e=>({conceptId:t,columnId:e.id}));return re(e.filters.map(t=>oe(t,o,i,e.filters))).map(e=>e.columnId)}class he{evaluate(e,t,i){var o;const r=null==(o=e.formula)?void 0:o[0];if(!r)return[];const n=[];for(const a of r.roles)for(const e of a.assertions)n.push(this._evaluateAssertion(e,a,t,i));return n}summarize(e){const t={totalAssertions:e.length,evaluated:0,skipped:0,passed:0,failed:0,failedWarnings:0,failedErrors:0};for(const i of e)i.skipped?t.skipped+=1:(t.evaluated+=1,i.satisfied?t.passed+=1:(t.failed+=1,"ERROR"===i.severity?t.failedErrors+=1:t.failedWarnings+=1));return t}_evaluateAssertion(e,t,i,o){try{const r=function(e,t){const i=new Map;for(const o of e.variables)i.set(o.name,se(o,t));return i}(e,i);if("VALUE_ASSERTION"===e.type){const i=function(e,t){for(const i of e.variables)if(void 0===t.get(i.name))return{satisfied:!1,skipReason:"unresolvable"};return{satisfied:!0}}(e,r);if(!i.satisfied)return this._skippedResult(e,t,i.skipReason??"unresolvable")}const n=function(e,t){var i;if(!(null==(i=e.test)?void 0:i.includes("has-fallback-value"))&&!e.preconditions.some(e=>e.test.includes("has-fallback-value")))return new Map;const o=new Map;for(const r of e.variables){const e=de(r,t);void 0!==e&&o.set(r.name,e)}return o}(e,i),a=function(e,t,i=new Map){if(0===e.length)return{satisfied:!0};for(const r of e){let e;try{e=O(r.test,t,i)}catch(o){if(o instanceof M)return{satisfied:!1,skipReason:"unresolvable"};throw o}if(!e)return{satisfied:!1,skipReason:"precondition"}}return{satisfied:!0}}(e.preconditions,r,n);if(!a.satisfied)return this._skippedResult(e,t,a.skipReason??"unresolvable");if("EXISTENCE_ASSERTION"===e.type){const r=1===e.variables.length?le(e.variables[0],i):function(e,t){const i=new Map;for(const o of e)for(const e of X(o,t))i.set(Q(e),e);return i.size}(e.variables,i),n=function(e,t){const i=(e??"").trim();return""===i?t>0:i.split(/\bor\b/).some(e=>{const o=V.exec(e.trim());if(!o)throw new M(`Unsupported existence-assertion test shape: "${e.trim()}"`,i,"unsupported-syntax");const[,r,n]=o;return function(e,t,i){switch(e){case"eq":return t===i;case"ne":return t!==i;case"gt":return t>i;case"lt":return t<i;case"ge":return t>=i;case"le":return t<=i}}(r,t,Number(n))})}(e.test,r);return this._evaluatedResult(e,t,i,n,o,r)}const s=O(e.test,r,n);return this._evaluatedResult(e,t,i,s,o)}catch(r){if(r instanceof M)return console.warn(`[FormulaValidationService] Assertion "${e.id}" could not be evaluated (${r.reason}): ${r.message}`),this._skippedResult(e,t,"unresolvable");throw r}}_skippedResult(e,t,i){return{assertionId:e.id,roleURI:t.roleURI,roleLabel:t.role,type:e.type,severity:e.severity,satisfied:!1,skipped:!0,skipReason:i}}_evaluatedResult(e,t,i,o,r,n){const a=o?void 0:this._pickMessage(e,r);return{assertionId:e.id,roleURI:t.roleURI,roleLabel:t.role,type:e.type,severity:e.severity,satisfied:o,skipped:!1,message:a,matchedFactCount:n,conceptLinks:a?this._buildConceptLinks(e,t.roleURI,i,a):void 0}}_pickMessage(e,t){const i=e.messages;if(0===i.length)return;const o=i.find(e=>e.xmlLang===t)??i.find(e=>"en"===e.xmlLang)??i[0];return this._stripTechnicalDetail(o.text)}_stripTechnicalDetail(e){const t=e.indexOf("{");return-1===t?e.trim():e.slice(0,t).replace(/\|\s*$/,"").trim()}_buildConceptLinks(e,t,i,o){var r,n,a;const s=[],l=new Set;for(const d of e.variables)for(const e of pe(d)){const c=(null==(r=i.conceptIdByQNamePerRole.get(t))?void 0:r.get(e))??(null==(a=null==(n=i.conceptByQName.get(e))?void 0:n[0])?void 0:a.conceptId);if(!c)continue;const p=e.includes(":")?e.split(":").pop():e;if(l.has(p))continue;if(!new RegExp("`"+this._escapeRegExp(p)+"`").test(o))continue;const u=ue(d,c,i);s.push({label:p,conceptQName:e,conceptId:c,columnId:u[0]}),l.add(p)}return s}_escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}class me{static findMatchingFact(e,t){if(!e||0===e.length)return null;const i=e.filter(e=>this.matchesPeriod(e,t));if(0===i.length)return null;const o=i.filter(e=>this.matchesDimensions(e,t));if(0===o.length)return null;if(o.length>1&&t.unit){const e=o.find(e=>this.matchesUnit(e,t));if(e)return e}return o[0]}static matchesPeriod(e,t){const i=this.parsePeriod(e.period);return"instant"===t.periodType&&t.periodInstantDate?i.isInstant&&i.instantDate===t.periodInstantDate:"duration"===t.periodType&&t.periodStartDate&&t.periodEndDate?!i.isInstant&&i.startDate===t.periodStartDate&&i.endDate===t.periodEndDate:t.periodInstantDate?i.isInstant&&i.instantDate===t.periodInstantDate:!t.periodStartDate||!t.periodEndDate||!i.isInstant&&i.startDate===t.periodStartDate&&i.endDate===t.periodEndDate}static matchesDimensions(e,t){const i=e.dimensions||[],o=this.extractDimensionsFromContext(t);if(0===o.length)return 0===i.length;if(0===i.length&&o.length>0)return!1;if(i.length!==o.length)return!1;return o.every(e=>i.some(t=>{if(!(this.normalizeAxisId(t.dimension)===this.normalizeAxisId(e.axisId)))return!1;if("explicit"===t.dimensionType&&e.memberId){return this.normalizeMemberId(t.member||"")===this.normalizeMemberId(e.memberId)}return!("typed"!==t.dimensionType||!e.isTyped)}))}static matchesUnit(e,t){if(!t.unit||!e.unitMeasure)return!0;return this.normalizeUnit(e.unitMeasure)===this.normalizeUnit(t.unit)}static parsePeriod(e){if(e.includes(" / ")){const[t,i]=e.split(" / ").map(e=>e.trim());return{isInstant:!1,startDate:t,endDate:i}}return{isInstant:!0,instantDate:e.trim()}}static extractDimensionsFromContext(e){if(!e.dimensionData)return[];const t=[];return e.dimensionData.combinations&&e.dimensionData.combinations.length>0&&e.dimensionData.combinations.forEach(e=>{t.push({axisId:e.axisId,memberId:e.memberId})}),e.dimensionData.typedMembers&&e.dimensionData.typedMembers.length>0&&e.dimensionData.typedMembers.forEach(e=>{t.push({axisId:e.axisId,memberId:"[typed]",isTyped:!0})}),t}static normalizeAxisId(e){if(!e)return"";if(e.includes(":")){const t=e.split(":");return t[1]||t[0]}if(e.includes("_")){e.split("_");const t=e.lastIndexOf("_");if(t>0)return e.substring(t+1)}return e}static normalizeMemberId(e){if(!e)return"";if(e.includes(":")){const t=e.split(":");return t[1]||t[0]}if(e.includes("_")){const t=e.lastIndexOf("_");if(t>0)return e.substring(t+1)}return e}static normalizeUnit(e){if(!e)return"";const t=e.split(":");return t.length>1?t[1]:t[0]}static extractTypedValues(e,t){const i={};if(!e||0===e.length)return i;return e.filter(e=>this.matchesPeriod(e,t)&&this.matchesDimensions(e,t)).forEach(e=>{e.dimensions&&e.dimensions.forEach(e=>{if("typed"===e.dimensionType&&e.typedMemberValue){const t=this.normalizeAxisId(e.dimension);i[t]=e.typedMemberValue}})}),i}static debugMatch(e,t){console.log("🔍 [FactMatcher] Debug Match"),console.log(" Context:",{conceptId:t.conceptId,columnId:t.columnId,period:"instant"===t.periodType?t.periodInstantDate:`${t.periodStartDate} / ${t.periodEndDate}`,dimensions:this.extractDimensionsFromContext(t)}),console.log(" Facts:",e.map(e=>{var t;return{value:e.value,period:e.period,dimensions:null==(t=e.dimensions)?void 0:t.map(e=>`${e.dimension}:${e.member}`)}}));const i=this.findMatchingFact(e,t);console.log(" Match Result:",i?i.value:"No match")}}class fe{static validateConceptValue(e,t,i){const o=[];if(null==t||""===t)return{valid:!0,errors:[]};if(!e||!i||0===i.length)return{valid:!0,errors:[]};const r=this.findDatatype(e,i);if(!r||!r.validation)return{valid:!0,errors:[]};const n=r.validation,a=String(t);if(n.pattern){const e=this.validatePattern(a,n.pattern);e&&o.push(e)}if(void 0!==n.length){const e=this.validateExactLength(a,n.length);e&&o.push(e)}if(void 0!==n.minLength){const e=this.validateMinLength(a,n.minLength);e&&o.push(e)}if(void 0!==n.maxLength){const e=this.validateMaxLength(a,n.maxLength);e&&o.push(e)}if(void 0!==n.totalDigits){const e=this.validateTotalDigits(a,n.totalDigits);e&&o.push(e)}return{valid:0===o.length,errors:o}}static findDatatype(e,t){let i=t.find(t=>t.type===e);if(i)return i;const o=new Set;let r=e;for(;r&&!o.has(r)&&(o.add(r),i=t.find(e=>e.type===r),i);){if(i.validation)return i;r=i.basetype}}static validatePattern(e,t){try{if(!new RegExp(`^${t}$`).test(e))return{type:"pattern",message:T.t("xbrlValidation.patternMismatch",{pattern:t}),expectedValue:t,actualValue:e}}catch(i){return console.error(`Invalid regex pattern: ${t}`,i),{type:"pattern",message:T.t("xbrlValidation.invalidPattern",{pattern:t}),expectedValue:t,actualValue:e}}return null}static validateExactLength(e,t){return e.length!==t?{type:"length",message:T.t("xbrlValidation.exactLength",{required:t,current:e.length}),expectedValue:t,actualValue:e.length}:null}static validateMinLength(e,t){return e.length<t?{type:"minLength",message:T.t("xbrlValidation.minLength",{required:t,current:e.length}),expectedValue:t,actualValue:e.length}:null}static validateMaxLength(e,t){return e.length>t?{type:"maxLength",message:T.t("xbrlValidation.maxLength",{required:t,current:e.length}),expectedValue:t,actualValue:e.length}:null}static validateTotalDigits(e,t){const i=e.replace(/[^\d]/g,"");return i.length>t?{type:"totalDigits",message:T.t("xbrlValidation.totalDigits",{required:t,current:i.length}),expectedValue:t,actualValue:i.length}:null}static getValidationRulesSummary(e,t){if(!e||!t)return[];const i=this.findDatatype(e,t);if(!i||!i.validation)return[];const o=i.validation,r=[];return o.pattern&&r.push(T.t("xbrlValidation.ruleSummaryPattern",{pattern:o.pattern})),void 0!==o.length&&r.push(T.t("xbrlValidation.ruleSummaryExactLength",{required:o.length})),void 0!==o.minLength&&r.push(T.t("xbrlValidation.ruleSummaryMinLength",{required:o.minLength})),void 0!==o.maxLength&&r.push(T.t("xbrlValidation.ruleSummaryMaxLength",{required:o.maxLength})),void 0!==o.totalDigits&&r.push(T.t("xbrlValidation.ruleSummaryTotalDigits",{required:o.totalDigits})),r}}const ge={"nl-types:formattedExplanationItemType":{fieldType:"textarea",placeholder:T.t("field.enterDetailedExplanation")},"nl-types:monetaryNoDecimals20ItemType":{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!1,step:1,placeholder:T.t("field.enterAmountNoDecimals")},"xbrli:monetaryItemType":{fieldType:"currency",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterCurrency")},"xbrli:stringItemType":{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterText")},"xbrli:dateItemType":{fieldType:"date",htmlInputType:"date"},"xbrli:dateTimeItemType":{fieldType:"datetime",htmlInputType:"datetime-local"},"xbrli:integerItemType":{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,step:1,placeholder:T.t("field.enterWholeNumber")},"xbrli:nonNegativeIntegerItemType":{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:0,step:1,placeholder:T.t("field.enterPositiveNumber")},"xbrli:positiveIntegerItemType":{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:1,step:1,placeholder:T.t("field.enterPositiveNumber")},"xbrli:decimalItemType":{fieldType:"decimal",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:"any",placeholder:T.t("field.enterDecimalValue")},"xbrli:sharesItemType":{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,min:0,step:.01,placeholder:T.t("field.enterNumberOfShares")},"xbrli:shares":{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,min:0,step:.01,placeholder:T.t("field.enterNumberOfShares")},"xbrli:gYearItemType":{fieldType:"number",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:1900,max:2100,step:1,placeholder:T.t("field.yearFormat")},"xbrli:booleanItemType":{fieldType:"boolean"},"xbrli:pureItemType":{fieldType:"percentage",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterPercentage")},"xbrli:percentItemType":{fieldType:"percentage",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterPercentage")},"xbrli:emailItemType":{fieldType:"email",htmlInputType:"email",placeholder:T.t("field.emailPlaceholder")},"xbrli:urlItemType":{fieldType:"url",htmlInputType:"url",placeholder:T.t("field.urlPlaceholder")},"xbrli:telephoneItemType":{fieldType:"tel",htmlInputType:"tel",placeholder:T.t("field.phonePlaceholder")}};function be(e,t){if(!e)return{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterValue")};if(t&&t.length>0){const i=_e(e,t);if(i.length>0){return Ie(i,t)}}if(console.log(`⚠️ [Type Resolution Fallback] Using pattern matching for: ${e}`),ge[e])return ge[e];const i=e.toLowerCase();if(i.includes("monetary"))return i.includes("nodecimals")||i.includes("no-decimals")?{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!1,step:1,placeholder:T.t("field.enterAmountNoDecimals")}:{fieldType:"currency",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterCurrency")};if(i.includes("explanation")||i.includes("description")||i.includes("notes")||i.includes("formatted"))return{fieldType:"textarea",placeholder:T.t("field.enterDetailedInformation")};if(i.includes("date"))return i.includes("time")?{fieldType:"datetime",htmlInputType:"datetime-local"}:{fieldType:"date",htmlInputType:"date"};if(i.includes("boolean")||i.includes("bool"))return{fieldType:"boolean"};if(i.includes("integer")||i.includes("int")){const e=i.includes("nonnegative")||i.includes("non-negative");return{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:i.includes("positive")?1:e?0:void 0,step:1,placeholder:T.t("field.enterWholeNumber")}}return i.includes("decimal")||i.includes("numeric")||i.includes("number")?{fieldType:"decimal",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:"any",placeholder:T.t("field.enterDecimalValue")}:i.includes("percent")||i.includes("pure")?{fieldType:"percentage",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterPercentage")}:{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterValue")}}function ve(e){return"textarea"===e}function ye(e){return"boolean"===e}function xe(e){return["number","decimal","integer","currency","percentage"].includes(e)}function _e(e,t){const i=[];if(!e)return i;if(!t||0===t.length)return i.push(e),i;let o=e;const r=new Set;for(;o;){if(i.push(o),r.has(o)){console.warn(`Circular reference detected in datatype hierarchy for type: ${o}`);break}r.add(o);const e=t.find(e=>e.type===o);if(!e||!e.basetype||""===e.basetype.trim())break;o=e.basetype}return i}function De(e,t){if(e&&0!==e.length&&t&&0!==t.length)for(const i of e){const e=t.find(e=>e.type===i);if(e&&e.enumerations&&e.enumerations.length>0)return e.enumerations.map(e=>({id:e.id||e.value,value:e.value,label:e.value}))}}function Ie(e,t){if(!e||0===e.length)return{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterValue")};if(t&&t.length>0){const i=De(e,t);if(i&&i.length>0)return{fieldType:"select",enumerations:i,placeholder:T.t("field.selectOption")}}const i=e.map(e=>e.toLowerCase()),o=i.join("|");if(e.some(e=>"nl-types:formattedExplanationItemType"===e)||o.includes("formattedexplanation")||o.includes("formatted")&&o.includes("explanation"))return{fieldType:"textarea",placeholder:T.t("field.enterDetailedExplanation")};if(i.some(e=>e.includes("date")))return o.includes("datetime")||o.includes("time")?{fieldType:"datetime",htmlInputType:"datetime-local"}:{fieldType:"date",htmlInputType:"date"};if(i.some(e=>e.includes("boolean")||e.includes("bool")))return{fieldType:"boolean"};if(i.some(e=>e.includes("integer")||"integer"===e)){const e=o.includes("nonnegative")||o.includes("non-negative");return{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:o.includes("positive")?1:e?0:void 0,step:1,placeholder:T.t("field.enterWholeNumber")}}return i.some(e=>e.includes("percent")||e.includes("pure"))?{fieldType:"percentage",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterPercentage")}:i.some(e=>e.includes("decimal")||"decimal"===e)?o.includes("monetary")||o.includes("currency")?o.includes("nodecimals")||o.includes("no-decimals")||o.includes("nodecimals20")?{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!1,step:1,placeholder:T.t("field.enterAmountNoDecimals")}:{fieldType:"currency",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterCurrency")}:{fieldType:"decimal",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:"any",placeholder:T.t("field.enterDecimalValue")}:e.some(e=>"xbrli:stringItemType"===e)||i.some(e=>"string"===e||e.includes("stringitem"))?{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterText")}:{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterValue")}}var $e=Object.defineProperty,we=Object.getOwnPropertyDescriptor,Se=(e,t,i,o)=>{for(var r,n=o>1?void 0:o?we(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(n=(o?r(t,i,n):r(n))||n);return o&&n&&$e(t,i,n),n};exports.JupiterFormField=class extends e.LitElement{constructor(){super(...arguments),this.defaultUnits=[],this.value=null,this.disabled=!1,this.locale="en-US",this.hideLabel=!1,this.mode="inputForm",this.globalDecimals="INF",this.typedMemberValues={},this._errors=[],this._xbrlErrors=[],this._touched=!1,this._showPeriodPopup=!1,this._availableUnits=[],this._numericDraftValue=null}willUpdate(e){var t;(e.has("value")||e.has("field"))&&this._validateField(),e.has("unit")&&this.unit&&(console.log(`🏷️ [FormField willUpdate] Unit property changed to: ${this.unit}, conceptId: ${this.conceptId}, columnId: ${this.columnId}`),this.dispatchEvent(new CustomEvent("unit-change",{detail:{fieldId:null==(t=this.field)?void 0:t.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit},bubbles:!0,composed:!0}))),e.has("field")&&this.field&&(this.conceptId.includes("DescriptionLocationNL")||this.columnId.startsWith("col-"))&&console.log(`📅 [FormField willUpdate] Concept ${this.conceptId}, Column ${this.columnId}: field.periodType=${this.field.periodType}, field.periodStartDate=${this.field.periodStartDate}, field.periodEndDate=${this.field.periodEndDate}, field.periodInstantDate=${this.field.periodInstantDate}`)}_validateField(){var e;(null==(e=this.field)?void 0:e.validation)&&(this._errors=C.validateField(this.field.id,this.conceptId,this.columnId,this.value,this.field.type,this.field.validation))}_isRoundingLevelConcept(){return!!this.conceptId&&this.conceptId.includes("DocumentIntendedRoundingLevel")}_isNumericField(){var e;return xe(be(this.conceptType,this.datatypes).fieldType||(null==(e=this.field)?void 0:e.type)||"text")||"number"===this._getInputType()}_isIntermediateNumericValue(e){return"-"===e||"."===e||"-."===e}_handleInput(e){const t=e.target,i=this.value;let o=t.value;if(this._isNumericField()){const e=t.value;if(this._numericDraftValue=e,""===e||this._isIntermediateNumericValue(e))o=null;else{const t=Number(e);o=Number.isNaN(t)?null:t}}else"boolean"===this.field.type?(o=t.checked,this._numericDraftValue=null):this._numericDraftValue=null;this.value=o,this._touched=!0,this.dispatchEvent(new CustomEvent("field-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,value:o,oldValue:i},bubbles:!0}))}_handleFocus(){this.dispatchEvent(new CustomEvent("field-focus",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId},bubbles:!0}))}_handleBlur(){let e=!1;if(this._isNumericField()&&null!==this._numericDraftValue){e=!0;const t=this._numericDraftValue;if(""===t||this._isIntermediateNumericValue(t))this.value=null;else{const e=Number(t);this.value=Number.isNaN(e)?null:e}this._numericDraftValue=null}if(this._isPercentItemType()&&e&&null!==this.value&&void 0!==this.value){const e=Number(this.value);if(!isNaN(e)&&Math.abs(e)>1){this.value=e/100;const t=e;this.dispatchEvent(new CustomEvent("field-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,value:this.value,oldValue:t},bubbles:!0}))}}this._touched=!0,this._validateXBRLDatatype(),this._validateUnitSelection(),console.log(`🟦 [FormField] Blur event - fieldId: ${this.field.id}, conceptId: ${this.conceptId}, columnId: ${this.columnId}`),console.log("🟦 [FormField] Current _xbrlErrors:",this._xbrlErrors),console.log("🟦 [FormField] Current value:",this.value),this.dispatchEvent(new CustomEvent("field-blur",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,xbrlValidationErrors:this._xbrlErrors},bubbles:!0,composed:!0})),console.log(`🟦 [FormField] Dispatched field-blur event with ${this._xbrlErrors.length} errors`)}_isMonetaryType(){if(!this.conceptType||!this.datatypes)return!1;if(this.conceptType.includes("monetary")||this.conceptType.includes("Monetary"))return!0;return _e(this.conceptType,this.datatypes).some(e=>e.includes("monetary")||e.includes("Monetary"))}_isPercentItemType(){if(!this.conceptType)return!1;if(this.conceptType.toLowerCase().includes("percent"))return!0;if(!this.datatypes)return!1;return _e(this.conceptType,this.datatypes).some(e=>e.toLowerCase().includes("percent"))}_handleKeyDown(e){const t=e.target;if(!this._isNumericField())return;if(["Backspace","Delete","Tab","Escape","Enter","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End"].includes(e.key))return;if(e.ctrlKey||e.metaKey)return;const i=be(this.conceptType,this.datatypes),o=void 0===i.min||i.min<0;("-"!==e.key||!o||t.value.includes("-")||0!==t.selectionStart&&0!==t.value.length)&&("."!==e.key||!1===i.allowDecimals||t.value.includes("."))&&(e.key>="0"&&e.key<="9"||e.preventDefault())}_validateXBRLDatatype(){if(this._xbrlErrors=[],null===this.value||void 0===this.value||""===this.value)return;if(!this.conceptType||!this.datatypes||0===this.datatypes.length)return;const e=fe.validateConceptValue(this.conceptType,this.value,this.datatypes);e.valid?console.log(`✅ [FormField] XBRL Validation passed for ${this.conceptId}`):(this._xbrlErrors=e.errors,console.log(`❌ [FormField] XBRL Validation failed for ${this.conceptId}:`,{conceptType:this.conceptType,value:this.value,errors:this._xbrlErrors}))}_validateUnitSelection(){if(null===this.value||void 0===this.value||""===this.value)return;const e=this._collectUnitsForConceptType();if(0===e.length)return;if(this.unit)return;const t=e.find(e=>!0===e.isDefault)??(1===e.length?e[0]:null);if(t)return this.unit=t.id,this.dispatchEvent(new CustomEvent("unit-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit},bubbles:!0,composed:!0})),void console.log(`🎯 [FormField] Auto-selected default unit on blur: ${this.unit} for ${this.conceptId}`);this._xbrlErrors=[...this._xbrlErrors,{type:"unit",message:T.t("validation.unitRequired"),expectedValue:e.map(e=>e.label).join(", "),actualValue:""}],console.log(`❌ [FormField] Unit validation failed for ${this.conceptId}: unit is required but not selected`)}_handlePeriodIconClick(){if(!this._isRoundingLevelConcept()){if(this._availableUnits=this._collectUnitsForConceptType(),console.log(`📊 [FormField] Collected ${this._availableUnits.length} units for concept ${this.conceptId}:`,this._availableUnits),console.log(`📊 [FormField] Current unit value: ${this.unit}`),console.log(`📊 [FormField] ConceptId: ${this.conceptId}, ColumnId: ${this.columnId}`),!this.unit&&this._availableUnits.length>0){let e=null;const t=this._availableUnits.find(e=>!0===e.isDefault);t?(e=t.id,console.log(`🎯 [FormField] Auto-selecting default unit: ${t.id} (${t.label})`)):1===this._availableUnits.length&&(e=this._availableUnits[0].id,console.log(`🎯 [FormField] Auto-selecting single available unit: ${e}`)),e&&(this.unit=e,this.dispatchEvent(new CustomEvent("unit-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit},bubbles:!0,composed:!0})))}else this.unit&&(console.log(`📊 [FormField] Unit already set, dispatching unit-change to ensure parent stores it: ${this.unit}`),this.dispatchEvent(new CustomEvent("unit-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit},bubbles:!0,composed:!0})));this._showPeriodPopup=!0}}_collectUnitsForConceptType(){if(!this.conceptType||!this.datatypes)return[];const e=_e(this.conceptType,this.datatypes);console.log(`🔍 [Unit Resolution] Concept: ${this.conceptId}, Type: ${this.conceptType}, BaseType Chain:`,e);for(const t of e){const e=this.datatypes.find(e=>e.type===t);if(e&&e.units&&Array.isArray(e.units)&&e.units.length>0)return console.log(`✅ [Unit Resolution] Found ${e.units.length} units in type: ${t}`),e.units}return console.log(`ℹ️ [Unit Resolution] No units found for concept ${this.conceptId}`),[]}_closePeriodPopup(){this._showPeriodPopup=!1}_handleUnitChange(e){const t=e.target.value;console.log(`🏷️ [FormField] Unit change detected: value=${t}, conceptId=${this.conceptId}, columnId=${this.columnId}`),console.log(`🏷️ [FormField] Previous unit value: ${this.unit}`),this.unit=t,console.log(`🏷️ [FormField] Updated unit value to: ${this.unit}`);const i={fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit};console.log("🏷️ [FormField] Dispatching unit-change event with detail:",i),this.dispatchEvent(new CustomEvent("unit-change",{detail:i,bubbles:!0,composed:!0})),console.log("🏷️ [FormField] unit-change event dispatched")}_handleDecimalsChange(e){const t=e.target.value.trim(),i=parseFloat(t),o=t&&!isNaN(i)?String(Math.abs(i)):""===t?"":t;this.decimals=o||void 0,this.dispatchEvent(new CustomEvent("decimals-change",{detail:{conceptId:this.conceptId,columnId:this.columnId,decimals:this.decimals},bubbles:!0,composed:!0}))}_handlePopupOverlayClick(e){e.target===e.currentTarget&&this._closePeriodPopup()}_ensureTextDialogStyles(){if(document.getElementById("jdf-text-dialog-styles"))return;const e=document.createElement("style");e.id="jdf-text-dialog-styles",e.textContent="\n dialog.jdf-text-entry-dialog {\n border: none; border-radius: 8px; padding: 0;\n max-width: 600px; width: 90vw;\n box-shadow: 0 8px 32px rgba(0,0,0,0.2); overflow: hidden;\n font-family: inherit;\n }\n dialog.jdf-text-entry-dialog::backdrop { background: rgba(0,0,0,0.35); }\n .jdf-text-dialog-header {\n background: #f0f2f5; padding: 14px 20px;\n display: flex; align-items: center; justify-content: space-between;\n border-bottom: 1px solid #ddd;\n }\n .jdf-text-dialog-title {\n font-size: 15px; font-weight: 600; color: #333; margin: 0;\n font-family: inherit; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n }\n .jdf-text-dialog-close {\n flex-shrink: 0; width: 28px; height: 28px; border: none; background: transparent;\n font-size: 20px; line-height: 1; cursor: pointer; color: #666;\n border-radius: 4px; display: flex; align-items: center; justify-content: center;\n padding: 0; font-family: inherit; margin-left: 8px;\n }\n .jdf-text-dialog-close:hover { background: #ddd; color: #333; }\n .jdf-text-dialog-body { padding: 20px 20px 12px; }\n .jdf-text-dialog-textarea {\n width: 100%; min-height: 200px; max-height: 50vh;\n padding: 10px 12px; font-size: 14px; font-family: inherit;\n border: 1px solid #ddd; border-radius: 4px;\n box-sizing: border-box; resize: vertical; line-height: 1.5;\n color: #333; background: #fff;\n }\n .jdf-text-dialog-textarea:focus {\n outline: none; border-color: #1976d2;\n box-shadow: 0 0 0 2px rgba(25,118,210,0.2);\n }\n .jdf-text-dialog-char-count {\n margin-top: 4px; font-size: 12px; color: #888; text-align: right;\n font-family: inherit;\n }\n .jdf-text-dialog-actions {\n display: flex; justify-content: flex-end; gap: 8px;\n padding: 12px 20px 16px; border-top: 1px solid #eee;\n }\n .jdf-text-dialog-cancel {\n padding: 7px 18px; border: 1px solid #ddd; border-radius: 4px;\n background: transparent; color: #555; font-size: 14px;\n cursor: pointer; font-family: inherit;\n }\n .jdf-text-dialog-cancel:hover { background: #f5f5f5; }\n .jdf-text-dialog-save {\n padding: 7px 18px; border: none; border-radius: 4px;\n background: #1976d2; color: #fff; font-size: 14px;\n cursor: pointer; font-family: inherit; font-weight: 500;\n }\n .jdf-text-dialog-save:hover { background: #1565c0; }\n ",document.head.appendChild(e)}_openTextDialog(e,t){var i;this._ensureTextDialogStyles(),null==(i=document.getElementById("jdf-text-entry-dialog"))||i.remove();const o=document.createElement("dialog");o.id="jdf-text-entry-dialog",o.className="jdf-text-entry-dialog",o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby","jdf-text-dialog-title"),o.innerHTML='\n <div class="jdf-text-dialog-header">\n <h3 class="jdf-text-dialog-title" id="jdf-text-dialog-title"></h3>\n <button class="jdf-text-dialog-close" type="button" aria-label="Close">×</button>\n </div>\n <div class="jdf-text-dialog-body">\n <textarea class="jdf-text-dialog-textarea" spellcheck="true"></textarea>\n <div class="jdf-text-dialog-char-count"></div>\n </div>\n <div class="jdf-text-dialog-actions">\n <button class="jdf-text-dialog-cancel" type="button"></button>\n <button class="jdf-text-dialog-save" type="button"></button>\n </div>\n ';const r=t;o.querySelector(".jdf-text-dialog-title").textContent=r||t,o.querySelector(".jdf-text-dialog-cancel").textContent=T.t("field.cancel"),o.querySelector(".jdf-text-dialog-save").textContent=T.t("field.save");const n=o.querySelector(".jdf-text-dialog-textarea"),a=o.querySelector(".jdf-text-dialog-char-count");n.value=e,a.textContent=`${e.length} ${T.t("field.characters")}`,n.addEventListener("input",()=>{a.textContent=`${n.value.length} ${T.t("field.characters")}`}),o.querySelector(".jdf-text-dialog-close").addEventListener("click",()=>o.close()),o.querySelector(".jdf-text-dialog-cancel").addEventListener("click",()=>o.close()),o.querySelector(".jdf-text-dialog-save").addEventListener("click",()=>{const e=n.value,t=this.value;this.value=e,this._touched=!0,this.dispatchEvent(new CustomEvent("field-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,value:e,oldValue:t},bubbles:!0})),o.close()}),o.addEventListener("click",e=>{const t=o.getBoundingClientRect();(e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)&&o.close()}),o.addEventListener("close",()=>o.remove()),document.body.appendChild(o),o.showModal(),n.focus()}_renderTextDialogTrigger(t,i){const o=null!=t&&""!==String(t).trim(),r=o?String(t):"";return i?e.html`
|
|
22
|
+
*/function S(e){return w({...e,state:!0,attribute:!1})}class C{static validateField(e,t,i,o,r,n=[]){const a=[];for(const s of n){const n=this.validateRule(e,t,i,o,r,s);n&&a.push(n)}return a}static validateRule(e,t,i,o,r,n){const a=null==o||""===o;switch(n.type){case"required":if(a)return this.createError(e,t,i,n);break;case"min":if(!a&&"number"==typeof o&&o<n.value)return this.createError(e,t,i,n);break;case"max":if(!a&&"number"==typeof o&&o>n.value)return this.createError(e,t,i,n);break;case"minLength":if(!a&&"string"==typeof o&&o.length<n.value)return this.createError(e,t,i,n);break;case"maxLength":if(!a&&"string"==typeof o&&o.length>n.value)return this.createError(e,t,i,n);break;case"pattern":if(!a&&"string"==typeof o){if(!new RegExp(n.value).test(o))return this.createError(e,t,i,n)}break;case"email":if(!a&&"string"==typeof o){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o))return this.createError(e,t,i,n)}break;case"url":if(!a&&"string"==typeof o)try{new URL(o)}catch{return this.createError(e,t,i,n)}break;case"custom":break;default:console.warn(`Unknown validation rule type: ${n.type}`)}return null}static createError(e,t,i,o){return{fieldId:e,conceptId:t,columnId:i,message:o.message,severity:o.severity||"error",rule:o}}static validateDataType(e,t){if(null==e||""===e)return{valid:!0,convertedValue:e};switch(t){case"number":case"decimal":case"currency":case"percentage":{const t=Number(e);return isNaN(t)?{valid:!1,error:"Invalid number format"}:{valid:!0,convertedValue:t}}case"date":{const t=new Date(e);return isNaN(t.getTime())?{valid:!1,error:"Invalid date format"}:{valid:!0,convertedValue:t.toISOString().split("T")[0]}}case"datetime":{const t=new Date(e);return isNaN(t.getTime())?{valid:!1,error:"Invalid datetime format"}:{valid:!0,convertedValue:t.toISOString()}}case"boolean":if("boolean"==typeof e)return{valid:!0,convertedValue:e};if("string"==typeof e){const t=e.toLowerCase();if("true"===t||"1"===t)return{valid:!0,convertedValue:!0};if("false"===t||"0"===t)return{valid:!0,convertedValue:!1}}return{valid:!1,error:"Invalid boolean format"};case"text":case"textarea":case"email":case"url":case"tel":return{valid:!0,convertedValue:String(e)};default:return{valid:!0,convertedValue:e}}}static formatValue(e,t,i="en-US"){if(null==e)return"";switch(t){case"number":return new Intl.NumberFormat(i).format(Number(e));case"decimal":return new Intl.NumberFormat(i,{minimumFractionDigits:2,maximumFractionDigits:2}).format(Number(e));case"currency":return new Intl.NumberFormat(i,{style:"currency",currency:"USD"}).format(Number(e));case"percentage":return new Intl.NumberFormat(i,{style:"percent",minimumFractionDigits:2}).format(Number(e)/100);case"date":return new Date(e).toLocaleDateString(i);case"datetime":return new Date(e).toLocaleString(i);default:return String(e)}}}class F{static formatPeriodDisplay(e,t){if(!e||!t)return`${e} / ${t}`;const i=e.substring(0,4);return i===t.substring(0,4)?i:`${e} / ${t}`}static createUniqueConceptId(e,t){let i=e.id;if(e.preferredLabel&&""!==e.preferredLabel.trim()){const t=e.preferredLabel.match(/\/([^\/]+)$/),o=t?t[1]:e.preferredLabel.replace(/[^a-zA-Z0-9]/g,"_");i=`${e.id}_${o}`}if(t){return`${i}__${this.createSectionHash(t)}`}return i}static createSectionHash(e){let t=0;for(let i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t&=t}return Math.abs(t).toString(36).substr(0,6)}static _extractDocumentationLabels(e){const t={};return e.filter(e=>"http://www.xbrl.org/2003/role/documentation"===e.role).forEach(e=>{t[e.lang]=e.label}),t}static buildFormSchema(e,t,i,o="en",r){var n,a;if(!e.presentation||0===e.presentation.length)throw new Error("XBRL presentation data is required");const s=e.presentation[0],l=null==(n=e.hypercubes)?void 0:n[0],d=Array.isArray(e.datatypes)?e.datatypes:(null==(a=e.datatypes)?void 0:a.concepts)||[],c=[];return s.roles.forEach(e=>{const n=this.buildSectionFromRole(e,t,i,l,o,r);d&&d.length>0?(n.datatypes=d,console.log(`✅ [buildFormSchema] Attached ${d.length} datatypes to section ${n.id}`)):console.warn(`⚠️ [buildFormSchema] No datatypes available for section ${n.id}`),this.assignFieldColumnIds(n),c.push(n)}),{formId:`xbrl-form-${Date.now()}`,title:`XBRL Form - ${this.extractEntityName(s.entrypoint)}`,description:"Dynamic form generated from XBRL taxonomy data",version:"1.0.0",sections:c}}static buildSectionFromRole(e,t,i,o,r="en",n){var a,s;let l;if(e.labels&&e.labels.length>0){const t=e.labels.find(e=>e.lang===r),i=e.labels.find(e=>"en"===e.lang)||e.labels[0];l=(t||i).label}else l=this.extractRoleTitle(e.role||e.id||"Unknown Role");const d=this.getAllNonAbstractConcepts(e),c=new Set(d.filter(e=>e.periodType).map(e=>e.periodType));let p=null==o?void 0:o.roles.find(t=>t.roleId===e.id);const u=null==n?void 0:n[e.id];p&&(null==u?void 0:u.dimensionSelections)&&u.dimensionSelections.length>0&&(console.log(`🔍 Filtering dimensions for role ${e.id} based on user selections`),p=this.filterHypercubeDimensionsBySelection(p,u.dimensionSelections));const h=this.generateDefaultColumnsForRole(e,t||"2025-01-01",i||"2025-12-31",p,d,c,u,r),m={periodTypes:c,availableColumnIds:h.map(e=>e.id),availableColumns:h},f=[],g=new Map;return(null==(a=e.presentationLinkbase)?void 0:a.concepts)&&e.presentationLinkbase.concepts.forEach(o=>{const n=this.buildConceptTree(o,0,t,i,m,e.id,r,g);n&&f.push(n)}),p&&(null==(s=p.items)?void 0:s.length)||!o||f.forEach(t=>this.applyCrossRoleDimensions(t,e.id,o,r)),{id:e.id,title:l,description:e.description||`Section for ${l}`,concepts:f,columns:h,expanded:!1,metadata:{roleURI:e.roleURI,originalRole:e.role},showPeriodControl:c.size>1,showPreviousYear:!0===e.showPreviousYear,instant:!0===e.instant,duration:!0===e.duration}}static buildConceptTree(e,t,i,o,r,n,a="en",s,l){var d,c;const p=this.getPreferredLabel(e.labels,a,e.preferredLabel),u=(null==(d=e.preferredLabel)?void 0:d.includes("periodStartLabel"))?"start":(null==(c=e.preferredLabel)?void 0:c.includes("periodEndLabel"))?"end":l,h="start"===u?"periodStartLabel":"end"===u?"periodEndLabel":void 0,m=[];if(!e.elementAbstract){let t=[];t=(null==r?void 0:r.availableColumnIds)&&r.availableColumnIds.length>0?r.availableColumnIds:["duration"],t.forEach(t=>{var n;const s=null==(n=null==r?void 0:r.availableColumns)?void 0:n.find(e=>e.id===t),d=(null==s?void 0:s.periodStartDate)||i,c=(null==s?void 0:s.periodEndDate)||o,p=this.createFieldFromConcept(e,d,c,t,l,a);p&&m.push(p)})}const f=[];e.children&&e.children.length>0&&e.children.forEach(e=>{const l=this.buildConceptTree(e,t+1,i,o,r,n,a,s,u);l&&f.push(l)});if(!(m.length>0||f.length>0))return null;let g=this.createUniqueConceptId(e,n);if(s){const e=s.get(g)??0;s.set(g,e+1),e>0&&(g=`${g}__occ${e+1}`)}const b={conceptName:e.conceptName,type:e.type,substitutionGroup:e.substitutionGroup,periodType:e.periodType,balance:e.balance,documentationLabels:this._extractDocumentationLabels(e.labels)};return{id:g,originalConceptId:e.id,name:e.conceptName,label:p,description:`${e.conceptName} (${e.type})`,type:e.type,level:t,children:f,fields:m,conceptMetadata:b,facts:e.facts||[],collapsed:t>0,abstract:e.elementAbstract,periodType:e.periodType,balance:e.balance,preferredLabel:e.preferredLabel,effectivePeriodRole:h}}static createFieldFromConcept(e,t,i,o,r,n="en"){var a;const s=this.mapXBRLTypeToFieldType(e.type),l=this.getPreferredLabel(e.labels,n,e.preferredLabel);let d;d=o||"duration";const c={id:`${e.id}_${d}_field`,conceptId:e.id,columnId:d,type:s,label:l,placeholder:`Enter ${l.toLowerCase()}`,required:!1,disabled:e.elementAbstract,defaultValue:null,periodType:"instant"===e.periodType||"duration"===e.periodType?e.periodType:void 0,periodStartDate:t||"2025-01-01",periodEndDate:i||"2025-12-31",periodInstantDate:"instant"===e.periodType?(null==(a=e.preferredLabel)?void 0:a.includes("periodStartLabel"))||"start"===r?this.subtractOneDay(t||"2025-01-01"):i||t||"2025-01-01":void 0};return"nl-cd_DescriptionLocationNL__a64trl"===e.id&&console.log(`🏗️ [Field Creation] Concept: ${e.id}, periodType from concept: ${e.periodType}, Field periodType: ${c.periodType}, ColumnId: ${d}`),c}static mapXBRLTypeToFieldType(e){return{"xbrli:stringItemType":"text","xbrli:monetaryItemType":"currency","xbrli:integerItemType":"number","xbrli:decimalItemType":"decimal","xbrli:percentItemType":"percentage","xbrli:dateItemType":"date","xbrli:booleanItemType":"boolean","dtr-types:domainItemType":"select","bw2-titel9:chamberOfCommerceRegistrationNumberItemType":"text"}[e]||"text"}static getPreferredLabel(e,t="en",i){if(!e||0===e.length)return"Unnamed Concept";const o=e.filter(e=>e.lang===t),r=o.length>0?o:e;if(i){const t=o.find(e=>e.role===i);if(t)return t.label;const r=e.find(e=>e.role===i);if(r)return r.label}const n=r.find(e=>e.preferredLabel);if(n)return n.label;const a=r.find(e=>"http://www.xbrl.org/2003/role/label"===e.role);if(a)return a.label;const s=r.find(e=>"http://www.xbrl.org/2003/role/terseLabel"===e.role);return s?s.label:r.length>0?r[0].label:e[0].label}static assignFieldColumnIds(e){if(!e.columns||0===e.columns.length)return;const t=e.columns.map(e=>e.id);e.concepts.forEach(e=>{this.assignColumnIdsToConceptFields(e,t)})}static assignColumnIdsToConceptFields(e,t){e.fields=e.fields.filter(e=>t.includes(e.columnId)),e.children&&e.children.forEach(e=>{this.assignColumnIdsToConceptFields(e,t)})}static countFieldsInTree(e){let t=e.fields.length;return e.children&&e.children.forEach(e=>{t+=this.countFieldsInTree(e)}),t}static getAllNonAbstractConcepts(e){var t;const i=[];return(null==(t=e.presentationLinkbase)?void 0:t.concepts)&&e.presentationLinkbase.concepts.forEach(e=>{this.collectNonAbstractConcepts(e,i)}),i}static collectNonAbstractConcepts(e,t){e.elementAbstract||t.push(e),e.children&&e.children.length>0&&e.children.forEach(e=>{this.collectNonAbstractConcepts(e,t)})}static filterHypercubeDimensionsBySelection(e,t){const i=JSON.parse(JSON.stringify(e));return i.items&&0!==i.items.length?(i.items.forEach(e=>{e.dimensions&&(e.dimensions=e.dimensions.map(e=>{var i,o;const r=t.find(t=>t.dimensionId===e.id);if(!r||!r.selectedMemberIds||0===r.selectedMemberIds.length)return e;const n={...e};return n.members=this.filterMembersBySelection(e.members,r.selectedMemberIds),console.log(` ✅ Filtered dimension ${e.id}: ${(null==(i=e.members)?void 0:i.length)||0} → ${(null==(o=n.members)?void 0:o.length)||0} members`),n}))}),i):i}static filterMembersBySelection(e,t){if(!e||!Array.isArray(e))return[];const i=[];return e.forEach(e=>{if(t.includes(e.id)&&i.push({...e,children:[]}),e.children&&e.children.length>0){const o=this.filterMembersBySelection(e.children,t);i.push(...o)}}),i}static findCrossRoleDimensions(e,t,i,o="en"){var r,n;const a=[];for(const d of i.roles)if(d.roleId!==t)for(const t of d.items)if((null==(r=t.conceptIds)?void 0:r.includes(e))&&(null==(n=t.dimensions)?void 0:n.some(e=>e.typedMember))){a.push(d);break}if(1!==a.length)return null;const s=a[0].items.find(t=>{var i;return null==(i=t.conceptIds)?void 0:i.includes(e)});if(!s)return null;const l=[];for(const d of s.dimensions){if(!d.typedMember)continue;const e=d.labels.find(e=>e.lang===o)||d.labels.find(e=>"en"===e.lang)||d.labels[0],t=(null==e?void 0:e.label)||d.id;l.push({axisId:d.id,axisLabel:t,typedMemberId:d.typedMember.id,memberLabel:t})}return l.length>0?l:null}static applyCrossRoleDimensions(e,t,i,o){var r;if(!e.abstract&&e.fields&&e.fields.length>0){const r=this.findCrossRoleDimensions(e.originalConceptId,t,i,o);r&&e.fields.forEach(e=>{e.crossRoleTypedMembers=r})}null==(r=e.children)||r.forEach(e=>this.applyCrossRoleDimensions(e,t,i,o))}static generateDefaultColumnsForRole(e,t,i,o,r,n,a,s="en"){var l,d;const c=r||this.getAllNonAbstractConcepts(e),p=n||new Set(c.filter(e=>e.periodType).map(e=>e.periodType));if(0===c.length)return[{id:"default",title:"Value",description:"Default value column",type:"base",order:0,removable:!1}];let u=[];if(1===(null==(l=null==o?void 0:o.items)?void 0:l.length)){const e=o.items[0];1===e.dimensions.length?u=this.generateSingleDimensionColumns(e.dimensions[0],t,i,p,s):e.dimensions.length>1&&(u=this.generateMultiDimensionColumns(e.dimensions,t,i,p,s)),a&&(u=this.filterColumnsByPeriodPreferences(u,a))}else(null==(d=null==o?void 0:o.items)?void 0:d.length)&&o.items.length;const h=[];u.length>0?h.push(...u):0===p.size?h.push({id:"default",title:this.formatPeriodDisplay(t,i),description:"",type:"base",order:0,removable:!1,periodStartDate:t,periodEndDate:i}):h.push({id:"duration",title:this.formatPeriodDisplay(t,i),description:"",type:"base",order:0,removable:!1,periodStartDate:t,periodEndDate:i});let m=h;if(a&&(m=this.filterColumnsByPeriodPreferences(h,a)),null==a?void 0:a.showPreviousYear){const e=this.generatePreviousYearColumns(m,t,i);m=[...m,...e]}return m}static getPreviousYearDate(e){try{const t=new Date(e);return t.setFullYear(t.getFullYear()-1),t.toISOString().split("T")[0]}catch(t){return console.error(`Error calculating previous year for date ${e}:`,t),e}}static subtractOneDay(e){try{const t=new Date(e);return t.setDate(t.getDate()-1),t.toISOString().split("T")[0]}catch(t){return console.error(`Error subtracting one day from date ${e}:`,t),e}}static generatePreviousYearColumns(e,t,i){const o=[],r=this.getPreviousYearDate(t),n=this.getPreviousYearDate(i);return e.forEach((e,t)=>{let i=e.title,a="",s="";e.dimensionData?(i=e.title,a=this.formatPeriodDisplay(r,n),s=`${e.id}_prev`):(i=this.formatPeriodDisplay(r,n),a="",s=`duration_prev_${t}`),o.push({...e,id:s,title:i,description:a,order:e.order+100,removable:!1,periodStartDate:r,periodEndDate:n,dimensionData:e.dimensionData?{...e.dimensionData,dimensionId:`${e.dimensionData.dimensionId}_prev`}:void 0})}),o}static filterColumnsByPeriodPreferences(e,t){return e.filter(e=>{var i,o,r,n;const a=e.id.includes("duration")||(null==(o=null==(i=e.dimensionData)?void 0:i.dimensionId)?void 0:o.includes("duration")),s=e.id.includes("instant")||(null==(n=null==(r=e.dimensionData)?void 0:r.dimensionId)?void 0:n.includes("instant"));return!a&&!s||!(a&&!t.showDuration)&&!(s&&!t.showInstant)})}static generateSingleDimensionColumns(e,t,i,o,r="en"){if(e.typedMember&&(!e.members||0===e.members.length)){const n=this.getPreferredLabel(e.labels,r)||e.conceptName,a={axisId:e.id,axisLabel:n,typedMemberId:e.typedMember.id,dimensionKey:`${n} | [Typed Input]`,dimensionIdKey:`${e.id}|[typed]`},s=[];return 0===o.size?s.push({id:"typed-default",title:n,description:"Typed dimension input column",type:"dimension",dimensionData:{dimensionId:"typed-default",axisId:a.axisId,memberId:"[typed]",memberValue:"Typed Input",memberLabel:"Typed Input",axis:a.axisLabel,axisLabel:a.axisLabel,memberKey:a.dimensionKey,dimensionIdKey:a.dimensionIdKey,hasTypedMembers:!0,typedMemberId:a.typedMemberId,typedMembers:[{axisId:a.axisId,axisLabel:a.axisLabel,typedMemberId:a.typedMemberId,memberLabel:a.axisLabel}]},order:0,removable:!1,periodStartDate:t,periodEndDate:i}):1===o.size&&o.has("instant")?s.push({id:"typed-instant",title:`${n} `,description:i,type:"dimension",dimensionData:{dimensionId:"typed-instant",axisId:a.axisId,memberId:"[typed]",memberValue:"Typed Input",memberLabel:"Typed Input",axis:a.axisLabel,axisLabel:a.axisLabel,memberKey:a.dimensionKey,dimensionIdKey:a.dimensionIdKey,hasTypedMembers:!0,typedMemberId:a.typedMemberId,typedMembers:[{axisId:a.axisId,axisLabel:a.axisLabel,typedMemberId:a.typedMemberId,memberLabel:a.axisLabel}]},order:0,removable:!1,periodStartDate:i,periodEndDate:i}):(1===o.size&&o.has("duration"),s.push({id:"typed-duration",title:`${n} `,description:this.formatPeriodDisplay(t,i),type:"dimension",dimensionData:{dimensionId:"typed-duration",axisId:a.axisId,memberId:"[typed]",memberValue:"Typed Input",memberLabel:"Typed Input",axis:a.axisLabel,axisLabel:a.axisLabel,memberKey:a.dimensionKey,dimensionIdKey:a.dimensionIdKey,hasTypedMembers:!0,typedMemberId:a.typedMemberId,typedMembers:[{axisId:a.axisId,axisLabel:a.axisLabel,typedMemberId:a.typedMemberId,memberLabel:a.axisLabel}]},order:0,removable:!1,periodStartDate:t,periodEndDate:i})),s}if(!e.members||!Array.isArray(e.members))return[];if(0===e.members.length)return[];const n=this.getPreferredLabel(e.labels,r)||e.conceptName,a=e.members[0],s=this.getPreferredLabel(a.labels,r)||a.conceptName,l={axisId:e.id,axisLabel:n,memberId:a.id,memberLabel:s,dimensionKey:`${n} | ${s}`,dimensionIdKey:`${e.id} | ${a.id}`},d=[];return 0===o.size?d.push({id:"default",title:l.memberLabel,description:"Default value column",type:"dimension",dimensionData:{dimensionId:"default",axisId:l.axisId,memberId:l.memberId,memberValue:l.memberLabel,memberLabel:l.memberLabel,axis:l.axisLabel,axisLabel:l.axisLabel,memberKey:l.dimensionKey,dimensionIdKey:l.dimensionIdKey},order:0,removable:!1,periodStartDate:t,periodEndDate:i}):1===o.size&&o.has("instant")?d.push({id:"instant",title:`${l.memberLabel}`,description:i,type:"dimension",dimensionData:{dimensionId:"instant",axisId:l.axisId,memberId:l.memberId,memberValue:l.memberLabel,memberLabel:l.memberLabel,axis:l.axisLabel,axisLabel:l.axisLabel,memberKey:l.dimensionKey,dimensionIdKey:l.dimensionIdKey},order:0,removable:!1,periodStartDate:i,periodEndDate:i}):1===o.size&&o.has("duration")?d.push({id:"duration",title:`${l.memberLabel}`,description:`${t} / ${i}`,type:"dimension",dimensionData:{dimensionId:"duration",axisId:l.axisId,memberId:l.memberId,memberValue:l.memberLabel,memberLabel:l.memberLabel,axis:l.axisLabel,axisLabel:l.axisLabel,memberKey:l.dimensionKey,dimensionIdKey:l.dimensionIdKey},order:0,removable:!1,periodStartDate:t,periodEndDate:i}):d.push({id:"duration",title:`${l.memberLabel}`,description:this.formatPeriodDisplay(t,i),type:"dimension",dimensionData:{dimensionId:"duration",axisId:l.axisId,memberId:l.memberId,memberValue:l.memberLabel,memberLabel:l.memberLabel,axis:l.axisLabel,axisLabel:l.axisLabel,memberKey:l.dimensionKey,dimensionIdKey:l.dimensionIdKey},order:0,removable:!1,periodStartDate:t,periodEndDate:i}),d}static generateMultiDimensionColumns(e,t,i,o,r="en"){e.some(e=>e.typedMember);const n=e.filter(e=>!!e.typedMember||!!(e.members&&Array.isArray(e.members)&&e.members.length>0));if(0===n.length)return[];const a=n.map(e=>{const t=this.getPreferredLabel(e.labels,r)||e.conceptName;if(e.typedMember)return{id:e.id,axisLabel:t,isTyped:!0,typedMemberId:e.typedMember.id,members:[{id:"[typed]",label:`${t}`}]};const i=this.getAllDimensionMembers(e.members);return{id:e.id,axisLabel:t,isTyped:!1,members:i.map(e=>({id:e.id,label:this.getPreferredLabel(e.labels,r)||e.conceptName}))}}),s=this.generateDimensionCombinations(a),l=[];return s.forEach((e,o)=>{const r=e.map(e=>e.memberLabel).join(" | "),n=e.filter(e=>e.isTyped),a=e.filter(e=>!e.isTyped),s={dimensionId:`multi_${o}`,memberValue:r,memberLabel:r,combinations:a.map(e=>({axisId:e.axisId,axisLabel:e.axisLabel,memberId:e.memberId,memberLabel:e.memberLabel})),typedMembers:n.map(e=>({axisId:e.axisId,axisLabel:e.axisLabel,typedMemberId:e.typedMemberId,memberLabel:e.memberLabel})),hasTypedMembers:n.length>0,memberKey:r,dimensionIdKey:[...a.map(e=>`${e.axisId}|${e.memberId}`),...n.map(e=>`${e.axisId}|[typed]`)].join("::")};l.push({id:`duration_${o}`,title:`${r}`,description:this.formatPeriodDisplay(t,i),type:"dimension",dimensionData:{...s,dimensionId:`duration_${o}`},order:o,removable:!1,periodStartDate:t,periodEndDate:i})}),l}static getAllDimensionMembers(e){if(!e||!Array.isArray(e))return[];const t=[];return e.forEach(e=>{t.push(e),e.children&&e.children.length>0&&t.push(...this.getAllDimensionMembers(e.children))}),t}static generateDimensionCombinations(e){if(0===e.length)return[];if(1===e.length)return e[0].members.map(t=>[{axisId:e[0].id,axisLabel:e[0].axisLabel,memberId:t.id,memberLabel:t.label,isTyped:e[0].isTyped||!1,typedMemberId:e[0].typedMemberId}]);const[t,...i]=e,o=this.generateDimensionCombinations(i),r=[];return t.members.forEach(e=>{0===o.length?r.push([{axisId:t.id,axisLabel:t.axisLabel,memberId:e.id,memberLabel:e.label,isTyped:t.isTyped||!1,typedMemberId:t.typedMemberId}]):o.forEach(i=>{r.push([{axisId:t.id,axisLabel:t.axisLabel,memberId:e.id,memberLabel:e.label,isTyped:t.isTyped||!1,typedMemberId:t.typedMemberId},...i])})}),r}static formatDateForDisplay(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}catch{return e}}static extractEntityName(e){try{const t=new URL(e).pathname.split("/");return t[t.length-1].replace(".xsd","").replace(/[^a-zA-Z0-9]/g," ").trim()||"Entity"}catch{return"Entity"}}static extractRoleTitle(e){if(!e)return"Unnamed Section";const t=e.match(/^\[[\d]+\]\s*(.+)$/);if(t)return t[1].trim();if(e.match(/^[a-z]+:[^:]*$/i)||e.match(/^urn:[^:]+:[^:]+/i)){const t=e.split(/[:\-]/);return t[t.length-1].replace(/[_\-]/g," ").replace(/\b\w/g,e=>e.toUpperCase())}return e.trim()||"Unnamed Section"}static extractRoleOrder(e){const t=e.match(/^\[([\d]+)\]/);return t?parseInt(t[1],10):0}static buildColumnsFromHypercubes(){return[{id:"default",label:"Values",type:"data"}]}}const k={en:{conceptInfo:{title:"Concept Information",conceptName:"Concept name",type:"Type",substitutionGroup:"Substitution group",periodType:"Period type",balance:"Balance",documentation:"Documentation",instant:"Instant",duration:"Duration",close:"Close"},form:{markAsComplete:"Mark as Complete",loading:"Loading form...",submit:"Validate",save:"Save",saveDraft:"Save Draft",savingDraft:"Saving draft",errors:"Errors",modified:"Modified",valid:"Valid",yes:"Yes",no:"No",noRoleSelected:"No Role Selected",pleaseSelectRole:"Please select a role from the list on the left.",expandPanel:"Expand side panel",collapsePanel:"Collapse side panel",validate:"Validate",preview:"Preview",download:"Download",cancelValidation:"Cancel Validation",lastValidationResults:"Last Validation Results",validationInProgress:"Validation In Progress",quickValidate:"Quick Validate"},filter:{selectRoles:"Select Roles",filterRoles:"Filter Roles",title:"Filter Roles",description:"Select the roles you want to display in the form. You can search and choose specific roles to focus on or manage all available roles.",searchPlaceholder:"Search..",clearSearch:"Clear search",showingResults:"Showing",of:"of",roles:"roles",matching:"matching",selectAll:"Select All",selectNone:"Select None",selectFiltered:"Select Filtered",deselectFiltered:"Deselect Filtered",deselectAll:"Deselect All",reset:"Reset",noRolesFound:"No roles found matching",tryDifferentSearch:"Try a different search term or clear the search.",noRolesAvailable:"No roles available.",cancel:"Cancel",applyFilter:"Apply Filter",showPeriodColumn:"Show Period Column:",additionalOptions:"Additional Options:",showPreviousYear:"Show previous year",duration:"Duration",instant:"Instant",uri:"URI",dimensionMemberSelection:"Dimension Member Selection",selectAllMembers:"Select All",clearMembers:"Clear",availableRoles:"Available Roles",chosenRoles:"Chosen Roles",roleCount:"role(s)",rolesSelected:"role(s) selected",addSelectedRole:"Add selected role",addAllRoles:"Add all roles",removeSelectedRole:"Remove selected role",removeAllRoles:"Remove all roles",advancedFilter:"Advanced Filter",backToFilterRoles:"← Back",showFactsOnly:"Show facts only",showFactsOnlyDescription:"Hide all blank rows and sections. Only roles and rows with at least one filled value will be shown.",searchByConcept:"Search by concept",searchByConceptDescription:"Type concept name or label to filter roles and rows. Press Apply Filter to apply.",searchByConceptPlaceholder:"Type concept name or label and press Apply Filter...",clearFilters:"Clear Filters",resetFilter:"Reset"},column:{addColumn:"Add Column",columnOptions:"Column Options",columnType:"Column Type",instantSingleDate:"Instant (single date)",durationDates:"Duration (start and end dates)",instantDate:"Instant Date",startPeriodDate:"Start Period Date",endPeriodDate:"End Period Date",availableDimensions:"Available Dimensions",dimensionsDescription:"Select dimensions to include in the column. Domain members can be selected here, while typed dimension values will be entered directly in the column header.",enterValue:"Enter value for",enterValuePlaceholder:"Enter value...",selectMember:"Select member:",noMembersAvailable:"No members available for this dimension",cancel:"Cancel",removeColumn:"Remove column",hideColumn:"Hide column",showColumn:"Double-click to show column",required:"required"},section:{enterPlaceholder:"Enter"},field:{selectOption:"Select an option...",select:"Select...",enterDetailedExplanation:"Enter detailed explanation...",enterAmountNoDecimals:"Enter amount (no decimals)",enterCurrency:"0.00",enterText:"Enter text",enterWholeNumber:"Enter whole number",enterPositiveNumber:"Enter positive number",enterDecimalValue:"Enter decimal value",enterNumberOfShares:"Enter number of shares",yearFormat:"YYYY",enterPercentage:"e.g. 0.25 for 25% or 0.2550 for 25.50%",emailPlaceholder:"email@example.com",urlPlaceholder:"https://example.com",phonePlaceholder:"+1 (555) 000-0000",enterValue:"Enter value",enterDetailedInformation:"Enter detailed information...",scale:"Scale",addText:"Add text",editText:"Edit",save:"Save",cancel:"Cancel",characters:"characters",editPeriod:"Edit Period",from:"From",to:"To",date:"Date",unit:"Unit",selectUnit:"Select Unit",leaveBlankForInf:"Leave blank for INF"},admin:{title:"Configure Roles",description:"Select which roles should display the 'Show Previous Year' checkbox and configure period type columns."},validation:{summary:"Please fix the following errors before submitting:",errorsFound:"errors found",unitRequired:"Unit is required. Please select a unit via the period icon."},xbrlValidation:{patternMismatch:"Value does not match required pattern: {{pattern}}",invalidPattern:"Invalid pattern configuration: {{pattern}}",exactLength:"Value must be exactly {{required}} characters (current: {{current}})",minLength:"Value must be at least {{required}} characters (current: {{current}})",maxLength:"Value must not exceed {{required}} characters (current: {{current}})",totalDigits:"Value must not exceed {{required}} total digits (current: {{current}})",ruleSummaryPattern:"Must match pattern: {{pattern}}",ruleSummaryExactLength:"Must be exactly {{required}} characters",ruleSummaryMinLength:"Minimum {{required}} characters",ruleSummaryMaxLength:"Maximum {{required}} characters",ruleSummaryTotalDigits:"Maximum {{required}} total digits"},error:{popup:{title:"Validation Errors",message:"Please fix the following validation errors before saving:",field:"Field:",value:"Value:",errors:"Errors:",clickToFocus:"Click to focus this field",ok:"OK"}},calculationWarning:{title:"Calculation warning",summaryLine:'Total "{{label}}" should equal {{calculated}}, but you entered {{entered}}.',childrenPrefix:"Children:",childAdded:"{{label}} = {{value}} (added)",childSubtracted:"{{label}} = {{value}} (subtracted, opposite balance)",added:"Added",subtracted:"Subtracted (opposite balance)"},formulaValidation:{dialogTitle:"Formula check results",allPassed:"All formula checks passed",summaryCount:"{{failed}} of {{total}} checks failed",summaryCountBreakdown:"{{warnings}} warnings, {{errors}} errors",severityWarning:"Warning",severityError:"Error",close:"Close"}},nl:{conceptInfo:{title:"Conceptinformatie",conceptName:"Conceptnaam",type:"Type",substitutionGroup:"Substitutiegroep",periodType:"Periodetype",balance:"Saldo",documentation:"Documentatie",instant:"Moment",duration:"Periode",close:"Sluiten"},form:{markAsComplete:"Markeren als volledig behandeld",loading:"Formulier laden...",submit:"Valideren",save:"Opslaan",saveDraft:"Concept opslaan",savingDraft:"Concept opslaan...",errors:"Fouten",modified:"Gewijzigd",valid:"Geldig",yes:"Ja",no:"Nee",noRoleSelected:"Geen rol geselecteerd",pleaseSelectRole:"Selecteer een rol uit de lijst aan de linkerkant.",expandPanel:"Zijpaneel uitvouwen",collapsePanel:"Zijpaneel inklappen",validate:"Valideren",preview:"Voorbeeld",download:"Downloaden",cancelValidation:"Validatie annuleren",lastValidationResults:"Laatste validatieresultaten",validationInProgress:"Validatie bezig",quickValidate:"Snel valideren"},filter:{selectRoles:"Rollen selecteren",filterRoles:"Rollen filteren",title:"Rollen filteren",description:"Selecteer de rollen die u in het formulier wilt weergeven. U kunt zoeken en specifieke rollen kiezen om op te focussen of alle beschikbare rollen beheren.",searchPlaceholder:"Zoek rollen op naam, ID of URI...",clearSearch:"Zoekopdracht wissen",showingResults:"Weergeven",of:"van",roles:"rollen",matching:"overeenkomend met",selectAll:"Alles selecteren",selectNone:"Niets selecteren",selectFiltered:"Gefilterd selecteren",deselectFiltered:"Gefilterd deselecteren",deselectAll:"Alles deselecteren",reset:"Resetten",noRolesFound:"Geen rollen gevonden die overeenkomen met",tryDifferentSearch:"Probeer een andere zoekterm of wis de zoekopdracht.",noRolesAvailable:"Geen rollen beschikbaar.",cancel:"Annuleren",applyFilter:"Filter toepassen",showPeriodColumn:"Periodekolom weergeven:",additionalOptions:"Aanvullende opties:",showPreviousYear:"Vorig jaar weergeven",duration:"Duur",instant:"Moment",uri:"URI",dimensionMemberSelection:"Dimensieleden selectie",selectAllMembers:"Alles selecteren",clearMembers:"Wissen",availableRoles:"Beschikbare rollen",chosenRoles:"Gekozen rollen",roleCount:"rol(len)",rolesSelected:"rol(len) geselecteerd",addSelectedRole:"Geselecteerde rol toevoegen",addAllRoles:"Alle rollen toevoegen",removeSelectedRole:"Geselecteerde rol verwijderen",removeAllRoles:"Alle rollen verwijderen",advancedFilter:"Geavanceerd filter",backToFilterRoles:"← Terug",showFactsOnly:"Alleen feiten weergeven",showFactsOnlyDescription:"Verberg alle lege rijen en secties. Alleen rollen en rijen met minimaal één ingevulde waarde worden weergegeven.",searchByConcept:"Zoeken op concept",searchByConceptDescription:"Typ een conceptnaam of label om rollen en rijen te filteren. Druk op Filter toepassen om te activeren.",searchByConceptPlaceholder:"Typ conceptnaam of label en druk op Filter toepassen...",clearFilters:"Filters wissen",resetFilter:"Resetten"},column:{addColumn:"Kolom toevoegen",columnOptions:"Kolomopties",columnType:"Kolomtype",instantSingleDate:"Moment (enkele datum)",durationDates:"Duur (begin- en einddatum)",instantDate:"Momentdatum",startPeriodDate:"Startdatum periode",endPeriodDate:"Einddatum periode",availableDimensions:"Beschikbare dimensies",dimensionsDescription:"Selecteer dimensies om in de kolom op te nemen. Domeinleden kunnen hier worden geselecteerd, terwijl getypte dimensiewaarden direct in de kolomkop worden ingevoerd.",enterValue:"Voer waarde in voor",enterValuePlaceholder:"Voer waarde in...",selectMember:"Selecteer lid:",noMembersAvailable:"Geen leden beschikbaar voor deze dimensie",cancel:"Annuleren",removeColumn:"Kolom verwijderen",hideColumn:"Kolom verbergen",showColumn:"Dubbelklik om kolom te tonen",required:"verplicht"},section:{enterPlaceholder:"Invoeren"},field:{selectOption:"Selecteer een optie...",select:"Selecteer...",enterDetailedExplanation:"Voer gedetailleerde uitleg in...",enterAmountNoDecimals:"Voer bedrag in (geen decimalen)",enterCurrency:"0,00",enterText:"Voer tekst in",enterWholeNumber:"Voer geheel getal in",enterPositiveNumber:"Voer positief getal in",enterDecimalValue:"Voer decimale waarde in",enterNumberOfShares:"Voer aantal aandelen in",yearFormat:"JJJJ",enterPercentage:"bijv. 0,25 voor 25% of 0,2550 voor 25,50%",emailPlaceholder:"email@voorbeeld.nl",urlPlaceholder:"https://voorbeeld.nl",phonePlaceholder:"+31 (0)20 123 4567",enterValue:"Voer waarde in",enterDetailedInformation:"Voer gedetailleerde informatie in...",scale:"Schaal",addText:"Tekst toevoegen",editText:"Bewerken",save:"Opslaan",cancel:"Annuleren",characters:"tekens",editPeriod:"Periode bewerken",from:"Van",to:"Tot",date:"Datum",unit:"Eenheid",selectUnit:"Selecteer eenheid",leaveBlankForInf:"Leeg laten voor INF"},admin:{title:"Rollen configureren",description:"Selecteer welke rollen het selectievakje 'Vorig jaar weergeven' moeten weergeven en configureer periodetype kolommen."},validation:{summary:"Corrigeer de volgende fouten voordat u indient:",errorsFound:"fouten gevonden",unitRequired:"Eenheid is verplicht. Selecteer een eenheid via het periodeicoon."},xbrlValidation:{patternMismatch:"Waarde voldoet niet aan het vereiste patroon: {{pattern}}",invalidPattern:"Ongeldige patternconfiguratie: {{pattern}}",exactLength:"Waarde moet exact {{required}} tekens bevatten (huidig: {{current}})",minLength:"Waarde moet minimaal {{required}} tekens bevatten (huidig: {{current}})",maxLength:"Waarde mag niet meer dan {{required}} tekens bevatten (huidig: {{current}})",totalDigits:"Waarde mag niet meer dan {{required}} cijfers bevatten (huidig: {{current}})",ruleSummaryPattern:"Moet overeenkomen met patroon: {{pattern}}",ruleSummaryExactLength:"Moet exact {{required}} tekens bevatten",ruleSummaryMinLength:"Minimaal {{required}} tekens",ruleSummaryMaxLength:"Maximaal {{required}} tekens",ruleSummaryTotalDigits:"Maximaal {{required}} cijfers"},error:{popup:{title:"Validatiefouten",message:"Corrigeer de volgende validatiefouten voordat u opslaat:",field:"Veld:",value:"Waarde:",errors:"Fouten:",clickToFocus:"Klik om dit veld te focussen",ok:"OK"}},calculationWarning:{title:"Berekeningswaarschuwing",summaryLine:'Totaal "{{label}}" zou {{calculated}} moeten zijn, maar u heeft {{entered}} ingevoerd.',childrenPrefix:"Onderdelen:",childAdded:"{{label}} = {{value}} (opgeteld)",childSubtracted:"{{label}} = {{value}} (afgetrokken, tegengestelde balans)",added:"Opgeteld",subtracted:"Afgetrokken (tegengestelde balans)"},formulaValidation:{dialogTitle:"Resultaten formulecontrole",allPassed:"Alle formulecontroles geslaagd",summaryCount:"{{failed}} van {{total}} controles mislukt",summaryCountBreakdown:"{{warnings}} waarschuwingen, {{errors}} fouten",severityWarning:"Waarschuwing",severityError:"Fout",close:"Sluiten"}}};class T{static setLanguage(e){k[e]?this.currentLanguage=e:(console.warn(`Language '${e}' not supported, falling back to 'en'`),this.currentLanguage="en")}static getLanguage(){return this.currentLanguage}static t(e,t){const i=e.split(".");let o=k[this.currentLanguage];for(const r of i){if(!o||"object"!=typeof o||!(r in o))return console.warn(`Translation key '${e}' not found for language '${this.currentLanguage}'`),e;o=o[r]}return t&&"string"==typeof o?this.interpolate(o,t):o}static interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,i)=>i in t?String(t[i]):e)}static has(e){const t=e.split(".");let i=k[this.currentLanguage];for(const o of t){if(!i||"object"!=typeof i||!(o in i))return!1;i=i[o]}return void 0!==i}static getAvailableLanguages(){return Object.keys(k)}}function E(e){return!!(null==e?void 0:e.toLowerCase().includes("totallabel"))}T.currentLanguage="en";class R{constructor(e=!1){this.DRAFT_DATA_KEY="jupiter-form-draft-data",this.DRAFT_METADATA_KEY="jupiter-form-draft-metadata",this.STORAGE_VERSION="1.0",this._storage=e?sessionStorage:localStorage,console.log(`💾 DraftStorageService initialized (using ${e?"sessionStorage":"localStorage"})`)}saveDraft(e,t){try{const i={formData:e,metadata:{...t,savedAt:(new Date).toISOString()},version:this.STORAGE_VERSION};return this._storage.setItem(this.DRAFT_DATA_KEY,JSON.stringify(i.formData)),this._storage.setItem(this.DRAFT_METADATA_KEY,JSON.stringify(i.metadata)),console.log("✅ Draft saved successfully",{entries:e.length,timestamp:i.metadata.savedAt,roles:t.selectedRoleIds.length,customColumns:t.customColumns.length}),!0}catch(i){return console.error("❌ Failed to save draft:",i),!1}}loadDraft(){try{const e=this._storage.getItem(this.DRAFT_DATA_KEY),t=this._storage.getItem(this.DRAFT_METADATA_KEY);if(!e||!t)return console.log("ℹ️ No saved draft found"),null;const i=JSON.parse(e),o=JSON.parse(t);return console.log("✅ Draft loaded successfully",{entries:i.length,savedAt:o.savedAt,roles:o.selectedRoleIds.length,customColumns:o.customColumns.length}),{formData:i,metadata:o,version:this.STORAGE_VERSION}}catch(e){return console.error("❌ Failed to load draft:",e),null}}hasDraft(){return null!==this._storage.getItem(this.DRAFT_DATA_KEY)&&null!==this._storage.getItem(this.DRAFT_METADATA_KEY)}getDraftMetadata(){try{const e=this._storage.getItem(this.DRAFT_METADATA_KEY);return e?JSON.parse(e):null}catch(e){return console.error("❌ Failed to load draft metadata:",e),null}}clearDraft(){try{return this._storage.removeItem(this.DRAFT_DATA_KEY),this._storage.removeItem(this.DRAFT_METADATA_KEY),console.log("🗑️ Draft cleared successfully"),!0}catch(e){return console.error("❌ Failed to clear draft:",e),!1}}getDraftAge(){const e=this.getDraftMetadata();if(!e)return null;const t=new Date(e.savedAt);return(new Date).getTime()-t.getTime()}isDraftStale(e){const t=this.getDraftAge();return null!==t&&t>e}extractCustomColumns(e){const t=[];return e.forEach(e=>{e.columns&&Array.isArray(e.columns)&&e.columns.forEach(i=>{t.push({sectionId:e.id,columnId:i.id,label:i.title,description:i.description,periodType:this._inferPeriodTypeFromColumn(i),date:i.periodStartDate,startDate:i.periodStartDate,endDate:i.periodEndDate,dimensionData:i.dimensionData})})}),t}_inferPeriodTypeFromColumn(e){return e.periodStartDate&&e.periodEndDate?"duration":"instant"}createMetadataSnapshot(e,t,i,o,r,n,a,s,l,d="en",c,p,u,h,m){return{periodStartDate:e,periodEndDate:t,language:i,reportingLanguage:d,selectedRoleIds:o,customColumns:this.extractCustomColumns(r),typedMemberData:n,periodPreferences:a,periodData:s,unitData:l,decimalsData:p,repeatCounts:c,roleCompletedStates:u,hiddenColumns:h,totalManuallyEditedData:m,schemaVersion:this.STORAGE_VERSION}}validateDraftCompatibility(e,t,i){const o=[];e.metadata.periodStartDate!==t&&o.push(`Draft period start (${e.metadata.periodStartDate}) differs from current (${t})`),e.metadata.periodEndDate!==i&&o.push(`Draft period end (${e.metadata.periodEndDate}) differs from current (${i})`);const r=this.getDraftAge();r&&r>6048e5&&o.push(`Draft is ${Math.floor(r/864e5)} days old`);return{compatible:0===o.length,warnings:o}}}class M extends Error{constructor(e,t,i="unsupported-syntax"){super(e),this.test=t,this.reason=i,this.name="FormulaExpressionError"}}const A=/\s*(?:(\$[A-Za-z_][\w-]*)|(-?\d+(?:\.\d+)?)|([A-Za-z][\w:-]*)|('[^']*')|(\()|(\))|(\+)|(-)|(=))/y;class P{constructor(e,t){this.tokens=e,this.test=t,this.pos=0}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}expect(e){const t=this.next();if(t.type!==e)throw new M(`Expected ${e} but got ${t.type} ("${t.value}")`,this.test,"parse-error");return t}parseBoolExpr(){const e=this.parseOrExpr();if("EOF"!==this.peek().type)throw new M(`Unexpected trailing token "${this.peek().value}"`,this.test,"unsupported-syntax");return e}parseOrExpr(){const e=[this.parseAndExpr()];for(;"IDENT"===this.peek().type&&"or"===this.peek().value;)this.next(),e.push(this.parseAndExpr());return 1===e.length?e[0]:{kind:"or",terms:e}}parseAndExpr(){const e=[this.parseBoolTerm()];for(;"IDENT"===this.peek().type&&"and"===this.peek().value;)this.next(),e.push(this.parseBoolTerm());return 1===e.length?e[0]:{kind:"and",terms:e}}parseBoolTerm(){const e=this.peek();if("IDENT"===e.type&&"not"===e.value){this.next(),this.expect("LPAREN");const e=this.parseOrExpr();return this.expect("RPAREN"),{kind:"not",arg:e}}if("IDENT"===e.type&&"empty"===e.value){this.next(),this.expect("LPAREN");const e=this.expect("VARIABLE").value;return this.expect("RPAREN"),{kind:"empty",variable:e}}if("IDENT"===e.type&&"xff:has-fallback-value"===e.value){this.next(),this.expect("LPAREN");const e=this.next();if("IDENT"!==e.type||"xs:QName"!==e.value)throw new M(`Expected xs:QName(...) inside xff:has-fallback-value(...), got "${e.value}"`,this.test,"unsupported-syntax");this.expect("LPAREN");const t=this.expect("STRING").value;return this.expect("RPAREN"),this.expect("RPAREN"),{kind:"hasFallbackValue",variableName:t}}const t=this.parseValueExpr(),i=this.peek();if("EQUALS"===i.type)return this.next(),{kind:"comparison",op:"=",left:t,right:this.parseValueExpr()};if("IDENT"===i.type&&"eq"===i.value)return this.next(),{kind:"comparison",op:"eq",left:t,right:this.parseValueExpr()};throw new M(`Expected a comparison operator ("=" or "eq") after value expression, got "${i.value}"`,this.test,"unsupported-syntax")}parseValueExpr(){const e=[];let t=1;for("PLUS"===this.peek().type?this.next():"MINUS"===this.peek().type&&(this.next(),t=-1),e.push({sign:t,term:this.parseValueTerm()});"PLUS"===this.peek().type||"MINUS"===this.peek().type;){const t="PLUS"===this.next().type?1:-1;e.push({sign:t,term:this.parseValueTerm()})}return 1===e.length&&1===e[0].sign?e[0].term:{kind:"additive",terms:e}}parseValueTerm(){const e=this.peek();if("NUMBER"===e.type)return this.next(),{kind:"number",value:Number(e.value)};if("STRING"===e.type)return this.next(),{kind:"string",value:e.value};if("VARIABLE"===e.type)return this.next(),{kind:"variable",name:e.value};if("IDENT"===e.type&&"sum"===e.value){this.next(),this.expect("LPAREN");const e=this.expect("VARIABLE").value;return this.expect("RPAREN"),{kind:"sum",variable:e}}if("LPAREN"===e.type){this.next();const e=this.parseValueExpr();return this.expect("RPAREN"),e}throw new M(`Expected a number, variable, sum(...), or parenthesized expression, got "${e.value}"`,this.test,"unsupported-syntax")}}function j(e,t){return e.get(t)}function L(e,t,i){switch(e.kind){case"number":case"string":return e.value;case"sum":return function(e,t,i){const o=j(t,e);return void 0===o?0:(Array.isArray(o)?o:[o]).reduce((t,o)=>{if("string"==typeof o)throw new M(`Variable "$${e}" resolved to a non-numeric value ("${o}") and cannot be used in sum(...)`,i,"unsupported-syntax");return t+o},0)}(e.variable,t,i);case"variable":{const o=j(t,e.name);if(void 0===o)throw new M(`Variable "$${e.name}" has no bound fact and cannot be evaluated directly (only sum()/empty() tolerate an unbound variable)`,i,"unbound-variable");if(Array.isArray(o))throw new M(`Variable "$${e.name}" is a sequence and must be wrapped in sum(...) to be used in arithmetic`,i,"unsupported-syntax");return o}case"additive":return e.terms.reduce((e,{sign:o,term:r})=>{const n=L(r,t,i);if("string"==typeof n)throw new M(`Non-numeric value ("${n}") cannot be used in arithmetic (+ / -)`,i,"unsupported-syntax");return e+o*n},0)}}function N(e,t,i,o){switch(e.kind){case"or":return e.terms.some(e=>N(e,t,i,o));case"and":return e.terms.every(e=>N(e,t,i,o));case"not":return!N(e.arg,t,i,o);case"empty":{const i=j(t,e.variable);return void 0===i||Array.isArray(i)&&0===i.length}case"hasFallbackValue":{const t=o.get(e.variableName);if(void 0===t)throw new M(`xff:has-fallback-value(xs:QName('${e.variableName}')) could not be evaluated — no fallback-usage tracked for this variable (either not one of this assertion's FACT_VARIABLEs, or it matched zero facts with no fallbackValue declared)`,i,"unbound-variable");return t}case"comparison":{const o=L(e.left,t,i),r=L(e.right,t,i);return"string"==typeof o||"string"==typeof r?String(o)===String(r):Math.abs(o-r)<.01}}}function O(e,t,i=new Map){const o=function(e){const t=[];A.lastIndex=0;let i=0;for(;i<e.length;){A.lastIndex=i;const o=A.exec(e);if(!o||o.index!==i){if(/^\s*$/.test(e.slice(i)))break;throw new M(`Unrecognized token at position ${i}: "${e.slice(i,i+10)}..."`,e,"unsupported-syntax")}const[r,n,a,s,l,d,c,p,u,h]=o;n?t.push({type:"VARIABLE",value:n.slice(1)}):a?t.push({type:"NUMBER",value:a}):s?t.push({type:"IDENT",value:s}):l?t.push({type:"STRING",value:l.slice(1,-1)}):d?t.push({type:"LPAREN",value:d}):c?t.push({type:"RPAREN",value:c}):p?t.push({type:"PLUS",value:p}):u?t.push({type:"MINUS",value:u}):h&&t.push({type:"EQUALS",value:h}),i+=r.length}return t.push({type:"EOF",value:""}),t}(e);return N(new P(o,e).parseBoolExpr(),t,e,i)}const V=/^\.\s*(eq|ne|gt|lt|ge|le)\s+(-?\d+(?:\.\d+)?)$/;function z(e){return!!(null==e?void 0:e.toLowerCase().includes("totallabel"))}function U(e){return!!(null==e?void 0:e.toLowerCase().includes("negatedtotallabel"))}function J(e,t,i=0){if(!t.isAbstract(e))return e;if(i>5)return null;const o=t.getChildren(e).find(e=>z(t.getPreferredLabel(e)));return o?J(o,t,i+1):null}function B(e,t,i,o,r){if(i<0)return o;const n=e[t];if(U(r.getPreferredLabel(n)))return o.length>0?o:[e[i]];if(o.length>0)return[e[i],...o];if(U(r.getPreferredLabel(e[i]))){let t=-1;for(let o=i-1;o>=0;o--)if(z(r.getPreferredLabel(e[o]))){t=o;break}return t>=0?[e[t],e[i]]:[e[i]]}return[e[i]]}function q(e){return null!=e&&""!==e}function H(e){const t=[];for(const i of Object.keys(e)){const o=e[i]||{};for(const e of Object.keys(o))q(o[e])&&t.push({conceptId:i,columnId:e})}return t}function Y(e,t,i,o,r,n){const a={conceptId:e.id,qname:e.name,balance:e.balance,effectivePeriodRole:e.effectivePeriodRole};i.set(e.id,a),(t.get(e.name)??t.set(e.name,[]).get(e.name)).push(a);const s=e.children||[],l=s.length>0,d=!0===r.get(e.name);(!o.has(e.name)||l&&!d)&&(o.set(e.name,e.id),r.set(e.name,l)),n.set(e.id,s.map(e=>e.id)),s.forEach(e=>Y(e,t,i,o,r,n))}function K(e,t,i){t.has(e.conceptName)||t.set(e.conceptName,e.id),i.has(e.conceptName)||i.set(e.conceptName,(e.children||[]).map(e=>e.id)),(e.children||[]).forEach(e=>K(e,t,i))}const W={getId:e=>e.id,getPreferredLabel:e=>e.preferredLabel,isAbstract:e=>!0===e.abstract,getChildren:e=>e.children||[]};function G(e,t,i,o,r,n,a){const s=new Map,l=new Map,d=new Map,c=new Map,p=new Map,u=new Map,h=new Map;i.forEach(e=>{const t=new Map,i=new Map,o=new Map;e.concepts.forEach(e=>Y(e,s,l,i,o,t)),c.set(e.roleURI,t),d.set(e.roleURI,i),p.set(e.roleURI,function(e,t){const i=new Map;function o(e,o){const r=[];for(const i of o){const e=J(i,t);e&&r.push(t.getId(e))}0!==r.length&&i.set(t.getId(e),r)}return function e(i){for(let r=0;r<i.length;r++){const n=i[r];if(z(t.getPreferredLabel(n))&&0===t.getChildren(n).length){let e=-1;for(let o=r-1;o>=0;o--)if(z(t.getPreferredLabel(i[o]))){e=o;break}const a=i.slice(e+1,r),s=B(i,r,e,a,t);s.length>0&&o(n,s)}const a=t.getChildren(n);a.length>0&&e(a)}}(e),i}(e.concepts,W));for(const r of t.keys())h.set(r,e.roleURI);e.columns&&u.set(e.roleURI,e.columns)});const m=new Map,f=new Map,g=new Map;return(o||[]).forEach(e=>{e.items.forEach(e=>{e.dimensions.forEach(e=>{m.has(e.conceptName)||m.set(e.conceptName,e.id),(e.members||[]).forEach(e=>K(e,f,g))})})}),{formData:e,columns:t,periodStartDate:r,periodEndDate:n,conceptByQName:s,conceptById:l,conceptIdByQNamePerRole:d,childrenByRole:c,totalGroupChildrenByRole:p,dimensionQNameToId:m,memberQNameToId:f,memberChildrenByQName:g,columnsByRole:u,roleURIByConceptId:h,allCandidates:H(e),typedMemberData:a??{}}}function Q(e){return`${e.conceptId}::${e.columnId}`}function X(e,t){return re(e.filters.map(i=>oe(i,t.allCandidates,t,e.filters)))}function Z(e,t){var i;const o=e.roleURIByConceptId.get(t.conceptId);return(o?null==(i=e.columnsByRole.get(o))?void 0:i.find(e=>e.id===t.columnId):void 0)??e.columns.find(e=>e.id===t.columnId)}function ee(e,t,i){if(!(null==e?void 0:e.dimensionData))return!1;return!(e.dimensionData.axisId!==t||void 0!==i&&e.dimensionData.memberId!==i)||(e.dimensionData.combinations||[]).some(e=>e.axisId===t&&(void 0===i||e.memberId===i))}function te(e,t){return{start:(null==e?void 0:e.periodStartDate)??t.periodStartDate,end:(null==e?void 0:e.periodEndDate)??t.periodEndDate}}function ie(e,t,i,o){var r,n;switch(e.type){case"CONCEPT_NAME":{const o=e.attributes["concept.qname"],r=o?i.conceptByQName.get(o):void 0;if(!r||0===r.length)return[];const n=new Set(r.map(e=>e.conceptId));return t.filter(e=>n.has(e.conceptId))}case"CONCEPT_BALANCE":{const o=e.attributes.balance;return t.filter(e=>{var t;return(null==(t=i.conceptById.get(e.conceptId))?void 0:t.balance)===o})}case"CONCEPT_RELATION":{const o=e.attributes.qname,a=e.attributes.linkrole,s=e.attributes.axis,l=o&&a?null==(r=i.conceptIdByQNamePerRole.get(a))?void 0:r.get(o):void 0,d=a?i.childrenByRole.get(a):void 0;if(!l||!d)return[];let c;if("descendant"===s)c=function(e,t){const i=[],o=[...e.get(t)||[]],r=new Set;for(;o.length>0;){const t=o.pop();r.has(t)||(r.add(t),i.push(t),o.push(...e.get(t)||[]))}return i}(d,l);else{const e=d.get(l)||[];c=e.length>0?e:(null==(n=i.totalGroupChildrenByRole.get(a??""))?void 0:n.get(l))||[]}const p=new Set(c);return t.filter(e=>p.has(e.conceptId))}case"EXPLICIT_DIMENSION":{const r=e.attributes["dimension.qname"],n=e.attributes["member.qname"],a=r?i.dimensionQNameToId.get(r):void 0;if(!a)return[];if(n&&"child"===e.attributes["member.axis"])return function(e,t,i,o,r){var n,a;const s=o.memberChildrenByQName.get(e)||[];if(s.length>0){const e=i.filter(e=>s.some(i=>ee(Z(o,e),t,i)));if(e.length>0)return e}const l=r.find(e=>"CONCEPT_RELATION"===e.type&&"descendant"===e.attributes.axis),d=null==l?void 0:l.attributes.linkrole,c=null==l?void 0:l.attributes.qname,p=c&&d?null==(n=o.conceptIdByQNamePerRole.get(d))?void 0:n.get(c):void 0,u=new Set(p&&d&&(null==(a=o.childrenByRole.get(d))?void 0:a.get(p))||[]);return 0===u.size?[]:i.filter(e=>!u.has(e.conceptId))}(n,a,t,i,o);const s=n?i.memberQNameToId.get(n):void 0;return t.filter(e=>ee(Z(i,e),a,s))}case"TYPED_DIMENSION":{const o=e.attributes["dimension.qname"],r=o?i.dimensionQNameToId.get(o):void 0;return r?t.filter(e=>function(e,t,i){if(!function(e,t){return!!(null==e?void 0:e.dimensionData)&&(void 0!==e.dimensionData.typedMemberId&&e.dimensionData.axisId===t||(e.dimensionData.typedMembers||[]).some(e=>e.axisId===t))}(Z(e,t),i))return!1;const o=e.typedMemberData[t.columnId];return void 0===o||!!o[i]}(i,e,r)):[]}case"PERIOD_INSTANT":case"PERIOD_END":{const o=e.attributes.date;return t.filter(e=>function(e,t,i){const o=function(e){if(e)return e.startsWith("$")?e.slice(1):e}(t);if(!o)return!1;const r=function(e,t){const i=e.includes("StartDate"),o=e.includes("EndDate")||"FinancialReportingPeriodCurrentEndDateParam"===e;if(e.startsWith("FinancialReportingPeriodCurrent"))return i?{start:t.periodStartDate}:o?{end:t.periodEndDate}:void 0;if(e.startsWith("FinancialReportingPeriodPrePrevious")||e.startsWith("FinancialReportingPeriodPrevious")){const e=function(e){return e.columns.find(t=>void 0!==t.periodEndDate&&t.periodEndDate<e.periodEndDate)}(t);if(!e)return;return i?{start:e.periodStartDate}:o?{end:e.periodEndDate}:void 0}}(o,i);if(!r)return!1;const n=te(e,i),a=r.end??r.start;return n.end===a}(Z(i,e),o,i))}case"OR_FILTER":return function(e){const t=new Map;return e.forEach(e=>e.forEach(e=>t.set(Q(e),e))),Array.from(t.values())}(e.children.map(e=>oe(e,t,i,o)));case"ASPECT_COVER":case"UNKNOWN":return t;default:return[]}}function oe(e,t,i,o){const r=ie(e,t,i,o);if(!e.complement)return r;const n=new Set(r.map(Q));return t.filter(e=>!n.has(Q(e)))}function re(e){return 0===e.length?[]:e.reduce((e,t)=>{const i=new Set(t.map(Q));return e.filter(e=>i.has(Q(e)))})}function ne(e){return e.some(e=>"PERIOD_INSTANT"===e.type||"PERIOD_END"===e.type||"OR_FILTER"===e.type&&ne(e.children))}function ae(e,t,i){if(e.length<=1||ne(t.filters))return e;const o=e.filter(e=>te(Z(i,e),i).end===i.periodEndDate);return o.length>0?o:e}function se(e,t){const i=function(e,t){const i=new Map;e.forEach(e=>{var o;const r=(null==(o=t.conceptById.get(e.conceptId))?void 0:o.qname)??e.conceptId,n=`${e.columnId}::${r}`,a=i.get(n);a?a.push(e):i.set(n,[e])});const o=[];return i.forEach(e=>{if(e.length<=1)return void o.push(...e);const i=e.map(e=>{var i;return null==(i=t.conceptById.get(e.conceptId))?void 0:i.effectivePeriodRole}),r=e.filter((e,t)=>"periodEndLabel"===i[t]),n=new Set(i).size>1;o.push(...n&&r.length>0?r:e)}),o}(function(e,t,i){var o,r;if(t.bindAsSequence)return e;if(new Set(e.map(e=>e.conceptId)).size<=1)return e;const n=t.filters.find(e=>"CONCEPT_RELATION"===e.type&&"descendant"===e.attributes.axis),a=null==n?void 0:n.attributes.qname,s=null==n?void 0:n.attributes.linkrole,l=a&&s?null==(o=i.conceptIdByQNamePerRole.get(s))?void 0:o.get(a):void 0,d=new Set(l&&s&&(null==(r=i.childrenByRole.get(s))?void 0:r.get(l))||[]);return 0===d.size?e:e.filter(e=>d.has(e.conceptId))}(ae(X(e,t),e,t),e,t),t),o=i.map(e=>{var i;return function(e){if(null==e||""===e)return;const t=parseFloat(String(e));return Number.isNaN(t)?String(e):t}(null==(i=t.formData[e.conceptId])?void 0:i[e.columnId])}).filter(e=>void 0!==e);if(e.bindAsSequence){if(0===o.length&&"()"===e.fallbackValue)return[];if(0===o.length)return;return o}if(0!==o.length)return o.length>1&&console.warn(`[formula-variable-resolver] Variable "${e.name}" is scalar (bindAsSequence: false) but matched ${o.length} facts; using the first match by column order. This can legitimately happen when filters under-constrain the candidate set.`),o[0]}function le(e,t){return X(e,t).length}function de(e,t){return!(le(e,t)>0)&&(void 0!==e.fallbackValue||void 0)}function ce(e){const t=[];for(const i of e)if("CONCEPT_NAME"===i.type){const e=i.attributes["concept.qname"];e&&t.push(e)}else"OR_FILTER"===i.type&&t.push(...ce(i.children));return t}function pe(e){return ce(e.filters)}function ue(e,t,i){const o=i.columns.map(e=>({conceptId:t,columnId:e.id}));return re(e.filters.map(t=>oe(t,o,i,e.filters))).map(e=>e.columnId)}class he{evaluate(e,t,i){var o;const r=null==(o=e.formula)?void 0:o[0];if(!r)return[];const n=[];for(const a of r.roles)for(const e of a.assertions)n.push(this._evaluateAssertion(e,a,t,i));return n}summarize(e){const t={totalAssertions:e.length,evaluated:0,skipped:0,passed:0,failed:0,failedWarnings:0,failedErrors:0};for(const i of e)i.skipped?t.skipped+=1:(t.evaluated+=1,i.satisfied?t.passed+=1:(t.failed+=1,"ERROR"===i.severity?t.failedErrors+=1:t.failedWarnings+=1));return t}_evaluateAssertion(e,t,i,o){try{const r=function(e,t){const i=new Map;for(const o of e.variables)i.set(o.name,se(o,t));return i}(e,i);if("VALUE_ASSERTION"===e.type){const i=function(e,t){for(const i of e.variables)if(void 0===t.get(i.name))return{satisfied:!1,skipReason:"unresolvable"};return{satisfied:!0}}(e,r);if(!i.satisfied)return this._skippedResult(e,t,i.skipReason??"unresolvable")}const n=function(e,t){var i;if(!(null==(i=e.test)?void 0:i.includes("has-fallback-value"))&&!e.preconditions.some(e=>e.test.includes("has-fallback-value")))return new Map;const o=new Map;for(const r of e.variables){const e=de(r,t);void 0!==e&&o.set(r.name,e)}return o}(e,i),a=function(e,t,i=new Map){if(0===e.length)return{satisfied:!0};for(const r of e){let e;try{e=O(r.test,t,i)}catch(o){if(o instanceof M)return{satisfied:!1,skipReason:"unresolvable"};throw o}if(!e)return{satisfied:!1,skipReason:"precondition"}}return{satisfied:!0}}(e.preconditions,r,n);if(!a.satisfied)return this._skippedResult(e,t,a.skipReason??"unresolvable");if("EXISTENCE_ASSERTION"===e.type){const r=1===e.variables.length?le(e.variables[0],i):function(e,t){const i=new Map;for(const o of e)for(const e of X(o,t))i.set(Q(e),e);return i.size}(e.variables,i),n=function(e,t){const i=(e??"").trim();return""===i?t>0:i.split(/\bor\b/).some(e=>{const o=V.exec(e.trim());if(!o)throw new M(`Unsupported existence-assertion test shape: "${e.trim()}"`,i,"unsupported-syntax");const[,r,n]=o;return function(e,t,i){switch(e){case"eq":return t===i;case"ne":return t!==i;case"gt":return t>i;case"lt":return t<i;case"ge":return t>=i;case"le":return t<=i}}(r,t,Number(n))})}(e.test,r);return this._evaluatedResult(e,t,i,n,o,r)}const s=O(e.test,r,n);return this._evaluatedResult(e,t,i,s,o)}catch(r){if(r instanceof M)return console.warn(`[FormulaValidationService] Assertion "${e.id}" could not be evaluated (${r.reason}): ${r.message}`),this._skippedResult(e,t,"unresolvable");throw r}}_skippedResult(e,t,i){return{assertionId:e.id,roleURI:t.roleURI,roleLabel:t.role,type:e.type,severity:e.severity,satisfied:!1,skipped:!0,skipReason:i}}_evaluatedResult(e,t,i,o,r,n){const a=o?void 0:this._pickMessage(e,r);return{assertionId:e.id,roleURI:t.roleURI,roleLabel:t.role,type:e.type,severity:e.severity,satisfied:o,skipped:!1,message:a,matchedFactCount:n,conceptLinks:a?this._buildConceptLinks(e,t.roleURI,i,a):void 0}}_pickMessage(e,t){const i=e.messages;if(0===i.length)return;const o=i.find(e=>e.xmlLang===t)??i.find(e=>"en"===e.xmlLang)??i[0];return this._stripTechnicalDetail(o.text)}_stripTechnicalDetail(e){const t=e.indexOf("{");return-1===t?e.trim():e.slice(0,t).replace(/\|\s*$/,"").trim()}_buildConceptLinks(e,t,i,o){var r,n,a;const s=[],l=new Set;for(const d of e.variables)for(const e of pe(d)){const c=(null==(r=i.conceptIdByQNamePerRole.get(t))?void 0:r.get(e))??(null==(a=null==(n=i.conceptByQName.get(e))?void 0:n[0])?void 0:a.conceptId);if(!c)continue;const p=e.includes(":")?e.split(":").pop():e;if(l.has(p))continue;if(!new RegExp("`"+this._escapeRegExp(p)+"`").test(o))continue;const u=ue(d,c,i);s.push({label:p,conceptQName:e,conceptId:c,columnId:u[0]}),l.add(p)}return s}_escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}class me{static findMatchingFact(e,t){if(!e||0===e.length)return null;const i=e.filter(e=>this.matchesPeriod(e,t));if(0===i.length)return null;const o=i.filter(e=>this.matchesDimensions(e,t));if(0===o.length)return null;if(o.length>1&&t.unit){const e=o.find(e=>this.matchesUnit(e,t));if(e)return e}return o[0]}static matchesPeriod(e,t){const i=this.parsePeriod(e.period);return"instant"===t.periodType&&t.periodInstantDate?i.isInstant&&i.instantDate===t.periodInstantDate:"duration"===t.periodType&&t.periodStartDate&&t.periodEndDate?!i.isInstant&&i.startDate===t.periodStartDate&&i.endDate===t.periodEndDate:t.periodInstantDate?i.isInstant&&i.instantDate===t.periodInstantDate:!t.periodStartDate||!t.periodEndDate||!i.isInstant&&i.startDate===t.periodStartDate&&i.endDate===t.periodEndDate}static matchesDimensions(e,t){const i=e.dimensions||[],o=this.extractDimensionsFromContext(t);if(0===o.length)return 0===i.length;if(0===i.length&&o.length>0)return!1;if(i.length!==o.length)return!1;return o.every(e=>i.some(t=>{if(!(this.normalizeAxisId(t.dimension)===this.normalizeAxisId(e.axisId)))return!1;if("explicit"===t.dimensionType&&e.memberId){return this.normalizeMemberId(t.member||"")===this.normalizeMemberId(e.memberId)}return!("typed"!==t.dimensionType||!e.isTyped)}))}static matchesUnit(e,t){if(!t.unit||!e.unitMeasure)return!0;return this.normalizeUnit(e.unitMeasure)===this.normalizeUnit(t.unit)}static parsePeriod(e){if(e.includes(" / ")){const[t,i]=e.split(" / ").map(e=>e.trim());return{isInstant:!1,startDate:t,endDate:i}}return{isInstant:!0,instantDate:e.trim()}}static extractDimensionsFromContext(e){if(!e.dimensionData)return[];const t=[];return e.dimensionData.combinations&&e.dimensionData.combinations.length>0&&e.dimensionData.combinations.forEach(e=>{t.push({axisId:e.axisId,memberId:e.memberId})}),e.dimensionData.typedMembers&&e.dimensionData.typedMembers.length>0&&e.dimensionData.typedMembers.forEach(e=>{t.push({axisId:e.axisId,memberId:"[typed]",isTyped:!0})}),t}static normalizeAxisId(e){if(!e)return"";if(e.includes(":")){const t=e.split(":");return t[1]||t[0]}if(e.includes("_")){e.split("_");const t=e.lastIndexOf("_");if(t>0)return e.substring(t+1)}return e}static normalizeMemberId(e){if(!e)return"";if(e.includes(":")){const t=e.split(":");return t[1]||t[0]}if(e.includes("_")){const t=e.lastIndexOf("_");if(t>0)return e.substring(t+1)}return e}static normalizeUnit(e){if(!e)return"";const t=e.split(":");return t.length>1?t[1]:t[0]}static extractTypedValues(e,t){const i={};if(!e||0===e.length)return i;return e.filter(e=>this.matchesPeriod(e,t)&&this.matchesDimensions(e,t)).forEach(e=>{e.dimensions&&e.dimensions.forEach(e=>{if("typed"===e.dimensionType&&e.typedMemberValue){const t=this.normalizeAxisId(e.dimension);i[t]=e.typedMemberValue}})}),i}static debugMatch(e,t){console.log("🔍 [FactMatcher] Debug Match"),console.log(" Context:",{conceptId:t.conceptId,columnId:t.columnId,period:"instant"===t.periodType?t.periodInstantDate:`${t.periodStartDate} / ${t.periodEndDate}`,dimensions:this.extractDimensionsFromContext(t)}),console.log(" Facts:",e.map(e=>{var t;return{value:e.value,period:e.period,dimensions:null==(t=e.dimensions)?void 0:t.map(e=>`${e.dimension}:${e.member}`)}}));const i=this.findMatchingFact(e,t);console.log(" Match Result:",i?i.value:"No match")}}class fe{static validateConceptValue(e,t,i){const o=[];if(null==t||""===t)return{valid:!0,errors:[]};if(!e||!i||0===i.length)return{valid:!0,errors:[]};const r=this.findDatatype(e,i);if(!r||!r.validation)return{valid:!0,errors:[]};const n=r.validation,a=String(t);if(n.pattern){const e=this.validatePattern(a,n.pattern);e&&o.push(e)}if(void 0!==n.length){const e=this.validateExactLength(a,n.length);e&&o.push(e)}if(void 0!==n.minLength){const e=this.validateMinLength(a,n.minLength);e&&o.push(e)}if(void 0!==n.maxLength){const e=this.validateMaxLength(a,n.maxLength);e&&o.push(e)}if(void 0!==n.totalDigits){const e=this.validateTotalDigits(a,n.totalDigits);e&&o.push(e)}return{valid:0===o.length,errors:o}}static findDatatype(e,t){let i=t.find(t=>t.type===e);if(i)return i;const o=new Set;let r=e;for(;r&&!o.has(r)&&(o.add(r),i=t.find(e=>e.type===r),i);){if(i.validation)return i;r=i.basetype}}static validatePattern(e,t){try{if(!new RegExp(`^${t}$`).test(e))return{type:"pattern",message:T.t("xbrlValidation.patternMismatch",{pattern:t}),expectedValue:t,actualValue:e}}catch(i){return console.error(`Invalid regex pattern: ${t}`,i),{type:"pattern",message:T.t("xbrlValidation.invalidPattern",{pattern:t}),expectedValue:t,actualValue:e}}return null}static validateExactLength(e,t){return e.length!==t?{type:"length",message:T.t("xbrlValidation.exactLength",{required:t,current:e.length}),expectedValue:t,actualValue:e.length}:null}static validateMinLength(e,t){return e.length<t?{type:"minLength",message:T.t("xbrlValidation.minLength",{required:t,current:e.length}),expectedValue:t,actualValue:e.length}:null}static validateMaxLength(e,t){return e.length>t?{type:"maxLength",message:T.t("xbrlValidation.maxLength",{required:t,current:e.length}),expectedValue:t,actualValue:e.length}:null}static validateTotalDigits(e,t){const i=e.replace(/[^\d]/g,"");return i.length>t?{type:"totalDigits",message:T.t("xbrlValidation.totalDigits",{required:t,current:i.length}),expectedValue:t,actualValue:i.length}:null}static getValidationRulesSummary(e,t){if(!e||!t)return[];const i=this.findDatatype(e,t);if(!i||!i.validation)return[];const o=i.validation,r=[];return o.pattern&&r.push(T.t("xbrlValidation.ruleSummaryPattern",{pattern:o.pattern})),void 0!==o.length&&r.push(T.t("xbrlValidation.ruleSummaryExactLength",{required:o.length})),void 0!==o.minLength&&r.push(T.t("xbrlValidation.ruleSummaryMinLength",{required:o.minLength})),void 0!==o.maxLength&&r.push(T.t("xbrlValidation.ruleSummaryMaxLength",{required:o.maxLength})),void 0!==o.totalDigits&&r.push(T.t("xbrlValidation.ruleSummaryTotalDigits",{required:o.totalDigits})),r}}const ge={"nl-types:formattedExplanationItemType":{fieldType:"textarea",placeholder:T.t("field.enterDetailedExplanation")},"nl-types:monetaryNoDecimals20ItemType":{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!1,step:1,placeholder:T.t("field.enterAmountNoDecimals")},"xbrli:monetaryItemType":{fieldType:"currency",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterCurrency")},"xbrli:stringItemType":{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterText")},"xbrli:dateItemType":{fieldType:"date",htmlInputType:"date"},"xbrli:dateTimeItemType":{fieldType:"datetime",htmlInputType:"datetime-local"},"xbrli:integerItemType":{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,step:1,placeholder:T.t("field.enterWholeNumber")},"xbrli:nonNegativeIntegerItemType":{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:0,step:1,placeholder:T.t("field.enterPositiveNumber")},"xbrli:positiveIntegerItemType":{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:1,step:1,placeholder:T.t("field.enterPositiveNumber")},"xbrli:decimalItemType":{fieldType:"decimal",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:"any",placeholder:T.t("field.enterDecimalValue")},"xbrli:sharesItemType":{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,min:0,step:.01,placeholder:T.t("field.enterNumberOfShares")},"xbrli:shares":{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,min:0,step:.01,placeholder:T.t("field.enterNumberOfShares")},"xbrli:gYearItemType":{fieldType:"number",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:1900,max:2100,step:1,placeholder:T.t("field.yearFormat")},"xbrli:booleanItemType":{fieldType:"boolean"},"xbrli:pureItemType":{fieldType:"percentage",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterPercentage")},"xbrli:percentItemType":{fieldType:"percentage",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterPercentage")},"xbrli:emailItemType":{fieldType:"email",htmlInputType:"email",placeholder:T.t("field.emailPlaceholder")},"xbrli:urlItemType":{fieldType:"url",htmlInputType:"url",placeholder:T.t("field.urlPlaceholder")},"xbrli:telephoneItemType":{fieldType:"tel",htmlInputType:"tel",placeholder:T.t("field.phonePlaceholder")}};function be(e,t){if(!e)return{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterValue")};if(t&&t.length>0){const i=_e(e,t);if(i.length>0){return Ie(i,t)}}if(console.log(`⚠️ [Type Resolution Fallback] Using pattern matching for: ${e}`),ge[e])return ge[e];const i=e.toLowerCase();if(i.includes("monetary"))return i.includes("nodecimals")||i.includes("no-decimals")?{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!1,step:1,placeholder:T.t("field.enterAmountNoDecimals")}:{fieldType:"currency",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterCurrency")};if(i.includes("explanation")||i.includes("description")||i.includes("notes")||i.includes("formatted"))return{fieldType:"textarea",placeholder:T.t("field.enterDetailedInformation")};if(i.includes("date"))return i.includes("time")?{fieldType:"datetime",htmlInputType:"datetime-local"}:{fieldType:"date",htmlInputType:"date"};if(i.includes("boolean")||i.includes("bool"))return{fieldType:"boolean"};if(i.includes("integer")||i.includes("int")){const e=i.includes("nonnegative")||i.includes("non-negative");return{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:i.includes("positive")?1:e?0:void 0,step:1,placeholder:T.t("field.enterWholeNumber")}}return i.includes("decimal")||i.includes("numeric")||i.includes("number")?{fieldType:"decimal",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:"any",placeholder:T.t("field.enterDecimalValue")}:i.includes("percent")||i.includes("pure")?{fieldType:"percentage",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterPercentage")}:{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterValue")}}function ve(e){return"textarea"===e}function ye(e){return"boolean"===e}function xe(e){return["number","decimal","integer","currency","percentage"].includes(e)}function _e(e,t){const i=[];if(!e)return i;if(!t||0===t.length)return i.push(e),i;let o=e;const r=new Set;for(;o;){if(i.push(o),r.has(o)){console.warn(`Circular reference detected in datatype hierarchy for type: ${o}`);break}r.add(o);const e=t.find(e=>e.type===o);if(!e||!e.basetype||""===e.basetype.trim())break;o=e.basetype}return i}function De(e,t){if(e&&0!==e.length&&t&&0!==t.length)for(const i of e){const e=t.find(e=>e.type===i);if(e&&e.enumerations&&e.enumerations.length>0)return e.enumerations.map(e=>({id:e.id||e.value,value:e.value,label:e.value}))}}function Ie(e,t){if(!e||0===e.length)return{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterValue")};if(t&&t.length>0){const i=De(e,t);if(i&&i.length>0)return{fieldType:"select",enumerations:i,placeholder:T.t("field.selectOption")}}const i=e.map(e=>e.toLowerCase()),o=i.join("|");if(e.some(e=>"nl-types:formattedExplanationItemType"===e)||o.includes("formattedexplanation")||o.includes("formatted")&&o.includes("explanation"))return{fieldType:"textarea",placeholder:T.t("field.enterDetailedExplanation")};if(i.some(e=>e.includes("date")))return o.includes("datetime")||o.includes("time")?{fieldType:"datetime",htmlInputType:"datetime-local"}:{fieldType:"date",htmlInputType:"date"};if(i.some(e=>e.includes("boolean")||e.includes("bool")))return{fieldType:"boolean"};if(i.some(e=>e.includes("integer")||"integer"===e)){const e=o.includes("nonnegative")||o.includes("non-negative");return{fieldType:"integer",htmlInputType:"text",inputMode:"numeric",allowDecimals:!1,min:o.includes("positive")?1:e?0:void 0,step:1,placeholder:T.t("field.enterWholeNumber")}}return i.some(e=>e.includes("percent")||e.includes("pure"))?{fieldType:"percentage",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterPercentage")}:i.some(e=>e.includes("decimal")||"decimal"===e)?o.includes("monetary")||o.includes("currency")?o.includes("nodecimals")||o.includes("no-decimals")||o.includes("nodecimals20")?{fieldType:"number",htmlInputType:"text",inputMode:"decimal",allowDecimals:!1,step:1,placeholder:T.t("field.enterAmountNoDecimals")}:{fieldType:"currency",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:.01,placeholder:T.t("field.enterCurrency")}:{fieldType:"decimal",htmlInputType:"text",inputMode:"decimal",allowDecimals:!0,step:"any",placeholder:T.t("field.enterDecimalValue")}:e.some(e=>"xbrli:stringItemType"===e)||i.some(e=>"string"===e||e.includes("stringitem"))?{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterText")}:{fieldType:"text",htmlInputType:"text",placeholder:T.t("field.enterValue")}}var $e=Object.defineProperty,we=Object.getOwnPropertyDescriptor,Se=(e,t,i,o)=>{for(var r,n=o>1?void 0:o?we(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(n=(o?r(t,i,n):r(n))||n);return o&&n&&$e(t,i,n),n};exports.JupiterFormField=class extends e.LitElement{constructor(){super(...arguments),this.defaultUnits=[],this.value=null,this.disabled=!1,this.locale="en-US",this.hideLabel=!1,this.mode="inputForm",this.globalDecimals="INF",this.typedMemberValues={},this._errors=[],this._xbrlErrors=[],this._touched=!1,this._showPeriodPopup=!1,this._availableUnits=[],this._numericDraftValue=null}willUpdate(e){var t;(e.has("value")||e.has("field"))&&this._validateField(),e.has("unit")&&this.unit&&(console.log(`🏷️ [FormField willUpdate] Unit property changed to: ${this.unit}, conceptId: ${this.conceptId}, columnId: ${this.columnId}`),this.dispatchEvent(new CustomEvent("unit-change",{detail:{fieldId:null==(t=this.field)?void 0:t.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit},bubbles:!0,composed:!0}))),e.has("field")&&this.field&&(this.conceptId.includes("DescriptionLocationNL")||this.columnId.startsWith("col-"))&&console.log(`📅 [FormField willUpdate] Concept ${this.conceptId}, Column ${this.columnId}: field.periodType=${this.field.periodType}, field.periodStartDate=${this.field.periodStartDate}, field.periodEndDate=${this.field.periodEndDate}, field.periodInstantDate=${this.field.periodInstantDate}`)}_validateField(){var e;(null==(e=this.field)?void 0:e.validation)&&(this._errors=C.validateField(this.field.id,this.conceptId,this.columnId,this.value,this.field.type,this.field.validation))}_isRoundingLevelConcept(){return!!this.conceptId&&this.conceptId.includes("DocumentIntendedRoundingLevel")}_isNumericField(){var e;return xe(be(this.conceptType,this.datatypes).fieldType||(null==(e=this.field)?void 0:e.type)||"text")||"number"===this._getInputType()}_isIntermediateNumericValue(e){return"-"===e||"."===e||"-."===e}_handleInput(e){const t=e.target,i=this.value;let o=t.value;if(this._isNumericField()){const e=t.value;if(this._numericDraftValue=e,""===e||this._isIntermediateNumericValue(e))o=null;else{const t=Number(e);o=Number.isNaN(t)?null:t}}else"boolean"===this.field.type?(o=t.checked,this._numericDraftValue=null):this._numericDraftValue=null;this.value=o,this._touched=!0,this.dispatchEvent(new CustomEvent("field-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,value:o,oldValue:i},bubbles:!0}))}_handleFocus(){this.dispatchEvent(new CustomEvent("field-focus",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId},bubbles:!0}))}_handleBlur(){let e=!1;if(this._isNumericField()&&null!==this._numericDraftValue){e=!0;const t=this._numericDraftValue;if(""===t||this._isIntermediateNumericValue(t))this.value=null;else{const e=Number(t);this.value=Number.isNaN(e)?null:e}this._numericDraftValue=null}if(this._isPercentItemType()&&e&&null!==this.value&&void 0!==this.value){const e=Number(this.value);if(!isNaN(e)&&Math.abs(e)>1){this.value=e/100;const t=e;this.dispatchEvent(new CustomEvent("field-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,value:this.value,oldValue:t},bubbles:!0}))}}this._touched=!0,this._validateXBRLDatatype(),this._validateUnitSelection(),console.log(`🟦 [FormField] Blur event - fieldId: ${this.field.id}, conceptId: ${this.conceptId}, columnId: ${this.columnId}`),console.log("🟦 [FormField] Current _xbrlErrors:",this._xbrlErrors),console.log("🟦 [FormField] Current value:",this.value),this.dispatchEvent(new CustomEvent("field-blur",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,xbrlValidationErrors:this._xbrlErrors},bubbles:!0,composed:!0})),console.log(`🟦 [FormField] Dispatched field-blur event with ${this._xbrlErrors.length} errors`)}_isMonetaryType(){if(!this.conceptType||!this.datatypes)return!1;if(this.conceptType.includes("monetary")||this.conceptType.includes("Monetary"))return!0;return _e(this.conceptType,this.datatypes).some(e=>e.includes("monetary")||e.includes("Monetary"))}_isPercentItemType(){if(!this.conceptType)return!1;if(this.conceptType.toLowerCase().includes("percent"))return!0;if(!this.datatypes)return!1;return _e(this.conceptType,this.datatypes).some(e=>e.toLowerCase().includes("percent"))}_handleKeyDown(e){const t=e.target;if(!this._isNumericField())return;if(["Backspace","Delete","Tab","Escape","Enter","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End"].includes(e.key))return;if(e.ctrlKey||e.metaKey)return;const i=be(this.conceptType,this.datatypes),o=void 0===i.min||i.min<0;("-"!==e.key||!o||t.value.includes("-")||0!==t.selectionStart&&0!==t.value.length)&&("."!==e.key||!1===i.allowDecimals||t.value.includes("."))&&(e.key>="0"&&e.key<="9"||e.preventDefault())}_validateXBRLDatatype(){if(this._xbrlErrors=[],null===this.value||void 0===this.value||""===this.value)return;if(!this.conceptType||!this.datatypes||0===this.datatypes.length)return;const e=fe.validateConceptValue(this.conceptType,this.value,this.datatypes);e.valid?console.log(`✅ [FormField] XBRL Validation passed for ${this.conceptId}`):(this._xbrlErrors=e.errors,console.log(`❌ [FormField] XBRL Validation failed for ${this.conceptId}:`,{conceptType:this.conceptType,value:this.value,errors:this._xbrlErrors}))}_validateUnitSelection(){if(null===this.value||void 0===this.value||""===this.value)return;const e=this._collectUnitsForConceptType();if(0===e.length)return;if(this.unit)return;const t=e.find(e=>!0===e.isDefault)??(1===e.length?e[0]:null);if(t)return this.unit=t.id,this.dispatchEvent(new CustomEvent("unit-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit},bubbles:!0,composed:!0})),void console.log(`🎯 [FormField] Auto-selected default unit on blur: ${this.unit} for ${this.conceptId}`);this._xbrlErrors=[...this._xbrlErrors,{type:"unit",message:T.t("validation.unitRequired"),expectedValue:e.map(e=>e.label).join(", "),actualValue:""}],console.log(`❌ [FormField] Unit validation failed for ${this.conceptId}: unit is required but not selected`)}_handlePeriodIconClick(){if(!this._isRoundingLevelConcept()){if(this._availableUnits=this._collectUnitsForConceptType(),console.log(`📊 [FormField] Collected ${this._availableUnits.length} units for concept ${this.conceptId}:`,this._availableUnits),console.log(`📊 [FormField] Current unit value: ${this.unit}`),console.log(`📊 [FormField] ConceptId: ${this.conceptId}, ColumnId: ${this.columnId}`),!this.unit&&this._availableUnits.length>0){let e=null;const t=this._availableUnits.find(e=>!0===e.isDefault);t?(e=t.id,console.log(`🎯 [FormField] Auto-selecting default unit: ${t.id} (${t.label})`)):1===this._availableUnits.length&&(e=this._availableUnits[0].id,console.log(`🎯 [FormField] Auto-selecting single available unit: ${e}`)),e&&(this.unit=e,this.dispatchEvent(new CustomEvent("unit-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit},bubbles:!0,composed:!0})))}else this.unit&&(console.log(`📊 [FormField] Unit already set, dispatching unit-change to ensure parent stores it: ${this.unit}`),this.dispatchEvent(new CustomEvent("unit-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit},bubbles:!0,composed:!0})));this._showPeriodPopup=!0}}_collectUnitsForConceptType(){if(!this.conceptType||!this.datatypes)return[];const e=_e(this.conceptType,this.datatypes);console.log(`🔍 [Unit Resolution] Concept: ${this.conceptId}, Type: ${this.conceptType}, BaseType Chain:`,e);for(const t of e){const e=this.datatypes.find(e=>e.type===t);if(e&&e.units&&Array.isArray(e.units)&&e.units.length>0)return console.log(`✅ [Unit Resolution] Found ${e.units.length} units in type: ${t}`),e.units}return console.log(`ℹ️ [Unit Resolution] No units found for concept ${this.conceptId}`),[]}_closePeriodPopup(){this._showPeriodPopup=!1}_handleUnitChange(e){const t=e.target.value;console.log(`🏷️ [FormField] Unit change detected: value=${t}, conceptId=${this.conceptId}, columnId=${this.columnId}`),console.log(`🏷️ [FormField] Previous unit value: ${this.unit}`),this.unit=t,console.log(`🏷️ [FormField] Updated unit value to: ${this.unit}`);const i={fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,unit:this.unit};console.log("🏷️ [FormField] Dispatching unit-change event with detail:",i),this.dispatchEvent(new CustomEvent("unit-change",{detail:i,bubbles:!0,composed:!0})),console.log("🏷️ [FormField] unit-change event dispatched")}_handleDecimalsChange(e){const t=e.target.value.trim(),i=parseFloat(t),o=t&&!isNaN(i)?String(Math.abs(i)):""===t?"":t;this.decimals=o||void 0,this.dispatchEvent(new CustomEvent("decimals-change",{detail:{conceptId:this.conceptId,columnId:this.columnId,decimals:this.decimals},bubbles:!0,composed:!0}))}_handlePopupOverlayClick(e){e.target===e.currentTarget&&this._closePeriodPopup()}_ensureTextDialogStyles(){if(document.getElementById("jdf-text-dialog-styles"))return;const e=document.createElement("style");e.id="jdf-text-dialog-styles",e.textContent="\n dialog.jdf-text-entry-dialog {\n border: none; border-radius: 8px; padding: 0;\n max-width: 600px; width: 90vw;\n box-shadow: 0 8px 32px rgba(0,0,0,0.2); overflow: hidden;\n font-family: inherit;\n }\n dialog.jdf-text-entry-dialog::backdrop { background: rgba(0,0,0,0.35); }\n .jdf-text-dialog-header {\n background: #f0f2f5; padding: 14px 20px;\n display: flex; align-items: center; justify-content: space-between;\n border-bottom: 1px solid #ddd;\n }\n .jdf-text-dialog-title {\n font-size: 15px; font-weight: 600; color: #333; margin: 0;\n font-family: inherit; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n }\n .jdf-text-dialog-close {\n flex-shrink: 0; width: 28px; height: 28px; border: none; background: transparent;\n font-size: 20px; line-height: 1; cursor: pointer; color: #666;\n border-radius: 4px; display: flex; align-items: center; justify-content: center;\n padding: 0; font-family: inherit; margin-left: 8px;\n }\n .jdf-text-dialog-close:hover { background: #ddd; color: #333; }\n .jdf-text-dialog-body { padding: 20px 20px 12px; }\n .jdf-text-dialog-textarea {\n width: 100%; min-height: 200px; max-height: 50vh;\n padding: 10px 12px; font-size: 14px; font-family: inherit;\n border: 1px solid #ddd; border-radius: 4px;\n box-sizing: border-box; resize: vertical; line-height: 1.5;\n color: #333; background: #fff;\n }\n .jdf-text-dialog-textarea:focus {\n outline: none; border-color: #1976d2;\n box-shadow: 0 0 0 2px rgba(25,118,210,0.2);\n }\n .jdf-text-dialog-char-count {\n margin-top: 4px; font-size: 12px; color: #888; text-align: right;\n font-family: inherit;\n }\n .jdf-text-dialog-actions {\n display: flex; justify-content: flex-end; gap: 8px;\n padding: 12px 20px 16px; border-top: 1px solid #eee;\n }\n .jdf-text-dialog-cancel {\n padding: 7px 18px; border: 1px solid #ddd; border-radius: 4px;\n background: transparent; color: #555; font-size: 14px;\n cursor: pointer; font-family: inherit;\n }\n .jdf-text-dialog-cancel:hover { background: #f5f5f5; }\n .jdf-text-dialog-save {\n padding: 7px 18px; border: none; border-radius: 4px;\n background: #1976d2; color: #fff; font-size: 14px;\n cursor: pointer; font-family: inherit; font-weight: 500;\n }\n .jdf-text-dialog-save:hover { background: #1565c0; }\n ",document.head.appendChild(e)}_openTextDialog(e,t){var i;this._ensureTextDialogStyles(),null==(i=document.getElementById("jdf-text-entry-dialog"))||i.remove();const o=document.createElement("dialog");o.id="jdf-text-entry-dialog",o.className="jdf-text-entry-dialog",o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby","jdf-text-dialog-title"),o.innerHTML='\n <div class="jdf-text-dialog-header">\n <h3 class="jdf-text-dialog-title" id="jdf-text-dialog-title"></h3>\n <button class="jdf-text-dialog-close" type="button" aria-label="Close">×</button>\n </div>\n <div class="jdf-text-dialog-body">\n <textarea class="jdf-text-dialog-textarea" spellcheck="true"></textarea>\n <div class="jdf-text-dialog-char-count"></div>\n </div>\n <div class="jdf-text-dialog-actions">\n <button class="jdf-text-dialog-cancel" type="button"></button>\n <button class="jdf-text-dialog-save" type="button"></button>\n </div>\n ';const r=t;o.querySelector(".jdf-text-dialog-title").textContent=r||t,o.querySelector(".jdf-text-dialog-cancel").textContent=T.t("field.cancel"),o.querySelector(".jdf-text-dialog-save").textContent=T.t("field.save");const n=o.querySelector(".jdf-text-dialog-textarea"),a=o.querySelector(".jdf-text-dialog-char-count");n.value=e,a.textContent=`${e.length} ${T.t("field.characters")}`,n.addEventListener("input",()=>{a.textContent=`${n.value.length} ${T.t("field.characters")}`}),o.querySelector(".jdf-text-dialog-close").addEventListener("click",()=>o.close()),o.querySelector(".jdf-text-dialog-cancel").addEventListener("click",()=>o.close()),o.querySelector(".jdf-text-dialog-save").addEventListener("click",()=>{const e=n.value,t=this.value;this.value=e,this._touched=!0,this.dispatchEvent(new CustomEvent("field-change",{detail:{fieldId:this.field.id,conceptId:this.conceptId,columnId:this.columnId,value:e,oldValue:t},bubbles:!0})),o.close()}),o.addEventListener("click",e=>{const t=o.getBoundingClientRect();(e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)&&o.close()}),o.addEventListener("close",()=>o.remove()),document.body.appendChild(o),o.showModal(),n.focus()}_renderTextDialogTrigger(t,i){const o=null!=t&&""!==String(t).trim(),r=o?String(t):"";return i?e.html`
|
|
23
23
|
<span class="text-readonly-label ${o?"":"empty"}"
|
|
24
24
|
title="${r}">${o?r:"—"}</span>
|
|
25
25
|
`:o?e.html`
|
|
@@ -1588,7 +1588,7 @@ const I={attribute:!0,type:String,converter:y,reflect:!1,hasChanged:x},$=(e=I,t,
|
|
|
1588
1588
|
margin: 0 0 12px 0;
|
|
1589
1589
|
line-height: 1.4;
|
|
1590
1590
|
}
|
|
1591
|
-
`,Re([w({type:String})],exports.JupiterAddColumnDialog.prototype,"periodType",2),Re([w({type:Boolean})],exports.JupiterAddColumnDialog.prototype,"open",2),Re([w({type:Array})],exports.JupiterAddColumnDialog.prototype,"availableDimensions",2),Re([w({type:String})],exports.JupiterAddColumnDialog.prototype,"periodStartDate",2),Re([w({type:String})],exports.JupiterAddColumnDialog.prototype,"periodEndDate",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_startDate",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_endDate",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_instantDate",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_selectedType",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_selectedDimensions",2),exports.JupiterAddColumnDialog=Re([t("jupiter-add-column-dialog")],exports.JupiterAddColumnDialog);var Me=Object.defineProperty,Ae=Object.getOwnPropertyDescriptor,je=(e,t,i,o)=>{for(var r,n=o>1?void 0:o?Ae(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(n=(o?r(t,i,n):r(n))||n);return o&&n&&Me(t,i,n),n};exports.JupiterFormSection=class extends e.LitElement{constructor(){super(...arguments),this.columns=[],this.formData={},this.periodData={},this.unitData={},this.decimalsData={},this.globalDecimals="INF",this.typedMemberData={},this.repeatCounts={},this.defaultUnits=[],this.disabled=!1,this.collapsible=!0,this.locale="en-US",this.isFirstSection=!1,this.availableDimensions=[],this.hideHeader=!1,this.mode="inputForm",this.showFactsOnly=!1,this.periodStartDate="",this.periodEndDate="",this.language="en",this.calculationEnabled=!1,this.totalManuallyEditedData={},this._expanded=!0,this._showAddColumnDialog=!1,this._sectionPeriodType="duration",this._openMenuColumnId=null,this._insertAfterColumnId=null,this._boundFieldBlur=e=>{if(this._clearHighlights(),this._focusedConceptId=null,"readonly"===this.mode||!this.calculationEnabled)return;const t=e.detail;(null==t?void 0:t.conceptId)&&(null==t?void 0:t.columnId)&&this._runCalculationCheck(t.conceptId,t.columnId)},this._expandedConcepts=new Set,this._allTreeExpanded=!1,this._highlightMap=new Map,this._focusedConceptId=null,this._calculationMismatches=new Map,this._totalChildrenMap=new Map,this._memberParentMap=new Map,this._totalConceptMap=new Map,this._totalChildConceptsMap=new Map,this._sessionManuallyEditedTotals=new Set}connectedCallback(){super.connectedCallback(),this._expanded=!1!==this.section.expanded,this._determinePeriodType(),this._checkAndExpandFirstSection(),document.addEventListener("click",()=>this._closeColumnMenu()),this.addEventListener("field-blur",this._boundFieldBlur)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("click",()=>this._closeColumnMenu()),this.removeEventListener("field-blur",this._boundFieldBlur)}updated(e){var t;super.updated(e),(e.has("isFirstSection")||e.has("section"))&&this._checkAndExpandFirstSection(),(e.has("section")||e.has("calculationEnabled"))&&(this.calculationEnabled&&(null==(t=this.section)?void 0:t.concepts)?this._buildTotalMaps(this.section.concepts):this._clearCalculationState()),e.has("totalManuallyEditedData")&&this._sessionManuallyEditedTotals.clear()}_checkAndExpandFirstSection(){this.isFirstSection&&this.section&&this.section.concepts&&(this._expanded=!0,setTimeout(()=>{this._expandAllTrees(),console.log("🎯 First section detected - expanded section and tree by default")},0))}_determinePeriodType(){const e=this._getAllNonAbstractConcepts(this.section.concepts);if(0===e.length)return this._sectionPeriodType="duration",void console.log(`📊 Section ${this.section.id}: No concepts, defaulting to duration`);const t=new Set(e.map(e=>e.periodType).filter(Boolean));if(0===t.size)this._sectionPeriodType="duration";else if(1===t.size){const e=Array.from(t)[0];this._sectionPeriodType="instant"===e?"instant":"duration"}else this._sectionPeriodType="mixed"}_getAllNonAbstractConcepts(e){const t=[];for(const i of e)i.abstract||t.push(i),i.children&&t.push(...this._getAllNonAbstractConcepts(i.children));return t}_toggleExpanded(){this.collapsible&&(this._expanded=!this._expanded,this._expanded&&this._expandAllTrees(),this.dispatchEvent(new CustomEvent("section-expand",{detail:{sectionId:this.section.id,expanded:this._expanded},bubbles:!0})))}_handleRemoveColumn(e){this._openMenuColumnId=null,this.dispatchEvent(new CustomEvent("column-remove",{detail:{columnId:e,sectionId:this.section.id},bubbles:!0}))}_handleHideColumn(e){this._openMenuColumnId=null,this.dispatchEvent(new CustomEvent("column-hide",{detail:{columnId:e,sectionId:this.section.id},bubbles:!0}))}_handleShowColumn(e){this.dispatchEvent(new CustomEvent("column-show",{detail:{columnId:e,sectionId:this.section.id},bubbles:!0}))}_toggleColumnMenu(e,t){t.stopPropagation(),this._openMenuColumnId=this._openMenuColumnId===e?null:e}_closeColumnMenu(){this._openMenuColumnId=null}_handleAddColumnFromMenu(e,t){t.stopPropagation(),this._openMenuColumnId=null,this._insertAfterColumnId=e,this._handleAddColumn()}_handleAddColumn(){const e=this._determineButtonPeriodType();this._sectionPeriodType=e,this._showAddColumnDialog=!0}_determineButtonPeriodType(){const e=this._getAllNonAbstractConcepts(this.section.concepts);if(0===e.length)return"duration";const t=new Set(e.map(e=>e.periodType).filter(e=>null!=e));if(0===t.size)return"duration";if(1===t.size){return"instant"===Array.from(t)[0]?"instant":"duration"}return"mixed"}_getConceptsWithFields(e){const t=[];for(const i of e)!i.abstract&&i.fields&&i.fields.length>0&&t.push(i),i.children&&t.push(...this._getConceptsWithFields(i.children));return t}_handleDialogCancel(){this._showAddColumnDialog=!1}_handleColumnAdd(e){e.stopPropagation(),this._showAddColumnDialog=!1,this.dispatchEvent(new CustomEvent("column-add-request",{detail:{sectionId:this.section.id,columnRequest:e.detail,insertAfterColumnId:this._insertAfterColumnId},bubbles:!0})),this._insertAfterColumnId=null}_handleFieldChange(e){e.stopPropagation();const{conceptId:t,columnId:i}=e.detail||{};t&&i&&this._totalConceptMap.has(t)&&(this._sessionManuallyEditedTotals.add(`${t}__${i}`),this.dispatchEvent(new CustomEvent("total-manually-edited",{detail:{conceptId:t,columnId:i},bubbles:!0,composed:!0}))),this.dispatchEvent(new CustomEvent("field-change",{detail:e.detail,bubbles:!0,composed:!0}))}_handlePeriodChange(e){console.log("📋 [FormSection] Received period-change event:",e.detail),e.stopPropagation(),this.dispatchEvent(new CustomEvent("period-change",{detail:e.detail,bubbles:!0,composed:!0})),console.log("📋 [FormSection] Forwarded period-change event to dynamic-form")}_flattenConcepts(e,t=new Set){const i=[];for(const o of e)if(i.push(o),o.children&&o.children.length>0&&t.has(o.id)){const e=this._flattenConcepts(o.children,t);i.push(...e)}return i}_isTotalManuallyEdited(e,t){var i,o;const r=`${e}__${t}`;return!!this._sessionManuallyEditedTotals.has(r)||!0===(null==(o=null==(i=this.totalManuallyEditedData)?void 0:i[e])?void 0:o[t])}_isConceptRowBlank(e){var t;for(const i of this.columns){const o=null==(t=this.formData[e.id])?void 0:t[i.id];if(null!=o&&""!==o)return!1}return!0}_getAllConceptIds(e){const t=[];for(const i of e)i.children&&i.children.length>0&&(t.push(i.id),t.push(...this._getAllConceptIds(i.children)));return t}_expandAllTrees(){const e=this._getAllConceptIds(this.section.concepts||[]);this._expandedConcepts=new Set([...this._expandedConcepts,...e]),this._allTreeExpanded=!0}_collapseAllTrees(){this._expandedConcepts=new Set,this._allTreeExpanded=!1}_handleConceptExpand(e){e.stopPropagation();const{conceptId:t,expanded:i}=e.detail,o=new Set(this._expandedConcepts);i?o.add(t):o.delete(t),this._expandedConcepts=o;const r=this._getAllConceptIds(this.section.concepts||[]);this._allTreeExpanded=r.length>0&&r.every(e=>o.has(e)),this.dispatchEvent(new CustomEvent("concept-expand",{detail:e.detail,bubbles:!0}))}_buildTotalMaps(e){this._totalChildrenMap.clear(),this._memberParentMap.clear(),this._totalConceptMap.clear(),this._totalChildConceptsMap.clear(),this._traverseTotalGroups(e)}_clearCalculationState(){this._totalChildrenMap.clear(),this._memberParentMap.clear(),this._totalConceptMap.clear(),this._totalChildConceptsMap.clear();for(const e of Array.from(this._calculationMismatches.keys()))this._clearCalculationMismatch(e)}static _isTotalLabel(e){return E(e)}static _isNegatedTotalLabel(e){return!!(null==e?void 0:e.toLowerCase().includes("negatedtotallabel"))}static _resolveValueConcept(e,t=0){var i;if(!e.abstract)return e;if(t>5||!(null==(i=e.children)?void 0:i.length))return null;const o=e.children.find(e=>exports.JupiterFormSection._isTotalLabel(e.preferredLabel));return o?exports.JupiterFormSection._resolveValueConcept(o,t+1):null}_registerTotalGroup(e,t){const i=t.map(e=>exports.JupiterFormSection._resolveValueConcept(e)).filter(e=>null!==e);if(0===i.length)return;const o=i.map(e=>e.id);this._totalChildrenMap.set(e.id,o),this._totalConceptMap.set(e.id,e),this._totalChildConceptsMap.set(e.id,i);for(const r of o)this._memberParentMap.set(r,e.id)}_resolveTotalGroupMembers(e,t,i,o){if(i<0)return o;const r=e[t];if(exports.JupiterFormSection._isNegatedTotalLabel(r.preferredLabel))return o.length>0?o:[e[i]];if(o.length>0)return[e[i],...o];if(exports.JupiterFormSection._isNegatedTotalLabel(e[i].preferredLabel)){let t=-1;for(let o=i-1;o>=0;o--)if(exports.JupiterFormSection._isTotalLabel(e[o].preferredLabel)){t=o;break}return t>=0?[e[t],e[i]]:[e[i]]}return[e[i]]}_traverseTotalGroups(e){var t,i;for(let o=0;o<e.length;o++){const r=e[o];if(exports.JupiterFormSection._isTotalLabel(r.preferredLabel))if(null==(t=r.children)?void 0:t.length)this._registerTotalGroup(r,r.children);else{let t=-1;for(let r=o-1;r>=0;r--)if(exports.JupiterFormSection._isTotalLabel(e[r].preferredLabel)){t=r;break}const i=e.slice(t+1,o),n=this._resolveTotalGroupMembers(e,o,t,i);n.length>0&&this._registerTotalGroup(r,n)}(null==(i=r.children)?void 0:i.length)&&this._traverseTotalGroups(r.children)}}_runCalculationCheck(e,t){const i=new Set;this._totalConceptMap.has(e)&&i.add(e);const o=this._memberParentMap.get(e);o&&i.add(o);for(const r of i)this._evaluateTotal(r,t)}_evaluateTotal(e,t){var i,o;const r=this._totalConceptMap.get(e),n=`${e}__${t}`,a=this._totalChildConceptsMap.get(e)||[],{calculatedSum:s,hasAnyValue:l,breakdown:d}=this._buildCalculationBreakdown(a,this.formData,t,r.balance);if(!this._isTotalManuallyEdited(e,t)){if(l){const o=null==(i=this.formData[e])?void 0:i[t],r=parseFloat(o);(null==o||""===o||isNaN(r)||!exports.JupiterFormSection._checkTotal(r,s))&&this._dispatchCalculationTotalAutoPopulated(e,t,s)}return void this._clearCalculationMismatch(n)}const c=null==(o=this.formData[e])?void 0:o[t];if(null==c||""===c)return void this._clearCalculationMismatch(n);const p=parseFloat(c);if(isNaN(p))return void this._clearCalculationMismatch(n);if(!l||exports.JupiterFormSection._checkTotal(p,s))return void this._clearCalculationMismatch(n);const u={totalConceptId:e,totalLabel:r.label,columnId:t,sectionId:this.section.id,enteredTotal:p,calculatedSum:s,children:d},h={...u,message:exports.JupiterFormSection._buildMismatchMessage(u)},m=new Map(this._calculationMismatches);m.set(n,h),this._calculationMismatches=m,this._dispatchCalculationMismatchChanged(n,h)}_dispatchCalculationTotalAutoPopulated(e,t,i){this.dispatchEvent(new CustomEvent("calculation-total-auto-populated",{detail:{conceptId:e,columnId:t,value:i,sectionId:this.section.id},bubbles:!0,composed:!0}))}_clearCalculationMismatch(e){if(!this._calculationMismatches.has(e))return;const t=new Map(this._calculationMismatches);t.delete(e),this._calculationMismatches=t,this._dispatchCalculationMismatchChanged(e,null)}_dispatchCalculationMismatchChanged(e,t){this.dispatchEvent(new CustomEvent("calculation-mismatch-changed",{detail:{key:e,mismatch:t},bubbles:!0,composed:!0}))}static _resolveWeight(e,t){return e&&t&&e!==t?-1:1}_resolveMemberContributions(e,t,i,o,r,n=0){var a;const s=parseFloat(null==(a=i[e.id])?void 0:a[o]);if(!isNaN(s))return[{conceptId:e.id,label:e.label,value:s,balance:e.balance,weight:t}];if(n>=5||r.has(e.id))return[];const l=this._totalChildConceptsMap.get(e.id);if(!l)return[];const d=new Set(r).add(e.id),c=[];for(const p of l){const r=t*exports.JupiterFormSection._resolveWeight(e.balance,p.balance);c.push(...this._resolveMemberContributions(p,r,i,o,d,n+1))}return c}_buildCalculationBreakdown(e,t,i,o){let r=0,n=!1;const a=[];for(const s of e){const e=exports.JupiterFormSection._resolveWeight(o,s.balance),l=this._resolveMemberContributions(s,e,t,i,new Set);for(const t of l)r+=t.weight*t.value,n=!0,a.push(t)}return{calculatedSum:r,hasAnyValue:n,breakdown:a}}static _checkTotal(e,t){return Math.abs(t-e)<.01}static _formatNumber(e){return Number.isInteger(e)?String(e):e.toFixed(2)}static _buildMismatchMessage(e){const t=T.t("calculationWarning.summaryLine",{label:e.totalLabel,calculated:exports.JupiterFormSection._formatNumber(e.calculatedSum),entered:exports.JupiterFormSection._formatNumber(e.enteredTotal)});if(0===e.children.length)return t;const i=e.children.map(e=>T.t(1===e.weight?"calculationWarning.childAdded":"calculationWarning.childSubtracted",{label:e.label,value:exports.JupiterFormSection._formatNumber(e.value)}));return`${t} ${T.t("calculationWarning.childrenPrefix")} ${i.join("; ")}`}_handleFieldFocusForHighlight(e){var t,i;const o=null==(t=e.detail)?void 0:t.conceptId,r=null==(i=e.detail)?void 0:i.columnId;if(!o||!r)return;this._focusedConceptId=o;const n=new Map;if(this._totalChildrenMap.has(o)){n.set(o,{type:"total",columnId:r});for(const e of this._totalChildrenMap.get(o))n.set(e,{type:"member",columnId:r})}else{const e=this._memberParentMap.get(o);if(e){n.set(e,{type:"total",columnId:r});for(const t of this._totalChildrenMap.get(e))n.set(t,{type:"member",columnId:r})}}this._highlightMap=n}_clearHighlights(){this._highlightMap.size>0&&(this._highlightMap=new Map)}_getTypedMemberHeaderValue(e,t){var i;return(null==(i=this.typedMemberData[e])?void 0:i[t])||""}_handleTypedMemberHeaderChange(e,t,i){const o=e.target.value;console.log(`🔍 [FormSection] Typed member header change: columnId=${t}, axisId=${i}, value=${o}`),this.dispatchEvent(new CustomEvent("typed-member-change",{detail:{columnId:t,axisId:i,value:o},bubbles:!0}))}_handleAddRepeat(e){e.stopPropagation(),this.dispatchEvent(new CustomEvent("add-concept-repeat",{detail:e.detail,bubbles:!0}))}_handleRemoveRepeat(e){e.stopPropagation(),this.dispatchEvent(new CustomEvent("remove-concept-repeat",{detail:e.detail,bubbles:!0}))}_renderConceptRows(t){var i;const o="readonly"!==this.mode&&!t.abstract&&(null==(i=t.fields)?void 0:i.some(e=>{var t;return(null==(t=e.crossRoleTypedMembers)?void 0:t.length)>0})),r=o&&this.repeatCounts[t.id]||0,n=(t,i)=>{var o,r;return e.html`
|
|
1591
|
+
`,Re([w({type:String})],exports.JupiterAddColumnDialog.prototype,"periodType",2),Re([w({type:Boolean})],exports.JupiterAddColumnDialog.prototype,"open",2),Re([w({type:Array})],exports.JupiterAddColumnDialog.prototype,"availableDimensions",2),Re([w({type:String})],exports.JupiterAddColumnDialog.prototype,"periodStartDate",2),Re([w({type:String})],exports.JupiterAddColumnDialog.prototype,"periodEndDate",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_startDate",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_endDate",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_instantDate",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_selectedType",2),Re([S()],exports.JupiterAddColumnDialog.prototype,"_selectedDimensions",2),exports.JupiterAddColumnDialog=Re([t("jupiter-add-column-dialog")],exports.JupiterAddColumnDialog);var Me=Object.defineProperty,Ae=Object.getOwnPropertyDescriptor,Pe=(e,t,i,o)=>{for(var r,n=o>1?void 0:o?Ae(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(n=(o?r(t,i,n):r(n))||n);return o&&n&&Me(t,i,n),n};exports.JupiterFormSection=class extends e.LitElement{constructor(){super(...arguments),this.columns=[],this.formData={},this.periodData={},this.unitData={},this.decimalsData={},this.globalDecimals="INF",this.typedMemberData={},this.repeatCounts={},this.defaultUnits=[],this.disabled=!1,this.collapsible=!0,this.locale="en-US",this.isFirstSection=!1,this.availableDimensions=[],this.hideHeader=!1,this.mode="inputForm",this.showFactsOnly=!1,this.periodStartDate="",this.periodEndDate="",this.language="en",this.calculationEnabled=!1,this.totalManuallyEditedData={},this._expanded=!0,this._showAddColumnDialog=!1,this._sectionPeriodType="duration",this._openMenuColumnId=null,this._insertAfterColumnId=null,this._boundFieldBlur=e=>{if(this._clearHighlights(),this._focusedConceptId=null,"readonly"===this.mode||!this.calculationEnabled)return;const t=e.detail;(null==t?void 0:t.conceptId)&&(null==t?void 0:t.columnId)&&this._runCalculationCheck(t.conceptId,t.columnId)},this._expandedConcepts=new Set,this._allTreeExpanded=!1,this._highlightMap=new Map,this._focusedConceptId=null,this._calculationMismatches=new Map,this._totalChildrenMap=new Map,this._memberParentMap=new Map,this._totalConceptMap=new Map,this._totalChildConceptsMap=new Map,this._sessionManuallyEditedTotals=new Set}connectedCallback(){super.connectedCallback(),this._expanded=!1!==this.section.expanded,this._determinePeriodType(),this._checkAndExpandFirstSection(),document.addEventListener("click",()=>this._closeColumnMenu()),this.addEventListener("field-blur",this._boundFieldBlur)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("click",()=>this._closeColumnMenu()),this.removeEventListener("field-blur",this._boundFieldBlur)}updated(e){var t;super.updated(e),(e.has("isFirstSection")||e.has("section"))&&this._checkAndExpandFirstSection(),(e.has("section")||e.has("calculationEnabled"))&&(this.calculationEnabled&&(null==(t=this.section)?void 0:t.concepts)?this._buildTotalMaps(this.section.concepts):this._clearCalculationState()),e.has("totalManuallyEditedData")&&this._sessionManuallyEditedTotals.clear()}_checkAndExpandFirstSection(){this.isFirstSection&&this.section&&this.section.concepts&&(this._expanded=!0,setTimeout(()=>{this._expandAllTrees(),console.log("🎯 First section detected - expanded section and tree by default")},0))}_determinePeriodType(){const e=this._getAllNonAbstractConcepts(this.section.concepts);if(0===e.length)return this._sectionPeriodType="duration",void console.log(`📊 Section ${this.section.id}: No concepts, defaulting to duration`);const t=new Set(e.map(e=>e.periodType).filter(Boolean));if(0===t.size)this._sectionPeriodType="duration";else if(1===t.size){const e=Array.from(t)[0];this._sectionPeriodType="instant"===e?"instant":"duration"}else this._sectionPeriodType="mixed"}_getAllNonAbstractConcepts(e){const t=[];for(const i of e)i.abstract||t.push(i),i.children&&t.push(...this._getAllNonAbstractConcepts(i.children));return t}_toggleExpanded(){this.collapsible&&(this._expanded=!this._expanded,this._expanded&&this._expandAllTrees(),this.dispatchEvent(new CustomEvent("section-expand",{detail:{sectionId:this.section.id,expanded:this._expanded},bubbles:!0})))}_handleRemoveColumn(e){this._openMenuColumnId=null,this.dispatchEvent(new CustomEvent("column-remove",{detail:{columnId:e,sectionId:this.section.id},bubbles:!0}))}_handleHideColumn(e){this._openMenuColumnId=null,this.dispatchEvent(new CustomEvent("column-hide",{detail:{columnId:e,sectionId:this.section.id},bubbles:!0}))}_handleShowColumn(e){this.dispatchEvent(new CustomEvent("column-show",{detail:{columnId:e,sectionId:this.section.id},bubbles:!0}))}_toggleColumnMenu(e,t){t.stopPropagation(),this._openMenuColumnId=this._openMenuColumnId===e?null:e}_closeColumnMenu(){this._openMenuColumnId=null}_handleAddColumnFromMenu(e,t){t.stopPropagation(),this._openMenuColumnId=null,this._insertAfterColumnId=e,this._handleAddColumn()}_handleAddColumn(){const e=this._determineButtonPeriodType();this._sectionPeriodType=e,this._showAddColumnDialog=!0}_determineButtonPeriodType(){const e=this._getAllNonAbstractConcepts(this.section.concepts);if(0===e.length)return"duration";const t=new Set(e.map(e=>e.periodType).filter(e=>null!=e));if(0===t.size)return"duration";if(1===t.size){return"instant"===Array.from(t)[0]?"instant":"duration"}return"mixed"}_getConceptsWithFields(e){const t=[];for(const i of e)!i.abstract&&i.fields&&i.fields.length>0&&t.push(i),i.children&&t.push(...this._getConceptsWithFields(i.children));return t}_handleDialogCancel(){this._showAddColumnDialog=!1}_handleColumnAdd(e){e.stopPropagation(),this._showAddColumnDialog=!1,this.dispatchEvent(new CustomEvent("column-add-request",{detail:{sectionId:this.section.id,columnRequest:e.detail,insertAfterColumnId:this._insertAfterColumnId},bubbles:!0})),this._insertAfterColumnId=null}_handleFieldChange(e){e.stopPropagation();const{conceptId:t,columnId:i}=e.detail||{};t&&i&&this._totalConceptMap.has(t)&&(this._sessionManuallyEditedTotals.add(`${t}__${i}`),this.dispatchEvent(new CustomEvent("total-manually-edited",{detail:{conceptId:t,columnId:i},bubbles:!0,composed:!0}))),this.dispatchEvent(new CustomEvent("field-change",{detail:e.detail,bubbles:!0,composed:!0}))}_handlePeriodChange(e){console.log("📋 [FormSection] Received period-change event:",e.detail),e.stopPropagation(),this.dispatchEvent(new CustomEvent("period-change",{detail:e.detail,bubbles:!0,composed:!0})),console.log("📋 [FormSection] Forwarded period-change event to dynamic-form")}_flattenConcepts(e,t=new Set){const i=[];for(const o of e)if(i.push(o),o.children&&o.children.length>0&&t.has(o.id)){const e=this._flattenConcepts(o.children,t);i.push(...e)}return i}_isTotalManuallyEdited(e,t){var i,o;const r=`${e}__${t}`;return!!this._sessionManuallyEditedTotals.has(r)||!0===(null==(o=null==(i=this.totalManuallyEditedData)?void 0:i[e])?void 0:o[t])}_isConceptRowBlank(e){var t;for(const i of this.columns){const o=null==(t=this.formData[e.id])?void 0:t[i.id];if(null!=o&&""!==o)return!1}return!0}_getAllConceptIds(e){const t=[];for(const i of e)i.children&&i.children.length>0&&(t.push(i.id),t.push(...this._getAllConceptIds(i.children)));return t}_expandAllTrees(){const e=this._getAllConceptIds(this.section.concepts||[]);this._expandedConcepts=new Set([...this._expandedConcepts,...e]),this._allTreeExpanded=!0}_collapseAllTrees(){this._expandedConcepts=new Set,this._allTreeExpanded=!1}_handleConceptExpand(e){e.stopPropagation();const{conceptId:t,expanded:i}=e.detail,o=new Set(this._expandedConcepts);i?o.add(t):o.delete(t),this._expandedConcepts=o;const r=this._getAllConceptIds(this.section.concepts||[]);this._allTreeExpanded=r.length>0&&r.every(e=>o.has(e)),this.dispatchEvent(new CustomEvent("concept-expand",{detail:e.detail,bubbles:!0}))}_buildTotalMaps(e){this._totalChildrenMap.clear(),this._memberParentMap.clear(),this._totalConceptMap.clear(),this._totalChildConceptsMap.clear(),this._traverseTotalGroups(e)}_clearCalculationState(){this._totalChildrenMap.clear(),this._memberParentMap.clear(),this._totalConceptMap.clear(),this._totalChildConceptsMap.clear();for(const e of Array.from(this._calculationMismatches.keys()))this._clearCalculationMismatch(e)}static _isTotalLabel(e){return E(e)}static _isNegatedTotalLabel(e){return!!(null==e?void 0:e.toLowerCase().includes("negatedtotallabel"))}static _resolveValueConcept(e,t=0){var i;if(!e.abstract)return e;if(t>5||!(null==(i=e.children)?void 0:i.length))return null;const o=e.children.find(e=>exports.JupiterFormSection._isTotalLabel(e.preferredLabel));return o?exports.JupiterFormSection._resolveValueConcept(o,t+1):null}_registerTotalGroup(e,t){const i=t.map(e=>exports.JupiterFormSection._resolveValueConcept(e)).filter(e=>null!==e);if(0===i.length)return;const o=i.map(e=>e.id);this._totalChildrenMap.set(e.id,o),this._totalConceptMap.set(e.id,e),this._totalChildConceptsMap.set(e.id,i);for(const r of o)this._memberParentMap.set(r,e.id)}_resolveTotalGroupMembers(e,t,i,o){if(i<0)return o;const r=e[t];if(exports.JupiterFormSection._isNegatedTotalLabel(r.preferredLabel))return o.length>0?o:[e[i]];if(o.length>0)return[e[i],...o];if(exports.JupiterFormSection._isNegatedTotalLabel(e[i].preferredLabel)){let t=-1;for(let o=i-1;o>=0;o--)if(exports.JupiterFormSection._isTotalLabel(e[o].preferredLabel)){t=o;break}return t>=0?[e[t],e[i]]:[e[i]]}return[e[i]]}_traverseTotalGroups(e){var t,i;for(let o=0;o<e.length;o++){const r=e[o];if(exports.JupiterFormSection._isTotalLabel(r.preferredLabel))if(null==(t=r.children)?void 0:t.length)this._registerTotalGroup(r,r.children);else{let t=-1;for(let r=o-1;r>=0;r--)if(exports.JupiterFormSection._isTotalLabel(e[r].preferredLabel)){t=r;break}const i=e.slice(t+1,o),n=this._resolveTotalGroupMembers(e,o,t,i);n.length>0&&this._registerTotalGroup(r,n)}(null==(i=r.children)?void 0:i.length)&&this._traverseTotalGroups(r.children)}}_runCalculationCheck(e,t){const i=new Set;this._totalConceptMap.has(e)&&i.add(e);const o=this._memberParentMap.get(e);o&&i.add(o);for(const r of i)this._evaluateTotal(r,t)}_evaluateTotal(e,t){var i,o;const r=this._totalConceptMap.get(e),n=`${e}__${t}`,a=this._totalChildConceptsMap.get(e)||[],{calculatedSum:s,hasAnyValue:l,breakdown:d}=this._buildCalculationBreakdown(a,this.formData,t,r.balance);if(!this._isTotalManuallyEdited(e,t)){if(l){const o=null==(i=this.formData[e])?void 0:i[t],r=parseFloat(o);(null==o||""===o||isNaN(r)||!exports.JupiterFormSection._checkTotal(r,s))&&this._dispatchCalculationTotalAutoPopulated(e,t,s)}return void this._clearCalculationMismatch(n)}const c=null==(o=this.formData[e])?void 0:o[t];if(null==c||""===c)return void this._clearCalculationMismatch(n);const p=parseFloat(c);if(isNaN(p))return void this._clearCalculationMismatch(n);if(!l||exports.JupiterFormSection._checkTotal(p,s))return void this._clearCalculationMismatch(n);const u={totalConceptId:e,totalLabel:r.label,columnId:t,sectionId:this.section.id,enteredTotal:p,calculatedSum:s,children:d},h={...u,message:exports.JupiterFormSection._buildMismatchMessage(u)},m=new Map(this._calculationMismatches);m.set(n,h),this._calculationMismatches=m,this._dispatchCalculationMismatchChanged(n,h)}_dispatchCalculationTotalAutoPopulated(e,t,i){this.dispatchEvent(new CustomEvent("calculation-total-auto-populated",{detail:{conceptId:e,columnId:t,value:i,sectionId:this.section.id},bubbles:!0,composed:!0}))}_clearCalculationMismatch(e){if(!this._calculationMismatches.has(e))return;const t=new Map(this._calculationMismatches);t.delete(e),this._calculationMismatches=t,this._dispatchCalculationMismatchChanged(e,null)}_dispatchCalculationMismatchChanged(e,t){this.dispatchEvent(new CustomEvent("calculation-mismatch-changed",{detail:{key:e,mismatch:t},bubbles:!0,composed:!0}))}static _resolveWeight(e,t){return e&&t&&e!==t?-1:1}_resolveMemberContributions(e,t,i,o,r,n=0){var a;const s=parseFloat(null==(a=i[e.id])?void 0:a[o]);if(!isNaN(s))return[{conceptId:e.id,label:e.label,value:s,balance:e.balance,weight:t}];if(n>=5||r.has(e.id))return[];const l=this._totalChildConceptsMap.get(e.id);if(!l)return[];const d=new Set(r).add(e.id),c=[];for(const p of l){const r=t*exports.JupiterFormSection._resolveWeight(e.balance,p.balance);c.push(...this._resolveMemberContributions(p,r,i,o,d,n+1))}return c}_buildCalculationBreakdown(e,t,i,o){let r=0,n=!1;const a=[];for(const s of e){const e=exports.JupiterFormSection._resolveWeight(o,s.balance),l=this._resolveMemberContributions(s,e,t,i,new Set);for(const t of l)r+=t.weight*t.value,n=!0,a.push(t)}return{calculatedSum:r,hasAnyValue:n,breakdown:a}}static _checkTotal(e,t){return Math.abs(t-e)<.01}static _formatNumber(e){return Number.isInteger(e)?String(e):e.toFixed(2)}static _buildMismatchMessage(e){const t=T.t("calculationWarning.summaryLine",{label:e.totalLabel,calculated:exports.JupiterFormSection._formatNumber(e.calculatedSum),entered:exports.JupiterFormSection._formatNumber(e.enteredTotal)});if(0===e.children.length)return t;const i=e.children.map(e=>T.t(1===e.weight?"calculationWarning.childAdded":"calculationWarning.childSubtracted",{label:e.label,value:exports.JupiterFormSection._formatNumber(e.value)}));return`${t} ${T.t("calculationWarning.childrenPrefix")} ${i.join("; ")}`}_handleFieldFocusForHighlight(e){var t,i;const o=null==(t=e.detail)?void 0:t.conceptId,r=null==(i=e.detail)?void 0:i.columnId;if(!o||!r)return;this._focusedConceptId=o;const n=new Map;if(this._totalChildrenMap.has(o)){n.set(o,{type:"total",columnId:r});for(const e of this._totalChildrenMap.get(o))n.set(e,{type:"member",columnId:r})}else{const e=this._memberParentMap.get(o);if(e){n.set(e,{type:"total",columnId:r});for(const t of this._totalChildrenMap.get(e))n.set(t,{type:"member",columnId:r})}}this._highlightMap=n}_clearHighlights(){this._highlightMap.size>0&&(this._highlightMap=new Map)}_getTypedMemberHeaderValue(e,t){var i;return(null==(i=this.typedMemberData[e])?void 0:i[t])||""}_handleTypedMemberHeaderChange(e,t,i){const o=e.target.value;console.log(`🔍 [FormSection] Typed member header change: columnId=${t}, axisId=${i}, value=${o}`),this.dispatchEvent(new CustomEvent("typed-member-change",{detail:{columnId:t,axisId:i,value:o},bubbles:!0}))}_handleAddRepeat(e){e.stopPropagation(),this.dispatchEvent(new CustomEvent("add-concept-repeat",{detail:e.detail,bubbles:!0}))}_handleRemoveRepeat(e){e.stopPropagation(),this.dispatchEvent(new CustomEvent("remove-concept-repeat",{detail:e.detail,bubbles:!0}))}_renderConceptRows(t){var i;const o="readonly"!==this.mode&&!t.abstract&&(null==(i=t.fields)?void 0:i.some(e=>{var t;return(null==(t=e.crossRoleTypedMembers)?void 0:t.length)>0})),r=o&&this.repeatCounts[t.id]||0,n=(t,i)=>{var o,r;return e.html`
|
|
1592
1592
|
<jupiter-concept-tree
|
|
1593
1593
|
.concept="${t}"
|
|
1594
1594
|
.columns="${this.columns}"
|
|
@@ -2045,7 +2045,7 @@ const I={attribute:!0,type:String,converter:y,reflect:!1,hasChanged:x},$=(e=I,t,
|
|
|
2045
2045
|
color: var(--jupiter-text-secondary, #666);
|
|
2046
2046
|
font-style: italic;
|
|
2047
2047
|
}
|
|
2048
|
-
`,
|
|
2048
|
+
`,Pe([w({type:Object})],exports.JupiterFormSection.prototype,"section",2),Pe([w({type:Array})],exports.JupiterFormSection.prototype,"columns",2),Pe([w({type:Array})],exports.JupiterFormSection.prototype,"datatypes",2),Pe([w({type:Object})],exports.JupiterFormSection.prototype,"formData",2),Pe([w({type:Object})],exports.JupiterFormSection.prototype,"periodData",2),Pe([w({type:Object})],exports.JupiterFormSection.prototype,"unitData",2),Pe([w({type:Object})],exports.JupiterFormSection.prototype,"decimalsData",2),Pe([w({type:String})],exports.JupiterFormSection.prototype,"globalDecimals",2),Pe([w({type:Object})],exports.JupiterFormSection.prototype,"typedMemberData",2),Pe([w({type:Object})],exports.JupiterFormSection.prototype,"repeatCounts",2),Pe([w({type:Array})],exports.JupiterFormSection.prototype,"defaultUnits",2),Pe([w({type:Boolean})],exports.JupiterFormSection.prototype,"disabled",2),Pe([w({type:Boolean})],exports.JupiterFormSection.prototype,"collapsible",2),Pe([w({type:String})],exports.JupiterFormSection.prototype,"locale",2),Pe([w({type:Boolean})],exports.JupiterFormSection.prototype,"isFirstSection",2),Pe([w({type:Array})],exports.JupiterFormSection.prototype,"availableDimensions",2),Pe([w({type:Boolean})],exports.JupiterFormSection.prototype,"hideHeader",2),Pe([w({type:String})],exports.JupiterFormSection.prototype,"mode",2),Pe([w({type:Boolean})],exports.JupiterFormSection.prototype,"showFactsOnly",2),Pe([w({type:Object})],exports.JupiterFormSection.prototype,"conceptMatchIds",2),Pe([w({type:Object})],exports.JupiterFormSection.prototype,"masterData",2),Pe([w({type:String})],exports.JupiterFormSection.prototype,"periodStartDate",2),Pe([w({type:String})],exports.JupiterFormSection.prototype,"periodEndDate",2),Pe([w({type:String})],exports.JupiterFormSection.prototype,"language",2),Pe([w({type:Boolean})],exports.JupiterFormSection.prototype,"calculationEnabled",2),Pe([w({type:Object})],exports.JupiterFormSection.prototype,"totalManuallyEditedData",2),Pe([S()],exports.JupiterFormSection.prototype,"_expanded",2),Pe([S()],exports.JupiterFormSection.prototype,"_showAddColumnDialog",2),Pe([S()],exports.JupiterFormSection.prototype,"_sectionPeriodType",2),Pe([S()],exports.JupiterFormSection.prototype,"_openMenuColumnId",2),Pe([S()],exports.JupiterFormSection.prototype,"_insertAfterColumnId",2),Pe([S()],exports.JupiterFormSection.prototype,"_expandedConcepts",2),Pe([S()],exports.JupiterFormSection.prototype,"_allTreeExpanded",2),Pe([S()],exports.JupiterFormSection.prototype,"_highlightMap",2),Pe([S()],exports.JupiterFormSection.prototype,"_focusedConceptId",2),Pe([S()],exports.JupiterFormSection.prototype,"_calculationMismatches",2),exports.JupiterFormSection=Pe([t("jupiter-form-section")],exports.JupiterFormSection);var je=Object.defineProperty,Le=Object.getOwnPropertyDescriptor,Ne=(e,t,i,o)=>{for(var r,n=o>1?void 0:o?Le(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(n=(o?r(t,i,n):r(n))||n);return o&&n&&je(t,i,n),n};exports.JupiterAdvancedFilter=class extends e.LitElement{constructor(){super(...arguments),this.showFactsOnly=!1,this.conceptSearchText="",this._localConceptSearchText=""}updated(e){e.has("conceptSearchText")&&this.conceptSearchText!==this._localConceptSearchText&&(this._localConceptSearchText=this.conceptSearchText)}_handleShowFactsOnlyChange(e){const t=e.target.checked;this.dispatchEvent(new CustomEvent("filter-change",{detail:{showFactsOnly:t,conceptSearchText:this._localConceptSearchText},bubbles:!0,composed:!0}))}_sanitizeSearchText(e){return e.replace(/[''‚‛′‵]/g,"'").replace(/[""„‟″‶]/g,'"').replace(/[]/g,"").replace(/\s+/g," ").trim()}_handleConceptSearchInput(e){this._localConceptSearchText=this._sanitizeSearchText(e.target.value),this.dispatchEvent(new CustomEvent("filter-change",{detail:{showFactsOnly:this.showFactsOnly,conceptSearchText:this._localConceptSearchText},bubbles:!0,composed:!0}))}_clearConceptSearch(){var e;this._localConceptSearchText="";const t=null==(e=this.shadowRoot)?void 0:e.querySelector(".concept-search-input");t&&(t.value="",t.focus()),this.dispatchEvent(new CustomEvent("filter-change",{detail:{showFactsOnly:this.showFactsOnly,conceptSearchText:""},bubbles:!0,composed:!0}))}render(){return e.html`
|
|
2049
2049
|
<div class="filter-options">
|
|
2050
2050
|
<label class="filter-option clickable">
|
|
2051
2051
|
<input
|
|
@@ -3662,7 +3662,7 @@ const I={attribute:!0,type:String,converter:y,reflect:!1,hasChanged:x},$=(e=I,t,
|
|
|
3662
3662
|
</div>
|
|
3663
3663
|
</div>
|
|
3664
3664
|
</div>
|
|
3665
|
-
`}getData(){return{...this._formData}}setData(e){this._formData={...e},this._dirty=!0,this._validateForm(),this.requestUpdate()}validate(){return this._validateForm(),this._valid}setValidation(e){console.log(`🔍 Validation status updated: ${e}`),this._validationStatus="cancel"===e?"idle":e,this.requestUpdate()}reset(){this._handleReset()}getState(){return this._getFormState()}_findConceptByName(e,t){var i;const o=t.includes(":")?t.split(":").pop():t;for(const r of e){if(r.name===t)return r;if((r.name.includes(":")?r.name.split(":").pop():r.name)===o)return r;if(null==(i=r.children)?void 0:i.length){const e=this._findConceptByName(r.children,t);if(e)return e}}return null}_findAllConceptsByName(e,t){var i;const o=t.includes(":")?t.split(":").pop():t,r=[];for(const n of e){const e=n.name.includes(":")?n.name.split(":").pop():n.name;n.name!==t&&e!==o||r.push(n),(null==(i=n.children)?void 0:i.length)&&r.push(...this._findAllConceptsByName(n.children,t))}return r}_findConceptById(e,t){var i;for(const o of e){if(o.id===t)return o;if(null==(i=o.children)?void 0:i.length){const e=this._findConceptById(o.children,t);if(e)return e}}return null}_valueLooselyMatches(e,t){const i=String(e??"");if(i===t)return!0;const o=Number(i),r=Number(t);if(isNaN(o)||isNaN(r))return!1;if(o===r)return!0;if(0!==o&&0!==r){const e=Math.abs(r/o),t=Math.log10(e);if(Math.abs(t-Math.round(t))<1e-4)return!0}return!1}_findColumnByDimensions(e,t){var i;return null==(i=e.find(e=>{if("dimension"!==e.type||!e.dimensionData)return!1;const i=e.dimensionData.combinations;return(null==i?void 0:i.length)?t.every(e=>i.some(t=>this._normalizeAxisId(t.axisId)===this._normalizeAxisId(e.axis)&&this._normalizeMemberId(t.memberId)===this._normalizeMemberId(e.member))):1===t.length&&this._normalizeAxisId(e.dimensionData.axisId??"")===this._normalizeAxisId(t[0].axis)&&this._normalizeMemberId(e.dimensionData.memberId??"")===this._normalizeMemberId(t[0].member)}))?void 0:i.id}async scrollToConcept(e,t,i,o,r){var n,a,s,l,d,c,p,u,h,m,f,g;console.log(`[scrollToConcept] ▶ START conceptName=${e} value=${null==i?void 0:i.value} dims=${JSON.stringify(t)} columnId=${o} exactConceptId=${r}`);let b=null,v=null;const y=[...(null==(n=this._currentSchema)?void 0:n.sections)??[],...this._allSections.filter(e=>{var t;return!(null==(t=this._currentSchema)?void 0:t.sections.find(t=>t.id===e.id))})];console.log(`[scrollToConcept] Searching ${y.length} sections`);const x=void 0!==(null==i?void 0:i.value)&&null!==(null==i?void 0:i.value),_=x?String(i.value):null;if(r)for(const U of y){const e=this._findConceptById(U.concepts,r);if(e){console.log(`[scrollToConcept] Section "${U.id}" matched exactConceptId="${r}"`),b=U,v=e;break}}if(!b||!v)for(const U of y){const i=this._findAllConceptsByName(U.concepts,e);if(!i.length)continue;const r=U.columns??this._columns,n=o??((null==t?void 0:t.length)?this._findColumnByDimensions(r,t):void 0);let a;i.length>1&&(a=i.find(e=>{const t=this._formData[e.id];if(!t)return!1;if(n){const e=t[n];return null!=e&&""!==e&&(!x||this._valueLooselyMatches(e,_))}return!!x&&Object.values(t).some(e=>null!=e&&""!==e&&this._valueLooselyMatches(e,_))}),console.log(`[scrollToConcept] Section "${U.id}" has ${i.length} rows named "${e}" | disambiguated=${(null==a?void 0:a.id)??"none (using first)"}`));const s=a??i[0];if(o){const e=r.some(e=>e.id===o);if(console.log(`[scrollToConcept] Section "${U.id}" has concept "${s.id}" | columnId="${o}" present=${e}`),e){b=U,v=s;break}b||(b=U,v=s)}else{if(!(null==t?void 0:t.length)){console.log(`[scrollToConcept] Section "${U.id}" has concept "${s.id}" (no dims, taking first)`),b=U,v=s;break}if(console.log(`[scrollToConcept] Section "${U.id}" has concept "${s.id}" | colMatch=${n??"null"} | cols=${r.map(e=>e.id).join(",")}`),n){b=U,v=s;break}b||(b=U,v=s)}}if(!b||!v)return void console.warn(`[scrollToConcept] Concept not found: ${e}`);console.log(`[scrollToConcept] → targetSection="${b.id}" targetConceptId="${v.id}"`),b.expanded=!0,"sidePanel"===this.display&&this._activeSidePanelRoleId!==b.id&&(this._activeSidePanelRoleId=b.id);const D=b.columns??this._columns;let I=null;o?I=o:(null==t?void 0:t.length)?I=this._findColumnByDimensions(D,t)??null:x||(I=(null==(a=D[0])?void 0:a.id)??null),console.log(`[scrollToConcept] targetColumnId=${I} hasValueMatch=${x} targetValue=${_}`),this._conceptSearchText=e.includes(":")?e.split(":").pop():e,this.requestUpdate(),await this.updateComplete,await new Promise(e=>setTimeout(e,300));const $=null==(s=this.shadowRoot)?void 0:s.querySelectorAll("jupiter-form-section");console.log(`[scrollToConcept] DOM: found ${(null==$?void 0:$.length)??0} jupiter-form-section elements`);let w=null;if(null==$||$.forEach(e=>{var t;(null==(t=e.section)?void 0:t.id)===b.id&&(w=e)}),!w)return void console.warn(`[scrollToConcept] Section element not found: ${b.id}`);await w.updateComplete;const S=null==(l=w.shadowRoot)?void 0:l.querySelectorAll("jupiter-concept-tree");console.log(`[scrollToConcept] conceptTrees in targetSection: ${(null==S?void 0:S.length)??0}`);let C=null;const F=v.id,k=F.includes("__")?F.split("__")[0]:F;console.log(`[scrollToConcept] conceptId="${F}" conceptIdBase="${k}"`);const T=e=>e===F||e.includes("__")&&e.split("__")[0]===k,E=e=>{const t=e.decimals||(void 0!==e.globalDecimals&&"INF"!==e.globalDecimals?e.globalDecimals:null);if(!t)return 1;const i=parseFloat(String(t));return isNaN(i)||i<=0?1:Math.pow(10,i)},R=(e,t)=>{if(String(e.value??"")===t)return!0;const i=Number(t),o=Number(e.value);if(!isNaN(i)&&!isNaN(o)&&0!==o){const t=E(e);if(1!==t&&Math.abs(o*t-i)<1e-4)return!0}return!1};let M=0;if(null==S||S.forEach(e=>{var t;if(C)return;const i=null==(t=e.shadowRoot)?void 0:t.querySelectorAll("jupiter-form-field");null==i||i.forEach(e=>{if(C)return;const t=I?e.conceptId===F&&e.columnId===I:e.conceptId===F,i=!x||R(e,_);t&&(M++,console.log(`[scrollToConcept] Phase1 candidate: conceptId=${e.conceptId} columnId=${e.columnId} value=${e.value} scale=${E(e)} valueMatch=${i}`)),t&&i&&(C=e)})}),console.log(`[scrollToConcept] Phase1: scanned ${M} candidates, found=${!!C}`),!C&&x){console.log("[scrollToConcept] Phase2: searching ALL sections by base concept name + value");const e=(null==(d=this.shadowRoot)?void 0:d.querySelectorAll("jupiter-form-section"))??[];for(const t of Array.from(e)){if(C)break;const e=(null==(c=t.shadowRoot)?void 0:c.querySelectorAll("jupiter-concept-tree"))??[];for(const t of Array.from(e)){if(C)break;((null==(p=t.shadowRoot)?void 0:p.querySelectorAll("jupiter-form-field"))??[]).forEach(e=>{if(C)return;const t=T(e.conceptId),i=R(e,_);t&&console.log(`[scrollToConcept] Phase2 candidate: conceptId=${e.conceptId} value=${e.value} scale=${E(e)} valMatch=${i}`),t&&i&&(console.log(`[scrollToConcept] Phase2 ✅ MATCH: conceptId=${e.conceptId} columnId=${e.columnId} value=${e.value}`),C=e)})}}}if(!C){const e=(null==(u=this.shadowRoot)?void 0:u.querySelectorAll("jupiter-form-section"))??[];for(const t of Array.from(e)){if(C)break;const e=(null==(h=t.shadowRoot)?void 0:h.querySelectorAll("jupiter-concept-tree"))??[];for(const t of Array.from(e)){if(C)break;((null==(m=t.shadowRoot)?void 0:m.querySelectorAll("jupiter-form-field"))??[]).forEach(e=>{if(C)return;(I?T(e.conceptId)&&e.columnId===I:T(e.conceptId))&&(console.log(`[scrollToConcept] Phase3 ✅ fallback: conceptId=${e.conceptId} columnId=${e.columnId} value=${e.value}`),C=e)})}}}if(!C)return void console.warn(`[scrollToConcept] Field element not found for concept: ${e}`);console.log(`[scrollToConcept] ✅ HIGHLIGHTING conceptId=${C.conceptId} columnId=${C.columnId} value=${C.value}`);const A=C.getBoundingClientRect(),
|
|
3665
|
+
`}getData(){return{...this._formData}}setData(e){this._formData={...e},this._dirty=!0,this._validateForm(),this.requestUpdate()}validate(){return this._validateForm(),this._valid}setValidation(e){console.log(`🔍 Validation status updated: ${e}`),this._validationStatus="cancel"===e?"idle":e,this.requestUpdate()}reset(){this._handleReset()}getState(){return this._getFormState()}_findConceptByName(e,t){var i;const o=t.includes(":")?t.split(":").pop():t;for(const r of e){if(r.name===t)return r;if((r.name.includes(":")?r.name.split(":").pop():r.name)===o)return r;if(null==(i=r.children)?void 0:i.length){const e=this._findConceptByName(r.children,t);if(e)return e}}return null}_findAllConceptsByName(e,t){var i;const o=t.includes(":")?t.split(":").pop():t,r=[];for(const n of e){const e=n.name.includes(":")?n.name.split(":").pop():n.name;n.name!==t&&e!==o||r.push(n),(null==(i=n.children)?void 0:i.length)&&r.push(...this._findAllConceptsByName(n.children,t))}return r}_findConceptById(e,t){var i;for(const o of e){if(o.id===t)return o;if(null==(i=o.children)?void 0:i.length){const e=this._findConceptById(o.children,t);if(e)return e}}return null}_valueLooselyMatches(e,t){const i=String(e??"");if(i===t)return!0;const o=Number(i),r=Number(t);if(isNaN(o)||isNaN(r))return!1;if(o===r)return!0;if(0!==o&&0!==r){const e=Math.abs(r/o),t=Math.log10(e);if(Math.abs(t-Math.round(t))<1e-4)return!0}return!1}_findColumnByDimensions(e,t){var i;return null==(i=e.find(e=>{if("dimension"!==e.type||!e.dimensionData)return!1;const i=e.dimensionData.combinations;return(null==i?void 0:i.length)?t.every(e=>i.some(t=>this._normalizeAxisId(t.axisId)===this._normalizeAxisId(e.axis)&&this._normalizeMemberId(t.memberId)===this._normalizeMemberId(e.member))):1===t.length&&this._normalizeAxisId(e.dimensionData.axisId??"")===this._normalizeAxisId(t[0].axis)&&this._normalizeMemberId(e.dimensionData.memberId??"")===this._normalizeMemberId(t[0].member)}))?void 0:i.id}async scrollToConcept(e,t,i,o,r){var n,a,s,l,d,c,p,u,h,m,f,g;console.log(`[scrollToConcept] ▶ START conceptName=${e} value=${null==i?void 0:i.value} dims=${JSON.stringify(t)} columnId=${o} exactConceptId=${r}`);let b=null,v=null;const y=[...(null==(n=this._currentSchema)?void 0:n.sections)??[],...this._allSections.filter(e=>{var t;return!(null==(t=this._currentSchema)?void 0:t.sections.find(t=>t.id===e.id))})];console.log(`[scrollToConcept] Searching ${y.length} sections`);const x=void 0!==(null==i?void 0:i.value)&&null!==(null==i?void 0:i.value),_=x?String(i.value):null;if(r)for(const U of y){const e=this._findConceptById(U.concepts,r);if(e){console.log(`[scrollToConcept] Section "${U.id}" matched exactConceptId="${r}"`),b=U,v=e;break}}if(!b||!v)for(const U of y){const i=this._findAllConceptsByName(U.concepts,e);if(!i.length)continue;const r=U.columns??this._columns,n=o??((null==t?void 0:t.length)?this._findColumnByDimensions(r,t):void 0);let a;i.length>1&&(a=i.find(e=>{const t=this._formData[e.id];if(!t)return!1;if(n){const e=t[n];return null!=e&&""!==e&&(!x||this._valueLooselyMatches(e,_))}return!!x&&Object.values(t).some(e=>null!=e&&""!==e&&this._valueLooselyMatches(e,_))}),console.log(`[scrollToConcept] Section "${U.id}" has ${i.length} rows named "${e}" | disambiguated=${(null==a?void 0:a.id)??"none (using first)"}`));const s=a??i[0];if(o){const e=r.some(e=>e.id===o);if(console.log(`[scrollToConcept] Section "${U.id}" has concept "${s.id}" | columnId="${o}" present=${e}`),e){b=U,v=s;break}b||(b=U,v=s)}else{if(!(null==t?void 0:t.length)){console.log(`[scrollToConcept] Section "${U.id}" has concept "${s.id}" (no dims, taking first)`),b=U,v=s;break}if(console.log(`[scrollToConcept] Section "${U.id}" has concept "${s.id}" | colMatch=${n??"null"} | cols=${r.map(e=>e.id).join(",")}`),n){b=U,v=s;break}b||(b=U,v=s)}}if(!b||!v)return void console.warn(`[scrollToConcept] Concept not found: ${e}`);console.log(`[scrollToConcept] → targetSection="${b.id}" targetConceptId="${v.id}"`),b.expanded=!0,"sidePanel"===this.display&&this._activeSidePanelRoleId!==b.id&&(this._activeSidePanelRoleId=b.id);const D=b.columns??this._columns;let I=null;o?I=o:(null==t?void 0:t.length)?I=this._findColumnByDimensions(D,t)??null:x||(I=(null==(a=D[0])?void 0:a.id)??null),console.log(`[scrollToConcept] targetColumnId=${I} hasValueMatch=${x} targetValue=${_}`),this._conceptSearchText=e.includes(":")?e.split(":").pop():e,this.requestUpdate(),await this.updateComplete,await new Promise(e=>setTimeout(e,300));const $=null==(s=this.shadowRoot)?void 0:s.querySelectorAll("jupiter-form-section");console.log(`[scrollToConcept] DOM: found ${(null==$?void 0:$.length)??0} jupiter-form-section elements`);let w=null;if(null==$||$.forEach(e=>{var t;(null==(t=e.section)?void 0:t.id)===b.id&&(w=e)}),!w)return void console.warn(`[scrollToConcept] Section element not found: ${b.id}`);await w.updateComplete;const S=null==(l=w.shadowRoot)?void 0:l.querySelectorAll("jupiter-concept-tree");console.log(`[scrollToConcept] conceptTrees in targetSection: ${(null==S?void 0:S.length)??0}`);let C=null;const F=v.id,k=F.includes("__")?F.split("__")[0]:F;console.log(`[scrollToConcept] conceptId="${F}" conceptIdBase="${k}"`);const T=e=>e===F||e.includes("__")&&e.split("__")[0]===k,E=e=>{const t=e.decimals||(void 0!==e.globalDecimals&&"INF"!==e.globalDecimals?e.globalDecimals:null);if(!t)return 1;const i=parseFloat(String(t));return isNaN(i)||i<=0?1:Math.pow(10,i)},R=(e,t)=>{if(String(e.value??"")===t)return!0;const i=Number(t),o=Number(e.value);if(!isNaN(i)&&!isNaN(o)&&0!==o){const t=E(e);if(1!==t&&Math.abs(o*t-i)<1e-4)return!0}return!1};let M=0;if(null==S||S.forEach(e=>{var t;if(C)return;const i=null==(t=e.shadowRoot)?void 0:t.querySelectorAll("jupiter-form-field");null==i||i.forEach(e=>{if(C)return;const t=I?e.conceptId===F&&e.columnId===I:e.conceptId===F,i=!x||R(e,_);t&&(M++,console.log(`[scrollToConcept] Phase1 candidate: conceptId=${e.conceptId} columnId=${e.columnId} value=${e.value} scale=${E(e)} valueMatch=${i}`)),t&&i&&(C=e)})}),console.log(`[scrollToConcept] Phase1: scanned ${M} candidates, found=${!!C}`),!C&&x){console.log("[scrollToConcept] Phase2: searching ALL sections by base concept name + value");const e=(null==(d=this.shadowRoot)?void 0:d.querySelectorAll("jupiter-form-section"))??[];for(const t of Array.from(e)){if(C)break;const e=(null==(c=t.shadowRoot)?void 0:c.querySelectorAll("jupiter-concept-tree"))??[];for(const t of Array.from(e)){if(C)break;((null==(p=t.shadowRoot)?void 0:p.querySelectorAll("jupiter-form-field"))??[]).forEach(e=>{if(C)return;const t=T(e.conceptId),i=R(e,_);t&&console.log(`[scrollToConcept] Phase2 candidate: conceptId=${e.conceptId} value=${e.value} scale=${E(e)} valMatch=${i}`),t&&i&&(console.log(`[scrollToConcept] Phase2 ✅ MATCH: conceptId=${e.conceptId} columnId=${e.columnId} value=${e.value}`),C=e)})}}}if(!C){const e=(null==(u=this.shadowRoot)?void 0:u.querySelectorAll("jupiter-form-section"))??[];for(const t of Array.from(e)){if(C)break;const e=(null==(h=t.shadowRoot)?void 0:h.querySelectorAll("jupiter-concept-tree"))??[];for(const t of Array.from(e)){if(C)break;((null==(m=t.shadowRoot)?void 0:m.querySelectorAll("jupiter-form-field"))??[]).forEach(e=>{if(C)return;(I?T(e.conceptId)&&e.columnId===I:T(e.conceptId))&&(console.log(`[scrollToConcept] Phase3 ✅ fallback: conceptId=${e.conceptId} columnId=${e.columnId} value=${e.value}`),C=e)})}}}if(!C)return void console.warn(`[scrollToConcept] Field element not found for concept: ${e}`);console.log(`[scrollToConcept] ✅ HIGHLIGHTING conceptId=${C.conceptId} columnId=${C.columnId} value=${C.value}`);const A=C.getBoundingClientRect(),P=this.shadowRoot,j=P?P.querySelector(".side-panel-content")??P.querySelector(".form-container"):null,L=j&&j.scrollHeight>j.clientHeight?j:null;if(L){const e=L.getBoundingClientRect(),t=Math.max(0,A.top-e.top+L.scrollTop-L.clientHeight/2+A.height/2);L.scrollTo({top:t,behavior:"smooth"})}else C.scrollIntoView({behavior:"smooth",block:"center"});const N=null==(f=null==w?void 0:w.shadowRoot)?void 0:f.querySelector(".table-container");if(N&&N.scrollWidth>N.clientWidth){const e=N.getBoundingClientRect(),t=Math.max(0,A.left-e.left+N.scrollLeft-N.clientWidth/2+A.width/2);N.scrollTo({left:t,behavior:"smooth"})}const O=C.getRootNode(),V=(O instanceof ShadowRoot?O.host:null)??C;V.classList.add("concept-highlight");const z=null==(g=C.shadowRoot)?void 0:g.querySelector('input:not([type="hidden"]), select, textarea, button, [tabindex]:not([tabindex="-1"])');z&&setTimeout(()=>z.focus({preventScroll:!0}),450),setTimeout(()=>V.classList.remove("concept-highlight"),1e4)}render(){var t;const i=this._errors.filter(e=>"error"===e.severity).length,o="readonly"===this.mode?0:this._errors.filter(e=>"warning"===e.severity).length,r=this.config||{},n=!1!==r.showValidationSummary&&(i>0&&this._submitted||o>0),a=this._currentSchema;return a?e.html`
|
|
3666
3666
|
<div class="form-container">
|
|
3667
3667
|
<!-- Form Header - Hidden in side panel mode -->
|
|
3668
3668
|
${"sidePanel"!==this.display?e.html`
|