@outbuild-company/schedule-core 1.1.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/schedule-core.global.js +1 -1
- package/dist/cdn/schedule-core.global.js.map +1 -1
- package/dist/index.cjs +1942 -1579
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +75 -214
- package/dist/index.d.ts +75 -214
- package/dist/index.js +1943 -1577
- package/dist/index.js.map +1 -1
- package/package.json +2 -3
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ScheduleCore=(()=>{var qr=Object.defineProperty;var Vl=Object.getOwnPropertyDescriptor;var Yl=Object.getOwnPropertyNames;var $l=Object.prototype.hasOwnProperty;var Gl=(e,t)=>{for(var r in t)qr(e,r,{get:t[r],enumerable:!0})},Kl=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Yl(t))!$l.call(e,n)&&n!==r&&qr(e,n,{get:()=>t[n],enumerable:!(i=Vl(t,n))||i.enumerable});return e};var zl=e=>Kl(qr({},"__esModule",{value:!0}),e);var zh={};Gl(zh,{ACTIVITY_TYPE:()=>Ue,CALENDAR_UNIT:()=>et,COLUMN:()=>E,CONSTRAINT_TYPE:()=>$,CONSTRAINT_TYPE_TO_LABEL:()=>Ul,CREATION_KIND:()=>jl,DEFAULT_HOURS_PER_DAY:()=>Bl,DISPATCH_ACTION_KIND:()=>X,DISPATCH_ACTION_KINDS:()=>Hl,DISPATCH_TRACK_EVENT:()=>yt,LINK_CODE_TO_TYPE:()=>Ht,LINK_TYPE:()=>V,LINK_TYPE_CODE:()=>Ma,NEW_ACTIVITY_DEFAULTS:()=>Ir,REJECTION_REASON:()=>R,ROOT_PARENT_ID:()=>j,ScheduleCore:()=>zr,WORK_TIME_DIRECTION:()=>q,applyBaselinePoints:()=>xr,checkNoUpdatedLinks:()=>Ml,computeExpectedProgress:()=>gi,expectedProgressFromBaseline:()=>ce,getActiveBaseline:()=>pt,getUnsavedActivities:()=>Wl,isRootParent:()=>O,normalizeParentKey:()=>Bt,parseFromBackend:()=>Hr,recomputeAllPonderators:()=>br,recomputeAllProgressRollup:()=>wr,willRunCriticalPath:()=>Vc,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 Ne=e=>String(e);function In(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:a,exists:s,autoCheckParents:o}=e,c=Ne(t),l=new Set([...i].map(String)),d=new Set(l),u=ql(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||Jl({id:c,isChecked:r,autoCheckParents:o,hierarchy:n,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:Xl(l,d),parentBlocked:p}}function ql(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=Ne(s);n.has(o)||(n.add(o),r.push(o),i.enqueue(o))}}return r}function Jl(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=Ne(c);if(a(l))return;let d=n.getChildrenIds(l).map(Ne).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 Xl(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 kn=(e,t)=>{let r=e.getActivity(t);return r!=null&&Jt(r)},Sn=(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 Dn(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=>kn(r,o),s=In({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:Sn(e,r,s.changed)}}function Tn(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!kn(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:Sn(e,r,a)}}function _n(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 Pn="text";var En="description";var Rn="duration";var Ln="progress";var bn="cost";var wn="used_cost";var On="hhWorkTime";var xn="start_date";var Nn="end_date";var Fn="constraint_type";var Mn="constraint_date";var Wn="calendar_id";var Un="custom_id";var Bn="subcontractId";var Hn="responsables";var jn="tags";var Vn="custom_predecessors";var Yn="custom_sucessors";var $n="real_work";var Gn="real_cost";var Kn="expected_progress";var zn="expected_progress_base";var qn="start_base";var Jn="end_base";var Xn="duration_base";var Zn="cost_base";var Qn="work_base";var ta="calendarDuration";var ea="is_critical",ra="earlyStart",ia="earlyFinish",na="lateStart",aa="lateFinish",sa="freeSlack",oa="totalSlack";var ca="correlative_id";var la="unique_correlative_id";var da="ponderator";var q={FUTURE:"future",PAST:"past"},et={HOUR:"hour",DAY:"day"},Pt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var Fe="status";var Jr="Baseline";function Me(e){return e==="Actual"?"Actual":Jr}var Zl={TEXT:Pn,DESCRIPTION:En,DURATION:Rn,PROGRESS:Ln,COST:bn,USED_COST:wn,HH_WORK_TIME:On,START_DATE:xn,END_DATE:Nn,CONSTRAINT_TYPE:Fn,CONSTRAINT_DATE:Mn,CALENDAR_ID:Wn,CUSTOM_ID:Un,SUBCONTRACT_ID:Bn,RESPONSABLES:Hn,TAGS:jn,CUSTOM_PREDECESSORS:Vn,CUSTOM_SUCESSORS:Yn},Ql={REAL_WORK:$n,REAL_COST:Gn,EXPECTED_PROGRESS:Kn,EXPECTED_PROGRESS_BASE:zn,START_BASE:qn,END_BASE:Jn,DURATION_BASE:Xn,COST_BASE:Zn,WORK_BASE:Qn,CALENDAR_DURATION:ta,IS_CRITICAL:ea,EARLY_START:ra,EARLY_FINISH:ia,LATE_START:na,LATE_FINISH:aa,FREE_SLACK:sa,TOTAL_SLACK:oa,CORRELATIVE_ID:ca,UNIQUE_CORRELATIVE_ID:la,PONDERATOR:da,STATUS:Fe},E={...Zl,...Ql};function ua(e,t){throw new Error(t)}function fa(e,t){return()=>t()===e}var $={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},td={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 ha(e,t,r){if(!t)return{violated:!1};let i=td[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var ed=new Set(["mso","snet","snlt"]);function ye(e,t,r){return ed.has(e)?t:r}function ya(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var rd={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}},We=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),pa=(e,t)=>new Date(e.getTime()+t*864e5),id=(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=rd[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:We(i),dir:q.FUTURE,task:e});if(id(n,i))return i.getTime()!==We(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:pa(We(i),1),dir:q.PAST,task:e});let a=We(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:q.FUTURE,task:e}):t.getClosestWorkTime({date:pa(a,1),dir:q.PAST,task:e})}function ma(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 ga(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 V={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var Ue={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},va={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Be=typeof window>"u",Qr=!Be&&typeof MessageChannel<"u"?new MessageChannel:null;function rt(){return Be||!Qr?Promise.resolve():new Promise(e=>{Qr.port1.onmessage=()=>e(),Qr.port2.postMessage(null)})}async function He(e,t){return performance.now()-e<va.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 Be||await rt(),e()?{aborted:!1}:{aborted:!0}}function je(e,t){let{inDegree:r,successors:i}=nd(e,t),n=ad(r),a=sd(n,r,i),s=a.length<e.length,o=s?od(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function nd(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 ad(e){let t=new ut;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function sd(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 od(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var Ve=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=je(t,r),this.cached)}};function Ca(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 It(e,t){return t||ei(e)&&ti[e].alwaysSummary}function me(e){return e==="milestone"}function Et(e){return ei(e)&&ti[e].promotesToProjectOnFirstChild}var ri="project",Zt="task";function ge(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function Aa(e,t){let r=t.getActivity(e);return r?It(r.type,t.getChildren(e).length>0):!1}function Ia(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 ka(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 cd(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 ld(e,t,r){if(e.length<=1)return e;let i=new Set(e.map(String)),n=[];for(let a of e)dd(a,i,t,r)||n.push(a);return n.length>0?n:e}function dd(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(ud(o))continue;let c=fd(o,n);if(!t.has(String(c)))continue;let l=r.getActivity(c);if(l&&l.autoScheduling!==!1&&pd(o,e,a,c,l))return!0}return!1}function ud(e){return e.source===e.target}function fd(e,t){return String(e.source)===t?e.target:e.source}function pd(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 Ta(e,t){let r=[],i=cd(e),n=0;for(let a of e){let s=Aa(a.source,t),o=Aa(a.target,t);if(s&&o||o&&Ia(a.source,a.target,t)||s&&Ia(a.target,a.source,t))continue;if(!s&&!o){r.push(a);continue}let c=s?ka(a.source,t):[a.source],l=o?ka(a.target,t):[a.target];if(s&&(c=Da(c,!1,t)),o){let d=ld(l,t,i);if(a.type===V.FINISH_TO_FINISH||a.type===V.START_TO_FINISH){n=hd(r,c,d,a,a.target,t,n);continue}l=Da(d,!0,t)}n=yd(r,c,l,a,n)}return r}function hd(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),C=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+C}),f+=1}return f}function Da(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 yd(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 Ye=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 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 _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===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 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===$.ASAP||a===$.ALAP)continue;let s=ma(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 $e(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):ga(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 $.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 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 He(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===Ue.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===$.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}));$e(p,m,r),a.set(u,m)}}return a}function Cd(e,t){return It(e.type,t.getChildren(e.id).length>0)}var j="0";function O(e){return e==null||e===0||e==="0"}function Bt(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===$.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 He(S,a);if(D.aborted)return s;S=D.newSliceStart;let m=i.getActivity(C);if(!m||m.constraintType!==$.ALAP||!m.autoScheduling||m.progress===100||It(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 z=i.getActivity(M.target);if(!z||z.autoScheduling===!1)continue;let ot=f(M.target),xe={...z,startDate:ot.startDate,endDate:ot.endDate},Ut=Ra(xe,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(C).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(C))??[]).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(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,$e(m,x,i),s.set(C,x)}return s}var Qt={warn(){},error(){}};function ve(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 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 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 Ge=null;function Dd(){return Ge===null&&(Ge=Date.now()),Ge+=1,String(Ge)}var Ma={[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},Wa="fs";function Ua(e){if(e in Ht)return Ht[e]}var Ba=";",Ha=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Ke(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?Ht[n]:Ht[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 Je(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 ft(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:q.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 Xe=class{adapter;reporter;currentCalculationId=0;topoCache=new Ve;expandedLinksCache=new Ye;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=fa(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Rd(this.adapter);let a=Lt("schedule.total"),s=Lt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);kt(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 _=_a(t.triggerId,l);f=_.links,p=Array.from(_.activityIds),v=new Set(p)}kt(d);let S=Lt("schedule.topologicalSort"),C=Ld(this.topoCache,u,l,v);if(kt(S),C.hasCycles)return kt(a),{...n,cycles:[C.cycleNodes]};if((await Xt(i)).aborted)return{...n,cancelled:!0};let D=Lt("schedule.processConstraints"),m=new Map;if(La(C.ordered,this.adapter,m),kt(D),(await Xt(i)).aborted)return{...n,cancelled:!0};let T=Lt("schedule.asapPass"),k=await xa(C.ordered,f,this.adapter,t,i,m);if(kt(T),(await Xt(i)).aborted)return{...n,cancelled:!0};let y=Lt("schedule.alapPass"),g=await Na(C.reversed,f,k,this.adapter,t,i);if(kt(y),(await Xt(i)).aborted)return{...n,cancelled:!0};let A=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 kt(A),kt(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 Lt(e){return{name:e,startedAt:performance.now()}}function Rd(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function kt(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 je(s,r)}if(!i)return n;let a=Ca(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&&Rt({kind:"update",linkId:a.id,lag:l},{port:t})}}function Ya(e,t){let r=t.getActivity(e);r&&me(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 Ze(e){return Number(e.toFixed(2))}function ct(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function Ce(e,t,r=!0,i={}){let n=t?$a(e,t):Nd(e);await bd(n,e,r,{recomputeRealWork:i.recomputeRealWork??!1})}function si(e,t,r=!0){let i=$a(e,t);for(let n of i)oi(n,e,r)}function Qe(e,t){oi(e,t,!1)}async function bd(e,t,r=!0,i={recomputeRealWork:!1}){let a=0;for(let s of e)oi(s,t,r,i.recomputeRealWork),a+=1,a%200===0&&await rt()}function $a(e,t){let r=new Set;for(let a of t)wd(a,e,r);if(r.size===0)return[];let i=Array.from(r),n=Ga(i,e);return Ka(i,n)}function wd(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 Od(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+=xd(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 oi(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=Od(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",Ze(f)),i&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function xd(e,t){return t?Number(e.realWorkHours)||0:ct(e.workHours,e.progress)}function Nd(e){let t=Fd(e),r=Ga(t,e);return Ka(t,r)}function Fd(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,Md(i,t));return r}function Md(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:Ud("updateTaskTiming"),adjustLinkLagOnTaskMove:Va,recordLastStartDate:Wd};function Wd(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 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 Ud(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 K(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 Ct(e){return e.constraintType??$.ASAP}var tr=100;function ee(e){return e.progress>=tr}function tt(e,t){return It(e.type,t.hasChildren(e.id))}function Xa(e){return e.progress>0}function Za(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 Ie(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 Bd(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 ci(e,t){return e.getClosestWorkTime({direction:q.FUTURE,date:t,unit:et.HOUR})}function li(e,t){let r=Bd(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 er=new Set(["snet","snlt","mso"]),di=new Set(["fnet","fnlt","mfo"]),wt=new Set(["asap","alap"]),rr="snet";function St(e,t,r){if(!er.has(r)&&!di.has(r))return e;let i=er.has(r)?ci(t,e):li(t,e),n=new Date(e);return n.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),n}var Dt=()=>({constraintType:rr});var Ot=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 ie(e,t,r){return ha(e,t,r)}function ne(e,t,r){return ya(e,t,r)}var is={targetField:"durationHours",canEdit(e,t){return ee(e)?K("completed","cant_edit_completed_activity"):tt(e,t)?K("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 rs(r)?Q(es.NEGATIVE_DURATION):Hd(t,r)?Q("unchanged"):W()},transform(e,t,r){if(rs(t))return F({},{autoSchedule:!1,postProcessors:[]});let i=jd(e,t,r),n=Vd(e,t,r,i.violated);return{...F(n,{autoSchedule:e.constraintType!=="alap",postProcessors:[ts.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:ne(i.constraintType,i.constraintDate,ns(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function rs(e){return Math.sign(e)===-1}function Hd(e,t){return e===t}function jd(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 Vd(e,t,r,i=!1){let n={};i&&Object.assign(n,Dt(),Ot(e.startDate));let a=ge(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let s=ns(e,t,r);return s&&Object.assign(n,re(s)),n}function ns(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var ae=e=>({realWorkHours:e});var Yd=0,$d=tr,as=0,ss={targetField:"progress",canEdit(e,t){return Za(e)?K("has_lookahead_tasks","cant_edit_actvity_with_task"):tt(e,t)?K("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 Gd(r)?Q("out_of_range"):W()},transform(e,t,r){let i=Kd(t),n=zd(t),a=Xd(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...ae(a.get(e.id)??0)},o=n?qd(e,t,i,r.hierarchy,a):[],c=n?Zd(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=n?tu(e,t):void 0;return F(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function Gd(e){return e<Yd||e>$d}function Kd(e){return e===as}function zd(e){return e===tr||e===as}function qd(e,t,r,i,n){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:Jd(t,r,n.get(s)??0)}))}function Jd(e,t,r){return{progress:e,autoScheduling:t,...ae(r)}}function Xd(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 Zd(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=Qd(s,i,r);i.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function Qd(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 tu(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)?K("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=eu(e,t,r.hierarchy);return F({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_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.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)?K("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=ru(e,t,r.hierarchy);return F({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_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.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)?K("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()===""?[]:iu(e,t,n,r.hierarchy);return F({workHours:t,...ae(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function ds(e,t){return ct(e,t)}function iu(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,...ae(l)}})}return s}function ir(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function ui(e,t){return e.getTime()<t.getTime()}function se(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var nr=e=>({durationHours:e});var us={targetField:"startDate",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):Xa(e)?K("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(ir(t,r))return Q("unchanged");let n=nu(e,r,i);return n||W()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return F({startDate:t,...Dt(),...Ot(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let n=ci(i,t),a=e.type==="milestone",s=a?n:i.calculateEndDate(n,e.durationHours),o=n;return{...F({startDate:n,...re(s),...a?nr(0):{},...Dt(),...Ot(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:au(e,n,i)}},trackEvent:"activity_start_date_entry"};function nu(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 au(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=ye(Ct(e),t,i),a=ie(Ct(e),e.constraintDate,n);if(a.violated)return ne(a.constraintType,a.constraintDate,n)}var su=99.999,fs={targetField:"endDate",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):ou(e)?K("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(li(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(ir(e.endDate,r))return Q("unchanged");if(cu(r,e))return Q("before_date_origin");if(lu(r,e))return Q("before_start_date");let n=du(r,e,i);return n||W()},transform(e,t,r){let i=uu(e,t),n=fu(e,t,r,!!i);return{...F(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function ou(e){return e.progress>=su}function cu(e,t){return t.dateOrigin?ui(e,t.dateOrigin):!1}function lu(e,t){return ui(e,t.startDate)}function du(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,et.DAY)?null:Q("not_working_day"):null}function uu(e,t){let r=ye(Ct(e),e.startDate,t),i=ie(Ct(e),e.constraintDate,r);if(i.violated)return ne(i.constraintType,i.constraintDate,r)}function fu(e,t,r,i=!1){let n={},a=me(e.type);a&&!i?Object.assign(n,Ot(e.startDate)):(i||pu(e))&&Object.assign(n,Dt(),Ot(e.startDate));let s=hu(e,t,r);if(!a){let o=ge(e.durationHours,s);o&&(n.type=o)}return Object.assign(n,nr(s)),n.endDate=t,n}function pu(e){return wt.has(Ct(e))}function hu(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var yu=new Set(Object.values($)),ps={targetField:"constraintType",canEdit(e,t){return ee(e)?K("completed","cant_edit_completed_activity"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){let t=String(e).toLowerCase();return mu(t)?w(t):N("invalid_constraint_type")},validate(){return W()},transform(e,t,r){let i=gu(e,t,r);return F(i,{autoSchedule:!0})}};function mu(e){return yu.has(e)}function gu(e,t,r){let i=Cu(e,t);return{constraintType:t,...Qa(vu(e,t,i,r))}}function vu(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?St(r,n,t):r}function Cu(e,t){return wt.has(t)?null:er.has(t)?e.startDate:di.has(t)?e.endDate:e.constraintDate}var hs={targetField:"constraintDate",canEdit(e,t){return ee(e)?K("completed","cant_edit_completed_activity"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){return se(e)?w(e):N("invalid_date")},validate(){return W()},transform(e,t,r){let i=ys(e)?rr:Ct(e),n=r.calendars.getCalendar(e.calendarId),a=n?St(t,n,i):t,s=Au(e,a);return F(s,{autoSchedule:!0})}};function Au(e,t){return{constraintDate:t,...ys(e)?Dt():{}}}function ys(e){return wt.has(Ct(e))||!e.constraintType}var ms={targetField:"calendarId",canEdit(){return U()},parseInput(e){let t=String(e).trim();return Iu(t)?N("empty_calendar"):w(t)},validate(e,t,r){return ku(e.calendarId,r)?Q("unchanged"):W()},transform(e,t,r){return F(Su(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function Iu(e){return e===""}function ku(e,t){return e===t}function Su(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,s=a?Du(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 Du(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 ke(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 ar(e){return e.some(t=>ke(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 ar(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(ke).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 ar(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(ke).filter(i=>i!==null);return F({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Tu=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 xt(e){return Tu.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"},fi={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 _u=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],Is=new Set(_u);function Z(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function ks(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,H(n))}return r}function H(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){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=pi(s,a);s?i.push({id:n,kind:"updated",fields:o,after:H(a)}):i.push({id:n,kind:"created",fields:o,after:H(a)})}return i}function pi(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 sr(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 or(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=H(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 Pu=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Tt(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(Pu);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 Eu=e=>e.type==="project",Ru=(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:Tt(String(s));return ce(a(e.startDate),a(e.endDate),t,n)};function Ps(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(!Eu(o)){let d=Ru(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 Es=e=>Math.round(e*100)/100;function Lu(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function bu(e,t){let r=Es(e),i=Es(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=bu(a,Lu(i,t));i.status!==s&&(Z(e,n,Fe,s),r.push(n))}),r}var hi=Number.MAX_SAFE_INTEGER;function $t(e,t){let r=mi(e,t);return r.sort(wu),r.map(i=>String(i.id))}function Ls(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 bs(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=ws(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&&!Ou(t,c))return c}return null}function yi(e,t){let r=t.getActivity(e);if(!r)return-1;let i=ws(r);return $t(i,t).findIndex(a=>String(a)===String(e))}function mi(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 wu(e,t){let r=Rs(e),i=Rs(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Rs(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:hi}function ws(e){let t=e.parentId;return t===null?"0":t}function Ou(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(Ns);let r=[];Os(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),xu(a,n)}n+=1;let s=mi(String(a.id),e);s.sort(Ns),Os(r,s)}return i}function Os(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function xs(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:hi}var Ns=(e,t)=>xs(e)-xs(t);function xu(e,t){e.correlativeId=t}function Fs(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 Ms(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(at(t),r.updateDurationForPrimaveraEndDate&&Fu(t),Mu(t),Fs(t),n){a&&(cr(t,a),Yt(t,r.statusCriteria));return}let s=await i.schedule({});ve(t,s),Wu(t),Nu(t),await Ce(t,void 0,!1),a&&(cr(t,a),Yt(t,r.statusCriteria))}function cr(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),Ps(r,t,e)}function Nu(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 Fu(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Mu(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=St(t.constraintDate,n,r))})}function Wu(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=St(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 Uu=e=>e.type==="project",Bu=e=>pt(e),Hu=(e,t,r,i)=>{let n=Bu(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 gi(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(!Uu(c)){let u=Hu(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 lr(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)}),gi(n,t,i,r)}function vi(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:()=>vi(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}vi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var ht=vi;function ju(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function dr(e){return ju(e)&&!isNaN(e.getTime())}function I(e,t,r,i){if(!dr(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(!dr(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 Vu=e=>e?e.$level===1:!1,Yu=e=>e.type==="project",$u=e=>e.$level!==0,Gu=e=>e.type==="task",Ku=e=>e.type==="task"||e.type==="milestone",it={byFirstLevel:Vu,filterByParentType:Yu,avoidSubproject:$u,byTaskType:Gu,byTaskTypeAndMilestone:Ku};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 Ws(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=zu({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=qu({gantt:t,subprojectsWithNoLinks:a}),o=Ju({gantt:t,childrenIds:s,linkProperty:n,getArrayOfLinkedActivities:Xu,calculations:i});return new Set(o.map(c=>c.id))}catch(a){throw a}}function zu(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(it.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function qu(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 Ju(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 Xu(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 Us({gantt:e,linkProperty:t,direction:r}){try{let i=Zu(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Qu(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function Zu(e,t){return e.getTaskByTime().filter(it.avoidSubproject).filter(it.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Qu(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 Bs({gantt:e,direction:t,linkProperty:r}){try{let i=tf(e),n=new Set,a=new Set,s=new Set;t==="backward"&&nf(i).forEach(d=>{n.add(d.id)});let o=ef(i,t,r),c=rf(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 tf(e){return e.getTaskByTime().filter(it.filterByParentType).filter(it.avoidSubproject)}function ef(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 rf(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function nf(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Hs({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),s=af(r),o=sf(r),c=a[s];if(!Array.isArray(c))return;of(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function af(e){return e==="forward"?"$source":"$target"}function sf(e){return e==="forward"?"target":"source"}function of(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var Se={identifySecondLevelActivities:Ws,identifyInitialActivities:Us,identifyParentsWithAndWithoutLinks:Bs,identifyForbiddenActivities:Hs};function ur(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Ci({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}):De(r,e,i,n)}function js({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:I(r,n,e,i),ef:n}}function Vs({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 De(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=ur(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=Vs({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=js({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=Ci({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity);t>0&&(n=De(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=Ci({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=De(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=De(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},Ys=Ai;var Ii=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)}},$s=Ii;function Gs(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:s}=e,o=t[r],c=cf(t),l=null;if(s==="forward"){let d=lf(o,i,n,a);l=new Ys(d,t,a),l=l.calculate()}else{let d=df(o,i,n,a);l=new $s({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function cf(e){return{duration:e.duration,calendarId:e.calendar_id}}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);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 df(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 qs(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(uf(t.id,r))return null;let a=ff(t.id,i),s=pf(a,r);return s.length===0?null:hf(s,n)}function uf(e,t){return t.has(e)}function ff(e,t){let r=t.get(e);return r?r.childrens:[]}function pf(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function hf(e,t){if(t==="forward"){let r=Ks(e,"es"),i=zs(e,"ef");return{es:r,ef:i}}else{let r=Ks(e,"ls"),i=zs(e,"lf");return{ls:r,lf:i}}}function Ks(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function zs(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var ki={parentWithLinks:Gs,parentWithNoLinks:qs};var Si=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=ki.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=ki.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)})}},Js=Si;var Di=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}}},Xs=Di;var Ti=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}=Se.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=Se.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 Xs({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=Se.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}=Se.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 Js({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=Ti;function yf(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 fr=yf;var _i=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})}},Zs=_i;var Te=class extends Zs{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 ur(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Pi=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}},pr=Pi;var Ei=(e,t)=>()=>t()===e;var Ri=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var mf=16,_e=async e=>performance.now()-e>mf?(await rt(),performance.now()):e;var Pe=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 _e(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await _e(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 Li=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 pr({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 Pe({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 Te({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 Te({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=fr(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)}},Qs=Li;var bi=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})}},to=bi;var wi=class extends to{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))}},eo=wi;function gf(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 ro=gf;var Oi=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 pr({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 Pe({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=fr(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 eo({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=ro(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}},io=Oi;function no(){return null}var ao=({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 xi=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)})}},so=xi;var Ni=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)}},oo=Ni;var co=e=>({totalFloat:new so(e.totalFloat).getTotalFloat(),freeFloat:new oo(e.freeFloat).getFreeFloat()});var Fi=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=ao({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=co(u);o.set(l,f),c.set(l,p),s=await _e(s)}return{totalFloatMap:o,freeFloatMap:c}};var Mi=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=Ei(i,this.getCurrentCalculationId),a=()=>n()&&r();try{let s=t||this.gantt;if(this.gantt=s||no(),Ri(this.gantt))return!1;let o=new Qs(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new io(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 Fi({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}}}},lo=Mi;var vf=e=>e==="fnet"||e==="fnlt"||e==="mfo",Cf=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Af(e,t){let r=e.constraintDate;if(!r||!vf(e.constraintType))return r;let i=Cf(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 If(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 kf(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 Sf(e){let t=kf(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 Df(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 Tf(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 uo(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=If(u);return r.set(l,f),f},n=Tf(e);await rt();let a=Sf(e);await rt();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await rt();let o=Df(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 _f=1e3;function Pf(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 Wi(e,t,r=()=>!0){if(!r())return null;let i=await uo(e,t);if(!r())return null;let n=new lo(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>=_f&&(l=0,await rt(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,Pf(d,f,s))}return r()?c:null}async function hr(e,t,r=()=>!0){let i=await Wi(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 yr(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 fo=new Set;var po=new Set(["activity-outdent","activity-indent"]);var Ee=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),Ef=new Set(["selection-toggle","selection-replace","visibility-set","sir-sync","activity-lookahead-sync"]);function Rf(e){return e.kind==="inline-edit"?Ee.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Ee.has(t.column)):!1}function yo(e,t){return!(Ef.has(e.kind)||t.has(e.kind)||Rf(e))}function Re(e){return yo(e,fo)}function mo(e){return yo(e,po)}function Ui(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 Lf(e){return mo(e)&&Ui(e)}var ho=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function bf(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?ho.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>ho.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 go(e,t,r){let i=new Set;t.ran&&i.add(st.AUTOSCHEDULE),i.add(st.PARENT_BOUNDS),bf(e)&&i.add(st.PARENT_PROGRESS),Ui(e)&&i.add(st.REAL_WORK);let n=!r.skipAutoSchedule;return n&&mo(e)&&i.add(st.EXPECTED_PROGRESS),n&&Lf(e)&&i.add(st.REAL_COST),n&&Re(e)&&!r.skipCriticalPath&&i.add(st.CRITICAL_PATH),i}async function Y(e,t){let r=wf(t),i=r.has(st.AUTOSCHEDULE)?await Of(e,t.autoscheduleFrom):Nf();return await Ff(e.adapter,t,i.scheduledIds,r),await Mf(e,r,t.now),i}function wf(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t;return go(e.action,{requested:t,ran:r},e.options)}async function Of(e,t){let r=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(r),n=xf(e.adapter,i.updatedIds);return ve(e.adapter,i),n}function xf(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,H(s)),e.noteScheduledBefore(a,s))}return{scheduledIds:r,scheduledBeforeImages:i}}function Nf(){return{scheduledIds:[],scheduledBeforeImages:new Map}}async function Ff(e,t,r,i){let n=t.collectDirty?t.collectDirty(r):Ts(t.recomputeParentsFrom,r);await Ce(e,n,i.has(st.PARENT_PROGRESS),{recomputeRealWork:i.has(st.REAL_WORK)})}async function Mf(e,t,r){t.has(st.EXPECTED_PROGRESS)&&r!==null&&(lr(e.adapter,r,e.defaultBaseCalendarId??null),cr(e.adapter,r),Yt(e.adapter,e.sector.statusCriteria)),t.has(st.REAL_COST)&&yr(e.adapter),t.has(st.CRITICAL_PATH)&&await hr(e.adapter,e.sector.hoursPerDay)}var Wf=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),Uf=new Set(["mso","mfo"]);function mr(e){return Wf.has(e)}function gr(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let a=n.constraintType;if(!a||wt.has(a)||Uf.has(a))return!1;let s=Bi(n.startDate),o=Bi(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Bf(t,a,String(n.calendarId??""),i),l=Bi(n.constraintDate);return Hf(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Bf(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?St(e,n,t):e}function Bi(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 Hf(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function vr(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n,scheduledBeforeImages:a}=await Y(e,vo(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,vo(t));n=Vf(n,o.scheduledIds),a=Yf(a,o.scheduledBeforeImages)}return Re(t.action)&&await Y(e,jf(t)),{scheduledIds:n,scheduledBeforeImages:a}}function vo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function jf(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Vf(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function Yf(e,t){let r=new Map(e);for(let[i,n]of t)r.has(i)||r.set(i,n);return r}function $f(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 Hi(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&&!$f(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 G(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(pi(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"?Hi(i,e,r):[],s=Ds(e,i,r),o=t.sirDetection==="after-diff"?Hi(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 Cr(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 Co(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}"`);Gf(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),C=le(i,String(e.activityId)),D=c.constraintDate;Ft(i,e.activityId,p),bt(e.activityId,p.postProcessors??[],i);let m=de(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:_=>sr(e.activityId,v,_),now:r.now,options:t}),k=mr(e.column),{scheduledIds:y,scheduledBeforeImages:g}=await(k?vr({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:T(),revertTargets:[{activityId:e.activityId,priorConstraintDate:D}],revert:(_,b)=>gr(_,b,i,n.calendars)}):Y({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},T())),A=(p.trackingEvents??[]).map(_=>({name:_.name,properties:_.properties??{}})),P=oe(e.activityId,p.constraintWarning);return{ok:!0,changes:G(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 Gf(e){return e===E.DURATION||e===L.AUTO_SCHEDULING}async function Ao(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 ji([Jf(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function Io(e,t,r){let{hoursPerDay:i}=r.sector,n=e.operations.map(s=>zf(s,i)),a=Kf(e.operations);return ji(n,e,t,r,a)}function Kf(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 zf(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 ji(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=qf(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,H(m))}let S=Cr(f,d,a),C=new Map;for(let[D,m]of d)C.set(String(D),m);return{ok:!0,__beforeLinks:C,changes:G(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:v,links:S,hoursPerDay:o.hoursPerDay})}}function qf(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 Jf(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 ko(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}=Ke(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?qe({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):Je({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return ji(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 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=Xf(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 So(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 Xf(e,t,r,i){return i.hasChildren(e)?Vi(t,L.REAL_WORK_HOURS):ct(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+=Zf(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 Do(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||$i(i,t)}function Zf(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+=Qf(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 To(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||Gi(i,t)}function Qf(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var Ir=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}),_o="New Master Plan",Po="New Activity";var tp=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Eo=new Set(tp);function ep(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"||!Eo.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function Ro(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=ep(e.activityOverrides??{}),n=e.numTasksInGantt===0?_o:Po,a=i.name??n,s=i.durationHours??e.sector.hoursPerDay,o=i.calendarId??e.sector.defaultCalendar,c=rp(r,e.fallbackStartDate,i.startDate),l={...Ir,...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 rp(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):ip(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=$.ASAP,a.constraintDate=null,(e.promotionSource??"create")==="create"&&(a.progress=0,a.expectedProgressBaseline=0)),{parentId:e.parentId,fields:a}}function ip(e){return Et(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function kr(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 Kt=Number.MAX_SAFE_INTEGER,Lo=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 Ki(e,t){let r=[];return e.forEachActivity(i=>{Bt(i.parentId)===t&&r.push(i)}),r}function bo(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 wo(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 Sr(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;n.invalidateAllCaches();let l=np(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=sp(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=Ro(S,{getActivity:g=>i.getActivity(g),calculateEndDate:g=>i.calculateEndDate(g),getClosestWorkTime:g=>i.getClosestWorkTime(g)}).newTask;D.realWorkHours=ct(D.workHours,D.progress),cp(D,e,t,u,d,r);let m=kr(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),lp(e,p,d,i,r.preserveParentCustomId??!1,k),So(p,i),Do(p,i),To(p,i),dp(i,p,y,T,r),{ok:!0,newId:p,parent:d,newActivity:D,beforeSnap:y,initialTouched:T}}function np(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=ap(e,t,r,s);return o||{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function ap(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 sp(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function op(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function cp(e,t,r,i,n,a){let{adapter:s,customIdTracker:o}=r,c=op(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 lp(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 dp(e,t,r,i,n){if(n.skipCorrelativeRecompute)return;let a=at(e);n.skipBeforeSnap||or(e,a,new Set([String(t)]),r,i)}function Oo(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 G(e,{source:t,beforeSnap:c,touchedIds:l,scheduledIds:i,scheduledBeforeImages:u,trackingEvents:[d],hoursPerDay:n})}function xo(e,t){let r=Sr(e,t);if(!r.ok)return{ok:!1,reason:r.reason};si(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=Oo(t.adapter,e,r,[],t.sector.hoursPerDay);return{ok:!0,activity:i,changes:n}}async function No(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=Sr(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:Oo(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 Fo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=fp(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 A=Sr({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=at(i),p=new Set(d.map(String));or(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:C}=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=Cr(v,new Map,i);return{ok:!0,changes:G(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 Mo(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 Wo(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 _t(e,t){Yi(e,t),$i(e,t),Gi(e,t)}function Uo(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 Bo(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 fe(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=hp(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 Ho(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 jo(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=Uo(e.activityIds,i),c=Bo(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=J(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),_=fe({parent:A,remainingChildIds:P.map(String),defaultDurationHours:s.hoursPerDay,idsRemoved:o});if(!_){Qe(g,i);continue}for(let[b,x]of Object.entries(_.fields))Z(i,g,b,x);if(A.customId==null||A.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)_t(g,i);let S=at(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=H(A);g.before!==void 0&&(P.correlativeId=g.before),u.set(g.activityId,P)}let{scheduledIds:C,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,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=G(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=Ho({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)||(Vo(s,a,t)||Vo(a,s,t))&&i.push(String(n.id))}return i}function Vo(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 Yo(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=kr(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=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:A,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),A=fe({parent:y,remainingChildIds:g.map(String),defaultDurationHours:a.hoursPerDay,idsRemoved:new Set([e.activityId])});if(A){for(let[M,z]of Object.entries(A.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"&&_t(d,i),o||_t(e.parentId,i));let C=at(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=H(g);y.before!==void 0&&(A.correlativeId=y.before),v.set(y.activityId,A)}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?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:G(i,{source:e,beforeSnap:v,touchedIds:p,scheduledIds:D,scheduledBeforeImages:m,sirDetection:"before-diff",trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function $o(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):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 A=bs(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=J(i,o);for(let{activityId:y,newParentId:g}of d)i.setActivityField(y,L.PARENT,g),i.setActivityField(y,L.CORRELATIVE_ID,Lo),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,_=Et(A.type)&&i.getChildren(g).filter(M=>!l.includes(M)).length===0,b=A.hasNewActivities&&A.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)_t(y,i);let C=at(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=H(g);y.before!==void 0&&(A.correlativeId=y.before),p.set(y.activityId,A)}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=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:G(i,{source:e,beforeSnap:p,touchedIds:o,scheduledIds:D,scheduledBeforeImages:m,trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function Go(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,yi(g,i)),c.set(g,bo(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):Kt,b=P?nt(P):Kt;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),z=yi(_,i)+1,ot=c.get(g);if(ot!=null&&s.has(ot)){let xe=o.get(ot)??-1,Ut=o.get(g)??-1;xe>=0&&Ut>=0&&(z+=Ut-xe)}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=wo(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=fe({parent:g,remainingChildIds:A.map(String),defaultDurationHours:a.hoursPerDay,idsRemoved:new Set(p.filter(z=>z.oldParentKey===y).map(z=>z.activityId))});if(!P){Qe(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 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)_t(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 A=H(g);y.before!==void 0&&(A.correlativeId=y.before),S.set(y.activityId,A)}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:G(i,{source:e,beforeSnap:S,touchedIds:l,scheduledIds:m,scheduledBeforeImages:T,trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function Ko(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=>sr(e.activityId,d,v),now:r.now,options:t}),p=(l.trackingEvents??[]).map(v=>({name:v.name,properties:v.properties??{}}));return{ok:!0,changes:G(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:p,hoursPerDay:s.hoursPerDay})}}async function zo(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=Nt(v.activityId,S.changes);Cp(o,C,r);for(let T of C)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:G(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=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 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 J(r.adapter,i))e.set(n,a)}var zi=E.CUSTOM_ID;async function qo(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=oe(T.activityId,k.changes.constraintWarning);y&&p.push(y);let g=Nt(T.activityId,k.changes);Dp(c,g,r);for(let b of g)d.add(b);Sp(l,T,c);let A=le(i,T.activityId),P=Ip(T,r),_=k.changes;Ft(i,T.activityId,_),bt(T.activityId,k.changes.postProcessors??[],i),kp(T,P,r),f.push(...de(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?vr({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:S,revertTargets:[...l].map(([T,k])=>({activityId:T,priorConstraintDate:k})),revert:(T,k)=>gr(T,k,i,r.ctx.calendars)}):Y({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},S));return{ok:!0,verdicts:o,changes:G(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=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===zi&&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!==zi)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!==zi)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(!mr(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 J(r.adapter,i))e.set(n,a)}async function Jo(e,t,r){return e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Ao(e,t,r):e.kind==="links-batch"?Io(e,t,r):e.kind==="activity-create"?No(e,t,r):e.kind==="activity-paste"?Fo(e,t,r):e.kind==="activity-delete"?jo(e,t,r):e.kind==="activity-move"?Yo(e,t,r):e.kind==="activity-indent"?$o(e,t,r):e.kind==="activity-outdent"?Go(e,t,r):e.kind==="activity-set-progress"?Ko(e,t,r):e.kind==="dates-batch"?zo(e,t,r):e.kind==="bulk-edit"?qo(e,t,r):e.kind==="selection-toggle"?Dn(e,qi(r)):e.kind==="selection-replace"?Tn(e,qi(r)):e.kind==="visibility-set"?_n(e,qi(r)):e.kind==="sir-sync"?Mo(e,r):e.kind==="activity-lookahead-sync"?Wo(e,r):e.kind==="inline-edit"&&(e.column===E.CUSTOM_PREDECESSORS||e.column===E.CUSTOM_SUCESSORS)?ko(e,t,r):e.kind!=="inline-edit"?ua(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Co(e,t,r)}function qi(e){return{adapter:e.adapter}}var Tp=new Set(["startDate","endDate","constraintDate"]);function Xo(e,t){return Tp.has(e)&&typeof t=="string"?new Date(t):t}function Zo(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?_p(n,r):null}}}function _p(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 Pp(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 Ep={}.constructor.toString();function Rp(e){var t=e.constructor.toString();return t!==Ep}function Lp(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 Pp(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=vt(e[t]);break;default:if(Rp(e))r=Object.create(e);else{if(Lp(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 Qo(e){return typeof e<"u"}var Tr;function Ji(){return Tr||(Tr=new Date().valueOf()),Tr++,Tr}function dt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var wp=(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)},Op=(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)},tc={date_to_str:wp,str_to_date:Op},xp=(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}}),Np=(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])},ec={date_to_str:xp,str_to_date:Np};function rc(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=tc;return a()&&(l=ec),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=tc;return a()&&(l=ec),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 Xi(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function Zi(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 Qi(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 Fp(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 ic=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 Xi)return t;var r;if(t.date?r=new Xi(t.date,t.unit,t.task,null,t.calendar):r=new Xi(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 Zi)return r;var i;if(zt(r)?i=new Zi(r):i=new Zi(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=Fp,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 Qi)return a;var s;if(zt(a)?s=new Qi(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new Qi(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 nc(){}nc.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 tn=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}},en=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={}}},rn=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 Mp(){return typeof Map<"u"?new tn:new en}var nn=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 an(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=Mp(),this._largeUnitsCache=new rn(this),this._dateDurationCache=new nn,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}an.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 an))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,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 Le={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 Wp(){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 Up=Wp();function ac(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Le.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))}ac.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 nc,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 an(this.$gantt,ic(this.$gantt));t.id=String(Ji());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=Le.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=Up.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Le.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Le.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=Le.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||Ji(),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 sn(e,t){this.argumentsHelper=t,this.$gantt=e}sn.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 sn},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 sc(e){this.$gantt=e.$gantt,this.argumentsHelper=ic(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new sn(this.$gantt,this.argumentsHelper)}sc.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 Bp=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)}},Hp={create:Bp};function oc(e){var t=new ac(e),r=new sc(t),i=Hp.create(t,r);pe(e,i)}var cc={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 lc(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||cc,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:Qo,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=rc(r),r.date.init(),oc(r),r}function jp(e={}){let t=lc(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 dc={createCalendar:jp};var fR=3600*1e3;function hc(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Vp}=dc,be="__replay_default__";function Yp(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 uc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},fc="__main_global__",$p={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function pc(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 Gp(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:Yp(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function yc(e){let t=Vp({config:{work_time:!0}});t.addCalendar({id:be,worktime:uc}),t.addCalendar({id:fc,worktime:$p});let r=new Set(e.filter(d=>!pc(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>pc(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?Gp(d.worktime):uc});let n=Zo(t),a=n.getCalendar(be),s=n.getCalendar(fc);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([be]);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 mc(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 Kp(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 Kp(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}var _r=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,on(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:on(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:gc(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,on(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:gc(r)}))}};function on(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 gc(e){return{...e}}var Pr=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=vc(t);return this.reader.getCalendar(r??be)}getClosestWorkTime(t){let r=`${ln(t.task)}|${t.dir}|${t.date.getTime()}`;return cn(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:et.HOUR}))}calculateEndDate(t){let r=`${ln(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return cn(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${ln(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return cn(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 cn(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var zp="__default__";function vc(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function ln(e){return vc(e)??zp}var Er=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 Rr=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 he=class{_activities=new Map;_lastStartDate=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_cache={ids:null,visualOrderIds:null};_writeCapture=new _r;_viewState=new Rr;_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 Pr(yc(t.calendars)),this._flags=Jp(t),this._hierarchy=new Er(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=Ls(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))??Cc}getIncomingLinkIds(t){return this._incoming.get(String(t))??Cc}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(),dn(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,Xo(r,i)),r===L.PARENT&&this._hierarchy.markDirty(),dn(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),dn(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){Ic(this._outgoing,String(t.source),t.id),Ic(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Ac(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),Ac(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(!qp(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))}},Cc=[];function qp(e){return e===fi.LAG||e===fi.TYPE}function dn(e){return e===L.PARENT||e===L.CORRELATIVE_ID}function Ac(e,t){return e.filter(r=>String(r)!==String(t))}function Ic(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Jp(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 kc(e,t){return e.getActivity(t)}function Sc(e){return e.getAllActivities()}function Dc(e){return e.getAllIds().map(String)}function Tc(e,t){e.forEachActivity((r,i)=>t(i))}function _c(e,t){let r=t==="0"?un(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 un(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 Pc(e){return e.checkedIds().map(String)}function Ec(e,t){return e.getChildren(t).length>0}function Rc(e,t){let r=e.getLink(t);return r?gt(r):null}function Lc(e){return e.getAllLinks().map(t=>gt(t))}function bc(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=Xp(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 Xp(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=pt(i);if(!n)return 0;if(t==="COST")return Lr(n.cost);if(t==="HH")return Lr(n.workHours);let a=i.type;return a==="project"?wc(e,r):a==="milestone"?0:Lr(n.durationDays)}function wc(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+=wc(String(i),t):s!=="milestone"&&(r+=Lr(a.durationDays))}return r}function Lr(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function br(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,E.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&bc(String(i),e,t)})}function wr(e){for(let t of Zp(e))th(t,e)}function Zp(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,Qp(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function Qp(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function th(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,Ze(n))}function Oc(e){return typeof e=="string"&&e.length>0?Tt(e):e instanceof Date?e:null}function fn(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 Or(e,t){let r=fn(e.duration),i=fn(e.cost),n=fn(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:Oc(e.start_date),endDate:Oc(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 xr(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=>Or(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 eh(e){let t=pt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function xc(e){let t=[];return e.forEachActivity((r,i)=>{let n=eh(r);n&&(e.setActivityField(i,"baselineSnapshot",n),t.push(i))}),t}function Nr(e,t,r,i,n=null){if(t.length===0)return[];let a=new Set;for(let s of xr(e,t,i))a.add(s);if(r)for(let s of lr(e,r,n))a.add(s);for(let s of xc(e))a.add(s);for(let s of yr(e))a.add(s);return[...a]}function Nc(e){let t=e.ponderator;return typeof t=="number"&&Number.isFinite(t)?t:0}function Fc(e){let t=e.progress;return typeof t=="number"&&Number.isFinite(t)?t:0}function Mc(e,t,r){let i=new Map;e.forEachActivity((a,s)=>{i.set(s,Nc(a))}),br(r,e);let n=[];return e.forEachActivity((a,s)=>{Nc(a)!==(i.get(s)??0)&&n.push(H(a))}),n}function Wc(e,t){let r=new Map;e.forEachActivity((n,a)=>{r.set(a,Fc(n))}),wr(e);let i=[];return e.forEachActivity((n,a)=>{Fc(n)!==(r.get(a)??0)&&i.push(H(n))}),i}function Uc(e,t,r,i,n,a=null){let s=Nr(e,r,i,n,a),o=[];for(let c of s){let l=e.getActivity(c);l&&o.push(H(l))}return o}function Bc(e,t,r){let i=[];for(let n of Yt(e,r)){let a=e.getActivity(n);a&&i.push(H(a))}return i}function Fr(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function rh(e){return e.reduce((t,r)=>Fr(r)<Fr(t)?r:t)}function ih(e){return e.reduce((t,r)=>Fr(r)>Fr(t)?r:t)}function nh(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Hc(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=nh(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:rh(i),endHour:ih(n)}}function jc(e,t){return{calendars:e.calendarReader,hierarchy:mc(e),activityReader:hc(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function Vc(e){return Re(e)}function pn(e,t,r,i,n){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:i,afterLinks:n}}function $c(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),H(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 Gc(e){return e.kind!=="inline-edit"||!Ee.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Yc(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 Kc(e,t){if(!Yc(e)||!Yc(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function zc(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 pn(o)}function qc(e){return e.kind!=="sir-sync"&&e.kind!=="activity-lookahead-sync"}function hn(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 yn(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?H(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?H(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?H(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"?ah(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function ah(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 mn(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Jc(e,t){Zc(e,t,"before")}function Xc(e,t){Zc(e,t,"after")}function Zc(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(H(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(H(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 sh=100,oh=600,Mr=class{constructor(t=sh){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<=oh&&n!==void 0&&Kc(n,t)?this.undoStack[this.undoStack.length-1]=zc(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}};function ch(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function lh(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Qc(e){return{id:String(e.id),worktime:lh(e.worktime)}}function Wr(e,t,r,i=[]){let n=t.map(ch),a=[...r.map(Qc),...i.map(Qc)];return{activities:[...e],links:n,calendars:a}}var tl=["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"],el=new Set(["startDate","endDate","constraintDate","dateOrigin"]),rl=new Set(["newActivityIds","pendingRequestIds","responsableIds","tagIds"]);function il(e){let t=tl.map(r=>[r,dh(r,e[r])]);return Object.fromEntries(t)}function dh(e,t){return el.has(e)?t instanceof Date?new Date(t):null:rl.has(e)?Array.isArray(t)?[...t]:[]:t}function nl(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of tl)if(!uh(r,e[r],t[r]))return!0;return!1}function uh(e,t,r){return el.has(e)?fh(t,r):rl.has(e)?ph(t,r):(t??null)===(r??null)}function fh(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function ph(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 Ur=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),il(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?nl(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 al=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var gn=[!1,!0,!0,!0,!0,!0,!1],sl=new Set(["1","true"]),vn="DURATION",ol="asap",cl={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 ll(e,t){let r=[],i=e.map(a=>{let s=kh(a,t);return a.should_be_showed===!1&&r.push(s.id),s});Sh(i);let n=new Set(i.map(a=>a.id));return Dh(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function hh(e){return e===0}function yh(e,t){if(!e)return null;let r=cl[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),ol):r}function mh(e,t){let r=yh(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?Tt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function gh(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function vh(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 Ch(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Cn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Ch(r)&&t.push(String(r.id));return t}function Ah(e){return e==="0"?null:String(e)}function Ih(e,t){return Array.isArray(e)?e.map(r=>Or(r,t)).filter(r=>r!==null):[]}function kh(e,t){let r=gh(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:s}=mh(e,t.reporter),o=e.type==="milestone",c=Tt(e.start_date),l=o?c:Tt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:Ah(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:hh(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:Tt(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:vh(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Cn(e.pendingRequests),responsableIds:Cn(e.responsables),tagIds:Cn(e.tags),baselinePoints:Ih(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 Sh(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function Dh(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 pl(e,t,r,i=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>Ph(c,i)),o=(r??[]).map(c=>Eh(c,i));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:_h(s)}}function _h(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function hl(e,t){let r=xh(e.working_days),{days:i,hours:n}=Oh(e,r),a=Rh(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 Ph(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return hl(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function Eh(e,t){return hl(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function Rh(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=Lh(i.from_date,i.to_date,t);if(n.length===0)continue;let a=bh(i);if(a!==void 0)for(let s of n)r[s]=a}return Object.keys(r).length>0?r:null}function Lh(e,t,r){let i=dl(e),n=dl(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 dl(e){if(typeof e!="string")return null;let t=al.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 bh(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=wh(t);if(r.length>0)return r}}var ul=/^\d{1,2}:\d{2}$/;function wh(e){let t=[];for(let r of e){let i=gl(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let o=i.startsCsv.trim(),c=i.endsCsv.trim();!Br(o)&&!Br(c)&&ul.test(o)&&ul.test(c)&&t.push(`${o}-${c}`);continue}let s=ml(i.startsCsv,i.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(yl),t}function fl(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 yl(e,t){return fl(e)-fl(t)}function Oh(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=ml(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=gl(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(yl);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 ml(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];Br(c)||Br(l)||(s[o]=`${c}-${l}`)}return s}function gl(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 xh(e){if(typeof e!="string")return[...gn];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...gn]:t.map(r=>sl.has(r))}var Nh=new Set(["false","null"]);function Br(e){return!e||Nh.has(e)}function Fh(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Mh(e){if(typeof e!="string")return null;let t=Ua(e);return t||(Fh(e)?e:null)}function Cl(e,t){let r=[];for(let i of e)try{r.push(Wh(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return Uh(r)}function Wh(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=Mh(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 Uh(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||vl(r)>vl(n))&&t.set(i,r)}return[...t.values()]}function vl(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Bh(e){if(typeof e!="string")return vn;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return vn}}function Hh(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function jh(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Al(e){let t=Hh(e),r=jh(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:Bh(e.activity_creter),statusCriteria:Jr}}function Hr(e,t=Qt){let r=Al(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:s}=pl(e.calendars,e.sector.calendars,e.baseCalendars,Vh(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=ll(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=Cl(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function Vh(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 Il(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 kl(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 Sl(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 Dl(e){return!!e&&typeof e=="string"&&e.trim().length>0}function jr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function Vr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Tl(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function _l(e,t){return!t&&Dl(e)}function Pl(e,t){return t&&Dl(e)}function Oe(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function we(e){if(!Oe(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Yh(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!Oe(t))return r;let i=t.length;return r.padStart(i,"0")}function mt(e,t){let r=we(e),i=we(t),n=r+i;return Yh(n,e)}function Yr(e,t){let r=we(e),i=we(t);return r<i?-1:r>i?1:0}function $r(e,t){return Yr(e,t)<=0?e:t}function Gr(e,t){return Yr(e,t)>=0?e:t}function El(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>$r(t,r))}function Rl(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Gr(t,r))}function Ll(e){return{prefix:e,baseSuffix:null}}function bl(e,t){let r=Vr(e);return{prefix:jr(e),baseSuffix:mt(r,t)}}function wl(e){return{prefix:e,baseSuffix:null}}function Ol(e,t){return _l(e,t)?"parentConversion":Pl(e,t)?"pasteReference":"noContext"}function $h(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Kr=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?$h(i):null,hadId:this.processedIds.has(t)})}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return jr(t)}extractSuffix(t){return Vr(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=$r(r,i.min),i.max=Gr(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=$r(i,n.min),n.max=Gr(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=El(o),n.max=Rl(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(;Yr(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&&Oe(r)?r:this.suffixIncrement;return`${t}${o}`.length>20?null:o}let i=this.prefixMap.get(t),n=this.suffixIncrement;if(!r||!Oe(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=Tl(r),a=Ol(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 Ll(this.defaultPrefix);case"pasteReference":return bl(r,this.suffixIncrement);default:return wl(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)}};function xl(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),Gh(e,r)}function Gh(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)}var At={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Nl(e){let t=e.clock??null,r=t?Ie(t()):null,i=e.reporter??Qt,n=Hr({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),a=n.sector;a.statusCriteria=Me(e.statusCriteria);let s=n.calendars,o=n.baseCalendars??[],c=Wr(n.activities,n.links,n.calendars,o),l=new he(c);l.hydrateViewState({hiddenIds:n.viewStateSeed.hiddenIds});let d=new Xe(l,i);xl(l);let u=Il({knownIds:n.activities.map(C=>C.id)}),f=kl({knownIds:n.links.map(C=>C.id)}),p=Sl({knownIds:n.activities.map(C=>C.uniqueCorrelativeId)}),v=new Kr({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;Nr(l,e.baselinePoints,r,i,C)}let S=Ms({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 Fl(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 zr=class{_status=At.READY;_dispatchInFlight=!1;coreRuntime;_undo=new Mr;_opQueue=Promise.resolve();_scheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=Nl(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!==At.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 this.coreRuntime.sector}getActivityView(t){return this.assertReady(),kc(this.coreRuntime.state,t)}getAllActivitiesView(){return this.assertReady(),Sc(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),_c(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Rc(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),Lc(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?i[r]:null}getAllIds(){return this.assertReady(),Dc(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Tc(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),un(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Pc(this.coreRuntime.state)}getVisualOrderIds(){return this.assertReady(),this.coreRuntime.state.getVisualOrderIds()}hasChild(t){return this.assertReady(),Ec(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(),Hc(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));Fl(r,"activity",s=>{let o=this.coreRuntime.state.getActivity(s);return{exists:o!==null,current:o?.proplannerId??null}},n),Fl(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?Ie(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(),Mc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t)}recomputeAllProgressRollup(){return this.assertReady(),Wc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay)}setStatusCriteria(t){this.assertReady();let r=Me(t);return this.coreRuntime.sector.statusCriteria=r,Bc(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=xo(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=jc(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),n=qc(t);this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction(),this._dispatchInFlight=!0;let a;try{a=await Jo(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?Ie(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&&mn(a.changes)){let s=$c(this.coreRuntime.state,a.changes);this._undo.record(pn(a.changes,a.__beforeSnap,a.__beforeLinks,s.afterSnap,s.afterLinks),Gc(t),Date.now())}return a.ok?(mn(a.changes)&&this._recordScheduleMutation(r.skipCriticalPath!==!0),{...a,changes:a.changes}):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===At.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 he(Wr(this.coreRuntime.state.getAllActivities().map(o=>H(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==At.DESTROYED&&this._scheduleRevision===t,a=(async()=>{let o=await Wi(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=G(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===At.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await hr(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=G(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(){let t=this._enqueue(async()=>{this.assertReady();let r=this._undo.takeUndo();return r?(Jc(this.coreRuntime.state,r),this._recordScheduleMutation(!1),hn(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(r),this._undo.resetCoalesce(),yn(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?(Xc(this.coreRuntime.state,r),this._recordScheduleMutation(!1),hn(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce(),yn(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}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._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=At.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Ur;assertReady(){if(this._status===At.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===At.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=At.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",t),t}}};function Ml(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 Wl=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Ul={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 Bl=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"},Kh={[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},Hl=Object.keys(Kh);var jl={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return zl(zh);})();
|
|
1
|
+
"use strict";var ScheduleCore=(()=>{var ni=Object.defineProperty;var Ql=Object.getOwnPropertyDescriptor;var td=Object.getOwnPropertyNames;var ed=Object.prototype.hasOwnProperty;var rd=(e,t)=>{for(var r in t)ni(e,r,{get:t[r],enumerable:!0})},id=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of td(t))!ed.call(e,n)&&n!==r&&ni(e,n,{get:()=>t[n],enumerable:!(i=Ql(t,n))||i.enumerable});return e};var nd=e=>id(ni({},"__esModule",{value:!0}),e);var Oy={};rd(Oy,{ACTIVITY_TYPE:()=>ze,CALENDAR_UNIT:()=>nt,COLUMN:()=>_,CONSTRAINT_TYPE:()=>Y,CONSTRAINT_TYPE_TO_LABEL:()=>zl,CREATION_KIND:()=>Xl,DEFAULT_HOURS_PER_DAY:()=>ql,DISPATCH_ACTION_KIND:()=>G,DISPATCH_ACTION_KINDS:()=>Jl,DISPATCH_TRACK_EVENT:()=>yt,LINK_CODE_TO_TYPE:()=>qt,LINK_TYPE:()=>M,LINK_TYPE_CODE:()=>qa,NEW_ACTIVITY_DEFAULTS:()=>Rr,REJECTION_REASON:()=>P,ROOT_PARENT_ID:()=>H,ScheduleCore:()=>ei,WORK_TIME_DIRECTION:()=>q,checkNoUpdatedLinks:()=>Gl,computeExpectedProgress:()=>ki,expectedProgressFromBaseline:()=>ve,getActiveBaseline:()=>rt,getUnsavedActivities:()=>Kl,isRootParent:()=>b,normalizeParentKey:()=>zt,parseFromBackend:()=>Kr,willRunCriticalPath:()=>Xc,yieldToBrowser:()=>at});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 Ye=e=>String(e);function On(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:a,exists:s,autoCheckParents:o}=e,c=Ye(t),l=new Set([...i].map(String)),d=new Set(l),u=ad(c,n).filter(s),f=u.filter(g=>!a(g)),h=r&&f.length<u.length;r&&!h?d.add(c):d.delete(c);for(let g of f)r?d.add(g):d.delete(g);return h||sd({id:c,isChecked:r,autoCheckParents:o,hierarchy:n,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:od(l,d),parentBlocked:h}}function ad(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=Ye(s);n.has(o)||(n.add(o),r.push(o),i.enqueue(o))}}return r}function sd(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=Ye(c);if(a(l))return;let d=n.getChildrenIds(l).map(Ye).filter(s),u=d.some(a),f=d.filter(C=>!a(C)),g=f.length>0&&f.every(C=>o.has(C))&&!u;if(r){if(!i||!g||o.has(l))return;o.add(l)}else{if(g||!o.has(l))return;o.delete(l)}c=n.getParentId(l)}}function od(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 ne(e){return(e.pendingRequestIds?.length??0)>0}var P={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 xn=(e,t)=>{let r=e.getActivity(t);return r!=null&&ne(r)},Nn=(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 Fn(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,a=n?o=>n.has(o):o=>xn(r,o),s=On({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:Nn(e,r,s.changed)}}function Mn(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!xn(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:Nn(e,r,a)}}function Wn(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 Un="text";var Bn="description";var Hn="duration";var jn="progress";var Vn="cost";var Yn="used_cost";var $n="hhWorkTime";var Gn="start_date";var Kn="end_date";var zn="constraint_type";var qn="constraint_date";var Jn="calendar_id";var Xn="custom_id";var Zn="subcontractId";var Qn="responsables";var ta="tags";var ea="custom_predecessors";var ra="custom_sucessors";var ia="real_work";var na="real_cost";var aa="expected_progress";var sa="expected_progress_base";var oa="start_base";var ca="end_base";var la="duration_base";var da="cost_base";var ua="work_base";var fa="calendarDuration";var pa="is_critical",ha="earlyStart",ya="earlyFinish",ma="lateStart",ga="lateFinish",va="freeSlack",Aa="totalSlack";var Ca="correlative_id";var Ia="unique_correlative_id";var Sa="ponderator";var q={FUTURE:"future",PAST:"past"},nt={HOUR:"hour",DAY:"day"},Ot={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var $e="status";var ai="Baseline";function Ge(e){return e==="Actual"?"Actual":ai}var cd={TEXT:Un,DESCRIPTION:Bn,DURATION:Hn,PROGRESS:jn,COST:Vn,USED_COST:Yn,HH_WORK_TIME:$n,START_DATE:Gn,END_DATE:Kn,CONSTRAINT_TYPE:zn,CONSTRAINT_DATE:qn,CALENDAR_ID:Jn,CUSTOM_ID:Xn,SUBCONTRACT_ID:Zn,RESPONSABLES:Qn,TAGS:ta,CUSTOM_PREDECESSORS:ea,CUSTOM_SUCESSORS:ra},ld={REAL_WORK:ia,REAL_COST:na,EXPECTED_PROGRESS:aa,EXPECTED_PROGRESS_BASE:sa,START_BASE:oa,END_BASE:ca,DURATION_BASE:la,COST_BASE:da,WORK_BASE:ua,CALENDAR_DURATION:fa,IS_CRITICAL:pa,EARLY_START:ha,EARLY_FINISH:ya,LATE_START:ma,LATE_FINISH:ga,FREE_SLACK:va,TOTAL_SLACK:Aa,CORRELATIVE_ID:Ca,UNIQUE_CORRELATIVE_ID:Ia,PONDERATOR:Sa,STATUS:$e},_={...cd,...ld};function ka(e,t){throw new Error(t)}function Da(e,t){return()=>t()===e}var Y={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},dd={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 _a(e,t,r){if(!t)return{violated:!1};let i=dd[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var ud=new Set(["mso","snet","snlt"]);function _e(e,t,r){return ud.has(e)?t:r}function Pa(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var fd={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}},Ke=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Ta=(e,t)=>new Date(e.getTime()+t*864e5),pd=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function si(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=fd[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Ke(i),dir:q.FUTURE,task:e});if(pd(n,i))return i.getTime()!==Ke(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:Ta(Ke(i),1),dir:q.PAST,task:e});let a=Ke(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:q.FUTURE,task:e}):t.getClosestWorkTime({date:Ta(a,1),dir:q.PAST,task:e})}function Ea(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=si(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 Ra(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function oi(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var M={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var ze={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},La={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var qe=typeof window>"u",ci=!qe&&typeof MessageChannel<"u"?new MessageChannel:null;function at(){return qe||!ci?Promise.resolve():new Promise(e=>{ci.port1.onmessage=()=>e(),ci.port2.postMessage(null)})}async function Je(e,t){return performance.now()-e<La.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await at(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ae(e){return qe||await at(),e()?{aborted:!1}:{aborted:!0}}function Xe(e,t){let{inDegree:r,successors:i}=hd(e,t),n=yd(r),a=md(n,r,i),s=a.length<e.length,o=s?gd(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function hd(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 yd(e){let t=new ft;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function md(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 gd(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var Ze=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=Xe(t,r),this.cached)}};function ba(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var li={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 di(e){return e==="project"||e==="task"||e==="milestone"}function _t(e,t){return t||di(e)&&li[e].alwaysSummary}function Kt(e){return e==="milestone"}function xt(e){return di(e)&&li[e].promotesToProjectOnFirstChild}var ui="project",se="task";function Pe(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function wa(e,t){let r=t.getActivity(e);return r?_t(r.type,t.getChildren(e).length>0):!1}function Oa(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 Fa(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 vd(e){let t=new Map;for(let r of e)xa(t,String(r.source),r),xa(t,String(r.target),r);return t}function xa(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function Ad(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(Id(c,a,s,t,r,n))return!0;return!1}function Id(e,t,r,i,n,a){if(Sd(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=kd(e,t);if(!i.has(String(o)))return!1;let c=n.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&Dd(e,r,c))}function Sd(e){return e.source===e.target}function kd(e,t){return String(e.source)===t?e.target:e.source}function Dd(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 Ma(e,t){let r=[],i=vd(e),n=0;for(let a of e){let s=wa(a.source,t),o=wa(a.target,t);if(Td(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=Na(a.source,s,t,i,!0),l=Na(a.target,o,t,i,!1);n=wd(r,c,l,a,t,n,i)}return r}function Td(e,t,r,i){return r&&Oa(e.source,e.target,i)||t&&Oa(e.target,e.source,i)}function Na(e,t,r,i,n){return t?Ad(Fa(e,r),r,i,n):[e]}function _d(e,t,r){let i=Fa(e,t);if(i.length===0)return null;let n=null,a=null;for(let s of i){let o=r(s);if(!o)continue;(n===null||o.startDate<n)&&(n=o.startDate),(a===null||o.endDate>a)&&(a=o.endDate)}return n===null||a===null?null:{startDate:n,endDate:a}}function Qe(e,t){return _d(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function Pd(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Ed(e,t,r,i){if(!t)return 0;let n=i.getActivity(e);return!r||!n?-t.durationHours:-i.calculateDuration({startDate:r.startDate,endDate:n.endDate,task:t})}function Rd(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function Ld(e,t,r,i,n){if(Rd(e,n))return 0;let a=i.getActivity(e);return!t||!a||!r?0:i.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function bd(e,t){let r=t.getActivity(e.source),i=t.getActivity(e.target),n=Qe(e.source,t),a=Qe(e.target,t),s=e.type===M.START_TO_START||e.type===M.START_TO_FINISH,o=e.type===M.FINISH_TO_FINISH||e.type===M.START_TO_FINISH;return{source:r,sourceBounds:n,targetStart:a?.startDate??i?.startDate,userLag:e.lag??0,sourceEndpointIsStart:s,targetLag:o?-Pd(i,a,t):0,summarySourceId:e.type===M.START_TO_START&&n?e.source:void 0}}function wd(e,t,r,i,n,a,s){let o=bd(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:h,summarySourceId:g}=o,C=a;for(let A of t){let k=f?Ed(A,c,l,n):0;for(let S of r){if(String(A)===String(S))continue;let D=Ld(S,d,c,n,s);e.push(Od(i,A,S,C,k,h,u+D,g,D!==0&&h===0?i.target:void 0)),C+=1}}return C}function Od(e,t,r,i,n,a,s,o,c){return{id:`virtual_${e.id}_${i}`,source:t,target:r,type:e.type,lag:e.lag,_sourceLag:n,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var tr=class{invalidate(){}get(t,r){return Ma(t,r)}};function xd(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 Nd(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 Wa(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let i=xd(t),n=Nd(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 Ua(e,t,r){let i=r.type===M.FINISH_TO_START,n=r.type===M.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 M.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case M.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case M.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case M.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 Fd(e,t,r){if(e._summarySourceId===void 0)return null;let i=r.getActivity(e._summarySourceId);if(!i)return null;let n=Qe(e._summarySourceId,r);return n?-r.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:i}):null}function Md(e,t,r,i,n){let a=t.durationHours===0&&n;return{successorStart:i.getClosestWorkTime({date:e.endDate,dir:a?"past":"future",task:t}),link:r}}function Ba(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s,isFS:o,isFF:c}=Ua(e,t,r),l=Fd(r,e,i)??n,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return Md(e,t,r,i,o||c);let h=o?t:e,g=i.getClosestWorkTime({date:e.endDate,dir:"future",task:h});if(l!==0&&(g=i.calculateEndDate({startDate:g,durationHours:l,task:e})),a!==0&&(g=i.calculateEndDate({startDate:g,durationHours:a,task:t})),s!==0&&(g=i.calculateEndDate({startDate:g,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:i.getClosestWorkTime({date:g,dir:"past",task:t}),link:r};let C=new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:C,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:g,dir:"future",task:t}),link:r}}function Ha(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s}=Ua(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 ja(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===Y.ASAP||a===Y.ALAP)continue;let s=Ea(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 er(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=oi(e.startDate,i):Ra(n,i)?a=n:a=oi(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function Va(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case Y.MSO:case Y.MFO:return new Date(i);case Y.SNET:case Y.FNET:return i>t?new Date(i):t;case Y.SNLT:case Y.FNLT:return i<t?new Date(i):t;default:return t}}function Wd(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function Ya(e,t,r){return fi(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function fi(e,t,r){return t.dragWithMultiple&&Wd(e,r)}async function Ga(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 h=r.getActivity(u);return h?{startDate:h.startDate,endDate:h.endDate}:{startDate:new Date,endDate:new Date}},c=r.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let f=await Je(d,n);if(f.aborted)return a;d=f.newSliceStart;let h=r.getActivity(u);if(!h||!h.autoScheduling||h.progress===100||Ud(h,r))continue;let g=s.get(String(u))??[],C=null,A=null,k=!1;for(let v of g){let E=r.getActivity(v.source);if(!E)continue;let T=o(v.source),R=T.startDate.getTime()!==E.startDate.getTime()||T.endDate.getTime()!==E.endDate.getTime(),O={...E,startDate:T.startDate,endDate:T.endDate},N=Ya(O,c,l),X={...O,startDate:N.startDate,endDate:N.endDate},z=fi(v.source,c,l)?{...v,lag:0}:v,gt=Ba(X,h,z,r);(!C||gt.successorStart>C)&&(C=gt.successorStart,A=String(v.id),k=v._summaryTargetId!==void 0&&!R)}C!==null&&k&&C<h.startDate&&(C=new Date(h.startDate));let D=a.get(u),p=D?{...D}:{activityId:u,startDate:h.startDate,endDate:h.endDate,drivingLinkId:null,kind:"asap",conflict:!1},y=p.earliestStart||p.latestStart||p.earliestEnd||p.latestEnd;if(!(!C&&!y)){if(C){let v=C;h.type===ze.MILESTONE&&(v=Va(h,C)),p.drivingLinkId=A,p.startDate=v,p.endDate=r.calculateEndDate({startDate:v,durationHours:h.durationHours,task:h}),p.earliestSchedulingStart=v,p.earliestSchedulingEnd=p.endDate}else h.constraintType===Y.MSO?p.earliestStart&&(p.startDate=p.earliestStart,p.endDate=p.earliestEnd??r.calculateEndDate({startDate:p.earliestStart,durationHours:h.durationHours,task:h})):h.constraintType===Y.MFO&&p.latestStart&&(p.startDate=p.latestStart,p.endDate=p.latestEnd??r.calculateEndDate({startDate:p.latestStart,durationHours:h.durationHours,task:h}));er(h,p,r),a.set(u,p)}}return a}function Ud(e,t){return _t(e.type,t.getChildren(e.id).length>0)}var H="0";function b(e){return e==null||e===0||e==="0"}function zt(e){return b(e)?"0":String(e)}async function Ka(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===Y.ALAP&&l.push(A.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let A of t){let k=String(A.source);d.has(k)||d.set(k,[]),d.get(k).push(A);let S=String(A.target);u.has(S)||u.set(S,[]),u.get(S).push(A)}let f=A=>{let k=s.get(A);if(k)return{startDate:k.startDate,endDate:k.endDate};let S=i.getActivity(A);return S?{startDate:S.startDate,endDate:S.endDate}:{startDate:new Date,endDate:new Date}},h=A=>!A.parentId||b(A.parentId)?i.getProjectEnd():f(A.parentId).endDate,g=(A,k)=>{let S=A,D=0;for(;S&&!b(S)&&D++<c+1;){if(String(S)===String(k))return!0;let p=i.getActivity(S);if(!p||!p.parentId)break;S=p.parentId}return!1},C=performance.now();for(let A of e){let k=await Je(C,a);if(k.aborted)return s;C=k.newSliceStart;let S=i.getActivity(A);if(!S||S.constraintType!==Y.ALAP||!S.autoScheduling||S.progress===100||_t(S.type,i.getChildren(A).length>0))continue;let D=h(S);if(!D)continue;let p=D,y=null,v=!1,E=d.get(String(A))??[];for(let At of E){if((At.lag??0)<0)continue;let ie=i.getActivity(At.target);if(!ie||ie.autoScheduling===!1)continue;let wn=f(At.target),Zl={...ie,startDate:wn.startDate,endDate:wn.endDate},Ve=Ha(Zl,S,At,i);Ve<p&&(p=Ve),(y===null||Ve<y)&&(y=Ve,v=S.parentId&&!b(S.parentId)?g(At.target,S.parentId):!1)}if(y!==null)if(v)p=y;else{let At=f(A).endDate,ie=At.getTime()>D.getTime()?At:D;p=y<ie?y:ie}else p>D&&(p=D);let R=(u.get(String(A))??[]).some(At=>At.type===M.FINISH_TO_START||At.type===M.FINISH_TO_FINISH),O=new Date(Date.UTC(p.getUTCFullYear(),p.getUTCMonth(),p.getUTCDate())),N=()=>i.getClosestWorkTime({date:O,dir:"past",task:S}),X=i.getClosestWorkTime({date:p,dir:"future",task:S}).getTime()===p.getTime(),z;S.durationHours===0&&y===null?z=R&&X?N():i.getClosestWorkTime({date:p,dir:"past",task:S}):S.durationHours===0?R?z=N():z=i.getClosestWorkTime({date:p,dir:"future",task:S}):z=i.getClosestWorkTime({date:p,dir:"future",task:S});let gt=i.calculateEndDate({startDate:z,durationHours:-S.durationHours,task:S}),Te=s.get(A),vt=Te?{...Te}:{activityId:A,startDate:gt,endDate:z,drivingLinkId:null,kind:"alap",conflict:!1};vt.startDate=gt,vt.endDate=z,vt.drivingLinkId=null,vt.kind="alap";let ri=vt.earliestSchedulingStart??null;vt.earliestSchedulingStart=null,vt.earliestSchedulingEnd=null;let ii=ri!==null&&ri.getTime()>gt.getTime()?ri:gt;vt.latestSchedulingStart=ii,vt.latestSchedulingEnd=ii===gt?z:i.calculateEndDate({startDate:ii,durationHours:S.durationHours,task:S}),er(S,vt,i),s.set(A,vt)}return s}var oe={warn(){},error(){}};function Ee(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 za(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 Bd(n,i,r)}function Bd(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 Nt(e,t){switch(e.kind){case"create":return Hd(e,t);case"update":return jd(e,t);case"delete":return Vd(e,t)}}function Hd(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(za(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Yd)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function jd(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 Vd(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 rr=null;function Yd(){return rr===null&&(rr=Date.now()),rr+=1,String(rr)}var qa={[M.FINISH_TO_START]:"fs",[M.START_TO_START]:"ss",[M.FINISH_TO_FINISH]:"ff",[M.START_TO_FINISH]:"sf"},qt={fs:M.FINISH_TO_START,ss:M.START_TO_START,ff:M.FINISH_TO_FINISH,sf:M.START_TO_FINISH},Ja="fs";function Xa(e){if(e in qt)return qt[e]}var Za=";",Qa=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function ir(e){let t=[],r=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:r};for(let n of i.split(Za)){if(n.length===0)continue;let a=$d(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function $d(e){let t=e.toLowerCase(),r=Qa.exec(t);if(!r)return null;let[,i,n,a,s]=r,o=n?qt[n]:qt[Ja],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 ar(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=nr(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(nr(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 nr(e,t){return`${String(e)}::${t}`}function sr(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=nr(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(nr(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 ts={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:nt.HOUR}):t.isWorkTime(e,nt.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function pi(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 hi=ts;var or=class{adapter;reporter;currentCalculationId=0;topoCache=new Ze;expandedLinksCache=new tr;constructor(t,r=oe){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{qd(this.adapter);let a=Ft("schedule.total"),s=Ft("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Pt(s);let l=c;if((await ae(i)).aborted)return{...n,cancelled:!0};let d=Ft("schedule.scoping"),u=this.adapter.getAllIds(),f=Jd(t,l,this.adapter),h=f.links,g=f.idSet;Pt(d);let C=Ft("schedule.topologicalSort"),A=Zd(this.topoCache,u,l,g);if(Pt(C),A.hasCycles)return Pt(a),{...n,cycles:[A.cycleNodes]};if((await ae(i)).aborted)return{...n,cancelled:!0};let k=Ft("schedule.processConstraints"),S=new Map;if(ja(A.ordered,this.adapter,S),Pt(k),(await ae(i)).aborted)return{...n,cancelled:!0};let D=Ft("schedule.asapPass"),p=await Ga(A.ordered,h,this.adapter,t,i,S);if(Pt(D),(await ae(i)).aborted)return{...n,cancelled:!0};let y=Ft("schedule.alapPass"),v=await Ka(A.reversed,h,p,this.adapter,t,i);if(Pt(y),(await ae(i)).aborted)return{...n,cancelled:!0};let E=Ft("schedule.diff"),T=[];for(let[R,O]of v){let N=this.adapter.getActivity(R);if(!N)continue;let X=N.startDate.getTime()!==O.startDate.getTime(),z=N.endDate.getTime()!==O.endDate.getTime();(X||z)&&T.push(R)}return Pt(E),Pt(a),{plans:v,updatedIds:T,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},Kd=!1;function zd(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Kd}function Ft(e){return{name:e,startedAt:performance.now()}}function qd(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Pt(e){if(!zd())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Jd(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=Wa(i,t);return Xd(n,t,r)}function Xd(e,t,r){let i=new Set(e.activityIds),n=new Set;for(let s of r.getAllActivities()){let o=String(s.id);s.constraintType===Y.ALAP&&!i.has(o)&&(n.add(o),i.add(o))}if(n.size===0)return{idSet:i,links:e.links};let a=[...e.links];for(let s of t)(n.has(String(s.source))||n.has(String(s.target)))&&a.push(s);return{idSet:i,links:a}}function Zd(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let s=i?Array.from(i):t;return Xe(s,r)}if(!i)return n;let a=ba(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function es(e,t,r){let i=t.getActivity(e);if(!i)return;let n=r?{...i,endDate:r.endDate}:i,a=t.calendarReader.getCalendar(String(i.calendarId));for(let s of t.getIncomingLinkIds(e)){let o=t.getLink(s);if(!o)continue;let c=t.getActivity(o.source);if(!c||c.constraintType==="alap"||Kt(i.type)&&(o.type===M.START_TO_FINISH||o.type===M.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=pi(c,n,o.type),f=hi.computeLagBetweenTasks(d,u,a);f!==o.lag&&Nt({kind:"update",linkId:o.id,lag:f},{port:t})}}function rs(e,t){let r=t.getActivity(e);r&&Kt(r.type)&&(r.durationHours=0)}function ce(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 cr(e){return Number(e.toFixed(2))}function lt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function le(e,t,r=!0,i={}){let n=t?tu(e,t):nu(e),a=r?i.progressMode??"freeze-when-no-contribution":"skip";await Qd(n,e,a,{recomputeRealWork:i.recomputeRealWork??!1})}function lr(e,t){is(e,t,"skip")}async function Qd(e,t,r,i={recomputeRealWork:!1}){let a=0;for(let s of e)is(s,t,r,i.recomputeRealWork),a+=1,a%200===0&&await at()}function tu(e,t){let r=new Set;for(let a of t)eu(a,e,r);if(r.size===0)return[];let i=Array.from(r),n=ns(i,e);return as(i,n)}function eu(e,t,r){let i=t.getParentId(e);for(;i&&!b(i);){if(r.has(i))return;r.add(i),i=t.getParentId(i)}}function ru(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+=iu(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 is(e,t,r="freeze-when-no-contribution",i=!1){let n=t.getActivity(e);if(!n)return;let a=t.getChildren(e);if(a.length===0)return;let s=ru(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=ce(s.weightedChildren);r!=="skip"&&(f!==null||r==="zero-when-no-contribution")&&t.setActivityField(e,"progress",cr(f??0)),i&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function iu(e,t){return t?Number(e.realWorkHours)||0:lt(e.workHours,e.progress)}function nu(e){let t=au(e),r=ns(t,e);return as(t,r)}function au(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function ns(e,t){let r=new Map;for(let i of e)r.set(i,su(i,t));return r}function su(e,t){let r=0,i=e;for(;i&&!b(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function as(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var ss={updateActivityDuration:rs,updateTaskTiming:cu("updateTaskTiming"),adjustLinkLagOnTaskMove:es,recordLastStartDate:ou};function ou(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Mt(e,t,r,i){for(let n of t){let a=n in ss?ss[n]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${n} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(e,r,i??null)}}function cu(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 x(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 K(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 os={targetField:"name",canEdit(){return U()},parseInput(e){return typeof e!="string"?x("not_a_string"):w(e)},validate(){return W()},transform(e,t){return F({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var cs={targetField:"description",canEdit(){return U()},parseInput(e){return typeof e!="string"?x("not_a_string"):w(e.trim())},validate(){return W()},transform(e,t){return F({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Ct(e){return e.constraintType??Y.ASAP}var dr=100;function de(e){return e.progress>=dr}function tt(e,t){return _t(e.type,t.hasChildren(e.id))}function ls(e){return e.progress>0}function ds(e){return e.hasLookaheadTasks}function Re(e,t){return Math.round(Math.ceil(e*t*60)/60)}var ue=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 Le(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(h=>h.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(h=>h.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 lu(e,t){let r=Jt(t);for(;!e.isWorkTime(r,nt.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Jt(r);return r}function yi(e,t){return e.getClosestWorkTime({direction:q.FUTURE,date:t,unit:nt.HOUR})}function mi(e,t){let r=lu(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:nt.HOUR})}var ur=new Set(["snet","snlt","mso"]),gi=new Set(["fnet","fnlt","mfo"]),Wt=new Set(["asap","alap"]),fr="snet";function Et(e,t,r){if(!ur.has(r)&&!gi.has(r))return e;let i=ur.has(r)?yi(t,e):mi(t,e),n=new Date(e);return n.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),n}var Rt=()=>({constraintType:fr});var Ut=e=>({constraintDate:e}),us=e=>({constraintDate:e});var fs={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var ps={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 fe(e,t,r){return _a(e,t,r)}function pe(e,t,r){return Pa(e,t,r)}var ys={targetField:"durationHours",canEdit(e,t){return de(e)?K("completed","cant_edit_completed_activity"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isNaN(i)?x("not_a_number"):w(r.inputUnit==="hours"?i:Re(i,r.hoursPerDay))},validate(e,t,r){return hs(r)?Q(ps.NEGATIVE_DURATION):du(t,r)?Q("unchanged"):W()},transform(e,t,r){if(hs(t))return F({},{autoSchedule:!1,postProcessors:[]});let i=uu(e,t,r),n=fu(e,t,r,i.violated);return{...F(n,{autoSchedule:!0,postProcessors:[fs.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:pe(i.constraintType,i.constraintDate,ms(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function hs(e){return Math.sign(e)===-1}function du(e,t){return e===t}function uu(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 fe(n,e.constraintDate,a)}function fu(e,t,r,i=!1){let n={};i&&Object.assign(n,Rt(),Ut(e.startDate));let a=Pe(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let s=ms(e,t,r);return s&&Object.assign(n,ue(s)),n}function ms(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var he=e=>({realWorkHours:e});var pu=0,hu=dr,gs=0,vs={targetField:"progress",canEdit(e,t){return ds(e)?K("has_lookahead_tasks","cant_edit_actvity_with_task"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?x("not_a_number"):w(t)},validate(e,t,r){return yu(r)?Q("out_of_range"):W()},transform(e,t,r){let i=mu(t),n=gu(t),a=Cu(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...he(a.get(e.id)??0)},o=n?vu(e,t,i,r.hierarchy,a):[],c=n?Su(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=n?Du(e,t):void 0;return F(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function yu(e){return e<pu||e>hu}function mu(e){return e===gs}function gu(e){return e===dr||e===gs}function vu(e,t,r,i,n){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:Au(t,r,n.get(s)??0)}))}function Au(e,t,r){return{progress:e,autoScheduling:t,...he(r)}}function Cu(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 Iu(e,t){let r=[e.id,...t.getDescendantIds(e.id)],i=a=>t.getChildProgressInfo(a).some(s=>t.hasChildren(s.id)),n=a=>t.getAncestorIds(a).length;return r.filter(a=>i(String(a))).map(String).sort((a,s)=>n(s)-n(a))}function Su(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=[...Iu(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of n){let o=ku(s,i,r);i.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function ku(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((ce(i)??0).toFixed(2))}function Du(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)?K("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)?x("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 Cs={targetField:"usedCost",canEdit(e,t){return tt(e,t)?K("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)?x("not_a_number"):w(r)},validate(){return W()},transform(e,t,r){let i=_u(e,t,r.hierarchy);return F({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function _u(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 Is={targetField:"workHours",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){if(String(e).trim()==="")return w(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?x("not_a_number"):w(t)},validate(){return W()},transform(e,t,r,i){let n=Ss(t,e.progress),a=String(i).trim()===""?[]:Pu(e,t,n,r.hierarchy);return F({workHours:t,...he(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Ss(e,t){return lt(e,t)}function Pu(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??Ss(d.workHours,d.progress);c+=u,l+=f}n.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...he(l)}})}return s}function pr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function vi(e,t){return e.getTime()<t.getTime()}function ye(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var hr=e=>({durationHours:e});var ks={targetField:"startDate",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):ls(e)?K("has_progress","cant_edit_activity_with_progress"):U()},parseInput(e,t,r){return ye(e)?w(Jt(e,"UTC")):x("invalid_date")},validate(e,t,r,i){if(pr(t,r))return Q("unchanged");let n=Eu(e,r,i);return n||W()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return F({startDate:t,...Rt(),...Ut(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let n=yi(i,t),a=e.type==="milestone",s=a?n:i.calculateEndDate(n,e.durationHours),o=n;return{...F({startDate:n,...ue(s),...a?hr(0):{},...Rt(),...Ut(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Ru(e,n,i)}},trackEvent:"activity_start_date_entry"};function Eu(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 Ru(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=_e(Ct(e),t,i),a=fe(Ct(e),e.constraintDate,n);if(a.violated)return pe(a.constraintType,a.constraintDate,n)}var Lu=99.999,Ts={targetField:"endDate",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):bu(e)?K("completed","cant_edit_completed_activity"):U()},parseInput(e,t,r){if(!ye(e))return x("invalid_date");let i=Jt(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,nt.DAY)?w(mi(n,i)):r.dateFormat.split(" ").length>1?w(i):w(n.getClosestWorkTime({direction:"past",date:i,unit:nt.HOUR})):w(i)},validate(e,t,r,i){if(pr(e.endDate,r))return Q("unchanged");if(wu(r,e))return Q("before_date_origin");if(Ou(r,e))return Q("before_start_date");let n=xu(r,e,i);return n||W()},transform(e,t,r){let i=Nu(e,t),n=Fu(e,t,r,!!i);return{...F(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function bu(e){return e.progress>=Lu}function wu(e,t){return t.dateOrigin?vi(e,t.dateOrigin):!1}function Ou(e,t){return vi(e,t.startDate)}function xu(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,nt.DAY)?null:Q("not_working_day"):null}function Nu(e,t){if(Ct(e)===Y.MSO)return;let i=_e(Ct(e),e.startDate,t),n=fe(Ct(e),e.constraintDate,i);if(n.violated)return pe(n.constraintType,n.constraintDate,i)}function Fu(e,t,r,i=!1){let n={};Kt(e.type)&&!i&&Ds(e)?Object.assign(n,Ut(e.startDate)):(i||Ds(e))&&Object.assign(n,Rt(),Ut(e.startDate));let o=Mu(e,t,r),c=Pe(e.durationHours,o);return c&&(n.type=c),Object.assign(n,hr(o)),n.endDate=t,n}function Ds(e){return Wt.has(Ct(e))}function Mu(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var Wu=new Set(Object.values(Y)),_s={targetField:"constraintType",canEdit(e,t){return de(e)?K("completed","cant_edit_completed_activity"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){let t=String(e).toLowerCase();return Uu(t)?w(t):x("invalid_constraint_type")},validate(){return W()},transform(e,t,r){let i=Bu(e,t,r);return F(i,{autoSchedule:!0})}};function Uu(e){return Wu.has(e)}function Bu(e,t,r){let i=ju(e,t);return{constraintType:t,...us(Hu(e,t,i,r))}}function Hu(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?Et(r,n,t):r}function ju(e,t){return Wt.has(t)?null:ur.has(t)?e.startDate:gi.has(t)?e.endDate:e.constraintDate}var Ps={targetField:"constraintDate",canEdit(e,t){return de(e)?K("completed","cant_edit_completed_activity"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){return ye(e)?w(e):x("invalid_date")},validate(){return W()},transform(e,t,r){let i=Es(e)?fr:Ct(e),n=r.calendars.getCalendar(e.calendarId),a=n?Et(t,n,i):t,s=Vu(e,a);return F(s,{autoSchedule:!0})}};function Vu(e,t){return{constraintDate:t,...Es(e)?Rt():{}}}function Es(e){return Wt.has(Ct(e))||!e.constraintType}var Rs={targetField:"calendarId",canEdit(){return U()},parseInput(e){let t=String(e).trim();return Yu(t)?x("empty_calendar"):w(t)},validate(e,t,r){return $u(e.calendarId,r)?Q("unchanged"):W()},transform(e,t,r){return F(Gu(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function Yu(e){return e===""}function $u(e,t){return e===t}function Gu(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,s=a?Ku(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,ue(n.calculateEndDate(c,e.durationHours)))}return i}function Ku(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var Ls={targetField:"customId",canEdit(){return U()},parseInput(e){if(e==null)return x("empty_custom_id");if(typeof e!="string")return x("not_a_string");let t=e.trim();return t.length===0?x("empty_custom_id"):t.length>20?x("exceeds_max_length"):w(t)},validate(){return W()},transform(e,t){return F({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var bs={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)?x("not_an_integer"):w(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?x("not_an_integer"):w(e):x("not_an_integer")},validate(){return W()},transform(e,t){return F({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function be(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 yr(e){return e.some(t=>be(t)===null)}var ws={targetField:"responsableIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):x("not_an_array")},validate(e,t,r){return yr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(be).filter(i=>i!==null);return F({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Os={targetField:"tagIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):x("not_an_array")},validate(e,t,r){return yr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(be).filter(i=>i!==null);return F({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var zu=new Map([[_.TEXT,os],[_.DESCRIPTION,cs],[_.DURATION,ys],[_.PROGRESS,vs],[_.COST,As],[_.USED_COST,Cs],[_.HH_WORK_TIME,Is],[_.START_DATE,ks],[_.END_DATE,Ts],[_.CONSTRAINT_TYPE,_s],[_.CONSTRAINT_DATE,Ps],[_.CALENDAR_ID,Rs],[_.CUSTOM_ID,Ls],[_.SUBCONTRACT_ID,bs],[_.RESPONSABLES,ws],[_.TAGS,Os]]);function Bt(e){return zu.get(e)}function me(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"},Ai={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};var qu=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],xs=new Set(qu);function Z(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Ns(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function ge(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:Dt(e.constraintDate),dateOrigin:Dt(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:Dt(t.startDate),endDate:Dt(t.endDate)})),baselineSnapshot:Ju(e.baselineSnapshot),criticalPath:Xu(e.criticalPath)}}function Dt(e){return e===null?null:new Date(e)}function Ju(e){return e===null?null:{...e,startDate:Dt(e.startDate),endDate:Dt(e.endDate)}}function Xu(e){return e===null?null:{...e,earlyStart:Dt(e.earlyStart),earlyFinish:Dt(e.earlyFinish),lateStart:Dt(e.lateStart),lateFinish:Dt(e.lateFinish)}}function Ht(e,t){let r=new Set([String(e)]);for(let i of t.cascadeMutations??[])r.add(String(i.activityId));return r}function V(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 ge(e)}function jt(e,t,r){Fs(e,t,r.patch);for(let i of r.cascadeMutations??[])Fs(e,i.activityId,i.fields)}function Fs(e,t,r){for(let[i,n]of Object.entries(r)){if(!xs.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);Z(e,t,i,n)}}function Ms(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=Ii(s,a);s&&Object.keys(o).length===0||(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 Ii(e,t){let r={},i=e??{},n=t,a=new Set([...Object.keys(i),...Object.keys(n)]);for(let s of a)(Object.hasOwn(i,s)!==Object.hasOwn(n,s)||!Ci(i[s],n[s]))&&(r[s]={before:i[s],after:n[s]});return r}function Ci(e,t){if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,o)=>Ci(s,t[o]));if(typeof e!="object"||typeof t!="object")return!1;let r=e,i=t,n=Object.keys(r),a=Object.keys(i);return n.length!==a.length?!1:n.every(s=>Object.hasOwn(i,s)&&Ci(r[s],i[s]))}function mr(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 Si(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 gr(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)}}var Zu=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Lt(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(Zu);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 ve(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 Qu=e=>e.type==="project",tf=(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:Lt(String(s));return ve(a(e.startDate),a(e.endDate),t,n)};function ef(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(!Qu(o)){let d=tf(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),h=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*h}let l=c/100;return n(s,l),l};for(let s of e)a(s);return i}function bt(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),ef(r,t,e)}function rt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var rf=e=>e.type==="project",nf=e=>rt(e),af=(e,t,r,i)=>{let n=nf(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:ve(n.startDate,n.endDate,t,a)};function ki(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(!rf(c)){let u=af(c,t,r,i);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),h=r.getActivity(u),g=typeof h?.ponderator=="number"?h.ponderator:0;l+=f*g}let d=l/100;return a(o,d),d};for(let o of e)s(o);return n}function Vt(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)}),ki(n,t,i,r)}var Ws=e=>Math.round(e*100)/100;function sf(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function of(e,t){let r=Ws(e),i=Ws(t);return r>99.99?Ot.DONE:i>r?Ot.OVERDUE:e>0&&r>i?Ot.ADVANCEMENT:e===0&&t===0?Ot.WAITING:e>0&&r<i?Ot.DOING:Ot.WAITING}function It(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,s=of(a,sf(i,t));i.status!==s&&(Z(e,n,$e,s),r.push(n))}),r}function Di(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:()=>Di(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}Di.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var ht=Di;function cf(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function vr(e){return cf(e)&&!isNaN(e.getTime())}function I(e,t,r,i){if(!vr(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(!vr(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 lf=e=>e?e.$level===1:!1,df=e=>e.type==="project",uf=e=>e.$level!==0,ff=e=>e.type==="task",pf=e=>e.type==="task"||e.type==="milestone",st={byFirstLevel:lf,filterByParentType:df,avoidSubproject:uf,byTaskType:ff,byTaskTypeAndMilestone:pf};var m=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 Zt(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Us(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=hf({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=yf({gantt:t,subprojectsWithNoLinks:a}),o=mf({gantt:t,childrenIds:s,linkProperty:n,getArrayOfLinkedActivities:gf,calculations:i});return new Set(o.map(c=>c.id))}catch(a){throw a}}function hf(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(st.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function yf(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=st.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>i.add(o));return[...i]}function mf(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 gf(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 Bs({gantt:e,linkProperty:t,direction:r}){try{let i=vf(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Af(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function vf(e,t){return e.getTaskByTime().filter(st.avoidSubproject).filter(st.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Af(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 Hs({gantt:e,direction:t,linkProperty:r}){try{let i=Cf(e),n=new Set,a=new Set,s=new Set;t==="backward"&&kf(i).forEach(d=>{n.add(d.id)});let o=If(i,t,r),c=Sf(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 Cf(e){return e.getTaskByTime().filter(st.filterByParentType).filter(st.avoidSubproject)}function If(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 Sf(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function kf(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function js({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),s=Df(r),o=Tf(r),c=a[s];if(!Array.isArray(c))return;_f(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function Df(e){return e==="forward"?"$source":"$target"}function Tf(e){return e==="forward"?"target":"source"}function _f(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var we={identifySecondLevelActivities:Us,identifyInitialActivities:Bs,identifyParentsWithAndWithoutLinks:Hs,identifyForbiddenActivities:js};function Ar(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Ti({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}):Oe(r,e,i,n)}function Vs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:I(r,n,e,i),ef:n}}function Ys({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 Oe(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 _i=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=Ar(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=Zt(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=Ys({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=Vs({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=Ti({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity);t>0&&(n=Oe(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=Ti({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=Oe(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=Oe(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},$s=_i;var Pi=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=Zt(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)}},Gs=Pi;function Ks(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:s}=e,o=t[r],c=Pf(t),l=null;if(s==="forward"){let d=Ef(o,i,n,a);l=new $s(d,t,a),l=l.calculate()}else{let d=Rf(o,i,n,a);l=new Gs({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function Pf(e){return{duration:e.duration,calendarId:e.calendar_id}}function Ef(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 Rf(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 Js(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(Lf(t.id,r))return null;let a=bf(t.id,i),s=wf(a,r);return s.length===0?null:Of(s,n)}function Lf(e,t){return t.has(e)}function bf(e,t){let r=t.get(e);return r?r.childrens:[]}function wf(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Of(e,t){if(t==="forward"){let r=zs(e,"es"),i=qs(e,"ef");return{es:r,ef:i}}else{let r=zs(e,"ls"),i=qs(e,"lf");return{ls:r,lf:i}}}function zs(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function qs(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var Ei={parentWithLinks:Ks,parentWithNoLinks:Js};var Ri=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=[m.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=Ei.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=Ei.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)})}},Xs=Ri;var Li=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(st.byFirstLevel).filter(st.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}}},Zs=Li;var bi=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(st.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=we.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=we.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 Zs({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=we.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}=we.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=[m.ASAP,m.ALAP,m.SNET,m.FNET],o=t.constraint_type||m.ASAP;if(s.includes(o))n=this.projectDates.end_date,i=I(r,n,-a,t);else{let c=[m.SNLT,m.MSO],l=[m.FNLT,m.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||m.ASAP,a=this.projectDates.end_date,s=[m.ASAP,m.ALAP,m.SNET,m.FNET],o=[m.SNLT,m.FNLT];if(s.includes(n))i=Math.max(t.end_date,a);else if(n===m.MSO)i=t.end_date;else if(n===m.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 Xs({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()}},Yt=bi;function xf(e,t,r){let i={es:null,ef:null};if(!e)return i;if([m.SNET,m.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if([m.FNLT,m.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}else if(t===m.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if(t===m.MFO){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}return i}var Cr=xf;var wi=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})}},Qs=wi;var xe=class extends Qs{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Yt(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 Ar(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Oi=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}},Ir=Oi;var xi=(e,t)=>()=>t()===e;var Ni=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var Nf=16,Ne=async e=>performance.now()-e>Nf?(await at(),performance.now()):e;var Fe=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 Ne(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await Ne(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 Fi=class extends Yt{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 Ir({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 Fe({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||m.ASAP,s=[m.SNET,m.SNLT,m.FNLT,m.FNET],o=[m.ASAP,m.ALAP,m.SNET,m.FNET,m.SNLT,m.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 xe({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===m.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new xe({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===m.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let h=Cr(i,a,c);if(s.includes(a)&&(this.constraintsMap.set(r,h),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,h,{es:d,ef:u})),[m.MSO,m.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,h),i.progress===0)d=h.es,u=h.ef;else{let g=i.end_date;a===m.MFO&&(g=Math.max(h.ef,i.end_date)),d=i.start_date,u=g}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=[m.SNET,m.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)}},to=Fi;var Mi=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===m.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===m.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===m.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})}},eo=Mi;var Wi=class extends eo{constructor(t){super(t),this.constraint=t.constraint||m.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Yt(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===m.ALAP)return m.ALAP;if(this.constraint===m.FNET||this.constraint===m.SNET)return"snet-fnet";if(this.constraint===m.FNLT)return m.FNLT}getSpecialParamForSf(){return!![m.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![m.MFO,m.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===m.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.SNET||this.constraint===m.SNLT||this.constraint===m.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===m.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===m.ALAP||this.constraint===m.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===m.ASAP)return new Date(Math.max(i,n));if(r===m.FNET||r===m.FNLT){let s=Math.min(i,a);return new Date(Math.max(i,s))}if(r===m.ALAP)return new Date(Math.min(i,n))}},ro=Wi;function Ff(e,t,r){let i={ls:null,lf:null};return r===m.MSO&&(i.ls=t.constraint_date,i.lf=I(e,i.ls,t.duration,t)),r===m.MFO&&(i.lf=t.constraint_date,i.ls=I(e,i.lf,-t.duration,t)),i}var io=Ff;var Ui=class extends Yt{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 Ir({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 Fe({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||m.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===m.MSO||a===m.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,a);return}if(a===m.MSO||a===m.MFO){this.recalculateInBaseRestriction(i,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===m.SNLT||a===m.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=Cr(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===m.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===m.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 ro({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=io(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([m.ASAP,m.ALAP,m.SNET,m.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([m.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([m.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)}[m.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[m.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}},no=Ui;function ao(){return null}var so=({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 Bi=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=m.ASAP),t===m.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===m.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===m.SNET||t===m.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===m.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===m.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===m.MSO||t===m.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===m.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===m.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)})}},oo=Bi;var Hi=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===m.MSO||t===m.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=m.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=m.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=0;return[m.SNLT,m.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=m.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===m.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===m.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===m.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Zt(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let a=({direction:s,constraint:o=m.ASAP})=>o===m.ALAP?this.backwardMap.get(n)[s]:this.forwardMap.get(n)[s];if(t===m.ASAP||t===m.SNET||t===m.FNET||t===m.MSO||t===m.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===m.ALAP)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:m.ALAP,direction:"lf"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:m.ALAP,direction:"ls"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:m.ALAP,direction:"lf"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:m.ALAP,direction:"ls"})}};if(t===m.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===m.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===m.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)}},co=Hi;var lo=e=>({totalFloat:new oo(e.totalFloat).getTotalFloat(),freeFloat:new co(e.freeFloat).getFreeFloat()});var ji=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=so({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:h}=lo(u);o.set(l,f),c.set(l,h),s=await Ne(s)}return{totalFloatMap:o,freeFloatMap:c}};var Vi=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=xi(i,this.getCurrentCalculationId),a=()=>n()&&r();try{let s=t||this.gantt;if(this.gantt=s||ao(),Ni(this.gantt))return!1;let o=new to(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new no(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 ji({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}}}},uo=Vi;var Mf=e=>e==="fnet"||e==="fnlt"||e==="mfo",Wf=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Uf(e,t){let r=e.constraintDate;if(!r||!Mf(e.constraintType))return r;let i=Wf(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()?si(e,t):r}function Bf(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 Hf(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 jf(e){let t=Hf(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:Uf(i,e)})}),r}function Vf(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 Yf(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 fo(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=Bf(u);return r.set(l,f),f},n=Yf(e);await at();let a=jf(e);await at();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await at();let o=Vf(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 $f=1e3;function Gf(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 Yi(e,t,r=()=>!0){if(!r())return null;let i=await fo(e,t);if(!r())return null;let n=new uo(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>=$f&&(l=0,await at(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,Gf(d,f,s))}return r()?c:null}async function Sr(e,t,r=()=>!0){let i=await Yi(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 $t(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=rt(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 po=new Set;var ho=new Set(["activity-outdent","activity-indent"]);var Me=new Set([_.TEXT,_.DESCRIPTION,_.COST,_.USED_COST,_.CUSTOM_ID,_.RESPONSABLES,_.SUBCONTRACT_ID,_.TAGS]),Kf=new Set(["selection-toggle","selection-replace","visibility-set","sir-sync","activity-lookahead-sync","persistence-acknowledge","baseline-apply","ponderator-criterion-set","status-criteria-set"]),zf=new Set;function qf(e){return e.kind==="inline-edit"?Me.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Me.has(t.column)):!1}function $i(e,t){return!(Kf.has(e.kind)||t.has(e.kind)||qf(e))}function mo(e){return $i(e,zf)}function We(e){return $i(e,po)}function go(e){return $i(e,ho)}function Gi(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===_.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===_.PROGRESS):!1}function Jf(e){return go(e)&&Gi(e)}var yo=new Set([_.PROGRESS,_.HH_WORK_TIME,_.DURATION,_.COST,_.USED_COST,_.REAL_COST]);function Xf(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?yo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>yo.has(t.column)):!1}var it={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 vo(e,t,r){let i=new Set;t.ran&&i.add(it.AUTOSCHEDULE),i.add(it.PARENT_BOUNDS),Xf(e)&&i.add(it.PARENT_PROGRESS),Gi(e)&&i.add(it.REAL_WORK);let n=!r.skipAutoSchedule;return n&&go(e)&&i.add(it.EXPECTED_PROGRESS),n&&Jf(e)&&i.add(it.REAL_COST),n&&We(e)&&!r.skipCriticalPath&&i.add(it.CRITICAL_PATH),i}async function $(e,t){let r=Zf(t);r.has(it.AUTOSCHEDULE)&&await rp(e.adapter,t);let i=r.has(it.AUTOSCHEDULE)?await Qf(e,t.autoscheduleFrom):ep();return await ip(e.adapter,t,i.scheduledIds,r),await np(e,r,t.now),i}function Zf(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,i=new Set(vo(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&i.add(it.PARENT_PROGRESS),i}async function Qf(e,t){let r=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(r),n=tp(e.adapter,i.updatedIds);return Ee(e.adapter,i),n}function tp(e,t){let r=[];for(let i of t){let n=String(i);r.push(n);let a=e.getActivity(n);a&&e.noteScheduledBefore(n,a)}return{scheduledIds:r}}function ep(){return{scheduledIds:[]}}async function rp(e,t){let r=t.collectDirty?t.collectDirty([]):Si(t.recomputeParentsFrom,[]);r.size!==0&&await le(e,r,!1)}async function ip(e,t,r,i){let n=t.collectDirty?t.collectDirty(r):Si(t.recomputeParentsFrom,r);await le(e,n,i.has(it.PARENT_PROGRESS),{recomputeRealWork:i.has(it.REAL_WORK),progressMode:t.recomputeParentProgress?"zero-when-no-contribution":"freeze-when-no-contribution"})}async function np(e,t,r){t.has(it.EXPECTED_PROGRESS)&&r!==null&&(ap(e.adapter)&&Vt(e.adapter,r,e.defaultBaseCalendarId??null),bt(e.adapter,r),It(e.adapter,e.sector.statusCriteria)),t.has(it.REAL_COST)&&$t(e.adapter),t.has(it.CRITICAL_PATH)&&await Sr(e.adapter,e.sector.hoursPerDay)}function ap(e){let t=!1;return e.forEachActivity(r=>{rt(r)&&(t=!0)}),t}var sp=new Set([_.CONSTRAINT_TYPE,_.CONSTRAINT_DATE]),op=new Set(["mso","mfo"]);function kr(e){return sp.has(e)}function Dr(e){return e===_.CONSTRAINT_DATE}function Tr(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let a=n.constraintType;if(!a||Wt.has(a)||op.has(a))return!1;let s=Ki(n.startDate),o=Ki(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=cp(t,a,String(n.calendarId??""),i),l=Ki(n.constraintDate);return lp(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function cp(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?Et(e,n,t):e}function Ki(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 lp(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function _r(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n}=await $(e,Ao(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=i(s,o);a=a||c}if(a){let s=await $(e,Ao(t));n=up(n,s.scheduledIds)}return We(t.action)&&await $(e,dp(t)),{scheduledIds:n}}function Ao(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function dp(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function up(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function fp(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 zi(e,t,r){let i=[];for(let n of r){let a=e.get(n);if(!a)continue;let s=a.pendingRequestIds??[];if(!ne({pendingRequestIds:s}))continue;let o=t.getActivity(n),c=o==null;if(!c&&!fp(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 j(e,t){let r=pp(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let l=yp(n);hp(e,n,l,i,r)}let a=t.sirDetection==="before-diff"?zi(i,e,r):[],s=Ms(e,i,r),o=t.sirDetection==="after-diff"?zi(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 pp(e,t){let r=new Set;for(let i of t.touchedIds)r.add(i);for(let i of t.scheduledIds)r.add(i);if(t.includeAllIds)for(let i of e.getAllIds())r.add(i);return r}function hp(e,t,r,i,n){for(let a of t.dirty){if(r.has(a)||i.has(a))continue;let s=t.before.get(a),o=e.getActivity(a);!s||!o||Object.keys(Ii(s,o)).length!==0&&(i.set(a,s),n.add(a))}}function yp(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function St(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 Pr(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:St(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:St(c)})}return i}function Ae(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 Ce(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:St(a)})}return i}function Er(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=Bt(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);mp(e.column)&&a.invalidateExpandedLinksCache(),e.column===L.PARENT&&a.invalidateAllCaches();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??P.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??P.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??P.INVALID,alertKey:f.notification?.messageKey};if(e.column===_.CUSTOM_ID&&d.value!==null){let T=i.getActivity(e.activityId),R=T?T.customId:null,O=typeof R=="string"?R:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),O))return{ok:!1,reason:P.CUSTOM_ID_DUPLICATE}}let h=o.transform(c,d.value,n,d.raw),g=Ht(e.activityId,h),C=V(i,g),A=Ae(i,String(e.activityId)),k=c.constraintDate;jt(i,e.activityId,h),Mt(e.activityId,h.postProcessors??[],i,C.get(String(e.activityId))??null);let S=Ce(A,i,String(e.activityId));if(e.column===_.CUSTOM_ID){let T=C.get(String(e.activityId)),R=T?T.customId:null,O=typeof R=="string"?R:null,N=typeof d.value=="string"?d.value:null;O!==N&&r.customIdTracker.trackCustomIdChange(O,N)}let D=()=>({action:e,autoscheduleFrom:h.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:T=>mr(e.activityId,g,T),now:r.now,options:t}),p=kr(e.column),{scheduledIds:y}=await(p?_r({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:D(),revertTargets:Dr(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:k}],revert:(T,R)=>Tr(T,R,i,n.calendars)}):$({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},D())),v=(h.trackingEvents??[]).map(T=>({name:T.name,properties:T.properties??{}})),E=me(e.activityId,h.constraintWarning);return{ok:!0,changes:j(i,{source:e,beforeSnap:C,touchedIds:g,scheduledIds:y,sirDetection:"before-diff",links:S,trackingEvents:v,...E?{warnings:[E]}:{},hoursPerDay:s.hoursPerDay})}}function mp(e){return e===_.DURATION||e===L.AUTO_SCHEDULING}function gp(e,t){let r=new Set,i=new Map;for(let n of e){if(n.kind==="create"){r.add(String(n.source)),r.add(String(n.target));continue}let a=t.getLink(n.linkId);a&&(r.add(String(a.source)),r.add(String(a.target)),i.set(n.linkId,{...a}))}return{activityIds:r,links:i}}function vp(e,t,r,i){return e.map((n,a)=>{let s=n.kind==="create"?i?.get(a):void 0,o=Nt(n,{port:t,newLinkId:s?()=>s:r.next});return{op:n,finalLinkId:o.applied?o.linkId:null,rejected:o.applied?null:o.rejected??"link_op_rejected"}})}function Ap(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function Io(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let i=e.type;if(i!==void 0&&!Object.values(M).some(a=>a===i))return{ok:!1,reason:P.INVALID_LINK_TYPE};let n=e.lag;if(n!==void 0&&!Number.isFinite(n))return{ok:!1,reason:P.INVALID_LINK_LAG}}return qi([Dp(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function So(e,t,r){let{hoursPerDay:i}=r.sector,n=e.operations.map(s=>Ip(s,i)),a=Cp(e.operations);return qi(n,e,t,r,a)}function Cp(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 Ip(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 qi(e,t,r,i,n){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=i;s.invalidateAllCaches();let{activityIds:l,links:d}=gp(e,a),u=V(a,l),f=vp(e,a,c,n);if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let h=Sp(f,d,a),{scheduledIds:g}=await $({adapter:a,scheduler:s,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:h,recomputeParentsFrom:l,now:i.now,options:r}),C=Pr(f,d,a);return{ok:!0,linkVerdicts:f.map((A,k)=>A.rejected===null?{operationIndex:k,kind:A.op.kind,ok:!0,linkId:String(A.finalLinkId)}:{operationIndex:k,kind:A.op.kind,ok:!1,reason:A.rejected}),__beforeLinks:Ap(d),changes:j(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:g,links:C,hoursPerDay:o.hoursPerDay})}}function Sp(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=kp(i.op,t,r);if(n!==null)return r.hasChildren(n)?"roots":String(n)}return null}function kp(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 Dp(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 ko(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:P.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let s=e.column===_.CUSTOM_PREDECESSORS,{specs:o}=ir(e.newValue),c=o.map(g=>({...g,lag:pt(g.lag,n.hoursPerDay)})),l=new Map;i.forEachActivity(g=>{g.correlativeId!=null&&l.set(String(g.correlativeId),g.id)});let d=g=>l.get(g)??null,u=s?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let g of u){let C=i.getLink(g);C&&f.push(C)}let h=s?ar({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):sr({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return qi(h.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 Ji=Number.MAX_SAFE_INTEGER;function Qt(e,t){let r=Zi(e,t);return r.sort(Qi),r.map(i=>String(i.id))}function To(e){let t=[],r=n=>{t.push(n);let a=Qt(String(n.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},i=Qt("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function _o(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=Po(i),a=Qt(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&&!Tp(t,c))return c}return null}function Xi(e,t){let r=t.getActivity(e);if(!r)return-1;let i=Po(r);return Qt(i,t).findIndex(a=>String(a)===String(e))}function Zi(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 Qi(e,t){let r=Do(e),i=Do(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Do(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Ji}function Po(e){let t=e.parentId;return t===null?"0":t}function Tp(e,t){return e.has(t)?!0:e.has(String(t))}function ct(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{b(a.parentId)&&t.push(a)}),t.sort(Lo);let r=[];Eo(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),_p(a,n)}n+=1;let s=Zi(String(a.id),e);s.sort(Lo),Eo(r,s)}return i}function Eo(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function Ro(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Ji}var Lo=(e,t)=>Ro(e)-Ro(t);function _p(e,t){e.correlativeId=t}function en(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=tn(l,L.WORK_HOURS),u=Pp(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||b(o))break;r=o}}function bo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||b(i)||en(i,t)}function tn(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Pp(e,t,r,i){return i.hasChildren(e)?tn(t,L.REAL_WORK_HOURS):lt(r,tn(t,L.PROGRESS))}function rn(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+=Ep(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||b(s))break;r=s}}function wo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||b(i)||rn(i,t)}function Ep(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function nn(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+=Rp(c,L.COST))}t.setActivityField(r,L.COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||b(s))break;r=s}}function Oo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||b(i)||nn(i,t)}function Rp(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var Rr=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}),xo="New Master Plan",No="New Activity";var Lp=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Fo=new Set(Lp);function bp(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"||!Fo.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function Mo(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=bp(e.activityOverrides??{}),n=e.numTasksInGantt===0?xo:No,a=i.name??n,s=i.durationHours??e.sector.hoursPerDay,o=i.calendarId??e.sector.defaultCalendar,c=wp(r,e.fallbackStartDate,i.startDate),l={...Rr,...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 wp(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Op(e){let t=e.type;if(t!=="task"&&t!=="milestone")return null;let r=e.startDate,i=e.endDate;return!(r instanceof Date)||!(i instanceof Date)?null:{type:t,startDate:new Date(r),endDate:new Date(i),durationHours:Number(e.durationHours??0),expectedProgressBaseline:typeof e.expectedProgressBaseline=="number"?e.expectedProgressBaseline:null,constraintType:e.constraintType??null,constraintDate:e.constraintDate instanceof Date?new Date(e.constraintDate):null,progress:Number(e.progress??0)}}function Ie(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&xt(t.type):xp(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=ui,(e.promotionSource??"create")==="create"&&(a.constraintType=Y.ASAP,a.constraintDate=null,a.progress=0,a.expectedProgressBaseline=0)),{parentId:e.parentId,fields:a,promotionSnapshot:Op(t)}}function xp(e){return xt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Lr(e,t,r,i){let n=t,a=n==="0",s=an(e,n);if(i!==void 0){let c=s.find(l=>l.id===i);if(c){let l=ot(c),d=s.map(ot).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=ot(c),d=s.map(ot).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(ot))+1}var te=Number.MAX_SAFE_INTEGER,Wo=Number.MAX_SAFE_INTEGER-1;function ot(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:te}function an(e,t){let r=[];return e.forEachActivity(i=>{zt(i.parentId)===t&&r.push(i)}),r}function Uo(e,t,r){let i=e,n=Gt(e,r);for(;n!=null&&t.has(n);)i=n,n=Gt(n,r);return i}function Gt(e,t){let r=t.getActivity(e);if(!r)return null;let i=zt(r.parentId),n=Qt(i,t),a=n.findIndex(s=>String(s)===String(e));return a<=0?null:n[a-1]??null}function Bo(e,t,r,i){let n=Qt(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(ot);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 sn(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;n.invalidateAllCaches();let l=Np(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,h=Mp(e.activityId,i,o),g=c.next(),C={id:h,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Vp(s)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:g,activityOverrides:e.overrides??{}},k=Mo(C,{getActivity:v=>i.getActivity(v),calculateEndDate:v=>i.calculateEndDate(v),getClosestWorkTime:v=>i.getClosestWorkTime(v)}).newTask;k.realWorkHours=lt(k.workHours,k.progress),Up(k,e,t,u,d,r);let S=Lr(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);k.correlativeId=S;let D=new Set([h]);d&&D.add(d.id);let p=d!==null&&i.getChildren(d.id).length===0,y=r.skipBeforeSnap?new Map:V(i,D);return i.addActivity(k),Bp(e,h,d,i,r.preserveParentCustomId??!1,p),bo(h,i),wo(h,i),Oo(h,i),Hp(i,h,y,D,r),{ok:!0,newId:h,parent:d,newActivity:k,beforeSnap:y,initialTouched:D}}function Np(e,t){let r=b(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:P.PARENT_NOT_FOUND};if(i!==null&&ne(i))return{ok:!1,reason:P.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:P.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=Fp(e,t,r,s);return o||{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function Fp(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:P.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==a?{ok:!1,reason:P.ANCHOR_SIBLING_WRONG_PARENT}:null}function Mp(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function Wp(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function Up(e,t,r,i,n,a){let{adapter:s,customIdTracker:o}=r,c=Wp(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 Bp(e,t,r,i,n,a){if(!r)return;let s=Ie({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);s.promotionSnapshot&&i.setPromotionSnapshot(s.parentId,s.promotionSnapshot)}}function Hp(e,t,r,i,n){if(n.skipCorrelativeRecompute)return;let a=ct(e);n.skipBeforeSnap||gr(e,a,new Set([String(t)]),r,i)}function jp(e,t,r,i,n){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c}=r,l={name:yt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:s.durationHours}};return t.eventSource!==void 0&&(l.properties.event_source=t.eventSource),j(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:i,trackingEvents:[l],hoursPerDay:n})}async function Ho(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=sn(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}=l;return{ok:!0,changes:jp(i,e,s,d,a.hoursPerDay)}}function Vp(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 Yp(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:P.ANCHOR_SIBLING_NOT_FOUND}}let r=e.parentId,n=an(t,r).sort((a,s)=>ot(a)-ot(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:n}}function $p(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function jo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=Yp(e.destination,i);if(!s.ok)return s;let o=V(i,new Set),c=new Set,l=new Map,d=[],u;for(let k of e.activities){let S=l.get(k.originalParentId),D,p,y;S!==void 0?D=S:(D=s.parentId,u===void 0?(p=s.firstAfter,y=s.firstBefore):p=u);let v=sn({kind:"activity-create",parentId:D,afterSiblingId:p,beforeSiblingId:y,...k.activityId?{activityId:k.activityId}:{},overrides:$p(k.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,...S!==void 0?{customIdReferenceId:e.referenceActivityId,preserveParentCustomId:!0}:{}});if(!v.ok)return v;if(k.baselineSnapshot!==void 0){let E=k.baselineSnapshot;i.setActivityField(v.newId,"baselineSnapshot",E?{...E,startDate:E.startDate?new Date(E.startDate):null,endDate:E.endDate?new Date(E.endDate):null}:null)}l.set(k.originalId,v.newId),d.push(v.newId),S===void 0&&(u=v.newId)}let f=ct(i),h=new Set(d.map(String));gr(i,f,h,o,c);for(let k of d)c.add(String(k));let g=[];for(let k of e.links){let S=l.get(k.source),D=l.get(k.target);if(S===void 0||D===void 0)continue;let p={kind:"create",source:S,target:D,type:k.type,lag:pt(k.lag,a.hoursPerDay)},y=Nt(p,{port:i,newLinkId:k.linkId?()=>k.linkId:r.linkIdGen.next});g.push({op:p,finalLinkId:y.applied?y.linkId:null,rejected:y.applied?null:y.rejected??"link_op_rejected"})}let{scheduledIds: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}),A=Pr(g,new Map,i);return{ok:!0,changes:j(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:C,links:A,hoursPerDay:a.hoursPerDay})}}function Vo(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:P.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 Yo(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:P.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 wt(e,t){en(e,t),rn(e,t),nn(e,t)}function $o(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 Go(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 Gp(e){return e?{type:e.type,startDate:new Date(e.startDate),endDate:new Date(e.endDate),durationHours:e.durationHours,expectedProgressBaseline:e.expectedProgressBaseline,constraintType:e.constraintType,constraintDate:e.constraintDate?new Date(e.constraintDate):null,progress:e.progress}:null}function Kp(e,t,r){let i=e.startDate;return!r||!(i instanceof Date)?{}:{endDate:r(i,t)}}function Se(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=Gp(e.promotionSnapshot)??(i?{type:se,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Kp(t,r,e.computeEndDate)}:{type:se});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 Ko(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 zo(e,t,r){let{adapter:i,scheduler:n,customIdTracker:a,sector:s}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:P.ACTIVITY_IDS_EMPTY};for(let y of e.activityIds)if(!i.getActivity(y))return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let o=$o(e.activityIds,i),c=Go(o,i),l=new Set;for(let y of e.activityIds){let v=i.getActivity(y);if(!v)continue;let E=v.parentId;if(b(E))continue;let T=String(E);o.has(T)||l.add(T)}let d=new Set([...o,...l]),u=V(i,d),f=new Map;for(let y of c){let v=i.getLink(y);v&&f.set(y,{...v})}let h=new Set;for(let y of o){let v=i.getActivity(y);if(!v)continue;let E=b(v.parentId)?null:i.getActivity(String(v.parentId)),T=E?.hasNewActivities===!0&&E.newActivityIds.some(O=>String(O)===String(y));(v.isNewActivity===!0||T)&&h.add(y);let R=v.customId;typeof R=="string"&&R.length>0&&a.releaseCustomId(R)}for(let y of c)i.removeLink(y);let g=qp(i,o);for(let y of o)i.removeActivity(y);for(let y of l){let v=i.getActivity(y);if(!v)continue;zp(v,h,i);let E=i.getChildren(y),T=Se({parent:v,remainingChildIds:E.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(y),computeEndDate:(R,O)=>i.calculateEndDate({startDate:R,durationHours:O,task:v}),idsRemoved:o});if(!T){lr(y,i);continue}for(let[R,O]of Object.entries(T.fields))Z(i,y,R,O);if(v.customId==null||v.customId===""){let R=Gt(y,i),O=R?i.getActivity(R)?.customId:null,N=a.generateCustomIdForRestoredChild(typeof O=="string"&&O?O:null);i.setActivityField(y,L.CUSTOM_ID,N)}}for(let y of l)wt(y,i);let C=ct(i);for(let y of C){if(d.add(y.activityId),u.has(y.activityId))continue;let v=i.getActivity(y.activityId);if(!v)continue;let E=J(v);y.before!==void 0&&(E.correlativeId=y.before),u.set(y.activityId,E)}let{scheduledIds:A}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),k={name:yt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(k.properties.event_source=e.eventSource);let S=new Map;for(let[y,v]of f)S.set(y,v);let D=new Map;for(let y of o){let v=u.get(String(y));v&&D.set(String(y),v)}let p=j(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:A,sirDetection:"after-diff",links:Jp(f),trackingEvents:[k],hoursPerDay:s.hoursPerDay});return{ok:!0,changes:g.length>0?{...p,viewState:g}:p,__beforeSnap:D,__beforeLinks:S}}function zp(e,t,r){let i=Ko({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))Z(r,i.parentId,n,a)}function qp(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 Jp(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 br(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)||(qo(s,a,t)||qo(a,s,t))&&i.push(String(n.id))}return i}function qo(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||b(s))return!1;let o=s;if(o===t)return!0;i=o}return!1}async function Jo(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:P.ACTIVITY_NOT_FOUND};let o=b(e.parentId);if(!o&&!i.getActivity(e.parentId))return{ok:!1,reason:P.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:P.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:P.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let y=i.getActivity(c);if(!y)return{ok:!1,reason:P.ANCHOR_SIBLING_NOT_FOUND};if((y.parentId===null?"0":String(y.parentId))!==e.parentId)return{ok:!1,reason:P.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=zt(l),u=String(e.parentId),f=d!==u,h=new Set([e.activityId]);f?(d!=="0"&&h.add(d),u!=="0"&&h.add(u)):d!=="0"&&h.add(d);let g=V(i,h);f&&i.setActivityField(e.activityId,L.PARENT,u);let C=Lr(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,L.CORRELATIVE_ID,C),f){if(!o){let y=i.getActivity(e.parentId);if(y){let v=y.customId,E=xt(y.type)&&i.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,T=Ie({parentId:e.parentId,newChildId:e.activityId,getParent:R=>i.getActivity(R)??null,isCurrentlyLeaf:E,promotionSource:"reparent"});if(T){for(let[R,O]of Object.entries(T.fields))Z(i,T.parentId,R,O);T.promotionSnapshot&&i.setPromotionSnapshot(T.parentId,T.promotionSnapshot),T.fields.customId===null&&Er(v,r.customIdTracker)}}}if(d!=="0"){let y=i.getActivity(d);if(y){let v=i.getChildren(d),E=Se({parent:y,remainingChildIds:v.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(T,R)=>i.calculateEndDate({startDate:T,durationHours:R,task:y}),idsRemoved:new Set([e.activityId])});if(E){for(let[X,z]of Object.entries(E.fields))Z(i,d,X,z);let T=Gt(d,i),R=T?i.getActivity(T)?.customId:null,O=typeof R=="string"&&R?R:null,N=r.customIdTracker.generateCustomIdForRestoredChild(O);i.setActivityField(d,L.CUSTOM_ID,N)}}}}f&&(d!=="0"&&wt(d,i),o||wt(e.parentId,i));let A=ct(i);for(let y of A){if(h.add(y.activityId),g.has(y.activityId))continue;let v=i.getActivity(y.activityId);if(!v)continue;let E=J(v);y.before!==void 0&&(E.correlativeId=y.before),g.set(y.activityId,E)}let k=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:S}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...k],now:r.now,options:t,recomputeParentProgress:f}),D=f?br([e.activityId],i):[],p={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:D.map(String)}};return e.eventSource!==void 0&&(p.properties.event_source=e.eventSource),{ok:!0,changes:j(i,{source:e,beforeSnap:g,touchedIds:h,scheduledIds:S,sirDetection:"before-diff",trackingEvents:[p],hoursPerDay:a.hoursPerDay})}}async function Xo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:P.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Set,c=[],l=[],d=[],u=new Set(s),f=[...e.activityIds].sort((p,y)=>{let v=i.getActivity(p),E=i.getActivity(y),T=v?ot(v):te,R=E?ot(E):te;return T-R});for(let p of f){if(!i.getActivity(p)){c.push({activityId:p,reason:P.ACTIVITY_NOT_FOUND}),u.delete(p);continue}let v=_o(p,u,i);if(v==null){c.push({activityId:p,reason:P.INDENT_NO_ELIGIBLE_SIBLING}),u.delete(p);continue}let E=i.getActivity(p)?.parentId,T=b(E)?"0":String(E);d.push({activityId:p,newParentId:v,oldParentId:T}),o.add(p),o.add(v),T!=="0"&&o.add(T)}let h=V(i,o);for(let{activityId:p,newParentId:y}of d)i.setActivityField(p,L.PARENT,y),i.setActivityField(p,L.CORRELATIVE_ID,Wo),l.push(p);let g=new Set;for(let{activityId:p,newParentId:y}of d){if(g.has(y))continue;g.add(y);let v=i.getActivity(y);if(!v)continue;let E=v.customId,T=xt(v.type)&&i.getChildren(y).filter(N=>!l.includes(N)).length===0,R=v.hasNewActivities&&v.newActivityIds.some(N=>String(N)===String(p)),O=Ie({parentId:y,newChildId:p,getParent:N=>i.getActivity(N)??null,isCurrentlyLeaf:T,promotionSource:"reparent"});if(O){for(let[N,X]of Object.entries(O.fields))Z(i,O.parentId,N,X);O.promotionSnapshot&&i.setPromotionSnapshot(O.parentId,O.promotionSnapshot),R||(i.setActivityField(y,L.HAS_NEW_ACTIVITIES,!1),i.setActivityField(y,L.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(y,L.CONSTRAINT_TYPE,"asap"),i.setActivityField(y,L.CONSTRAINT_DATE,null),i.setActivityField(y,L.CUSTOM_ID,null),Er(E,r.customIdTracker)}let C=new Set;for(let p of d)p.oldParentId!=="0"&&C.add(p.oldParentId),C.add(p.newParentId);for(let p of C)wt(p,i);let A=ct(i);for(let p of A){if(o.add(p.activityId),h.has(p.activityId))continue;let y=i.getActivity(p.activityId);if(!y)continue;let v=J(y);p.before!==void 0&&(v.correlativeId=p.before),h.set(p.activityId,v)}let{scheduledIds:k}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),S=br(l,i),D={name:yt.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(p=>({activity_id:p.activityId,reason:p.reason})),invalid_link_ids:S}};return e.eventSource!==void 0&&(D.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(p=>{let y=c.find(v=>String(v.activityId)===String(p));return y?{activityId:String(p),ok:!1,reason:y.reason}:{activityId:String(p),ok:!0}}),changes:j(i,{source:e,beforeSnap:h,touchedIds:o,scheduledIds:k,trackingEvents:[D],hoursPerDay:a.hoursPerDay})}}async function Zo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:P.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let p of e.activityIds){let y=p;i.getActivity(y)&&(o.set(y,Xi(y,i)),c.set(y,Uo(y,s,i)))}let l=new Set,d=[],u=[],f=new Set,h=[],g=[...e.activityIds].sort((p,y)=>{let v=i.getActivity(p),E=i.getActivity(y),T=v?ot(v):te,R=E?ot(E):te;return T-R});for(let p of g){let y=p,v=i.getActivity(y);if(!v){d.push({activityId:y,reason:P.ACTIVITY_NOT_FOUND});continue}let E=v.parentId;if(b(E)){d.push({activityId:y,reason:P.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let T=String(E),R=i.getActivity(T);if(!R){d.push({activityId:y,reason:P.ACTIVITY_NOT_FOUND});continue}let O=R.parentId;if(b(O)){d.push({activityId:y,reason:P.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let N=String(O),X=Xi(T,i)+1,z=c.get(y);if(z!=null&&s.has(z)){let gt=o.get(z)??-1,Te=o.get(y)??-1;gt>=0&&Te>=0&&(X+=Te-gt)}h.push({activityId:y,grandparentKey:N,oldParentKey:T,targetIndexInGrandparent:X}),l.add(String(y)),l.add(String(T)),N!=="0"&&l.add(String(N)),f.add(T)}let C=V(i,l);for(let p of h){i.setActivityField(p.activityId,L.PARENT,p.grandparentKey);let y=Bo(i,p.grandparentKey,p.targetIndexInGrandparent,p.activityId);i.setActivityField(p.activityId,L.CORRELATIVE_ID,y),u.push(p.activityId)}for(let p of f){let y=i.getActivity(p);if(!y)continue;let v=i.getChildren(p),E=Se({parent:y,remainingChildIds:v.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(p),computeEndDate:(X,z)=>i.calculateEndDate({startDate:X,durationHours:z,task:y}),idsRemoved:new Set(h.filter(X=>X.oldParentKey===p).map(X=>X.activityId))});if(!E){lr(p,i);continue}for(let[X,z]of Object.entries(E.fields))Z(i,p,X,z);let T=Gt(p,i),R=T?i.getActivity(T)?.customId:null,O=typeof R=="string"&&R?R:null,N=r.customIdTracker.generateCustomIdForRestoredChild(O);i.setActivityField(p,L.CUSTOM_ID,N)}let A=new Set;for(let p of f)A.add(String(p));for(let p of h)p.grandparentKey!=="0"&&A.add(String(p.grandparentKey));for(let p of A)wt(p,i);let k=ct(i);for(let p of k){if(l.add(p.activityId),C.has(p.activityId))continue;let y=i.getActivity(p.activityId);if(!y)continue;let v=J(y);p.before!==void 0&&(v.correlativeId=p.before),C.set(p.activityId,v)}let{scheduledIds:S}=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}),D={name:yt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(p=>({activity_id:String(p.activityId),reason:p.reason}))}};return e.eventSource!==void 0&&(D.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(p=>{let y=d.find(v=>String(v.activityId)===String(p));return y?{activityId:String(p),ok:!1,reason:y.reason}:{activityId:String(p),ok:!0}}),changes:j(i,{source:e,beforeSnap:C,touchedIds:l,scheduledIds:S,trackingEvents:[D],hoursPerDay:a.hoursPerDay})}}async function Qo(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:P.INVALID_PROGRESS_VALUE};let o=n.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let c=Bt(_.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=Ht(e.activityId,l),u=V(i,d);jt(i,e.activityId,l),Mt(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:g=>mr(e.activityId,d,g),now:r.now,options:t}),h=(l.trackingEvents??[]).map(g=>({name:g.name,properties:g.properties??{}}));return{ok:!0,changes:j(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:h,hoursPerDay:s.hoursPerDay})}}async function tc(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 g of e.edits){let C=Xp(g,r);if(s.push(C.verdict),!C.verdict.ok||!C.changes)continue;let A=Ht(g.activityId,C.changes);Zp(o,A,r);for(let p of A)c.add(p);let k=Ae(i,g.activityId),S=V(i,new Set([String(g.activityId)])).get(String(g.activityId))??null;jt(i,g.activityId,C.changes),Mt(g.activityId,C.changes.postProcessors??[],i,S),d.push(...Ce(k,i,g.activityId)),f||=!!C.changes.needsAutoSchedule;for(let p of C.changes.trackingEvents??[])l.push({name:p.name,properties:p.properties??{}});let D=me(g.activityId,C.changes.constraintWarning);D&&u.push(D)}let{scheduledIds:h}=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:j(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:h,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function Xp(e,t){let{ctx:r}=t,i=e.activityId,n=Bt(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??P.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??P.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??P.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 Zp(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 V(r.adapter,i))e.set(n,a)}var on=_.CUSTOM_ID;async function ec(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;e.edits.some(D=>D.column===_.DURATION)&&n.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],h=[],g=[],C=!1;for(let D of e.edits){let p=Qp(D,r);if(o.push(p.verdict),!p.verdict.ok||!p.changes)continue;let y=me(D.activityId,p.changes.constraintWarning);y&&g.push(y);let v=Ht(D.activityId,p.changes);ih(c,v,r);for(let N of v)u.add(N);rh(l,D,c),Dr(D.column)&&d.add(String(D.activityId));let E=Ae(i,D.activityId),T=V(i,new Set([String(D.activityId)])).get(String(D.activityId))??null,R=th(D,r),O=p.changes;jt(i,D.activityId,O),Mt(D.activityId,p.changes.postProcessors??[],i,T),eh(D,R,r),h.push(...Ce(E,i,D.activityId)),C||=!!p.changes.needsAutoSchedule;for(let N of p.changes.trackingEvents??[])f.push({name:N.name,properties:N.properties??{}})}let A={action:e,autoscheduleFrom:C?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},k=l.size>0,{scheduledIds:S}=await(k?_r({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:A,revertTargets:[...l].filter(([D])=>!d.has(D)).map(([D,p])=>({activityId:D,priorConstraintDate:p})),revert:(D,p)=>Tr(D,p,i,r.ctx.calendars)}):$({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},A));return{ok:!0,verdicts:o,changes:j(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:S,sirDetection:"before-diff",links:h,trackingEvents:f,warnings:g,hoursPerDay:a.hoursPerDay})}}function Qp(e,t){let{ctx:r}=t,i=e.activityId,n=Bt(e.column);if(!n)return{verdict:{activityId:i,ok:!1,reason:P.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:i,ok:!1,reason:P.ACTIVITY_NOT_FOUND},changes:null};let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??P.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??P.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??P.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===on&&o.value!==null){let u=t.adapter.getActivity(e.activityId),f=u?u.customId:null,h=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(o.value),h))return{verdict:{activityId:i,ok:!1,reason:P.CUSTOM_ID_DUPLICATE},changes:null}}let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function th(e,t){if(e.column!==on)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function eh(e,t,r){if(e.column!==on)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 rh(e,t,r){if(!kr(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 ih(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 V(r.adapter,i))e.set(n,a)}function nh(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 rc(e,t,r,i){let n=new Set,a=new Set;for(let s of e)nh(s,t,r,i,n,a)}function ic(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));rc(r,"activity",c=>{let l=t.adapter.getActivity(c);return{exists:l!==null,current:l?.proplannerId??null}},n),rc(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 nc(e){return typeof e=="string"&&e.length>0?Lt(e):e instanceof Date?e:null}function cn(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 wr(e,t){let r=cn(e.duration),i=cn(e.cost),n=cn(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:nc(e.start_date),endDate:nc(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 ac(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=>wr(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 ah(e){let t=rt(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=ah(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 Or(e,t,r,i,n=null){let a=new Set;for(let s of ac(e,t,i))a.add(s);if(r)for(let s of Vt(e,r,n))a.add(s);for(let s of sc(e))a.add(s);for(let s of $t(e))a.add(s);return[...a]}function oc(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=sh(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(rt(c)){let u=n.get(String(o))??0;r.setActivityField(o,_.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,_.PONDERATOR,0)}}function sh(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=rt(i);if(!n)return 0;if(t==="COST")return xr(n.cost);if(t==="HH")return xr(n.workHours);let a=i.type;return a==="project"?cc(e,r):a==="milestone"?0:xr(n.durationDays)}function cc(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=rt(n);if(!a)continue;let s=n.type;s==="project"?r+=cc(String(i),t):s!=="milestone"&&(r+=xr(a.durationDays))}return r}function xr(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function lc(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,_.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&oc(String(i),e,t)})}function Nr(e){for(let t of oh(e))lh(t,e)}function oh(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,ch(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function ch(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function lh(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=ce(i);n!==null&&t.setActivityField(e,_.PROGRESS,cr(n))}function Fr(e,t){lc(t,e.adapter),Nr(e.adapter),e.now&&(Vt(e.adapter,e.now,e.defaultBaseCalendarId??null),bt(e.adapter,e.now)),$t(e.adapter),e.now&&It(e.adapter,e.sector.statusCriteria)}function dc(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 uc(e,t){let r=V(t.adapter,new Set(t.adapter.getAllIds())),i=dc(t),n=Or(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return dc(t)!==i&&Fr(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:j(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function dh(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}function fc(e,t){dh(e.criterion);let r=new Set(t.adapter.getAllIds()),i=V(t.adapter,r);return Fr(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:j(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function pc(e,t){let r=Ge(e.criteria),i=new Set(t.adapter.getAllIds()),n=V(t.adapter,i),a=It(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:j(t.adapter,{source:e,beforeSnap:n,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function hc(e,t,r){return e.kind==="persistence-acknowledge"?ic(e,r):e.kind==="baseline-apply"?uc(e,r):e.kind==="ponderator-criterion-set"?fc(e,r):e.kind==="status-criteria-set"?pc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Io(e,t,r):e.kind==="links-batch"?So(e,t,r):e.kind==="activity-create"?Ho(e,t,r):e.kind==="activity-paste"?jo(e,t,r):e.kind==="activity-delete"?zo(e,t,r):e.kind==="activity-move"?Jo(e,t,r):e.kind==="activity-indent"?Xo(e,t,r):e.kind==="activity-outdent"?Zo(e,t,r):e.kind==="activity-set-progress"?Qo(e,t,r):e.kind==="dates-batch"?tc(e,t,r):e.kind==="bulk-edit"?ec(e,t,r):e.kind==="selection-toggle"?Fn(e,ln(r)):e.kind==="selection-replace"?Mn(e,ln(r)):e.kind==="visibility-set"?Wn(e,ln(r)):e.kind==="sir-sync"?Vo(e,r):e.kind==="activity-lookahead-sync"?Yo(e,r):e.kind==="inline-edit"&&(e.column===_.CUSTOM_PREDECESSORS||e.column===_.CUSTOM_SUCESSORS)?ko(e,t,r):e.kind!=="inline-edit"?ka(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Co(e,t,r)}function ln(e){return{adapter:e.adapter}}var uh=new Set(["startDate","endDate","constraintDate"]);function yc(e,t){return uh.has(e)&&typeof t=="string"?new Date(t):t}function mc(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?fh(n,r):null}}}function fh(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 ph(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function ee(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function re(e){return ee(e)&&!isNaN(e.getTime())}var hh={}.constructor.toString();function yh(e){var t=e.constructor.toString();return t!==hh}function mh(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function kt(e){var t,r;if(e&&typeof e=="object")switch(!0){case ee(e):r=new Date(e);break;case ph(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=kt(e[t]);break;default:if(yh(e))r=Object.create(e);else{if(mh(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=kt(e[t]));break}return r||e}function ke(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function gc(e){return typeof e<"u"}var Mr;function dn(){return Mr||(Mr=new Date().valueOf()),Mr++,Mr}function ut(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var vh=(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)},Ah=(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)},vc={date_to_str:vh,str_to_date:Ah},Ch=(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}}),Ih=(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])},Ac={date_to_str:Ch,str_to_date:Ih};function Cc(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=vc;return a()&&(l=Ac),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=vc;return a()&&(l=Ac),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),h=1+Math.floor(f/7);return h},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 un(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function fn(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 pn(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 Sh(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 Ic=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(ee(t)?t={date:t}:t=ke({},t),!re(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 un)return t;var r;if(t.date?r=new un(t.date,t.unit,t.task,null,t.calendar):r=new un(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!re(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 fn)return r;var i;if(ee(r)?i=new fn(r):i=new fn(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,!re(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=Sh,i;if(t instanceof r)return t;if(ee(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,!re(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!re(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 pn)return a;var s;if(ee(a)?s=new pn(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new pn(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,!re(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 Sc(){}Sc.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=kt(e.getConfig()),i=kt(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 h in d.dates){let g=d.dates[h];if(h==u&&(s.dates[u]=!!(f&&g)),Array.isArray(f)){let C=Array.isArray(g)?g:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,C))}}}};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 hn=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}},yn=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={}}},mn=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 kh(){return typeof Map<"u"?new hn:new yn}var gn=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 vn(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=kh(),this._largeUnitsCache=new mn(this),this._dateDurationCache=new gn,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}vn.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 h=!1;a.valueOf()<s.valueOf();){if(c=this._nextDate(a,r,i),h=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&h)&&(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&&h?(f=!1,o+=(s.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):o++;else{var g=this._getUnitOrder(r),C=this.units[g-1];C&&!this._isWorkTime(a,C)&&(c=this._getClosestWorkTimeFuture(a,C))}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),h=d+f+u;return h},_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),h=d+f+u;return Math.round(h)},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 vn))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 h=r;return i===t&&(h=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:h}},_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 h=r;return i===t&&(h=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:h}},_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 h=Math.abs(Math.round((d-u)/60));n-=h,i+=h,s=u}}var g=r;return i===t&&(g=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:i,end:g}},_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 h=t-n,g=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=g&&h>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var C=!1,A=null,k=null,S=c.length-1;S>=0;S--)if(c[S].start<g-1&&c[S].end>=g-1){C=!0,A=c[S],k=c[S-1];break}if(C)if(g===A.end&&h>=A.durationMinutes)n+=A.durationMinutes,i=this.$gantt.date.add(i,-A.durationMinutes,"minute");else if(!a&&h<=g/60-A.startMinute)n+=h,i=this.$gantt.date.add(i,-h,"minute");else if(a)h<=g/60-A.startMinute?(n+=h,i=this.$gantt.date.add(i,-h,"minute")):(n+=g/60-A.startMinute,k?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,k.end)):i=this.$gantt.date.day_start(i));else{var D=this._getMinutesPerHour(i);D<=h?(n+=D,i=this._nextDate(i,"hour",r)):(s=this._subtractMinutesUntilHourStart(i,h),n+=s.added,i=s.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var p=this._getClosestWorkTimePast(i,"hour");if(p.valueOf()===i.valueOf()){var p=this.$gantt.date.add(i,-1,"day"),y=this._getWorkHours(p);if(y.length){var v=y[y.length-1];p.setUTCSeconds(v.durationSeconds)}}i=p}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var E=t-n;s=this._subtractMinutesUntilHourStart(i,E),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 h=!1,g=null,C=0;C<o.length;C++)if(o[C].start<=f&&o[C].end>f){h=!0,g=o[C];break}if(h)if(f===g.start&&u>=g.durationMinutes)n+=g.durationMinutes,i=this.$gantt.date.add(i,g.durationMinutes,"minute");else if(u<=g.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 k=t-n;a=this._addMinutesUntilHourEnd(i,k),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 Ue={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 Dh(){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 Th=Dh();function kc(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Ue.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))}kc.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 Sc,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 vn(this.$gantt,Ic(this.$gantt));t.id=String(dn());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=kt(e.getConfig()):e.worktime?t=kt(e.worktime):t=kt(e);var r=kt(this.defaults.fulltime.worktime);return ke(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=Ue.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=Th.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Ue.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Ue.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=Ue.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||dn(),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 An(e,t){this.argumentsHelper=t,this.$gantt=e}An.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 An},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 Dc(e){this.$gantt=e.$gantt,this.argumentsHelper=Ic(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new An(this.$gantt,this.argumentsHelper)}Dc.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 _h=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)}},Ph={create:_h};function Tc(e){var t=new kc(e),r=new Dc(t),i=Ph.create(t,r);ke(e,i)}var _c={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 Pc(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||_c,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:gc,mixin:ke,copy:kt,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=Cc(r),r.date.init(),Tc(r),r}function Eh(e={}){let t=Pc(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 Ec={createCalendar:Eh};var UL=3600*1e3;function wc(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Rh}=Ec,Be="__replay_default__";function Lh(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 Rc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Lc="__main_global__",bh={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function bc(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 wh(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:Lh(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Oc(e){let t=Rh({config:{work_time:!0}});t.addCalendar({id:Be,worktime:Rc}),t.addCalendar({id:Lc,worktime:bh});let r=new Set(e.filter(d=>!bc(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>bc(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?wh(d.worktime):Rc});let n=mc(t),a=n.getCalendar(Be),s=n.getCalendar(Lc);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([Be]);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 h=a;return o.has(u)?h=n.getCalendar(d)??a:r.has(u)&&(h=s),c.set(u,h),h}}}}function xc(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 Oh(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 Oh(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 Wr=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,ge(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:ge(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:Nc(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;if(!i)return;let n=ge(r);i.scheduledBefore.has(t)||i.scheduledBefore.set(t,n),i.before.has(t)||i.before.set(t,n),i.dirty.add(t)}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:Nc(r)}))}};function Nc(e){return{...e}}var Ur=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Fc(t);return this.reader.getCalendar(r??Be)}getClosestWorkTime(t){let r=`${In(t.task)}|${t.dir}|${t.date.getTime()}`;return Cn(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:nt.HOUR}))}calculateEndDate(t){let r=`${In(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Cn(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${In(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Cn(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 Cn(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var xh="__default__";function Fc(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function In(e){return Fc(e)??xh}var Br=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&&!b(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||b(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(b(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(b(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?Qi(n,a):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Hr=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 De=class{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_cache={ids:null,visualOrderIds:null};_writeCapture=new Wr;_viewState=new Hr;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=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 Ur(Oc(t.calendars)),this._flags=Fh(t),this._hierarchy=new Br(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=To(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)}getPromotionSnapshot(t){return this._promotionSnapshot.get(String(t))??null}setPromotionSnapshot(t,r){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(t),r)}_capturePromotionSnapshotOnce(){this._writeCapture.peek()!==null&&this._promotionSnapshotBefore===null&&(this._promotionSnapshotBefore=new Map(this._promotionSnapshot))}_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))??Mc}getIncomingLinkIds(t){return this._incoming.get(String(t))??Mc}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,this._promotionSnapshotBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=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(),Sn(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,yc(r,i)),r===L.PARENT&&this._hierarchy.markDirty(),Sn(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),Sn(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){Uc(this._outgoing,String(t.source),t.id),Uc(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Wc(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),Wc(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(!Nh(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._promotionSnapshotBefore!==null&&(this._promotionSnapshot=this._promotionSnapshotBefore),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))}},Mc=[];function Nh(e){return e===Ai.LAG||e===Ai.TYPE}function Sn(e){return e===L.PARENT||e===L.CORRELATIVE_ID}function Wc(e,t){return e.filter(r=>String(r)!==String(t))}function Uc(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Fh(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 et(e){return structuredClone(e)}function Bc(e,t){let r=e.getActivity(t);return r?et(r):null}function Hc(e){return e.getAllActivities().map(et)}function jc(e){return e.getAllIds().map(String)}function Vc(e,t){e.forEachActivity((r,i)=>t(i))}function Yc(e,t){let r=t==="0"?kn(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(et(a))}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function kn(e,t){let r=t;if(r==="0"){let i=[];return e.forEachActivity((n,a)=>{b(n.parentId)&&i.push(a)}),i}return[...e.getChildren(r)].map(String)}function $c(e){return e.checkedIds().map(String)}function Gc(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=b(i.parentId)}),r}return e.getChildren(t).length>0}function Kc(e,t){let r=e.getLink(t);return r?St(r):null}function zc(e){return e.getAllLinks().map(t=>St(t))}function jr(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Mh(e){return e.reduce((t,r)=>jr(r)<jr(t)?r:t)}function Wh(e){return e.reduce((t,r)=>jr(r)>jr(t)?r:t)}function Uh(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function qc(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=Uh(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:Mh(i),endHour:Wh(n)}}function Jc(e,t){return{calendars:e.calendarReader,hierarchy:xc(e),activityReader:wc(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function Xc(e){return We(e)}function Dn(e,t,r,i,n){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:i,afterLinks:n}}function tl(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 el(e){return e.kind!=="inline-edit"||!Me.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Zc(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 rl(e,t){if(!Zc(e)||!Zc(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function il(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 Dn(o)}function nl(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 Tn(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&_.CUSTOM_ID in t.fields)return!0;return!1}function _n(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",fields:Qc(s.fields,r),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",fields:Qc(s.fields,r),after:c?St(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);n.push({id:o,kind:"created",after:c?St(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?St(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?Bh(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Qc(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t==="before"?{before:et(i.after),after:et(i.before)}:{before:et(i.before),after:et(i.after)}]))}function Bh(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 Pn(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function al(e,t){ol(e,t,"before")}function sl(e,t){ol(e,t,"after")}function ol(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))Ns(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 Hh=100,jh=600,Vr=class{constructor(t=Hh){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<=jh&&n!==void 0&&rl(n,t)?this.undoStack[this.undoStack.length-1]=il(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 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 cl(e){return{id:String(e.id),worktime:Yh(e.worktime)}}function Yr(e,t,r,i=[]){let n=t.map(Vh),a=[...r.map(cl),...i.map(cl)];return{activities:[...e],links:n,calendars:a}}var ll=["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"],dl=new Set(["startDate","endDate","constraintDate","dateOrigin"]),ul=new Set(["newActivityIds","pendingRequestIds","responsableIds","tagIds"]);function fl(e){let t=ll.map(r=>[r,$h(r,e[r])]);return Object.fromEntries(t)}function $h(e,t){return dl.has(e)?t instanceof Date?new Date(t):null:ul.has(e)?Array.isArray(t)?[...t]:[]:t}function pl(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of ll)if(!Gh(r,e[r],t[r]))return!0;return!1}function Gh(e,t,r){return dl.has(e)?Kh(t,r):ul.has(e)?zh(t,r):(t??null)===(r??null)}function Kh(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function zh(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 $r=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),fl(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?pl(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 hl=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var En=[!1,!0,!0,!0,!0,!0,!1],yl=new Set(["1","true"]),Rn="DURATION",ml="asap",gl={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 vl(e,t){let r=[],i=e.map(a=>{let s=iy(a,t);return a.should_be_showed===!1&&r.push(s.id),s});ny(i);let n=new Set(i.map(a=>a.id));return ay(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function qh(e){return e===0}function Jh(e,t){if(!e)return null;let r=gl[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),ml):r}function Xh(e,t){let r=Jh(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?Lt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function Zh(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function Qh(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 ty(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Ln(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)ty(r)&&t.push(String(r.id));return t}function ey(e){return e==="0"?null:String(e)}function ry(e,t){return Array.isArray(e)?e.map(r=>wr(r,t)).filter(r=>r!==null):[]}function iy(e,t){let r=Zh(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:s}=Xh(e,t.reporter),o=e.type==="milestone",c=Lt(e.start_date),l=o?c:Lt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:ey(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Re(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:qh(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:Lt(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:Qh(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Ln(e.pendingRequests),responsableIds:Ln(e.responsables),tagIds:Ln(e.tags),baselinePoints:ry(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:Re(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),isCritical:!!e.is_critical,freeSlackHours:e.freeSlack,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function ny(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function ay(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 Sl(e,t,r,i=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>cy(c,i)),o=(r??[]).map(c=>ly(c,i));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:oy(s)}}function oy(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function kl(e,t){let r=yy(e.working_days),{days:i,hours:n}=hy(e,r),a=dy(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 cy(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return kl(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function ly(e,t){return kl(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function dy(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=uy(i.from_date,i.to_date,t);if(n.length===0)continue;let a=fy(i);if(a!==void 0)for(let s of n)r[s]=a}return Object.keys(r).length>0?r:null}function uy(e,t,r){let i=Al(e),n=Al(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 Al(e){if(typeof e!="string")return null;let t=hl.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 fy(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=py(t);if(r.length>0)return r}}var Cl=/^\d{1,2}:\d{2}$/;function py(e){let t=[];for(let r of e){let i=_l(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let o=i.startsCsv.trim(),c=i.endsCsv.trim();!Gr(o)&&!Gr(c)&&Cl.test(o)&&Cl.test(c)&&t.push(`${o}-${c}`);continue}let s=Tl(i.startsCsv,i.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(Dl),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 Dl(e,t){return Il(e)-Il(t)}function hy(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=Tl(l,d);for(let f=0;f<7;f+=1){let h=u[f],g=r[f];h&&g&&g.push(h)}},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=_l(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(Dl);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 Tl(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];Gr(c)||Gr(l)||(s[o]=`${c}-${l}`)}return s}function _l(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 yy(e){if(typeof e!="string")return[...En];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...En]:t.map(r=>yl.has(r))}var my=new Set(["false","null"]);function Gr(e){return!e||my.has(e)}function gy(e){return e==="0"||e==="1"||e==="2"||e==="3"}function vy(e){if(typeof e!="string")return null;let t=Xa(e);return t||(gy(e)?e:null)}function El(e,t){let r=[];for(let i of e)try{r.push(Ay(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return Cy(r)}function Ay(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=vy(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 Cy(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||Pl(r)>Pl(n))&&t.set(i,r)}return[...t.values()]}function Pl(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Iy(e){if(typeof e!="string")return Rn;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return Rn}}function Sy(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function ky(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Rl(e){let t=Sy(e),r=ky(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:Iy(e.activity_creter),statusCriteria:ai}}function Kr(e,t=oe){let r=Rl(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:s}=Sl(e.calendars,e.sector.calendars,e.baseCalendars,Dy(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=vl(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=El(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function Dy(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 Ll(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 bl(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 wl(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 Ol(e){return!!e&&typeof e=="string"&&e.trim().length>0}function zr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function qr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function xl(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Nl(e,t){return!t&&Ol(e)}function Fl(e,t){return t&&Ol(e)}function je(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function He(e){if(!je(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Ty(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!je(t))return r;let i=t.length;return r.padStart(i,"0")}function mt(e,t){let r=He(e),i=He(t),n=r+i;return Ty(n,e)}function Jr(e,t){let r=He(e),i=He(t);return r<i?-1:r>i?1:0}function Xr(e,t){return Jr(e,t)<=0?e:t}function Zr(e,t){return Jr(e,t)>=0?e:t}function Ml(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Xr(t,r))}function Wl(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Zr(t,r))}function Ul(e){return{prefix:e,baseSuffix:null}}function Bl(e,t){let r=qr(e);return{prefix:zr(e),baseSuffix:mt(r,t)}}function Hl(e){return{prefix:e,baseSuffix:null}}function jl(e,t){return Nl(e,t)?"parentConversion":Fl(e,t)?"pasteReference":"noContext"}function _y(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Qr=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?_y(i):null,hadId:this.processedIds.has(t)})}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return zr(t)}extractSuffix(t){return qr(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=Xr(r,i.min),i.max=Zr(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=Xr(i,n.min),n.max=Zr(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=Ml(o),n.max=Wl(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(;Jr(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&&je(r)?r:this.suffixIncrement;return`${t}${o}`.length>20?null:o}let i=this.prefixMap.get(t),n=this.suffixIncrement;if(!r||!je(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=xl(r),a=jl(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 Ul(this.defaultPrefix);case"pasteReference":return Bl(r,this.suffixIncrement);default:return Hl(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)}};function Vl(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,se),Py(e,r)}function Py(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 ti(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 Yl(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(ct(t),r.updateDurationForPrimaveraEndDate&&Ry(t),Ly(t),ti(t),n){a&&(bt(t,a),It(t,r.statusCriteria));return}let s=await i.schedule({});Ee(t,s),by(t),Ey(t),await le(t,void 0,!1),a&&(bt(t,a),It(t,r.statusCriteria))}function Ey(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 Ry(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Ly(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=Et(t.constraintDate,n,r))})}function by(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=Et(t.constraintDate,i,r))})}var Tt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function $l(e){let t=e.clock??null,r=t?Le(t()):null,i=e.reporter??oe,n=Kr({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),a=n.sector;a.statusCriteria=Ge(e.statusCriteria);let s=n.calendars,o=n.baseCalendars??[],c=Yr(n.activities,n.links,n.calendars,o),l=new De(c);l.hydrateViewState({hiddenIds:n.viewStateSeed.hiddenIds});let d=new or(l,i);Vl(l);let u=Ll({knownIds:n.activities.map(A=>A.id)}),f=bl({knownIds:n.links.map(A=>A.id)}),h=wl({knownIds:n.activities.map(A=>A.uniqueCorrelativeId)}),g=new Qr({defaultPrefix:a.customIdPrefix,suffixIncrement:a.customIdIncrement});if(g.populateFromActivities(n.activities),e.baselinePoints&&e.baselinePoints.length>0){let A=o.find(k=>k.baseDefault)?.id??null;Or(l,e.baselinePoints,r,i,A)}let C=Yl({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:h,customIdTracker:g,calendars:s,baseCalendars:o,clock:t,reporter:i,initPromise:C}}var ei=class{_status=Tt.READY;coreRuntime;_undo=new Vr;_opQueue=Promise.resolve();_scheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=$l(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!==Tt.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 et(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),Bc(this.coreRuntime.state,t)}getAllActivitiesView(){return this.assertReady(),Hc(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),Yc(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Kc(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),zc(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?et(i[r]):null}getAllIds(){return this.assertReady(),jc(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Vc(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),kn(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),$c(this.coreRuntime.state)}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),Gc(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?et(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>et(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>et(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),qc(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(et)}_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=Jc(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),n=nl(t);this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let a;try{a=await hc(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?Le(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"&&Pn(a.changes)){let s=tl(this.coreRuntime.state,a.changes);this._undo.record(Dn(a.changes,a.__beforeSnap,a.__beforeLinks,s.afterSnap,s.afterLinks),el(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?(mo(t)&&Pn(a.changes)&&this._recordScheduleMutation(r.skipCriticalPath!==!0),et(a)):a}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:r})=>r);return this._criticalPathReady=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===Tt.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 De(Yr(this.coreRuntime.state.getAllActivities().map(o=>J(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==Tt.DESTROYED&&this._scheduleRevision===t,a=(async()=>{let o=await Yi(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=j(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===Tt.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await Sr(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=j(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(Nr(t),ti(t),$t(t),this.coreRuntime.clock){let r=Le(this.coreRuntime.clock());bt(t,r);let i=!1;t.forEachActivity(n=>{i||=rt(n)!==null}),i&&Vt(t,r,this.coreRuntime.baseCalendars.find(n=>n.baseDefault)?.id??null),It(t,this.coreRuntime.sector.statusCriteria)}}undo(){let t=this._enqueue(async()=>{this.assertReady();let r=this._undo.takeUndo();return r?(al(this.coreRuntime.state,r),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),Tn(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(r),this._undo.resetCoalesce(),_n(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?(sl(this.coreRuntime.state,r),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),Tn(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce(),_n(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=Tt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new $r;assertReady(){if(this._status===Tt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Tt.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=Tt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",t),t}}};function Gl(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 Kl=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var zl={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 ql=8;var G={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"},wy={[G.PERSISTENCE_ACKNOWLEDGE]:!0,[G.BASELINE_APPLY]:!0,[G.PONDERATOR_CRITERION_SET]:!0,[G.STATUS_CRITERIA_SET]:!0,[G.INLINE_EDIT]:!0,[G.DATES_BATCH]:!0,[G.BULK_EDIT]:!0,[G.LINK_CREATE]:!0,[G.LINK_UPDATE]:!0,[G.LINK_DELETE]:!0,[G.LINKS_BATCH]:!0,[G.ACTIVITY_CREATE]:!0,[G.ACTIVITY_DELETE]:!0,[G.ACTIVITY_MOVE]:!0,[G.ACTIVITY_INDENT]:!0,[G.ACTIVITY_OUTDENT]:!0,[G.ACTIVITY_SET_PROGRESS]:!0,[G.ACTIVITY_PASTE]:!0,[G.SELECTION_TOGGLE]:!0,[G.SELECTION_REPLACE]:!0,[G.VISIBILITY_SET]:!0,[G.SIR_SYNC]:!0,[G.ACTIVITY_LOOKAHEAD_SYNC]:!0},Jl=Object.keys(wy);var Xl={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return nd(Oy);})();
|
|
2
2
|
//# sourceMappingURL=schedule-core.global.js.map
|