@outbuild-company/schedule-core 1.1.0 → 1.1.2

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.
@@ -1,2 +1,2 @@
1
- "use strict";var ScheduleCore=(()=>{var zr=Object.defineProperty;var jl=Object.getOwnPropertyDescriptor;var Vl=Object.getOwnPropertyNames;var Yl=Object.prototype.hasOwnProperty;var $l=(e,t)=>{for(var r in t)zr(e,r,{get:t[r],enumerable:!0})},Gl=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Vl(t))!Yl.call(e,n)&&n!==r&&zr(e,n,{get:()=>t[n],enumerable:!(i=jl(t,n))||i.enumerable});return e};var Kl=e=>Gl(zr({},"__esModule",{value:!0}),e);var Gh={};$l(Gh,{ACTIVITY_TYPE:()=>We,CALENDAR_UNIT:()=>et,COLUMN:()=>E,CONSTRAINT_TYPE:()=>$,CONSTRAINT_TYPE_TO_LABEL:()=>Wl,CREATION_KIND:()=>Hl,DEFAULT_HOURS_PER_DAY:()=>Ul,DISPATCH_ACTION_KIND:()=>X,DISPATCH_ACTION_KINDS:()=>Bl,DISPATCH_TRACK_EVENT:()=>yt,LINK_CODE_TO_TYPE:()=>Ht,LINK_TYPE:()=>V,LINK_TYPE_CODE:()=>Na,NEW_ACTIVITY_DEFAULTS:()=>Cr,REJECTION_REASON:()=>R,ROOT_PARENT_ID:()=>H,ScheduleCore:()=>Kr,WORK_TIME_DIRECTION:()=>q,applyBaselinePoints:()=>Er,checkNoUpdatedLinks:()=>Fl,computeExpectedProgress:()=>mi,expectedProgressFromBaseline:()=>ce,getActiveBaseline:()=>pt,getUnsavedActivities:()=>Ml,isRootParent:()=>O,normalizeParentKey:()=>Bt,parseFromBackend:()=>Nr,recomputeAllPonderators:()=>Tr,recomputeAllProgressRollup:()=>_r,willRunCriticalPath:()=>xc,yieldToBrowser:()=>rt});var ut=class{items=[];head=0;enqueue(t){this.items.push(t)}dequeue(){if(this.head>=this.items.length)return;let t=this.items[this.head];return this.head+=1,t}peek(){if(!(this.head>=this.items.length))return this.items[this.head]}get size(){return this.items.length-this.head}isEmpty(){return this.head>=this.items.length}};var xe=e=>String(e);function An(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:a,exists:s,autoCheckParents:o}=e,c=xe(t),l=new Set([...i].map(String)),d=new Set(l),u=zl(c,n).filter(s),f=u.filter(v=>!a(v)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let v of f)r?d.add(v):d.delete(v);return p||ql({id:c,isChecked:r,autoCheckParents:o,hierarchy:n,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:Jl(l,d),parentBlocked:p}}function zl(e,t){let r=[],i=new ut;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let a=i.dequeue();for(let s of t.getChildrenIds(a)){let o=xe(s);n.has(o)||(n.add(o),r.push(o),i.enqueue(o))}}return r}function ql(e){let{id:t,isChecked:r,autoCheckParents:i,hierarchy:n,isFrozen:a,exists:s,next:o}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=xe(c);if(a(l))return;let d=n.getChildrenIds(l).map(xe).filter(s),u=d.some(a),f=d.filter(S=>!a(S)),v=f.length>0&&f.every(S=>o.has(S))&&!u;if(r){if(!i||!v||o.has(l))return;o.add(l)}else{if(v||!o.has(l))return;o.delete(l)}c=n.getParentId(l)}}function Jl(e,t){let r=[],i=[];for(let n of t)e.has(n)||r.push(n);for(let n of e)t.has(n)||i.push(n);return{checked:r,unchecked:i}}function Jt(e){return(e.pendingRequestIds?.length??0)>0}var R={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var Cn=(e,t)=>{let r=e.getActivity(t);return r!=null&&Jt(r)},In=(e,t,r)=>{let i=[],n=(a,s)=>{let o=t.isChecked(a);t.setChecked(a,s)&&i.push({activityId:a,checked:{before:o,after:s}})};for(let a of r.checked)n(a,!0);for(let a of r.unchecked)n(a,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}};function kn(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,a=n?o=>n.has(o):o=>Cn(r,o),s=An({clickedId:i,isChecked:e.isChecked,currentSelection:new Set(r.checkedIds().map(String)),hierarchy:{getChildrenIds:o=>r.getChildren(o),getParentId:o=>{let c=r.getParentId(o);return!c||c==="0"?null:String(c)}},isFrozen:a,exists:o=>r.activityExists(o),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:In(e,r,s.changed)}}function Sn(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!Cn(r,s))),n=new Set(r.checkedIds().map(String)),a={checked:[...i].filter(s=>!n.has(s)),unchecked:[...n].filter(s=>!i.has(s))};return{ok:!0,changes:In(e,r,a)}}function Dn(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=[];return r.forEachActivity((s,o)=>{let c=String(o),l=i.has(c),d=r.isVisible(c);d!==l&&(r.setVisible(c,l),n.push({activityId:c,visible:{before:d,after:l}}))}),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var Tn="text";var _n="description";var Pn="duration";var En="progress";var Rn="cost";var Ln="used_cost";var bn="hhWorkTime";var wn="start_date";var On="end_date";var xn="constraint_type";var Nn="constraint_date";var Fn="calendar_id";var Mn="custom_id";var Wn="subcontractId";var Un="responsables";var Bn="tags";var Hn="custom_predecessors";var jn="custom_sucessors";var Vn="real_work";var Yn="real_cost";var $n="expected_progress";var Gn="expected_progress_base";var Kn="start_base";var zn="end_base";var qn="duration_base";var Jn="cost_base";var Xn="work_base";var Zn="calendarDuration";var Qn="is_critical",ta="earlyStart",ea="earlyFinish",ra="lateStart",ia="lateFinish",na="freeSlack",aa="totalSlack";var sa="correlative_id";var oa="unique_correlative_id";var ca="ponderator";var q={FUTURE:"future",PAST:"past"},et={HOUR:"hour",DAY:"day"},Pt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var Ne="status";var qr="Baseline";function Fe(e){return e==="Actual"?"Actual":qr}var Xl={TEXT:Tn,DESCRIPTION:_n,DURATION:Pn,PROGRESS:En,COST:Rn,USED_COST:Ln,HH_WORK_TIME:bn,START_DATE:wn,END_DATE:On,CONSTRAINT_TYPE:xn,CONSTRAINT_DATE:Nn,CALENDAR_ID:Fn,CUSTOM_ID:Mn,SUBCONTRACT_ID:Wn,RESPONSABLES:Un,TAGS:Bn,CUSTOM_PREDECESSORS:Hn,CUSTOM_SUCESSORS:jn},Zl={REAL_WORK:Vn,REAL_COST:Yn,EXPECTED_PROGRESS:$n,EXPECTED_PROGRESS_BASE:Gn,START_BASE:Kn,END_BASE:zn,DURATION_BASE:qn,COST_BASE:Jn,WORK_BASE:Xn,CALENDAR_DURATION:Zn,IS_CRITICAL:Qn,EARLY_START:ta,EARLY_FINISH:ea,LATE_START:ra,LATE_FINISH:ia,FREE_SLACK:na,TOTAL_SLACK:aa,CORRELATIVE_ID:sa,UNIQUE_CORRELATIVE_ID:oa,PONDERATOR:ca,STATUS:Ne},E={...Xl,...Zl};function la(e,t){throw new Error(t)}function da(e,t){return()=>t()===e}var $={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Ql={mso:()=>!0,mfo:()=>!0,snlt:(e,t)=>e<t,snet:(e,t)=>e>t,fnlt:(e,t)=>e<t,fnet:(e,t)=>e>t};function fa(e,t,r){if(!t)return{violated:!1};let i=Ql[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var td=new Set(["mso","snet","snlt"]);function he(e,t,r){return td.has(e)?t:r}function pa(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var ed={snet:{startOfDay:!0,direction:q.FUTURE},snlt:{startOfDay:!0,direction:q.PAST},fnet:{startOfDay:!1,direction:q.FUTURE},fnlt:{startOfDay:!1,direction:q.PAST},mso:{startOfDay:!0,direction:q.FUTURE},mfo:{startOfDay:!1,direction:q.PAST}},Me=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),ua=(e,t)=>new Date(e.getTime()+t*864e5),rd=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Jr(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=ed[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Me(i),dir:q.FUTURE,task:e});if(rd(n,i))return i.getTime()!==Me(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:ua(Me(i),1),dir:q.PAST,task:e});let a=Me(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:q.FUTURE,task:e}):t.getClosestWorkTime({date:ua(a,1),dir:q.PAST,task:e})}function ha(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i==="asap"||i==="alap")return r;let n=Jr(e,t);if(!n)return r;let a=o=>t.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e}),s=o=>t.calculateEndDate({startDate:o,durationHours:-e.durationHours,task:e});switch(i){case"snet":return{earliestStart:n,latestStart:null,earliestEnd:a(n),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:a(n)};case"fnet":return{earliestStart:s(n),latestStart:null,earliestEnd:n,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:s(n),earliestEnd:null,latestEnd:n};case"mso":{let o=a(n);return{earliestStart:n,latestStart:n,earliestEnd:o,latestEnd:o}}case"mfo":{let o=s(n);return{earliestStart:o,latestStart:o,earliestEnd:n,latestEnd:n}}default:return r}}function ya(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Xr(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var V={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var We={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},ma={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Ue=typeof window>"u",Zr=!Ue&&typeof MessageChannel<"u"?new MessageChannel:null;function rt(){return Ue||!Zr?Promise.resolve():new Promise(e=>{Zr.port1.onmessage=()=>e(),Zr.port2.postMessage(null)})}async function Be(e,t){return performance.now()-e<ma.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await rt(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function Xt(e){return Ue||await rt(),e()?{aborted:!1}:{aborted:!0}}function He(e,t){let{inDegree:r,successors:i}=id(e,t),n=nd(r),a=ad(n,r,i),s=a.length<e.length,o=s?sd(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function id(e,t){let r=new Map,i=new Map;for(let n of e)r.set(n,0),i.set(n,[]);for(let n of t){let a=n.source,s=n.target;!r.has(a)||!r.has(s)||(i.get(a).push(s),r.set(s,(r.get(s)??0)+1))}return{inDegree:r,successors:i}}function nd(e){let t=new ut;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function ad(e,t,r){let i=[];for(;!e.isEmpty();){let n=e.dequeue();i.push(n);for(let a of r.get(n)??[]){let s=(t.get(a)??1)-1;t.set(a,s),s===0&&e.enqueue(a)}}return i}function sd(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var je=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=He(t,r),this.cached)}};function ga(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var Qr={project:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:"recursive-leaf-sum",promotesToProjectOnFirstChild:!1},task:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:"own-baseline",promotesToProjectOnFirstChild:!0},milestone:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:"zero",promotesToProjectOnFirstChild:!0}};function ti(e){return e==="project"||e==="task"||e==="milestone"}function Ct(e,t){return t||ti(e)&&Qr[e].alwaysSummary}function ye(e){return e==="milestone"}function Et(e){return ti(e)&&Qr[e].promotesToProjectOnFirstChild}var ei="project",Zt="task";function me(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function va(e,t){let r=t.getActivity(e);return r?Ct(r.type,t.getChildren(e).length>0):!1}function Aa(e,t,r){let i=String(t),n=r.getActivity(e);for(;n?.parentId&&String(n.parentId)!=="0";){if(String(n.parentId)===i)return!0;n=r.getActivity(n.parentId)}return!1}function Ca(e,t){let r=[],i=[e];for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);if(a.length===0){String(n)!==String(e)&&r.push(n);continue}for(let s of a)i.push(s)}return r}function od(e){let t=new Map;for(let r of e)Ia(t,String(r.source),r),Ia(t,String(r.target),r);return t}function Ia(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function cd(e,t,r){if(e.length<=1)return e;let i=new Set(e.map(String)),n=[];for(let a of e)ld(a,i,t,r)||n.push(a);return n.length>0?n:e}function ld(e,t,r,i){let n=String(e),a=r.getActivity(e);if(!a||a.autoScheduling===!1)return!1;let s=i.get(n)??[];for(let o of s){if(dd(o))continue;let c=ud(o,n);if(!t.has(String(c)))continue;let l=r.getActivity(c);if(l&&l.autoScheduling!==!1&&fd(o,e,a,c,l))return!0}return!1}function dd(e){return e.source===e.target}function ud(e,t){return String(e.source)===t?e.target:e.source}function fd(e,t,r,i,n){let a=e.lag??0,s=Math.abs(a);return e.target===t&&s<=r.durationHours||e.target===i&&s<=n.durationHours}function Sa(e,t){let r=[],i=od(e),n=0;for(let a of e){let s=va(a.source,t),o=va(a.target,t);if(s&&o||o&&Aa(a.source,a.target,t)||s&&Aa(a.target,a.source,t))continue;if(!s&&!o){r.push(a);continue}let c=s?Ca(a.source,t):[a.source],l=o?Ca(a.target,t):[a.target];if(s&&(c=ka(c,!1,t)),o){let d=cd(l,t,i);if(a.type===V.FINISH_TO_FINISH||a.type===V.START_TO_FINISH){n=pd(r,c,d,a,a.target,t,n);continue}l=ka(d,!0,t)}n=hd(r,c,l,a,n)}return r}function pd(e,t,r,i,n,a,s){let o=a.getActivity(n),c=o?.startDate,l=o?.durationHours??0,d=i.lag??0,u=a.getActivity(i.source),f=s;for(let p of t)for(let v of r){if(String(p)===String(v))continue;let S=a.getActivity(v),A=c&&S&&u?a.calculateDuration({startDate:c,endDate:S.startDate,task:u}):0;e.push({id:`virtual_${i.id}_${f}`,source:p,target:v,type:i.type,lag:i.lag,_sourceLag:0,_targetLag:-l,_trueLag:d+A}),f+=1}return f}function ka(e,t,r){if(e.length<=1)return e;let i=null;for(let a of e){let s=r.getActivity(a),o=t?s?.startDate:s?.endDate;if(!o)continue;let c=o.getTime();(i===null||(t?c<i:c>i))&&(i=c)}if(i===null)return e;let n=e.filter(a=>{let s=r.getActivity(a),o=t?s?.startDate:s?.endDate;return o!=null&&o.getTime()===i});return n.length>0?n:e}function hd(e,t,r,i,n){let a=n;for(let s of t)for(let o of r)String(s)!==String(o)&&(e.push({id:`virtual_${i.id}_${a}`,source:s,target:o,type:i.type,lag:i.lag}),a+=1);return a}var Ve=class{invalidate(){}get(t,r){return Sa(t,r)}};function yd(e){let t=new Map,r=i=>(t.has(i)||t.set(i,new Set),t.get(i));for(let i of e)r(i.source).add(i.id),r(i.target).add(i.id);return{neighbors:t}}function md(e,t,r){let i=new Set,n=new Map,a=new ut;for(a.enqueue(e);!a.isEmpty();){let s=a.dequeue(),o=String(s);if(i.has(o))continue;i.add(o);let c=r.neighbors.get(s);if(c)for(let l of c){let d=t.get(l);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;n.has(u)||n.set(u,d);let f=String(d.source)===o?d.target:d.source;i.has(String(f))||a.enqueue(f)}}return Array.from(n.values())}function Da(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let i=yd(t),n=md(e,r,i),a=new Set([String(e)]);for(let s of n)a.add(String(s.source)),a.add(String(s.target));return{activityIds:a,links:n}}function Ta(e,t,r){let i=r.type===V.FINISH_TO_START,n=r.type===V.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:i,isFF:n,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case V.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case V.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case V.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case V.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1}}}function _a(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s,isFS:o,isFF:c}=Ta(e,t,r);if(!(n!==0||a!==0||s!==0)){let f=o||c;return t.durationHours===0&&f?{successorStart:i.getClosestWorkTime({date:e.endDate,dir:"past",task:t}),link:r}:{successorStart:i.getClosestWorkTime({date:e.endDate,dir:"future",task:t}),link:r}}let d=o?t:e,u=i.getClosestWorkTime({date:e.endDate,dir:"future",task:d});if(n!==0&&(u=i.calculateEndDate({startDate:u,durationHours:n,task:e})),a!==0&&(u=i.calculateEndDate({startDate:u,durationHours:a,task:t})),s!==0&&(u=i.calculateEndDate({startDate:u,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:i.getClosestWorkTime({date:u,dir:"past",task:t}),link:r};let f=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:f,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:u,dir:"future",task:t}),link:r}}function Pa(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s}=Ta(t,e,r),o=i.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return s!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-s,task:e})),a!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-a,task:e})),n!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-n,task:t})),o}function Ea(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===$.ASAP||a===$.ALAP)continue;let s=ha(n,t);!s.earliestStart&&!s.latestStart&&!s.earliestEnd&&!s.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:s.earliestStart,latestStart:s.latestStart,earliestEnd:s.earliestEnd,latestEnd:s.latestEnd})}}function Ye(e,t,r){let i={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},n=t.earliestSchedulingStart??t.latestSchedulingStart??null,a;n===null?a=Xr(e.startDate,i):ya(n,i)?a=n:a=Xr(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function Ra(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case $.MSO:case $.MFO:return new Date(i);case $.SNET:case $.FNET:return i>t?new Date(i):t;case $.SNLT:case $.FNLT:return i<t?new Date(i):t;default:return t}}function gd(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function La(e,t,r){return ri(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function ri(e,t,r){return t.dragWithMultiple&&gd(e,r)}async function wa(e,t,r,i,n,a){let s=new Map;for(let u of t){let f=String(u.target);s.has(f)||s.set(f,[]),s.get(f).push(u)}let o=u=>{let f=a.get(u);if(f?.startDate&&f.endDate)return{startDate:f.startDate,endDate:f.endDate};let p=r.getActivity(u);return p?{startDate:p.startDate,endDate:p.endDate}:{startDate:new Date,endDate:new Date}},c=r.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let f=await Be(d,n);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||vd(p,r))continue;let v=s.get(String(u))??[],S=null,A=null;for(let k of v){let y=r.getActivity(k.source);if(!y)continue;let g=o(k.source),C={...y,startDate:g.startDate,endDate:g.endDate},P=La(C,c,l),_={...C,startDate:P.startDate,endDate:P.endDate},b=ri(k.source,c,l)?{...k,lag:0}:k,x=_a(_,p,b,r);(!S||x.successorStart>S)&&(S=x.successorStart,A=String(k.id))}let D=a.get(u),m=D?{...D}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},T=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!S&&!T)){if(S){let k=S;p.type===We.MILESTONE&&(k=Ra(p,S)),m.drivingLinkId=A,m.startDate=k,m.endDate=r.calculateEndDate({startDate:k,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=k,m.earliestSchedulingEnd=m.endDate}else p.constraintType===$.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===$.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));Ye(p,m,r),a.set(u,m)}}return a}function vd(e,t){return Ct(e.type,t.getChildren(e.id).length>0)}var H="0";function O(e){return e==null||e===0||e==="0"}function Bt(e){return O(e)?"0":String(e)}async function Oa(e,t,r,i,n,a){let s=new Map(r),o=i.getAllActivities(),c=o.length,l=[];for(let A of o)A.constraintType===$.ALAP&&l.push(A.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let A of t){let D=String(A.source);d.has(D)||d.set(D,[]),d.get(D).push(A);let m=String(A.target);u.has(m)||u.set(m,[]),u.get(m).push(A)}let f=A=>{let D=s.get(A);if(D)return{startDate:D.startDate,endDate:D.endDate};let m=i.getActivity(A);return m?{startDate:m.startDate,endDate:m.endDate}:{startDate:new Date,endDate:new Date}},p=A=>!A.parentId||O(A.parentId)?i.getProjectEnd():f(A.parentId).endDate,v=(A,D)=>{let m=A,T=0;for(;m&&!O(m)&&T++<c+1;){if(String(m)===String(D))return!0;let k=i.getActivity(m);if(!k||!k.parentId)break;m=k.parentId}return!1},S=performance.now();for(let A of e){let D=await Be(S,a);if(D.aborted)return s;S=D.newSliceStart;let m=i.getActivity(A);if(!m||m.constraintType!==$.ALAP||!m.autoScheduling||m.progress===100||Ct(m.type,i.getChildren(A).length>0))continue;let T=p(m);if(!T)continue;let k=T,y=null,g=!1,C=d.get(String(A))??[];for(let M of C){if((M.lag??0)<0)continue;let z=i.getActivity(M.target);if(!z||z.autoScheduling===!1)continue;let ot=f(M.target),Oe={...z,startDate:ot.startDate,endDate:ot.endDate},Ut=Pa(Oe,m,M,i);Ut<k&&(k=Ut),(y===null||Ut<y)&&(y=Ut,g=m.parentId&&!O(m.parentId)?v(M.target,m.parentId):!1)}if(y!==null)if(g)k=y;else{let M=f(A).endDate,z=M.getTime()>T.getTime()?M:T;k=y<z?y:z}else k>T&&(k=T);let P;if(m.durationHours===0&&y===null)P=i.getClosestWorkTime({date:k,dir:"past",task:m});else if(m.durationHours===0)if((u.get(String(A))??[]).some(ot=>ot.type===V.FINISH_TO_START||ot.type===V.FINISH_TO_FINISH)){let ot=new Date(Date.UTC(k.getUTCFullYear(),k.getUTCMonth(),k.getUTCDate()));P=i.getClosestWorkTime({date:ot,dir:"past",task:m})}else P=i.getClosestWorkTime({date:k,dir:"future",task:m});else P=i.getClosestWorkTime({date:k,dir:"future",task:m});let _=i.calculateEndDate({startDate:P,durationHours:-m.durationHours,task:m}),b=s.get(A),x=b?{...b}:{activityId:A,startDate:_,endDate:P,drivingLinkId:null,kind:"alap",conflict:!1};x.startDate=_,x.endDate=P,x.drivingLinkId=null,x.kind="alap",x.earliestSchedulingStart=null,x.earliestSchedulingEnd=null,x.latestSchedulingStart=_,x.latestSchedulingEnd=P,Ye(m,x,i),s.set(A,x)}return s}var Qt={warn(){},error(){}};function ge(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let i=t.plans.get(r);if(!i)continue;let n=e.getLiveActivity(r);n&&(n.startDate=i.startDate,n.endDate=i.endDate,e.updateActivity(r))}})}function xa(e,t){let r=String(t.source),i=String(t.target);if(r===i)return!0;let n=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=n.get(s)??[];c.push(o),n.set(s,c)}return Ad(n,i,r)}function Ad(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new ut;for(n.enqueue(t);!n.isEmpty();){let a=n.dequeue(),s=e.get(a)??[];for(let o of s){if(o===r)return!0;i.has(o)||(i.add(o),n.enqueue(o))}}return!1}function Rt(e,t){switch(e.kind){case"create":return Cd(e,t);case"update":return Id(e,t);case"delete":return kd(e,t)}}function Cd(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:"activity-missing"};let a=r.getAllLinks();for(let l of a)if(String(l.source)===String(e.source)&&String(l.target)===String(e.target)&&l.type===e.type)return{applied:!1,rejected:"duplicate",linkId:l.id};let s=a.map(l=>({source:l.source,target:l.target}));if(xa(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Sd)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function Id(e,t){let{port:r}=t;return r.getLink(e.linkId)?(e.lag!==void 0&&r.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&r.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}function kd(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}var $e=null;function Sd(){return $e===null&&($e=Date.now()),$e+=1,String($e)}var Na={[V.FINISH_TO_START]:"fs",[V.START_TO_START]:"ss",[V.FINISH_TO_FINISH]:"ff",[V.START_TO_FINISH]:"sf"},Ht={fs:V.FINISH_TO_START,ss:V.START_TO_START,ff:V.FINISH_TO_FINISH,sf:V.START_TO_FINISH},Fa="fs";function Ma(e){if(e in Ht)return Ht[e]}var Wa=";",Ua=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Ge(e){let t=[],r=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:r};for(let n of i.split(Wa)){if(n.length===0)continue;let a=Dd(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function Dd(e){let t=e.toLowerCase(),r=Ua.exec(t);if(!r)return null;let[,i,n,a,s]=r,o=n?Ht[n]:Ht[Fa],c=0;if(s!==void 0){let l=Number(s);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:i,type:o,lag:c}}function ze(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Ke(l,c.type);a.has(d)||a.set(d,{source:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.target)===String(t)&&s.set(Ke(c.source,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:l.source,target:t,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function Ke(e,t){return`${String(e)}::${t}`}function qe(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Ke(l,c.type);a.has(d)||a.set(d,{target:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.source)===String(t)&&s.set(Ke(c.target,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:t,target:l.target,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function ft(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var Ba={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:q.FUTURE,date:e,unit:et.HOUR}):t.isWorkTime(e,et.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function ii(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var ni=Ba;var Je=class{adapter;reporter;currentCalculationId=0;topoCache=new je;expandedLinksCache=new Ve;constructor(t,r=Qt){this.adapter=t,this.reporter=r}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let r=++this.currentCalculationId,i=da(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Ed(this.adapter);let a=Lt("schedule.total"),s=Lt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);It(s);let l=c;if((await Xt(i)).aborted)return{...n,cancelled:!0};let d=Lt("schedule.scoping"),u=this.adapter.getAllIds(),f=l,p=u,v=null;if(t.triggerId!==void 0&&t.triggerId!==null){let _=Da(t.triggerId,l);f=_.links,p=Array.from(_.activityIds),v=new Set(p)}It(d);let S=Lt("schedule.topologicalSort"),A=Rd(this.topoCache,u,l,v);if(It(S),A.hasCycles)return It(a),{...n,cycles:[A.cycleNodes]};if((await Xt(i)).aborted)return{...n,cancelled:!0};let D=Lt("schedule.processConstraints"),m=new Map;if(Ea(A.ordered,this.adapter,m),It(D),(await Xt(i)).aborted)return{...n,cancelled:!0};let T=Lt("schedule.asapPass"),k=await wa(A.ordered,f,this.adapter,t,i,m);if(It(T),(await Xt(i)).aborted)return{...n,cancelled:!0};let y=Lt("schedule.alapPass"),g=await Oa(A.reversed,f,k,this.adapter,t,i);if(It(y),(await Xt(i)).aborted)return{...n,cancelled:!0};let C=Lt("schedule.diff"),P=[];for(let[_,b]of g){let x=this.adapter.getActivity(_);if(!x)continue;let M=x.startDate.getTime()!==b.startDate.getTime(),z=x.endDate.getTime()!==b.endDate.getTime();(M||z)&&P.push(_)}return It(C),It(a),{plans:g,updatedIds:P,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},_d=!1;function Pd(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:_d}function Lt(e){return{name:e,startedAt:performance.now()}}function Ed(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function It(e){if(!Pd())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Rd(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let s=i?Array.from(i):t;return He(s,r)}if(!i)return n;let a=ga(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function Ha(e,t){let r=t.getActivity(e);if(!r)return;let i=t.calendarReader.getCalendar(String(r.calendarId));for(let n of t.getIncomingLinkIds(e)){let a=t.getLink(n);if(!a)continue;let s=t.getActivity(a.source);if(!s||s.constraintType==="alap")continue;let{sourceDate:o,targetDate:c}=ii(s,r,a.type),l=ni.computeLagBetweenTasks(o,c,i);l!==a.lag&&Rt({kind:"update",linkId:a.id,lag:l},{port:t})}}function ja(e,t){let r=t.getActivity(e);r&&ye(r.type)&&(r.durationHours=0)}function te(e){let t=0,r=!1;for(let i of e)i.ponderator>0&&(t+=i.ponderator/100*i.progress,r=!0);return r?t:null}function Xe(e){return Number(e.toFixed(2))}function ct(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function ve(e,t,r=!0,i={}){let n=t?Va(e,t):xd(e);await Ld(n,e,r,{recomputeRealWork:i.recomputeRealWork??!1})}function ai(e,t,r=!0){let i=Va(e,t);for(let n of i)si(n,e,r)}function Ze(e,t){si(e,t,!1)}async function Ld(e,t,r=!0,i={recomputeRealWork:!1}){let a=0;for(let s of e)si(s,t,r,i.recomputeRealWork),a+=1,a%200===0&&await rt()}function Va(e,t){let r=new Set;for(let a of t)bd(a,e,r);if(r.size===0)return[];let i=Array.from(r),n=Ya(i,e);return $a(i,n)}function bd(e,t,r){let i=t.getParentId(e);for(;i&&!O(i);){if(r.has(i))return;r.add(i),i=t.getParentId(i)}}function wd(e,t,r){let i=null,n=null,a=0,s=[];for(let o of e){let c=t.getActivity(o);if(!c)continue;let l=c.startDate.getTime(),d=c.endDate.getTime();(i===null||l<i)&&(i=l),(n===null||d>n)&&(n=d),r&&(a+=Od(c,t.getChildren(o).length>0)),s.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:n,realWorkSum:a,weightedChildren:s}}function si(e,t,r=!0,i=!1){let n=t.getActivity(e);if(!n)return;let a=t.getChildren(e);if(a.length===0)return;let s=wd(a,t,i);if(s.minStart===null||s.maxEnd===null)return;let o=String(n.calendarId??""),c=t.calendarReader.getCalendar(o),l=new Date(s.minStart),d=new Date(s.maxEnd),u=c.calculateDuration(l,d);t.setActivityField(e,"startDate",l),t.setActivityField(e,"endDate",d),t.setActivityField(e,"durationHours",u);let f=te(s.weightedChildren);r&&f!==null&&t.setActivityField(e,"progress",Xe(f)),i&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function Od(e,t){return t?Number(e.realWorkHours)||0:ct(e.workHours,e.progress)}function xd(e){let t=Nd(e),r=Ya(t,e);return $a(t,r)}function Nd(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Ya(e,t){let r=new Map;for(let i of e)r.set(i,Fd(i,t));return r}function Fd(e,t){let r=0,i=e;for(;i&&!O(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function $a(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var Ga={updateActivityDuration:ja,updateTaskTiming:Wd("updateTaskTiming"),adjustLinkLagOnTaskMove:Ha,recordLastStartDate:Md};function Md(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function bt(e,t,r){for(let i of t){let n=i in Ga?Ga[i]:void 0;if(!n){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}n(e,r)}}function Wd(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function w(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function N(e){return{ok:!1,reason:e}}function W(){return{valid:!0}}function Q(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function U(){return{allowed:!0}}function G(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function F(e,t={}){return{patch:e,needsAutoSchedule:t.autoSchedule??!1,postProcessors:t.postProcessors??[],...t.cascadeMutations!==void 0?{cascadeMutations:t.cascadeMutations}:{},...t.trackingEvents!==void 0?{trackingEvents:t.trackingEvents}:{}}}var Ka={targetField:"name",canEdit(){return U()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e)},validate(){return W()},transform(e,t){return F({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var za={targetField:"description",canEdit(){return U()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e.trim())},validate(){return W()},transform(e,t){return F({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function At(e){return e.constraintType??$.ASAP}var Qe=100;function ee(e){return e.progress>=Qe}function tt(e,t){return Ct(e.type,t.hasChildren(e.id))}function qa(e){return e.progress>0}function Ja(e){return e.hasLookaheadTasks}function Ae(e,t){return Math.round(Math.ceil(e*t*60)/60)}var re=e=>({endDate:e});function jt(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=n=>Number(r.find(a=>a.type===n)?.value);return new Date(Date.UTC(i("year"),i("month")-1,i("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function Ce(e,t){if(!t||t==="UTC"){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=f=>Number(r.find(p=>p.type===f)?.value),n=i("year"),a=i("month"),s=i("day"),o=Date.UTC(n,a-1,s,23,59,0,0),c=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(o)),l=f=>Number(c.find(p=>p.type===f)?.value),u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")===24?0:l("hour"),l("minute"),l("second"))-o;return new Date(o-u)}function Ud(e,t){let r=jt(t);for(;!e.isWorkTime(r,et.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=jt(r);return r}function oi(e,t){return e.getClosestWorkTime({direction:q.FUTURE,date:t,unit:et.HOUR})}function ci(e,t){let r=Ud(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:q.PAST,date:i,unit:et.HOUR})}var tr=new Set(["snet","snlt","mso"]),li=new Set(["fnet","fnlt","mfo"]),wt=new Set(["asap","alap"]),er="snet";function kt(e,t,r){if(!tr.has(r)&&!li.has(r))return e;let i=tr.has(r)?oi(t,e):ci(t,e),n=new Date(e);return n.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),n}var St=()=>({constraintType:er});var Ot=e=>({constraintDate:e}),Xa=e=>({constraintDate:e});var Za={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Qa={UNCHANGED:"unchanged",OUT_OF_RANGE:"out_of_range",NEGATIVE_DURATION:"negative_duration",NOT_WORKING_DAY:"not_working_day",BEFORE_PARENT_START:"before_parent_start",BEFORE_START_DATE:"before_start_date",BEFORE_DATE_ORIGIN:"before_date_origin",CONSTRAINT_VIOLATION:"constraint_violation",MISSING_ID:"missing_id"};function ie(e,t,r){return fa(e,t,r)}function ne(e,t,r){return pa(e,t,r)}var es={targetField:"durationHours",canEdit(e,t){return ee(e)?G("completed","cant_edit_completed_activity"):tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isNaN(i)?N("not_a_number"):w(r.inputUnit==="hours"?i:Ae(i,r.hoursPerDay))},validate(e,t,r){return ts(r)?Q(Qa.NEGATIVE_DURATION):Bd(t,r)?Q("unchanged"):W()},transform(e,t,r){if(ts(t))return F({},{autoSchedule:!1,postProcessors:[]});let i=Hd(e,t,r),n=jd(e,t,r,i.violated);return{...F(n,{autoSchedule:e.constraintType!=="alap",postProcessors:[Za.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:ne(i.constraintType,i.constraintDate,rs(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function ts(e){return Math.sign(e)===-1}function Bd(e,t){return e===t}function Hd(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!=="fnet"&&n!=="fnlt"&&n!=="mfo")return{violated:!1};let a=i.calculateEndDate(e.startDate,t);return ie(n,e.constraintDate,a)}function jd(e,t,r,i=!1){let n={};i&&Object.assign(n,St(),Ot(e.startDate));let a=me(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let s=rs(e,t,r);return s&&Object.assign(n,re(s)),n}function rs(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var ae=e=>({realWorkHours:e});var Vd=0,Yd=Qe,is=0,ns={targetField:"progress",canEdit(e,t){return Ja(e)?G("has_lookahead_tasks","cant_edit_actvity_with_task"):tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(e,t,r){return $d(r)?Q("out_of_range"):W()},transform(e,t,r){let i=Gd(t),n=Kd(t),a=Jd(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...ae(a.get(e.id)??0)},o=n?zd(e,t,i,r.hierarchy,a):[],c=n?Xd(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=n?Qd(e,t):void 0;return F(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function $d(e){return e<Vd||e>Yd}function Gd(e){return e===is}function Kd(e){return e===Qe||e===is}function zd(e,t,r,i,n){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:qd(t,r,n.get(s)??0)}))}function qd(e,t,r){return{progress:e,autoScheduling:t,...ae(r)}}function Jd(e,t,r){let i=new Map,n=s=>{let o=0;for(let c of r.getChildHhInfo(s)){let l=r.hasChildren(c.id)?n(c.id):ct(c.workHours,t);i.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?n(e.id):ct(e.workHours,t);return i.set(e.id,a),i}function Xd(e,t,r){let i=new Map;i.set(e.id,t);for(let s of r.getDescendantIds(e.id))i.set(s,t);let n=[];for(let s of r.getAncestorIds(e.id))n.push(s);let a=[];for(let s of n){let o=Zd(s,i,r);i.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function Zd(e,t,r){let i=r.getChildProgressInfo(e).map(n=>({progress:t.has(n.id)?t.get(n.id):n.progress,ponderator:n.ponderator??0}));return Number((te(i)??0).toFixed(2))}function Qd(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var as={targetField:"cost",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e,t){if(String(e).trim()==="")return w(t.cost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return W()},transform(e,t,r){let i=tu(e,t,r.hierarchy);return F({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_entry"};function tu(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.cost;i.set(a,s),n.push({activityId:a,fields:{cost:s}})}return n}var ss={targetField:"usedCost",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e,t){if(String(e).trim()==="")return w(t.usedCost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return W()},transform(e,t,r){let i=eu(e,t,r.hierarchy);return F({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function eu(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildUsedCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.usedCost;i.set(a,s),n.push({activityId:a,fields:{usedCost:s}})}return n}var os={targetField:"workHours",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e){if(String(e).trim()==="")return w(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(){return W()},transform(e,t,r,i){let n=cs(t,e.progress),a=String(i).trim()===""?[]:ru(e,t,n,r.hierarchy);return F({workHours:t,...ae(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function cs(e,t){return ct(e,t)}function ru(e,t,r,i){let n=new Map,a=new Map;n.set(e.id,t),a.set(e.id,r);let s=[];for(let o of i.getAncestorIds(e.id)){let c=0,l=0;for(let d of i.getChildHhInfo(o)){let u=n.has(d.id)?n.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??cs(d.workHours,d.progress);c+=u,l+=f}n.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...ae(l)}})}return s}function rr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function di(e,t){return e.getTime()<t.getTime()}function se(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var ir=e=>({durationHours:e});var ls={targetField:"startDate",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):qa(e)?G("has_progress","cant_edit_activity_with_progress"):U()},parseInput(e,t,r){return se(e)?w(jt(e,"UTC")):N("invalid_date")},validate(e,t,r,i){if(rr(t,r))return Q("unchanged");let n=iu(e,r,i);return n||W()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return F({startDate:t,...St(),...Ot(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let n=oi(i,t),a=e.type==="milestone",s=a?n:i.calculateEndDate(n,e.durationHours),o=n;return{...F({startDate:n,...re(s),...a?ir(0):{},...St(),...Ot(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:nu(e,n,i)}},trackEvent:"activity_start_date_entry"};function iu(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=jt(i);return t.getTime()<n.getTime()?Q("before_parent_start"):null}function nu(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=he(At(e),t,i),a=ie(At(e),e.constraintDate,n);if(a.violated)return ne(a.constraintType,a.constraintDate,n)}var au=99.999,ds={targetField:"endDate",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):su(e)?G("completed","cant_edit_completed_activity"):U()},parseInput(e,t,r){if(!se(e))return N("invalid_date");let i=jt(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,et.DAY)?w(ci(n,i)):r.dateFormat.split(" ").length>1?w(i):w(n.getClosestWorkTime({direction:"past",date:i,unit:et.HOUR})):w(i)},validate(e,t,r,i){if(rr(e.endDate,r))return Q("unchanged");if(ou(r,e))return Q("before_date_origin");if(cu(r,e))return Q("before_start_date");let n=lu(r,e,i);return n||W()},transform(e,t,r){let i=du(e,t),n=uu(e,t,r,!!i);return{...F(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function su(e){return e.progress>=au}function ou(e,t){return t.dateOrigin?di(e,t.dateOrigin):!1}function cu(e,t){return di(e,t.startDate)}function lu(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,et.DAY)?null:Q("not_working_day"):null}function du(e,t){let r=he(At(e),e.startDate,t),i=ie(At(e),e.constraintDate,r);if(i.violated)return ne(i.constraintType,i.constraintDate,r)}function uu(e,t,r,i=!1){let n={},a=ye(e.type);a&&!i?Object.assign(n,Ot(e.startDate)):(i||fu(e))&&Object.assign(n,St(),Ot(e.startDate));let s=pu(e,t,r);if(!a){let o=me(e.durationHours,s);o&&(n.type=o)}return Object.assign(n,ir(s)),n.endDate=t,n}function fu(e){return wt.has(At(e))}function pu(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var hu=new Set(Object.values($)),us={targetField:"constraintType",canEdit(e,t){return ee(e)?G("completed","cant_edit_completed_activity"):tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e){let t=String(e).toLowerCase();return yu(t)?w(t):N("invalid_constraint_type")},validate(){return W()},transform(e,t,r){let i=mu(e,t,r);return F(i,{autoSchedule:!0})}};function yu(e){return hu.has(e)}function mu(e,t,r){let i=vu(e,t);return{constraintType:t,...Xa(gu(e,t,i,r))}}function gu(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?kt(r,n,t):r}function vu(e,t){return wt.has(t)?null:tr.has(t)?e.startDate:li.has(t)?e.endDate:e.constraintDate}var fs={targetField:"constraintDate",canEdit(e,t){return ee(e)?G("completed","cant_edit_completed_activity"):tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e){return se(e)?w(e):N("invalid_date")},validate(){return W()},transform(e,t,r){let i=ps(e)?er:At(e),n=r.calendars.getCalendar(e.calendarId),a=n?kt(t,n,i):t,s=Au(e,a);return F(s,{autoSchedule:!0})}};function Au(e,t){return{constraintDate:t,...ps(e)?St():{}}}function ps(e){return wt.has(At(e))||!e.constraintType}var hs={targetField:"calendarId",canEdit(){return U()},parseInput(e){let t=String(e).trim();return Cu(t)?N("empty_calendar"):w(t)},validate(e,t,r){return Iu(e.calendarId,r)?Q("unchanged"):W()},transform(e,t,r){return F(ku(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function Cu(e){return e===""}function Iu(e,t){return e===t}function ku(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,s=a?Su(e.startDate):e.startDate,o=n.getClosestWorkTime({date:s,direction:"future",unit:"hour"});if((!e.autoScheduling||a||n.getWorkHours(e.startDate).length===0)&&(i.startDate=o),!e.autoScheduling)return i;let c=i.startDate??e.startDate;Object.assign(i,re(n.calculateEndDate(c,e.durationHours)))}return i}function Su(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var ys={targetField:"customId",canEdit(){return U()},parseInput(e){if(e==null)return N("empty_custom_id");if(typeof e!="string")return N("not_a_string");let t=e.trim();return t.length===0?N("empty_custom_id"):t.length>20?N("exceeds_max_length"):w(t)},validate(){return W()},transform(e,t){return F({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var ms={targetField:"subcontractId",canEdit(){return U()},parseInput(e){if(e==null)return w(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return w(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?N("not_an_integer"):w(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?N("not_an_integer"):w(e):N("not_an_integer")},validate(){return W()},transform(e,t){return F({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Ie(e){if(e==null)return null;if(typeof e=="object"){if(!("id"in e))return null;let t=e.id;return t==null?null:String(t)}return String(e)}function nr(e){return e.some(t=>Ie(t)===null)}var gs={targetField:"responsableIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return nr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(Ie).filter(i=>i!==null);return F({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var vs={targetField:"tagIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return nr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(Ie).filter(i=>i!==null);return F({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Du=new Map([[E.TEXT,Ka],[E.DESCRIPTION,za],[E.DURATION,es],[E.PROGRESS,ns],[E.COST,as],[E.USED_COST,ss],[E.HH_WORK_TIME,os],[E.START_DATE,ls],[E.END_DATE,ds],[E.CONSTRAINT_TYPE,us],[E.CONSTRAINT_DATE,fs],[E.CALENDAR_ID,hs],[E.CUSTOM_ID,ys],[E.SUBCONTRACT_ID,ms],[E.RESPONSABLES,gs],[E.TAGS,vs]]);function xt(e){return Du.get(e)}function oe(e,t){if(!t||t.type!=="constraint")return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:"constraint_violation",activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var L={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath",PROMOTION_RESTORE:"promotionRestore"},ui={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};var Tu=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],As=new Set(Tu);function Z(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Cs(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function Nt(e,t){let r=new Set([String(e)]);for(let i of t.cascadeMutations??[])r.add(String(i.activityId));return r}function J(e,t){let r=new Map;for(let i of t){let n=e.getActivity(i);n&&r.set(i,j(n))}return r}function j(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:e.constraintDate?new Date(e.constraintDate):null,dateOrigin:e.dateOrigin?new Date(e.dateOrigin):null}}function Ft(e,t,r){Is(e,t,r.patch);for(let i of r.cascadeMutations??[])Is(e,i.activityId,i.fields)}function Is(e,t,r){for(let[i,n]of Object.entries(r)){if(!As.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);Z(e,t,i,n)}}function ks(e,t,r){let i=[];for(let n of r){let a=e.getActivity(n);if(!a){i.push({id:n,kind:"deleted",after:null});continue}let s=t.get(n),o=fi(s,a);s?i.push({id:n,kind:"updated",fields:o,after:j(a)}):i.push({id:n,kind:"created",fields:o,after:j(a)})}return i}function fi(e,t){let r={},i=e??{},n=t,a=new Set([...Object.keys(i),...Object.keys(n)]);for(let s of a)Ds(i[s],n[s])||(r[s]={before:i[s],after:n[s]});return r}function ar(e,t,r){let i=new Set;i.add(e);for(let n of t)i.add(n);for(let n of r)i.add(n);return i}function Ss(e,t){let r=new Set;for(let i of e)r.add(String(i));for(let i of t)r.add(i);return r}function sr(e,t,r,i,n){for(let a of t){if(r.has(a.activityId)||(n.add(a.activityId),i.has(a.activityId)))continue;let s=e.getActivity(a.activityId);if(!s)continue;let o=j(s);a.before!==void 0&&(o.correlativeId=a.before),i.set(a.activityId,o)}}function Ds(e,t){if(e===t)return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ds(e[r],t[r]))return!1;return!0}return!1}var _u=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Dt(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let o=new Date(e);if(Number.isNaN(o.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return o}let t=e.match(_u);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,i,n,a,s]=t;return new Date(Date.UTC(Number(r),Number(i)-1,Number(n),Number(a),Number(s)))}function ce(e,t,r,i){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let n=i.calculateDuration(e,r),a=i.calculateDuration(e,t);return a===0?0:n*100/a}var Pu=e=>e.type==="project",Eu=(e,t,r)=>{let i=e.calendarId,n=i!=null?r.calendarReader.getCalendar(String(i)):null;if(!n)return 0;let a=s=>s instanceof Date?s:Dt(String(s));return ce(a(e.startDate),a(e.endDate),t,n)};function Ts(e,t,r){let i=[],n=(s,o)=>{let c=r.getActivity(s);c&&c.expectedProgress!==o&&(r.setActivityField(s,"expectedProgress",o),i.push(String(s)))},a=s=>{let o=r.getActivity(s);if(!o)return 0;if(!Pu(o)){let d=Eu(o,t,r);return n(s,d),d}let c=0;for(let d of r.getChildren(s)){let u=a(d),f=r.getActivity(d),p=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*p}let l=c/100;return n(s,l),l};for(let s of e)a(s);return i}var _s=e=>Math.round(e*100)/100;function Ru(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Lu(e,t){let r=_s(e),i=_s(t);return r>99.99?Pt.DONE:i>r?Pt.OVERDUE:e>0&&r>i?Pt.ADVANCEMENT:e===0&&t===0?Pt.WAITING:e>0&&r<i?Pt.DOING:Pt.WAITING}function Yt(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,s=Lu(a,Ru(i,t));i.status!==s&&(Z(e,n,Ne,s),r.push(n))}),r}var pi=Number.MAX_SAFE_INTEGER;function $t(e,t){let r=yi(e,t);return r.sort(bu),r.map(i=>String(i.id))}function Es(e){let t=[],r=n=>{t.push(n);let a=$t(String(n.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},i=$t("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function Rs(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=Ls(i),a=$t(n,r),s=a.findIndex(o=>String(o)===String(e));if(s<=0)return null;for(let o=s-1;o>=0;o--){let c=a[o];if(c!==void 0&&!wu(t,c))return c}return null}function hi(e,t){let r=t.getActivity(e);if(!r)return-1;let i=Ls(r);return $t(i,t).findIndex(a=>String(a)===String(e))}function yi(e,t){if(String(e)==="0")return t.getAllActivities().filter(a=>a.parentId===null);let i=t.getChildren(e),n=[];for(let a of i){let s=t.getActivity(a);s&&n.push(s)}return n}function bu(e,t){let r=Ps(e),i=Ps(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Ps(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:pi}function Ls(e){let t=e.parentId;return t===null?"0":t}function wu(e,t){return e.has(t)?!0:e.has(String(t))}function at(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{O(a.parentId)&&t.push(a)}),t.sort(Os);let r=[];bs(r,t);let i=[],n=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==n){let o=typeof a.correlativeId=="number"?a.correlativeId:void 0;i.push({activityId:String(a.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(a.id),o),Ou(a,n)}n+=1;let s=yi(String(a.id),e);s.sort(Os),bs(r,s)}return i}function bs(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function ws(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:pi}var Os=(e,t)=>ws(e)-ws(t);function Ou(e,t){e.correlativeId=t}function xs(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(n);if(!a)return 0;let s=[...e.getChildren(n)],o=s.length===0?ct(a.workHours,a.progress):s.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,L.REAL_WORK_HOURS,o),r.push(n),o};for(let n of t)i(n);return r}async function Ns(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(at(t),r.updateDurationForPrimaveraEndDate&&Nu(t),Fu(t),xs(t),n){a&&(or(t,a),Yt(t,r.statusCriteria));return}let s=await i.schedule({});ge(t,s),Mu(t),xu(t),await ve(t,void 0,!1),a&&(or(t,a),Yt(t,r.statusCriteria))}function or(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),Ts(r,t,e)}function xu(e){e.forEachActivity(t=>{t.autoScheduling||!t.startDate||t.durationHours==null||e.getChildren(t.id).length>0||(t.endDate=e.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:t}))})}function Nu(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Fu(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type==="milestone"&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=kt(t.constraintDate,n,r))})}function Mu(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=kt(t.constraintDate,i,r))})}function pt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var Wu=e=>e.type==="project",Uu=e=>pt(e),Bu=(e,t,r,i)=>{let n=Uu(e);if(!n)return 0;let a=(n.baseCalendarId!=null?r.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(i?r.getBaseCalendar(i):null);return!a||!n.startDate||!n.endDate?0:ce(n.startDate,n.endDate,t,a)};function mi(e,t,r,i=null){let n=[],a=(o,c)=>{let l=r.getActivity(o);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(o,"expectedProgressBaseline",c),n.push(o))},s=o=>{let c=r.getActivity(o);if(!c)return 0;if(!Wu(c)){let u=Bu(c,t,r,i);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),p=r.getActivity(u),v=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*v}let d=l/100;return a(o,d),d};for(let o of e)s(o);return n}function cr(e,t,r=null){let i={getChildrenIds:a=>e.getChildren(String(a)).map(s=>String(s)),getActivity:a=>e.getActivity(a),setActivityField:(a,s,o)=>Z(e,a,s,o),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},n=[];return e.forEachActivity((a,s)=>{a.parentId===null&&n.push(s)}),mi(n,t,i,r)}function gi(e){let t=e instanceof Date?new Date(e.getTime()):e&&typeof e=="object"&&typeof e.valueOf=="function"?new Date(e.valueOf()):new Date(e),r=(n,a)=>s=>s===void 0?t[n]():(t[a](s),i),i={__isMomentShim:!0,clone:()=>gi(t),hours:r("getUTCHours","setUTCHours"),minutes:r("getUTCMinutes","setUTCMinutes"),seconds:r("getUTCSeconds","setUTCSeconds"),milliseconds:r("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return i}gi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var ht=gi;function Hu(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function lr(e){return Hu(e)&&!isNaN(e.getTime())}function I(e,t,r,i){if(!lr(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(i)}`);let n=t;return e.calculateEndDate({start_date:new Date(n),duration:r,unit:"hour",task:i})}function lt(e){if(!lr(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:i,activity:n}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:i,unit:"hour",task:n})}var ju=e=>e?e.$level===1:!1,Vu=e=>e.type==="project",Yu=e=>e.$level!==0,$u=e=>e.type==="task",Gu=e=>e.type==="task"||e.type==="milestone",it={byFirstLevel:ju,filterByParentType:Vu,avoidSubproject:Yu,byTaskType:$u,byTaskTypeAndMilestone:Gu};var h=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var B=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function Gt(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Fs(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=Ku({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=zu({gantt:t,subprojectsWithNoLinks:a}),o=qu({gantt:t,childrenIds:s,linkProperty:n,getArrayOfLinkedActivities:Ju,calculations:i});return new Set(o.map(c=>c.id))}catch(a){throw a}}function Ku(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(it.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function zu(e){let{gantt:t,subprojectsWithNoLinks:r}=e,i=new Set;for(let n of r)t.getChildren(n).filter(o=>{let c=t.getTask(o),l=it.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>i.add(o));return[...i]}function qu(e){let{gantt:t,childrenIds:r,linkProperty:i,getArrayOfLinkedActivities:n,calculations:a}=e,s=[];for(let o of r){let c=t.getTask(o),l=c[i]||[];n({gantt:t,links:l,linkDirection:i==="$source"?"target":"source"}).every(f=>a.has(f))&&s.push(c)}return s}function Ju(e){let{gantt:t,links:r,linkDirection:i}=e,n=[];for(let a of r){let s=t.getLink(a);if(!s){`${a}`;continue}let o=Number(s[i]);n.push(o)}return n}function Ms({gantt:e,linkProperty:t,direction:r}){try{let i=Xu(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Zu(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function Xu(e,t){return e.getTaskByTime().filter(it.avoidSubproject).filter(it.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Zu(e,t,r){let i=[],n=new Set;return e.forEach(a=>{let s=Number(a.parent),o=t.getTask(s);o&&(o[r].length>0?n.add(a.id):o.constraint_type!=="fnlt"&&i.push(a))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function Ws({gantt:e,direction:t,linkProperty:r}){try{let i=Qu(e),n=new Set,a=new Set,s=new Set;t==="backward"&&rf(i).forEach(d=>{n.add(d.id)});let o=tf(i,t,r),c=ef(i,o);return o.forEach(l=>{a.add(l.id)}),c.forEach(l=>{s.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:a,pendingParentsWithLinks:s}}catch(i){throw i}}function Qu(e){return e.getTaskByTime().filter(it.filterByParentType).filter(it.avoidSubproject)}function tf(e,t,r){return e.filter(i=>{let n=i[r];if(!Array.isArray(n))return!1;let a=n.length>0,s=i.constraint_type||"",o=s!=="fnlt";return t==="forward"?!a&&o&&s!=="snet":!a&&o})}function ef(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function rf(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Us({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),s=nf(r),o=af(r),c=a[s];if(!Array.isArray(c))return;sf(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function nf(e){return e==="forward"?"$source":"$target"}function af(e){return e==="forward"?"target":"source"}function sf(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var ke={identifySecondLevelActivities:Fs,identifyInitialActivities:Ms,identifyParentsWithAndWithoutLinks:Ws,identifyForbiddenActivities:Us};function dr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function vi({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===B.FS&&t===0?lt({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):Se(r,e,i,n)}function Bs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:I(r,n,e,i),ef:n}}function Hs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),a=I(r,n,e,i);return{es:n,ef:a}}function Se(e,t,r,i){if(![B.FS,B.SS,B.FF].includes(t))return e;let a=[B.FS,B.SS].includes(t)?"future":"past";return lt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:i})}var Ai=class{constructor(t,r,i){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=i,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=dr(t),i=this.activity.constraint_type;return i==="snet"?this.handleSNETConstraint(r):i==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=Gt(i),a=r.linkLag,s=r.es,o=r.ef,c=null;if(n==="ss")c=this.calculateSSLink({lag:a,predecessorEs:s});else if(n==="ff")c=this.calculateFFLink({lag:a,predecessorEf:o});else if(n==="fs")c=this.calculateFSLink({lag:a,predecessorEf:o});else if(n==="sf")c=this.calculateSFLink({lag:a,predecessorEs:s,predecessorEf:o});else continue;c&&t.push(c)}return t}handleSNETConstraint(t){let r=Hs({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>r.ef?t:r}handleFNLTConstraint(t){let r=Bs({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>r.ef?r:t:r}calculateSSLink({lag:t,predecessorEs:r}){let i=vi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity);t>0&&(n=Se(n,"ss",this.activityCalendar,this.activity));let a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let i=vi({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(a=Se(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=lt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let i=I(this.activityCalendar,r,t,this.activity),n=I(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=Se(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},js=Ai;var Ci=class{constructor(t){this.linkedActivitiesData=t.linksWithActivityData,this.activity=t.activity,this.gantt=t.gantt}calculate(){if(this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let t=[];for(let r of this.linkedActivitiesData){let i=Gt(r.linkType);if(r.type==="task"&&Number(r.progress)>0||r.type==="project"&&Number(r.progress)===100)continue;let n=r.linkLag,a=r.ls,s=r.lf;if(i==="ss"){let o={lag:n,workTime:a,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(o);t.push({ls:c,lf:l})}if(i==="ff"){let o={lag:n,workTime:s,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFFLink(o);t.push({ls:c,lf:l})}if(i==="fs"){let o={lag:n,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFsLink(o);t.push({ls:c,lf:l})}if(i==="sf"){let o={lag:n,workTime:s,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(o);t.push({ls:c,lf:l})}}if(this.activity.constraint_type==="fnlt"){let r=this.getMinLfFromLinks(t),i=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([i,r]):i}else{let r=this.getMinLfFromLinks(t);if(r===!1){let i=this.gantt.getSubtaskDates();return{ls:I(this.activityCalendar,i.end_date,-this.activity.duration,this.activity),lf:i.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null;if(t===0)return a=I(this.activityCalendar,r,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=I(this.activityCalendar,o,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return s=I(this.activityCalendar,l,n,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=I(this.activityCalendar,s,i,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=I(this.activityCalendar,c,n,this.activity),o=I(this.activityCalendar,s,i,this.activity),a||(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),{ls:o,lf:s}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null,o=r;return s=I(this.activityCalendar,o,i,this.activity),a=I(this.activityCalendar,s,n,this.activity),{ls:s,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0)return o=I(this.activityCalendar,r,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),o=I(this.activityCalendar,c,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:I(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=ht(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),lt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),ht.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}},Vs=Ci;function Ys(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:s}=e,o=t[r],c=of(t),l=null;if(s==="forward"){let d=cf(o,i,n,a);l=new js(d,t,a),l=l.calculate()}else{let d=lf(o,i,n,a);l=new Vs({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function of(e){return{duration:e.duration,calendarId:e.calendar_id}}function cf(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);return o?{es:o.es,ef:o.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${s}`),null)}).filter(Boolean)}function lf(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);if(!o)return null;let c=i.getTask(s);return c?{ls:o.ls,lf:o.lf,linkLag:a.lag||0,linkType:a.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function Ks(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(df(t.id,r))return null;let a=uf(t.id,i),s=ff(a,r);return s.length===0?null:pf(s,n)}function df(e,t){return t.has(e)}function uf(e,t){let r=t.get(e);return r?r.childrens:[]}function ff(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function pf(e,t){if(t==="forward"){let r=$s(e,"es"),i=Gs(e,"ef");return{es:r,ef:i}}else{let r=$s(e,"ls"),i=Gs(e,"lf");return{ls:r,lf:i}}}function $s(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function Gs(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var Ii={parentWithLinks:Ys,parentWithNoLinks:Ks};var ki=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction==="forward"?"$target":"$source",this.linkDirection=t.direction==="forward"?"source":"target",this.calculationsOfParentThatImpactChildrens=t.calculationsOfParentThatImpactChildrens,this.calculations=t.calculations,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.parentCalculationFromChildren=t.parentCalculationFromChildren,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let i=[h.FNLT];if(this.shouldCalculateParentWithLinksBackward(i)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(i)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(t)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction==="forward"&&this.setDatesToParentsWithLinks(),this.direction==="backward"&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(t){throw t}}shouldCalculateParentWithLinksBackward(t){let r=t.includes(this.activity.constraint_type),i=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}calculateAndStoreParentWithLinks(t){let r=Ii.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),i=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}handleParentWithNoLinks(){let t=Ii.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});t&&this.calculations.set(this.activity.id,t)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minEs:n,maxEf:a}=i.reduce((s,{es:o,ef:c})=>({minEs:new Date(Math.min(s.minEs.getTime(),new Date(o).getTime())),maxEf:new Date(Math.max(s.maxEf.getTime(),new Date(c).getTime()))}),{minEs:new Date(i[0].es),maxEf:new Date(i[0].ef)});this.calculations.set(this.activity.id,{es:n,ef:a}),this.parentCalculationFromChildren.add(this.activity.id)}setDatesToParentsWithLinksBackward(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minLs:n,maxLf:a}=i.reduce((s,{ls:o,lf:c})=>({minLs:new Date(Math.min(s.minLs.getTime(),new Date(o).getTime())),maxLf:new Date(Math.max(s.maxLf.getTime(),new Date(c).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(this.activity.id,{ls:n,lf:a})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}},zs=ki;var Si=class{constructor({gantt:t,linkProperty:r}){this.gantt=t,this.linkProperty=r,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let r of t){let i=this.processEachActivity(r),{activitiesByLevel:n}=i,a=this.getAllLevels(n),s=this.getDeepestLevel(a),o=this.createResult(r,i,s,a);this.structureOfParents.set(r.id,o)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(it.byFirstLevel).filter(it.filterByParentType)}processEachActivity(t){let r=new Set,i=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(a=>{this.processActivity(a,r,i,n)},t.id),{parentsIds:r,allTasks:i,activitiesByLevel:n}}initializeParent(t){let r=Number(t.id),i=!!t[this.linkProperty]?.length,n=t.$level;this.singleParents.set(r,{level:n,hasLink:i,childrens:[]})}processActivity(t,r,i,n){let a=Number(t.id),s=Number(t.parent);i.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(s);s!=null&&c&&this.addChildToParent(s,a),this.addActivityToLevel(t,n)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let i=Number(t.id),n=t.$level,a=this.hasLink(t),s={level:n,hasLink:a,childrens:[]};r.add(i),this.singleParents.set(i,s)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let i=t.$level,n=Number(t.parent);r.has(i)||r.set(i,new Map);let a=r.get(i);a.has(n)||a.set(n,[]),a.get(n).push({id:Number(t.id),isParent:this.isProjectActivity(t),calculated:!1})}getAllLevels(t){return new Set(t.keys())}getDeepestLevel(t){return t.size===0?0:Math.max(...t)}createResult(t,r,i,n){let{activitiesByLevel:a,parentsIds:s,allTasks:o}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:s,allChildrens:o,childrensByLevel:a,currentResolutionLevel:i,canBeCalculated:!1}}},qs=Si;var Di=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction==="forward"?"$target":"$source",this.linkDirection=this.direction==="forward"?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:r,childrensByLevel:i,isALinkedParent:n}=t;if(n)return;let a=i.get(r);for(let[s,o]of a)if(o.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(s);this.calculateParentWithNoLinks(l,o);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(it.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=ke.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=i}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=ke.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new qs({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,i=new Set,n=new Map,a=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((s,o)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(i.add(c.id),c.type==="project"){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};r.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),n.has(c.$level)||n.set(c.$level,new Map);let d=n.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type==="project",calculated:!1})}.bind(this),t.id),s({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:a})})}identifySecondLevelActivities(){try{let t=ke.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...t])}catch(t){throw t}}identifyInitialActivities(){try{let{chainStartActivities:t,activitiesStartChainButChildrenOfLinkedParents:r}=ke.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,r&&(this.activitiesStartChainButChildrenOfLinkedParents=r)}catch(t){throw new Error("Error in identifyInitialActivities",{cause:t})}}calculateSecondLevelActivities(){try{this.direction==="forward"?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(t){throw t}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(t=>{if(!t||t.progress>100||t.type==="project")return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction==="forward"){let{es:i,ef:n}=r;this.calculations.set(t.id,{es:i,ef:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:i,lf:n}=r;this.calculations.set(t.id,{ls:i,lf:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,i=new Set(this.calculations.keys()),n=new Map;return t.forEach(a=>{a&&n.set(a.id,a)}),n.forEach((a,s)=>{if(i.has(s))return;let o=[];(a[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);o.push(u)}}),o=o.filter(l=>n.has(l)||i.has(l)),r.set(s,o)}),{graph:r,activityMap:n,calculatedActivities:i}}topologicalSort(t,r){let i=new Set,n=new Set,a=[],s=o=>{if(n.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!i.has(o)&&!r.has(o)){n.add(o);let c=t.get(o)||[];for(let l of c)s(l);n.delete(o),i.add(o),a.push(o)}};for(let o of t.keys())!i.has(o)&&!r.has(o)&&s(o);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let i=t,n=Number(i.progress);n==="0.00"&&(n=0);let a=this.gantt.getCalendar(i.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);if((r||this.direction)==="forward"){let o=i.start_date,c=i.end_date;return{es:o,ef:c}}else{if(n>=100)return{ls:ht(i.start_date).clone(),lf:ht(i.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(i,a);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,a)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(t,r){let i=ht(t.start_date).clone(),n=ht(t.end_date).clone(),a=t.duration,s=[h.ASAP,h.ALAP,h.SNET,h.FNET],o=t.constraint_type||h.ASAP;if(s.includes(o))n=this.projectDates.end_date,i=I(r,n,-a,t);else{let c=[h.SNLT,h.MSO],l=[h.FNLT,h.MFO];c.includes(o)&&(i=t.constraint_date,n=I(r,i,a,t)),l.includes(o)&&(n=t.constraint_date,i=I(r,n,-a,t))}return{ls:i,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,i=null,n=t.constraint_type||h.ASAP,a=this.projectDates.end_date,s=[h.ASAP,h.ALAP,h.SNET,h.FNET],o=[h.SNLT,h.FNLT];if(s.includes(n))i=Math.max(t.end_date,a);else if(n===h.MSO)i=t.end_date;else if(n===h.MFO||o.includes(n)){let c=Math.min(a,t.constraint_date);i=Math.max(c,t.end_date)}return{ls:r,lf:new Date(i)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(i=>Number(this.gantt.getTask(i).progress)===100).map(i=>this.gantt.getTask(i)).forEach(i=>{let n=i.type==="project";this.setDatesForActivityWithFullProgress(i),this.activitiesWaitingForCalculation.delete(i.id),n&&this.pendingParentsWithLinks.has(i.id)&&(this.parentCalculationFromChildren.add(i.id),this.calculationsOfParentThatImpactChildrens.set(i.id,{[this.direction==="forward"?"es":"ls"]:i.start_date,[this.direction==="forward"?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new zs({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},Mt=Di;function hf(e,t,r){let i={es:null,ef:null};if(!e)return i;if([h.SNET,h.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if([h.FNLT,h.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}else if(t===h.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if(t===h.MFO){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}return i}var ur=hf;var Ti=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,i=0,n,a=B.FS){let s=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.referenceActivity.calendar_id}`);let o=t,c=null,l=null,d=this.referenceActivity.type==="milestone";return d||(a===B.FS&&n===0?o=lt({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[B.FF,B.SF].includes(a)?(l=I(s,o,i,this.referenceActivity),c=I(s,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=I(s,o,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=I(s,c,i,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,s,B.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,s,B.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,s,B.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,s,B.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![B.FS,B.SS,B.FF].includes(r))return t;let a=[B.FS,B.SS].includes(r)?"future":"past";return lt({dateBaseToCalculate:t,activityCalendar:i,direction:a,activity:this.referenceActivity})}},Js=Ti;var De=class extends Js{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Mt(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(i=>{let n=this.gantt.getLink(i);if(!n)throw new Error("Link data not found",{cause:{linkId:i}});return this.calculateLink(n)}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let i=this.gantt.getCalendar(this.referenceActivity.calendar_id),n=this.parentsCalculations.get(r).es,a=I(i,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:a})}return dr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var _i=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let r=new Set,i=new Set(t);for(let n of t){let a=this.gantt.getTask(n);a.type==="project"?this.handleProjectActivity(n,a,r,i):this.handleNonProjectActivity(n,a,r,i)}return{activitiesThatCanBeCalculated:r,pendingActivities:i}}handleProjectActivity(t,r,i,n){let a=this.pendingParentsWithNoLinks.has(t),s=this.pendingParentsWithLinks.has(t),o=this.calculationOfParentsFromLinks.has(t);if(a){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}if(s&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}s&&!o&&this.canCalculateParentActivity(r)&&(i.add(t),n.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,i=t.constraint_type;return(this.direction==="forward"?i==="fnlt"||i==="snlt":i==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(s=>this.calculations.has(s))}handleNonProjectActivity(t,r,i,n){let a=Number(r.parent),s=this.pendingParentsWithLinks.has(a),o=this.calculationOfParentsFromLinks.has(a);if(s&&!o||this.direction==="backward"&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!o)return;if(r.$target.length===0&&r.$source.length===0){i.add(t),n.delete(t);return}let c=this.getLinkedActivities(r[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction==="backward"&&(c.length===0||l)&&o){i.add(t),n.delete(t);return}l&&(i.add(t),n.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=n[this.linkDirection],s=this.gantt.getTask(a);s&&r.push(s)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);n&&r.push(Number(n[this.linkDirection]))}return r}},fr=_i;var Pi=(e,t)=>()=>t()===e;var Ei=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var yf=16,Te=async e=>performance.now()-e>yf?(await rt(),performance.now()):e;var _e=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:i,isCalculated:n,onActivityProcessed:a,isCurrent:s})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!s())return;c=await Te(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await Te(c),r([u])}for(let u of l){if(!s())return;i(u)&&d.add(u),a(u),n(u)&&d.delete(u)}o=d}};var Ri=class extends Mt{constructor(t){super(t,"forward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new fr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await _e({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(i.type==="project")return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:r}});let n=i.$target,a=i.constraint_type||h.ASAP,s=[h.SNET,h.SNLT,h.FNLT,h.FNET],o=[h.ASAP,h.ALAP,h.SNET,h.FNET,h.SNLT,h.FNLT],c=this.gantt.getCalendar(i.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);let l=Number(i.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(i);return}l>0&&o.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),f=new De({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===h.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new De({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===h.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let p=ur(i,a,c);if(s.includes(a)&&(this.constraintsMap.set(r,p),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,p,{es:d,ef:u})),[h.MSO,h.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),i.progress===0)d=p.es,u=p.ef;else{let v=i.end_date;a===h.MFO&&(v=Math.max(p.ef,i.end_date)),d=i.start_date,u=v}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,i="greater"){if(i==="greater")return r.ef>t.ef?r:t;if(i==="less")return r.ef<t.ef?r:t}setDatesForActivityWithFullProgress(t){this.calculations.set(t.id,{es:t.start_date,ef:t.end_date})}getDatesForActivityWithZeroProgress(t){return{es:t.start_date,ef:t.end_date}}recalculateInBaseConstraint(t,r,i){let n=[h.SNET,h.FNET].includes(t)?"greater":"less",{es:a,ef:s}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,i,n);return{es:a,ef:s}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r);if(!i)throw new Error("Error trying to get link",{cause:{linkId:r}});let n=i.source,a=i.target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},Xs=Ri;var Li=class{constructor(t){this.activity=t.activity,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.forwardPathCalculations=t.calculatedForwardActivitiesMap,this.gantt=t.ganttInstance}getForwardOrBackwardCalculations(t,r=null){return r===h.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,a=B.FS){let s=this.gantt.getCalendar(this.activity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let o=t,c=this.activity.type==="milestone";if(c&&n===0){let d=I(s,o,r,this.activity),u=I(s,d,i,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:o,activityCalendar:s,lsDataCalculation:r,lfDataCalculation:i,isMilestone:c};if(a===B.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===B.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===B.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===B.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let i=this.getValueForSS(t,r),n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,B.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===h.ALAP?"ef":"lf",a=i[n],s=-this.activity.duration,o=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,s,o,c,B.FF)}calculateFS(t,r){let i="ls";i=r===h.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,s=t.lag||0,o=-t.lag||0;return this.calculateSuccessorTimes(n[i],a,o,s,B.FS)}calculateSF(t,r=!1){let i=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,B.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,i){let n=ht(r).clone();return I(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=ht(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),lt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),ht.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}calculateFsLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,i,"past");return o=I(i,d,a,this.activity),o=this.getLastWorkingHour(o,i,"past"),c=I(i,o,n,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,i)),o=I(i,l,a,this.activity),c=I(i,o,n,this.activity),s||(o=this.getLastWorkingHour(o,i,"past",!0)),{ls:c,lf:o}}calculateFFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;if(t===0)return s=I(i,r,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),s=I(i,c,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s}}calculateSSlink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0)return c=I(i,r,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,i,"future")),c=I(i,l,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o}}calculateSFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;return t===0?(o=I(i,r,n),s=I(i,o,a,this.activity),{ls:o,lf:s}):(o=I(i,r,n,this.activity),s=I(i,o,a,this.activity),{ls:o,lf:s})}},Zs=Li;var bi=class extends Zs{constructor(t){super(t),this.constraint=t.constraint||h.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Mt(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),i=!1;r&&(i=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let n=this.links.map(s=>{let o=this.gantt.getLink(s);if(!o)throw new Error("Link not found",{cause:{linkId:s}});if(!this.parentsWithFullProgress.has(Number(o.target)))return this.calculateLink(o)}).filter(s=>s);if(n.length!==0){let s=this.getMinLfFromLinks(n);if(n.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));n.push(this.calculateTheLsAndLfForTheActivity(d))}let o=this.getMinDateFromLinks(n),c=o.ls,l=o.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(o)),{ls:c,lf:l,minFromLinks:s}}if(i){n.push(this.calculateTheLsAndLfForTheActivity());let o=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=I(this.gantt.getCalendar(this.activity.calendar_id),o,-this.activity.duration,this.activity);n.push({ls:c,lf:o});let l=this.getMinDateFromLinks(n);return{ls:l.ls,lf:l.lf,minFromLinks:l}}let a=this.calculateTheLsAndLfForTheActivity();return{ls:a.ls,lf:a.lf,minFromLinks:a}}calculateTheLsAndLfForTheActivity(t=null){try{let r=this.activity.duration,i=this.gantt.getCalendar(this.activity.calendar_id);if(!i)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let n=t?t.lf:this.projectDates.end_date;if(!n)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:I(i,n,-r,this.activity),lf:n}}catch(r){throw Error(r.message)}}SnetSnltMsoMinDate(t){let r=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(r,this.activity.end_date))}calculateLink(t){let r=this.gantt.getTask(t.target);if(!r||r.progress>0&&r.type!=="project")return;let i=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,i),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,a),3:()=>this.calculateSF(t,n)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===h.ALAP)return h.ALAP;if(this.constraint===h.FNET||this.constraint===h.SNET)return"snet-fnet";if(this.constraint===h.FNLT)return h.FNLT}getSpecialParamForSf(){return!![h.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![h.MFO,h.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===h.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.SNET||this.constraint===h.SNLT||this.constraint===h.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===h.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===h.ALAP||this.constraint===h.ASAP?t.reduce((i,n)=>n.lf<i.lf?n:i):t.reduce((r,i)=>i.ls<r.ls?i:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,i)=>i.lf<r.lf?i:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let i=Math.min(t.lf,this.projectDates.end_date),n=this.activity.end_date,a=this.activity.constraint_date;if(r===h.ASAP)return new Date(Math.max(i,n));if(r===h.FNET||r===h.FNLT){let s=Math.min(i,a);return new Date(Math.max(i,s))}if(r===h.ALAP)return new Date(Math.min(i,n))}},Qs=bi;function mf(e,t,r){let i={ls:null,lf:null};return r===h.MSO&&(i.ls=t.constraint_date,i.lf=I(e,i.ls,t.duration,t)),r===h.MFO&&(i.lf=t.constraint_date,i.ls=I(e,i.lf,-t.duration,t)),i}var to=mf;var wi=class extends Mt{constructor(t,r,i){super(t,"backward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.activitiesWaitingForCalculation=new Set,this.calculations=new Map,this.mapOfRelationsWithActivitiesIds=new Map,this.activitiesWaitingForCalculation=new Set,this.forwardPathCalculations=r,this.forwardConstraintsMap=i,this.constraintMap=new Map,this.minFromLinks=new Map,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.parentsWithFullProgress=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateLfAndLs(t))))))}async iterativeCalculateLfAndLs(t){let r=new fr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await _e({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let r=this.singleParents.get(t.id).childrens,n=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=n.reduce((o,{ls:c,lf:l})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(o.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(!i)throw new Error("Activity not found",{cause:{activityId:r}});let n=i.$source,a=i.constraint_type||h.ASAP,s=Number(i.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(i.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(i.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(i,this.direction);this.setCalculations(i,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(i)}if(i.type==="project")return this.doCalculationForParentType(i);if(s===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(n,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(s>0&&s<100&&(a===h.MSO||a===h.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,a);return}if(a===h.MSO||a===h.MFO){this.recalculateInBaseRestriction(i,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===h.SNLT||a===h.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:o,lf:c},a)),this.setCalculations(i,o,c),this.minFromLinks.set(i.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,i){let n=this.forwardConstraintsMap.get(t);if(!n){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);n=ur(a,i,s)}return r.lf<n.ef?r:{ls:n.es,lf:n.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=this.gantt.getTask(n.target);a&&(a.type==="project"&&(r=!1),a.progress===0&&(r=!1))}return r}catch(r){throw new Error(r.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let r=Number(t.parent),{ls:i,lf:n}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){i=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(n=new Date(Math.min(n,a.lf)))}this.setCalculations(t,i,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===h.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===h.MFO){let i=Math.min(t.constraint_date,this.projectDates.end_date),n=new Date(Math.max(i,t.end_date));this.setCalculations(t,t.start_date,n);return}}setCalculations(t,r,i){this.calculations.set(t.id,{ls:r,lf:i,text:t.text})}calculateLfandLsFromLinks(t,r,i,n,a){return new Qs({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:n,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let i=this.gantt.getCalendar(t.calendar_id);if(!i)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let n=to(i,t,r);this.constraintMap.set(t,n),this.setCalculations(t,n.ls,n.lf)}catch(i){throw new Error(i.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r).source,n=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project"))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,a=0;if([h.ASAP,h.ALAP,h.SNET,h.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;a=new Date(Math.min(l,i.lf)),n=t.start_date}else a=i.lf,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([h.SNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r),u=I(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);n=new Date(Math.min(l.getTime(),u.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([h.FNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r);n=new Date(Math.min(l.getTime(),d.lf.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[h.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[h.MFO].includes(t.constraint_type)&&(a=t.constraint_date,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:n,lf:a}];o.push({ls:I(this.gantt.getCalendar(t.calendar_id),s,-t.duration,t),lf:s});let c=this.getMinLfFromLinks(o);this.calculations.set(t.id,{ls:c.ls,lf:c.lf,text:t.text})}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}},eo=wi;function ro(){return null}var io=({forward:e,backward:t,id:r,activity:i,gantt:n,projectDates:a})=>({totalFloat:{es:e.calculations.get(r)?.es||0,ef:e.calculations.get(r)?.ef||0,ls:t.calculations.get(r)?.ls||0,lf:t.calculations.get(r)?.lf||0,constraintsMap:e.constraintsMap.get(r),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(r),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(r),minFromLinks:t.minFromLinks.get(r),activity:i,gantt:n},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:i,projectDates:a,gantt:n}});var Oi=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.es=t.es,this.ef=t.ef,this.ls=t.ls,this.lf=t.lf,this.constrainstMap=t.constraintsMap,this.totalFloatSnltFnlt=t.totalFloatSnltFnlt,this.totalFloatForMsoMfo=t.totalFloatForMsoMfo,this.minFromLinks=t.minFromLinks}getTotalFloat(){let{constraint_type:t}=this.activity,r=Number(this.activity.progress);if(r===100)return 0;if(t||(t=h.ASAP),t===h.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===h.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===h.SNET||t===h.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===h.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===h.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===h.MSO||t===h.MFO)return r===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r),n=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateAlapWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFnetSnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),r=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,i)/this.gantt.config.hoursPerDay}return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateMsoMfoWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFet(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.SNLT?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.MSO?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,r){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)})}},no=Oi;var xi=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),r=this.getConstraintType();return this.calculateFreeFloatOfLink(r),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(r),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===h.MSO||t===h.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=h.ASAP){let r=this.activity.$source.map(i=>{let{LINK:n,LINK_TYPE:a}=this.getLinkData(i),s=this.gantt.getTask(n.target);if(!s)return{linkId:n.id,freeFloat:null,hasProgress:!1};let o=Number(s.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(a,t,s),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(n.lag),f=Math.max(0,u);return this.linksFreeFloatObject[n.id]=f,{linkId:n.id,freeFloat:f,hasProgress:o}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=h.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=0;return[h.SNLT,h.FNLT].includes(t)?n=this.doCalculationForSnltFnlt(t,i,r):n=this.doGeneralCalculation(i,r),Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=h.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===h.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:n,sucessorId:i.id,predecessorId:this.activity.id}),s=new Date,o=new Date;return s=a[t].sucessor,o=a[t].predecessor,{sucessorDateToCalculate:s,predecessorDateToCalculate:o}}doGeneralCalculation(t,r){return r===null?t:this.getMinValue(r,t)}doCalculationForSnltFnlt(t,r,i){let n=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(i,r,n)}calculateFreeFloatForEndOfProject(t){return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===h.ALAP?this.backwardMap.get(this.activity.id).lf:this.forwardMap.get(this.activity.id).ef))}calculateFreeFloatOfRestriction(t){return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===h.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Gt(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let a=({direction:s,constraint:o=h.ASAP})=>o===h.ALAP?this.backwardMap.get(n)[s]:this.forwardMap.get(n)[s];if(t===h.ASAP||t===h.SNET||t===h.FNET||t===h.MSO||t===h.MFO)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===h.ALAP)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:h.ALAP,direction:"lf"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:h.ALAP,direction:"ls"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:h.ALAP,direction:"lf"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:h.ALAP,direction:"ls"})}};if(t===h.SNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===h.FNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,i=t===h.MSO?this.forwardMap.get(this.activity.id).es:this.forwardMap.get(this.activity.id).ef,n=this.calculationWithCalendar(r,i);return Math.max(0,this.parseHoursToDays(n))}getMinValue(...t){let r=t.filter(i=>i!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){let i=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(i))return this.durationCache.get(i);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(i,a),a}parseHoursToDays(t){return t?t/this.gantt.config.hoursPerDay:0}getMinFloat(t){if(!t?.length)return null;let r=t.filter(i=>!i.hasProgress).map(i=>i.freeFloat);return r.length===0?null:Math.min(...r)}},ao=xi;var so=e=>({totalFloat:new no(e.totalFloat).getTotalFloat(),freeFloat:new ao(e.freeFloat).getFreeFloat()});var Ni=async({activityIds:e,forward:t,backward:r,gantt:i,projectDates:n,isCurrent:a})=>{let s=performance.now(),o=new Map,c=new Map;for(let l of e){if(a&&!a())return{totalFloatMap:o,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=io({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=so(u);o.set(l,f),c.set(l,p),s=await Te(s)}return{totalFloatMap:o,freeFloatMap:c}};var Fi=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t){let r=++this.currentCalculationId,i=Pi(r,this.getCurrentCalculationId);try{let n=t||this.gantt;if(this.gantt=n||ro(),Ei(this.gantt))return!1;let a=new Xs(this.gantt);if(await a.calculateAsync(i),!i())return!1;let s=a.calculations,o=a.constraintsMap,c=new eo(this.gantt,s,o);if(await c.calculateAsync(i),!i())return!1;this.forwardPathCalculations=s,this.backwardPathCalculations=c.calculations;let{totalFloatMap:l,freeFloatMap:d}=await this.calculateFloatsAsync(a,c,i);return i()?(this.totalFloat=l,this.freeFloat=d,this.gantt.refreshData(),!0):!1}catch(n){return this.forwardPathCalculations?.size,!1}}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await Ni({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){return this.forwardPathCalculations?.size,{totalFloatMap:new Map,freeFloatMap:new Map}}}},oo=Fi;var gf=e=>e==="fnet"||e==="fnlt"||e==="mfo",vf=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Af(e,t){let r=e.constraintDate;if(!r||!gf(e.constraintType))return r;let i=vf(r);if(r.getTime()!==i.getTime())return r;let n=t.getClosestWorkTime({date:i,dir:"future",task:e});return n.getUTCFullYear()===r.getUTCFullYear()&&n.getUTCMonth()===r.getUTCMonth()&&n.getUTCDate()===r.getUTCDate()?Jr(e,t):r}function Cf(e){return{calculateEndDate:({start_date:t,duration:r})=>e.calculateEndDate(t,r),calculateDuration:({start_date:t,end_date:r})=>e.calculateDuration(t,r),getWorkHours:t=>e.getWorkHours(t),$gantt:{getClosestWorkTime:({date:t,dir:r,unit:i})=>e.getClosestWorkTime({date:t,direction:r,unit:i??"hour"})}}}function If(e){let t=new Map;e.forEachActivity((n,a)=>t.set(String(a),n));let r=new Map,i=(n,a)=>{let s=r.get(n);if(s!=null)return s;let c=t.get(n)?.parentId??null,l=0;return c!==null&&!a.has(n)&&(a.add(n),l=i(String(c),a)+1),r.set(n,l),l};for(let n of t.keys())i(n,new Set);return r}function kf(e){let t=If(e),r=new Map;return e.forEachActivity((i,n)=>{let a=String(n);r.set(a,{id:Number(n),parent:i.parentId===null?0:Number(i.parentId),$level:t.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),start_date:i.startDate,end_date:i.endDate,duration:i.durationHours,progress:i.progress,type:i.type,calendar_id:i.calendarId,constraint_type:i.constraintType,constraint_date:Af(i,e)})}),r}function Sf(e){let t=new Map;for(let s of e.values()){let o=t.get(s.parent);o?o.push(s):t.set(s.parent,[s])}let r=[],i=new Set,n=[],a=s=>{if(s)for(let o=s.length-1;o>=0;o-=1)n.push(s[o])};for(a(t.get(0));n.length>0;){let s=n.pop();i.has(s)||(i.add(s),r.push(s),a(t.get(s.id)))}if(r.length<e.size)for(let s of e.values())i.has(s)||r.push(s);return r}function Df(e){let t=null,r=null;return e.forEachActivity(i=>{if(i.startDate){let n=i.startDate.getTime();t=t==null?n:Math.min(t,n)}if(i.endDate){let n=i.endDate.getTime();r=r==null?n:Math.max(r,n)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function co(e,t){let r=new Map,i=c=>{let l=c==null?"__default__":String(c),d=r.get(l);if(d)return d;let u=e.calendarReader.getCalendar(String(c)),f=Cf(u);return r.set(l,f),f},n=Df(e);await rt();let a=kf(e);await rt();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await rt();let o=Sf(a);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:c=>a.get(String(c))??null,getLink:c=>{let l=e.getLink(c);return l?{...l,source:Number(l.source),target:Number(l.target),lag:l.lag}:null},getCalendar:i,getChildren:c=>e.getChildren(c).map(l=>Number(l)),eachTask:c=>{for(let l of o)c(l)},getTaskByTime:()=>s,getSubtaskDates:()=>n,refreshData:()=>{}}}var Tf=1e3;async function pr(e,t){let r=await co(e,t),i=new oo(r);if(!await i.calculate(r))return;let a=i.forwardPathCalculations,s=i.backwardPathCalculations,o=i.totalFloat,c=i.freeFloat,l=f=>f==null?null:new Date(f),d=new Set([...a?.keys()??[]]),u=0;for(let f of d){++u>=Tf&&(u=0,await rt());let p=e.getActivity(f);if(!p)continue;let v=a?.get(f),S=s?.get(f),A=o.get(f)??null,D=Number(p.progress??0),m={earlyStart:l(v?.es),earlyFinish:l(v?.ef),lateStart:l(S?.ls),lateFinish:l(S?.lf),totalSlackHours:A},T=String(f);e.setActivityFields(T,{criticalPath:m,isCritical:D<100&&A!=null&&A<=0,freeSlackHours:c.get(f)?.activityFreeFloat??null})}}function hr(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(String(n));if(!a)return 0;let s=[...e.getChildren(String(n))],o;if(s.length===0){let c=pt(a),l=c&&Number(c.cost)||0;o=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of s)c+=i(String(l));o=c}return e.setActivityField(String(n),L.REAL_COST,o),r.push(String(n)),o};for(let n of t)i(n);return r}var lo=new Set(["activity-outdent","activity-indent"]);var uo=new Set(["activity-outdent","activity-indent"]);var Pe=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),_f=new Set(["selection-toggle","selection-replace","visibility-set","sir-sync","activity-lookahead-sync"]);function Pf(e){return e.kind==="inline-edit"?Pe.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Pe.has(t.column)):!1}function po(e,t){return!(_f.has(e.kind)||t.has(e.kind)||Pf(e))}function Ee(e){return po(e,lo)}function Mi(e){return po(e,uo)}function Wi(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===E.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===E.PROGRESS):!1}function Ef(e){return Mi(e)&&Wi(e)}var fo=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function Rf(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?fo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>fo.has(t.column)):!1}var st={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",CRITICAL_PATH:"critical-path"};function ho(e,t,r){let i=new Set;t.ran&&i.add(st.AUTOSCHEDULE),i.add(st.PARENT_BOUNDS),Rf(e)&&i.add(st.PARENT_PROGRESS),Wi(e)&&i.add(st.REAL_WORK);let n=!r.skipAutoSchedule;return n&&Mi(e)&&i.add(st.EXPECTED_PROGRESS),n&&Ef(e)&&i.add(st.REAL_COST),n&&Mi(e)&&Ee(e)&&!r.skipCriticalPath&&i.add(st.CRITICAL_PATH),i}async function Y(e,t){let r=Lf(t),i=r.has(st.AUTOSCHEDULE)?await bf(e,t.autoscheduleFrom):Of();return await xf(e.adapter,t,i.scheduledIds,r),await Nf(e,r,t.now),i}function Lf(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t;return ho(e.action,{requested:t,ran:r},e.options)}async function bf(e,t){let r=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(r),n=wf(e.adapter,i.updatedIds);return ge(e.adapter,i),n}function wf(e,t){let r=[],i=new Map;for(let n of t){let a=String(n);r.push(a);let s=e.getActivity(a);s&&(i.set(a,j(s)),e.noteScheduledBefore(a,s))}return{scheduledIds:r,scheduledBeforeImages:i}}function Of(){return{scheduledIds:[],scheduledBeforeImages:new Map}}async function xf(e,t,r,i){let n=t.collectDirty?t.collectDirty(r):Ss(t.recomputeParentsFrom,r);await ve(e,n,i.has(st.PARENT_PROGRESS),{recomputeRealWork:i.has(st.REAL_WORK)})}async function Nf(e,t,r){t.has(st.EXPECTED_PROGRESS)&&r!==null&&(cr(e.adapter,r,e.defaultBaseCalendarId??null),or(e.adapter,r),Yt(e.adapter,e.sector.statusCriteria)),t.has(st.REAL_COST)&&hr(e.adapter),t.has(st.CRITICAL_PATH)&&await pr(e.adapter,e.sector.hoursPerDay)}var Ff=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),Mf=new Set(["mso","mfo"]);function yr(e){return Ff.has(e)}function mr(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let a=n.constraintType;if(!a||wt.has(a)||Mf.has(a))return!1;let s=Ui(n.startDate),o=Ui(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Wf(t,a,String(n.calendarId??""),i),l=Ui(n.constraintDate);return Uf(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Wf(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?kt(e,n,t):e}function Ui(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Uf(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function gr(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n,scheduledBeforeImages:a}=await Y(e,yo(t)),s=!1;for(let{activityId:o,priorConstraintDate:c}of r){let l=i(o,c);s=s||l}if(s){let o=await Y(e,yo(t));n=Hf(n,o.scheduledIds),a=jf(a,o.scheduledBeforeImages)}return Ee(t.action)&&await Y(e,Bf(t)),{scheduledIds:n,scheduledBeforeImages:a}}function yo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Bf(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Hf(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function jf(e,t){let r=new Map(e);for(let[i,n]of t)r.has(i)||r.set(i,n);return r}function Vf(e,t){let r=i=>i.getTime();return r(e.startDate)!==r(t.startDate)||r(e.endDate)!==r(t.endDate)||e.durationHours!==t.durationHours}function Bi(e,t,r){let i=[];for(let n of r){let a=e.get(n);if(!a)continue;let s=a.pendingRequestIds??[];if(!Jt({pendingRequestIds:s}))continue;let o=t.getActivity(n),c=o==null;if(!c&&!Vf(a,o))continue;let l=c?"activity_deleted":"date_changed";for(let d of s)i.push({kind:"sir-auto-reject",activityId:n,sirId:d,reason:l});c||t.setActivityField(n,"pendingRequestIds",[])}return i}function K(e,t){let r=new Set;for(let l of t.touchedIds)r.add(l);for(let l of t.scheduledIds)r.add(l);if(t.includeAllIds)for(let l of e.getAllIds())r.add(l);let i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n)for(let l of n.dirty){if(r.has(l))continue;let d=n.before.get(l),u=e.getActivity(l);!d||!u||Object.keys(fi(d,u)).length!==0&&(i.set(l,d),r.add(l))}if(t.scheduledBeforeImages)for(let[l,d]of t.scheduledBeforeImages){let u=String(l);i.has(u)||(i.set(u,d),r.add(u))}let a=t.sirDetection==="before-diff"?Bi(i,e,r):[],s=ks(e,i,r),o=t.sirDetection==="after-diff"?Bi(i,e,r):a,c=t.warnings??[];return{source:t.source,activities:s,links:t.links??[],calendars:[],trackingEvents:t.trackingEvents??[],...o.length>0?{effects:o}:{},...c.length>0?{warnings:c}:{}}}function gt(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}function vr(e,t,r){let i=[];for(let{op:n,finalLinkId:a,rejected:s}of e){if(s!==null)continue;if(n.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;i.push({id:String(a),kind:"created",fields:{source:{before:void 0,after:String(d.source)},target:{before:void 0,after:String(d.target)},type:{before:void 0,after:d.type},lag:{before:void 0,after:Number(d.lag)}},after:gt(d)});continue}if(n.kind==="delete"){let d=t.get(n.linkId);i.push({id:String(n.linkId),kind:"deleted",fields:d?{source:{before:String(d.source),after:void 0},target:{before:String(d.target),after:void 0},type:{before:d.type,after:void 0},lag:{before:Number(d.lag),after:void 0}}:void 0,after:null});continue}let o=t.get(n.linkId),c=r.getLink(n.linkId);if(!c)continue;let l={};o&&o.type!==c.type&&(l.type={before:o.type,after:c.type}),o&&Number(o.lag)!==Number(c.lag)&&(l.lag={before:Number(o.lag),after:Number(c.lag)}),i.push({id:String(n.linkId),kind:"updated",fields:l,after:gt(c)})}return i}function le(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let i of e.getIncomingLinkIds(t)){let n=e.getLink(i);n&&r.set(String(n.id),Number(n.lag))}return r}function de(e,t,r){let i=[];if(!t.getActivity(r))return i;for(let n of t.getIncomingLinkIds(r)){let a=t.getLink(n);if(!a)continue;let s=e.get(String(a.id));s===void 0||s===Number(a.lag)||i.push({id:String(a.id),kind:"updated",fields:{lag:{before:s,after:Number(a.lag)}},after:gt(a)})}return i}function Ar(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function mo(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r,o=xt(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);Yf(e.column)&&a.invalidateExpandedLinksCache(),e.column===L.PARENT&&a.invalidateAllCaches();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??R.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??R.PARSE_ERROR};let u=Reflect.get(c,o.targetField),f=o.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??R.INVALID,alertKey:f.notification?.messageKey};if(e.column===E.CUSTOM_ID&&d.value!==null){let _=i.getActivity(e.activityId),b=_?_.customId:null,x=typeof b=="string"?b:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),x))return{ok:!1,reason:R.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,n,d.raw),v=Nt(e.activityId,p),S=J(i,v),A=le(i,String(e.activityId)),D=c.constraintDate;Ft(i,e.activityId,p),bt(e.activityId,p.postProcessors??[],i);let m=de(A,i,String(e.activityId));if(e.column===E.CUSTOM_ID){let _=S.get(String(e.activityId)),b=_?_.customId:null,x=typeof b=="string"?b:null,M=typeof d.value=="string"?d.value:null;x!==M&&r.customIdTracker.trackCustomIdChange(x,M)}let T=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:_=>ar(e.activityId,v,_),now:r.now,options:t}),k=yr(e.column),{scheduledIds:y,scheduledBeforeImages:g}=await(k?gr({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:T(),revertTargets:[{activityId:e.activityId,priorConstraintDate:D}],revert:(_,b)=>mr(_,b,i,n.calendars)}):Y({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},T())),C=(p.trackingEvents??[]).map(_=>({name:_.name,properties:_.properties??{}})),P=oe(e.activityId,p.constraintWarning);return{ok:!0,changes:K(i,{source:e,beforeSnap:S,touchedIds:v,scheduledIds:y,scheduledBeforeImages:g,sirDetection:"before-diff",links:m,trackingEvents:C,...P?{warnings:[P]}:{},hoursPerDay:s.hoursPerDay})}}function Yf(e){return e===E.DURATION||e===L.AUTO_SCHEDULING}async function go(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let i=e.type;if(i!==void 0&&!Object.values(V).some(a=>a===i))return{ok:!1,reason:R.INVALID_LINK_TYPE};let n=e.lag;if(n!==void 0&&!Number.isFinite(n))return{ok:!1,reason:R.INVALID_LINK_LAG}}return Hi([zf(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function vo(e,t,r){let{hoursPerDay:i}=r.sector,n=e.operations.map(s=>Gf(s,i)),a=$f(e.operations);return Hi(n,e,t,r,a)}function $f(e){let t=new Map;return e.forEach((r,i)=>{r.kind==="create"&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function Gf(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:ft(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:ft(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Hi(e,t,r,i,n){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=i;s.invalidateAllCaches();let l=new Set,d=new Map;for(let D of e)if(D.kind==="create")l.add(String(D.source)),l.add(String(D.target));else{let m=a.getLink(D.linkId);m&&(l.add(String(m.source)),l.add(String(m.target)),d.set(D.linkId,{...m}))}let u=J(a,l),f=[];for(let D=0;D<e.length;D++){let m=e[D],T=m.kind==="create"&&n?n.get(D):void 0,k=Rt(m,{port:a,newLinkId:T?()=>T:c.next});f.push({op:m,finalLinkId:k.applied?k.linkId:null,rejected:k.applied?null:k.rejected??"link_op_rejected"})}if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=Kf(f,d,a),{scheduledIds:v}=await Y({adapter:a,scheduler:s,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r});for(let D of v)if(!u.has(D)){let m=a.getActivity(D);m&&u.set(D,j(m))}let S=vr(f,d,a),A=new Map;for(let[D,m]of d)A.set(String(D),m);return{ok:!0,__beforeLinks:A,changes:K(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:v,links:S,hoursPerDay:o.hoursPerDay})}}function Kf(e,t,r){for(let i of e)if(i.rejected===null){if(i.op.kind==="create")return r.hasChildren(i.op.target)?"roots":String(i.op.target);if(i.op.kind==="delete"){let n=t.get(i.op.linkId);if(n)return r.hasChildren(n.target)?"roots":String(n.target)}if(i.op.kind==="update"){let n=r.getLink(i.op.linkId);if(n)return r.hasChildren(n.target)?"roots":String(n.target)}}return null}function zf(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:ft(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:ft(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Ao(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:R.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let s=e.column===E.CUSTOM_PREDECESSORS,{specs:o}=Ge(e.newValue),c=o.map(v=>({...v,lag:ft(v.lag,n.hoursPerDay)})),l=new Map;i.forEachActivity(v=>{v.correlativeId!=null&&l.set(String(v.correlativeId),v.id)});let d=v=>l.get(v)??null,u=s?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let v of u){let S=i.getLink(v);S&&f.push(S)}let p=s?ze({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):qe({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Hi(p.operations,e,t,r)}var yt={ACTIVITY_CREATION:"schedule_activity_creation",ACTIVITY_DELETION:"schedule_activity_deletion",ACTIVITY_MOVE:"schedule_activity_move",ACTIVITY_INDENT:"schedule_activity_indent",ACTIVITY_OUTDENT:"schedule_activity_outdent"};function Vi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0,a=0;for(let c of i){let l=t.getActivity(c);if(!l)continue;let d=ji(l,L.WORK_HOURS),u=qf(c,l,d,t);n+=d,a+=u}t.setActivityField(r,L.WORK_HOURS,n),t.setActivityField(r,L.REAL_WORK_HOURS,a);let s=t.getActivity(r);if(!s)break;let o=s.parentId;if(!o||O(o))break;r=o}}function Co(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||Vi(i,t)}function ji(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function qf(e,t,r,i){return i.hasChildren(e)?ji(t,L.REAL_WORK_HOURS):ct(r,ji(t,L.PROGRESS))}function Yi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Jf(c,L.USED_COST))}t.setActivityField(r,L.USED_COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||O(s))break;r=s}}function Io(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||Yi(i,t)}function Jf(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function $i(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Xf(c,L.COST))}t.setActivityField(r,L.COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||O(s))break;r=s}}function ko(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||$i(i,t)}function Xf(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var Cr=Object.freeze({proplannerId:null,description:"",type:"task",progress:0,constraintType:"asap",constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:[],hasNewActivities:!1,pendingRequestIds:[],responsableIds:[],tagIds:[],baselinePoints:[],baselineSnapshot:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null,promotionRestore:null}),So="New Master Plan",Do="New Activity";var Zf=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],To=new Set(Zf);function Qf(e){let t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let r of Reflect.ownKeys(e))if(typeof r=="symbol"||!To.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function _o(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=Qf(e.activityOverrides??{}),n=e.numTasksInGantt===0?So:Do,a=i.name??n,s=i.durationHours??e.sector.hoursPerDay,o=i.calendarId??e.sector.defaultCalendar,c=tp(r,e.fallbackStartDate,i.startDate),l={...Cr,...i,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:s,calendarId:o,startDate:c,endDate:c},d=i.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:q.FUTURE,task:l}),u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function tp(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function ue(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Et(t.type):ep(t),i=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(s=>String(s)===String(e.newChildId))?[...i]:[...i,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=ei,a.constraintType=$.ASAP,a.constraintDate=null,(e.promotionSource??"create")==="create"&&(a.progress=0,a.expectedProgressBaseline=0)),{parentId:e.parentId,fields:a}}function ep(e){return Et(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Ir(e,t,r,i){let n=t,a=n==="0",s=Gi(e,n);if(i!==void 0){let c=s.find(l=>l.id===i);if(c){let l=nt(c),d=s.map(nt).filter(f=>f<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(r!==void 0){let c=s.find(l=>l.id===r);if(c){let l=nt(c),d=s.map(nt).filter(f=>f>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return s.length===0?0:Math.max(...s.map(nt))+1}var Kt=Number.MAX_SAFE_INTEGER,Po=Number.MAX_SAFE_INTEGER-1;function nt(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Kt}function Gi(e,t){let r=[];return e.forEachActivity(i=>{Bt(i.parentId)===t&&r.push(i)}),r}function Eo(e,t,r){let i=e,n=Wt(e,r);for(;n!=null&&t.has(n);)i=n,n=Wt(n,r);return i}function Wt(e,t){let r=t.getActivity(e);if(!r)return null;let i=Bt(r.parentId),n=$t(i,t),a=n.findIndex(s=>String(s)===String(e));return a<=0?null:n[a-1]??null}function Ro(e,t,r,i){let n=$t(t,e).filter(c=>String(c)!==String(i)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let a=n.map(nt);if(r<=0)return a[0]-1;if(r>=a.length)return a[a.length-1]+1;let s=a[r-1],o=a[r];return(s+o)/2}function kr(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;n.invalidateAllCaches();let l=rp(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=np(e.activityId,i,o),v=c.next(),S={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:lp(s)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:v,activityOverrides:e.overrides??{}},D=_o(S,{getActivity:g=>i.getActivity(g),calculateEndDate:g=>i.calculateEndDate(g),getClosestWorkTime:g=>i.getClosestWorkTime(g)}).newTask;D.realWorkHours=ct(D.workHours,D.progress),sp(D,e,t,u,d,r);let m=Ir(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);D.correlativeId=m;let T=new Set([p]);d&&T.add(d.id);let k=d!==null&&i.getChildren(d.id).length===0,y=r.skipBeforeSnap?new Map:J(i,T);return i.addActivity(D),op(e,p,d,i,r.preserveParentCustomId??!1,k),Co(p,i),Io(p,i),ko(p,i),cp(i,p,y,T,r),{ok:!0,newId:p,parent:d,newActivity:D,beforeSnap:y,initialTouched:T}}function rp(e,t){let r=O(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:R.PARENT_NOT_FOUND};if(i!==null&&Jt(i))return{ok:!1,reason:R.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:R.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=ip(e,t,r,s);return o||{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function ip(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:R.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==a?{ok:!1,reason:R.ANCHOR_SIBLING_WRONG_PARENT}:null}function np(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function ap(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function sp(e,t,r,i,n,a){let{adapter:s,customIdTracker:o}=r,c=ap(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=i??a.customIdReferenceId,d=l!==void 0,u=d?s.getActivity(l):n;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function op(e,t,r,i,n,a){if(!r)return;let s=ue({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:a,getParent:o=>i.getActivity(o)??null});if(s)for(let[o,c]of Object.entries(s.fields))o===L.CUSTOM_ID&&n||Z(i,s.parentId,o,c)}function cp(e,t,r,i,n){if(n.skipCorrelativeRecompute)return;let a=at(e);n.skipBeforeSnap||sr(e,a,new Set([String(t)]),r,i)}function Lo(e,t,r,i,n,a){let{newId:s,newActivity:o,beforeSnap:c,initialTouched:l}=r,d={name:yt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:s,created_duration:o.durationHours}};t.eventSource!==void 0&&(d.properties.event_source=t.eventSource);let u=a?new Map([...a].filter(([f])=>String(f)!==String(s))):void 0;return K(e,{source:t,beforeSnap:c,touchedIds:l,scheduledIds:i,scheduledBeforeImages:u,trackingEvents:[d],hoursPerDay:n})}function bo(e,t){let r=kr(e,t);if(!r.ok)return{ok:!1,reason:r.reason};ai(t.adapter,new Set([r.newId]));let i=t.adapter.getActivity(r.newId);if(!i)throw new Error(`[ScheduleCore] createActivity: new activity ${r.newId} missing after commit`);let n=Lo(t.adapter,e,r,[],t.sector.hoursPerDay);return{ok:!0,activity:i,changes:n}}async function wo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=kr(e,r);if(!s.ok)return s;let{newId:o}=s,c=s.newActivity.autoScheduling;i.setActivityField(o,"autoScheduling",!1);let l;try{l=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[o],now:r.now,options:t})}finally{i.setActivityField(o,"autoScheduling",c)}let{scheduledIds:d,scheduledBeforeImages:u}=l;return{ok:!0,changes:Lo(i,e,s,d,a.hoursPerDay,u)}}function lp(e){for(let r of e.values())if(r.is_default)return r.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function dp(e,t){if("afterSiblingId"in e){let a=t.getActivity(e.afterSiblingId);return a?{ok:!0,parentId:a.parentId==null?"0":String(a.parentId),firstAfter:e.afterSiblingId}:{ok:!1,reason:R.ANCHOR_SIBLING_NOT_FOUND}}let r=e.parentId,n=Gi(t,r).sort((a,s)=>nt(a)-nt(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:n}}function up(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function Oo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=dp(e.destination,i);if(!s.ok)return s;let o=J(i,new Set),c=new Set,l=new Map,d=[],u;for(let m of e.activities){let T=l.get(m.originalParentId),k,y,g;T!==void 0?k=T:(k=s.parentId,u===void 0?(y=s.firstAfter,g=s.firstBefore):y=u);let C=kr({kind:"activity-create",parentId:k,afterSiblingId:y,beforeSiblingId:g,...m.activityId?{activityId:m.activityId}:{},overrides:up(m.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,...T!==void 0?{customIdReferenceId:e.referenceActivityId,preserveParentCustomId:!0}:{}});if(!C.ok)return C;if(m.baselineSnapshot!==void 0){let P=m.baselineSnapshot;i.setActivityField(C.newId,"baselineSnapshot",P?{...P,startDate:P.startDate?new Date(P.startDate):null,endDate:P.endDate?new Date(P.endDate):null}:null)}l.set(m.originalId,C.newId),d.push(C.newId),T===void 0&&(u=C.newId)}let f=at(i),p=new Set(d.map(String));sr(i,f,p,o,c);for(let m of d)c.add(String(m));let v=[];for(let m of e.links){let T=l.get(m.source),k=l.get(m.target);if(T===void 0||k===void 0)continue;let y={kind:"create",source:T,target:k,type:m.type,lag:ft(m.lag,a.hoursPerDay)},g=Rt(y,{port:i,newLinkId:m.linkId?()=>m.linkId:r.linkIdGen.next});v.push({op:y,finalLinkId:g.applied?g.linkId:null,rejected:g.applied?null:g.rejected??"link_op_rejected"})}let{scheduledIds:S,scheduledBeforeImages:A}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:r.now,options:t}),D=vr(v,new Map,i);return{ok:!0,changes:K(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:S,scheduledBeforeImages:new Map([...A].filter(([m])=>!p.has(String(m)))),links:D,hoursPerDay:a.hoursPerDay})}}function xo(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let a=n.pendingRequestIds??[],s=e.pendingRequests.map(c=>c.id);return r.setActivityField(e.activityId,"pendingRequestIds",s),{ok:!0,changes:{source:e,activities:[{id:i,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:{id:i,pendingRequestIds:s}}],links:[],calendars:[],trackingEvents:[]}}}function No(e,t){let r=[...new Set(e.activityIds.map(String))],i=r.map(a=>t.adapter.getActivity(a));if(i.some(a=>!a))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let n=[];for(let[a,s]of r.entries()){let o=i[a];if(!o)continue;let c={};o.isLookahead!==e.isLookahead&&(c.isLookahead={before:o.isLookahead,after:e.isLookahead},t.adapter.setActivityField(s,"isLookahead",e.isLookahead)),o.hasLookaheadTasks!==e.hasLookaheadTasks&&(c.hasLookaheadTasks={before:o.hasLookaheadTasks,after:e.hasLookaheadTasks},t.adapter.setActivityField(s,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(c).length!==0&&n.push({id:s,kind:"updated",fields:c,after:{...o,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return{ok:!0,changes:{source:e,activities:n,links:[],calendars:[],trackingEvents:[]}}}function Tt(e,t){Vi(e,t),Yi(e,t),$i(e,t)}function Fo(e,t){let r=new Set,i=[];for(let n of e){let a=String(n);r.has(a)||(r.add(a),i.push(a))}for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);for(let s of a){let o=String(s);r.has(o)||(r.add(o),i.push(o))}}return r}function Mo(e,t){let r=new Set;for(let i of e){for(let n of t.getOutgoingLinkIds(i))r.add(String(n));for(let n of t.getIncomingLinkIds(i))r.add(String(n))}return[...r]}function fp(e){let t=e.promotionRestore;return typeof t!="object"||t===null||t.type!=="task"&&t.type!=="milestone"?null:{type:t.type,startDate:new Date(t.startDate),endDate:new Date(t.endDate),durationHours:t.durationHours,expectedProgressBaseline:t.expectedProgressBaseline,constraintType:t.constraintType,constraintDate:t.constraintDate?new Date(t.constraintDate):null,progress:t.progress,promotionRestore:null}}function fe(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=fp(t)??(i?{type:Zt,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,promotionRestore:null}:{type:Zt});if(e.idsRemoved&&e.idsRemoved.size>0){let a=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(a.length>0){let s=a.filter(o=>!e.idsRemoved.has(o)&&!e.idsRemoved.has(String(o)));s.length!==a.length&&(n.newActivityIds=s)}}return t.hasLookaheadTasks&&(n.isLookahead=!0),{parentId:String(t.id),fields:n}}function Wo(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let r=t,i=r.filter(n=>!e.idsRemoved.has(n)&&!e.idsRemoved.has(String(n)));return i.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...i],hasNewActivities:i.length>0}}}async function Uo(e,t,r){let{adapter:i,scheduler:n,customIdTracker:a,sector:s}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:R.ACTIVITY_IDS_EMPTY};for(let g of e.activityIds)if(!i.getActivity(g))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let o=Fo(e.activityIds,i),c=Mo(o,i),l=new Set;for(let g of e.activityIds){let C=i.getActivity(g);if(!C)continue;let P=C.parentId;if(O(P))continue;let _=String(P);o.has(_)||l.add(_)}let d=new Set([...o,...l]),u=J(i,d),f=new Map;for(let g of c){let C=i.getLink(g);C&&f.set(g,{...C})}let p=new Set;for(let g of o){let C=i.getActivity(g);if(!C)continue;let P=O(C.parentId)?null:i.getActivity(String(C.parentId)),_=P?.hasNewActivities===!0&&P.newActivityIds.some(x=>String(x)===String(g));(C.isNewActivity===!0||_)&&p.add(g);let b=C.customId;typeof b=="string"&&b.length>0&&a.releaseCustomId(b)}for(let g of c)i.removeLink(g);let v=hp(i,o);for(let g of o)i.removeActivity(g);for(let g of l){let C=i.getActivity(g);if(!C)continue;pp(C,p,i);let P=i.getChildren(g),_=fe({parent:C,remainingChildIds:P.map(String),defaultDurationHours:s.hoursPerDay,idsRemoved:o});if(!_){Ze(g,i);continue}for(let[b,x]of Object.entries(_.fields))Z(i,g,b,x);if(C.customId==null||C.customId===""){let b=Wt(g,i),x=b?i.getActivity(b)?.customId:null,M=a.generateCustomIdForRestoredChild(typeof x=="string"&&x?x:null);i.setActivityField(g,L.CUSTOM_ID,M)}}for(let g of l)Tt(g,i);let S=at(i);for(let g of S){if(d.add(g.activityId),u.has(g.activityId))continue;let C=i.getActivity(g.activityId);if(!C)continue;let P=j(C);g.before!==void 0&&(P.correlativeId=g.before),u.set(g.activityId,P)}let{scheduledIds:A,scheduledBeforeImages:D}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),m={name:yt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(m.properties.event_source=e.eventSource);let T=new Map;for(let[g,C]of f)T.set(g,C);let k=new Map;for(let g of o){let C=u.get(String(g));C&&k.set(String(g),C)}let y=K(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:A,scheduledBeforeImages:D,sirDetection:"after-diff",links:yp(f),trackingEvents:[m],hoursPerDay:s.hoursPerDay});return{ok:!0,changes:v.length>0?{...y,viewState:v}:y,__beforeSnap:k,__beforeLinks:T}}function pp(e,t,r){let i=Wo({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))Z(r,i.parentId,n,a)}function hp(e,t){let r=[];for(let i of t){let n=e.isChecked(i),a=e.isVisible(i);!n&&a||r.push({activityId:String(i),...n?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return r}function yp(e){let t=[];for(let[r,i]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(i.source),after:void 0},target:{before:String(i.target),after:void 0},type:{before:i.type,after:void 0},lag:{before:Number(i.lag),after:void 0}},after:null});return t}function Sr(e,t){let r=new Set;for(let n of e)r.add(String(n));let i=[];for(let n of t.getAllLinks()){let a=String(n.source),s=String(n.target);!r.has(a)&&!r.has(s)||(Bo(s,a,t)||Bo(a,s,t))&&i.push(String(n.id))}return i}function Bo(e,t,r){let i=String(e),n=new Set;for(;i!=null;){if(n.has(i))return!1;n.add(i);let a=r.getActivity(i);if(!a)return!1;let s=a.parentId;if(s===null||O(s))return!1;let o=s;if(o===t)return!0;i=o}return!1}async function Ho(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;n.invalidateAllCaches();let s=i.getActivity(e.activityId);if(!s)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let o=O(e.parentId);if(!o&&!i.getActivity(e.parentId))return{ok:!1,reason:R.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:R.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:R.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let y=i.getActivity(c);if(!y)return{ok:!1,reason:R.ANCHOR_SIBLING_NOT_FOUND};if((y.parentId===null?"0":String(y.parentId))!==e.parentId)return{ok:!1,reason:R.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=Bt(l),u=String(e.parentId),f=d!==u,p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let v=J(i,p);f&&i.setActivityField(e.activityId,L.PARENT,u);let S=Ir(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,L.CORRELATIVE_ID,S),f){if(!o){let y=i.getActivity(e.parentId);if(y){let g=y.customId,C=Et(y.type)&&i.getChildren(e.parentId).filter(_=>_!==e.activityId).length===0,P=ue({parentId:e.parentId,newChildId:e.activityId,getParent:_=>i.getActivity(_)??null,isCurrentlyLeaf:C,promotionSource:"reparent"});if(P){for(let[_,b]of Object.entries(P.fields))Z(i,P.parentId,_,b);P.fields.customId===null&&Ar(g,r.customIdTracker)}}}if(d!=="0"){let y=i.getActivity(d);if(y){let g=i.getChildren(d),C=fe({parent:y,remainingChildIds:g.map(String),defaultDurationHours:a.hoursPerDay,idsRemoved:new Set([e.activityId])});if(C){for(let[M,z]of Object.entries(C.fields))Z(i,d,M,z);let P=Wt(d,i),_=P?i.getActivity(P)?.customId:null,b=typeof _=="string"&&_?_:null,x=r.customIdTracker.generateCustomIdForRestoredChild(b);i.setActivityField(d,L.CUSTOM_ID,x)}}}}f&&(d!=="0"&&Tt(d,i),o||Tt(e.parentId,i));let A=at(i);for(let y of A){if(p.add(y.activityId),v.has(y.activityId))continue;let g=i.getActivity(y.activityId);if(!g)continue;let C=j(g);y.before!==void 0&&(C.correlativeId=y.before),v.set(y.activityId,C)}let{scheduledIds:D,scheduledBeforeImages:m}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId],now:r.now,options:t}),T=f?Sr([e.activityId],i):[],k={name:yt.ACTIVITY_MOVE,properties:{activity_id:e.activityId,new_parent_id:e.parentId,after_sibling_id:e.afterSiblingId??null,before_sibling_id:e.beforeSiblingId??null,invalid_link_ids:T.map(String)}};return e.eventSource!==void 0&&(k.properties.event_source=e.eventSource),{ok:!0,changes:K(i,{source:e,beforeSnap:v,touchedIds:p,scheduledIds:D,scheduledBeforeImages:m,sirDetection:"before-diff",trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function jo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:R.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Set,c=[],l=[],d=[],u=new Set(s),f=[...e.activityIds].sort((y,g)=>{let C=i.getActivity(y),P=i.getActivity(g),_=C?nt(C):Kt,b=P?nt(P):Kt;return _-b});for(let y of f){if(!i.getActivity(y)){c.push({activityId:y,reason:R.ACTIVITY_NOT_FOUND}),u.delete(y);continue}let C=Rs(y,u,i);if(C==null){c.push({activityId:y,reason:R.INDENT_NO_ELIGIBLE_SIBLING}),u.delete(y);continue}let P=i.getActivity(y)?.parentId,_=O(P)?"0":String(P);d.push({activityId:y,newParentId:C,oldParentId:_}),o.add(y),o.add(C),_!=="0"&&o.add(_)}let p=J(i,o);for(let{activityId:y,newParentId:g}of d)i.setActivityField(y,L.PARENT,g),i.setActivityField(y,L.CORRELATIVE_ID,Po),l.push(y);let v=new Set;for(let{activityId:y,newParentId:g}of d){if(v.has(g))continue;v.add(g);let C=i.getActivity(g);if(!C)continue;let P=C.customId,_=Et(C.type)&&i.getChildren(g).filter(M=>!l.includes(M)).length===0,b=C.hasNewActivities&&C.newActivityIds.some(M=>String(M)===String(y)),x=ue({parentId:g,newChildId:y,getParent:M=>i.getActivity(M)??null,isCurrentlyLeaf:_,promotionSource:"reparent"});if(x){for(let[M,z]of Object.entries(x.fields))Z(i,x.parentId,M,z);b||(i.setActivityField(g,L.HAS_NEW_ACTIVITIES,!1),i.setActivityField(g,L.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(g,L.CONSTRAINT_TYPE,"asap"),i.setActivityField(g,L.CONSTRAINT_DATE,null),i.setActivityField(g,L.CUSTOM_ID,null),Ar(P,r.customIdTracker)}let S=new Set;for(let y of d)y.oldParentId!=="0"&&S.add(y.oldParentId),S.add(y.newParentId);for(let y of S)Tt(y,i);let A=at(i);for(let y of A){if(o.add(y.activityId),p.has(y.activityId))continue;let g=i.getActivity(y.activityId);if(!g)continue;let C=j(g);y.before!==void 0&&(C.correlativeId=y.before),p.set(y.activityId,C)}let{scheduledIds:D,scheduledBeforeImages:m}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),T=Sr(l,i),k={name:yt.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(y=>({activity_id:y.activityId,reason:y.reason})),invalid_link_ids:T}};return e.eventSource!==void 0&&(k.properties.event_source=e.eventSource),{ok:!0,changes:K(i,{source:e,beforeSnap:p,touchedIds:o,scheduledIds:D,scheduledBeforeImages:m,trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function Vo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:R.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let y of e.activityIds){let g=y;i.getActivity(g)&&(o.set(g,hi(g,i)),c.set(g,Eo(g,s,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],v=[...e.activityIds].sort((y,g)=>{let C=i.getActivity(y),P=i.getActivity(g),_=C?nt(C):Kt,b=P?nt(P):Kt;return _-b});for(let y of v){let g=y,C=i.getActivity(g);if(!C){d.push({activityId:g,reason:R.ACTIVITY_NOT_FOUND});continue}let P=C.parentId;if(O(P)){d.push({activityId:g,reason:R.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let _=String(P),b=i.getActivity(_);if(!b){d.push({activityId:g,reason:R.ACTIVITY_NOT_FOUND});continue}let x=b.parentId;if(O(x)){d.push({activityId:g,reason:R.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let M=String(x),z=hi(_,i)+1,ot=c.get(g);if(ot!=null&&s.has(ot)){let Oe=o.get(ot)??-1,Ut=o.get(g)??-1;Oe>=0&&Ut>=0&&(z+=Ut-Oe)}p.push({activityId:g,grandparentKey:M,oldParentKey:_,targetIndexInGrandparent:z}),l.add(String(g)),l.add(String(_)),M!=="0"&&l.add(String(M)),f.add(_)}let S=J(i,l);for(let y of p){i.setActivityField(y.activityId,L.PARENT,y.grandparentKey);let g=Ro(i,y.grandparentKey,y.targetIndexInGrandparent,y.activityId);i.setActivityField(y.activityId,L.CORRELATIVE_ID,g),u.push(y.activityId)}for(let y of f){let g=i.getActivity(y);if(!g)continue;let C=i.getChildren(y),P=fe({parent:g,remainingChildIds:C.map(String),defaultDurationHours:a.hoursPerDay,idsRemoved:new Set(p.filter(z=>z.oldParentKey===y).map(z=>z.activityId))});if(!P){Ze(y,i);continue}for(let[z,ot]of Object.entries(P.fields))Z(i,y,z,ot);let _=Wt(y,i),b=_?i.getActivity(_)?.customId:null,x=typeof b=="string"&&b?b:null,M=r.customIdTracker.generateCustomIdForRestoredChild(x);i.setActivityField(y,L.CUSTOM_ID,M)}let A=new Set;for(let y of f)A.add(String(y));for(let y of p)y.grandparentKey!=="0"&&A.add(String(y.grandparentKey));for(let y of A)Tt(y,i);let D=at(i);for(let y of D){if(l.add(y.activityId),S.has(y.activityId))continue;let g=i.getActivity(y.activityId);if(!g)continue;let C=j(g);y.before!==void 0&&(C.correlativeId=y.before),S.set(y.activityId,C)}let{scheduledIds:m,scheduledBeforeImages:T}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:r.now,options:t}),k={name:yt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(y=>({activity_id:String(y.activityId),reason:y.reason}))}};return e.eventSource!==void 0&&(k.properties.event_source=e.eventSource),{ok:!0,changes:K(i,{source:e,beforeSnap:S,touchedIds:l,scheduledIds:m,scheduledBeforeImages:T,trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function Yo(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:R.INVALID_PROGRESS_VALUE};let o=n.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let c=xt(E.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.transform(o,e.newValue,n,e.newValue),d=Nt(e.activityId,l),u=J(i,d);Ft(i,e.activityId,l),bt(e.activityId,l.postProcessors??[],i);let{scheduledIds:f}=await Y({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:l.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:v=>ar(e.activityId,d,v),now:r.now,options:t}),p=(l.trackingEvents??[]).map(v=>({name:v.name,properties:v.properties??{}}));return{ok:!0,changes:K(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:p,hoursPerDay:s.hoursPerDay})}}async function $o(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=[],o=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let v of e.edits){let S=mp(v,r);if(s.push(S.verdict),!S.verdict.ok||!S.changes)continue;let A=Nt(v.activityId,S.changes);gp(o,A,r);for(let T of A)c.add(T);let D=le(i,v.activityId);Ft(i,v.activityId,S.changes),bt(v.activityId,S.changes.postProcessors??[],i),d.push(...de(D,i,v.activityId)),f||=!!S.changes.needsAutoSchedule;for(let T of S.changes.trackingEvents??[])l.push({name:T.name,properties:T.properties??{}});let m=oe(v.activityId,S.changes.constraintWarning);m&&u.push(m)}let{scheduledIds:p}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?"roots":null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:s,changes:K(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function mp(e,t){let{ctx:r}=t,i=e.activityId,n=xt(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let a=r.activityReader.getActivity(e.activityId);if(!a)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??R.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??R.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??R.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function gp(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let[n,a]of J(r.adapter,i))e.set(n,a)}var Ki=E.CUSTOM_ID;async function Go(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;e.edits.some(T=>T.column===E.DURATION)&&n.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=[],f=[],p=[],v=!1;for(let T of e.edits){let k=vp(T,r);if(o.push(k.verdict),!k.verdict.ok||!k.changes)continue;let y=oe(T.activityId,k.changes.constraintWarning);y&&p.push(y);let g=Nt(T.activityId,k.changes);kp(c,g,r);for(let b of g)d.add(b);Ip(l,T,c);let C=le(i,T.activityId),P=Ap(T,r),_=k.changes;Ft(i,T.activityId,_),bt(T.activityId,k.changes.postProcessors??[],i),Cp(T,P,r),f.push(...de(C,i,T.activityId)),v||=!!k.changes.needsAutoSchedule;for(let b of k.changes.trackingEvents??[])u.push({name:b.name,properties:b.properties??{}})}let S={action:e,autoscheduleFrom:v?"roots":null,recomputeParentsFrom:d,now:r.now,options:t},A=l.size>0,{scheduledIds:D,scheduledBeforeImages:m}=await(A?gr({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:S,revertTargets:[...l].map(([T,k])=>({activityId:T,priorConstraintDate:k})),revert:(T,k)=>mr(T,k,i,r.ctx.calendars)}):Y({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},S));return{ok:!0,verdicts:o,changes:K(i,{source:e,beforeSnap:c,touchedIds:d,scheduledIds:D,scheduledBeforeImages:m,sirDetection:"before-diff",links:f,trackingEvents:u,warnings:p,hoursPerDay:a.hoursPerDay})}}function vp(e,t){let{ctx:r}=t,i=e.activityId,n=xt(e.column);if(!n)return{verdict:{activityId:i,ok:!1,reason:R.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:i,ok:!1,reason:R.ACTIVITY_NOT_FOUND},changes:null};let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??R.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??R.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??R.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===Ki&&o.value!==null){let u=t.adapter.getActivity(e.activityId),f=u?u.customId:null,p=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(o.value),p))return{verdict:{activityId:i,ok:!1,reason:R.CUSTOM_ID_DUPLICATE},changes:null}}let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function Ap(e,t){if(e.column!==Ki)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function Cp(e,t,r){if(e.column!==Ki)return;let i=r.adapter.getActivity(e.activityId),n=i?i.customId:null,a=typeof n=="string"?n:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function Ip(e,t,r){if(!yr(t.column))return;let i=String(t.activityId);if(e.has(i))return;let n=r.get(i);n&&e.set(i,n.constraintDate??null)}function kp(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let[n,a]of J(r.adapter,i))e.set(n,a)}async function Ko(e,t,r){return e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?go(e,t,r):e.kind==="links-batch"?vo(e,t,r):e.kind==="activity-create"?wo(e,t,r):e.kind==="activity-paste"?Oo(e,t,r):e.kind==="activity-delete"?Uo(e,t,r):e.kind==="activity-move"?Ho(e,t,r):e.kind==="activity-indent"?jo(e,t,r):e.kind==="activity-outdent"?Vo(e,t,r):e.kind==="activity-set-progress"?Yo(e,t,r):e.kind==="dates-batch"?$o(e,t,r):e.kind==="bulk-edit"?Go(e,t,r):e.kind==="selection-toggle"?kn(e,zi(r)):e.kind==="selection-replace"?Sn(e,zi(r)):e.kind==="visibility-set"?Dn(e,zi(r)):e.kind==="sir-sync"?xo(e,r):e.kind==="activity-lookahead-sync"?No(e,r):e.kind==="inline-edit"&&(e.column===E.CUSTOM_PREDECESSORS||e.column===E.CUSTOM_SUCESSORS)?Ao(e,t,r):e.kind!=="inline-edit"?la(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):mo(e,t,r)}function zi(e){return{adapter:e.adapter}}function zo(e,t){return e.getActivity(t)}function qo(e){return e.getAllActivities()}function Jo(e){return e.getAllIds().map(String)}function Xo(e,t){e.forEachActivity((r,i)=>t(i))}function Zo(e,t){let r=t==="0"?qi(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(a)}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function qi(e,t){let r=t;if(r==="0"){let i=[];return e.forEachActivity((n,a)=>{O(n.parentId)&&i.push(a)}),i}return[...e.getChildren(r)].map(String)}function Qo(e){return e.checkedIds().map(String)}function tc(e,t){return e.getChildren(t).length>0}function ec(e,t){let r=e.getLink(t);return r?gt(r):null}function rc(e){return e.getAllLinks().map(t=>gt(t))}function ic(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,a=0;for(let o of i){let c=Sp(String(o),t,r);n.set(String(o),c),a+=c}let s=a?100/a:0;for(let o of i){let c=r.getActivity(o);if(!c)continue;let l=c.baselinePoints;if(pt(c)){let u=n.get(String(o))??0;r.setActivityField(o,E.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,E.PONDERATOR,0)}}function Sp(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=pt(i);if(!n)return 0;if(t==="COST")return Dr(n.cost);if(t==="HH")return Dr(n.workHours);let a=i.type;return a==="project"?nc(e,r):a==="milestone"?0:Dr(n.durationDays)}function nc(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=pt(n);if(!a)continue;let s=n.type;s==="project"?r+=nc(String(i),t):s!=="milestone"&&(r+=Dr(a.durationDays))}return r}function Dr(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Tr(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,E.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&ic(String(i),e,t)})}function _r(e){for(let t of Dp(e))_p(t,e)}function Dp(e){let t=new Set;e.forEachActivity((i,n)=>{e.getChildren(n).length>0&&t.add(n)});let r=new Map;for(let i of t)r.set(i,Tp(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function Tp(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function _p(e,t){let r=t.getChildren(e);if(r.length===0)return;let i=[];for(let a of r){let s=t.getActivity(a);s&&i.push({progress:Number(s.progress??0),ponderator:Number(s.ponderator??0)})}let n=te(i);n!==null&&t.setActivityField(e,E.PROGRESS,Xe(n))}function ac(e){return typeof e=="string"&&e.length>0?Dt(e):e instanceof Date?e:null}function Ji(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function Pr(e,t){let r=Ji(e.duration),i=Ji(e.cost),n=Ji(e.hh_work);return r===null||i===null||n===null?(t.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(e.duration)}, cost=${JSON.stringify(e.cost)}, hh_work=${JSON.stringify(e.hh_work)}`),null):{startDate:ac(e.start_date),endDate:ac(e.end_date),durationDays:r,cost:i,workHours:n,versionId:typeof e.sectorbaselineversionId=="number"?e.sectorbaselineversionId:null,isActiveVersion:!!e.sectorbaselineversion?.active,baseCalendarId:e.baseCalendarId!=null?String(e.baseCalendarId):null,hoursPerDay:typeof e.hoursPerDay=="number"?e.hoursPerDay:null,hoursPerWeek:typeof e.hoursPerWeek=="number"?e.hoursPerWeek:null}}function Er(e,t,r){let i=new Map;e.forEachActivity((s,o)=>{let c=s.proplannerId;typeof c=="number"&&i.set(c,o)});let n=new Map;for(let s of t){let o=s.activityId;if(typeof o!="number")continue;let c=i.get(o);if(c===void 0)continue;let l=n.get(c);l?l.push(s):n.set(c,[s])}let a=[];for(let[s,o]of n)e.setActivityField(s,"baselinePoints",o.map(c=>Pr(c,r)).filter(c=>c!==null)),a.push(s);return e.forEachActivity((s,o)=>{if(n.has(o))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(o,"baselinePoints",[]),a.push(o))}),a}function Pp(e){let t=pt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function sc(e){let t=[];return e.forEachActivity((r,i)=>{let n=Pp(r);n&&(e.setActivityField(i,"baselineSnapshot",n),t.push(i))}),t}function Rr(e,t,r,i,n=null){if(t.length===0)return[];let a=new Set;for(let s of Er(e,t,i))a.add(s);if(r)for(let s of cr(e,r,n))a.add(s);for(let s of sc(e))a.add(s);for(let s of hr(e))a.add(s);return[...a]}function oc(e){let t=e.ponderator;return typeof t=="number"&&Number.isFinite(t)?t:0}function cc(e){let t=e.progress;return typeof t=="number"&&Number.isFinite(t)?t:0}function lc(e,t,r){let i=new Map;e.forEachActivity((a,s)=>{i.set(s,oc(a))}),Tr(r,e);let n=[];return e.forEachActivity((a,s)=>{oc(a)!==(i.get(s)??0)&&n.push(j(a))}),n}function dc(e,t){let r=new Map;e.forEachActivity((n,a)=>{r.set(a,cc(n))}),_r(e);let i=[];return e.forEachActivity((n,a)=>{cc(n)!==(r.get(a)??0)&&i.push(j(n))}),i}function uc(e,t,r,i,n,a=null){let s=Rr(e,r,i,n,a),o=[];for(let c of s){let l=e.getActivity(c);l&&o.push(j(l))}return o}function fc(e,t,r){let i=[];for(let n of Yt(e,r)){let a=e.getActivity(n);a&&i.push(j(a))}return i}function Lr(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Ep(e){return e.reduce((t,r)=>Lr(r)<Lr(t)?r:t)}function Rp(e){return e.reduce((t,r)=>Lr(r)>Lr(t)?r:t)}function Lp(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function pc(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=Lp(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:Ep(i),endHour:Rp(n)}}function hc(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?bp(n,r):null}}}function bp(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,i){return e.calculateEndDate({start_date:r,duration:i,unit:t})},calculateDuration(r,i){return e.calculateDuration({start_date:r,end_date:i,unit:t})},isWorkTime(r,i){return e.isWorkTime({date:r,unit:i})},getWorkHours(r){return e.getWorkHours(r)}}}function wp(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function zt(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function qt(e){return zt(e)&&!isNaN(e.getTime())}var Op={}.constructor.toString();function xp(e){var t=e.constructor.toString();return t!==Op}function Np(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function vt(e){var t,r;if(e&&typeof e=="object")switch(!0){case zt(e):r=new Date(e);break;case wp(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=vt(e[t]);break;default:if(xp(e))r=Object.create(e);else{if(Np(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=vt(e[t]));break}return r||e}function pe(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function yc(e){return typeof e<"u"}var br;function Xi(){return br||(br=new Date().valueOf()),br++,br}function dt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var Mp=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return`"+to_fixed(date.get${t?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${t?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${t?"UTC":""}Date()+"`;case"%n":return`"+(date.get${t?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${t?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${t?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${t?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${t?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${t?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${t?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${t?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${t?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${t?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${t?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${t?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${t?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return n}});let i=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return n=>i(n,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},Wp=(e,t,r)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",n=e.match(/%[a-zA-Z]/g);for(let o=0;o<n.length;o++)switch(n[o]){case"%j":case"%d":i+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":i+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":i+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":i+=`set[3]=temp[${o}]||0;`;break;case"%i":i+=`set[4]=temp[${o}]||0;`;break;case"%Y":i+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":i+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":i+=`set[5]=temp[${o}]||0;`;break;case"%M":i+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":i+=`set[1]=locale.date.month_full_hash[temp[${o}]]||0;`;break}let a="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(a=` Date.UTC(${a})`);let s=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${a});`);return o=>s(o,r.locale)},mc={date_to_str:Mp,str_to_date:Wp},Up=(e,t,r)=>i=>e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return t?r.date.to_fixed(i.getUTCDate()):r.date.to_fixed(i.getDate());case"%m":return t?r.date.to_fixed(i.getUTCMonth()+1):r.date.to_fixed(i.getMonth()+1);case"%j":return t?i.getUTCDate():i.getDate();case"%n":return t?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return t?r.date.to_fixed(i.getUTCFullYear()%100):r.date.to_fixed(i.getFullYear()%100);case"%Y":return t?i.getUTCFullYear():i.getFullYear();case"%D":return t?r.locale.date.day_short[i.getUTCDay()]:r.locale.date.day_short[i.getDay()];case"%l":return t?r.locale.date.day_full[i.getUTCDay()]:r.locale.date.day_full[i.getDay()];case"%M":return t?r.locale.date.month_short[i.getUTCMonth()]:r.locale.date.month_short[i.getMonth()];case"%F":return t?r.locale.date.month_full[i.getUTCMonth()]:r.locale.date.month_full[i.getMonth()];case"%h":return t?r.date.to_fixed((i.getUTCHours()+11)%12+1):r.date.to_fixed((i.getHours()+11)%12+1);case"%g":return t?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return t?i.getUTCHours():i.getHours();case"%H":return t?r.date.to_fixed(i.getUTCHours()):r.date.to_fixed(i.getHours());case"%i":return t?r.date.to_fixed(i.getUTCMinutes()):r.date.to_fixed(i.getMinutes());case"%a":return t?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return t?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(i.getUTCSeconds()):r.date.to_fixed(i.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(i)):r.date.to_fixed(r.date.getISOWeek(i));case"%w":return r.date.to_fixed(r.date.getWeek(i));default:return n}}),Bp=(e,t,r)=>i=>{let n=[0,0,1,0,0,0],a=i.match(/[a-zA-Z]+|[0-9]+/g),s=e.match(/%[a-zA-Z]/g);for(let o=0;o<s.length;o++)switch(s[o]){case"%j":case"%d":n[2]=a[o]||1;break;case"%n":case"%m":n[1]=(a[o]||1)-1;break;case"%y":n[0]=a[o]*1+(a[o]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":n[3]=a[o]||0;break;case"%i":n[4]=a[o]||0;break;case"%Y":n[0]=a[o]||0;break;case"%a":case"%A":n[3]=n[3]%12+((a[o]||"").toLowerCase()==="am"?0:12);break;case"%s":n[5]=a[o]||0;break;case"%M":n[1]=r.locale.date.month_short_hash[a[o]]||0;break;case"%F":n[1]=r.locale.date.month_full_hash[a[o]]||0;break}return t?new Date(Date.UTC(n[0],n[1],n[2],n[3],n[4],n[5])):new Date(n[0],n[1],n[2],n[3],n[4],n[5])},gc={date_to_str:Up,str_to_date:Bp};function vc(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function r(o){var c=new Date(o);return isNaN(c.getTime())?null:c}var i=null;function n(){try{new Function("canUseCsp = false;")}catch{i=!0}}function a(){var o=!1;return e.config.csp==="auto"?(i===null&&n(),o=i):o=e.config.csp,o}var s={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(o){return o.toISOString()},formatISODateOnly:function(o){return o.getUTCFullYear()+"-"+e.date.to_fixed(o.getUTCMonth()+1)+"-"+e.date.to_fixed(o.getUTCDate())},init:function(){for(var o=e.locale,l=o.date.month_short,d=o.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=o.date.month_full,d=o.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(o){return o.setUTCHours(0,0,0,0),o},time_part:function(o){return o.valueOf()/1e3%86400},week_start:function(o){var c=o.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(o,-1*c,"day"))},month_start:function(o){return o.setUTCDate(1),this.date_part(o)},quarter_start:function(o){this.month_start(o);var c=o.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,o.setUTCMonth(l),o},year_start:function(o){return o.setUTCMonth(0),this.month_start(o)},day_start:function(o){return this.date_part(o)},hour_start:function(o){return o.getUTCMinutes()&&o.setUTCMinutes(0),this.minute_start(o),o},minute_start:function(o){return o.getUTCSeconds()&&o.setUTCSeconds(0),o.getUTCMilliseconds()&&o.setUTCMilliseconds(0),o},_add_days:function(o,c,l){return o.setUTCDate(o.getUTCDate()+c),o},add:function(o,c,l){var d=new Date(o.valueOf());switch(l){case"day":d=this._add_days(d,c,o);break;case"week":d=this._add_days(d,c*7,o);break;case"month":d.setUTCMonth(d.getUTCMonth()+c);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+c);break;case"hour":d.setTime(d.getTime()+c*60*60*1e3);break;case"minute":d.setTime(d.getTime()+c*60*1e3);break;default:return this["add_"+l](o,c,l)}return d},add_quarter:function(o,c){return this.add(o,c*3,"month")},to_fixed:function(o){return o<10?"0"+o:o},copy:function(o){return new Date(o.valueOf())},date_to_str:function(o,c){var l=mc;return a()&&(l=gc),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=mc;return a()&&(l=gc),l.str_to_date(o,c,e)},getISOWeek:function(o){return e.date._getWeekNumber(o,!0)},_getWeekNumber:function(o,c){if(!o)return!1;var l=o.getUTCDay();c&&l===0&&(l=7);var d=new Date(o.valueOf());d.setUTCDate(o.getUTCDate()+(4-l));var u=d.getUTCFullYear(),f=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),p=1+Math.floor(f/7);return p},getWeek:function(o){return e.date._getWeekNumber(o,e.config.start_on_monday)},getUTCISOWeek:function(o){return e.date.getISOWeek(o)},parseDate:function(o,c){if(o&&!o.getFullYear){var l=!c||c==="parse_date"||c==="xml_date",d=l&&(e.defined(e.templates.xml_date)||e.templates.parse_date&&!e.templates.parse_date._ganttAuto);if(!d&&typeof o=="string"&&t.test(o)){var u=o.indexOf("T")!==-1,f=r(o);if(f)return s._isoDateDetected?u&&(s._isoDateOnly=!1):(s._isoDateDetected=!0,s._isoDateOnly=!u),f}typeof c!="function"&&(typeof c=="string"?c==="parse_date"||c==="xml_date"?c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date:c=e.defined(e.templates[c])?e.templates[c]:e.date.str_to_date(c,!0):c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date),o?o=c(o):o=null}return o}};return s}function Zi(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function Qi(e,t,r,i,n,a){return this.date=e,this.dir=t,this.unit=r,this.task=i,this.id=n,this.calendar=a,this}function tn(e,t,r,i,n,a,s){return this.start_date=e,this.duration=t,this.unit=r,this.step=i,this.task=n,this.id=a,this.calendar=s,this}function Hp(e,t,r,i){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=i,this.unit=null,this.step=null,this}var Ac=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(zt(t)?t={date:t}:t=pe({},t),!qt(t.date))throw e.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return t},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var t=arguments[0];if(t instanceof Zi)return t;var r;if(t.date?r=new Zi(t.date,t.unit,t.task,null,t.calendar):r=new Zi(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!qt(r.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return r},getClosestWorkTimeArguments:function(t){var r=arguments[0];if(r instanceof Qi)return r;var i;if(zt(r)?i=new Qi(r):i=new Qi(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(i.task=r),i.dir=r.dir||"any",i.unit=r.unit||e.config.duration_unit,!qt(i.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return i},_getStartEndConfig:function(t){var r=Hp,i;if(t instanceof r)return t;if(zt(t)?i=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(i=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(i.task=t)),i.unit=i.unit||e.config.duration_unit,i.step=i.step||e.config.duration_step,i.start_date=i.start_date||i.start||i.date,!qt(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!qt(i.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return i},getDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,i,n){var a=arguments[0];if(a instanceof tn)return a;var s;if(zt(a)?s=new tn(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new tn(a.start_date,a.duration,a.unit,a.step,a.task,null,a.calendar),a.id!==null&&a.id!==void 0&&(s.task=a,s.unit=null,s.step=null),s.unit=s.unit||e.config.duration_unit,s.step=s.step||e.config.duration_step,!qt(s.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return s}}};function Cc(){}Cc.prototype={_getIntervals:function(e){for(var t=[],r=0;r<e.length;r+=2)t.push({start:e[r],end:e[r+1]});return t},_toHoursArray:function(e){var t=[];function r(a){var s=String(a);return s.length<2&&(s="0"+s),s}function i(a){var s=Math.floor(a/3600),o=a-s*60*60,c=Math.floor(o/60);return s+":"+r(c)}for(var n=0;n<e.length;n++)t.push(i(e[n].start)+"-"+i(e[n].end));return t},_intersectHourRanges:function(e,t){var n=[],r=e.length>t.length?e:t,i=e===r?t:e;r=r.slice(),i=i.slice();for(var n=[],a=0;a<r.length;a++)for(var s=r[a],o=0;o<i.length;o++){var c=i[o];c.start<s.end&&c.end>s.start&&(n.push({start:Math.max(s.start,c.start),end:Math.min(s.end,c.end)}),s.end>c.end&&(i.splice(o,1),o--,a--))}return n},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,s){return a.start-s.start});for(var r=t[0],i=1;i<t.length;i++){var n=t[i];n.start<=r.end?(n.end>r.end&&(r.end=n.end),t.splice(i,1),i--):r=n}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=vt(e.getConfig()),i=vt(t.getConfig()),n=r.parsed,a=i.parsed;n.customWeeks=r.customWeeks,a.customWeeks=i.customWeeks;var s={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,a.hours)),dates:{},customWeeks:{}};let o=(l,d)=>{for(let u in l.dates){let f=l.dates[u];+u>1e3&&(s.dates[u]=!1);for(let p in d.dates){let v=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&v)),Array.isArray(f)){let S=Array.isArray(v)?v:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,S))}}}};if(o(n,a),o(a,n),n.customWeeks)for(var c in n.customWeeks)s.customWeeks[c]=n.customWeeks[c];if(a.customWeeks)for(var c in a.customWeeks)s.customWeeks[c]?s.customWeeks[c+"_second"]=a.customWeeks[c]:s.customWeeks[c]=a.customWeeks[c];return s}};var en=class{constructor(){this.clear()}getItem(t,r,i){if(this._cache.has(t)){let a=this._cache.get(t)[i.getUTCFullYear()];if(a&&a.has(r))return a.get(r)}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache,s=n.getUTCFullYear(),o;a.has(t)?o=a.get(t):(o=[],a.set(t,o));let c=o[s];c||(c=o[s]=new Map),c.set(r,i)}clear(){this._cache=new Map}},rn=class{constructor(){this.clear()}getItem(t,r,i){let n=this._cache;if(n&&n[t]){let a=n[t];if(a===void 0)return-1;let s=a[i.getUTCFullYear()];if(s&&s[r]!==void 0)return s[r]}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let s=a[t],o=n.getUTCFullYear(),c=s[o];c||(c=s[o]={}),c[r]=i}clear(){this._cache={}}},nn=class{constructor(t){this.getMinutesPerWeek=r=>{let i=r.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r));for(let c=0;c<7;c++)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._weekCache.set(i,s),s},this.getMinutesPerMonth=r=>{let i=r.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r)),c=a.date.add(o,1,"month").valueOf();for(;o.valueOf()<c;)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._monthCache.set(i,s),s},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function jp(){return typeof Map<"u"?new en:new rn}var an=class{constructor(){this.clear()}_getCacheObject(t,r,i){let n=this._cache;n[r]||(n[r]=[]);let a=n[r];a||(a=n[r]={});let s=a[i];s||(s=a[i]={});let o=t.getUTCFullYear(),c=s[o];return c||(c=s[o]={durations:{},endDates:{}}),c}_endDateCacheKey(t,r){return String(t)+"-"+String(r)}_durationCacheKey(t,r){return String(t)+"-"+String(r)}getEndDate(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=this._endDateCacheKey(o,r),l;if(s.endDates[c]===void 0){let d=a(),u=d.valueOf();s.endDates[c]=u,s.durations[this._durationCacheKey(o,u)]=r,l=d}else l=new Date(s.endDates[c]);return l}getDuration(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=r.valueOf(),l=this._durationCacheKey(o,c),d;if(s.durations[l]===void 0){let u=a();s.durations[l]=u.valueOf(),d=u}else d=s.durations[l];return d}clear(){this._cache={}}};function sn(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=jp(),this._largeUnitsCache=new nn(this),this._dateDurationCache=new an,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}sn.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(e){for(var t=0,r=this.units.length;t<r;t++)if(this.units[t]==e)return t},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(e){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var t=null;if(e.day||e.day===0)t=e.day;else if(e.date){var r=String(e.date.valueOf());this._cached_timestamps[r]?t=this._cached_timestamps[r]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[r]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let r=this.$gantt.date[`${t}_start`](new Date(e)),i=this.$gantt.date.add(r,1,t);return this.hasDuration(r,i)}return this["_is_work_"+t](e)},_is_work_day:function(e){var t=this._getWorkHours(e);return Array.isArray(t)?t.length>0:!1},_is_work_hour:function(e){for(var t=this._getWorkHours(e),r=e.getUTCHours(),i=0;i<t.length;i++)if(r>=t[i].startHour&&r<t[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var r=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(r=24),r*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),r=this._getTimeOfDayStamp(e),i=0;i<t.length;i++)if(r>=t[i].start&&r<t[i].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,i){var n=this.$gantt.date,a=new Date(e),s=new Date(t);i=i||1;var o=0,c=null,l,d,u=!1;l=n[r+"_start"](new Date(a)),l.valueOf()!=a.valueOf()&&(u=!0);var f=!1;d=n[r+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var p=!1;a.valueOf()<s.valueOf();){if(c=this._nextDate(a,r,i),p=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&p)&&(l=n[r+"_start"](new Date(a)),d=n.add(l,i,r)),u?(u=!1,c=this._nextDate(l,r,i),o+=(d.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):f&&p?(f=!1,o+=(s.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):o++;else{var v=this._getUnitOrder(r),S=this.units[v-1];S&&!this._isWorkTime(a,S)&&(c=this._getClosestWorkTimeFuture(a,S))}a=c}return o},_getMinutesPerHour:function(e){var t=this._getTimeOfDayStamp(e),r=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));r===0&&(r=1440*60);for(var i=this._getWorkHours(e),n=0;n<i.length;n++){var a=i[n];if(t>=a.start&&r<=a.end)return 60;if(t<a.end&&r>a.start){var s=Math.min(r,a.end)-Math.max(t,a.start);return s/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,i){var n=0,a=new Date(e),s=new Date(t),o;for(r=="minute"?o=dt(this._getMinutesPerDay,this):o=dt(this.getHoursPerDay,this);a.valueOf()<s.valueOf();){if(s-a>1e3*60*60*24*32&&a.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,1,"month");continue}else if(s-a>1e3*60*60*24*16){var l=this.$gantt.date.week_start(new Date(a));if(a.valueOf()===l.valueOf()){var c=this._largeUnitsCache.getMinutesPerWeek(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,7,"day");continue}}n+=o(a),a=this._nextDate(a,"day",1)}return n/i},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),i=this._getWorkHours(e),n=0,a=0;a<i.length;a++){var s=i[a];if(r.end>=s.start&&r.start<=s.end){var o=Math.max(s.start,r.start),c=Math.min(s.end,r.end);n+=(c-o)/60,r.start=c}}return Math.floor(n)},_getMinutesBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o),u=this._getMinutesBetweenSingleDay(c,l),f=this._getWorkUnitsForRange(o,c,r,i),p=d+f+u;return p},_getHoursBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o,r,i)/60,u=this._getMinutesBetweenSingleDay(c,l,r,i)/60,f=this._getWorkUnitsForRange(o,c,r,i),p=d+f+u;return Math.round(p)},getConfig:function(){return this._worktime},_setConfig:function(e){this._worktime=e,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var e=this.getConfig();e.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},e.parsed.hours=this._parseHours(e.hours);for(var t in e.dates)e.parsed.dates[t]=this._parseHours(e.dates[t]);if(e.customWeeks){var r=null,i=null;for(var t in e.customWeeks){var n=e.customWeeks[t];if(n.from&&n.to){var a=n.from,s=n.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!i||i<s.valueOf())&&(i=s.valueOf()),e.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:s.valueOf(),toReadable:new Date(s),name:t}),e.parsed.haveCustomWeeks=!0;var o=e.parsed.customWeeks[t]={from:n.from,to:n.to,hours:this._parseHours(n.hours),dates:{}};if(n.days&&!n.dates){n.dates=n.dates||{};for(var t=0;t<n.days.length;t++)n.dates[t]=n.days[t],n.days[t]instanceof Array||(n.dates[t]=!!n.days[t]);delete n.days}for(var c in n.dates)o.dates[c]=this._parseHours(n.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(e){var t=JSON.stringify(this.getConfig());return e(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(t)),this._clearCaches(),!1)},_arraysEqual:function(e,t){if(e===t)return!0;if(!e||!t||e.length!=t.length)return!1;for(var r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var r=Object.keys(e.dates),i=Object.keys(t.dates);if(r.sort(),i.sort(),!this._arraysEqual(r,i))return!1;for(var n=0;n<r.length;n++){var a=r[n],s=e.dates[a],o=t.dates[a];if(s!==o&&!(Array.isArray(s)&&Array.isArray(o)&&this._arraysEqual(s,o)))return!1}return!0},equals:function(e){if(!(e instanceof sn))return!1;var t=this.getConfig(),r=e.getConfig();if(!this._compareSettings(t,r))return!1;if(t.parsed.haveCustomWeeks&&r.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=r.parsed.customWeeksBoundaries.length)return!1;for(var i in t.parsed.customWeeks){var n=t.parsed.customWeeks[i],a=r.parsed.customWeeks[i];if(!a||!this._compareSettings(n,a))return!1}}else if(t.parse.haveCustomWeeks!==r.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(e.date,!1)},_getWorkHours:function(e,t){var r=this.getConfig();if(t!==!1&&(r=r.parsed),!e)return r.hours;let i=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var n=this._timestamp({date:i});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=n&&r.customWeeksRangeEnd>n){for(var a=0;a<r.customWeeksBoundaries.length;a++)if(r.customWeeksBoundaries[a].from<=n&&r.customWeeksBoundaries[a].to>n){r=r.customWeeks[r.customWeeksBoundaries[a].name];break}}var s=!0;return r.dates[n]!==void 0?s=r.dates[n]:r.dates[e.getUTCDay()]!==void 0&&(s=r.dates[e.getUTCDay()]),s===!0?r.hours:s||[]},_getIntervalTimestamp:function(e,t){var r={start:0,end:0};r.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var i=t.getUTCHours();return!i&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(i=24),r.end=i*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),r},_parseHours:function(e){if(Array.isArray(e)){var t=[];e.forEach(function(o){typeof o=="number"?t.push(o*60*60):typeof o=="string"&&o.split("-").map(function(c){return c.trim()}).forEach(function(c){var l=c.split(":").map(function(u){return u.trim()}),d=parseInt(l[0]*60*60);l[1]&&(d+=parseInt(l[1]*60)),l[2]&&(d+=parseInt(l[2])),t.push(d)})});for(var r=[],i=0;i<t.length;i+=2){var n=t[i],a=t[i+1],s=a-n;r.push({start:n,end:a,startHour:Math.floor(n/3600),startMinute:Math.floor(n/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:s,durationMinutes:s/60,durationHours:s/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(dt(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),i=this.getConfig();if(r!==null?i.dates[r]=t:e.customWeeks||(i.hours=t),e.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof e.customWeeks=="string")r!==null?i.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(i.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)i.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(dt(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var r=-1,i=null;return i=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,i,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,i,r,e)),r},isWorkTime:function(){var e=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(e.date,e.unit)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!e.unit)return!1;var t=this;return this._dateDurationCache.getDuration(e.start_date,e.end_date,e.unit,e.step,function(){return t._calculateDuration(e.start_date,e.end_date,e.unit,e.step)})},_calculateDuration:function(e,t,r,i){var n=0,a=1;if(e.valueOf()>t.valueOf()){var s=t;t=e,e=s,a=-1}return r=="hour"&&i==1?n=this._getHoursBetween(e,t,r,i):r=="minute"&&i==1?n=this._getMinutesBetween(e,t,r,i):n=this._getWorkUnitsBetweenGeneric(e,t,r,i),a*Math.round(n)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;if(!i)return!1;var a=new Date(t),s=new Date(r);for(n=n||1;a.valueOf()<s.valueOf();){if(this._isWorkTime(a,i))return!0;a=this._nextDate(a,i,n)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;if(!i)return!1;var a=e.duration>=0?1:-1;r=Math.abs(r*1);var s=this;return this._dateDurationCache.getEndDate(t,r,i,n*a,function(){return s._calculateEndDate(t,r,i,n*a)})},_calculateEndDate:function(e,t,r,i){if(!r)return!1;if(i==1&&r=="minute")return this._calculateMinuteEndDate(e,t,i);if(i==-1&&r=="minute")return this._subtractMinuteDate(e,t,i);if(i==1&&r=="hour")return this._calculateHourEndDate(e,t,i);var n=this._addInterval(e,t,r,i,null);return n.end},_addInterval:function(e,t,r,i,n){for(var a=0,s=e;a<t&&!(n&&n(s));){var o=this._nextDate(s,r,i),c=new Date(o.valueOf()+1);i>0&&(c=new Date(o.valueOf()-1));var l=this._isWorkTime(c,r);l&&a++,s=o}return{end:s,start:e,added:a}},_addHoursUntilDayEnd:function(e,t){for(var r=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/3600;u>n&&(u=n,d=l+n*60*60);var f=Math.round((d-l)/3600);i+=f,n-=f,a.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_calculateHourEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1);var a=this._addHoursUntilDayEnd(i,t);n=a.added,i=a.end;var s=t-n;if(s){for(var o=i;n<t;){var c=this._nextDate(o,"day",r);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(r>0?l=this.getHoursPerDay(new Date(c.valueOf()-1)):l=this.getHoursPerDay(new Date(c.valueOf()+1)),n+l>=t)break;n+=l,o=c}i=o}if(n<t){var s=t-n;a=this._addHoursUntilDayEnd(i,s),i=a.end}return i},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var r=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/60;u>n&&(u=n,d=l+n*60);var f=Math.round((d-l)/60);n-=f,i+=f,a.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),i=0,n=t,a=r.getUTCHours()*60*60+r.getUTCMinutes()*60+r.getUTCSeconds(),s=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),o=this._getWorkHours(e),c=o.length-1;c>=0&&i<t;c--){var l=o[c];if(s>l.start&&a<=l.end){var d=Math.min(s,l.end),u=Math.max(a,l.start),f=(d-u)/60;f>n&&(f=n,u=d-n*60);var p=Math.abs(Math.round((d-u)/60));n-=p,i+=p,s=u}}var v=r;return i===t&&(v=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:i,end:v}},_subtractMinuteDate:function(e,t,r){var i=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),n=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let a=this._isMinutePrecision(i),s=this._subtractMinutesUntilHourStart(i,t);n+=s.added,i=s.end;for(var o=0,c=[],l=0;n<t;){var d=this.$gantt.date.day_start(new Date(i)),u=!1;i.valueOf()===d.valueOf()&&(d=this.$gantt.date.add(d,-1,"day"),u=!0);var f=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();f!==o&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),o=f);var p=t-n,v=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=v&&p>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var S=!1,A=null,D=null,m=c.length-1;m>=0;m--)if(c[m].start<v-1&&c[m].end>=v-1){S=!0,A=c[m],D=c[m-1];break}if(S)if(v===A.end&&p>=A.durationMinutes)n+=A.durationMinutes,i=this.$gantt.date.add(i,-A.durationMinutes,"minute");else if(!a&&p<=v/60-A.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(a)p<=v/60-A.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=v/60-A.startMinute,D?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,D.end)):i=this.$gantt.date.day_start(i));else{var T=this._getMinutesPerHour(i);T<=p?(n+=T,i=this._nextDate(i,"hour",r)):(s=this._subtractMinutesUntilHourStart(i,p),n+=s.added,i=s.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var k=this._getClosestWorkTimePast(i,"hour");if(k.valueOf()===i.valueOf()){var k=this.$gantt.date.add(i,-1,"day"),y=this._getWorkHours(k);if(y.length){var g=y[y.length-1];k.setUTCSeconds(g.durationSeconds)}}i=k}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var C=t-n;s=this._subtractMinutesUntilHourStart(i,C),n+=s.added,i=s.end}return i},_calculateMinuteEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(i,t);n+=a.added,i=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(i);n<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==s&&(o=this._getWorkHours(i),c=this._getMinutesPerDay(i),s=d);var u=t-n,f=this._getTimeOfDayStamp(i);if(!o.length||!c){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(o[0].start>=f&&u>=c){if(n+=c,u==c){i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,o[o.length-1].end));break}else i=this.$gantt.date.add(i,1,"day"),i=this.$gantt.date.day_start(i);continue}for(var p=!1,v=null,S=0;S<o.length;S++)if(o[S].start<=f&&o[S].end>f){p=!0,v=o[S];break}if(p)if(f===v.start&&u>=v.durationMinutes)n+=v.durationMinutes,i=this.$gantt.date.add(i,v.durationMinutes,"minute");else if(u<=v.endMinute-f/60)n+=u,i=this.$gantt.date.add(i,u,"minute");else{var A=this._getMinutesPerHour(i);A<=u?(n+=A,l?i=this.$gantt.date.add(i,A,"minute"):i=this._nextDate(i,"hour",r)):(a=this._addMinutesUntilHourEnd(i,u),n+=a.added,i=a.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(n<t){var D=t-n;a=this._addMinutesUntilHourEnd(i,D),n+=a.added,i=a.end}return i},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,r){var i=new Date(e);if(this._isWorkTime(i,t))return i;if(i=this.$gantt.date[t+"_start"](i),r=="any"||!r){var n=this._getClosestWorkTimeFuture(i,t),a=this._getClosestWorkTimePast(i,t);Math.abs(n-e)<=Math.abs(e-a)?i=n:i=a}else r=="past"?i=this._getClosestWorkTimePast(i,t):i=this._getClosestWorkTimeFuture(i,t);return i},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var r=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(r,1,t)},_findClosestTimeInDay:function(e,t,r){var i=new Date(e),n=null,a=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",t<0?"past":"future"),t<0&&(i=new Date(i.valueOf()-1),a=!0),r=this._getWorkHours(i));var s=this._getTimeOfDayStamp(i);if(a&&(s=this._getTimeOfDayStamp(new Date(i.valueOf()+1),a)),t>0){for(var o=0;o<r.length;o++)if(r[o].start>=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].start));break}}else for(var o=r.length-1;o>=0;o--)if(r[o].end<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].end));break}else if(r[o].end>s&&r[o].start<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,s));break}return n},_getClosestWorkMinute:function(e,t,r){var i=new Date(e),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n);return a||(r>0?(i=this.calculateEndDate(i,r,t),i=this.$gantt.date.day_start(i)):(i=this.calculateEndDate(i,r,"day"),i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n)),r<0&&(a=this.$gantt.date.add(a,-1,t)),a},_getClosestWorkTimeGeneric:function(e,t,r){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,r);for(var i=this._getUnitOrder(t),n=this.units[i-1],a=e,s=3e3,o=0;!this._isWorkTime(a,t)&&!(n&&!this._isWorkTime(a,n)&&(r>0?a=this._getClosestWorkTimeFuture(a,n):a=this._getClosestWorkTimePast(a,n),this._isWorkTime(a,t)));){if(o++,o>s)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,r,t),this.$gantt.date[t+"_start"]&&(a=this.$gantt.date[t+"_start"](a))}return a},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,r=[0,1,2,3,4,5,6];for(var i in e.dates);var n=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(s){if(!a){var o=t[s];o===!0?a=n:Array.isArray(o)&&(a=this._checkWorkHours(o))}}).bind(this)),a},_checkWorkHours:function(e){if(e.length===0)return!1;for(var t=!1,r=0;r<e.length;r+=2)e[r]!==e[r+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(r){(r.startMinute%60||r.endMinute%60)&&(t=!0)}),t}};var Re={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,r=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var i in e){r=i;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var i=t[r];if(e[r]){var n=i[e[r]];if(n)return n}}return null}};function Vp(){function e(n){return n.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var t={};function r(n,a){return a.mergeCalendars(n.map(function(s){var o=s&&s.resource_id?s.resource_id:s;return a.getResourceCalendar(o)}))}function i(n,a){var s=e(n);if(n.length){if(n.length===1)return a.getResourceCalendar(s).id;if(t[s])return t[s].id;var o=r(n,a);return t[s]=o,a.addCalendar(o)}else return null}return{getCalendarIdFromMultipleResources:i}}var Yp=Vp();function Ic(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Re.isLegacyResourceCalendarFormat(this.$gantt.config.resource_calendars))}).bind(this)),this.$gantt.attachEvent("onBeforeGanttReady",(function(){this.createDefaultCalendars()}).bind(this)),this.$gantt.attachEvent("onBeforeGanttRender",(function(){this.createDefaultCalendars()}).bind(this))}Ic.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let r={};if(t?.weekdays)for(let i=0;i<7;i++)r[i]=t.weekdays[i];t?.dates&&Object.entries(t.dates).forEach(([i,n])=>{r[new Date(i).valueOf()]=n}),Object.entries(r).forEach(([i,n])=>{n instanceof Array||(r[i]=!!n)}),e={...e,dates:r}}else if(t&&!e.dates){e.dates=e.dates||{};for(let r=0;r<t.length;r++)e.dates[r]=t[r],t[r]instanceof Array||(e.dates[r]=!!t[r])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var r=0;r<arguments.length;r++)e.push(arguments[r]);var i=new Cc,n;return e.forEach((function(a){n?n=this._createCalendarFromConfig(i.merge(n,a)):n=a}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new sn(this.$gantt,Ac(this.$gantt));t.id=String(Xi());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var i in r.customWeeks)r.customWeeks[i]=this._convertWorkTimeSettings(r.customWeeks[i]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=vt(e.getConfig()):e.worktime?t=vt(e.worktime):t=vt(e);var r=vt(this.defaults.fulltime.worktime);return pe(t,r),this._createCalendarFromConfig(t)},getCalendar:function(e){e=e||"global";var t=this._calendars[e];return t||(this.createDefaultCalendars(),t=this._calendars[e]),t},getCalendars:function(){var e=[];for(var t in this._calendars)e.push(this.getCalendar(t));return e},_getOwnCalendar:function(e){var t=this.$gantt.config;if(e[t.calendar_property])return this.getCalendar(e[t.calendar_property]);if(t.resource_calendars){var r,i,n;if(this._legacyConfig===!1?n=t.resource_property:n=Re.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=Yp.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Re.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Re.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(n&&e[n]&&t.resource_calendars[e[n]])var r=this.getResourceCalendar(e[n]);if(i&&(r=this.getCalendar(i)),r)return r}return null},getResourceCalendar:function(e){if(e==null)return this.getCalendar();var t=null;typeof e=="number"||typeof e=="string"?t=e:t=e.id||e.key;var r=this.$gantt.config,i=r.resource_calendars,n=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),i){if(this._legacyConfig===void 0&&(this._legacyConfig=Re.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in i)if(i[a][t]){n=i[a][t];break}}else var n=i[t];if(n)return this.getCalendar(n)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,r;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?r=t.getTask(e):r=e,!r)return this.getCalendar();var i=this._getOwnCalendar(r),n=!!t.getState().group_mode;if(!i&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(i=this._getOwnCalendar(a),i))););n&&!i&&e.$effective_calendar&&(i=this.getCalendar(e.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(e){if(!this.isCalendar(e)){var t=e.id;e=this.createCalendar(e),e.id=t}if(e._tryChangeCalendarSettings(function(){})){var r=this.$gantt.config;return e.id=e.id||Xi(),this._calendars[e.id]=e,r.worktimes||(r.worktimes={}),r.worktimes[e.id]=e.getConfig(),e.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},e]),null},deleteCalendar:function(e){var t=this.$gantt.config;return e&&this._calendars[e]?(delete this._calendars[e],t.worktimes&&t.worktimes[e]&&delete t.worktimes[e],!0):!1},restoreConfigCalendars:function(e){for(var t in e)if(!this._calendars[t]){var r=e[t],i=this.createCalendar(r);i.id=t,this.addCalendar(i)}},defaults:{global:{id:"global",worktime:{hours:[8,12,13,17],days:[0,1,1,1,1,1,0]}},fulltime:{id:"fulltime",worktime:{hours:[0,24],days:[1,1,1,1,1,1,1]}}},createDefaultCalendars:function(){var e=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(e.worktimes)},isCalendar:function(e){var t=[e.isWorkTime,e.setWorkTime,e.getWorkHours,e.unsetWorkTime,e.getClosestWorkTime,e.calculateDuration,e.hasDuration,e.calculateEndDate];return t.every(function(r){return r instanceof Function})}};function on(e,t){this.argumentsHelper=t,this.$gantt=e}on.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(t){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return t.date},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;return this._calculateDuration(t,r,i,n)},_calculateDuration:function(e,t,r,i){var n=this.$gantt.date,a={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},s=0;if(a[r])s=Math.round((t-e)/(i*a[r]));else{for(var o=new Date(e),c=new Date(t);o.valueOf()<c.valueOf();)s+=1,o=n.add(o,i,r);o.valueOf()!=t.valueOf()&&(s+=(c-o)/(n.add(o,i,r)-o))}return Math.round(s)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit;return i?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof on},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;return this.$gantt.date.add(t,n*r,i)}};function kc(e){this.$gantt=e.$gantt,this.argumentsHelper=Ac(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new on(this.$gantt,this.argumentsHelper)}kc.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var r=this.calendarManager;e.task?t=r.getTaskCalendar(e.task):e.id?t=r.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=r.getTaskCalendar())}return t},getWorkHours:function(e){e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getWorkHours(e.date)},setWorkTime:function(e,t){return e=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.setWorkTime(e)},unsetWorkTime:function(e,t){return e=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.unsetWorkTime(e)},isWorkTime:function(e,t,r,i){var n=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return i=this._getCalendar(n),i.isWorkTime(n)},getClosestWorkTime:function(e){e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getClosestWorkTime(e)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.calculateDuration(e)},hasDuration:function(){var e=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.hasDuration(e)},calculateEndDate:function(t){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),r=this._getCalendar(t);return r.calculateEndDate(t)}};var $p=function(e,t){return{getWorkHours:function(r){return t.getWorkHours(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){t.unsetWorkTime(r)},isWorkTime:function(r,i,n){return t.isWorkTime(r,i,n)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,i,n){return t.calculateDuration(r,i,n)},_hasDuration:function(r,i,n){return t.hasDuration(r,i,n)},calculateEndDate:function(r,i,n,a){return t.calculateEndDate(r,i,n,a)},mergeCalendars:dt(e.mergeCalendars,e),createCalendar:dt(e.createCalendar,e),addCalendar:dt(e.addCalendar,e),getCalendar:dt(e.getCalendar,e),getCalendars:dt(e.getCalendars,e),getResourceCalendar:dt(e.getResourceCalendar,e),getTaskCalendar:dt(e.getTaskCalendar,e),deleteCalendar:dt(e.deleteCalendar,e)}},Gp={create:$p};function Sc(e){var t=new Ic(e),r=new kc(t),i=Gp.create(t,r);pe(e,i)}var Dc={date:{month_full:["January","February","March","April","May","June","July","August","September","October","November","December"],month_short:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],day_full:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],day_short:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},labels:{}};function Tc(e={}){let t=e.config||{},r={config:Object.assign({duration_unit:"hour",duration_step:1,work_time:!1,worktimes:{},work_days:null,inherit_calendar:!1,calendar_property:"calendar_id",resource_property:"resource_id",resource_calendars:{},dynamic_resource_calendars:!1,start_on_monday:!0,server_utc:!0,csp:"auto",show_errors:!1},t),locale:e.locale||Dc,templates:e.templates||{},getTask:e.getTask||function(i){return null},isTaskExists:e.isTaskExists||function(i){return!1},isSummaryTask:e.isSummaryTask||function(i){return!1},getState:function(){return{group_mode:!1}},callEvent:function(i,n){let a=e.onEvent;return a&&a(i,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:yc,mixin:pe,copy:vt,assert:function(i,n){if(!i){if(e.throwOnAssert)throw new Error("[calendar] "+n);e.silent!==!0&&console.error("[calendar]",n)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(i){return i},r.date=vc(r),r.date.init(),Sc(r),r}function Kp(e={}){let t=Tc(e);return{addCalendar:function(r){return t.addCalendar(r)},deleteCalendar:function(r){return t.deleteCalendar(r)},getCalendar:function(r){return t.getCalendar(r)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(r){return t.getTaskCalendar(r)},getResourceCalendar:function(r){return t.getResourceCalendar(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){return t.unsetWorkTime(r)},isWorkTime:function(){return t.isWorkTime.apply(t,arguments)},getClosestWorkTime:function(){return t.getClosestWorkTime.apply(t,arguments)},getWorkHours:function(){return t.getWorkHours.apply(t,arguments)},calculateDuration:function(){return t.calculateDuration.apply(t,arguments)},calculateEndDate:function(){return t.calculateEndDate.apply(t,arguments)},_internals:t}}var _c={createCalendar:Kp};var UR=3600*1e3;function Lc(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:zp}=_c,Le="__replay_default__";function qp(e){if(!e||e.length===0||typeof e[0]=="string")return e;let t=e.map(Number);if(t.some(a=>Number.isNaN(a)))return e;let r=t[0],i=t[t.length-1];return t.every((a,s)=>a===r+s)?[`${r}:00-${i+1}:00`]:e}var Pc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Ec="__main_global__",Jp={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Rc(e){return!e||e.hours===void 0||e.hours.length>0||e.days?.some(t=>Array.isArray(t)&&t.length>0)===!0?!0:Object.values(e.dates??{}).some(t=>Array.isArray(t)&&t.length>0)}function Xp(e){let t={};if(Array.isArray(e.days))for(let i=0;i<e.days.length;i+=1)t[i]=e.days[i];if(e.dates)for(let[i,n]of Object.entries(e.dates))t[i]=n;let r={hours:qp(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function bc(e){let t=zp({config:{work_time:!0}});t.addCalendar({id:Le,worktime:Pc}),t.addCalendar({id:Ec,worktime:Jp});let r=new Set(e.filter(d=>!Rc(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>Rc(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?Xp(d.worktime):Pc});let n=hc(t),a=n.getCalendar(Le),s=n.getCalendar(Ec);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([Le]);for(let d of i)o.add(String(d.id));let c=new Map;return{reader:{getCalendar(d){let u=String(d),f=c.get(u);if(f)return f;let p=a;return o.has(u)?p=n.getCalendar(d)??a:r.has(u)&&(p=s),c.set(u,p),p}}}}function wc(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let i=e.getParent(r.id);return!i||e.getIncomingLinkIds(i.id).length===0?null:i.startDate},getDescendantIds(t){return Zp(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],i=e.getActivity(t);for(;i;){let n=i.parentId;if(n===null)break;let a=e.getActivity(n);if(!a)break;r.push(String(n)),i=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,progress:Number(n?.progress??0),ponderator:Number(n?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,workHours:Number(n?.workHours??0),progress:Number(n?.progress??0),realWorkHours:Number(n?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,usedCost:Number(n?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,cost:Number(n?.cost??0)}})}}}function Zp(e,t){let r=[],i=new ut;for(let n of e.getChildren(t))i.enqueue(n);for(;!i.isEmpty();){let n=i.dequeue();r.push(n);for(let a of e.getChildren(n))i.enqueue(a)}return r}function Oc(e,t){return{calendars:e.calendarReader,hierarchy:wc(e),activityReader:Lc(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function xc(e){return Ee(e)}function cn(e,t,r,i,n){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:i,afterLinks:n}}function Fc(e,t){let r=new Map,i=new Map;for(let n of t.activities){if(n.kind!=="created")continue;let a=e.getActivity(String(n.id));a&&r.set(String(n.id),j(a))}for(let n of t.links){if(n.kind!=="created")continue;let a=e.getLink(String(n.id));a&&i.set(String(n.id),{...a})}return{afterSnap:r,afterLinks:i}}function Mc(e){return e.kind!=="inline-edit"||!Pe.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Nc(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind==="updated"&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function Wc(e,t){if(!Nc(e)||!Nc(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function Uc(e,t){let r=e.changeSet.activities[0],i=t.changeSet.activities[0];if(!r||!i)return t;let n=r.fields??{},a=i.fields??{},s={};for(let c of new Set([...Object.keys(n),...Object.keys(a)])){let l=n[c],d=a[c];s[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let o={...t.changeSet,activities:[{...i,fields:s}]};return cn(o)}function Bc(e){return e.kind!=="sir-sync"&&e.kind!=="activity-lookahead-sync"}function ln(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&E.CUSTOM_ID in t.fields)return!0;return!1}function dn(e,t,r){let i=[],n=[];for(let s of t.changeSet.activities){let o=String(s.id);if(s.kind==="updated"){let c=e.getActivity(o);i.push({id:o,kind:"updated",after:c?j(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?j(c):null})}else i.push({id:o,kind:"deleted",after:null});else if(r==="before")i.push({id:o,kind:"deleted",after:null});else{let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?j(c):null})}}for(let s of t.changeSet.links){let o=String(s.id);if(s.kind==="updated"){let c=e.getLink(o);n.push({id:o,kind:"updated",after:c?gt(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);n.push({id:o,kind:"created",after:c?gt(c):null})}else n.push({id:o,kind:"deleted",after:null});else if(r==="before")n.push({id:o,kind:"deleted",after:null});else{let c=e.getLink(o);n.push({id:o,kind:"created",after:c?gt(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?Qp(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Qp(e){return{activityId:e.activityId,...e.checked?{checked:{before:e.checked.after,after:e.checked.before}}:{},...e.visible?{visible:{before:e.visible.after,after:e.visible.before}}:{}}}function Hc(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function jc(e,t){Yc(e,t,"before")}function Vc(e,t){Yc(e,t,"after")}function Yc(e,t,r){let i=t.changeSet;for(let n of i.activities)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))Z(e,n.id,a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeSnap?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${n.id}`);e.addActivity(j(a))}else e.removeActivity(String(n.id));else if(r==="before")e.removeActivity(String(n.id));else{let a=t.afterSnap?.get(String(n.id));if(!a)throw new Error(`redo: missing afterSnap for re-creating activity ${n.id}`);e.addActivity(j(a))}for(let n of i.links)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))Cs(e,String(n.id),a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeLinks?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeLinks for re-adding link ${n.id}`);e.addLink(a)}else e.removeLink(String(n.id));else if(r==="before")e.removeLink(String(n.id));else{let a=t.afterLinks?.get(String(n.id));if(!a)throw new Error(`redo: missing afterLinks for re-creating link ${n.id}`);e.addLink(a)}for(let n of i.viewState??[])n.checked&&e.setChecked(n.activityId,r==="before"?n.checked.before:n.checked.after),n.visible&&e.setVisible(n.activityId,r==="before"?n.visible.before:n.visible.after)}var th=100,eh=600,wr=class{constructor(t=th){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;record(t,r=null,i=0){let n=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&i-this._lastTime<=eh&&n!==void 0&&Wc(n,t)?this.undoStack[this.undoStack.length-1]=Uc(n,t):(this.undoStack.push(t),this.undoStack.length>this.maxDepth&&this.undoStack.shift()),this._lastKey=r,this._lastTime=i,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){return this.undoStack.pop()??null}takeRedo(){return this.redoStack.pop()??null}pushRedo(t){this.redoStack.push(t)}pushUndo(t){this.undoStack.push(t)}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}clear(){this.undoStack.length=0,this.redoStack.length=0}};var $c=["id","proplannerId","parentId","name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","assignedDefaultCalendar","dateOrigin","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","correlativeId","uniqueCorrelativeId","customId","subcontractId","isLookahead","newActivityIds","hasNewActivities","pendingRequestIds","responsableIds","tagIds"],Gc=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Kc=new Set(["newActivityIds","pendingRequestIds","responsableIds","tagIds"]);function zc(e){let t=$c.map(r=>[r,rh(r,e[r])]);return Object.fromEntries(t)}function rh(e,t){return Gc.has(e)?t instanceof Date?new Date(t):null:Kc.has(e)?Array.isArray(t)?[...t]:[]:t}function qc(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of $c)if(!ih(r,e[r],t[r]))return!0;return!1}function ih(e,t,r){return Gc.has(e)?nh(t,r):Kc.has(e)?ah(t,r):(t??null)===(r??null)}function nh(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function ah(e,t){let r=Array.isArray(e)?[...e].map(String).sort():[],i=Array.isArray(t)?[...t].map(String).sort():[];return r.length!==i.length?!1:r.every((n,a)=>n===i[a])}var Or=class{initialized=!1;linksAtLastSave=new Map;activitiesAtLastSave=new Map;init(t,r){this.snapshotActivities(t),this.snapshotLinks(r),this.initialized=!0}snapshotActivities(t){this.activitiesAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.activitiesAtLastSave.set(String(r.id),zc(r))}snapshotLinks(t){this.linksAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.linksAtLastSave.set(String(r.id),{lag:r.lag,type:r.type})}modifiedActivities(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;if(r.assignedDefaultCalendar)return!0;let i=this.activitiesAtLastSave.get(String(r.id));return i?qc(r,i):!0}):[]}modifiedLinks(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;let i=this.linksAtLastSave.get(String(r.id));return i?r.lag!==i.lag||r.type!==i.type:!0}):[]}clear(){this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var Jc=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var un=[!1,!0,!0,!0,!0,!0,!1],Xc=new Set(["1","true"]),fn="DURATION",Zc="asap",Qc={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo","AS SOON AS POSSIBLE":"asap","AS LATE AS POSSIBLE":"alap","START NO EARLIER THAN":"snet","START NO LATER THAN":"snlt","FINISH NO EARLIER THAN":"fnet","FINISH NO LATER THAN":"fnlt","MUST START ON":"mso","MUST FINISH ON":"mfo"};function tl(e,t){let r=[],i=e.map(a=>{let s=hh(a,t);return a.should_be_showed===!1&&r.push(s.id),s});yh(i);let n=new Set(i.map(a=>a.id));return mh(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function sh(e){return e===0}function oh(e,t){if(!e)return null;let r=Qc[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Zc):r}function ch(e,t){let r=oh(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?Dt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function lh(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function dh(e){if(e==null||e==="")return[];if(Array.isArray(e))return e.map(String);if(typeof e!="string")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(String):[]}catch{return[]}}function uh(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function pn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)uh(r)&&t.push(String(r.id));return t}function fh(e){return e==="0"?null:String(e)}function ph(e,t){return Array.isArray(e)?e.map(r=>Pr(r,t)).filter(r=>r!==null):[]}function hh(e,t){let r=lh(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:s}=ch(e,t.reporter),o=e.type==="milestone",c=Dt(e.start_date),l=o?c:Dt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:fh(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Ae(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:sh(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:Dt(e.date_origin),progress:n,cost:Number(e.cost),usedCost:Number(e.used_cost??0),realCost:Number(e.real_cost??0),workHours:Number(e.hhWorkTime),realWorkHours:Number(e.real_work??0),ponderator:Number(e.ponderator??0),hasCustomPonderator:e.hasCustomPonderator,correlativeId:e.correlative_id,uniqueCorrelativeId:e.unique_correlative_id,customId:e.custom_id,subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:dh(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:pn(e.pendingRequests),responsableIds:pn(e.responsables),tagIds:pn(e.tags),baselinePoints:ph(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:Ae(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),isCritical:!!e.is_critical,freeSlackHours:e.freeSlack,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null,promotionRestore:null}}function yh(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function mh(e,t,r){for(let i of e)i.parentId!==null&&(t.has(i.parentId)||(r.warn(`[parseFromBackend] activity "${i.id}" references unknown parent "${i.parentId}" \u2014 re-parenting to root (null)`),i.parentId=null))}function nl(e,t,r,i=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>Ah(c,i)),o=(r??[]).map(c=>Ch(c,i));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:vh(s)}}function vh(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function al(e,t){let r=_h(e.working_days),{days:i,hours:n}=Th(e,r),a=Ih(t.exceptionsSource,t.exceptionRange),s={days:i,hours:n};return a&&(s.dates=a),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:s}}function Ah(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return al(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function Ch(e,t){return al(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function Ih(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=kh(i.from_date,i.to_date,t);if(n.length===0)continue;let a=Sh(i);if(a!==void 0)for(let s of n)r[s]=a}return Object.keys(r).length>0?r:null}function kh(e,t,r){let i=el(e),n=el(t);if(i===null||n===null)return[];if(r&&(n<r.start||i>r.end))return[];let a=[],s=r?Math.max(i,r.start):i,o=r?Math.min(n,r.end):n;for(;s<=o;)a.push(String(s)),s+=864e5;return a}function el(e){if(typeof e!="string")return null;let t=Jc.exec(e.trim());if(!t)return null;let r=Number(t[1]),i=Number(t[2]),n=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(i)&&Number.isFinite(n)?Date.UTC(r,i-1,n):null}function Sh(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=Dh(t);if(r.length>0)return r}}var rl=/^\d{1,2}:\d{2}$/;function Dh(e){let t=[];for(let r of e){let i=cl(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let o=i.startsCsv.trim(),c=i.endsCsv.trim();!xr(o)&&!xr(c)&&rl.test(o)&&rl.test(c)&&t.push(`${o}-${c}`);continue}let s=ol(i.startsCsv,i.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(sl),t}function il(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[i,n]=r.split(":");return(Number(i)||0)*60+(Number(n)||0)}function sl(e,t){return il(e)-il(t)}function Th(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=ol(l,d);for(let f=0;f<7;f+=1){let p=u[f],v=r[f];p&&v&&v.push(p)}},n=Array.isArray(e.shifts)&&e.shifts.length>0,a=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(n)for(let l of e.shifts){let d=cl(l?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else a&&i(e.shift_start,e.shift_end);for(let l of r)l.sort(sl);let o=r.find((l,d)=>!!t[d]&&l.length>0)??[];return{days:t.map((l,d)=>{if(!l)return!1;let u=r[d];return u&&u.length>0?u:o}),hours:o}}function ol(e,t){let r=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return r;let i=e.split(",").map(o=>o.trim()),n=t.split(",").map(o=>o.trim());if(!(i.length===n.length&&i.length>0&&i.length<=7))return r;let s=[...r];for(let o=0;o<i.length;o+=1){let c=i[o],l=n[o];xr(c)||xr(l)||(s[o]=`${c}-${l}`)}return s}function cl(e){if(typeof e!="string")return null;let t=e.indexOf("-");return t<=0?null:{startsCsv:e.slice(0,t),endsCsv:e.slice(t+1)}}function _h(e){if(typeof e!="string")return[...un];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...un]:t.map(r=>Xc.has(r))}var Ph=new Set(["false","null"]);function xr(e){return!e||Ph.has(e)}function Eh(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Rh(e){if(typeof e!="string")return null;let t=Ma(e);return t||(Eh(e)?e:null)}function dl(e,t){let r=[];for(let i of e)try{r.push(Lh(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return bh(r)}function Lh(e,t,r){let i=String(e.unique_id??e.id),n=String(e.source_id??e.source??""),a=String(e.target_id??e.target??"");if(!t.has(n))throw new Error(`[parseFromBackend] link "${i}" source "${n}" does not exist`);if(!t.has(a))throw new Error(`[parseFromBackend] link "${i}" target "${a}" does not exist`);let s=Rh(e.type);if(s===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=e.id;return{id:i,source:n,target:a,type:s,lag:ft(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function bh(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||ll(r)>ll(n))&&t.set(i,r)}return[...t.values()]}function ll(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function wh(e){if(typeof e!="string")return fn;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return fn}}function Oh(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function xh(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function ul(e){let t=Oh(e),r=xh(e),i=e.update_duration_for_primavera_for_end_date===!0;return{id:String(e.id),name:e.name,hoursPerDay:e.hoursPerDay,hoursPerWeek:e.hoursPerWeek,dateFormat:e.dateFormat,projectId:e.projectId,companyId:e.companyId,...t!==void 0?{customIdPrefix:t}:{},...r!==void 0?{customIdIncrement:r}:{},...i?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:wh(e.activity_creter),statusCriteria:qr}}function Nr(e,t=Qt){let r=ul(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:s}=nl(e.calendars,e.sector.calendars,e.baseCalendars,Nh(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=tl(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=dl(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function Nh(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let a of e){let s=new Date(a.start_date).getTime(),o=new Date(a.end_date).getTime();Number.isFinite(s)&&(t=Math.min(t,s)),Number.isFinite(o)&&(r=Math.max(r,o))}if(!Number.isFinite(t)||!Number.isFinite(r))return null;let i=new Date(t),n=new Date(r);return i.setFullYear(i.getFullYear()-1),n.setFullYear(n.getFullYear()+1),{start:i.getTime(),end:n.getTime()}}function fl(e={}){let t=e.seed??0,r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function pl(e={}){let t=e.seed??Date.now(),r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function hl(e={}){let t=e.seed??0,r=i=>{Number.isFinite(i)&&i>0&&i<=9999999&&i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){if(i==null)continue;let n=typeof i=="number"?i:Number(i);r(n)}return{next(){return t+=1,String(t)},bump(i){if(i==null)return;let n=typeof i=="number"?i:Number(i);r(n)}}}function yl(e){return!!e&&typeof e=="string"&&e.trim().length>0}function Fr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function Mr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function ml(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function gl(e,t){return!t&&yl(e)}function vl(e,t){return t&&yl(e)}function we(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function be(e){if(!we(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Fh(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!we(t))return r;let i=t.length;return r.padStart(i,"0")}function mt(e,t){let r=be(e),i=be(t),n=r+i;return Fh(n,e)}function Wr(e,t){let r=be(e),i=be(t);return r<i?-1:r>i?1:0}function Ur(e,t){return Wr(e,t)<=0?e:t}function Br(e,t){return Wr(e,t)>=0?e:t}function Al(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Ur(t,r))}function Cl(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Br(t,r))}function Il(e){return{prefix:e,baseSuffix:null}}function kl(e,t){let r=Mr(e);return{prefix:Fr(e),baseSuffix:mt(r,t)}}function Sl(e){return{prefix:e,baseSuffix:null}}function Dl(e,t){return gl(e,t)?"parentConversion":vl(e,t)?"pasteReference":"noContext"}function Mh(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Hr=class{prefixMap=new Map;processedIds=new Set;_journal=null;beginCustomIdTransaction(){this._journal=[]}commitCustomIdTransaction(){this._journal=null}rollbackCustomIdTransaction(){let t=this._journal;if(t!==null){for(let r of[...t].reverse()){let{prefix:i}=this.analyzeCustomId(r.customId);r.prefixBefore===null?this.prefixMap.delete(i):this.prefixMap.set(i,r.prefixBefore),r.hadId?this.processedIds.add(r.customId):this.processedIds.delete(r.customId)}this._journal=null}}_noteCustomIdBefore(t){if(this._journal===null)return;let{prefix:r}=this.analyzeCustomId(t),i=this.prefixMap.get(r);this._journal.push({customId:t,prefixBefore:i?Mh(i):null,hadId:this.processedIds.has(t)})}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return Fr(t)}extractSuffix(t){return Mr(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let i=this.prefixMap.get(t);i.usedSuffixes.has(r)||(i.usedSuffixes.add(r),i.min=Ur(r,i.min),i.max=Br(r,i.max),i.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let i=this.getNextAvailableSuffix(t);r.next=i??this.suffixIncrement}getPrefixStats(t){let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!r&&!i)return{prefix:r,suffix:i};if(this._noteCustomIdBefore(t),this.prefixMap.has(r)){let n=this.prefixMap.get(r);n.usedSuffixes.has(i)||(n.usedSuffixes.add(i),n.min=Ur(i,n.min),n.max=Br(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:mt(i,this.suffixIncrement),quantity:1,usedSuffixes:new Set([i])});return this.processedIds.add(t),{prefix:r,suffix:i}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:i};this._noteCustomIdBefore(t);let n=this.prefixMap.get(r);if(n.usedSuffixes.has(i)){let a=n.quantity-1;if(a===0)this.prefixMap.delete(r);else{let s=new Set(n.usedSuffixes);s.delete(i);let o=Array.from(s);o.length===0?this.prefixMap.delete(r):(n.usedSuffixes=s,n.min=Al(o),n.max=Cl(o),n.quantity=a,this._recalculateNext(r))}}return this.processedIds.delete(t),{prefix:r,suffix:i}}trackCustomIdChange(t,r){let i=this.releaseCustomId(t),n=this.registerCustomId(r);return{oldPrefix:i.prefix,oldSuffix:i.suffix,newPrefix:n.prefix,newSuffix:n.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(!this.prefixMap.has(t))return!1;let r=this.prefixMap.get(t);return`${t}${mt(r.max,this.suffixIncrement)}`.length>20}_findFirstAvailableGap(t){if(!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),i=this.suffixIncrement;for(;Wr(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=mt(i,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let r=this._findFirstAvailableGap(this.defaultPrefix);if(r!==null)return`${this.defaultPrefix}${r}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,r=null){if(!this.prefixMap.has(t)){let o=r&&we(r)?r:this.suffixIncrement;return`${t}${o}`.length>20?null:o}let i=this.prefixMap.get(t),n=this.suffixIncrement;if(!r||!we(r)){let o=mt(i.max,n);return`${t}${o}`.length>20?null:o}let a=r;for(let o=0;o<100;o++){if(`${t}${a}`.length>20)return null;if(!i.usedSuffixes.has(a))return a;a=mt(a,n)}let s=mt(i.max,n);return`${t}${s}`.length>20?null:s}generateNextCustomId(t){let r=this.getNextAvailableSuffix(t);if(r===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),a=0;for(;n.usedSuffixes.has(r)&&a<1e4;){let s=this.getNextAvailableSuffix(t,mt(r,this.suffixIncrement));if(s===null)return this._generateDefaultCustomId();r=s,a++}}let i=`${t}${r}`;return this._exceedsMaxLength(i)&&(i=this._generateDefaultCustomId()),i}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(i=>i&&typeof i.customId=="string"&&i.customId).map(i=>i.customId))];for(let i of r){if(this.processedIds.has(i))continue;let{prefix:n,suffix:a}=this.analyzeCustomId(i);(n||a)&&(this._updatePrefixStats(n,a),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:i=!1}=t,n=ml(r),a=Dl(n,i),{prefix:s,baseSuffix:o}=this._applyGenerationStrategy(a,n),c=null;if(a==="parentConversion"&&this.prefixMap.has(s)){let f=this.prefixMap.get(s).max;c=mt(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(n);let l=a==="parentConversion"&&c?c:o,d=this.getNextAvailableSuffix(s,l);if(d===null){let f=this._generateDefaultCustomId();return this.registerCustomId(f),f}let u=`${s}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,r){switch(t){case"parentConversion":return Il(this.defaultPrefix);case"pasteReference":return kl(r,this.suffixIncrement);default:return Sl(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let n=this.extractPrefix(i),a=this.extractSuffix(i),s=mt(a,this.suffixIncrement),o=this.getNextAvailableSuffix(n,s);if(o===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${n}${o}`;return this._exceedsMaxLength(c)&&(c=this._generateDefaultCustomId()),this.registerCustomId(c),c}}let r=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(r),r}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,r=null){if(!t||typeof t!="string"||!t.trim())return!1;let i=t.trim();return r&&i===r.trim()?!1:this.processedIds.has(i)}};var Wh=new Set(["startDate","endDate","constraintDate"]);function Tl(e,t){return Wh.has(e)&&typeof t=="string"?new Date(t):t}var jr=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let i=this._journal;i&&(i.before.has(t)||i.before.set(t,yn(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:"insert",activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:"remove",activityId:t,before:yn(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:"link-add",linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:"link-remove",linkId:t,before:_l(r)})}noteCorrelativeBefore(t,r){let i=this._journal;!i||i.correlativeBefore.has(t)||i.correlativeBefore.set(t,r)}noteScheduledBefore(t,r){let i=this._journal;!i||i.scheduledBefore.has(t)||i.scheduledBefore.set(t,yn(r))}noteLinkField(t,r){let i=this._journal;!i||i.linkFieldCaptured.has(t)||(i.linkFieldCaptured.add(t),i.ops.push({kind:"link-field",linkId:t,before:_l(r)}))}};function yn(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:e.constraintDate?new Date(e.constraintDate):null,dateOrigin:e.dateOrigin?new Date(e.dateOrigin):null,newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:[...e.baselinePoints]}}function _l(e){return{...e}}var Vr=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Pl(t);return this.reader.getCalendar(r??Le)}getClosestWorkTime(t){let r=`${gn(t.task)}|${t.dir}|${t.date.getTime()}`;return mn(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:et.HOUR}))}calculateEndDate(t){let r=`${gn(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return mn(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${gn(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return mn(this._cache.duration,r,()=>this.resolveCalendar(t.task).calculateDuration(t.startDate,t.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function mn(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var Uh="__default__";function Pl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function gn(e){return Pl(e)??Uh}var Yr=class{constructor(t){this.activities=t}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;markDirty(){this._dirty=!0}getChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(t))??[]}hasChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(t))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(t,r){let i=this.activities.get(t)?.parentId,n=0,a=this.activities.size;for(;i&&!O(i);){if(i===r)return!0;if(++n>a)return!1;i=this.activities.get(i)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||O(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(O(t)){this._roots.push(r);return}let i=String(t),n=this._childrenByParent.get(i);n?n.push(r):this._childrenByParent.set(i,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let t of this.activities.values()){if(O(t.parentId)){this._roots.push(t.id);continue}let r=String(t.parentId),i=this._childrenByParent.get(r)??[];i.push(t.id),this._childrenByParent.set(r,i)}}};var $r=class{checkedSet=new Set;hiddenSet=new Set;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[])}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet)}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden)}};var Gr=class{_activities=new Map;_lastStartDate=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_cache={ids:null,visualOrderIds:null};_writeCapture=new jr;_viewState=new $r;_viewStateBefore=null;_lastStartDateBefore=null;_calendar;_flags;constructor(t){for(let r of t.activities)this._activities.set(r.id,r);for(let r of t.links)this._links.set(String(r.id),r),this._indexLink(r);this._calendar=new Vr(bc(t.calendars)),this._flags=Hh(t),this._hierarchy=new Yr(this._activities),this._hierarchy.rebuild()}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Es(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,i]of this._activities)t(i,r)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLastStartDate(t){return this._lastStartDate.get(String(t))??null}setLastStartDate(t,r){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),r)}_captureLastStartDateOnce(){this._writeCapture.peek()!==null&&this._lastStartDateBefore===null&&(this._lastStartDateBefore=new Map(this._lastStartDate))}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}isChecked(t){return this._viewState.isChecked(String(t))}isVisible(t){return this._viewState.isVisible(String(t))}checkedIds(){return this._viewState.checkedIds()}setChecked(t,r){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),r)}setVisible(t,r){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),r)}hydrateViewState(t){this._viewState.hydrate(t)}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??El}getIncomingLinkIds(t){return this._incoming.get(String(t))??El}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,r){return this._hierarchy.isChildOf(t,r)}getParent(t){return this._hierarchy.getParent(t)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null}setActivityField(t,r,i){let n=this.getActivity(t);n&&(this._writeCapture.note(String(t),n),n[r]=i,r===L.PARENT&&this._hierarchy.markDirty(),vn(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,i){let n=this.getActivity(t);if(n){if(!Object.hasOwn(n,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),n),Reflect.set(n,r,Tl(r,i)),r===L.PARENT&&this._hierarchy.markDirty(),vn(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let i=this.getActivity(t);if(!i)return;this._writeCapture.note(String(t),i);let n=!1;for(let a of Object.keys(r))Reflect.set(i,a,Reflect.get(r,a)),a===L.PARENT&&(n=!0),vn(a)&&(this._cache.visualOrderIds=null);n&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let r=this._links.get(String(t.id));r&&this._deindexLink(r),this._links.set(String(t.id),{...t}),this._indexLink(t)}_indexLink(t){Ll(this._outgoing,String(t.source),t.id),Ll(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Rl(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),Rl(i,t.id))}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkFieldDynamic(t,r,i){if(!Bh(r))return;let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),Reflect.set(n,r,i))}setLinkProplannerId(t,r){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i.proplannerId=r)}removeLink(t){let r=this.getLink(t);r&&(this._writeCapture.noteLinkRemove(String(t),r),this._links.delete(String(t)),this._deindexLink(r))}addActivity(t){this._writeCapture.noteInsert(String(t.id)),this._activities.set(t.id,t),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(t.parentId,t.id)}removeActivity(t){let r=this.getActivity(t);r&&this._writeCapture.noteRemove(String(t),r);let i=String(t);(this._viewState.isChecked(i)||!this._viewState.isVisible(i))&&(this._captureViewStateOnce(),this._viewState.forget(i)),this._activities.delete(t),this._lastStartDate.has(String(t))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(t))),this._outgoing.delete(String(t)),this._incoming.delete(String(t)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(t,r){this._writeCapture.noteCorrelativeBefore(t,r)}noteScheduledBefore(t,r){this._writeCapture.noteScheduledBefore(t,r)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:r,before:i,correlativeBefore:n,scheduledBefore:a}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreCorrelatives(n),this._restoreActivityFields(a),this._restoreActivityFields(i),this._viewStateBefore!==null&&this._viewState.restore(this._viewStateBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreCorrelatives(t){for(let[r,i]of t){let n=this._activities.get(r);n&&(n.correlativeId=i)}}_undoLinkAdds(t){for(let r of t)r.kind==="link-add"&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind==="insert"&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind==="remove"&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind==="link-remove"&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t)r.kind==="link-field"&&this._links.has(r.linkId)&&this._links.set(r.linkId,r.before)}_restoreActivityFields(t){for(let[r,i]of t){let n=this._activities.get(r);n&&this._restoreScalarFields(n,i)}}_restoreScalarFields(t,r){for(let i of Object.keys(t))Object.hasOwn(r,i)||Reflect.deleteProperty(t,i);for(let i of Object.keys(r))Reflect.set(t,i,Reflect.get(r,i))}_attachLink(t){this._links.set(String(t.id),{...t}),this._indexLink(t)}_detachLink(t){let r=this.getLink(t);r&&(this._links.delete(String(t)),this._deindexLink(r))}},El=[];function Bh(e){return e===ui.LAG||e===ui.TYPE}function vn(e){return e===L.PARENT||e===L.CORRELATIVE_ID}function Rl(e,t){return e.filter(r=>String(r)!==String(t))}function Ll(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Hh(e){let t=e.runtimeFlags??{};return{isPasting:!!t.isPasting,isBulkOperation:!!t.isBulkOperation,dragWithMultiple:!!t.dragWithMultiple,draggingSingleMilestone:!!t.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!t.maxPerformance,allCheckedTaskIds:[]}}function bl(e){let t=[];e.forEachActivity((r,i)=>{r.type==="project"&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,L.TYPE,Zt),jh(e,r)}function jh(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let i=new Date(r.startDate);i.setUTCHours(0,0,0,0);let n=e.getClosestWorkTime({date:i,dir:q.FUTURE,task:r});if(n.getTime()===r.startDate.getTime())return;let a=e.calculateEndDate({startDate:n,durationHours:r.durationHours,task:r});e.setActivityField(t,L.START_DATE,n),e.setActivityField(t,L.END_DATE,a)}function Vh(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Yh(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function wl(e){return{id:String(e.id),worktime:Yh(e.worktime)}}function Ol(e,t,r,i=[]){let n=t.map(Vh),a=[...r.map(wl),...i.map(wl)];return{activities:[...e],links:n,calendars:a}}var _t={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function xl(e){let t=e.clock??null,r=t?Ce(t()):null,i=e.reporter??Qt,n=Nr({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),a=n.sector;a.statusCriteria=Fe(e.statusCriteria);let s=n.calendars,o=n.baseCalendars??[],c=Ol(n.activities,n.links,n.calendars,o),l=new Gr(c);l.hydrateViewState({hiddenIds:n.viewStateSeed.hiddenIds});let d=new Je(l,i);bl(l);let u=fl({knownIds:n.activities.map(A=>A.id)}),f=pl({knownIds:n.links.map(A=>A.id)}),p=hl({knownIds:n.activities.map(A=>A.uniqueCorrelativeId)}),v=new Hr({defaultPrefix:a.customIdPrefix,suffixIncrement:a.customIdIncrement});if(v.populateFromActivities(n.activities),e.baselinePoints&&e.baselinePoints.length>0){let A=o.find(D=>D.baseDefault)?.id??null;Rr(l,e.baselinePoints,r,i,A)}let S=Ns({state:l,sector:a,scheduler:d,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??void 0});return{sector:a,state:l,scheduler:d,activityIdGen:u,linkIdGen:f,uidGen:p,customIdTracker:v,calendars:s,baseCalendars:o,clock:t,reporter:i,initPromise:S}}function Nl(e,t,r,i){let n=new Set,a=new Set;for(let s of e){let o=String(s.id);if(o.length===0||n.has(o))throw new Error(`acknowledgePersistence: duplicate or empty ${t} id "${o}"`);if(!Number.isSafeInteger(s.proplannerId)||s.proplannerId<=0||a.has(s.proplannerId))throw new Error(`acknowledgePersistence: invalid or duplicate ${t} proplannerId ${String(s.proplannerId)}`);let c=r(o);if(!c.exists)throw new Error(`acknowledgePersistence: unknown ${t} id "${o}"`);if(c.current!==null&&c.current!==s.proplannerId)throw new Error(`acknowledgePersistence: ${t} "${o}" already has proplannerId ${String(c.current)}`);let l=i.get(s.proplannerId);if(l!==void 0&&l!==o)throw new Error(`acknowledgePersistence: ${t} proplannerId ${String(s.proplannerId)} already belongs to "${l}"`);n.add(o),a.add(s.proplannerId)}}var Kr=class{_status=_t.READY;_dispatchInFlight=!1;coreRuntime;_undo=new wr;_opQueue=Promise.resolve();_mutationEpoch=0;_cpComputedEpoch=0;constructor(t){let r=xl(t);this.coreRuntime={state:r.state,scheduler:r.scheduler,sector:r.sector,activityIdGenerator:r.activityIdGen,linkIdGenerator:r.linkIdGen,uniqueCorrelativeIdGenerator:r.uidGen,customIdTracker:r.customIdTracker,clock:r.clock,calendars:new Map(r.calendars.map(n=>[n.id,n])),baseCalendars:r.baseCalendars,reporter:r.reporter},this._initPromise=r.initPromise.then(()=>{this._status!==_t.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._enqueue(()=>this._runCriticalPathAndCapture()));let i=t.criticalPathOnLoad===!0;this._ready=i?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return this.coreRuntime.sector}getActivityView(t){return this.assertReady(),zo(this.coreRuntime.state,t)}getAllActivitiesView(){return this.assertReady(),qo(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),Zo(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),ec(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),rc(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?i[r]:null}getAllIds(){return this.assertReady(),Jo(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Xo(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),qi(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Qo(this.coreRuntime.state)}getVisualOrderIds(){return this.assertReady(),this.coreRuntime.state.getVisualOrderIds()}hasChild(t){return this.assertReady(),tc(this.coreRuntime.state,t)}getCalendar(t){return this.assertReady(),this.coreRuntime.calendars.get(t)??null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values())}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),pc(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(this.getAllLinksView())}markLinksPersisted(){this._saveTracker.snapshotLinks(this.getAllLinksView())}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(this.coreRuntime.state.getAllActivities())}markActivitiesPersisted(){this._saveTracker.snapshotActivities(this.coreRuntime.state.getAllActivities())}acknowledgePersistence(t){this.assertReady();let r=t.activities??[],i=t.links??[],n=new Map;for(let s of this.coreRuntime.state.getAllActivities())s.proplannerId!=null&&n.set(s.proplannerId,String(s.id));let a=new Map;for(let s of this.coreRuntime.state.getAllLinks())s.proplannerId!=null&&a.set(s.proplannerId,String(s.id));Nl(r,"activity",s=>{let o=this.coreRuntime.state.getActivity(s);return{exists:o!==null,current:o?.proplannerId??null}},n),Nl(i,"link",s=>{let o=this.coreRuntime.state.getLink(s);return{exists:o!==null,current:o?.proplannerId??null}},a),this.coreRuntime.state.batchUpdate(()=>{for(let s of r)this.coreRuntime.state.setActivityField(s.id,"proplannerId",s.proplannerId);for(let s of i)this.coreRuntime.state.setLinkProplannerId(s.id,s.proplannerId)}),this.markActivitiesPersisted(),this.markLinksPersisted()}applyBaselines(t){this.assertReady();let r=this.coreRuntime.clock?Ce(this.coreRuntime.clock()):null,i=this.coreRuntime.baseCalendars.find(n=>n.baseDefault)?.id??null;return uc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t,r,this.coreRuntime.reporter,i)}recomputeAllPonderators(t){return this.assertReady(),lc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t)}recomputeAllProgressRollup(){return this.assertReady(),dc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay)}setStatusCriteria(t){this.assertReady();let r=Fe(t);return this.coreRuntime.sector.statusCriteria=r,fc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,r)}allocateActivityId(){return this.assertReady(),this.coreRuntime.activityIdGenerator.next()}createActivity(t){if(this.assertReady(),this._dispatchInFlight)throw new Error("[ScheduleCore] createActivity called during an in-flight dispatch");let r={kind:"activity-create",...t};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let i;try{i=bo(r,{adapter:this.coreRuntime.state,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker}),i.ok||this._rollback()}catch(n){throw this._rollback(),n}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return i.ok?{ok:!0,activity:i.activity,changes:i.changes}:i}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}async dispatch(t,r={}){return this._enqueue(()=>this._dispatchInner(t,r))}async _dispatchInner(t,r={}){this.assertReady();let i=Oc(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),n=Bc(t);this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction(),this._dispatchInFlight=!0;let a;try{a=await Ko(t,r,{adapter:this.coreRuntime.state,ctx:i,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(s=>s.baseDefault)?.id??null,now:this.coreRuntime.clock?Ce(this.coreRuntime.clock()):null}),a.ok||this._rollback()}catch(s){throw this._rollback(),s}finally{this._dispatchInFlight=!1,this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(a.ok&&n&&Hc(a.changes)){let s=Fc(this.coreRuntime.state,a.changes);this._undo.record(cn(a.changes,a.__beforeSnap,a.__beforeLinks,s.afterSnap,s.afterLinks),Mc(t),Date.now())}return a.ok?(r.skipCriticalPath&&this._mutationEpoch++,{...a,changes:a.changes}):a}recomputeCriticalPath(){return this._enqueue(()=>this._recomputeCriticalPathIfStale())}async _recomputeCriticalPathIfStale(){if(this._status===_t.DESTROYED)return null;let t=this._mutationEpoch;if(this._cpComputedEpoch===t)return null;let r=await this._runCriticalPathAndCapture();return this._cpComputedEpoch=t,r}async _runCriticalPathAndCapture(){if(this._status===_t.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await pr(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=K(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:t}}undo(){return this._enqueue(async()=>{this.assertReady();let t=this._undo.takeUndo();return t?(jc(this.coreRuntime.state,t),this._mutationEpoch++,ln(t)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(t),this._undo.resetCoalesce(),dn(this.coreRuntime.state,t,"before")):null})}redo(){return this._enqueue(async()=>{this.assertReady();let t=this._undo.takeRedo();return t?(Vc(this.coreRuntime.state,t),this._mutationEpoch++,ln(t)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(t),this._undo.resetCoalesce(),dn(this.coreRuntime.state,t,"after")):null})}clearHistory(){this._undo.clear()}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=_t.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Or;assertReady(){if(this._status===_t.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===_t.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction()}catch(t){throw this._status=_t.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",t),t}}};function Fl(e,t){let r=new Map(e.map(i=>[String(i.id),i]));return t.filter(i=>{let n=r.get(String(i.id));return n?n.lag!==i.lag||n.type!==i.type:!1})}var Ml=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Wl={asap:"AS SOON AS POSSIBLE",alap:"AS LATE AS POSSIBLE",snet:"START NO EARLIER THAN",snlt:"START NO LATER THAN",fnet:"FINISH NO EARLIER THAN",fnlt:"FINISH NO LATER THAN",mso:"MUST START ON",mfo:"MUST FINISH ON"};var Ul=8;var X={INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_PASTE:"activity-paste",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},$h={[X.INLINE_EDIT]:!0,[X.DATES_BATCH]:!0,[X.BULK_EDIT]:!0,[X.LINK_CREATE]:!0,[X.LINK_UPDATE]:!0,[X.LINK_DELETE]:!0,[X.LINKS_BATCH]:!0,[X.ACTIVITY_CREATE]:!0,[X.ACTIVITY_DELETE]:!0,[X.ACTIVITY_MOVE]:!0,[X.ACTIVITY_INDENT]:!0,[X.ACTIVITY_OUTDENT]:!0,[X.ACTIVITY_SET_PROGRESS]:!0,[X.ACTIVITY_PASTE]:!0,[X.SELECTION_TOGGLE]:!0,[X.SELECTION_REPLACE]:!0,[X.VISIBILITY_SET]:!0,[X.SIR_SYNC]:!0,[X.ACTIVITY_LOOKAHEAD_SYNC]:!0},Bl=Object.keys($h);var Hl={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return Kl(Gh);})();
1
+ "use strict";var ScheduleCore=(()=>{var qr=Object.defineProperty;var Bl=Object.getOwnPropertyDescriptor;var Hl=Object.getOwnPropertyNames;var jl=Object.prototype.hasOwnProperty;var Vl=(e,t)=>{for(var r in t)qr(e,r,{get:t[r],enumerable:!0})},Yl=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Hl(t))!jl.call(e,n)&&n!==r&&qr(e,n,{get:()=>t[n],enumerable:!(i=Bl(t,n))||i.enumerable});return e};var $l=e=>Yl(qr({},"__esModule",{value:!0}),e);var ty={};Vl(ty,{ACTIVITY_TYPE:()=>Ve,CALENDAR_UNIT:()=>et,COLUMN:()=>E,CONSTRAINT_TYPE:()=>G,CONSTRAINT_TYPE_TO_LABEL:()=>Fl,CREATION_KIND:()=>Ul,DEFAULT_HOURS_PER_DAY:()=>Ml,DISPATCH_ACTION_KIND:()=>z,DISPATCH_ACTION_KINDS:()=>Wl,DISPATCH_TRACK_EVENT:()=>yt,LINK_CODE_TO_TYPE:()=>Gt,LINK_TYPE:()=>j,LINK_TYPE_CODE:()=>Ma,NEW_ACTIVITY_DEFAULTS:()=>kr,REJECTION_REASON:()=>R,ROOT_PARENT_ID:()=>V,ScheduleCore:()=>zr,WORK_TIME_DIRECTION:()=>X,checkNoUpdatedLinks:()=>xl,computeExpectedProgress:()=>fi,expectedProgressFromBaseline:()=>fe,getActiveBaseline:()=>at,getUnsavedActivities:()=>Nl,isRootParent:()=>O,normalizeParentKey:()=>$t,parseFromBackend:()=>Br,willRunCriticalPath:()=>Bc,yieldToBrowser:()=>rt});var ft=class{items=[];head=0;enqueue(t){this.items.push(t)}dequeue(){if(this.head>=this.items.length)return;let t=this.items[this.head];return this.head+=1,t}peek(){if(!(this.head>=this.items.length))return this.items[this.head]}get size(){return this.items.length-this.head}isEmpty(){return this.head>=this.items.length}};var Ue=e=>String(e);function kn(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:a,exists:s,autoCheckParents:o}=e,c=Ue(t),l=new Set([...i].map(String)),d=new Set(l),u=Gl(c,n).filter(s),f=u.filter(v=>!a(v)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let v of f)r?d.add(v):d.delete(v);return p||Kl({id:c,isChecked:r,autoCheckParents:o,hierarchy:n,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:zl(l,d),parentBlocked:p}}function Gl(e,t){let r=[],i=new ft;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let a=i.dequeue();for(let s of t.getChildrenIds(a)){let o=Ue(s);n.has(o)||(n.add(o),r.push(o),i.enqueue(o))}}return r}function Kl(e){let{id:t,isChecked:r,autoCheckParents:i,hierarchy:n,isFrozen:a,exists:s,next:o}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=Ue(c);if(a(l))return;let d=n.getChildrenIds(l).map(Ue).filter(s),u=d.some(a),f=d.filter(S=>!a(S)),v=f.length>0&&f.every(S=>o.has(S))&&!u;if(r){if(!i||!v||o.has(l))return;o.add(l)}else{if(v||!o.has(l))return;o.delete(l)}c=n.getParentId(l)}}function zl(e,t){let r=[],i=[];for(let n of t)e.has(n)||r.push(n);for(let n of e)t.has(n)||i.push(n);return{checked:r,unchecked:i}}function te(e){return(e.pendingRequestIds?.length??0)>0}var R={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var Sn=(e,t)=>{let r=e.getActivity(t);return r!=null&&te(r)},Dn=(e,t,r)=>{let i=[],n=(a,s)=>{let o=t.isChecked(a);t.setChecked(a,s)&&i.push({activityId:a,checked:{before:o,after:s}})};for(let a of r.checked)n(a,!0);for(let a of r.unchecked)n(a,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}};function Tn(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,a=n?o=>n.has(o):o=>Sn(r,o),s=kn({clickedId:i,isChecked:e.isChecked,currentSelection:new Set(r.checkedIds().map(String)),hierarchy:{getChildrenIds:o=>r.getChildren(o),getParentId:o=>{let c=r.getParentId(o);return!c||c==="0"?null:String(c)}},isFrozen:a,exists:o=>r.activityExists(o),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:Dn(e,r,s.changed)}}function _n(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!Sn(r,s))),n=new Set(r.checkedIds().map(String)),a={checked:[...i].filter(s=>!n.has(s)),unchecked:[...n].filter(s=>!i.has(s))};return{ok:!0,changes:Dn(e,r,a)}}function Pn(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=[];return r.forEachActivity((s,o)=>{let c=String(o),l=i.has(c),d=r.isVisible(c);d!==l&&(r.setVisible(c,l),n.push({activityId:c,visible:{before:d,after:l}}))}),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var En="text";var Rn="description";var Ln="duration";var bn="progress";var wn="cost";var On="used_cost";var xn="hhWorkTime";var Nn="start_date";var Fn="end_date";var Mn="constraint_type";var Wn="constraint_date";var Un="calendar_id";var Bn="custom_id";var Hn="subcontractId";var jn="responsables";var Vn="tags";var Yn="custom_predecessors";var $n="custom_sucessors";var Gn="real_work";var Kn="real_cost";var zn="expected_progress";var qn="expected_progress_base";var Jn="start_base";var Xn="end_base";var Zn="duration_base";var Qn="cost_base";var ta="work_base";var ea="calendarDuration";var ra="is_critical",ia="earlyStart",na="earlyFinish",aa="lateStart",sa="lateFinish",oa="freeSlack",ca="totalSlack";var la="correlative_id";var da="unique_correlative_id";var ua="ponderator";var X={FUTURE:"future",PAST:"past"},et={HOUR:"hour",DAY:"day"},Lt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var Be="status";var Jr="Baseline";function He(e){return e==="Actual"?"Actual":Jr}var ql={TEXT:En,DESCRIPTION:Rn,DURATION:Ln,PROGRESS:bn,COST:wn,USED_COST:On,HH_WORK_TIME:xn,START_DATE:Nn,END_DATE:Fn,CONSTRAINT_TYPE:Mn,CONSTRAINT_DATE:Wn,CALENDAR_ID:Un,CUSTOM_ID:Bn,SUBCONTRACT_ID:Hn,RESPONSABLES:jn,TAGS:Vn,CUSTOM_PREDECESSORS:Yn,CUSTOM_SUCESSORS:$n},Jl={REAL_WORK:Gn,REAL_COST:Kn,EXPECTED_PROGRESS:zn,EXPECTED_PROGRESS_BASE:qn,START_BASE:Jn,END_BASE:Xn,DURATION_BASE:Zn,COST_BASE:Qn,WORK_BASE:ta,CALENDAR_DURATION:ea,IS_CRITICAL:ra,EARLY_START:ia,EARLY_FINISH:na,LATE_START:aa,LATE_FINISH:sa,FREE_SLACK:oa,TOTAL_SLACK:ca,CORRELATIVE_ID:la,UNIQUE_CORRELATIVE_ID:da,PONDERATOR:ua,STATUS:Be},E={...ql,...Jl};function fa(e,t){throw new Error(t)}function pa(e,t){return()=>t()===e}var G={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Xl={mso:()=>!0,mfo:()=>!0,snlt:(e,t)=>e<t,snet:(e,t)=>e>t,fnlt:(e,t)=>e<t,fnet:(e,t)=>e>t};function ya(e,t,r){if(!t)return{violated:!1};let i=Xl[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Zl=new Set(["mso","snet","snlt"]);function Ce(e,t,r){return Zl.has(e)?t:r}function ma(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Ql={snet:{startOfDay:!0,direction:X.FUTURE},snlt:{startOfDay:!0,direction:X.PAST},fnet:{startOfDay:!1,direction:X.FUTURE},fnlt:{startOfDay:!1,direction:X.PAST},mso:{startOfDay:!0,direction:X.FUTURE},mfo:{startOfDay:!1,direction:X.PAST}},je=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),ha=(e,t)=>new Date(e.getTime()+t*864e5),td=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Xr(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Ql[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:je(i),dir:X.FUTURE,task:e});if(td(n,i))return i.getTime()!==je(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:ha(je(i),1),dir:X.PAST,task:e});let a=je(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:X.FUTURE,task:e}):t.getClosestWorkTime({date:ha(a,1),dir:X.PAST,task:e})}function ga(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i==="asap"||i==="alap")return r;let n=Xr(e,t);if(!n)return r;let a=o=>t.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e}),s=o=>t.calculateEndDate({startDate:o,durationHours:-e.durationHours,task:e});switch(i){case"snet":return{earliestStart:n,latestStart:null,earliestEnd:a(n),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:a(n)};case"fnet":return{earliestStart:s(n),latestStart:null,earliestEnd:n,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:s(n),earliestEnd:null,latestEnd:n};case"mso":{let o=a(n);return{earliestStart:n,latestStart:n,earliestEnd:o,latestEnd:o}}case"mfo":{let o=s(n);return{earliestStart:o,latestStart:o,earliestEnd:n,latestEnd:n}}default:return r}}function va(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Zr(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var j={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var Ve={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},Ca={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Ye=typeof window>"u",Qr=!Ye&&typeof MessageChannel<"u"?new MessageChannel:null;function rt(){return Ye||!Qr?Promise.resolve():new Promise(e=>{Qr.port1.onmessage=()=>e(),Qr.port2.postMessage(null)})}async function $e(e,t){return performance.now()-e<Ca.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await rt(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ee(e){return Ye||await rt(),e()?{aborted:!1}:{aborted:!0}}function Ge(e,t){let{inDegree:r,successors:i}=ed(e,t),n=rd(r),a=id(n,r,i),s=a.length<e.length,o=s?nd(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function ed(e,t){let r=new Map,i=new Map;for(let n of e)r.set(n,0),i.set(n,[]);for(let n of t){let a=n.source,s=n.target;!r.has(a)||!r.has(s)||(i.get(a).push(s),r.set(s,(r.get(s)??0)+1))}return{inDegree:r,successors:i}}function rd(e){let t=new ft;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function id(e,t,r){let i=[];for(;!e.isEmpty();){let n=e.dequeue();i.push(n);for(let a of r.get(n)??[]){let s=(t.get(a)??1)-1;t.set(a,s),s===0&&e.enqueue(a)}}return i}function nd(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var Ke=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=Ge(t,r),this.cached)}};function Aa(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var ti={project:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:"recursive-leaf-sum",promotesToProjectOnFirstChild:!1},task:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:"own-baseline",promotesToProjectOnFirstChild:!0},milestone:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:"zero",promotesToProjectOnFirstChild:!0}};function ei(e){return e==="project"||e==="task"||e==="milestone"}function St(e,t){return t||ei(e)&&ti[e].alwaysSummary}function Ae(e){return e==="milestone"}function bt(e){return ei(e)&&ti[e].promotesToProjectOnFirstChild}var ri="project",re="task";function Ie(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function Ia(e,t){let r=t.getActivity(e);return r?St(r.type,t.getChildren(e).length>0):!1}function ka(e,t,r){let i=String(t),n=r.getActivity(e);for(;n?.parentId&&String(n.parentId)!=="0";){if(String(n.parentId)===i)return!0;n=r.getActivity(n.parentId)}return!1}function ad(e,t){let r=[],i=[e];for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);if(a.length===0){String(n)!==String(e)&&r.push(n);continue}for(let s of a)i.push(s)}return r}function sd(e){let t=new Map;for(let r of e)Sa(t,String(r.source),r),Sa(t,String(r.target),r);return t}function Sa(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function od(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),a=[];for(let s of e)cd(s,n,t,r,i)||a.push(s);return a.length>0?a:e}function cd(e,t,r,i,n){let a=String(e),s=r.getActivity(e);if(!s||s.autoScheduling===!1)return!1;let o=i.get(a)??[];for(let c of o)if(ld(c,a,s,t,r,n))return!0;return!1}function ld(e,t,r,i,n,a){if(dd(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=ud(e,t);if(!i.has(String(o)))return!1;let c=n.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&fd(e,r,c))}function dd(e){return e.source===e.target}function ud(e,t){return String(e.source)===t?e.target:e.source}function fd(e,t,r){let i=e.lag??0,n=Math.abs(i);return String(e.target)===String(r.id)&&n<=r.durationHours||String(e.target)===String(t.id)&&n<=t.durationHours}function Ta(e,t){let r=[],i=sd(e),n=0;for(let a of e){let s=Ia(a.source,t),o=Ia(a.target,t);if(pd(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=Da(a.source,s,t,i,!0),l=Da(a.target,o,t,i,!1);n=hd(r,c,l,a,t,n)}return r}function pd(e,t,r,i){return r&&ka(e.source,e.target,i)||t&&ka(e.target,e.source,i)}function Da(e,t,r,i,n){return t?od(ad(e,r),r,i,n):[e]}function hd(e,t,r,i,n,a){let s=n.getActivity(i.source),o=n.getActivity(i.target),c=o?.startDate,l=i.lag??0,d=i.type===j.START_TO_START||i.type===j.START_TO_FINISH,u=i.type===j.FINISH_TO_FINISH||i.type===j.START_TO_FINISH,f=d?-(s?.durationHours??0):0,p=u?-(o?.durationHours??0):0,v=a;for(let S of t)for(let C of r)String(S)!==String(C)&&(e.push(yd(i,S,C,v,f,p,l,s,c,n)),v+=1);return v}function yd(e,t,r,i,n,a,s,o,c,l){let d=l.getActivity(r),u=c&&d&&o?l.calculateDuration({startDate:c,endDate:d.startDate,task:o}):0;return{id:`virtual_${e.id}_${i}`,source:t,target:r,type:e.type,lag:e.lag,_sourceLag:n,_targetLag:a,_trueLag:s+u}}var ze=class{invalidate(){}get(t,r){return Ta(t,r)}};function md(e){let t=new Map,r=i=>(t.has(i)||t.set(i,new Set),t.get(i));for(let i of e)r(i.source).add(i.id),r(i.target).add(i.id);return{neighbors:t}}function gd(e,t,r){let i=new Set,n=new Map,a=new ft;for(a.enqueue(e);!a.isEmpty();){let s=a.dequeue(),o=String(s);if(i.has(o))continue;i.add(o);let c=r.neighbors.get(s);if(c)for(let l of c){let d=t.get(l);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;n.has(u)||n.set(u,d);let f=String(d.source)===o?d.target:d.source;i.has(String(f))||a.enqueue(f)}}return Array.from(n.values())}function _a(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let i=md(t),n=gd(e,r,i),a=new Set([String(e)]);for(let s of n)a.add(String(s.source)),a.add(String(s.target));return{activityIds:a,links:n}}function Pa(e,t,r){let i=r.type===j.FINISH_TO_START,n=r.type===j.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:i,isFF:n,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case j.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case j.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case j.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case j.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1}}}function Ea(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s,isFS:o,isFF:c}=Pa(e,t,r);if(!(n!==0||a!==0||s!==0)){let f=o||c;return t.durationHours===0&&f?{successorStart:i.getClosestWorkTime({date:e.endDate,dir:"past",task:t}),link:r}:{successorStart:i.getClosestWorkTime({date:e.endDate,dir:"future",task:t}),link:r}}let d=o?t:e,u=i.getClosestWorkTime({date:e.endDate,dir:"future",task:d});if(n!==0&&(u=i.calculateEndDate({startDate:u,durationHours:n,task:e})),a!==0&&(u=i.calculateEndDate({startDate:u,durationHours:a,task:t})),s!==0&&(u=i.calculateEndDate({startDate:u,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:i.getClosestWorkTime({date:u,dir:"past",task:t}),link:r};let f=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:f,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:u,dir:"future",task:t}),link:r}}function Ra(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s}=Pa(t,e,r),o=i.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return s!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-s,task:e})),a!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-a,task:e})),n!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-n,task:t})),o}function La(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===G.ASAP||a===G.ALAP)continue;let s=ga(n,t);!s.earliestStart&&!s.latestStart&&!s.earliestEnd&&!s.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:s.earliestStart,latestStart:s.latestStart,earliestEnd:s.earliestEnd,latestEnd:s.latestEnd})}}function qe(e,t,r){let i={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},n=t.earliestSchedulingStart??t.latestSchedulingStart??null,a;n===null?a=Zr(e.startDate,i):va(n,i)?a=n:a=Zr(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function ba(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case G.MSO:case G.MFO:return new Date(i);case G.SNET:case G.FNET:return i>t?new Date(i):t;case G.SNLT:case G.FNLT:return i<t?new Date(i):t;default:return t}}function vd(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function wa(e,t,r){return ii(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function ii(e,t,r){return t.dragWithMultiple&&vd(e,r)}async function xa(e,t,r,i,n,a){let s=new Map;for(let u of t){let f=String(u.target);s.has(f)||s.set(f,[]),s.get(f).push(u)}let o=u=>{let f=a.get(u);if(f?.startDate&&f.endDate)return{startDate:f.startDate,endDate:f.endDate};let p=r.getActivity(u);return p?{startDate:p.startDate,endDate:p.endDate}:{startDate:new Date,endDate:new Date}},c=r.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let f=await $e(d,n);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Cd(p,r))continue;let v=s.get(String(u))??[],S=null,C=null;for(let k of v){let y=r.getActivity(k.source);if(!y)continue;let g=o(k.source),A={...y,startDate:g.startDate,endDate:g.endDate},P=wa(A,c,l),_={...A,startDate:P.startDate,endDate:P.endDate},b=ii(k.source,c,l)?{...k,lag:0}:k,x=Ea(_,p,b,r);(!S||x.successorStart>S)&&(S=x.successorStart,C=String(k.id))}let D=a.get(u),m=D?{...D}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},T=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!S&&!T)){if(S){let k=S;p.type===Ve.MILESTONE&&(k=ba(p,S)),m.drivingLinkId=C,m.startDate=k,m.endDate=r.calculateEndDate({startDate:k,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=k,m.earliestSchedulingEnd=m.endDate}else p.constraintType===G.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===G.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));qe(p,m,r),a.set(u,m)}}return a}function Cd(e,t){return St(e.type,t.getChildren(e.id).length>0)}var V="0";function O(e){return e==null||e===0||e==="0"}function $t(e){return O(e)?"0":String(e)}async function Na(e,t,r,i,n,a){let s=new Map(r),o=i.getAllActivities(),c=o.length,l=[];for(let C of o)C.constraintType===G.ALAP&&l.push(C.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let C of t){let D=String(C.source);d.has(D)||d.set(D,[]),d.get(D).push(C);let m=String(C.target);u.has(m)||u.set(m,[]),u.get(m).push(C)}let f=C=>{let D=s.get(C);if(D)return{startDate:D.startDate,endDate:D.endDate};let m=i.getActivity(C);return m?{startDate:m.startDate,endDate:m.endDate}:{startDate:new Date,endDate:new Date}},p=C=>!C.parentId||O(C.parentId)?i.getProjectEnd():f(C.parentId).endDate,v=(C,D)=>{let m=C,T=0;for(;m&&!O(m)&&T++<c+1;){if(String(m)===String(D))return!0;let k=i.getActivity(m);if(!k||!k.parentId)break;m=k.parentId}return!1},S=performance.now();for(let C of e){let D=await $e(S,a);if(D.aborted)return s;S=D.newSliceStart;let m=i.getActivity(C);if(!m||m.constraintType!==G.ALAP||!m.autoScheduling||m.progress===100||St(m.type,i.getChildren(C).length>0))continue;let T=p(m);if(!T)continue;let k=T,y=null,g=!1,A=d.get(String(C))??[];for(let M of A){if((M.lag??0)<0)continue;let J=i.getActivity(M.target);if(!J||J.autoScheduling===!1)continue;let ct=f(M.target),We={...J,startDate:ct.startDate,endDate:ct.endDate},Yt=Ra(We,m,M,i);Yt<k&&(k=Yt),(y===null||Yt<y)&&(y=Yt,g=m.parentId&&!O(m.parentId)?v(M.target,m.parentId):!1)}if(y!==null)if(g)k=y;else{let M=f(C).endDate,J=M.getTime()>T.getTime()?M:T;k=y<J?y:J}else k>T&&(k=T);let P;if(m.durationHours===0&&y===null)P=i.getClosestWorkTime({date:k,dir:"past",task:m});else if(m.durationHours===0)if((u.get(String(C))??[]).some(ct=>ct.type===j.FINISH_TO_START||ct.type===j.FINISH_TO_FINISH)){let ct=new Date(Date.UTC(k.getUTCFullYear(),k.getUTCMonth(),k.getUTCDate()));P=i.getClosestWorkTime({date:ct,dir:"past",task:m})}else P=i.getClosestWorkTime({date:k,dir:"future",task:m});else P=i.getClosestWorkTime({date:k,dir:"future",task:m});let _=i.calculateEndDate({startDate:P,durationHours:-m.durationHours,task:m}),b=s.get(C),x=b?{...b}:{activityId:C,startDate:_,endDate:P,drivingLinkId:null,kind:"alap",conflict:!1};x.startDate=_,x.endDate=P,x.drivingLinkId=null,x.kind="alap",x.earliestSchedulingStart=null,x.earliestSchedulingEnd=null,x.latestSchedulingStart=_,x.latestSchedulingEnd=P,qe(m,x,i),s.set(C,x)}return s}var ie={warn(){},error(){}};function ke(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let i=t.plans.get(r);if(!i)continue;let n=e.getLiveActivity(r);n&&(n.startDate=i.startDate,n.endDate=i.endDate,e.updateActivity(r))}})}function Fa(e,t){let r=String(t.source),i=String(t.target);if(r===i)return!0;let n=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=n.get(s)??[];c.push(o),n.set(s,c)}return Ad(n,i,r)}function Ad(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new ft;for(n.enqueue(t);!n.isEmpty();){let a=n.dequeue(),s=e.get(a)??[];for(let o of s){if(o===r)return!0;i.has(o)||(i.add(o),n.enqueue(o))}}return!1}function wt(e,t){switch(e.kind){case"create":return Id(e,t);case"update":return kd(e,t);case"delete":return Sd(e,t)}}function Id(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:"activity-missing"};let a=r.getAllLinks();for(let l of a)if(String(l.source)===String(e.source)&&String(l.target)===String(e.target)&&l.type===e.type)return{applied:!1,rejected:"duplicate",linkId:l.id};let s=a.map(l=>({source:l.source,target:l.target}));if(Fa(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Dd)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function kd(e,t){let{port:r}=t;return r.getLink(e.linkId)?(e.lag!==void 0&&r.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&r.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}function Sd(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}var Je=null;function Dd(){return Je===null&&(Je=Date.now()),Je+=1,String(Je)}var Ma={[j.FINISH_TO_START]:"fs",[j.START_TO_START]:"ss",[j.FINISH_TO_FINISH]:"ff",[j.START_TO_FINISH]:"sf"},Gt={fs:j.FINISH_TO_START,ss:j.START_TO_START,ff:j.FINISH_TO_FINISH,sf:j.START_TO_FINISH},Wa="fs";function Ua(e){if(e in Gt)return Gt[e]}var Ba=";",Ha=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Xe(e){let t=[],r=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:r};for(let n of i.split(Ba)){if(n.length===0)continue;let a=Td(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function Td(e){let t=e.toLowerCase(),r=Ha.exec(t);if(!r)return null;let[,i,n,a,s]=r,o=n?Gt[n]:Gt[Wa],c=0;if(s!==void 0){let l=Number(s);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:i,type:o,lag:c}}function Qe(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Ze(l,c.type);a.has(d)||a.set(d,{source:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.target)===String(t)&&s.set(Ze(c.source,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:l.source,target:t,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function Ze(e,t){return`${String(e)}::${t}`}function tr(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Ze(l,c.type);a.has(d)||a.set(d,{target:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.source)===String(t)&&s.set(Ze(c.target,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:t,target:l.target,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function pt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var ja={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:X.FUTURE,date:e,unit:et.HOUR}):t.isWorkTime(e,et.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function ni(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var ai=ja;var er=class{adapter;reporter;currentCalculationId=0;topoCache=new Ke;expandedLinksCache=new ze;constructor(t,r=ie){this.adapter=t,this.reporter=r}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let r=++this.currentCalculationId,i=pa(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Rd(this.adapter);let a=Ot("schedule.total"),s=Ot("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Dt(s);let l=c;if((await ee(i)).aborted)return{...n,cancelled:!0};let d=Ot("schedule.scoping"),u=this.adapter.getAllIds(),f=l,p=u,v=null;if(t.triggerId!==void 0&&t.triggerId!==null){let _=_a(t.triggerId,l);f=_.links,p=Array.from(_.activityIds),v=new Set(p)}Dt(d);let S=Ot("schedule.topologicalSort"),C=Ld(this.topoCache,u,l,v);if(Dt(S),C.hasCycles)return Dt(a),{...n,cycles:[C.cycleNodes]};if((await ee(i)).aborted)return{...n,cancelled:!0};let D=Ot("schedule.processConstraints"),m=new Map;if(La(C.ordered,this.adapter,m),Dt(D),(await ee(i)).aborted)return{...n,cancelled:!0};let T=Ot("schedule.asapPass"),k=await xa(C.ordered,f,this.adapter,t,i,m);if(Dt(T),(await ee(i)).aborted)return{...n,cancelled:!0};let y=Ot("schedule.alapPass"),g=await Na(C.reversed,f,k,this.adapter,t,i);if(Dt(y),(await ee(i)).aborted)return{...n,cancelled:!0};let A=Ot("schedule.diff"),P=[];for(let[_,b]of g){let x=this.adapter.getActivity(_);if(!x)continue;let M=x.startDate.getTime()!==b.startDate.getTime(),J=x.endDate.getTime()!==b.endDate.getTime();(M||J)&&P.push(_)}return Dt(A),Dt(a),{plans:g,updatedIds:P,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},Pd=!1;function Ed(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Pd}function Ot(e){return{name:e,startedAt:performance.now()}}function Rd(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Dt(e){if(!Ed())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Ld(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let s=i?Array.from(i):t;return Ge(s,r)}if(!i)return n;let a=Aa(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function Va(e,t){let r=t.getActivity(e);if(!r)return;let i=t.calendarReader.getCalendar(String(r.calendarId));for(let n of t.getIncomingLinkIds(e)){let a=t.getLink(n);if(!a)continue;let s=t.getActivity(a.source);if(!s||s.constraintType==="alap")continue;let{sourceDate:o,targetDate:c}=ni(s,r,a.type),l=ai.computeLagBetweenTasks(o,c,i);l!==a.lag&&wt({kind:"update",linkId:a.id,lag:l},{port:t})}}function Ya(e,t){let r=t.getActivity(e);r&&Ae(r.type)&&(r.durationHours=0)}function ne(e){let t=0,r=!1;for(let i of e)i.ponderator>0&&(t+=i.ponderator/100*i.progress,r=!0);return r?t:null}function rr(e){return Number(e.toFixed(2))}function lt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function Se(e,t,r=!0,i={}){let n=t?wd(e,t):Fd(e);await bd(n,e,r,{recomputeRealWork:i.recomputeRealWork??!1})}function ir(e,t){$a(e,t,!1)}async function bd(e,t,r=!0,i={recomputeRealWork:!1}){let a=0;for(let s of e)$a(s,t,r,i.recomputeRealWork),a+=1,a%200===0&&await rt()}function wd(e,t){let r=new Set;for(let a of t)Od(a,e,r);if(r.size===0)return[];let i=Array.from(r),n=Ga(i,e);return Ka(i,n)}function Od(e,t,r){let i=t.getParentId(e);for(;i&&!O(i);){if(r.has(i))return;r.add(i),i=t.getParentId(i)}}function xd(e,t,r){let i=null,n=null,a=0,s=[];for(let o of e){let c=t.getActivity(o);if(!c)continue;let l=c.startDate.getTime(),d=c.endDate.getTime();(i===null||l<i)&&(i=l),(n===null||d>n)&&(n=d),r&&(a+=Nd(c,t.getChildren(o).length>0)),s.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:n,realWorkSum:a,weightedChildren:s}}function $a(e,t,r=!0,i=!1){let n=t.getActivity(e);if(!n)return;let a=t.getChildren(e);if(a.length===0)return;let s=xd(a,t,i);if(s.minStart===null||s.maxEnd===null)return;let o=String(n.calendarId??""),c=t.calendarReader.getCalendar(o),l=new Date(s.minStart),d=new Date(s.maxEnd),u=c.calculateDuration(l,d);t.setActivityField(e,"startDate",l),t.setActivityField(e,"endDate",d),t.setActivityField(e,"durationHours",u);let f=ne(s.weightedChildren);r&&f!==null&&t.setActivityField(e,"progress",rr(f)),i&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function Nd(e,t){return t?Number(e.realWorkHours)||0:lt(e.workHours,e.progress)}function Fd(e){let t=Md(e),r=Ga(t,e);return Ka(t,r)}function Md(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Ga(e,t){let r=new Map;for(let i of e)r.set(i,Wd(i,t));return r}function Wd(e,t){let r=0,i=e;for(;i&&!O(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Ka(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var za={updateActivityDuration:Ya,updateTaskTiming:Bd("updateTaskTiming"),adjustLinkLagOnTaskMove:Va,recordLastStartDate:Ud};function Ud(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function xt(e,t,r){for(let i of t){let n=i in za?za[i]:void 0;if(!n){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}n(e,r)}}function Bd(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function w(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function N(e){return{ok:!1,reason:e}}function W(){return{valid:!0}}function Q(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function U(){return{allowed:!0}}function q(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function F(e,t={}){return{patch:e,needsAutoSchedule:t.autoSchedule??!1,postProcessors:t.postProcessors??[],...t.cascadeMutations!==void 0?{cascadeMutations:t.cascadeMutations}:{},...t.trackingEvents!==void 0?{trackingEvents:t.trackingEvents}:{}}}var qa={targetField:"name",canEdit(){return U()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e)},validate(){return W()},transform(e,t){return F({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var Ja={targetField:"description",canEdit(){return U()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e.trim())},validate(){return W()},transform(e,t){return F({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function It(e){return e.constraintType??G.ASAP}var nr=100;function ae(e){return e.progress>=nr}function tt(e,t){return St(e.type,t.hasChildren(e.id))}function Xa(e){return e.progress>0}function Za(e){return e.hasLookaheadTasks}function De(e,t){return Math.round(Math.ceil(e*t*60)/60)}var se=e=>({endDate:e});function Kt(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=n=>Number(r.find(a=>a.type===n)?.value);return new Date(Date.UTC(i("year"),i("month")-1,i("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function Te(e,t){if(!t||t==="UTC"){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=f=>Number(r.find(p=>p.type===f)?.value),n=i("year"),a=i("month"),s=i("day"),o=Date.UTC(n,a-1,s,23,59,0,0),c=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(o)),l=f=>Number(c.find(p=>p.type===f)?.value),u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")===24?0:l("hour"),l("minute"),l("second"))-o;return new Date(o-u)}function Hd(e,t){let r=Kt(t);for(;!e.isWorkTime(r,et.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Kt(r);return r}function si(e,t){return e.getClosestWorkTime({direction:X.FUTURE,date:t,unit:et.HOUR})}function oi(e,t){let r=Hd(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:X.PAST,date:i,unit:et.HOUR})}var ar=new Set(["snet","snlt","mso"]),ci=new Set(["fnet","fnlt","mfo"]),Nt=new Set(["asap","alap"]),sr="snet";function Tt(e,t,r){if(!ar.has(r)&&!ci.has(r))return e;let i=ar.has(r)?si(t,e):oi(t,e),n=new Date(e);return n.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),n}var _t=()=>({constraintType:sr});var Ft=e=>({constraintDate:e}),Qa=e=>({constraintDate:e});var ts={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var es={UNCHANGED:"unchanged",OUT_OF_RANGE:"out_of_range",NEGATIVE_DURATION:"negative_duration",NOT_WORKING_DAY:"not_working_day",BEFORE_PARENT_START:"before_parent_start",BEFORE_START_DATE:"before_start_date",BEFORE_DATE_ORIGIN:"before_date_origin",CONSTRAINT_VIOLATION:"constraint_violation",MISSING_ID:"missing_id"};function oe(e,t,r){return ya(e,t,r)}function ce(e,t,r){return ma(e,t,r)}var is={targetField:"durationHours",canEdit(e,t){return ae(e)?q("completed","cant_edit_completed_activity"):tt(e,t)?q("summary","summary_column_value"):U()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isNaN(i)?N("not_a_number"):w(r.inputUnit==="hours"?i:De(i,r.hoursPerDay))},validate(e,t,r){return rs(r)?Q(es.NEGATIVE_DURATION):jd(t,r)?Q("unchanged"):W()},transform(e,t,r){if(rs(t))return F({},{autoSchedule:!1,postProcessors:[]});let i=Vd(e,t,r),n=Yd(e,t,r,i.violated);return{...F(n,{autoSchedule:e.constraintType!=="alap",postProcessors:[ts.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:ce(i.constraintType,i.constraintDate,ns(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function rs(e){return Math.sign(e)===-1}function jd(e,t){return e===t}function Vd(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!=="fnet"&&n!=="fnlt"&&n!=="mfo")return{violated:!1};let a=i.calculateEndDate(e.startDate,t);return oe(n,e.constraintDate,a)}function Yd(e,t,r,i=!1){let n={};i&&Object.assign(n,_t(),Ft(e.startDate));let a=Ie(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let s=ns(e,t,r);return s&&Object.assign(n,se(s)),n}function ns(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var le=e=>({realWorkHours:e});var $d=0,Gd=nr,as=0,ss={targetField:"progress",canEdit(e,t){return Za(e)?q("has_lookahead_tasks","cant_edit_actvity_with_task"):tt(e,t)?q("summary","summary_column_value"):U()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(e,t,r){return Kd(r)?Q("out_of_range"):W()},transform(e,t,r){let i=zd(t),n=qd(t),a=Zd(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...le(a.get(e.id)??0)},o=n?Jd(e,t,i,r.hierarchy,a):[],c=n?Qd(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=n?eu(e,t):void 0;return F(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function Kd(e){return e<$d||e>Gd}function zd(e){return e===as}function qd(e){return e===nr||e===as}function Jd(e,t,r,i,n){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:Xd(t,r,n.get(s)??0)}))}function Xd(e,t,r){return{progress:e,autoScheduling:t,...le(r)}}function Zd(e,t,r){let i=new Map,n=s=>{let o=0;for(let c of r.getChildHhInfo(s)){let l=r.hasChildren(c.id)?n(c.id):lt(c.workHours,t);i.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?n(e.id):lt(e.workHours,t);return i.set(e.id,a),i}function Qd(e,t,r){let i=new Map;i.set(e.id,t);for(let s of r.getDescendantIds(e.id))i.set(s,t);let n=[];for(let s of r.getAncestorIds(e.id))n.push(s);let a=[];for(let s of n){let o=tu(s,i,r);i.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function tu(e,t,r){let i=r.getChildProgressInfo(e).map(n=>({progress:t.has(n.id)?t.get(n.id):n.progress,ponderator:n.ponderator??0}));return Number((ne(i)??0).toFixed(2))}function eu(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var os={targetField:"cost",canEdit(e,t){return tt(e,t)?q("summary","summary_column_value"):U()},parseInput(e,t){if(String(e).trim()==="")return w(t.cost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return W()},transform(e,t,r){let i=ru(e,t,r.hierarchy);return F({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_entry"};function ru(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.cost;i.set(a,s),n.push({activityId:a,fields:{cost:s}})}return n}var cs={targetField:"usedCost",canEdit(e,t){return tt(e,t)?q("summary","summary_column_value"):U()},parseInput(e,t){if(String(e).trim()==="")return w(t.usedCost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return W()},transform(e,t,r){let i=iu(e,t,r.hierarchy);return F({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function iu(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildUsedCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.usedCost;i.set(a,s),n.push({activityId:a,fields:{usedCost:s}})}return n}var ls={targetField:"workHours",canEdit(e,t){return tt(e,t)?q("summary","summary_column_value"):U()},parseInput(e){if(String(e).trim()==="")return w(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(){return W()},transform(e,t,r,i){let n=ds(t,e.progress),a=String(i).trim()===""?[]:nu(e,t,n,r.hierarchy);return F({workHours:t,...le(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function ds(e,t){return lt(e,t)}function nu(e,t,r,i){let n=new Map,a=new Map;n.set(e.id,t),a.set(e.id,r);let s=[];for(let o of i.getAncestorIds(e.id)){let c=0,l=0;for(let d of i.getChildHhInfo(o)){let u=n.has(d.id)?n.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??ds(d.workHours,d.progress);c+=u,l+=f}n.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...le(l)}})}return s}function or(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function li(e,t){return e.getTime()<t.getTime()}function de(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var cr=e=>({durationHours:e});var us={targetField:"startDate",canEdit(e,t){return tt(e,t)?q("summary","summary_column_value"):Xa(e)?q("has_progress","cant_edit_activity_with_progress"):U()},parseInput(e,t,r){return de(e)?w(Kt(e,"UTC")):N("invalid_date")},validate(e,t,r,i){if(or(t,r))return Q("unchanged");let n=au(e,r,i);return n||W()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return F({startDate:t,..._t(),...Ft(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let n=si(i,t),a=e.type==="milestone",s=a?n:i.calculateEndDate(n,e.durationHours),o=n;return{...F({startDate:n,...se(s),...a?cr(0):{},..._t(),...Ft(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:su(e,n,i)}},trackEvent:"activity_start_date_entry"};function au(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=Kt(i);return t.getTime()<n.getTime()?Q("before_parent_start"):null}function su(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=Ce(It(e),t,i),a=oe(It(e),e.constraintDate,n);if(a.violated)return ce(a.constraintType,a.constraintDate,n)}var ou=99.999,fs={targetField:"endDate",canEdit(e,t){return tt(e,t)?q("summary","summary_column_value"):cu(e)?q("completed","cant_edit_completed_activity"):U()},parseInput(e,t,r){if(!de(e))return N("invalid_date");let i=Kt(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,et.DAY)?w(oi(n,i)):r.dateFormat.split(" ").length>1?w(i):w(n.getClosestWorkTime({direction:"past",date:i,unit:et.HOUR})):w(i)},validate(e,t,r,i){if(or(e.endDate,r))return Q("unchanged");if(lu(r,e))return Q("before_date_origin");if(du(r,e))return Q("before_start_date");let n=uu(r,e,i);return n||W()},transform(e,t,r){let i=fu(e,t),n=pu(e,t,r,!!i);return{...F(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function cu(e){return e.progress>=ou}function lu(e,t){return t.dateOrigin?li(e,t.dateOrigin):!1}function du(e,t){return li(e,t.startDate)}function uu(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,et.DAY)?null:Q("not_working_day"):null}function fu(e,t){let r=Ce(It(e),e.startDate,t),i=oe(It(e),e.constraintDate,r);if(i.violated)return ce(i.constraintType,i.constraintDate,r)}function pu(e,t,r,i=!1){let n={},a=Ae(e.type);a&&!i?Object.assign(n,Ft(e.startDate)):(i||hu(e))&&Object.assign(n,_t(),Ft(e.startDate));let s=yu(e,t,r);if(!a){let o=Ie(e.durationHours,s);o&&(n.type=o)}return Object.assign(n,cr(s)),n.endDate=t,n}function hu(e){return Nt.has(It(e))}function yu(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var mu=new Set(Object.values(G)),ps={targetField:"constraintType",canEdit(e,t){return ae(e)?q("completed","cant_edit_completed_activity"):tt(e,t)?q("summary","summary_column_value"):U()},parseInput(e){let t=String(e).toLowerCase();return gu(t)?w(t):N("invalid_constraint_type")},validate(){return W()},transform(e,t,r){let i=vu(e,t,r);return F(i,{autoSchedule:!0})}};function gu(e){return mu.has(e)}function vu(e,t,r){let i=Au(e,t);return{constraintType:t,...Qa(Cu(e,t,i,r))}}function Cu(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?Tt(r,n,t):r}function Au(e,t){return Nt.has(t)?null:ar.has(t)?e.startDate:ci.has(t)?e.endDate:e.constraintDate}var hs={targetField:"constraintDate",canEdit(e,t){return ae(e)?q("completed","cant_edit_completed_activity"):tt(e,t)?q("summary","summary_column_value"):U()},parseInput(e){return de(e)?w(e):N("invalid_date")},validate(){return W()},transform(e,t,r){let i=ys(e)?sr:It(e),n=r.calendars.getCalendar(e.calendarId),a=n?Tt(t,n,i):t,s=Iu(e,a);return F(s,{autoSchedule:!0})}};function Iu(e,t){return{constraintDate:t,...ys(e)?_t():{}}}function ys(e){return Nt.has(It(e))||!e.constraintType}var ms={targetField:"calendarId",canEdit(){return U()},parseInput(e){let t=String(e).trim();return ku(t)?N("empty_calendar"):w(t)},validate(e,t,r){return Su(e.calendarId,r)?Q("unchanged"):W()},transform(e,t,r){return F(Du(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function ku(e){return e===""}function Su(e,t){return e===t}function Du(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,s=a?Tu(e.startDate):e.startDate,o=n.getClosestWorkTime({date:s,direction:"future",unit:"hour"});if((!e.autoScheduling||a||n.getWorkHours(e.startDate).length===0)&&(i.startDate=o),!e.autoScheduling)return i;let c=i.startDate??e.startDate;Object.assign(i,se(n.calculateEndDate(c,e.durationHours)))}return i}function Tu(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var gs={targetField:"customId",canEdit(){return U()},parseInput(e){if(e==null)return N("empty_custom_id");if(typeof e!="string")return N("not_a_string");let t=e.trim();return t.length===0?N("empty_custom_id"):t.length>20?N("exceeds_max_length"):w(t)},validate(){return W()},transform(e,t){return F({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var vs={targetField:"subcontractId",canEdit(){return U()},parseInput(e){if(e==null)return w(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return w(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?N("not_an_integer"):w(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?N("not_an_integer"):w(e):N("not_an_integer")},validate(){return W()},transform(e,t){return F({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function _e(e){if(e==null)return null;if(typeof e=="object"){if(!("id"in e))return null;let t=e.id;return t==null?null:String(t)}return String(e)}function lr(e){return e.some(t=>_e(t)===null)}var Cs={targetField:"responsableIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return lr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(_e).filter(i=>i!==null);return F({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var As={targetField:"tagIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return lr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(_e).filter(i=>i!==null);return F({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var _u=new Map([[E.TEXT,qa],[E.DESCRIPTION,Ja],[E.DURATION,is],[E.PROGRESS,ss],[E.COST,os],[E.USED_COST,cs],[E.HH_WORK_TIME,ls],[E.START_DATE,us],[E.END_DATE,fs],[E.CONSTRAINT_TYPE,ps],[E.CONSTRAINT_DATE,hs],[E.CALENDAR_ID,ms],[E.CUSTOM_ID,gs],[E.SUBCONTRACT_ID,vs],[E.RESPONSABLES,Cs],[E.TAGS,As]]);function Mt(e){return _u.get(e)}function ue(e,t){if(!t||t.type!=="constraint")return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:"constraint_violation",activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var L={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath",PROMOTION_RESTORE:"promotionRestore"},di={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};var Pu=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],Is=new Set(Pu);function Z(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function ks(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function Wt(e,t){let r=new Set([String(e)]);for(let i of t.cascadeMutations??[])r.add(String(i.activityId));return r}function Y(e,t){let r=new Map;for(let i of t){let n=e.getActivity(i);n&&r.set(i,K(n))}return r}function K(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:e.constraintDate?new Date(e.constraintDate):null,dateOrigin:e.dateOrigin?new Date(e.dateOrigin):null}}function Ut(e,t,r){Ss(e,t,r.patch);for(let i of r.cascadeMutations??[])Ss(e,i.activityId,i.fields)}function Ss(e,t,r){for(let[i,n]of Object.entries(r)){if(!Is.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);Z(e,t,i,n)}}function Ds(e,t,r){let i=[];for(let n of r){let a=e.getActivity(n);if(!a){i.push({id:n,kind:"deleted",after:null});continue}let s=t.get(n),o=ui(s,a);s&&Object.keys(o).length===0||(s?i.push({id:n,kind:"updated",fields:o,after:K(a)}):i.push({id:n,kind:"created",fields:o,after:K(a)}))}return i}function ui(e,t){let r={},i=e??{},n=t,a=new Set([...Object.keys(i),...Object.keys(n)]);for(let s of a)_s(i[s],n[s])||(r[s]={before:i[s],after:n[s]});return r}function dr(e,t,r){let i=new Set;i.add(e);for(let n of t)i.add(n);for(let n of r)i.add(n);return i}function Ts(e,t){let r=new Set;for(let i of e)r.add(String(i));for(let i of t)r.add(i);return r}function ur(e,t,r,i,n){for(let a of t){if(r.has(a.activityId)||(n.add(a.activityId),i.has(a.activityId)))continue;let s=e.getActivity(a.activityId);if(!s)continue;let o=K(s);a.before!==void 0&&(o.correlativeId=a.before),i.set(a.activityId,o)}}function _s(e,t){if(e===t)return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!_s(e[r],t[r]))return!1;return!0}return!1}var Eu=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Pt(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let o=new Date(e);if(Number.isNaN(o.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return o}let t=e.match(Eu);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,i,n,a,s]=t;return new Date(Date.UTC(Number(r),Number(i)-1,Number(n),Number(a),Number(s)))}function fe(e,t,r,i){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let n=i.calculateDuration(e,r),a=i.calculateDuration(e,t);return a===0?0:n*100/a}var Ru=e=>e.type==="project",Lu=(e,t,r)=>{let i=e.calendarId,n=i!=null?r.calendarReader.getCalendar(String(i)):null;if(!n)return 0;let a=s=>s instanceof Date?s:Pt(String(s));return fe(a(e.startDate),a(e.endDate),t,n)};function bu(e,t,r){let i=[],n=(s,o)=>{let c=r.getActivity(s);c&&c.expectedProgress!==o&&(r.setActivityField(s,"expectedProgress",o),i.push(String(s)))},a=s=>{let o=r.getActivity(s);if(!o)return 0;if(!Ru(o)){let d=Lu(o,t,r);return n(s,d),d}let c=0;for(let d of r.getChildren(s)){let u=a(d),f=r.getActivity(d),p=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*p}let l=c/100;return n(s,l),l};for(let s of e)a(s);return i}function Et(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),bu(r,t,e)}function at(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var wu=e=>e.type==="project",Ou=e=>at(e),xu=(e,t,r,i)=>{let n=Ou(e);if(!n)return 0;let a=(n.baseCalendarId!=null?r.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(i?r.getBaseCalendar(i):null);return!a||!n.startDate||!n.endDate?0:fe(n.startDate,n.endDate,t,a)};function fi(e,t,r,i=null){let n=[],a=(o,c)=>{let l=r.getActivity(o);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(o,"expectedProgressBaseline",c),n.push(o))},s=o=>{let c=r.getActivity(o);if(!c)return 0;if(!wu(c)){let u=xu(c,t,r,i);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),p=r.getActivity(u),v=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*v}let d=l/100;return a(o,d),d};for(let o of e)s(o);return n}function Bt(e,t,r=null){let i={getChildrenIds:a=>e.getChildren(String(a)).map(s=>String(s)),getActivity:a=>e.getActivity(a),setActivityField:(a,s,o)=>Z(e,a,s,o),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},n=[];return e.forEachActivity((a,s)=>{a.parentId===null&&n.push(s)}),fi(n,t,i,r)}var Ps=e=>Math.round(e*100)/100;function Nu(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Fu(e,t){let r=Ps(e),i=Ps(t);return r>99.99?Lt.DONE:i>r?Lt.OVERDUE:e>0&&r>i?Lt.ADVANCEMENT:e===0&&t===0?Lt.WAITING:e>0&&r<i?Lt.DOING:Lt.WAITING}function vt(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,s=Fu(a,Nu(i,t));i.status!==s&&(Z(e,n,Be,s),r.push(n))}),r}function pi(e){let t=e instanceof Date?new Date(e.getTime()):e&&typeof e=="object"&&typeof e.valueOf=="function"?new Date(e.valueOf()):new Date(e),r=(n,a)=>s=>s===void 0?t[n]():(t[a](s),i),i={__isMomentShim:!0,clone:()=>pi(t),hours:r("getUTCHours","setUTCHours"),minutes:r("getUTCMinutes","setUTCMinutes"),seconds:r("getUTCSeconds","setUTCSeconds"),milliseconds:r("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return i}pi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var ht=pi;function Mu(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function fr(e){return Mu(e)&&!isNaN(e.getTime())}function I(e,t,r,i){if(!fr(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(i)}`);let n=t;return e.calculateEndDate({start_date:new Date(n),duration:r,unit:"hour",task:i})}function dt(e){if(!fr(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:i,activity:n}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:i,unit:"hour",task:n})}var Wu=e=>e?e.$level===1:!1,Uu=e=>e.type==="project",Bu=e=>e.$level!==0,Hu=e=>e.type==="task",ju=e=>e.type==="task"||e.type==="milestone",it={byFirstLevel:Wu,filterByParentType:Uu,avoidSubproject:Bu,byTaskType:Hu,byTaskTypeAndMilestone:ju};var h=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var B=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function qt(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Es(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=Vu({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=Yu({gantt:t,subprojectsWithNoLinks:a}),o=$u({gantt:t,childrenIds:s,linkProperty:n,getArrayOfLinkedActivities:Gu,calculations:i});return new Set(o.map(c=>c.id))}catch(a){throw a}}function Vu(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(it.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function Yu(e){let{gantt:t,subprojectsWithNoLinks:r}=e,i=new Set;for(let n of r)t.getChildren(n).filter(o=>{let c=t.getTask(o),l=it.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>i.add(o));return[...i]}function $u(e){let{gantt:t,childrenIds:r,linkProperty:i,getArrayOfLinkedActivities:n,calculations:a}=e,s=[];for(let o of r){let c=t.getTask(o),l=c[i]||[];n({gantt:t,links:l,linkDirection:i==="$source"?"target":"source"}).every(f=>a.has(f))&&s.push(c)}return s}function Gu(e){let{gantt:t,links:r,linkDirection:i}=e,n=[];for(let a of r){let s=t.getLink(a);if(!s){`${a}`;continue}let o=Number(s[i]);n.push(o)}return n}function Rs({gantt:e,linkProperty:t,direction:r}){try{let i=Ku(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return zu(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function Ku(e,t){return e.getTaskByTime().filter(it.avoidSubproject).filter(it.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function zu(e,t,r){let i=[],n=new Set;return e.forEach(a=>{let s=Number(a.parent),o=t.getTask(s);o&&(o[r].length>0?n.add(a.id):o.constraint_type!=="fnlt"&&i.push(a))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function Ls({gantt:e,direction:t,linkProperty:r}){try{let i=qu(e),n=new Set,a=new Set,s=new Set;t==="backward"&&Zu(i).forEach(d=>{n.add(d.id)});let o=Ju(i,t,r),c=Xu(i,o);return o.forEach(l=>{a.add(l.id)}),c.forEach(l=>{s.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:a,pendingParentsWithLinks:s}}catch(i){throw i}}function qu(e){return e.getTaskByTime().filter(it.filterByParentType).filter(it.avoidSubproject)}function Ju(e,t,r){return e.filter(i=>{let n=i[r];if(!Array.isArray(n))return!1;let a=n.length>0,s=i.constraint_type||"",o=s!=="fnlt";return t==="forward"?!a&&o&&s!=="snet":!a&&o})}function Xu(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function Zu(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function bs({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),s=Qu(r),o=tf(r),c=a[s];if(!Array.isArray(c))return;ef(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function Qu(e){return e==="forward"?"$source":"$target"}function tf(e){return e==="forward"?"target":"source"}function ef(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var Pe={identifySecondLevelActivities:Es,identifyInitialActivities:Rs,identifyParentsWithAndWithoutLinks:Ls,identifyForbiddenActivities:bs};function pr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function hi({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===B.FS&&t===0?dt({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):Ee(r,e,i,n)}function ws({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:I(r,n,e,i),ef:n}}function Os({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),a=I(r,n,e,i);return{es:n,ef:a}}function Ee(e,t,r,i){if(![B.FS,B.SS,B.FF].includes(t))return e;let a=[B.FS,B.SS].includes(t)?"future":"past";return dt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:i})}var yi=class{constructor(t,r,i){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=i,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=pr(t),i=this.activity.constraint_type;return i==="snet"?this.handleSNETConstraint(r):i==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=qt(i),a=r.linkLag,s=r.es,o=r.ef,c=null;if(n==="ss")c=this.calculateSSLink({lag:a,predecessorEs:s});else if(n==="ff")c=this.calculateFFLink({lag:a,predecessorEf:o});else if(n==="fs")c=this.calculateFSLink({lag:a,predecessorEf:o});else if(n==="sf")c=this.calculateSFLink({lag:a,predecessorEs:s,predecessorEf:o});else continue;c&&t.push(c)}return t}handleSNETConstraint(t){let r=Os({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>r.ef?t:r}handleFNLTConstraint(t){let r=ws({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>r.ef?r:t:r}calculateSSLink({lag:t,predecessorEs:r}){let i=hi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity);t>0&&(n=Ee(n,"ss",this.activityCalendar,this.activity));let a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let i=hi({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(a=Ee(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=dt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let i=I(this.activityCalendar,r,t,this.activity),n=I(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=Ee(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},xs=yi;var mi=class{constructor(t){this.linkedActivitiesData=t.linksWithActivityData,this.activity=t.activity,this.gantt=t.gantt}calculate(){if(this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let t=[];for(let r of this.linkedActivitiesData){let i=qt(r.linkType);if(r.type==="task"&&Number(r.progress)>0||r.type==="project"&&Number(r.progress)===100)continue;let n=r.linkLag,a=r.ls,s=r.lf;if(i==="ss"){let o={lag:n,workTime:a,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(o);t.push({ls:c,lf:l})}if(i==="ff"){let o={lag:n,workTime:s,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFFLink(o);t.push({ls:c,lf:l})}if(i==="fs"){let o={lag:n,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFsLink(o);t.push({ls:c,lf:l})}if(i==="sf"){let o={lag:n,workTime:s,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(o);t.push({ls:c,lf:l})}}if(this.activity.constraint_type==="fnlt"){let r=this.getMinLfFromLinks(t),i=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([i,r]):i}else{let r=this.getMinLfFromLinks(t);if(r===!1){let i=this.gantt.getSubtaskDates();return{ls:I(this.activityCalendar,i.end_date,-this.activity.duration,this.activity),lf:i.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null;if(t===0)return a=I(this.activityCalendar,r,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=I(this.activityCalendar,o,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return s=I(this.activityCalendar,l,n,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=I(this.activityCalendar,s,i,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=I(this.activityCalendar,c,n,this.activity),o=I(this.activityCalendar,s,i,this.activity),a||(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),{ls:o,lf:s}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null,o=r;return s=I(this.activityCalendar,o,i,this.activity),a=I(this.activityCalendar,s,n,this.activity),{ls:s,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0)return o=I(this.activityCalendar,r,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),o=I(this.activityCalendar,c,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:I(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=ht(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),dt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),ht.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}},Ns=mi;function Fs(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:s}=e,o=t[r],c=rf(t),l=null;if(s==="forward"){let d=nf(o,i,n,a);l=new xs(d,t,a),l=l.calculate()}else{let d=af(o,i,n,a);l=new Ns({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function rf(e){return{duration:e.duration,calendarId:e.calendar_id}}function nf(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);return o?{es:o.es,ef:o.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${s}`),null)}).filter(Boolean)}function af(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);if(!o)return null;let c=i.getTask(s);return c?{ls:o.ls,lf:o.lf,linkLag:a.lag||0,linkType:a.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function Us(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(sf(t.id,r))return null;let a=of(t.id,i),s=cf(a,r);return s.length===0?null:lf(s,n)}function sf(e,t){return t.has(e)}function of(e,t){let r=t.get(e);return r?r.childrens:[]}function cf(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function lf(e,t){if(t==="forward"){let r=Ms(e,"es"),i=Ws(e,"ef");return{es:r,ef:i}}else{let r=Ms(e,"ls"),i=Ws(e,"lf");return{ls:r,lf:i}}}function Ms(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function Ws(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var gi={parentWithLinks:Fs,parentWithNoLinks:Us};var vi=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction==="forward"?"$target":"$source",this.linkDirection=t.direction==="forward"?"source":"target",this.calculationsOfParentThatImpactChildrens=t.calculationsOfParentThatImpactChildrens,this.calculations=t.calculations,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.parentCalculationFromChildren=t.parentCalculationFromChildren,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let i=[h.FNLT];if(this.shouldCalculateParentWithLinksBackward(i)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(i)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(t)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction==="forward"&&this.setDatesToParentsWithLinks(),this.direction==="backward"&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(t){throw t}}shouldCalculateParentWithLinksBackward(t){let r=t.includes(this.activity.constraint_type),i=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}calculateAndStoreParentWithLinks(t){let r=gi.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),i=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}handleParentWithNoLinks(){let t=gi.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});t&&this.calculations.set(this.activity.id,t)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minEs:n,maxEf:a}=i.reduce((s,{es:o,ef:c})=>({minEs:new Date(Math.min(s.minEs.getTime(),new Date(o).getTime())),maxEf:new Date(Math.max(s.maxEf.getTime(),new Date(c).getTime()))}),{minEs:new Date(i[0].es),maxEf:new Date(i[0].ef)});this.calculations.set(this.activity.id,{es:n,ef:a}),this.parentCalculationFromChildren.add(this.activity.id)}setDatesToParentsWithLinksBackward(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minLs:n,maxLf:a}=i.reduce((s,{ls:o,lf:c})=>({minLs:new Date(Math.min(s.minLs.getTime(),new Date(o).getTime())),maxLf:new Date(Math.max(s.maxLf.getTime(),new Date(c).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(this.activity.id,{ls:n,lf:a})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}},Bs=vi;var Ci=class{constructor({gantt:t,linkProperty:r}){this.gantt=t,this.linkProperty=r,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let r of t){let i=this.processEachActivity(r),{activitiesByLevel:n}=i,a=this.getAllLevels(n),s=this.getDeepestLevel(a),o=this.createResult(r,i,s,a);this.structureOfParents.set(r.id,o)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(it.byFirstLevel).filter(it.filterByParentType)}processEachActivity(t){let r=new Set,i=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(a=>{this.processActivity(a,r,i,n)},t.id),{parentsIds:r,allTasks:i,activitiesByLevel:n}}initializeParent(t){let r=Number(t.id),i=!!t[this.linkProperty]?.length,n=t.$level;this.singleParents.set(r,{level:n,hasLink:i,childrens:[]})}processActivity(t,r,i,n){let a=Number(t.id),s=Number(t.parent);i.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(s);s!=null&&c&&this.addChildToParent(s,a),this.addActivityToLevel(t,n)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let i=Number(t.id),n=t.$level,a=this.hasLink(t),s={level:n,hasLink:a,childrens:[]};r.add(i),this.singleParents.set(i,s)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let i=t.$level,n=Number(t.parent);r.has(i)||r.set(i,new Map);let a=r.get(i);a.has(n)||a.set(n,[]),a.get(n).push({id:Number(t.id),isParent:this.isProjectActivity(t),calculated:!1})}getAllLevels(t){return new Set(t.keys())}getDeepestLevel(t){return t.size===0?0:Math.max(...t)}createResult(t,r,i,n){let{activitiesByLevel:a,parentsIds:s,allTasks:o}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:s,allChildrens:o,childrensByLevel:a,currentResolutionLevel:i,canBeCalculated:!1}}},Hs=Ci;var Ai=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction==="forward"?"$target":"$source",this.linkDirection=this.direction==="forward"?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:r,childrensByLevel:i,isALinkedParent:n}=t;if(n)return;let a=i.get(r);for(let[s,o]of a)if(o.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(s);this.calculateParentWithNoLinks(l,o);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(it.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=Pe.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=i}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Pe.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new Hs({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,i=new Set,n=new Map,a=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((s,o)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(i.add(c.id),c.type==="project"){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};r.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),n.has(c.$level)||n.set(c.$level,new Map);let d=n.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type==="project",calculated:!1})}.bind(this),t.id),s({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:a})})}identifySecondLevelActivities(){try{let t=Pe.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...t])}catch(t){throw t}}identifyInitialActivities(){try{let{chainStartActivities:t,activitiesStartChainButChildrenOfLinkedParents:r}=Pe.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,r&&(this.activitiesStartChainButChildrenOfLinkedParents=r)}catch(t){throw new Error("Error in identifyInitialActivities",{cause:t})}}calculateSecondLevelActivities(){try{this.direction==="forward"?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(t){throw t}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(t=>{if(!t||t.progress>100||t.type==="project")return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction==="forward"){let{es:i,ef:n}=r;this.calculations.set(t.id,{es:i,ef:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:i,lf:n}=r;this.calculations.set(t.id,{ls:i,lf:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,i=new Set(this.calculations.keys()),n=new Map;return t.forEach(a=>{a&&n.set(a.id,a)}),n.forEach((a,s)=>{if(i.has(s))return;let o=[];(a[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);o.push(u)}}),o=o.filter(l=>n.has(l)||i.has(l)),r.set(s,o)}),{graph:r,activityMap:n,calculatedActivities:i}}topologicalSort(t,r){let i=new Set,n=new Set,a=[],s=o=>{if(n.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!i.has(o)&&!r.has(o)){n.add(o);let c=t.get(o)||[];for(let l of c)s(l);n.delete(o),i.add(o),a.push(o)}};for(let o of t.keys())!i.has(o)&&!r.has(o)&&s(o);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let i=t,n=Number(i.progress);n==="0.00"&&(n=0);let a=this.gantt.getCalendar(i.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);if((r||this.direction)==="forward"){let o=i.start_date,c=i.end_date;return{es:o,ef:c}}else{if(n>=100)return{ls:ht(i.start_date).clone(),lf:ht(i.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(i,a);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,a)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(t,r){let i=ht(t.start_date).clone(),n=ht(t.end_date).clone(),a=t.duration,s=[h.ASAP,h.ALAP,h.SNET,h.FNET],o=t.constraint_type||h.ASAP;if(s.includes(o))n=this.projectDates.end_date,i=I(r,n,-a,t);else{let c=[h.SNLT,h.MSO],l=[h.FNLT,h.MFO];c.includes(o)&&(i=t.constraint_date,n=I(r,i,a,t)),l.includes(o)&&(n=t.constraint_date,i=I(r,n,-a,t))}return{ls:i,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,i=null,n=t.constraint_type||h.ASAP,a=this.projectDates.end_date,s=[h.ASAP,h.ALAP,h.SNET,h.FNET],o=[h.SNLT,h.FNLT];if(s.includes(n))i=Math.max(t.end_date,a);else if(n===h.MSO)i=t.end_date;else if(n===h.MFO||o.includes(n)){let c=Math.min(a,t.constraint_date);i=Math.max(c,t.end_date)}return{ls:r,lf:new Date(i)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(i=>Number(this.gantt.getTask(i).progress)===100).map(i=>this.gantt.getTask(i)).forEach(i=>{let n=i.type==="project";this.setDatesForActivityWithFullProgress(i),this.activitiesWaitingForCalculation.delete(i.id),n&&this.pendingParentsWithLinks.has(i.id)&&(this.parentCalculationFromChildren.add(i.id),this.calculationsOfParentThatImpactChildrens.set(i.id,{[this.direction==="forward"?"es":"ls"]:i.start_date,[this.direction==="forward"?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new Bs({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},Ht=Ai;function df(e,t,r){let i={es:null,ef:null};if(!e)return i;if([h.SNET,h.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if([h.FNLT,h.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}else if(t===h.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if(t===h.MFO){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}return i}var hr=df;var Ii=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,i=0,n,a=B.FS){let s=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.referenceActivity.calendar_id}`);let o=t,c=null,l=null,d=this.referenceActivity.type==="milestone";return d||(a===B.FS&&n===0?o=dt({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[B.FF,B.SF].includes(a)?(l=I(s,o,i,this.referenceActivity),c=I(s,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=I(s,o,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=I(s,c,i,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,s,B.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,s,B.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,s,B.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,s,B.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![B.FS,B.SS,B.FF].includes(r))return t;let a=[B.FS,B.SS].includes(r)?"future":"past";return dt({dateBaseToCalculate:t,activityCalendar:i,direction:a,activity:this.referenceActivity})}},js=Ii;var Re=class extends js{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Ht(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(i=>{let n=this.gantt.getLink(i);if(!n)throw new Error("Link data not found",{cause:{linkId:i}});return this.calculateLink(n)}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let i=this.gantt.getCalendar(this.referenceActivity.calendar_id),n=this.parentsCalculations.get(r).es,a=I(i,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:a})}return pr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var ki=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let r=new Set,i=new Set(t);for(let n of t){let a=this.gantt.getTask(n);a.type==="project"?this.handleProjectActivity(n,a,r,i):this.handleNonProjectActivity(n,a,r,i)}return{activitiesThatCanBeCalculated:r,pendingActivities:i}}handleProjectActivity(t,r,i,n){let a=this.pendingParentsWithNoLinks.has(t),s=this.pendingParentsWithLinks.has(t),o=this.calculationOfParentsFromLinks.has(t);if(a){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}if(s&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}s&&!o&&this.canCalculateParentActivity(r)&&(i.add(t),n.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,i=t.constraint_type;return(this.direction==="forward"?i==="fnlt"||i==="snlt":i==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(s=>this.calculations.has(s))}handleNonProjectActivity(t,r,i,n){let a=Number(r.parent),s=this.pendingParentsWithLinks.has(a),o=this.calculationOfParentsFromLinks.has(a);if(s&&!o||this.direction==="backward"&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!o)return;if(r.$target.length===0&&r.$source.length===0){i.add(t),n.delete(t);return}let c=this.getLinkedActivities(r[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction==="backward"&&(c.length===0||l)&&o){i.add(t),n.delete(t);return}l&&(i.add(t),n.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=n[this.linkDirection],s=this.gantt.getTask(a);s&&r.push(s)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);n&&r.push(Number(n[this.linkDirection]))}return r}},yr=ki;var Si=(e,t)=>()=>t()===e;var Di=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var uf=16,Le=async e=>performance.now()-e>uf?(await rt(),performance.now()):e;var be=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:i,isCalculated:n,onActivityProcessed:a,isCurrent:s})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!s())return;c=await Le(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await Le(c),r([u])}for(let u of l){if(!s())return;i(u)&&d.add(u),a(u),n(u)&&d.delete(u)}o=d}};var Ti=class extends Ht{constructor(t){super(t,"forward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new yr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await be({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(i.type==="project")return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:r}});let n=i.$target,a=i.constraint_type||h.ASAP,s=[h.SNET,h.SNLT,h.FNLT,h.FNET],o=[h.ASAP,h.ALAP,h.SNET,h.FNET,h.SNLT,h.FNLT],c=this.gantt.getCalendar(i.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);let l=Number(i.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(i);return}l>0&&o.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),f=new Re({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===h.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new Re({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===h.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let p=hr(i,a,c);if(s.includes(a)&&(this.constraintsMap.set(r,p),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,p,{es:d,ef:u})),[h.MSO,h.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),i.progress===0)d=p.es,u=p.ef;else{let v=i.end_date;a===h.MFO&&(v=Math.max(p.ef,i.end_date)),d=i.start_date,u=v}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,i="greater"){if(i==="greater")return r.ef>t.ef?r:t;if(i==="less")return r.ef<t.ef?r:t}setDatesForActivityWithFullProgress(t){this.calculations.set(t.id,{es:t.start_date,ef:t.end_date})}getDatesForActivityWithZeroProgress(t){return{es:t.start_date,ef:t.end_date}}recalculateInBaseConstraint(t,r,i){let n=[h.SNET,h.FNET].includes(t)?"greater":"less",{es:a,ef:s}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,i,n);return{es:a,ef:s}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r);if(!i)throw new Error("Error trying to get link",{cause:{linkId:r}});let n=i.source,a=i.target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},Vs=Ti;var _i=class{constructor(t){this.activity=t.activity,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.forwardPathCalculations=t.calculatedForwardActivitiesMap,this.gantt=t.ganttInstance}getForwardOrBackwardCalculations(t,r=null){return r===h.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,a=B.FS){let s=this.gantt.getCalendar(this.activity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let o=t,c=this.activity.type==="milestone";if(c&&n===0){let d=I(s,o,r,this.activity),u=I(s,d,i,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:o,activityCalendar:s,lsDataCalculation:r,lfDataCalculation:i,isMilestone:c};if(a===B.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===B.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===B.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===B.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let i=this.getValueForSS(t,r),n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,B.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===h.ALAP?"ef":"lf",a=i[n],s=-this.activity.duration,o=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,s,o,c,B.FF)}calculateFS(t,r){let i="ls";i=r===h.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,s=t.lag||0,o=-t.lag||0;return this.calculateSuccessorTimes(n[i],a,o,s,B.FS)}calculateSF(t,r=!1){let i=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,B.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,i){let n=ht(r).clone();return I(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=ht(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),dt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),ht.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}calculateFsLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,i,"past");return o=I(i,d,a,this.activity),o=this.getLastWorkingHour(o,i,"past"),c=I(i,o,n,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,i)),o=I(i,l,a,this.activity),c=I(i,o,n,this.activity),s||(o=this.getLastWorkingHour(o,i,"past",!0)),{ls:c,lf:o}}calculateFFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;if(t===0)return s=I(i,r,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),s=I(i,c,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s}}calculateSSlink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0)return c=I(i,r,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,i,"future")),c=I(i,l,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o}}calculateSFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;return t===0?(o=I(i,r,n),s=I(i,o,a,this.activity),{ls:o,lf:s}):(o=I(i,r,n,this.activity),s=I(i,o,a,this.activity),{ls:o,lf:s})}},Ys=_i;var Pi=class extends Ys{constructor(t){super(t),this.constraint=t.constraint||h.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Ht(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),i=!1;r&&(i=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let n=this.links.map(s=>{let o=this.gantt.getLink(s);if(!o)throw new Error("Link not found",{cause:{linkId:s}});if(!this.parentsWithFullProgress.has(Number(o.target)))return this.calculateLink(o)}).filter(s=>s);if(n.length!==0){let s=this.getMinLfFromLinks(n);if(n.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));n.push(this.calculateTheLsAndLfForTheActivity(d))}let o=this.getMinDateFromLinks(n),c=o.ls,l=o.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(o)),{ls:c,lf:l,minFromLinks:s}}if(i){n.push(this.calculateTheLsAndLfForTheActivity());let o=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=I(this.gantt.getCalendar(this.activity.calendar_id),o,-this.activity.duration,this.activity);n.push({ls:c,lf:o});let l=this.getMinDateFromLinks(n);return{ls:l.ls,lf:l.lf,minFromLinks:l}}let a=this.calculateTheLsAndLfForTheActivity();return{ls:a.ls,lf:a.lf,minFromLinks:a}}calculateTheLsAndLfForTheActivity(t=null){try{let r=this.activity.duration,i=this.gantt.getCalendar(this.activity.calendar_id);if(!i)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let n=t?t.lf:this.projectDates.end_date;if(!n)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:I(i,n,-r,this.activity),lf:n}}catch(r){throw Error(r.message)}}SnetSnltMsoMinDate(t){let r=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(r,this.activity.end_date))}calculateLink(t){let r=this.gantt.getTask(t.target);if(!r||r.progress>0&&r.type!=="project")return;let i=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,i),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,a),3:()=>this.calculateSF(t,n)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===h.ALAP)return h.ALAP;if(this.constraint===h.FNET||this.constraint===h.SNET)return"snet-fnet";if(this.constraint===h.FNLT)return h.FNLT}getSpecialParamForSf(){return!![h.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![h.MFO,h.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===h.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.SNET||this.constraint===h.SNLT||this.constraint===h.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===h.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===h.ALAP||this.constraint===h.ASAP?t.reduce((i,n)=>n.lf<i.lf?n:i):t.reduce((r,i)=>i.ls<r.ls?i:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,i)=>i.lf<r.lf?i:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let i=Math.min(t.lf,this.projectDates.end_date),n=this.activity.end_date,a=this.activity.constraint_date;if(r===h.ASAP)return new Date(Math.max(i,n));if(r===h.FNET||r===h.FNLT){let s=Math.min(i,a);return new Date(Math.max(i,s))}if(r===h.ALAP)return new Date(Math.min(i,n))}},$s=Pi;function ff(e,t,r){let i={ls:null,lf:null};return r===h.MSO&&(i.ls=t.constraint_date,i.lf=I(e,i.ls,t.duration,t)),r===h.MFO&&(i.lf=t.constraint_date,i.ls=I(e,i.lf,-t.duration,t)),i}var Gs=ff;var Ei=class extends Ht{constructor(t,r,i){super(t,"backward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.activitiesWaitingForCalculation=new Set,this.calculations=new Map,this.mapOfRelationsWithActivitiesIds=new Map,this.activitiesWaitingForCalculation=new Set,this.forwardPathCalculations=r,this.forwardConstraintsMap=i,this.constraintMap=new Map,this.minFromLinks=new Map,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.parentsWithFullProgress=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateLfAndLs(t))))))}async iterativeCalculateLfAndLs(t){let r=new yr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await be({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let r=this.singleParents.get(t.id).childrens,n=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=n.reduce((o,{ls:c,lf:l})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(o.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(!i)throw new Error("Activity not found",{cause:{activityId:r}});let n=i.$source,a=i.constraint_type||h.ASAP,s=Number(i.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(i.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(i.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(i,this.direction);this.setCalculations(i,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(i)}if(i.type==="project")return this.doCalculationForParentType(i);if(s===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(n,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(s>0&&s<100&&(a===h.MSO||a===h.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,a);return}if(a===h.MSO||a===h.MFO){this.recalculateInBaseRestriction(i,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===h.SNLT||a===h.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:o,lf:c},a)),this.setCalculations(i,o,c),this.minFromLinks.set(i.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,i){let n=this.forwardConstraintsMap.get(t);if(!n){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);n=hr(a,i,s)}return r.lf<n.ef?r:{ls:n.es,lf:n.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=this.gantt.getTask(n.target);a&&(a.type==="project"&&(r=!1),a.progress===0&&(r=!1))}return r}catch(r){throw new Error(r.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let r=Number(t.parent),{ls:i,lf:n}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){i=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(n=new Date(Math.min(n,a.lf)))}this.setCalculations(t,i,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===h.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===h.MFO){let i=Math.min(t.constraint_date,this.projectDates.end_date),n=new Date(Math.max(i,t.end_date));this.setCalculations(t,t.start_date,n);return}}setCalculations(t,r,i){this.calculations.set(t.id,{ls:r,lf:i,text:t.text})}calculateLfandLsFromLinks(t,r,i,n,a){return new $s({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:n,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let i=this.gantt.getCalendar(t.calendar_id);if(!i)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let n=Gs(i,t,r);this.constraintMap.set(t,n),this.setCalculations(t,n.ls,n.lf)}catch(i){throw new Error(i.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r).source,n=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project"))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,a=0;if([h.ASAP,h.ALAP,h.SNET,h.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;a=new Date(Math.min(l,i.lf)),n=t.start_date}else a=i.lf,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([h.SNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r),u=I(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);n=new Date(Math.min(l.getTime(),u.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([h.FNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r);n=new Date(Math.min(l.getTime(),d.lf.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[h.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[h.MFO].includes(t.constraint_type)&&(a=t.constraint_date,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:n,lf:a}];o.push({ls:I(this.gantt.getCalendar(t.calendar_id),s,-t.duration,t),lf:s});let c=this.getMinLfFromLinks(o);this.calculations.set(t.id,{ls:c.ls,lf:c.lf,text:t.text})}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}},Ks=Ei;function zs(){return null}var qs=({forward:e,backward:t,id:r,activity:i,gantt:n,projectDates:a})=>({totalFloat:{es:e.calculations.get(r)?.es||0,ef:e.calculations.get(r)?.ef||0,ls:t.calculations.get(r)?.ls||0,lf:t.calculations.get(r)?.lf||0,constraintsMap:e.constraintsMap.get(r),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(r),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(r),minFromLinks:t.minFromLinks.get(r),activity:i,gantt:n},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:i,projectDates:a,gantt:n}});var Ri=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.es=t.es,this.ef=t.ef,this.ls=t.ls,this.lf=t.lf,this.constrainstMap=t.constraintsMap,this.totalFloatSnltFnlt=t.totalFloatSnltFnlt,this.totalFloatForMsoMfo=t.totalFloatForMsoMfo,this.minFromLinks=t.minFromLinks}getTotalFloat(){let{constraint_type:t}=this.activity,r=Number(this.activity.progress);if(r===100)return 0;if(t||(t=h.ASAP),t===h.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===h.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===h.SNET||t===h.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===h.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===h.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===h.MSO||t===h.MFO)return r===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r),n=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateAlapWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFnetSnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),r=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,i)/this.gantt.config.hoursPerDay}return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateMsoMfoWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFet(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.SNLT?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.MSO?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,r){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)})}},Js=Ri;var Li=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),r=this.getConstraintType();return this.calculateFreeFloatOfLink(r),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(r),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===h.MSO||t===h.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=h.ASAP){let r=this.activity.$source.map(i=>{let{LINK:n,LINK_TYPE:a}=this.getLinkData(i),s=this.gantt.getTask(n.target);if(!s)return{linkId:n.id,freeFloat:null,hasProgress:!1};let o=Number(s.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(a,t,s),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(n.lag),f=Math.max(0,u);return this.linksFreeFloatObject[n.id]=f,{linkId:n.id,freeFloat:f,hasProgress:o}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=h.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=0;return[h.SNLT,h.FNLT].includes(t)?n=this.doCalculationForSnltFnlt(t,i,r):n=this.doGeneralCalculation(i,r),Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=h.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===h.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:n,sucessorId:i.id,predecessorId:this.activity.id}),s=new Date,o=new Date;return s=a[t].sucessor,o=a[t].predecessor,{sucessorDateToCalculate:s,predecessorDateToCalculate:o}}doGeneralCalculation(t,r){return r===null?t:this.getMinValue(r,t)}doCalculationForSnltFnlt(t,r,i){let n=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(i,r,n)}calculateFreeFloatForEndOfProject(t){return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===h.ALAP?this.backwardMap.get(this.activity.id).lf:this.forwardMap.get(this.activity.id).ef))}calculateFreeFloatOfRestriction(t){return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===h.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=qt(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let a=({direction:s,constraint:o=h.ASAP})=>o===h.ALAP?this.backwardMap.get(n)[s]:this.forwardMap.get(n)[s];if(t===h.ASAP||t===h.SNET||t===h.FNET||t===h.MSO||t===h.MFO)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===h.ALAP)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:h.ALAP,direction:"lf"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:h.ALAP,direction:"ls"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:h.ALAP,direction:"lf"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:h.ALAP,direction:"ls"})}};if(t===h.SNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===h.FNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,i=t===h.MSO?this.forwardMap.get(this.activity.id).es:this.forwardMap.get(this.activity.id).ef,n=this.calculationWithCalendar(r,i);return Math.max(0,this.parseHoursToDays(n))}getMinValue(...t){let r=t.filter(i=>i!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){let i=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(i))return this.durationCache.get(i);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(i,a),a}parseHoursToDays(t){return t?t/this.gantt.config.hoursPerDay:0}getMinFloat(t){if(!t?.length)return null;let r=t.filter(i=>!i.hasProgress).map(i=>i.freeFloat);return r.length===0?null:Math.min(...r)}},Xs=Li;var Zs=e=>({totalFloat:new Js(e.totalFloat).getTotalFloat(),freeFloat:new Xs(e.freeFloat).getFreeFloat()});var bi=async({activityIds:e,forward:t,backward:r,gantt:i,projectDates:n,isCurrent:a})=>{let s=performance.now(),o=new Map,c=new Map;for(let l of e){if(a&&!a())return{totalFloatMap:o,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=qs({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=Zs(u);o.set(l,f),c.set(l,p),s=await Le(s)}return{totalFloatMap:o,freeFloatMap:c}};var wi=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let i=++this.currentCalculationId,n=Si(i,this.getCurrentCalculationId),a=()=>n()&&r();try{let s=t||this.gantt;if(this.gantt=s||zs(),Di(this.gantt))return!1;let o=new Vs(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new Ks(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let{totalFloatMap:u,freeFloatMap:f}=await this.calculateFloatsAsync(o,d,a);return a()?(this.totalFloat=u,this.freeFloat=f,this.gantt.refreshData(),!0):!1}catch(s){return this.forwardPathCalculations?.size,!1}}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await bi({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){return this.forwardPathCalculations?.size,{totalFloatMap:new Map,freeFloatMap:new Map}}}},Qs=wi;var pf=e=>e==="fnet"||e==="fnlt"||e==="mfo",hf=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function yf(e,t){let r=e.constraintDate;if(!r||!pf(e.constraintType))return r;let i=hf(r);if(r.getTime()!==i.getTime())return r;let n=t.getClosestWorkTime({date:i,dir:"future",task:e});return n.getUTCFullYear()===r.getUTCFullYear()&&n.getUTCMonth()===r.getUTCMonth()&&n.getUTCDate()===r.getUTCDate()?Xr(e,t):r}function mf(e){return{calculateEndDate:({start_date:t,duration:r})=>e.calculateEndDate(t,r),calculateDuration:({start_date:t,end_date:r})=>e.calculateDuration(t,r),getWorkHours:t=>e.getWorkHours(t),$gantt:{getClosestWorkTime:({date:t,dir:r,unit:i})=>e.getClosestWorkTime({date:t,direction:r,unit:i??"hour"})}}}function gf(e){let t=new Map;e.forEachActivity((n,a)=>t.set(String(a),n));let r=new Map,i=(n,a)=>{let s=r.get(n);if(s!=null)return s;let c=t.get(n)?.parentId??null,l=0;return c!==null&&!a.has(n)&&(a.add(n),l=i(String(c),a)+1),r.set(n,l),l};for(let n of t.keys())i(n,new Set);return r}function vf(e){let t=gf(e),r=new Map;return e.forEachActivity((i,n)=>{let a=String(n);r.set(a,{id:Number(n),parent:i.parentId===null?0:Number(i.parentId),$level:t.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),start_date:i.startDate,end_date:i.endDate,duration:i.durationHours,progress:i.progress,type:i.type,calendar_id:i.calendarId,constraint_type:i.constraintType,constraint_date:yf(i,e)})}),r}function Cf(e){let t=new Map;for(let s of e.values()){let o=t.get(s.parent);o?o.push(s):t.set(s.parent,[s])}let r=[],i=new Set,n=[],a=s=>{if(s)for(let o=s.length-1;o>=0;o-=1)n.push(s[o])};for(a(t.get(0));n.length>0;){let s=n.pop();i.has(s)||(i.add(s),r.push(s),a(t.get(s.id)))}if(r.length<e.size)for(let s of e.values())i.has(s)||r.push(s);return r}function Af(e){let t=null,r=null;return e.forEachActivity(i=>{if(i.startDate){let n=i.startDate.getTime();t=t==null?n:Math.min(t,n)}if(i.endDate){let n=i.endDate.getTime();r=r==null?n:Math.max(r,n)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function to(e,t){let r=new Map,i=c=>{let l=c==null?"__default__":String(c),d=r.get(l);if(d)return d;let u=e.calendarReader.getCalendar(String(c)),f=mf(u);return r.set(l,f),f},n=Af(e);await rt();let a=vf(e);await rt();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await rt();let o=Cf(a);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:c=>a.get(String(c))??null,getLink:c=>{let l=e.getLink(c);return l?{...l,source:Number(l.source),target:Number(l.target),lag:l.lag}:null},getCalendar:i,getChildren:c=>e.getChildren(c).map(l=>Number(l)),eachTask:c=>{for(let l of o)c(l)},getTaskByTime:()=>s,getSubtaskDates:()=>n,refreshData:()=>{}}}var If=1e3;function kf(e,t,r){let i=o=>o==null?null:new Date(o),n=r.forward?.get(e),a=r.backward?.get(e),s=r.totalFloat.get(e)??null;return{criticalPath:{earlyStart:i(n?.es),earlyFinish:i(n?.ef),lateStart:i(a?.ls),lateFinish:i(a?.lf),totalSlackHours:s},isCritical:t<100&&s!=null&&s<=0,freeSlackHours:r.freeFloat.get(e)?.activityFreeFloat??null}}async function Oi(e,t,r=()=>!0){if(!r())return null;let i=await to(e,t);if(!r())return null;let n=new Qs(i);if(!await n.calculate(i,r)||!r())return null;let s={forward:n.forwardPathCalculations,backward:n.backwardPathCalculations,totalFloat:n.totalFloat,freeFloat:n.freeFloat},o=new Set([...s.forward?.keys()??[]]),c=new Map,l=0;for(let d of o){if(++l>=If&&(l=0,await rt(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,kf(d,f,s))}return r()?c:null}async function mr(e,t,r=()=>!0){let i=await Oi(e,t,r);if(!i||!r())return!1;for(let[n,a]of i){if(!r())return!1;e.setActivityFields(n,a)}return!0}function jt(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(String(n));if(!a)return 0;let s=[...e.getChildren(String(n))],o;if(s.length===0){let c=at(a),l=c&&Number(c.cost)||0;o=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of s)c+=i(String(l));o=c}return e.setActivityField(String(n),L.REAL_COST,o),r.push(String(n)),o};for(let n of t)i(n);return r}var eo=new Set;var ro=new Set(["activity-outdent","activity-indent"]);var we=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),Sf=new Set(["selection-toggle","selection-replace","visibility-set","sir-sync","activity-lookahead-sync","persistence-acknowledge","baseline-apply","ponderator-criterion-set","status-criteria-set"]),Df=new Set;function Tf(e){return e.kind==="inline-edit"?we.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>we.has(t.column)):!1}function xi(e,t){return!(Sf.has(e.kind)||t.has(e.kind)||Tf(e))}function no(e){return xi(e,Df)}function Oe(e){return xi(e,eo)}function ao(e){return xi(e,ro)}function Ni(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===E.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===E.PROGRESS):!1}function _f(e){return ao(e)&&Ni(e)}var io=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function Pf(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?io.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>io.has(t.column)):!1}var st={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",CRITICAL_PATH:"critical-path"};function so(e,t,r){let i=new Set;t.ran&&i.add(st.AUTOSCHEDULE),i.add(st.PARENT_BOUNDS),Pf(e)&&i.add(st.PARENT_PROGRESS),Ni(e)&&i.add(st.REAL_WORK);let n=!r.skipAutoSchedule;return n&&ao(e)&&i.add(st.EXPECTED_PROGRESS),n&&_f(e)&&i.add(st.REAL_COST),n&&Oe(e)&&!r.skipCriticalPath&&i.add(st.CRITICAL_PATH),i}async function $(e,t){let r=Ef(t),i=r.has(st.AUTOSCHEDULE)?await Rf(e,t.autoscheduleFrom):bf();return await wf(e.adapter,t,i.scheduledIds,r),await Of(e,r,t.now),i}function Ef(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t;return so(e.action,{requested:t,ran:r},e.options)}async function Rf(e,t){let r=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(r),n=Lf(e.adapter,i.updatedIds);return ke(e.adapter,i),n}function Lf(e,t){let r=[],i=new Map;for(let n of t){let a=String(n);r.push(a);let s=e.getActivity(a);s&&(i.set(a,K(s)),e.noteScheduledBefore(a,s))}return{scheduledIds:r,scheduledBeforeImages:i}}function bf(){return{scheduledIds:[],scheduledBeforeImages:new Map}}async function wf(e,t,r,i){let n=t.collectDirty?t.collectDirty(r):Ts(t.recomputeParentsFrom,r);await Se(e,n,i.has(st.PARENT_PROGRESS),{recomputeRealWork:i.has(st.REAL_WORK)})}async function Of(e,t,r){t.has(st.EXPECTED_PROGRESS)&&r!==null&&(Bt(e.adapter,r,e.defaultBaseCalendarId??null),Et(e.adapter,r),vt(e.adapter,e.sector.statusCriteria)),t.has(st.REAL_COST)&&jt(e.adapter),t.has(st.CRITICAL_PATH)&&await mr(e.adapter,e.sector.hoursPerDay)}var xf=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),Nf=new Set(["mso","mfo"]);function gr(e){return xf.has(e)}function vr(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let a=n.constraintType;if(!a||Nt.has(a)||Nf.has(a))return!1;let s=Fi(n.startDate),o=Fi(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Ff(t,a,String(n.calendarId??""),i),l=Fi(n.constraintDate);return Mf(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Ff(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?Tt(e,n,t):e}function Fi(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Mf(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function Cr(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n,scheduledBeforeImages:a}=await $(e,oo(t)),s=!1;for(let{activityId:o,priorConstraintDate:c}of r){let l=i(o,c);s=s||l}if(s){let o=await $(e,oo(t));n=Uf(n,o.scheduledIds),a=Bf(a,o.scheduledBeforeImages)}return Oe(t.action)&&await $(e,Wf(t)),{scheduledIds:n,scheduledBeforeImages:a}}function oo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Wf(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Uf(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function Bf(e,t){let r=new Map(e);for(let[i,n]of t)r.has(i)||r.set(i,n);return r}function Hf(e,t){let r=i=>i.getTime();return r(e.startDate)!==r(t.startDate)||r(e.endDate)!==r(t.endDate)||e.durationHours!==t.durationHours}function Mi(e,t,r){let i=[];for(let n of r){let a=e.get(n);if(!a)continue;let s=a.pendingRequestIds??[];if(!te({pendingRequestIds:s}))continue;let o=t.getActivity(n),c=o==null;if(!c&&!Hf(a,o))continue;let l=c?"activity_deleted":"date_changed";for(let d of s)i.push({kind:"sir-auto-reject",activityId:n,sirId:d,reason:l});c||t.setActivityField(n,"pendingRequestIds",[])}return i}function H(e,t){let r=new Set;for(let l of t.touchedIds)r.add(l);for(let l of t.scheduledIds)r.add(l);if(t.includeAllIds)for(let l of e.getAllIds())r.add(l);let i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n)for(let l of n.dirty){if(r.has(l))continue;let d=n.before.get(l),u=e.getActivity(l);!d||!u||Object.keys(ui(d,u)).length!==0&&(i.set(l,d),r.add(l))}if(t.scheduledBeforeImages)for(let[l,d]of t.scheduledBeforeImages){let u=String(l);i.has(u)||(i.set(u,d),r.add(u))}let a=t.sirDetection==="before-diff"?Mi(i,e,r):[],s=Ds(e,i,r),o=t.sirDetection==="after-diff"?Mi(i,e,r):a,c=t.warnings??[];return{source:t.source,activities:s,links:t.links??[],calendars:[],trackingEvents:t.trackingEvents??[],...o.length>0?{effects:o}:{},...c.length>0?{warnings:c}:{}}}function Ct(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}function Ar(e,t,r){let i=[];for(let{op:n,finalLinkId:a,rejected:s}of e){if(s!==null)continue;if(n.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;i.push({id:String(a),kind:"created",fields:{source:{before:void 0,after:String(d.source)},target:{before:void 0,after:String(d.target)},type:{before:void 0,after:d.type},lag:{before:void 0,after:Number(d.lag)}},after:Ct(d)});continue}if(n.kind==="delete"){let d=t.get(n.linkId);i.push({id:String(n.linkId),kind:"deleted",fields:d?{source:{before:String(d.source),after:void 0},target:{before:String(d.target),after:void 0},type:{before:d.type,after:void 0},lag:{before:Number(d.lag),after:void 0}}:void 0,after:null});continue}let o=t.get(n.linkId),c=r.getLink(n.linkId);if(!c)continue;let l={};o&&o.type!==c.type&&(l.type={before:o.type,after:c.type}),o&&Number(o.lag)!==Number(c.lag)&&(l.lag={before:Number(o.lag),after:Number(c.lag)}),i.push({id:String(n.linkId),kind:"updated",fields:l,after:Ct(c)})}return i}function pe(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let i of e.getIncomingLinkIds(t)){let n=e.getLink(i);n&&r.set(String(n.id),Number(n.lag))}return r}function he(e,t,r){let i=[];if(!t.getActivity(r))return i;for(let n of t.getIncomingLinkIds(r)){let a=t.getLink(n);if(!a)continue;let s=e.get(String(a.id));s===void 0||s===Number(a.lag)||i.push({id:String(a.id),kind:"updated",fields:{lag:{before:s,after:Number(a.lag)}},after:Ct(a)})}return i}function Ir(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function co(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r,o=Mt(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);jf(e.column)&&a.invalidateExpandedLinksCache(),e.column===L.PARENT&&a.invalidateAllCaches();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??R.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??R.PARSE_ERROR};let u=Reflect.get(c,o.targetField),f=o.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??R.INVALID,alertKey:f.notification?.messageKey};if(e.column===E.CUSTOM_ID&&d.value!==null){let _=i.getActivity(e.activityId),b=_?_.customId:null,x=typeof b=="string"?b:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),x))return{ok:!1,reason:R.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,n,d.raw),v=Wt(e.activityId,p),S=Y(i,v),C=pe(i,String(e.activityId)),D=c.constraintDate;Ut(i,e.activityId,p),xt(e.activityId,p.postProcessors??[],i);let m=he(C,i,String(e.activityId));if(e.column===E.CUSTOM_ID){let _=S.get(String(e.activityId)),b=_?_.customId:null,x=typeof b=="string"?b:null,M=typeof d.value=="string"?d.value:null;x!==M&&r.customIdTracker.trackCustomIdChange(x,M)}let T=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:_=>dr(e.activityId,v,_),now:r.now,options:t}),k=gr(e.column),{scheduledIds:y,scheduledBeforeImages:g}=await(k?Cr({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:T(),revertTargets:[{activityId:e.activityId,priorConstraintDate:D}],revert:(_,b)=>vr(_,b,i,n.calendars)}):$({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},T())),A=(p.trackingEvents??[]).map(_=>({name:_.name,properties:_.properties??{}})),P=ue(e.activityId,p.constraintWarning);return{ok:!0,changes:H(i,{source:e,beforeSnap:S,touchedIds:v,scheduledIds:y,scheduledBeforeImages:g,sirDetection:"before-diff",links:m,trackingEvents:A,...P?{warnings:[P]}:{},hoursPerDay:s.hoursPerDay})}}function jf(e){return e===E.DURATION||e===L.AUTO_SCHEDULING}async function lo(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let i=e.type;if(i!==void 0&&!Object.values(j).some(a=>a===i))return{ok:!1,reason:R.INVALID_LINK_TYPE};let n=e.lag;if(n!==void 0&&!Number.isFinite(n))return{ok:!1,reason:R.INVALID_LINK_LAG}}return Wi([Kf(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function uo(e,t,r){let{hoursPerDay:i}=r.sector,n=e.operations.map(s=>Yf(s,i)),a=Vf(e.operations);return Wi(n,e,t,r,a)}function Vf(e){let t=new Map;return e.forEach((r,i)=>{r.kind==="create"&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function Yf(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:pt(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:pt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Wi(e,t,r,i,n){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=i;s.invalidateAllCaches();let l=new Set,d=new Map;for(let D of e)if(D.kind==="create")l.add(String(D.source)),l.add(String(D.target));else{let m=a.getLink(D.linkId);m&&(l.add(String(m.source)),l.add(String(m.target)),d.set(D.linkId,{...m}))}let u=Y(a,l),f=[];for(let D=0;D<e.length;D++){let m=e[D],T=m.kind==="create"&&n?n.get(D):void 0,k=wt(m,{port:a,newLinkId:T?()=>T:c.next});f.push({op:m,finalLinkId:k.applied?k.linkId:null,rejected:k.applied?null:k.rejected??"link_op_rejected"})}if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=$f(f,d,a),{scheduledIds:v}=await $({adapter:a,scheduler:s,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r});for(let D of v)if(!u.has(D)){let m=a.getActivity(D);m&&u.set(D,K(m))}let S=Ar(f,d,a),C=new Map;for(let[D,m]of d)C.set(String(D),m);return{ok:!0,__beforeLinks:C,changes:H(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:v,links:S,hoursPerDay:o.hoursPerDay})}}function $f(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=Gf(i.op,t,r);if(n!==null)return r.hasChildren(n)?"roots":String(n)}return null}function Gf(e,t,r){return e.kind==="create"?e.target:e.kind==="delete"?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function Kf(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:pt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:pt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function fo(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:R.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let s=e.column===E.CUSTOM_PREDECESSORS,{specs:o}=Xe(e.newValue),c=o.map(v=>({...v,lag:pt(v.lag,n.hoursPerDay)})),l=new Map;i.forEachActivity(v=>{v.correlativeId!=null&&l.set(String(v.correlativeId),v.id)});let d=v=>l.get(v)??null,u=s?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let v of u){let S=i.getLink(v);S&&f.push(S)}let p=s?Qe({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):tr({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Wi(p.operations,e,t,r)}var yt={ACTIVITY_CREATION:"schedule_activity_creation",ACTIVITY_DELETION:"schedule_activity_deletion",ACTIVITY_MOVE:"schedule_activity_move",ACTIVITY_INDENT:"schedule_activity_indent",ACTIVITY_OUTDENT:"schedule_activity_outdent"};var Ui=Number.MAX_SAFE_INTEGER;function Jt(e,t){let r=Hi(e,t);return r.sort(ji),r.map(i=>String(i.id))}function ho(e){let t=[],r=n=>{t.push(n);let a=Jt(String(n.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},i=Jt("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function yo(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=mo(i),a=Jt(n,r),s=a.findIndex(o=>String(o)===String(e));if(s<=0)return null;for(let o=s-1;o>=0;o--){let c=a[o];if(c!==void 0&&!zf(t,c))return c}return null}function Bi(e,t){let r=t.getActivity(e);if(!r)return-1;let i=mo(r);return Jt(i,t).findIndex(a=>String(a)===String(e))}function Hi(e,t){if(String(e)==="0")return t.getAllActivities().filter(a=>a.parentId===null);let i=t.getChildren(e),n=[];for(let a of i){let s=t.getActivity(a);s&&n.push(s)}return n}function ji(e,t){let r=po(e),i=po(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function po(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Ui}function mo(e){let t=e.parentId;return t===null?"0":t}function zf(e,t){return e.has(t)?!0:e.has(String(t))}function ot(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{O(a.parentId)&&t.push(a)}),t.sort(Co);let r=[];go(r,t);let i=[],n=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==n){let o=typeof a.correlativeId=="number"?a.correlativeId:void 0;i.push({activityId:String(a.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(a.id),o),qf(a,n)}n+=1;let s=Hi(String(a.id),e);s.sort(Co),go(r,s)}return i}function go(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function vo(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Ui}var Co=(e,t)=>vo(e)-vo(t);function qf(e,t){e.correlativeId=t}function Yi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0,a=0;for(let c of i){let l=t.getActivity(c);if(!l)continue;let d=Vi(l,L.WORK_HOURS),u=Jf(c,l,d,t);n+=d,a+=u}t.setActivityField(r,L.WORK_HOURS,n),t.setActivityField(r,L.REAL_WORK_HOURS,a);let s=t.getActivity(r);if(!s)break;let o=s.parentId;if(!o||O(o))break;r=o}}function Ao(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||Yi(i,t)}function Vi(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Jf(e,t,r,i){return i.hasChildren(e)?Vi(t,L.REAL_WORK_HOURS):lt(r,Vi(t,L.PROGRESS))}function $i(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Xf(c,L.USED_COST))}t.setActivityField(r,L.USED_COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||O(s))break;r=s}}function Io(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||$i(i,t)}function Xf(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Gi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Zf(c,L.COST))}t.setActivityField(r,L.COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||O(s))break;r=s}}function ko(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||Gi(i,t)}function Zf(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var kr=Object.freeze({proplannerId:null,description:"",type:"task",progress:0,constraintType:"asap",constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:[],hasNewActivities:!1,pendingRequestIds:[],responsableIds:[],tagIds:[],baselinePoints:[],baselineSnapshot:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null,promotionRestore:null}),So="New Master Plan",Do="New Activity";var Qf=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],To=new Set(Qf);function tp(e){let t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let r of Reflect.ownKeys(e))if(typeof r=="symbol"||!To.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function _o(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=tp(e.activityOverrides??{}),n=e.numTasksInGantt===0?So:Do,a=i.name??n,s=i.durationHours??e.sector.hoursPerDay,o=i.calendarId??e.sector.defaultCalendar,c=ep(r,e.fallbackStartDate,i.startDate),l={...kr,...i,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:s,calendarId:o,startDate:c,endDate:c},d=i.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:X.FUTURE,task:l}),u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function ep(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function ye(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&bt(t.type):rp(t),i=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(s=>String(s)===String(e.newChildId))?[...i]:[...i,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=ri,a.constraintType=G.ASAP,a.constraintDate=null,(e.promotionSource??"create")==="create"&&(a.progress=0,a.expectedProgressBaseline=0)),{parentId:e.parentId,fields:a}}function rp(e){return bt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Sr(e,t,r,i){let n=t,a=n==="0",s=Ki(e,n);if(i!==void 0){let c=s.find(l=>l.id===i);if(c){let l=nt(c),d=s.map(nt).filter(f=>f<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(r!==void 0){let c=s.find(l=>l.id===r);if(c){let l=nt(c),d=s.map(nt).filter(f=>f>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return s.length===0?0:Math.max(...s.map(nt))+1}var Xt=Number.MAX_SAFE_INTEGER,Po=Number.MAX_SAFE_INTEGER-1;function nt(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Xt}function Ki(e,t){let r=[];return e.forEachActivity(i=>{$t(i.parentId)===t&&r.push(i)}),r}function Eo(e,t,r){let i=e,n=Vt(e,r);for(;n!=null&&t.has(n);)i=n,n=Vt(n,r);return i}function Vt(e,t){let r=t.getActivity(e);if(!r)return null;let i=$t(r.parentId),n=Jt(i,t),a=n.findIndex(s=>String(s)===String(e));return a<=0?null:n[a-1]??null}function Ro(e,t,r,i){let n=Jt(t,e).filter(c=>String(c)!==String(i)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let a=n.map(nt);if(r<=0)return a[0]-1;if(r>=a.length)return a[a.length-1]+1;let s=a[r-1],o=a[r];return(s+o)/2}function zi(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;n.invalidateAllCaches();let l=ip(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=ap(e.activityId,i,o),v=c.next(),S={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:up(s)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:v,activityOverrides:e.overrides??{}},D=_o(S,{getActivity:g=>i.getActivity(g),calculateEndDate:g=>i.calculateEndDate(g),getClosestWorkTime:g=>i.getClosestWorkTime(g)}).newTask;D.realWorkHours=lt(D.workHours,D.progress),op(D,e,t,u,d,r);let m=Sr(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);D.correlativeId=m;let T=new Set([p]);d&&T.add(d.id);let k=d!==null&&i.getChildren(d.id).length===0,y=r.skipBeforeSnap?new Map:Y(i,T);return i.addActivity(D),cp(e,p,d,i,r.preserveParentCustomId??!1,k),Ao(p,i),Io(p,i),ko(p,i),lp(i,p,y,T,r),{ok:!0,newId:p,parent:d,newActivity:D,beforeSnap:y,initialTouched:T}}function ip(e,t){let r=O(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:R.PARENT_NOT_FOUND};if(i!==null&&te(i))return{ok:!1,reason:R.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:R.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=np(e,t,r,s);return o||{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function np(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:R.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==a?{ok:!1,reason:R.ANCHOR_SIBLING_WRONG_PARENT}:null}function ap(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function sp(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function op(e,t,r,i,n,a){let{adapter:s,customIdTracker:o}=r,c=sp(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=i??a.customIdReferenceId,d=l!==void 0,u=d?s.getActivity(l):n;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function cp(e,t,r,i,n,a){if(!r)return;let s=ye({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:a,getParent:o=>i.getActivity(o)??null});if(s)for(let[o,c]of Object.entries(s.fields))o===L.CUSTOM_ID&&n||Z(i,s.parentId,o,c)}function lp(e,t,r,i,n){if(n.skipCorrelativeRecompute)return;let a=ot(e);n.skipBeforeSnap||ur(e,a,new Set([String(t)]),r,i)}function dp(e,t,r,i,n,a){let{newId:s,newActivity:o,beforeSnap:c,initialTouched:l}=r,d={name:yt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:s,created_duration:o.durationHours}};t.eventSource!==void 0&&(d.properties.event_source=t.eventSource);let u=a?new Map([...a].filter(([f])=>String(f)!==String(s))):void 0;return H(e,{source:t,beforeSnap:c,touchedIds:l,scheduledIds:i,scheduledBeforeImages:u,trackingEvents:[d],hoursPerDay:n})}async function Lo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=zi(e,r);if(!s.ok)return s;let{newId:o}=s,c=s.newActivity.autoScheduling;i.setActivityField(o,"autoScheduling",!1);let l;try{l=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[o],now:r.now,options:t})}finally{i.setActivityField(o,"autoScheduling",c)}let{scheduledIds:d,scheduledBeforeImages:u}=l;return{ok:!0,changes:dp(i,e,s,d,a.hoursPerDay,u)}}function up(e){for(let r of e.values())if(r.is_default)return r.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function fp(e,t){if("afterSiblingId"in e){let a=t.getActivity(e.afterSiblingId);return a?{ok:!0,parentId:a.parentId==null?"0":String(a.parentId),firstAfter:e.afterSiblingId}:{ok:!1,reason:R.ANCHOR_SIBLING_NOT_FOUND}}let r=e.parentId,n=Ki(t,r).sort((a,s)=>nt(a)-nt(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:n}}function pp(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function bo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=fp(e.destination,i);if(!s.ok)return s;let o=Y(i,new Set),c=new Set,l=new Map,d=[],u;for(let m of e.activities){let T=l.get(m.originalParentId),k,y,g;T!==void 0?k=T:(k=s.parentId,u===void 0?(y=s.firstAfter,g=s.firstBefore):y=u);let A=zi({kind:"activity-create",parentId:k,afterSiblingId:y,beforeSiblingId:g,...m.activityId?{activityId:m.activityId}:{},overrides:pp(m.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,...T!==void 0?{customIdReferenceId:e.referenceActivityId,preserveParentCustomId:!0}:{}});if(!A.ok)return A;if(m.baselineSnapshot!==void 0){let P=m.baselineSnapshot;i.setActivityField(A.newId,"baselineSnapshot",P?{...P,startDate:P.startDate?new Date(P.startDate):null,endDate:P.endDate?new Date(P.endDate):null}:null)}l.set(m.originalId,A.newId),d.push(A.newId),T===void 0&&(u=A.newId)}let f=ot(i),p=new Set(d.map(String));ur(i,f,p,o,c);for(let m of d)c.add(String(m));let v=[];for(let m of e.links){let T=l.get(m.source),k=l.get(m.target);if(T===void 0||k===void 0)continue;let y={kind:"create",source:T,target:k,type:m.type,lag:pt(m.lag,a.hoursPerDay)},g=wt(y,{port:i,newLinkId:m.linkId?()=>m.linkId:r.linkIdGen.next});v.push({op:y,finalLinkId:g.applied?g.linkId:null,rejected:g.applied?null:g.rejected??"link_op_rejected"})}let{scheduledIds:S,scheduledBeforeImages:C}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:r.now,options:t}),D=Ar(v,new Map,i);return{ok:!0,changes:H(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:S,scheduledBeforeImages:new Map([...C].filter(([m])=>!p.has(String(m)))),links:D,hoursPerDay:a.hoursPerDay})}}function wo(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let a=n.pendingRequestIds??[],s=e.pendingRequests.map(c=>c.id);return r.setActivityField(e.activityId,"pendingRequestIds",s),{ok:!0,changes:{source:e,activities:[{id:i,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:{id:i,pendingRequestIds:s}}],links:[],calendars:[],trackingEvents:[]}}}function Oo(e,t){let r=[...new Set(e.activityIds.map(String))],i=r.map(a=>t.adapter.getActivity(a));if(i.some(a=>!a))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let n=[];for(let[a,s]of r.entries()){let o=i[a];if(!o)continue;let c={};o.isLookahead!==e.isLookahead&&(c.isLookahead={before:o.isLookahead,after:e.isLookahead},t.adapter.setActivityField(s,"isLookahead",e.isLookahead)),o.hasLookaheadTasks!==e.hasLookaheadTasks&&(c.hasLookaheadTasks={before:o.hasLookaheadTasks,after:e.hasLookaheadTasks},t.adapter.setActivityField(s,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(c).length!==0&&n.push({id:s,kind:"updated",fields:c,after:{...o,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return{ok:!0,changes:{source:e,activities:n,links:[],calendars:[],trackingEvents:[]}}}function Rt(e,t){Yi(e,t),$i(e,t),Gi(e,t)}function xo(e,t){let r=new Set,i=[];for(let n of e){let a=String(n);r.has(a)||(r.add(a),i.push(a))}for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);for(let s of a){let o=String(s);r.has(o)||(r.add(o),i.push(o))}}return r}function No(e,t){let r=new Set;for(let i of e){for(let n of t.getOutgoingLinkIds(i))r.add(String(n));for(let n of t.getIncomingLinkIds(i))r.add(String(n))}return[...r]}function hp(e){let t=e.promotionRestore;return typeof t!="object"||t===null||t.type!=="task"&&t.type!=="milestone"?null:{type:t.type,startDate:new Date(t.startDate),endDate:new Date(t.endDate),durationHours:t.durationHours,expectedProgressBaseline:t.expectedProgressBaseline,constraintType:t.constraintType,constraintDate:t.constraintDate?new Date(t.constraintDate):null,progress:t.progress,promotionRestore:null}}function me(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=hp(t)??(i?{type:re,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,promotionRestore:null}:{type:re});if(e.idsRemoved&&e.idsRemoved.size>0){let a=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(a.length>0){let s=a.filter(o=>!e.idsRemoved.has(o)&&!e.idsRemoved.has(String(o)));s.length!==a.length&&(n.newActivityIds=s)}}return t.hasLookaheadTasks&&(n.isLookahead=!0),{parentId:String(t.id),fields:n}}function Fo(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let r=t,i=r.filter(n=>!e.idsRemoved.has(n)&&!e.idsRemoved.has(String(n)));return i.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...i],hasNewActivities:i.length>0}}}async function Mo(e,t,r){let{adapter:i,scheduler:n,customIdTracker:a,sector:s}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:R.ACTIVITY_IDS_EMPTY};for(let g of e.activityIds)if(!i.getActivity(g))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let o=xo(e.activityIds,i),c=No(o,i),l=new Set;for(let g of e.activityIds){let A=i.getActivity(g);if(!A)continue;let P=A.parentId;if(O(P))continue;let _=String(P);o.has(_)||l.add(_)}let d=new Set([...o,...l]),u=Y(i,d),f=new Map;for(let g of c){let A=i.getLink(g);A&&f.set(g,{...A})}let p=new Set;for(let g of o){let A=i.getActivity(g);if(!A)continue;let P=O(A.parentId)?null:i.getActivity(String(A.parentId)),_=P?.hasNewActivities===!0&&P.newActivityIds.some(x=>String(x)===String(g));(A.isNewActivity===!0||_)&&p.add(g);let b=A.customId;typeof b=="string"&&b.length>0&&a.releaseCustomId(b)}for(let g of c)i.removeLink(g);let v=mp(i,o);for(let g of o)i.removeActivity(g);for(let g of l){let A=i.getActivity(g);if(!A)continue;yp(A,p,i);let P=i.getChildren(g),_=me({parent:A,remainingChildIds:P.map(String),defaultDurationHours:s.hoursPerDay,idsRemoved:o});if(!_){ir(g,i);continue}for(let[b,x]of Object.entries(_.fields))Z(i,g,b,x);if(A.customId==null||A.customId===""){let b=Vt(g,i),x=b?i.getActivity(b)?.customId:null,M=a.generateCustomIdForRestoredChild(typeof x=="string"&&x?x:null);i.setActivityField(g,L.CUSTOM_ID,M)}}for(let g of l)Rt(g,i);let S=ot(i);for(let g of S){if(d.add(g.activityId),u.has(g.activityId))continue;let A=i.getActivity(g.activityId);if(!A)continue;let P=K(A);g.before!==void 0&&(P.correlativeId=g.before),u.set(g.activityId,P)}let{scheduledIds:C,scheduledBeforeImages:D}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),m={name:yt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(m.properties.event_source=e.eventSource);let T=new Map;for(let[g,A]of f)T.set(g,A);let k=new Map;for(let g of o){let A=u.get(String(g));A&&k.set(String(g),A)}let y=H(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:C,scheduledBeforeImages:D,sirDetection:"after-diff",links:gp(f),trackingEvents:[m],hoursPerDay:s.hoursPerDay});return{ok:!0,changes:v.length>0?{...y,viewState:v}:y,__beforeSnap:k,__beforeLinks:T}}function yp(e,t,r){let i=Fo({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))Z(r,i.parentId,n,a)}function mp(e,t){let r=[];for(let i of t){let n=e.isChecked(i),a=e.isVisible(i);!n&&a||r.push({activityId:String(i),...n?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return r}function gp(e){let t=[];for(let[r,i]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(i.source),after:void 0},target:{before:String(i.target),after:void 0},type:{before:i.type,after:void 0},lag:{before:Number(i.lag),after:void 0}},after:null});return t}function Dr(e,t){let r=new Set;for(let n of e)r.add(String(n));let i=[];for(let n of t.getAllLinks()){let a=String(n.source),s=String(n.target);!r.has(a)&&!r.has(s)||(Wo(s,a,t)||Wo(a,s,t))&&i.push(String(n.id))}return i}function Wo(e,t,r){let i=String(e),n=new Set;for(;i!=null;){if(n.has(i))return!1;n.add(i);let a=r.getActivity(i);if(!a)return!1;let s=a.parentId;if(s===null||O(s))return!1;let o=s;if(o===t)return!0;i=o}return!1}async function Uo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;n.invalidateAllCaches();let s=i.getActivity(e.activityId);if(!s)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let o=O(e.parentId);if(!o&&!i.getActivity(e.parentId))return{ok:!1,reason:R.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:R.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:R.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let y=i.getActivity(c);if(!y)return{ok:!1,reason:R.ANCHOR_SIBLING_NOT_FOUND};if((y.parentId===null?"0":String(y.parentId))!==e.parentId)return{ok:!1,reason:R.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=$t(l),u=String(e.parentId),f=d!==u,p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let v=Y(i,p);f&&i.setActivityField(e.activityId,L.PARENT,u);let S=Sr(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,L.CORRELATIVE_ID,S),f){if(!o){let y=i.getActivity(e.parentId);if(y){let g=y.customId,A=bt(y.type)&&i.getChildren(e.parentId).filter(_=>_!==e.activityId).length===0,P=ye({parentId:e.parentId,newChildId:e.activityId,getParent:_=>i.getActivity(_)??null,isCurrentlyLeaf:A,promotionSource:"reparent"});if(P){for(let[_,b]of Object.entries(P.fields))Z(i,P.parentId,_,b);P.fields.customId===null&&Ir(g,r.customIdTracker)}}}if(d!=="0"){let y=i.getActivity(d);if(y){let g=i.getChildren(d),A=me({parent:y,remainingChildIds:g.map(String),defaultDurationHours:a.hoursPerDay,idsRemoved:new Set([e.activityId])});if(A){for(let[M,J]of Object.entries(A.fields))Z(i,d,M,J);let P=Vt(d,i),_=P?i.getActivity(P)?.customId:null,b=typeof _=="string"&&_?_:null,x=r.customIdTracker.generateCustomIdForRestoredChild(b);i.setActivityField(d,L.CUSTOM_ID,x)}}}}f&&(d!=="0"&&Rt(d,i),o||Rt(e.parentId,i));let C=ot(i);for(let y of C){if(p.add(y.activityId),v.has(y.activityId))continue;let g=i.getActivity(y.activityId);if(!g)continue;let A=K(g);y.before!==void 0&&(A.correlativeId=y.before),v.set(y.activityId,A)}let{scheduledIds:D,scheduledBeforeImages:m}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId],now:r.now,options:t}),T=f?Dr([e.activityId],i):[],k={name:yt.ACTIVITY_MOVE,properties:{activity_id:e.activityId,new_parent_id:e.parentId,after_sibling_id:e.afterSiblingId??null,before_sibling_id:e.beforeSiblingId??null,invalid_link_ids:T.map(String)}};return e.eventSource!==void 0&&(k.properties.event_source=e.eventSource),{ok:!0,changes:H(i,{source:e,beforeSnap:v,touchedIds:p,scheduledIds:D,scheduledBeforeImages:m,sirDetection:"before-diff",trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function Bo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:R.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Set,c=[],l=[],d=[],u=new Set(s),f=[...e.activityIds].sort((y,g)=>{let A=i.getActivity(y),P=i.getActivity(g),_=A?nt(A):Xt,b=P?nt(P):Xt;return _-b});for(let y of f){if(!i.getActivity(y)){c.push({activityId:y,reason:R.ACTIVITY_NOT_FOUND}),u.delete(y);continue}let A=yo(y,u,i);if(A==null){c.push({activityId:y,reason:R.INDENT_NO_ELIGIBLE_SIBLING}),u.delete(y);continue}let P=i.getActivity(y)?.parentId,_=O(P)?"0":String(P);d.push({activityId:y,newParentId:A,oldParentId:_}),o.add(y),o.add(A),_!=="0"&&o.add(_)}let p=Y(i,o);for(let{activityId:y,newParentId:g}of d)i.setActivityField(y,L.PARENT,g),i.setActivityField(y,L.CORRELATIVE_ID,Po),l.push(y);let v=new Set;for(let{activityId:y,newParentId:g}of d){if(v.has(g))continue;v.add(g);let A=i.getActivity(g);if(!A)continue;let P=A.customId,_=bt(A.type)&&i.getChildren(g).filter(M=>!l.includes(M)).length===0,b=A.hasNewActivities&&A.newActivityIds.some(M=>String(M)===String(y)),x=ye({parentId:g,newChildId:y,getParent:M=>i.getActivity(M)??null,isCurrentlyLeaf:_,promotionSource:"reparent"});if(x){for(let[M,J]of Object.entries(x.fields))Z(i,x.parentId,M,J);b||(i.setActivityField(g,L.HAS_NEW_ACTIVITIES,!1),i.setActivityField(g,L.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(g,L.CONSTRAINT_TYPE,"asap"),i.setActivityField(g,L.CONSTRAINT_DATE,null),i.setActivityField(g,L.CUSTOM_ID,null),Ir(P,r.customIdTracker)}let S=new Set;for(let y of d)y.oldParentId!=="0"&&S.add(y.oldParentId),S.add(y.newParentId);for(let y of S)Rt(y,i);let C=ot(i);for(let y of C){if(o.add(y.activityId),p.has(y.activityId))continue;let g=i.getActivity(y.activityId);if(!g)continue;let A=K(g);y.before!==void 0&&(A.correlativeId=y.before),p.set(y.activityId,A)}let{scheduledIds:D,scheduledBeforeImages:m}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),T=Dr(l,i),k={name:yt.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(y=>({activity_id:y.activityId,reason:y.reason})),invalid_link_ids:T}};return e.eventSource!==void 0&&(k.properties.event_source=e.eventSource),{ok:!0,changes:H(i,{source:e,beforeSnap:p,touchedIds:o,scheduledIds:D,scheduledBeforeImages:m,trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function Ho(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:R.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let y of e.activityIds){let g=y;i.getActivity(g)&&(o.set(g,Bi(g,i)),c.set(g,Eo(g,s,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],v=[...e.activityIds].sort((y,g)=>{let A=i.getActivity(y),P=i.getActivity(g),_=A?nt(A):Xt,b=P?nt(P):Xt;return _-b});for(let y of v){let g=y,A=i.getActivity(g);if(!A){d.push({activityId:g,reason:R.ACTIVITY_NOT_FOUND});continue}let P=A.parentId;if(O(P)){d.push({activityId:g,reason:R.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let _=String(P),b=i.getActivity(_);if(!b){d.push({activityId:g,reason:R.ACTIVITY_NOT_FOUND});continue}let x=b.parentId;if(O(x)){d.push({activityId:g,reason:R.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let M=String(x),J=Bi(_,i)+1,ct=c.get(g);if(ct!=null&&s.has(ct)){let We=o.get(ct)??-1,Yt=o.get(g)??-1;We>=0&&Yt>=0&&(J+=Yt-We)}p.push({activityId:g,grandparentKey:M,oldParentKey:_,targetIndexInGrandparent:J}),l.add(String(g)),l.add(String(_)),M!=="0"&&l.add(String(M)),f.add(_)}let S=Y(i,l);for(let y of p){i.setActivityField(y.activityId,L.PARENT,y.grandparentKey);let g=Ro(i,y.grandparentKey,y.targetIndexInGrandparent,y.activityId);i.setActivityField(y.activityId,L.CORRELATIVE_ID,g),u.push(y.activityId)}for(let y of f){let g=i.getActivity(y);if(!g)continue;let A=i.getChildren(y),P=me({parent:g,remainingChildIds:A.map(String),defaultDurationHours:a.hoursPerDay,idsRemoved:new Set(p.filter(J=>J.oldParentKey===y).map(J=>J.activityId))});if(!P){ir(y,i);continue}for(let[J,ct]of Object.entries(P.fields))Z(i,y,J,ct);let _=Vt(y,i),b=_?i.getActivity(_)?.customId:null,x=typeof b=="string"&&b?b:null,M=r.customIdTracker.generateCustomIdForRestoredChild(x);i.setActivityField(y,L.CUSTOM_ID,M)}let C=new Set;for(let y of f)C.add(String(y));for(let y of p)y.grandparentKey!=="0"&&C.add(String(y.grandparentKey));for(let y of C)Rt(y,i);let D=ot(i);for(let y of D){if(l.add(y.activityId),S.has(y.activityId))continue;let g=i.getActivity(y.activityId);if(!g)continue;let A=K(g);y.before!==void 0&&(A.correlativeId=y.before),S.set(y.activityId,A)}let{scheduledIds:m,scheduledBeforeImages:T}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:r.now,options:t}),k={name:yt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(y=>({activity_id:String(y.activityId),reason:y.reason}))}};return e.eventSource!==void 0&&(k.properties.event_source=e.eventSource),{ok:!0,changes:H(i,{source:e,beforeSnap:S,touchedIds:l,scheduledIds:m,scheduledBeforeImages:T,trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function jo(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:R.INVALID_PROGRESS_VALUE};let o=n.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let c=Mt(E.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.transform(o,e.newValue,n,e.newValue),d=Wt(e.activityId,l),u=Y(i,d);Ut(i,e.activityId,l),xt(e.activityId,l.postProcessors??[],i);let{scheduledIds:f}=await $({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:l.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:v=>dr(e.activityId,d,v),now:r.now,options:t}),p=(l.trackingEvents??[]).map(v=>({name:v.name,properties:v.properties??{}}));return{ok:!0,changes:H(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:p,hoursPerDay:s.hoursPerDay})}}async function Vo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=[],o=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let v of e.edits){let S=vp(v,r);if(s.push(S.verdict),!S.verdict.ok||!S.changes)continue;let C=Wt(v.activityId,S.changes);Cp(o,C,r);for(let T of C)c.add(T);let D=pe(i,v.activityId);Ut(i,v.activityId,S.changes),xt(v.activityId,S.changes.postProcessors??[],i),d.push(...he(D,i,v.activityId)),f||=!!S.changes.needsAutoSchedule;for(let T of S.changes.trackingEvents??[])l.push({name:T.name,properties:T.properties??{}});let m=ue(v.activityId,S.changes.constraintWarning);m&&u.push(m)}let{scheduledIds:p}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?"roots":null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:s,changes:H(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function vp(e,t){let{ctx:r}=t,i=e.activityId,n=Mt(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let a=r.activityReader.getActivity(e.activityId);if(!a)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??R.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??R.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??R.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function Cp(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let[n,a]of Y(r.adapter,i))e.set(n,a)}var qi=E.CUSTOM_ID;async function Yo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;e.edits.some(T=>T.column===E.DURATION)&&n.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=[],f=[],p=[],v=!1;for(let T of e.edits){let k=Ap(T,r);if(o.push(k.verdict),!k.verdict.ok||!k.changes)continue;let y=ue(T.activityId,k.changes.constraintWarning);y&&p.push(y);let g=Wt(T.activityId,k.changes);Dp(c,g,r);for(let b of g)d.add(b);Sp(l,T,c);let A=pe(i,T.activityId),P=Ip(T,r),_=k.changes;Ut(i,T.activityId,_),xt(T.activityId,k.changes.postProcessors??[],i),kp(T,P,r),f.push(...he(A,i,T.activityId)),v||=!!k.changes.needsAutoSchedule;for(let b of k.changes.trackingEvents??[])u.push({name:b.name,properties:b.properties??{}})}let S={action:e,autoscheduleFrom:v?"roots":null,recomputeParentsFrom:d,now:r.now,options:t},C=l.size>0,{scheduledIds:D,scheduledBeforeImages:m}=await(C?Cr({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:S,revertTargets:[...l].map(([T,k])=>({activityId:T,priorConstraintDate:k})),revert:(T,k)=>vr(T,k,i,r.ctx.calendars)}):$({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},S));return{ok:!0,verdicts:o,changes:H(i,{source:e,beforeSnap:c,touchedIds:d,scheduledIds:D,scheduledBeforeImages:m,sirDetection:"before-diff",links:f,trackingEvents:u,warnings:p,hoursPerDay:a.hoursPerDay})}}function Ap(e,t){let{ctx:r}=t,i=e.activityId,n=Mt(e.column);if(!n)return{verdict:{activityId:i,ok:!1,reason:R.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:i,ok:!1,reason:R.ACTIVITY_NOT_FOUND},changes:null};let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??R.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??R.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??R.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===qi&&o.value!==null){let u=t.adapter.getActivity(e.activityId),f=u?u.customId:null,p=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(o.value),p))return{verdict:{activityId:i,ok:!1,reason:R.CUSTOM_ID_DUPLICATE},changes:null}}let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function Ip(e,t){if(e.column!==qi)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function kp(e,t,r){if(e.column!==qi)return;let i=r.adapter.getActivity(e.activityId),n=i?i.customId:null,a=typeof n=="string"?n:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function Sp(e,t,r){if(!gr(t.column))return;let i=String(t.activityId);if(e.has(i))return;let n=r.get(i);n&&e.set(i,n.constraintDate??null)}function Dp(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let[n,a]of Y(r.adapter,i))e.set(n,a)}function Tp(e,t,r,i,n,a){let s=String(e.id);if(s.length===0||n.has(s))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${s}"`);if(!Number.isSafeInteger(e.proplannerId)||e.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${t} proplannerId ${String(e.proplannerId)}`);if(a.has(e.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${t} proplannerId ${String(e.proplannerId)}`);let o=r(s);if(!o.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${s}"`);if(o.current!==null&&o.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${s}" already has proplannerId ${String(o.current)}`);let c=i.get(e.proplannerId);if(c!==void 0&&c!==s)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);n.add(s),a.add(e.proplannerId)}function $o(e,t,r,i){let n=new Set,a=new Set;for(let s of e)Tp(s,t,r,i,n,a)}function Go(e,t){let r=e.activities??[],i=e.links??[],n=new Map;for(let c of t.adapter.getAllActivities())c.proplannerId!=null&&n.set(c.proplannerId,String(c.id));let a=new Map;for(let c of t.adapter.getAllLinks())c.proplannerId!=null&&a.set(c.proplannerId,String(c.id));$o(r,"activity",c=>{let l=t.adapter.getActivity(c);return{exists:l!==null,current:l?.proplannerId??null}},n),$o(i,"link",c=>{let l=t.adapter.getLink(c);return{exists:l!==null,current:l?.proplannerId??null}},a);let s=[],o=[];return t.adapter.batchUpdate(()=>{for(let c of r){let l=t.adapter.getActivity(c.id);!l||l.proplannerId===c.proplannerId||(t.adapter.setActivityField(c.id,"proplannerId",c.proplannerId),s.push({id:c.id,kind:"updated",fields:{proplannerId:{before:l.proplannerId,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}}))}for(let c of i){let l=t.adapter.getLink(c.id);!l||l.proplannerId===c.proplannerId||(t.adapter.setLinkProplannerId(c.id,c.proplannerId),o.push({id:c.id,kind:"updated",fields:{proplannerId:{before:l.proplannerId,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}}))}}),{ok:!0,changes:{source:e,activities:s,links:o,calendars:[],trackingEvents:[]}}}function Ko(e){return typeof e=="string"&&e.length>0?Pt(e):e instanceof Date?e:null}function Ji(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function Tr(e,t){let r=Ji(e.duration),i=Ji(e.cost),n=Ji(e.hh_work);return r===null||i===null||n===null?(t.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(e.duration)}, cost=${JSON.stringify(e.cost)}, hh_work=${JSON.stringify(e.hh_work)}`),null):{startDate:Ko(e.start_date),endDate:Ko(e.end_date),durationDays:r,cost:i,workHours:n,versionId:typeof e.sectorbaselineversionId=="number"?e.sectorbaselineversionId:null,isActiveVersion:!!e.sectorbaselineversion?.active,isVisibleVersion:!!e.sectorbaselineversion?.visible,baseCalendarId:e.baseCalendarId!=null?String(e.baseCalendarId):null,hoursPerDay:typeof e.hoursPerDay=="number"?e.hoursPerDay:null,hoursPerWeek:typeof e.hoursPerWeek=="number"?e.hoursPerWeek:null}}function zo(e,t,r){let i=new Map;e.forEachActivity((s,o)=>{let c=s.proplannerId;typeof c=="number"&&i.set(c,o)});let n=new Map;for(let s of t){let o=s.activityId;if(typeof o!="number")continue;let c=i.get(o);if(c===void 0)continue;let l=n.get(c);l?l.push(s):n.set(c,[s])}let a=[];for(let[s,o]of n)e.setActivityField(s,"baselinePoints",o.map(c=>Tr(c,r)).filter(c=>c!==null)),a.push(s);return e.forEachActivity((s,o)=>{if(n.has(o))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(o,"baselinePoints",[]),a.push(o))}),a}function _p(e){let t=at(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function qo(e){let t=[];return e.forEachActivity((r,i)=>{let n=_p(r);if(!n){r.baselineSnapshot!==null&&(e.setActivityField(i,"baselineSnapshot",null),t.push(i));return}e.setActivityField(i,"baselineSnapshot",n),t.push(i)}),t}function _r(e,t,r,i,n=null){let a=new Set;for(let s of zo(e,t,i))a.add(s);if(r)for(let s of Bt(e,r,n))a.add(s);for(let s of qo(e))a.add(s);for(let s of jt(e))a.add(s);return[...a]}function Jo(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,a=0;for(let o of i){let c=Pp(String(o),t,r);n.set(String(o),c),a+=c}let s=a?100/a:0;for(let o of i){let c=r.getActivity(o);if(!c)continue;let l=c.baselinePoints;if(at(c)){let u=n.get(String(o))??0;r.setActivityField(o,E.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,E.PONDERATOR,0)}}function Pp(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=at(i);if(!n)return 0;if(t==="COST")return Pr(n.cost);if(t==="HH")return Pr(n.workHours);let a=i.type;return a==="project"?Xo(e,r):a==="milestone"?0:Pr(n.durationDays)}function Xo(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=at(n);if(!a)continue;let s=n.type;s==="project"?r+=Xo(String(i),t):s!=="milestone"&&(r+=Pr(a.durationDays))}return r}function Pr(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Zo(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,E.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&Jo(String(i),e,t)})}function Er(e){for(let t of Ep(e))Lp(t,e)}function Ep(e){let t=new Set;e.forEachActivity((i,n)=>{e.getChildren(n).length>0&&t.add(n)});let r=new Map;for(let i of t)r.set(i,Rp(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function Rp(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Lp(e,t){let r=t.getChildren(e);if(r.length===0)return;let i=[];for(let a of r){let s=t.getActivity(a);s&&i.push({progress:Number(s.progress??0),ponderator:Number(s.ponderator??0)})}let n=ne(i);n!==null&&t.setActivityField(e,E.PROGRESS,rr(n))}function Rr(e,t){Zo(t,e.adapter),Er(e.adapter),e.now&&(Bt(e.adapter,e.now,e.defaultBaseCalendarId??null),Et(e.adapter,e.now)),jt(e.adapter),e.now&&vt(e.adapter,e.sector.statusCriteria)}function Qo(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let r=e.adapter.getActivity(t)?.baselinePoints.find(i=>i.isActiveVersion);return r?[String(t),r.versionId,r.startDate?.getTime()??null,r.endDate?.getTime()??null,r.durationDays,r.cost,r.workHours,r.baseCalendarId,r.hoursPerDay,r.hoursPerWeek]:[String(t),null]}))}function tc(e,t){let r=Y(t.adapter,new Set(t.adapter.getAllIds())),i=Qo(t),n=_r(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return Qo(t)!==i&&Rr(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:H(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function bp(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}function ec(e,t){bp(e.criterion);let r=new Set(t.adapter.getAllIds()),i=Y(t.adapter,r);return Rr(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:H(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function rc(e,t){let r=He(e.criteria),i=new Set(t.adapter.getAllIds()),n=Y(t.adapter,i),a=vt(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:H(t.adapter,{source:e,beforeSnap:n,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function ic(e,t,r){return e.kind==="persistence-acknowledge"?Go(e,r):e.kind==="baseline-apply"?tc(e,r):e.kind==="ponderator-criterion-set"?ec(e,r):e.kind==="status-criteria-set"?rc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?lo(e,t,r):e.kind==="links-batch"?uo(e,t,r):e.kind==="activity-create"?Lo(e,t,r):e.kind==="activity-paste"?bo(e,t,r):e.kind==="activity-delete"?Mo(e,t,r):e.kind==="activity-move"?Uo(e,t,r):e.kind==="activity-indent"?Bo(e,t,r):e.kind==="activity-outdent"?Ho(e,t,r):e.kind==="activity-set-progress"?jo(e,t,r):e.kind==="dates-batch"?Vo(e,t,r):e.kind==="bulk-edit"?Yo(e,t,r):e.kind==="selection-toggle"?Tn(e,Xi(r)):e.kind==="selection-replace"?_n(e,Xi(r)):e.kind==="visibility-set"?Pn(e,Xi(r)):e.kind==="sir-sync"?wo(e,r):e.kind==="activity-lookahead-sync"?Oo(e,r):e.kind==="inline-edit"&&(e.column===E.CUSTOM_PREDECESSORS||e.column===E.CUSTOM_SUCESSORS)?fo(e,t,r):e.kind!=="inline-edit"?fa(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):co(e,t,r)}function Xi(e){return{adapter:e.adapter}}var wp=new Set(["startDate","endDate","constraintDate"]);function nc(e,t){return wp.has(e)&&typeof t=="string"?new Date(t):t}function ac(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?Op(n,r):null}}}function Op(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,i){return e.calculateEndDate({start_date:r,duration:i,unit:t})},calculateDuration(r,i){return e.calculateDuration({start_date:r,end_date:i,unit:t})},isWorkTime(r,i){return e.isWorkTime({date:r,unit:i})},getWorkHours(r){return e.getWorkHours(r)}}}function xp(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function Zt(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Qt(e){return Zt(e)&&!isNaN(e.getTime())}var Np={}.constructor.toString();function Fp(e){var t=e.constructor.toString();return t!==Np}function Mp(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function At(e){var t,r;if(e&&typeof e=="object")switch(!0){case Zt(e):r=new Date(e);break;case xp(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=At(e[t]);break;default:if(Fp(e))r=Object.create(e);else{if(Mp(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=At(e[t]));break}return r||e}function ge(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function sc(e){return typeof e<"u"}var Lr;function Zi(){return Lr||(Lr=new Date().valueOf()),Lr++,Lr}function ut(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var Up=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return`"+to_fixed(date.get${t?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${t?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${t?"UTC":""}Date()+"`;case"%n":return`"+(date.get${t?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${t?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${t?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${t?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${t?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${t?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${t?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${t?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${t?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${t?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${t?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${t?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${t?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return n}});let i=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return n=>i(n,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},Bp=(e,t,r)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",n=e.match(/%[a-zA-Z]/g);for(let o=0;o<n.length;o++)switch(n[o]){case"%j":case"%d":i+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":i+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":i+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":i+=`set[3]=temp[${o}]||0;`;break;case"%i":i+=`set[4]=temp[${o}]||0;`;break;case"%Y":i+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":i+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":i+=`set[5]=temp[${o}]||0;`;break;case"%M":i+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":i+=`set[1]=locale.date.month_full_hash[temp[${o}]]||0;`;break}let a="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(a=` Date.UTC(${a})`);let s=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${a});`);return o=>s(o,r.locale)},oc={date_to_str:Up,str_to_date:Bp},Hp=(e,t,r)=>i=>e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return t?r.date.to_fixed(i.getUTCDate()):r.date.to_fixed(i.getDate());case"%m":return t?r.date.to_fixed(i.getUTCMonth()+1):r.date.to_fixed(i.getMonth()+1);case"%j":return t?i.getUTCDate():i.getDate();case"%n":return t?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return t?r.date.to_fixed(i.getUTCFullYear()%100):r.date.to_fixed(i.getFullYear()%100);case"%Y":return t?i.getUTCFullYear():i.getFullYear();case"%D":return t?r.locale.date.day_short[i.getUTCDay()]:r.locale.date.day_short[i.getDay()];case"%l":return t?r.locale.date.day_full[i.getUTCDay()]:r.locale.date.day_full[i.getDay()];case"%M":return t?r.locale.date.month_short[i.getUTCMonth()]:r.locale.date.month_short[i.getMonth()];case"%F":return t?r.locale.date.month_full[i.getUTCMonth()]:r.locale.date.month_full[i.getMonth()];case"%h":return t?r.date.to_fixed((i.getUTCHours()+11)%12+1):r.date.to_fixed((i.getHours()+11)%12+1);case"%g":return t?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return t?i.getUTCHours():i.getHours();case"%H":return t?r.date.to_fixed(i.getUTCHours()):r.date.to_fixed(i.getHours());case"%i":return t?r.date.to_fixed(i.getUTCMinutes()):r.date.to_fixed(i.getMinutes());case"%a":return t?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return t?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(i.getUTCSeconds()):r.date.to_fixed(i.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(i)):r.date.to_fixed(r.date.getISOWeek(i));case"%w":return r.date.to_fixed(r.date.getWeek(i));default:return n}}),jp=(e,t,r)=>i=>{let n=[0,0,1,0,0,0],a=i.match(/[a-zA-Z]+|[0-9]+/g),s=e.match(/%[a-zA-Z]/g);for(let o=0;o<s.length;o++)switch(s[o]){case"%j":case"%d":n[2]=a[o]||1;break;case"%n":case"%m":n[1]=(a[o]||1)-1;break;case"%y":n[0]=a[o]*1+(a[o]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":n[3]=a[o]||0;break;case"%i":n[4]=a[o]||0;break;case"%Y":n[0]=a[o]||0;break;case"%a":case"%A":n[3]=n[3]%12+((a[o]||"").toLowerCase()==="am"?0:12);break;case"%s":n[5]=a[o]||0;break;case"%M":n[1]=r.locale.date.month_short_hash[a[o]]||0;break;case"%F":n[1]=r.locale.date.month_full_hash[a[o]]||0;break}return t?new Date(Date.UTC(n[0],n[1],n[2],n[3],n[4],n[5])):new Date(n[0],n[1],n[2],n[3],n[4],n[5])},cc={date_to_str:Hp,str_to_date:jp};function lc(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function r(o){var c=new Date(o);return isNaN(c.getTime())?null:c}var i=null;function n(){try{new Function("canUseCsp = false;")}catch{i=!0}}function a(){var o=!1;return e.config.csp==="auto"?(i===null&&n(),o=i):o=e.config.csp,o}var s={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(o){return o.toISOString()},formatISODateOnly:function(o){return o.getUTCFullYear()+"-"+e.date.to_fixed(o.getUTCMonth()+1)+"-"+e.date.to_fixed(o.getUTCDate())},init:function(){for(var o=e.locale,l=o.date.month_short,d=o.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=o.date.month_full,d=o.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(o){return o.setUTCHours(0,0,0,0),o},time_part:function(o){return o.valueOf()/1e3%86400},week_start:function(o){var c=o.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(o,-1*c,"day"))},month_start:function(o){return o.setUTCDate(1),this.date_part(o)},quarter_start:function(o){this.month_start(o);var c=o.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,o.setUTCMonth(l),o},year_start:function(o){return o.setUTCMonth(0),this.month_start(o)},day_start:function(o){return this.date_part(o)},hour_start:function(o){return o.getUTCMinutes()&&o.setUTCMinutes(0),this.minute_start(o),o},minute_start:function(o){return o.getUTCSeconds()&&o.setUTCSeconds(0),o.getUTCMilliseconds()&&o.setUTCMilliseconds(0),o},_add_days:function(o,c,l){return o.setUTCDate(o.getUTCDate()+c),o},add:function(o,c,l){var d=new Date(o.valueOf());switch(l){case"day":d=this._add_days(d,c,o);break;case"week":d=this._add_days(d,c*7,o);break;case"month":d.setUTCMonth(d.getUTCMonth()+c);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+c);break;case"hour":d.setTime(d.getTime()+c*60*60*1e3);break;case"minute":d.setTime(d.getTime()+c*60*1e3);break;default:return this["add_"+l](o,c,l)}return d},add_quarter:function(o,c){return this.add(o,c*3,"month")},to_fixed:function(o){return o<10?"0"+o:o},copy:function(o){return new Date(o.valueOf())},date_to_str:function(o,c){var l=oc;return a()&&(l=cc),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=oc;return a()&&(l=cc),l.str_to_date(o,c,e)},getISOWeek:function(o){return e.date._getWeekNumber(o,!0)},_getWeekNumber:function(o,c){if(!o)return!1;var l=o.getUTCDay();c&&l===0&&(l=7);var d=new Date(o.valueOf());d.setUTCDate(o.getUTCDate()+(4-l));var u=d.getUTCFullYear(),f=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),p=1+Math.floor(f/7);return p},getWeek:function(o){return e.date._getWeekNumber(o,e.config.start_on_monday)},getUTCISOWeek:function(o){return e.date.getISOWeek(o)},parseDate:function(o,c){if(o&&!o.getFullYear){var l=!c||c==="parse_date"||c==="xml_date",d=l&&(e.defined(e.templates.xml_date)||e.templates.parse_date&&!e.templates.parse_date._ganttAuto);if(!d&&typeof o=="string"&&t.test(o)){var u=o.indexOf("T")!==-1,f=r(o);if(f)return s._isoDateDetected?u&&(s._isoDateOnly=!1):(s._isoDateDetected=!0,s._isoDateOnly=!u),f}typeof c!="function"&&(typeof c=="string"?c==="parse_date"||c==="xml_date"?c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date:c=e.defined(e.templates[c])?e.templates[c]:e.date.str_to_date(c,!0):c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date),o?o=c(o):o=null}return o}};return s}function Qi(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function tn(e,t,r,i,n,a){return this.date=e,this.dir=t,this.unit=r,this.task=i,this.id=n,this.calendar=a,this}function en(e,t,r,i,n,a,s){return this.start_date=e,this.duration=t,this.unit=r,this.step=i,this.task=n,this.id=a,this.calendar=s,this}function Vp(e,t,r,i){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=i,this.unit=null,this.step=null,this}var dc=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(Zt(t)?t={date:t}:t=ge({},t),!Qt(t.date))throw e.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return t},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var t=arguments[0];if(t instanceof Qi)return t;var r;if(t.date?r=new Qi(t.date,t.unit,t.task,null,t.calendar):r=new Qi(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!Qt(r.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return r},getClosestWorkTimeArguments:function(t){var r=arguments[0];if(r instanceof tn)return r;var i;if(Zt(r)?i=new tn(r):i=new tn(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(i.task=r),i.dir=r.dir||"any",i.unit=r.unit||e.config.duration_unit,!Qt(i.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return i},_getStartEndConfig:function(t){var r=Vp,i;if(t instanceof r)return t;if(Zt(t)?i=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(i=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(i.task=t)),i.unit=i.unit||e.config.duration_unit,i.step=i.step||e.config.duration_step,i.start_date=i.start_date||i.start||i.date,!Qt(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!Qt(i.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return i},getDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,i,n){var a=arguments[0];if(a instanceof en)return a;var s;if(Zt(a)?s=new en(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new en(a.start_date,a.duration,a.unit,a.step,a.task,null,a.calendar),a.id!==null&&a.id!==void 0&&(s.task=a,s.unit=null,s.step=null),s.unit=s.unit||e.config.duration_unit,s.step=s.step||e.config.duration_step,!Qt(s.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return s}}};function uc(){}uc.prototype={_getIntervals:function(e){for(var t=[],r=0;r<e.length;r+=2)t.push({start:e[r],end:e[r+1]});return t},_toHoursArray:function(e){var t=[];function r(a){var s=String(a);return s.length<2&&(s="0"+s),s}function i(a){var s=Math.floor(a/3600),o=a-s*60*60,c=Math.floor(o/60);return s+":"+r(c)}for(var n=0;n<e.length;n++)t.push(i(e[n].start)+"-"+i(e[n].end));return t},_intersectHourRanges:function(e,t){var n=[],r=e.length>t.length?e:t,i=e===r?t:e;r=r.slice(),i=i.slice();for(var n=[],a=0;a<r.length;a++)for(var s=r[a],o=0;o<i.length;o++){var c=i[o];c.start<s.end&&c.end>s.start&&(n.push({start:Math.max(s.start,c.start),end:Math.min(s.end,c.end)}),s.end>c.end&&(i.splice(o,1),o--,a--))}return n},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,s){return a.start-s.start});for(var r=t[0],i=1;i<t.length;i++){var n=t[i];n.start<=r.end?(n.end>r.end&&(r.end=n.end),t.splice(i,1),i--):r=n}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=At(e.getConfig()),i=At(t.getConfig()),n=r.parsed,a=i.parsed;n.customWeeks=r.customWeeks,a.customWeeks=i.customWeeks;var s={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,a.hours)),dates:{},customWeeks:{}};let o=(l,d)=>{for(let u in l.dates){let f=l.dates[u];+u>1e3&&(s.dates[u]=!1);for(let p in d.dates){let v=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&v)),Array.isArray(f)){let S=Array.isArray(v)?v:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,S))}}}};if(o(n,a),o(a,n),n.customWeeks)for(var c in n.customWeeks)s.customWeeks[c]=n.customWeeks[c];if(a.customWeeks)for(var c in a.customWeeks)s.customWeeks[c]?s.customWeeks[c+"_second"]=a.customWeeks[c]:s.customWeeks[c]=a.customWeeks[c];return s}};var rn=class{constructor(){this.clear()}getItem(t,r,i){if(this._cache.has(t)){let a=this._cache.get(t)[i.getUTCFullYear()];if(a&&a.has(r))return a.get(r)}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache,s=n.getUTCFullYear(),o;a.has(t)?o=a.get(t):(o=[],a.set(t,o));let c=o[s];c||(c=o[s]=new Map),c.set(r,i)}clear(){this._cache=new Map}},nn=class{constructor(){this.clear()}getItem(t,r,i){let n=this._cache;if(n&&n[t]){let a=n[t];if(a===void 0)return-1;let s=a[i.getUTCFullYear()];if(s&&s[r]!==void 0)return s[r]}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let s=a[t],o=n.getUTCFullYear(),c=s[o];c||(c=s[o]={}),c[r]=i}clear(){this._cache={}}},an=class{constructor(t){this.getMinutesPerWeek=r=>{let i=r.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r));for(let c=0;c<7;c++)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._weekCache.set(i,s),s},this.getMinutesPerMonth=r=>{let i=r.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r)),c=a.date.add(o,1,"month").valueOf();for(;o.valueOf()<c;)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._monthCache.set(i,s),s},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function Yp(){return typeof Map<"u"?new rn:new nn}var sn=class{constructor(){this.clear()}_getCacheObject(t,r,i){let n=this._cache;n[r]||(n[r]=[]);let a=n[r];a||(a=n[r]={});let s=a[i];s||(s=a[i]={});let o=t.getUTCFullYear(),c=s[o];return c||(c=s[o]={durations:{},endDates:{}}),c}_endDateCacheKey(t,r){return String(t)+"-"+String(r)}_durationCacheKey(t,r){return String(t)+"-"+String(r)}getEndDate(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=this._endDateCacheKey(o,r),l;if(s.endDates[c]===void 0){let d=a(),u=d.valueOf();s.endDates[c]=u,s.durations[this._durationCacheKey(o,u)]=r,l=d}else l=new Date(s.endDates[c]);return l}getDuration(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=r.valueOf(),l=this._durationCacheKey(o,c),d;if(s.durations[l]===void 0){let u=a();s.durations[l]=u.valueOf(),d=u}else d=s.durations[l];return d}clear(){this._cache={}}};function on(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=Yp(),this._largeUnitsCache=new an(this),this._dateDurationCache=new sn,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}on.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(e){for(var t=0,r=this.units.length;t<r;t++)if(this.units[t]==e)return t},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(e){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var t=null;if(e.day||e.day===0)t=e.day;else if(e.date){var r=String(e.date.valueOf());this._cached_timestamps[r]?t=this._cached_timestamps[r]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[r]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let r=this.$gantt.date[`${t}_start`](new Date(e)),i=this.$gantt.date.add(r,1,t);return this.hasDuration(r,i)}return this["_is_work_"+t](e)},_is_work_day:function(e){var t=this._getWorkHours(e);return Array.isArray(t)?t.length>0:!1},_is_work_hour:function(e){for(var t=this._getWorkHours(e),r=e.getUTCHours(),i=0;i<t.length;i++)if(r>=t[i].startHour&&r<t[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var r=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(r=24),r*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),r=this._getTimeOfDayStamp(e),i=0;i<t.length;i++)if(r>=t[i].start&&r<t[i].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,i){var n=this.$gantt.date,a=new Date(e),s=new Date(t);i=i||1;var o=0,c=null,l,d,u=!1;l=n[r+"_start"](new Date(a)),l.valueOf()!=a.valueOf()&&(u=!0);var f=!1;d=n[r+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var p=!1;a.valueOf()<s.valueOf();){if(c=this._nextDate(a,r,i),p=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&p)&&(l=n[r+"_start"](new Date(a)),d=n.add(l,i,r)),u?(u=!1,c=this._nextDate(l,r,i),o+=(d.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):f&&p?(f=!1,o+=(s.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):o++;else{var v=this._getUnitOrder(r),S=this.units[v-1];S&&!this._isWorkTime(a,S)&&(c=this._getClosestWorkTimeFuture(a,S))}a=c}return o},_getMinutesPerHour:function(e){var t=this._getTimeOfDayStamp(e),r=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));r===0&&(r=1440*60);for(var i=this._getWorkHours(e),n=0;n<i.length;n++){var a=i[n];if(t>=a.start&&r<=a.end)return 60;if(t<a.end&&r>a.start){var s=Math.min(r,a.end)-Math.max(t,a.start);return s/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,i){var n=0,a=new Date(e),s=new Date(t),o;for(r=="minute"?o=ut(this._getMinutesPerDay,this):o=ut(this.getHoursPerDay,this);a.valueOf()<s.valueOf();){if(s-a>1e3*60*60*24*32&&a.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,1,"month");continue}else if(s-a>1e3*60*60*24*16){var l=this.$gantt.date.week_start(new Date(a));if(a.valueOf()===l.valueOf()){var c=this._largeUnitsCache.getMinutesPerWeek(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,7,"day");continue}}n+=o(a),a=this._nextDate(a,"day",1)}return n/i},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),i=this._getWorkHours(e),n=0,a=0;a<i.length;a++){var s=i[a];if(r.end>=s.start&&r.start<=s.end){var o=Math.max(s.start,r.start),c=Math.min(s.end,r.end);n+=(c-o)/60,r.start=c}}return Math.floor(n)},_getMinutesBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o),u=this._getMinutesBetweenSingleDay(c,l),f=this._getWorkUnitsForRange(o,c,r,i),p=d+f+u;return p},_getHoursBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o,r,i)/60,u=this._getMinutesBetweenSingleDay(c,l,r,i)/60,f=this._getWorkUnitsForRange(o,c,r,i),p=d+f+u;return Math.round(p)},getConfig:function(){return this._worktime},_setConfig:function(e){this._worktime=e,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var e=this.getConfig();e.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},e.parsed.hours=this._parseHours(e.hours);for(var t in e.dates)e.parsed.dates[t]=this._parseHours(e.dates[t]);if(e.customWeeks){var r=null,i=null;for(var t in e.customWeeks){var n=e.customWeeks[t];if(n.from&&n.to){var a=n.from,s=n.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!i||i<s.valueOf())&&(i=s.valueOf()),e.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:s.valueOf(),toReadable:new Date(s),name:t}),e.parsed.haveCustomWeeks=!0;var o=e.parsed.customWeeks[t]={from:n.from,to:n.to,hours:this._parseHours(n.hours),dates:{}};if(n.days&&!n.dates){n.dates=n.dates||{};for(var t=0;t<n.days.length;t++)n.dates[t]=n.days[t],n.days[t]instanceof Array||(n.dates[t]=!!n.days[t]);delete n.days}for(var c in n.dates)o.dates[c]=this._parseHours(n.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(e){var t=JSON.stringify(this.getConfig());return e(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(t)),this._clearCaches(),!1)},_arraysEqual:function(e,t){if(e===t)return!0;if(!e||!t||e.length!=t.length)return!1;for(var r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var r=Object.keys(e.dates),i=Object.keys(t.dates);if(r.sort(),i.sort(),!this._arraysEqual(r,i))return!1;for(var n=0;n<r.length;n++){var a=r[n],s=e.dates[a],o=t.dates[a];if(s!==o&&!(Array.isArray(s)&&Array.isArray(o)&&this._arraysEqual(s,o)))return!1}return!0},equals:function(e){if(!(e instanceof on))return!1;var t=this.getConfig(),r=e.getConfig();if(!this._compareSettings(t,r))return!1;if(t.parsed.haveCustomWeeks&&r.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=r.parsed.customWeeksBoundaries.length)return!1;for(var i in t.parsed.customWeeks){var n=t.parsed.customWeeks[i],a=r.parsed.customWeeks[i];if(!a||!this._compareSettings(n,a))return!1}}else if(t.parse.haveCustomWeeks!==r.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(e.date,!1)},_getWorkHours:function(e,t){var r=this.getConfig();if(t!==!1&&(r=r.parsed),!e)return r.hours;let i=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var n=this._timestamp({date:i});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=n&&r.customWeeksRangeEnd>n){for(var a=0;a<r.customWeeksBoundaries.length;a++)if(r.customWeeksBoundaries[a].from<=n&&r.customWeeksBoundaries[a].to>n){r=r.customWeeks[r.customWeeksBoundaries[a].name];break}}var s=!0;return r.dates[n]!==void 0?s=r.dates[n]:r.dates[e.getUTCDay()]!==void 0&&(s=r.dates[e.getUTCDay()]),s===!0?r.hours:s||[]},_getIntervalTimestamp:function(e,t){var r={start:0,end:0};r.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var i=t.getUTCHours();return!i&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(i=24),r.end=i*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),r},_parseHours:function(e){if(Array.isArray(e)){var t=[];e.forEach(function(o){typeof o=="number"?t.push(o*60*60):typeof o=="string"&&o.split("-").map(function(c){return c.trim()}).forEach(function(c){var l=c.split(":").map(function(u){return u.trim()}),d=parseInt(l[0]*60*60);l[1]&&(d+=parseInt(l[1]*60)),l[2]&&(d+=parseInt(l[2])),t.push(d)})});for(var r=[],i=0;i<t.length;i+=2){var n=t[i],a=t[i+1],s=a-n;r.push({start:n,end:a,startHour:Math.floor(n/3600),startMinute:Math.floor(n/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:s,durationMinutes:s/60,durationHours:s/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(ut(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),i=this.getConfig();if(r!==null?i.dates[r]=t:e.customWeeks||(i.hours=t),e.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof e.customWeeks=="string")r!==null?i.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(i.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)i.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(ut(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var r=-1,i=null;return i=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,i,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,i,r,e)),r},isWorkTime:function(){var e=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(e.date,e.unit)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!e.unit)return!1;var t=this;return this._dateDurationCache.getDuration(e.start_date,e.end_date,e.unit,e.step,function(){return t._calculateDuration(e.start_date,e.end_date,e.unit,e.step)})},_calculateDuration:function(e,t,r,i){var n=0,a=1;if(e.valueOf()>t.valueOf()){var s=t;t=e,e=s,a=-1}return r=="hour"&&i==1?n=this._getHoursBetween(e,t,r,i):r=="minute"&&i==1?n=this._getMinutesBetween(e,t,r,i):n=this._getWorkUnitsBetweenGeneric(e,t,r,i),a*Math.round(n)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;if(!i)return!1;var a=new Date(t),s=new Date(r);for(n=n||1;a.valueOf()<s.valueOf();){if(this._isWorkTime(a,i))return!0;a=this._nextDate(a,i,n)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;if(!i)return!1;var a=e.duration>=0?1:-1;r=Math.abs(r*1);var s=this;return this._dateDurationCache.getEndDate(t,r,i,n*a,function(){return s._calculateEndDate(t,r,i,n*a)})},_calculateEndDate:function(e,t,r,i){if(!r)return!1;if(i==1&&r=="minute")return this._calculateMinuteEndDate(e,t,i);if(i==-1&&r=="minute")return this._subtractMinuteDate(e,t,i);if(i==1&&r=="hour")return this._calculateHourEndDate(e,t,i);var n=this._addInterval(e,t,r,i,null);return n.end},_addInterval:function(e,t,r,i,n){for(var a=0,s=e;a<t&&!(n&&n(s));){var o=this._nextDate(s,r,i),c=new Date(o.valueOf()+1);i>0&&(c=new Date(o.valueOf()-1));var l=this._isWorkTime(c,r);l&&a++,s=o}return{end:s,start:e,added:a}},_addHoursUntilDayEnd:function(e,t){for(var r=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/3600;u>n&&(u=n,d=l+n*60*60);var f=Math.round((d-l)/3600);i+=f,n-=f,a.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_calculateHourEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1);var a=this._addHoursUntilDayEnd(i,t);n=a.added,i=a.end;var s=t-n;if(s){for(var o=i;n<t;){var c=this._nextDate(o,"day",r);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(r>0?l=this.getHoursPerDay(new Date(c.valueOf()-1)):l=this.getHoursPerDay(new Date(c.valueOf()+1)),n+l>=t)break;n+=l,o=c}i=o}if(n<t){var s=t-n;a=this._addHoursUntilDayEnd(i,s),i=a.end}return i},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var r=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/60;u>n&&(u=n,d=l+n*60);var f=Math.round((d-l)/60);n-=f,i+=f,a.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),i=0,n=t,a=r.getUTCHours()*60*60+r.getUTCMinutes()*60+r.getUTCSeconds(),s=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),o=this._getWorkHours(e),c=o.length-1;c>=0&&i<t;c--){var l=o[c];if(s>l.start&&a<=l.end){var d=Math.min(s,l.end),u=Math.max(a,l.start),f=(d-u)/60;f>n&&(f=n,u=d-n*60);var p=Math.abs(Math.round((d-u)/60));n-=p,i+=p,s=u}}var v=r;return i===t&&(v=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:i,end:v}},_subtractMinuteDate:function(e,t,r){var i=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),n=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let a=this._isMinutePrecision(i),s=this._subtractMinutesUntilHourStart(i,t);n+=s.added,i=s.end;for(var o=0,c=[],l=0;n<t;){var d=this.$gantt.date.day_start(new Date(i)),u=!1;i.valueOf()===d.valueOf()&&(d=this.$gantt.date.add(d,-1,"day"),u=!0);var f=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();f!==o&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),o=f);var p=t-n,v=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=v&&p>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var S=!1,C=null,D=null,m=c.length-1;m>=0;m--)if(c[m].start<v-1&&c[m].end>=v-1){S=!0,C=c[m],D=c[m-1];break}if(S)if(v===C.end&&p>=C.durationMinutes)n+=C.durationMinutes,i=this.$gantt.date.add(i,-C.durationMinutes,"minute");else if(!a&&p<=v/60-C.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(a)p<=v/60-C.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=v/60-C.startMinute,D?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,D.end)):i=this.$gantt.date.day_start(i));else{var T=this._getMinutesPerHour(i);T<=p?(n+=T,i=this._nextDate(i,"hour",r)):(s=this._subtractMinutesUntilHourStart(i,p),n+=s.added,i=s.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var k=this._getClosestWorkTimePast(i,"hour");if(k.valueOf()===i.valueOf()){var k=this.$gantt.date.add(i,-1,"day"),y=this._getWorkHours(k);if(y.length){var g=y[y.length-1];k.setUTCSeconds(g.durationSeconds)}}i=k}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var A=t-n;s=this._subtractMinutesUntilHourStart(i,A),n+=s.added,i=s.end}return i},_calculateMinuteEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(i,t);n+=a.added,i=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(i);n<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==s&&(o=this._getWorkHours(i),c=this._getMinutesPerDay(i),s=d);var u=t-n,f=this._getTimeOfDayStamp(i);if(!o.length||!c){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(o[0].start>=f&&u>=c){if(n+=c,u==c){i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,o[o.length-1].end));break}else i=this.$gantt.date.add(i,1,"day"),i=this.$gantt.date.day_start(i);continue}for(var p=!1,v=null,S=0;S<o.length;S++)if(o[S].start<=f&&o[S].end>f){p=!0,v=o[S];break}if(p)if(f===v.start&&u>=v.durationMinutes)n+=v.durationMinutes,i=this.$gantt.date.add(i,v.durationMinutes,"minute");else if(u<=v.endMinute-f/60)n+=u,i=this.$gantt.date.add(i,u,"minute");else{var C=this._getMinutesPerHour(i);C<=u?(n+=C,l?i=this.$gantt.date.add(i,C,"minute"):i=this._nextDate(i,"hour",r)):(a=this._addMinutesUntilHourEnd(i,u),n+=a.added,i=a.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(n<t){var D=t-n;a=this._addMinutesUntilHourEnd(i,D),n+=a.added,i=a.end}return i},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,r){var i=new Date(e);if(this._isWorkTime(i,t))return i;if(i=this.$gantt.date[t+"_start"](i),r=="any"||!r){var n=this._getClosestWorkTimeFuture(i,t),a=this._getClosestWorkTimePast(i,t);Math.abs(n-e)<=Math.abs(e-a)?i=n:i=a}else r=="past"?i=this._getClosestWorkTimePast(i,t):i=this._getClosestWorkTimeFuture(i,t);return i},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var r=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(r,1,t)},_findClosestTimeInDay:function(e,t,r){var i=new Date(e),n=null,a=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",t<0?"past":"future"),t<0&&(i=new Date(i.valueOf()-1),a=!0),r=this._getWorkHours(i));var s=this._getTimeOfDayStamp(i);if(a&&(s=this._getTimeOfDayStamp(new Date(i.valueOf()+1),a)),t>0){for(var o=0;o<r.length;o++)if(r[o].start>=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].start));break}}else for(var o=r.length-1;o>=0;o--)if(r[o].end<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].end));break}else if(r[o].end>s&&r[o].start<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,s));break}return n},_getClosestWorkMinute:function(e,t,r){var i=new Date(e),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n);return a||(r>0?(i=this.calculateEndDate(i,r,t),i=this.$gantt.date.day_start(i)):(i=this.calculateEndDate(i,r,"day"),i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n)),r<0&&(a=this.$gantt.date.add(a,-1,t)),a},_getClosestWorkTimeGeneric:function(e,t,r){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,r);for(var i=this._getUnitOrder(t),n=this.units[i-1],a=e,s=3e3,o=0;!this._isWorkTime(a,t)&&!(n&&!this._isWorkTime(a,n)&&(r>0?a=this._getClosestWorkTimeFuture(a,n):a=this._getClosestWorkTimePast(a,n),this._isWorkTime(a,t)));){if(o++,o>s)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,r,t),this.$gantt.date[t+"_start"]&&(a=this.$gantt.date[t+"_start"](a))}return a},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,r=[0,1,2,3,4,5,6];for(var i in e.dates);var n=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(s){if(!a){var o=t[s];o===!0?a=n:Array.isArray(o)&&(a=this._checkWorkHours(o))}}).bind(this)),a},_checkWorkHours:function(e){if(e.length===0)return!1;for(var t=!1,r=0;r<e.length;r+=2)e[r]!==e[r+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(r){(r.startMinute%60||r.endMinute%60)&&(t=!0)}),t}};var xe={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,r=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var i in e){r=i;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var i=t[r];if(e[r]){var n=i[e[r]];if(n)return n}}return null}};function $p(){function e(n){return n.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var t={};function r(n,a){return a.mergeCalendars(n.map(function(s){var o=s&&s.resource_id?s.resource_id:s;return a.getResourceCalendar(o)}))}function i(n,a){var s=e(n);if(n.length){if(n.length===1)return a.getResourceCalendar(s).id;if(t[s])return t[s].id;var o=r(n,a);return t[s]=o,a.addCalendar(o)}else return null}return{getCalendarIdFromMultipleResources:i}}var Gp=$p();function fc(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=xe.isLegacyResourceCalendarFormat(this.$gantt.config.resource_calendars))}).bind(this)),this.$gantt.attachEvent("onBeforeGanttReady",(function(){this.createDefaultCalendars()}).bind(this)),this.$gantt.attachEvent("onBeforeGanttRender",(function(){this.createDefaultCalendars()}).bind(this))}fc.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let r={};if(t?.weekdays)for(let i=0;i<7;i++)r[i]=t.weekdays[i];t?.dates&&Object.entries(t.dates).forEach(([i,n])=>{r[new Date(i).valueOf()]=n}),Object.entries(r).forEach(([i,n])=>{n instanceof Array||(r[i]=!!n)}),e={...e,dates:r}}else if(t&&!e.dates){e.dates=e.dates||{};for(let r=0;r<t.length;r++)e.dates[r]=t[r],t[r]instanceof Array||(e.dates[r]=!!t[r])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var r=0;r<arguments.length;r++)e.push(arguments[r]);var i=new uc,n;return e.forEach((function(a){n?n=this._createCalendarFromConfig(i.merge(n,a)):n=a}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new on(this.$gantt,dc(this.$gantt));t.id=String(Zi());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var i in r.customWeeks)r.customWeeks[i]=this._convertWorkTimeSettings(r.customWeeks[i]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=At(e.getConfig()):e.worktime?t=At(e.worktime):t=At(e);var r=At(this.defaults.fulltime.worktime);return ge(t,r),this._createCalendarFromConfig(t)},getCalendar:function(e){e=e||"global";var t=this._calendars[e];return t||(this.createDefaultCalendars(),t=this._calendars[e]),t},getCalendars:function(){var e=[];for(var t in this._calendars)e.push(this.getCalendar(t));return e},_getOwnCalendar:function(e){var t=this.$gantt.config;if(e[t.calendar_property])return this.getCalendar(e[t.calendar_property]);if(t.resource_calendars){var r,i,n;if(this._legacyConfig===!1?n=t.resource_property:n=xe.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=Gp.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=xe.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=xe.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(n&&e[n]&&t.resource_calendars[e[n]])var r=this.getResourceCalendar(e[n]);if(i&&(r=this.getCalendar(i)),r)return r}return null},getResourceCalendar:function(e){if(e==null)return this.getCalendar();var t=null;typeof e=="number"||typeof e=="string"?t=e:t=e.id||e.key;var r=this.$gantt.config,i=r.resource_calendars,n=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),i){if(this._legacyConfig===void 0&&(this._legacyConfig=xe.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in i)if(i[a][t]){n=i[a][t];break}}else var n=i[t];if(n)return this.getCalendar(n)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,r;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?r=t.getTask(e):r=e,!r)return this.getCalendar();var i=this._getOwnCalendar(r),n=!!t.getState().group_mode;if(!i&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(i=this._getOwnCalendar(a),i))););n&&!i&&e.$effective_calendar&&(i=this.getCalendar(e.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(e){if(!this.isCalendar(e)){var t=e.id;e=this.createCalendar(e),e.id=t}if(e._tryChangeCalendarSettings(function(){})){var r=this.$gantt.config;return e.id=e.id||Zi(),this._calendars[e.id]=e,r.worktimes||(r.worktimes={}),r.worktimes[e.id]=e.getConfig(),e.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},e]),null},deleteCalendar:function(e){var t=this.$gantt.config;return e&&this._calendars[e]?(delete this._calendars[e],t.worktimes&&t.worktimes[e]&&delete t.worktimes[e],!0):!1},restoreConfigCalendars:function(e){for(var t in e)if(!this._calendars[t]){var r=e[t],i=this.createCalendar(r);i.id=t,this.addCalendar(i)}},defaults:{global:{id:"global",worktime:{hours:[8,12,13,17],days:[0,1,1,1,1,1,0]}},fulltime:{id:"fulltime",worktime:{hours:[0,24],days:[1,1,1,1,1,1,1]}}},createDefaultCalendars:function(){var e=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(e.worktimes)},isCalendar:function(e){var t=[e.isWorkTime,e.setWorkTime,e.getWorkHours,e.unsetWorkTime,e.getClosestWorkTime,e.calculateDuration,e.hasDuration,e.calculateEndDate];return t.every(function(r){return r instanceof Function})}};function cn(e,t){this.argumentsHelper=t,this.$gantt=e}cn.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(t){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return t.date},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;return this._calculateDuration(t,r,i,n)},_calculateDuration:function(e,t,r,i){var n=this.$gantt.date,a={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},s=0;if(a[r])s=Math.round((t-e)/(i*a[r]));else{for(var o=new Date(e),c=new Date(t);o.valueOf()<c.valueOf();)s+=1,o=n.add(o,i,r);o.valueOf()!=t.valueOf()&&(s+=(c-o)/(n.add(o,i,r)-o))}return Math.round(s)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit;return i?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof cn},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;return this.$gantt.date.add(t,n*r,i)}};function pc(e){this.$gantt=e.$gantt,this.argumentsHelper=dc(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new cn(this.$gantt,this.argumentsHelper)}pc.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var r=this.calendarManager;e.task?t=r.getTaskCalendar(e.task):e.id?t=r.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=r.getTaskCalendar())}return t},getWorkHours:function(e){e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getWorkHours(e.date)},setWorkTime:function(e,t){return e=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.setWorkTime(e)},unsetWorkTime:function(e,t){return e=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.unsetWorkTime(e)},isWorkTime:function(e,t,r,i){var n=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return i=this._getCalendar(n),i.isWorkTime(n)},getClosestWorkTime:function(e){e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getClosestWorkTime(e)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.calculateDuration(e)},hasDuration:function(){var e=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.hasDuration(e)},calculateEndDate:function(t){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),r=this._getCalendar(t);return r.calculateEndDate(t)}};var Kp=function(e,t){return{getWorkHours:function(r){return t.getWorkHours(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){t.unsetWorkTime(r)},isWorkTime:function(r,i,n){return t.isWorkTime(r,i,n)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,i,n){return t.calculateDuration(r,i,n)},_hasDuration:function(r,i,n){return t.hasDuration(r,i,n)},calculateEndDate:function(r,i,n,a){return t.calculateEndDate(r,i,n,a)},mergeCalendars:ut(e.mergeCalendars,e),createCalendar:ut(e.createCalendar,e),addCalendar:ut(e.addCalendar,e),getCalendar:ut(e.getCalendar,e),getCalendars:ut(e.getCalendars,e),getResourceCalendar:ut(e.getResourceCalendar,e),getTaskCalendar:ut(e.getTaskCalendar,e),deleteCalendar:ut(e.deleteCalendar,e)}},zp={create:Kp};function hc(e){var t=new fc(e),r=new pc(t),i=zp.create(t,r);ge(e,i)}var yc={date:{month_full:["January","February","March","April","May","June","July","August","September","October","November","December"],month_short:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],day_full:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],day_short:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},labels:{}};function mc(e={}){let t=e.config||{},r={config:Object.assign({duration_unit:"hour",duration_step:1,work_time:!1,worktimes:{},work_days:null,inherit_calendar:!1,calendar_property:"calendar_id",resource_property:"resource_id",resource_calendars:{},dynamic_resource_calendars:!1,start_on_monday:!0,server_utc:!0,csp:"auto",show_errors:!1},t),locale:e.locale||yc,templates:e.templates||{},getTask:e.getTask||function(i){return null},isTaskExists:e.isTaskExists||function(i){return!1},isSummaryTask:e.isSummaryTask||function(i){return!1},getState:function(){return{group_mode:!1}},callEvent:function(i,n){let a=e.onEvent;return a&&a(i,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:sc,mixin:ge,copy:At,assert:function(i,n){if(!i){if(e.throwOnAssert)throw new Error("[calendar] "+n);e.silent!==!0&&console.error("[calendar]",n)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(i){return i},r.date=lc(r),r.date.init(),hc(r),r}function qp(e={}){let t=mc(e);return{addCalendar:function(r){return t.addCalendar(r)},deleteCalendar:function(r){return t.deleteCalendar(r)},getCalendar:function(r){return t.getCalendar(r)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(r){return t.getTaskCalendar(r)},getResourceCalendar:function(r){return t.getResourceCalendar(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){return t.unsetWorkTime(r)},isWorkTime:function(){return t.isWorkTime.apply(t,arguments)},getClosestWorkTime:function(){return t.getClosestWorkTime.apply(t,arguments)},getWorkHours:function(){return t.getWorkHours.apply(t,arguments)},calculateDuration:function(){return t.calculateDuration.apply(t,arguments)},calculateEndDate:function(){return t.calculateEndDate.apply(t,arguments)},_internals:t}}var gc={createCalendar:qp};var ZR=3600*1e3;function Ic(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Jp}=gc,Ne="__replay_default__";function Xp(e){if(!e||e.length===0||typeof e[0]=="string")return e;let t=e.map(Number);if(t.some(a=>Number.isNaN(a)))return e;let r=t[0],i=t[t.length-1];return t.every((a,s)=>a===r+s)?[`${r}:00-${i+1}:00`]:e}var vc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Cc="__main_global__",Zp={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Ac(e){return!e||e.hours===void 0||e.hours.length>0||e.days?.some(t=>Array.isArray(t)&&t.length>0)===!0?!0:Object.values(e.dates??{}).some(t=>Array.isArray(t)&&t.length>0)}function Qp(e){let t={};if(Array.isArray(e.days))for(let i=0;i<e.days.length;i+=1)t[i]=e.days[i];if(e.dates)for(let[i,n]of Object.entries(e.dates))t[i]=n;let r={hours:Xp(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function kc(e){let t=Jp({config:{work_time:!0}});t.addCalendar({id:Ne,worktime:vc}),t.addCalendar({id:Cc,worktime:Zp});let r=new Set(e.filter(d=>!Ac(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>Ac(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?Qp(d.worktime):vc});let n=ac(t),a=n.getCalendar(Ne),s=n.getCalendar(Cc);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([Ne]);for(let d of i)o.add(String(d.id));let c=new Map;return{reader:{getCalendar(d){let u=String(d),f=c.get(u);if(f)return f;let p=a;return o.has(u)?p=n.getCalendar(d)??a:r.has(u)&&(p=s),c.set(u,p),p}}}}function Sc(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let i=e.getParent(r.id);return!i||e.getIncomingLinkIds(i.id).length===0?null:i.startDate},getDescendantIds(t){return th(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],i=e.getActivity(t);for(;i;){let n=i.parentId;if(n===null)break;let a=e.getActivity(n);if(!a)break;r.push(String(n)),i=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,progress:Number(n?.progress??0),ponderator:Number(n?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,workHours:Number(n?.workHours??0),progress:Number(n?.progress??0),realWorkHours:Number(n?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,usedCost:Number(n?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,cost:Number(n?.cost??0)}})}}}function th(e,t){let r=[],i=new ft;for(let n of e.getChildren(t))i.enqueue(n);for(;!i.isEmpty();){let n=i.dequeue();r.push(n);for(let a of e.getChildren(n))i.enqueue(a)}return r}var br=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let i=this._journal;i&&(i.before.has(t)||i.before.set(t,ln(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:"insert",activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:"remove",activityId:t,before:ln(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:"link-add",linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:"link-remove",linkId:t,before:Dc(r)})}noteCorrelativeBefore(t,r){let i=this._journal;!i||i.correlativeBefore.has(t)||i.correlativeBefore.set(t,r)}noteScheduledBefore(t,r){let i=this._journal;!i||i.scheduledBefore.has(t)||i.scheduledBefore.set(t,ln(r))}noteLinkField(t,r){let i=this._journal;!i||i.linkFieldCaptured.has(t)||(i.linkFieldCaptured.add(t),i.ops.push({kind:"link-field",linkId:t,before:Dc(r)}))}};function ln(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:e.constraintDate?new Date(e.constraintDate):null,dateOrigin:e.dateOrigin?new Date(e.dateOrigin):null,newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:[...e.baselinePoints]}}function Dc(e){return{...e}}var wr=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Tc(t);return this.reader.getCalendar(r??Ne)}getClosestWorkTime(t){let r=`${un(t.task)}|${t.dir}|${t.date.getTime()}`;return dn(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:et.HOUR}))}calculateEndDate(t){let r=`${un(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return dn(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${un(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return dn(this._cache.duration,r,()=>this.resolveCalendar(t.task).calculateDuration(t.startDate,t.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function dn(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var eh="__default__";function Tc(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function un(e){return Tc(e)??eh}var Or=class{constructor(t){this.activities=t}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;markDirty(){this._dirty=!0}getChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(t))??[]}hasChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(t))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(t,r){let i=this.activities.get(t)?.parentId,n=0,a=this.activities.size;for(;i&&!O(i);){if(i===r)return!0;if(++n>a)return!1;i=this.activities.get(i)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||O(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(O(t)){this._roots.push(r);return}let i=String(t),n=this._childrenByParent.get(i);n?n.push(r):this._childrenByParent.set(i,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let r of this.activities.values()){if(O(r.parentId)){this._roots.push(r.id);continue}let i=String(r.parentId),n=this._childrenByParent.get(i)??[];n.push(r.id),this._childrenByParent.set(i,n)}let t=(r,i)=>{let n=this.activities.get(r),a=this.activities.get(i);return n&&a?ji(n,a):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var xr=class{checkedSet=new Set;hiddenSet=new Set;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[])}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet)}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden)}};var ve=class{_activities=new Map;_lastStartDate=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_cache={ids:null,visualOrderIds:null};_writeCapture=new br;_viewState=new xr;_viewStateBefore=null;_lastStartDateBefore=null;_calendar;_flags;constructor(t){for(let r of t.activities)this._activities.set(r.id,r);for(let r of t.links)this._links.set(String(r.id),r),this._indexLink(r);this._calendar=new wr(kc(t.calendars)),this._flags=ih(t),this._hierarchy=new Or(this._activities),this._hierarchy.rebuild()}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=ho(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,i]of this._activities)t(i,r)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLastStartDate(t){return this._lastStartDate.get(String(t))??null}setLastStartDate(t,r){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),r)}_captureLastStartDateOnce(){this._writeCapture.peek()!==null&&this._lastStartDateBefore===null&&(this._lastStartDateBefore=new Map(this._lastStartDate))}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}isChecked(t){return this._viewState.isChecked(String(t))}isVisible(t){return this._viewState.isVisible(String(t))}checkedIds(){return this._viewState.checkedIds()}setChecked(t,r){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),r)}setVisible(t,r){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),r)}hydrateViewState(t){this._viewState.hydrate(t)}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??_c}getIncomingLinkIds(t){return this._incoming.get(String(t))??_c}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,r){return this._hierarchy.isChildOf(t,r)}getParent(t){return this._hierarchy.getParent(t)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null}setActivityField(t,r,i){let n=this.getActivity(t);n&&(this._writeCapture.note(String(t),n),n[r]=i,r===L.PARENT&&this._hierarchy.markDirty(),fn(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,i){let n=this.getActivity(t);if(n){if(!Object.hasOwn(n,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),n),Reflect.set(n,r,nc(r,i)),r===L.PARENT&&this._hierarchy.markDirty(),fn(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let i=this.getActivity(t);if(!i)return;this._writeCapture.note(String(t),i);let n=!1;for(let a of Object.keys(r))Reflect.set(i,a,Reflect.get(r,a)),a===L.PARENT&&(n=!0),fn(a)&&(this._cache.visualOrderIds=null);n&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let r=this._links.get(String(t.id));r&&this._deindexLink(r),this._links.set(String(t.id),{...t}),this._indexLink(t)}_indexLink(t){Ec(this._outgoing,String(t.source),t.id),Ec(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Pc(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),Pc(i,t.id))}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkFieldDynamic(t,r,i){if(!rh(r))return;let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),Reflect.set(n,r,i))}setLinkProplannerId(t,r){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i.proplannerId=r)}removeLink(t){let r=this.getLink(t);r&&(this._writeCapture.noteLinkRemove(String(t),r),this._links.delete(String(t)),this._deindexLink(r))}addActivity(t){this._writeCapture.noteInsert(String(t.id)),this._activities.set(t.id,t),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(t.parentId,t.id)}removeActivity(t){let r=this.getActivity(t);r&&this._writeCapture.noteRemove(String(t),r);let i=String(t);(this._viewState.isChecked(i)||!this._viewState.isVisible(i))&&(this._captureViewStateOnce(),this._viewState.forget(i)),this._activities.delete(t),this._lastStartDate.has(String(t))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(t))),this._outgoing.delete(String(t)),this._incoming.delete(String(t)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(t,r){this._writeCapture.noteCorrelativeBefore(t,r)}noteScheduledBefore(t,r){this._writeCapture.noteScheduledBefore(t,r)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:r,before:i,correlativeBefore:n,scheduledBefore:a}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreCorrelatives(n),this._restoreActivityFields(a),this._restoreActivityFields(i),this._viewStateBefore!==null&&this._viewState.restore(this._viewStateBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreCorrelatives(t){for(let[r,i]of t){let n=this._activities.get(r);n&&(n.correlativeId=i)}}_undoLinkAdds(t){for(let r of t)r.kind==="link-add"&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind==="insert"&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind==="remove"&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind==="link-remove"&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t)r.kind==="link-field"&&this._links.has(r.linkId)&&this._links.set(r.linkId,r.before)}_restoreActivityFields(t){for(let[r,i]of t){let n=this._activities.get(r);n&&this._restoreScalarFields(n,i)}}_restoreScalarFields(t,r){for(let i of Object.keys(t))Object.hasOwn(r,i)||Reflect.deleteProperty(t,i);for(let i of Object.keys(r))Reflect.set(t,i,Reflect.get(r,i))}_attachLink(t){this._links.set(String(t.id),{...t}),this._indexLink(t)}_detachLink(t){let r=this.getLink(t);r&&(this._links.delete(String(t)),this._deindexLink(r))}},_c=[];function rh(e){return e===di.LAG||e===di.TYPE}function fn(e){return e===L.PARENT||e===L.CORRELATIVE_ID}function Pc(e,t){return e.filter(r=>String(r)!==String(t))}function Ec(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function ih(e){let t=e.runtimeFlags??{};return{isPasting:!!t.isPasting,isBulkOperation:!!t.isBulkOperation,dragWithMultiple:!!t.dragWithMultiple,draggingSingleMilestone:!!t.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!t.maxPerformance,allCheckedTaskIds:[]}}function mt(e){return structuredClone(e)}function Rc(e,t){let r=e.getActivity(t);return r?mt(r):null}function Lc(e){return e.getAllActivities().map(mt)}function bc(e){return e.getAllIds().map(String)}function wc(e,t){e.forEachActivity((r,i)=>t(i))}function Oc(e,t){let r=t==="0"?pn(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(mt(a))}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function pn(e,t){let r=t;if(r==="0"){let i=[];return e.forEachActivity((n,a)=>{O(n.parentId)&&i.push(a)}),i}return[...e.getChildren(r)].map(String)}function xc(e){return e.checkedIds().map(String)}function Nc(e,t){return e.getChildren(t).length>0}function Fc(e,t){let r=e.getLink(t);return r?Ct(r):null}function Mc(e){return e.getAllLinks().map(t=>Ct(t))}function Nr(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function nh(e){return e.reduce((t,r)=>Nr(r)<Nr(t)?r:t)}function ah(e){return e.reduce((t,r)=>Nr(r)>Nr(t)?r:t)}function sh(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Wc(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=sh(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:nh(i),endHour:ah(n)}}function Uc(e,t){return{calendars:e.calendarReader,hierarchy:Sc(e),activityReader:Ic(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function Bc(e){return Oe(e)}function hn(e,t,r,i,n){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:i,afterLinks:n}}function jc(e,t){let r=new Map,i=new Map;for(let n of t.activities){if(n.kind!=="created")continue;let a=e.getActivity(String(n.id));a&&r.set(String(n.id),K(a))}for(let n of t.links){if(n.kind!=="created")continue;let a=e.getLink(String(n.id));a&&i.set(String(n.id),{...a})}return{afterSnap:r,afterLinks:i}}function Vc(e){return e.kind!=="inline-edit"||!we.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Hc(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind==="updated"&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function Yc(e,t){if(!Hc(e)||!Hc(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function $c(e,t){let r=e.changeSet.activities[0],i=t.changeSet.activities[0];if(!r||!i)return t;let n=r.fields??{},a=i.fields??{},s={};for(let c of new Set([...Object.keys(n),...Object.keys(a)])){let l=n[c],d=a[c];s[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let o={...t.changeSet,activities:[{...i,fields:s}]};return hn(o)}function Gc(e){return e.kind==="persistence-acknowledge"?"clear-on-success":e.kind==="sir-sync"||e.kind==="activity-lookahead-sync"||e.kind==="baseline-apply"||e.kind==="ponderator-criterion-set"||e.kind==="status-criteria-set"?"skip":"record"}function yn(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&E.CUSTOM_ID in t.fields)return!0;return!1}function mn(e,t,r){let i=[],n=[];for(let s of t.changeSet.activities){let o=String(s.id);if(s.kind==="updated"){let c=e.getActivity(o);i.push({id:o,kind:"updated",after:c?K(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?K(c):null})}else i.push({id:o,kind:"deleted",after:null});else if(r==="before")i.push({id:o,kind:"deleted",after:null});else{let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?K(c):null})}}for(let s of t.changeSet.links){let o=String(s.id);if(s.kind==="updated"){let c=e.getLink(o);n.push({id:o,kind:"updated",after:c?Ct(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);n.push({id:o,kind:"created",after:c?Ct(c):null})}else n.push({id:o,kind:"deleted",after:null});else if(r==="before")n.push({id:o,kind:"deleted",after:null});else{let c=e.getLink(o);n.push({id:o,kind:"created",after:c?Ct(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?oh(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function oh(e){return{activityId:e.activityId,...e.checked?{checked:{before:e.checked.after,after:e.checked.before}}:{},...e.visible?{visible:{before:e.visible.after,after:e.visible.before}}:{}}}function gn(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Kc(e,t){qc(e,t,"before")}function zc(e,t){qc(e,t,"after")}function qc(e,t,r){let i=t.changeSet;for(let n of i.activities)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))Z(e,n.id,a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeSnap?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${n.id}`);e.addActivity(K(a))}else e.removeActivity(String(n.id));else if(r==="before")e.removeActivity(String(n.id));else{let a=t.afterSnap?.get(String(n.id));if(!a)throw new Error(`redo: missing afterSnap for re-creating activity ${n.id}`);e.addActivity(K(a))}for(let n of i.links)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))ks(e,String(n.id),a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeLinks?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeLinks for re-adding link ${n.id}`);e.addLink(a)}else e.removeLink(String(n.id));else if(r==="before")e.removeLink(String(n.id));else{let a=t.afterLinks?.get(String(n.id));if(!a)throw new Error(`redo: missing afterLinks for re-creating link ${n.id}`);e.addLink(a)}for(let n of i.viewState??[])n.checked&&e.setChecked(n.activityId,r==="before"?n.checked.before:n.checked.after),n.visible&&e.setVisible(n.activityId,r==="before"?n.visible.before:n.visible.after)}var ch=100,lh=600,Fr=class{constructor(t=ch){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;record(t,r=null,i=0){let n=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&i-this._lastTime<=lh&&n!==void 0&&Yc(n,t)?this.undoStack[this.undoStack.length-1]=$c(n,t):(this.undoStack.push(t),this.undoStack.length>this.maxDepth&&this.undoStack.shift()),this._lastKey=r,this._lastTime=i,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){return this.undoStack.pop()??null}takeRedo(){return this.redoStack.pop()??null}pushRedo(t){this.redoStack.push(t)}pushUndo(t){this.undoStack.push(t)}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}};function dh(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function uh(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Jc(e){return{id:String(e.id),worktime:uh(e.worktime)}}function Mr(e,t,r,i=[]){let n=t.map(dh),a=[...r.map(Jc),...i.map(Jc)];return{activities:[...e],links:n,calendars:a}}var Xc=["id","proplannerId","parentId","name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","assignedDefaultCalendar","dateOrigin","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","correlativeId","uniqueCorrelativeId","customId","subcontractId","isLookahead","newActivityIds","hasNewActivities","pendingRequestIds","responsableIds","tagIds"],Zc=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Qc=new Set(["newActivityIds","pendingRequestIds","responsableIds","tagIds"]);function tl(e){let t=Xc.map(r=>[r,fh(r,e[r])]);return Object.fromEntries(t)}function fh(e,t){return Zc.has(e)?t instanceof Date?new Date(t):null:Qc.has(e)?Array.isArray(t)?[...t]:[]:t}function el(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of Xc)if(!ph(r,e[r],t[r]))return!0;return!1}function ph(e,t,r){return Zc.has(e)?hh(t,r):Qc.has(e)?yh(t,r):(t??null)===(r??null)}function hh(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function yh(e,t){let r=Array.isArray(e)?[...e].map(String).sort():[],i=Array.isArray(t)?[...t].map(String).sort():[];return r.length!==i.length?!1:r.every((n,a)=>n===i[a])}var Wr=class{initialized=!1;linksAtLastSave=new Map;activitiesAtLastSave=new Map;init(t,r){this.snapshotActivities(t),this.snapshotLinks(r),this.initialized=!0}snapshotActivities(t){this.activitiesAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.activitiesAtLastSave.set(String(r.id),tl(r))}snapshotLinks(t){this.linksAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.linksAtLastSave.set(String(r.id),{lag:r.lag,type:r.type})}modifiedActivities(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;if(r.assignedDefaultCalendar)return!0;let i=this.activitiesAtLastSave.get(String(r.id));return i?el(r,i):!0}):[]}modifiedLinks(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;let i=this.linksAtLastSave.get(String(r.id));return i?r.lag!==i.lag||r.type!==i.type:!0}):[]}clear(){this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var rl=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var vn=[!1,!0,!0,!0,!0,!0,!1],il=new Set(["1","true"]),Cn="DURATION",nl="asap",al={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo","AS SOON AS POSSIBLE":"asap","AS LATE AS POSSIBLE":"alap","START NO EARLIER THAN":"snet","START NO LATER THAN":"snlt","FINISH NO EARLIER THAN":"fnet","FINISH NO LATER THAN":"fnlt","MUST START ON":"mso","MUST FINISH ON":"mfo"};function sl(e,t){let r=[],i=e.map(a=>{let s=Dh(a,t);return a.should_be_showed===!1&&r.push(s.id),s});Th(i);let n=new Set(i.map(a=>a.id));return _h(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function mh(e){return e===0}function gh(e,t){if(!e)return null;let r=al[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),nl):r}function vh(e,t){let r=gh(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?Pt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function Ch(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function Ah(e){if(e==null||e==="")return[];if(Array.isArray(e))return e.map(String);if(typeof e!="string")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(String):[]}catch{return[]}}function Ih(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function An(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Ih(r)&&t.push(String(r.id));return t}function kh(e){return e==="0"?null:String(e)}function Sh(e,t){return Array.isArray(e)?e.map(r=>Tr(r,t)).filter(r=>r!==null):[]}function Dh(e,t){let r=Ch(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:s}=vh(e,t.reporter),o=e.type==="milestone",c=Pt(e.start_date),l=o?c:Pt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:kh(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:De(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:mh(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:Pt(e.date_origin),progress:n,cost:Number(e.cost),usedCost:Number(e.used_cost??0),realCost:Number(e.real_cost??0),workHours:Number(e.hhWorkTime),realWorkHours:Number(e.real_work??0),ponderator:Number(e.ponderator??0),hasCustomPonderator:e.hasCustomPonderator,correlativeId:e.correlative_id,uniqueCorrelativeId:e.unique_correlative_id,customId:e.custom_id,subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Ah(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:An(e.pendingRequests),responsableIds:An(e.responsables),tagIds:An(e.tags),baselinePoints:Sh(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:De(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),isCritical:!!e.is_critical,freeSlackHours:e.freeSlack,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null,promotionRestore:null}}function Th(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function _h(e,t,r){for(let i of e)i.parentId!==null&&(t.has(i.parentId)||(r.warn(`[parseFromBackend] activity "${i.id}" references unknown parent "${i.parentId}" \u2014 re-parenting to root (null)`),i.parentId=null))}function dl(e,t,r,i=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>Rh(c,i)),o=(r??[]).map(c=>Lh(c,i));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:Eh(s)}}function Eh(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function ul(e,t){let r=Fh(e.working_days),{days:i,hours:n}=Nh(e,r),a=bh(t.exceptionsSource,t.exceptionRange),s={days:i,hours:n};return a&&(s.dates=a),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:s}}function Rh(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return ul(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function Lh(e,t){return ul(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function bh(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=wh(i.from_date,i.to_date,t);if(n.length===0)continue;let a=Oh(i);if(a!==void 0)for(let s of n)r[s]=a}return Object.keys(r).length>0?r:null}function wh(e,t,r){let i=ol(e),n=ol(t);if(i===null||n===null)return[];if(r&&(n<r.start||i>r.end))return[];let a=[],s=r?Math.max(i,r.start):i,o=r?Math.min(n,r.end):n;for(;s<=o;)a.push(String(s)),s+=864e5;return a}function ol(e){if(typeof e!="string")return null;let t=rl.exec(e.trim());if(!t)return null;let r=Number(t[1]),i=Number(t[2]),n=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(i)&&Number.isFinite(n)?Date.UTC(r,i-1,n):null}function Oh(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=xh(t);if(r.length>0)return r}}var cl=/^\d{1,2}:\d{2}$/;function xh(e){let t=[];for(let r of e){let i=hl(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let o=i.startsCsv.trim(),c=i.endsCsv.trim();!Ur(o)&&!Ur(c)&&cl.test(o)&&cl.test(c)&&t.push(`${o}-${c}`);continue}let s=pl(i.startsCsv,i.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(fl),t}function ll(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[i,n]=r.split(":");return(Number(i)||0)*60+(Number(n)||0)}function fl(e,t){return ll(e)-ll(t)}function Nh(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=pl(l,d);for(let f=0;f<7;f+=1){let p=u[f],v=r[f];p&&v&&v.push(p)}},n=Array.isArray(e.shifts)&&e.shifts.length>0,a=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(n)for(let l of e.shifts){let d=hl(l?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else a&&i(e.shift_start,e.shift_end);for(let l of r)l.sort(fl);let o=r.find((l,d)=>!!t[d]&&l.length>0)??[];return{days:t.map((l,d)=>{if(!l)return!1;let u=r[d];return u&&u.length>0?u:o}),hours:o}}function pl(e,t){let r=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return r;let i=e.split(",").map(o=>o.trim()),n=t.split(",").map(o=>o.trim());if(!(i.length===n.length&&i.length>0&&i.length<=7))return r;let s=[...r];for(let o=0;o<i.length;o+=1){let c=i[o],l=n[o];Ur(c)||Ur(l)||(s[o]=`${c}-${l}`)}return s}function hl(e){if(typeof e!="string")return null;let t=e.indexOf("-");return t<=0?null:{startsCsv:e.slice(0,t),endsCsv:e.slice(t+1)}}function Fh(e){if(typeof e!="string")return[...vn];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...vn]:t.map(r=>il.has(r))}var Mh=new Set(["false","null"]);function Ur(e){return!e||Mh.has(e)}function Wh(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Uh(e){if(typeof e!="string")return null;let t=Ua(e);return t||(Wh(e)?e:null)}function ml(e,t){let r=[];for(let i of e)try{r.push(Bh(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return Hh(r)}function Bh(e,t,r){let i=String(e.unique_id??e.id),n=String(e.source_id??e.source??""),a=String(e.target_id??e.target??"");if(!t.has(n))throw new Error(`[parseFromBackend] link "${i}" source "${n}" does not exist`);if(!t.has(a))throw new Error(`[parseFromBackend] link "${i}" target "${a}" does not exist`);let s=Uh(e.type);if(s===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=e.id;return{id:i,source:n,target:a,type:s,lag:pt(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function Hh(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||yl(r)>yl(n))&&t.set(i,r)}return[...t.values()]}function yl(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function jh(e){if(typeof e!="string")return Cn;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return Cn}}function Vh(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function Yh(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function gl(e){let t=Vh(e),r=Yh(e),i=e.update_duration_for_primavera_for_end_date===!0;return{id:String(e.id),name:e.name,hoursPerDay:e.hoursPerDay,hoursPerWeek:e.hoursPerWeek,dateFormat:e.dateFormat,projectId:e.projectId,companyId:e.companyId,...t!==void 0?{customIdPrefix:t}:{},...r!==void 0?{customIdIncrement:r}:{},...i?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:jh(e.activity_creter),statusCriteria:Jr}}function Br(e,t=ie){let r=gl(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:s}=dl(e.calendars,e.sector.calendars,e.baseCalendars,$h(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=sl(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=ml(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function $h(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let a of e){let s=new Date(a.start_date).getTime(),o=new Date(a.end_date).getTime();Number.isFinite(s)&&(t=Math.min(t,s)),Number.isFinite(o)&&(r=Math.max(r,o))}if(!Number.isFinite(t)||!Number.isFinite(r))return null;let i=new Date(t),n=new Date(r);return i.setFullYear(i.getFullYear()-1),n.setFullYear(n.getFullYear()+1),{start:i.getTime(),end:n.getTime()}}function vl(e={}){let t=e.seed??0,r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function Cl(e={}){let t=e.seed??Date.now(),r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function Al(e={}){let t=e.seed??0,r=i=>{Number.isFinite(i)&&i>0&&i<=9999999&&i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){if(i==null)continue;let n=typeof i=="number"?i:Number(i);r(n)}return{next(){return t+=1,String(t)},bump(i){if(i==null)return;let n=typeof i=="number"?i:Number(i);r(n)}}}function Il(e){return!!e&&typeof e=="string"&&e.trim().length>0}function Hr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function jr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function kl(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Sl(e,t){return!t&&Il(e)}function Dl(e,t){return t&&Il(e)}function Me(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function Fe(e){if(!Me(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Gh(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!Me(t))return r;let i=t.length;return r.padStart(i,"0")}function gt(e,t){let r=Fe(e),i=Fe(t),n=r+i;return Gh(n,e)}function Vr(e,t){let r=Fe(e),i=Fe(t);return r<i?-1:r>i?1:0}function Yr(e,t){return Vr(e,t)<=0?e:t}function $r(e,t){return Vr(e,t)>=0?e:t}function Tl(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Yr(t,r))}function _l(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>$r(t,r))}function Pl(e){return{prefix:e,baseSuffix:null}}function El(e,t){let r=jr(e);return{prefix:Hr(e),baseSuffix:gt(r,t)}}function Rl(e){return{prefix:e,baseSuffix:null}}function Ll(e,t){return Sl(e,t)?"parentConversion":Dl(e,t)?"pasteReference":"noContext"}function Kh(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Gr=class{prefixMap=new Map;processedIds=new Set;_journal=null;beginCustomIdTransaction(){this._journal=[]}commitCustomIdTransaction(){this._journal=null}rollbackCustomIdTransaction(){let t=this._journal;if(t!==null){for(let r of[...t].reverse()){let{prefix:i}=this.analyzeCustomId(r.customId);r.prefixBefore===null?this.prefixMap.delete(i):this.prefixMap.set(i,r.prefixBefore),r.hadId?this.processedIds.add(r.customId):this.processedIds.delete(r.customId)}this._journal=null}}_noteCustomIdBefore(t){if(this._journal===null)return;let{prefix:r}=this.analyzeCustomId(t),i=this.prefixMap.get(r);this._journal.push({customId:t,prefixBefore:i?Kh(i):null,hadId:this.processedIds.has(t)})}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return Hr(t)}extractSuffix(t){return jr(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let i=this.prefixMap.get(t);i.usedSuffixes.has(r)||(i.usedSuffixes.add(r),i.min=Yr(r,i.min),i.max=$r(r,i.max),i.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let i=this.getNextAvailableSuffix(t);r.next=i??this.suffixIncrement}getPrefixStats(t){let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!r&&!i)return{prefix:r,suffix:i};if(this._noteCustomIdBefore(t),this.prefixMap.has(r)){let n=this.prefixMap.get(r);n.usedSuffixes.has(i)||(n.usedSuffixes.add(i),n.min=Yr(i,n.min),n.max=$r(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:gt(i,this.suffixIncrement),quantity:1,usedSuffixes:new Set([i])});return this.processedIds.add(t),{prefix:r,suffix:i}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:i};this._noteCustomIdBefore(t);let n=this.prefixMap.get(r);if(n.usedSuffixes.has(i)){let a=n.quantity-1;if(a===0)this.prefixMap.delete(r);else{let s=new Set(n.usedSuffixes);s.delete(i);let o=Array.from(s);o.length===0?this.prefixMap.delete(r):(n.usedSuffixes=s,n.min=Tl(o),n.max=_l(o),n.quantity=a,this._recalculateNext(r))}}return this.processedIds.delete(t),{prefix:r,suffix:i}}trackCustomIdChange(t,r){let i=this.releaseCustomId(t),n=this.registerCustomId(r);return{oldPrefix:i.prefix,oldSuffix:i.suffix,newPrefix:n.prefix,newSuffix:n.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(!this.prefixMap.has(t))return!1;let r=this.prefixMap.get(t);return`${t}${gt(r.max,this.suffixIncrement)}`.length>20}_findFirstAvailableGap(t){if(!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),i=this.suffixIncrement;for(;Vr(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=gt(i,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let r=this._findFirstAvailableGap(this.defaultPrefix);if(r!==null)return`${this.defaultPrefix}${r}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,r=null){if(!this.prefixMap.has(t)){let o=r&&Me(r)?r:this.suffixIncrement;return`${t}${o}`.length>20?null:o}let i=this.prefixMap.get(t),n=this.suffixIncrement;if(!r||!Me(r)){let o=gt(i.max,n);return`${t}${o}`.length>20?null:o}let a=r;for(let o=0;o<100;o++){if(`${t}${a}`.length>20)return null;if(!i.usedSuffixes.has(a))return a;a=gt(a,n)}let s=gt(i.max,n);return`${t}${s}`.length>20?null:s}generateNextCustomId(t){let r=this.getNextAvailableSuffix(t);if(r===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),a=0;for(;n.usedSuffixes.has(r)&&a<1e4;){let s=this.getNextAvailableSuffix(t,gt(r,this.suffixIncrement));if(s===null)return this._generateDefaultCustomId();r=s,a++}}let i=`${t}${r}`;return this._exceedsMaxLength(i)&&(i=this._generateDefaultCustomId()),i}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(i=>i&&typeof i.customId=="string"&&i.customId).map(i=>i.customId))];for(let i of r){if(this.processedIds.has(i))continue;let{prefix:n,suffix:a}=this.analyzeCustomId(i);(n||a)&&(this._updatePrefixStats(n,a),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:i=!1}=t,n=kl(r),a=Ll(n,i),{prefix:s,baseSuffix:o}=this._applyGenerationStrategy(a,n),c=null;if(a==="parentConversion"&&this.prefixMap.has(s)){let f=this.prefixMap.get(s).max;c=gt(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(n);let l=a==="parentConversion"&&c?c:o,d=this.getNextAvailableSuffix(s,l);if(d===null){let f=this._generateDefaultCustomId();return this.registerCustomId(f),f}let u=`${s}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,r){switch(t){case"parentConversion":return Pl(this.defaultPrefix);case"pasteReference":return El(r,this.suffixIncrement);default:return Rl(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let n=this.extractPrefix(i),a=this.extractSuffix(i),s=gt(a,this.suffixIncrement),o=this.getNextAvailableSuffix(n,s);if(o===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${n}${o}`;return this._exceedsMaxLength(c)&&(c=this._generateDefaultCustomId()),this.registerCustomId(c),c}}let r=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(r),r}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,r=null){if(!t||typeof t!="string"||!t.trim())return!1;let i=t.trim();return r&&i===r.trim()?!1:this.processedIds.has(i)}};function bl(e){let t=[];e.forEachActivity((r,i)=>{r.type==="project"&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,L.TYPE,re),zh(e,r)}function zh(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let i=new Date(r.startDate);i.setUTCHours(0,0,0,0);let n=e.getClosestWorkTime({date:i,dir:X.FUTURE,task:r});if(n.getTime()===r.startDate.getTime())return;let a=e.calculateEndDate({startDate:n,durationHours:r.durationHours,task:r});e.setActivityField(t,L.START_DATE,n),e.setActivityField(t,L.END_DATE,a)}function Kr(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(n);if(!a)return 0;let s=[...e.getChildren(n)],o=s.length===0?lt(a.workHours,a.progress):s.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,L.REAL_WORK_HOURS,o),r.push(n),o};for(let n of t)i(n);return r}async function wl(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(ot(t),r.updateDurationForPrimaveraEndDate&&Jh(t),Xh(t),Kr(t),n){a&&(Et(t,a),vt(t,r.statusCriteria));return}let s=await i.schedule({});ke(t,s),Zh(t),qh(t),await Se(t,void 0,!1),a&&(Et(t,a),vt(t,r.statusCriteria))}function qh(e){e.forEachActivity(t=>{t.autoScheduling||!t.startDate||t.durationHours==null||e.getChildren(t.id).length>0||(t.endDate=e.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:t}))})}function Jh(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Xh(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type==="milestone"&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=Tt(t.constraintDate,n,r))})}function Zh(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=Tt(t.constraintDate,i,r))})}var kt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Ol(e){let t=e.clock??null,r=t?Te(t()):null,i=e.reporter??ie,n=Br({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),a=n.sector;a.statusCriteria=He(e.statusCriteria);let s=n.calendars,o=n.baseCalendars??[],c=Mr(n.activities,n.links,n.calendars,o),l=new ve(c);l.hydrateViewState({hiddenIds:n.viewStateSeed.hiddenIds});let d=new er(l,i);bl(l);let u=vl({knownIds:n.activities.map(C=>C.id)}),f=Cl({knownIds:n.links.map(C=>C.id)}),p=Al({knownIds:n.activities.map(C=>C.uniqueCorrelativeId)}),v=new Gr({defaultPrefix:a.customIdPrefix,suffixIncrement:a.customIdIncrement});if(v.populateFromActivities(n.activities),e.baselinePoints&&e.baselinePoints.length>0){let C=o.find(D=>D.baseDefault)?.id??null;_r(l,e.baselinePoints,r,i,C)}let S=wl({state:l,sector:a,scheduler:d,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??void 0});return{sector:a,state:l,scheduler:d,activityIdGen:u,linkIdGen:f,uidGen:p,customIdTracker:v,calendars:s,baseCalendars:o,clock:t,reporter:i,initPromise:S}}var zr=class{_status=kt.READY;coreRuntime;_undo=new Fr;_opQueue=Promise.resolve();_scheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=Ol(t);this.coreRuntime={state:r.state,scheduler:r.scheduler,sector:r.sector,activityIdGenerator:r.activityIdGen,linkIdGenerator:r.linkIdGen,uniqueCorrelativeIdGenerator:r.uidGen,customIdTracker:r.customIdTracker,clock:r.clock,calendars:new Map(r.calendars.map(n=>[n.id,n])),baseCalendars:r.baseCalendars,reporter:r.reporter},this._initPromise=r.initPromise.then(()=>{this._status!==kt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._enqueue(async()=>{let n=await this._runCriticalPathAndCapture();return this._criticalPathRevision=this._scheduleRevision,n}));let i=t.criticalPathOnLoad===!0;this._ready=i?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return mt(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),Rc(this.coreRuntime.state,t)}getAllActivitiesView(){return this.assertReady(),Lc(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),Oc(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Fc(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),Mc(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?mt(i[r]):null}getAllIds(){return this.assertReady(),bc(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),wc(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),pn(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),xc(this.coreRuntime.state)}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),Nc(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?mt(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>mt(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>mt(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),Wc(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(this.getAllLinksView())}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(this.coreRuntime.state.getAllActivities()).map(mt)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}async dispatch(t,r={}){return this._enqueue(()=>this._dispatchInner(t,r))}async _dispatchInner(t,r={}){this.assertReady();let i=Uc(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),n=Gc(t);this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let a;try{a=await ic(t,r,{adapter:this.coreRuntime.state,ctx:i,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(s=>s.baseDefault)?.id??null,now:this.coreRuntime.clock?Te(this.coreRuntime.clock()):null}),a.ok||this._rollback()}catch(s){throw this._rollback(),s}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(a.ok&&n==="record"&&gn(a.changes)){let s=jc(this.coreRuntime.state,a.changes);this._undo.record(hn(a.changes,a.__beforeSnap,a.__beforeLinks,s.afterSnap,s.afterLinks),Vc(t),Date.now())}return a.ok&&n==="clear-on-success"&&(this._saveTracker.snapshotActivities(this.coreRuntime.state.getAllActivities()),this._saveTracker.snapshotLinks(this.getAllLinksView()),this._undo.clear()),a.ok?(no(t)&&gn(a.changes)&&this._recordScheduleMutation(r.skipCriticalPath!==!0),mt(a)):a}recomputeCriticalPath(){return this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:t})=>t)}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_recordScheduleMutation(t){this._scheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),t&&(this._criticalPathRevision=this._scheduleRevision)}_startCriticalPathForCurrentRevision(){if(this._status===kt.DESTROYED)return Promise.resolve(null);let t=this._scheduleRevision;if(this._criticalPathRevision===t)return Promise.resolve(null);if(this._activeCriticalPath?.revision===t)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let r={cancelled:!1},i=new ve(Mr(this.coreRuntime.state.getAllActivities().map(o=>K(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==kt.DESTROYED&&this._scheduleRevision===t,a=(async()=>{let o=await Oi(i,this.coreRuntime.sector.hoursPerDay,n);if(!n())return null;let c=o??new Map;return this._enqueue(async()=>{if(!n())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let l;try{for(let[d,u]of c)this.coreRuntime.state.setActivityFields(d,u);l=H(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=t}catch(d){throw this._rollback(),d}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:l}})})();this._activeCriticalPath={revision:t,cancellation:r,promise:a};let s=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(s,s),a}async _runCriticalPathAndCapture(){if(this._status===kt.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await mr(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=H(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:t}}_recomputeAfterHistoryRestore(){let t=this.coreRuntime.state;if(Er(t),Kr(t),jt(t),this.coreRuntime.clock){let r=Te(this.coreRuntime.clock());Et(t,r);let i=!1;t.forEachActivity(n=>{i||=at(n)!==null}),i&&Bt(t,r,this.coreRuntime.baseCalendars.find(n=>n.baseDefault)?.id??null),vt(t,this.coreRuntime.sector.statusCriteria)}}undo(){let t=this._enqueue(async()=>{this.assertReady();let r=this._undo.takeUndo();return r?(Kc(this.coreRuntime.state,r),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),yn(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(r),this._undo.resetCoalesce(),mn(this.coreRuntime.state,r,"before")):null});return t.then(r=>{r&&this.recomputeCriticalPath().catch(i=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",i)})},()=>{}),t}redo(){let t=this._enqueue(async()=>{this.assertReady();let r=this._undo.takeRedo();return r?(zc(this.coreRuntime.state,r),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),yn(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce(),mn(this.coreRuntime.state,r,"after")):null});return t.then(r=>{r&&this.recomputeCriticalPath().catch(i=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",i)})},()=>{}),t}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}clearHistory(){this._undo.clear()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=kt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Wr;assertReady(){if(this._status===kt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===kt.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction()}catch(t){throw this._status=kt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",t),t}}};function xl(e,t){let r=new Map(e.map(i=>[String(i.id),i]));return t.filter(i=>{let n=r.get(String(i.id));return n?n.lag!==i.lag||n.type!==i.type:!1})}var Nl=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Fl={asap:"AS SOON AS POSSIBLE",alap:"AS LATE AS POSSIBLE",snet:"START NO EARLIER THAN",snlt:"START NO LATER THAN",fnet:"FINISH NO EARLIER THAN",fnlt:"FINISH NO LATER THAN",mso:"MUST START ON",mfo:"MUST FINISH ON"};var Ml=8;var z={PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",BASELINE_APPLY:"baseline-apply",PONDERATOR_CRITERION_SET:"ponderator-criterion-set",STATUS_CRITERIA_SET:"status-criteria-set",INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_PASTE:"activity-paste",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},Qh={[z.PERSISTENCE_ACKNOWLEDGE]:!0,[z.BASELINE_APPLY]:!0,[z.PONDERATOR_CRITERION_SET]:!0,[z.STATUS_CRITERIA_SET]:!0,[z.INLINE_EDIT]:!0,[z.DATES_BATCH]:!0,[z.BULK_EDIT]:!0,[z.LINK_CREATE]:!0,[z.LINK_UPDATE]:!0,[z.LINK_DELETE]:!0,[z.LINKS_BATCH]:!0,[z.ACTIVITY_CREATE]:!0,[z.ACTIVITY_DELETE]:!0,[z.ACTIVITY_MOVE]:!0,[z.ACTIVITY_INDENT]:!0,[z.ACTIVITY_OUTDENT]:!0,[z.ACTIVITY_SET_PROGRESS]:!0,[z.ACTIVITY_PASTE]:!0,[z.SELECTION_TOGGLE]:!0,[z.SELECTION_REPLACE]:!0,[z.VISIBILITY_SET]:!0,[z.SIR_SYNC]:!0,[z.ACTIVITY_LOOKAHEAD_SYNC]:!0},Wl=Object.keys(Qh);var Ul={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return $l(ty);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map