PageSourceSearch

https://dashboard.leaptodigital.com/assets/index-y92FpbmK.js

js leaptodigital.com collected 2026-10-02 10:48:32 UTC 627,883 bytes, 20 lines download raw bytes

1var Bu=Object.defineProperty;var $u=(n,e,s)=>e in n?Bu(n,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):n[e]=s;var W=(n,e,s)=>$u(n,typeof e!="symbol"?e+"":e,s);import{P as se,fh as He,fo as Vt,gV as _n,g as y,j as t,h1 as pe,B as N,gN as Wr,eZ as he,fM as Q,e as Hn,fw as Do,I as At,T as z,f5 as Hr,fn as Rs,hm as qr,eU as J,k as we,hn as zu,f6 as kt,f7 as ue,f8 as $e,ho as Wu,fc as Hu,hj as Vr,fd as qu,f2 as Tn,f3 as vt,fQ as Qn,fR as In,fU as es,fV as ts,fX as Sn,fY as _s,hp as Vu,hq as Kr,d as Je,hr as Ku,f_ as Oo,hs as Uu,ht as Gu,D as ie,fI as tl,fl as Le,e_ as Ur,e$ as Ft,f0 as Rt,hu as Ju,n as zt,l as at,hv as Yu,hw as Xu,f9 as Te,hx as Zu,gc as Qt,fk as ye,hy as Gr,hz as ns,hA as Gt,hB as Ve,hC as Qu,hD as ep,fF as mt,hE as tp,fS as np,fT as Jr,fW as sp,fZ as No,fN as Yr,fO as Xr,hF as ss,hG as op,hH as Zr,hI as ap,hJ as ip,hK as lp,hL as rp,hM as cp,_ as lt,fz as dp,hN as ft,hO as up,hP as b,hQ as pp,hR as hp,hS as Ge,hT as La,hU as Mo,hV as Z,hW as Jt,hX as We,hY as Ke,hZ as Ea,h_ as fe,h$ as xe,i0 as _,i1 as en,i2 as Qr,i3 as ze,i4 as vn,fy as Ct,i5 as mp,i6 as gp,i7 as Ae,i8 as Aa,i9 as xp,ia as Go,ib as nl,ic as fp,id as on,ie as Yt,ig as Ze,F as Qe,gr as Tt,gX as Bs,gY as An,fE as xt,ih as ec,ii as Lo,eT as tc,ij as Cn,ik as Xt,il as St,im as Eo,io as bp,ip as yp,iq as jp,ir as Cp,is as Ip,fp as wt,it as go,iu as xo,iv as fo,iw as bo,ix as sl,iy as ol,iz as nc,iA as sc,iB as Sp,go as vp,hd as $s,iC as Tp,iD as Ht,iE as os,iF as oc,iG as ac,iH as ic,iI as lc,iJ as Ao,iK as Fo,iL as wp,iM as wn,iN as rc,fA as kp,iO as Pp,iP as cc,fL as Dp,iQ as kn,h2 as Pt,fr as Dt,iR as Op,iS as Np,iT as Mp,iU as dc,iV as Lp,iW as Is,iX as Ep,ff as Ap,iY as zs,fB as uc,iZ as Fp,i_ as Kn,f as Rp,u as _p,i$ as Ro,f$ as Fa,j0 as Bp,j1 as $p,j2 as zp,j3 as Wp,j4 as pc,j5 as Hp,j6 as qp,j7 as Ra,j8 as Vp,j9 as Kp,ja as Up,jb as hc,jc as Gp,jd as mc,je as ga,jf as Jp,jg as Yp,jh as _a,ji as Xp,jj as gc,gQ as Zp,jk as Qp,jl as eh,jm as th,ha as nh,jn as sh,jo as oh,jp as ah,jq as ih,jr as lh,js as rh,g1 as yo,jt as Ba,ju as ch,jv as dh,jw as uh,jx as xc,jy as $a,jz as fc,jA as ph,jB as hh,jC as za,jD as Wa,jE as mh,jF as gh,jG as xh,jH as fh,jI as bh,jJ as yh,jK as jh,jL as bc,jM as Ch,jN as Ih,jO as Sh,jP as vh,jQ as Th,jR as wh,fq as kh,jS as Ph,jT as Dh,g0 as al,jU as xa,fP as il,jV as Oh,jW as ll,jX as Nh,gC as Mh,gw as Lh,jY as Eh,jZ as Mt,j_ as Ah,j$ as Fh,gd as Rh,gb as _h,k0 as Bh,k1 as $h,gi as zh,gj as Wh,gl as Hh,gk as ds}from"./vendor-DgNr872F.js";import{r as rn,c as an,b as qh,F as _o,Z as Vh,X as Kh,h as Ws,B as Bo,w as $o,M as zo,L as Os,x as yc,_ as Uh,k as Ns,S as _t,H as Gh,$ as jc,a0 as Jh,a1 as Cc,a2 as Yh,a3 as Xh,a4 as Zh,a5 as Qh,j as Ic,Y as Sc}from"./index-D4fDBXv7.js";import{G as em,g as tm,a as nm,f as sm,s as om,b as am,c as im}from"./saveLinkedValue-faNmPHSt.js";import{f as lm}from"./fetchCustomConfig-BjJXxvTc.js";import{s as vc,C as rm,A as cm,a as dm}from"./CopyFromAnotherOffice-BAjfwjz0.js";import{p as um}from"./parseUtils-D-87CBpI.js";import{S as Tc}from"./SearchBox-By-_1Ntz.js";import{S as Un}from"./SearchableMultiSelect-zzHDzXtS.js";import{u as wc}from"./useUrlParams-C_PsC2g7.js";import{u as Ha}from"./useOfficeOptions-DQLLWN3e.js";import{u as pm,a as kc,g as hm,b as mm}from"./useOfficeCountryStateOptions-B27k0VNW.js";import{g as gm,a as xm,f as fm,u as bm,b as ym,t as jm}from"./observeMeasureSheetItem-KXe2V589.js";import{S as Pc}from"./SearchableSelect-Bg6fNn34.js";import{f as Cm}from"./fetchCompany-BTW6B5Gv.js";import{u as Im}from"./useCurrentOffice-tQmmRWIv.js";import{A as Sm}from"./AgGridCustomLoadingOverlay-DqipKjtH.js";import"./copyFromOffice-CMWje-OK.js";import"./getParsePaginatedOffice-DFyjOPds.js";const vm=async n=>{try{return await se.Cloud.run("saveDocumentSortOrder",n)}catch(e){throw await rn(e),e}},Tm=async n=>await se.Cloud.run("publishToTemplates",{...n}),wm=async n=>{const{templateType:e,objectId:s}=n,o=await se.Cloud.run("startCloneTemplateJob",{objectId:s,templateType:e});try{const a=await um(o,10,6e3),i=new se.Object("ContractObject");return i.id=a,i}catch(a){throw a instanceof Error&&a.message==="timed out"?new Error("This template is taking a little longer than usual to copy because of its size. You can safely leave this page and check back in a minute. Your template copy will appear once it’s ready."):a}},km=async n=>await se.Cloud.run("cloneTemplate",n),Pm=async n=>{try{const e=new se.Object("ContractObject");return e.id=n,(await e.destroy()).id}catch(e){throw await rn(e),e}},qa=n=>{const e=(l,r="Custom Document Error")=>an({title:r,showVerbose:!0,error:l}),{data:s=[],isFetching:o,refetch:a}=He({queryKey:["mainMenuOptions",n],queryFn:async()=>
1{if(!n)return[];const l=await lm(n);return((l==null?void 0:l.mainMenuOptions)||[]).map(d=>({...d,id:d.objectId}))},enabled:!!n,onError:l=>e(l,"Fetch Custom Document Error"),refetchOnWindowFocus:!1,retry:!1}),i=Vt({mutationKey:["removeCustomDocument",{officeId:n}],mutationFn:async l=>{if(!n)throw new Error("Invalid office ID");if(!l)throw new Error("Invalid document ID");const r=s.filter(d=>d.objectId!==l);await vc(n,r)},onError:l=>e(l,"Remove Custom Document Error")});return{fetching:o,mainMenuOptions:s,onError:e,refetchMainMenuOptions:a,removeCustomDocument:i.mutateAsync}},Dm=(n,e,s)=>{switch(n){case"contract":case"proposal":return[{title:`${n} Templates`,link:s.includes("/custom")?`/documents/templates/custom/${n}`:`/documents/templates/${n}`}];default:{const o=e.find(a=>a.objectId===n);return o?[{title:"Custom Documents",link:"/documents/custom"},{title:`${o.title} Templates`,link:s.includes("/custom")?`/documents/templates/custom/${o.objectId}`:`/documents/templates/${o.objectId}`}]:[{title:"Custom Documents",link:"/documents/custom"}]}}},Om=()=>{const{libraryId:n="",templateType:e="contract"}=_n(),{lastPath:s}=qh(),{mainMenuOptions:o=[]}=qa(),[a,i]=y.useState({field:"order",direction:"asc"}),l=(u,p="Document Error")=>{an({title:p,showVerbose:!0,error:u})},{data:r,isFetching:d}=He({queryKey:["contractObjects",{groupId:n,sortState:a}],queryFn:async({queryKey:u})=>await em(u[1]),onError:u=>l(u,"Error fetching documents"),refetchOnWindowFocus:!1,retry:!1,staleTime:600*1e3,cacheTime:1200*1e3,keepPreviousData:!0});return{breadCrumbs:y.useMemo(()=>{const u=Dm(e,o,s.toString());return n?[...u,{title:`${(r==null?void 0:r.groupName)||n} Templates`,link:""}]:u},[n,r==null?void 0:r.groupName,o,e,s]),documents:(r==null?void 0:r.contractObjects)||[],fetchingDocuments:d,sortState:a,setSortState:i}},Nm={templateItem:{width:"168px",margin:"0 auto",borderRadius:"16px","& .MuiCard-root":{height:"160px",borderRadius:"16px",display:"flex",justifyContent:"center",alignItems:"center",position:"relative",backgroundColor:"gray2.main","& .mask":{backgroundColor:"rgba(0, 0, 0, 0.5)",position:"absolute",top:0,right:0,bottom:0,left:0,opacity:0,borderRadius:"16px",width:"100%",height:"100%"},"& .templateThumbnail":{width:"100%",height:"auto",padding:"10px"}},"& .cardContainer":{padding:"4px",borderRadius:"16px"},"&:hover":{"& .cardContainer":{backgroundColor:"primary.main"},"& .MuiCard-root":{},"& .templateToolbar":{opacity:1},"& .mask":{opacity:1},"& .groupTitle":{color:"white"},"& .bottomToolbar":{opacity:1}}},templateIcon:{color:"secondary.main",width:"65px",height:"auto",display:"flex",alignItems:"center","& svg":{width:"100%",height:"auto"}},toolbar:{position:"absolute",opacity:0,zIndex:1,transition:"all 0.5s ease",top:10,right:10,"& .MuiFab-root":{background:"white",marginLeft:"7px",width:25,height:25,minHeight:"auto"},"& .MuiIcon-root":{fontSize:12,color:"text.secondary",height:"auto",width:"auto"}},title:{color:"text.primary",padding:"5px 0 10px 0",position:"relative",textAlign:"center",".display-name":{maxWidth:"100%",whiteSpace:"normal",wordBreak:"break-word",margin:"0 auto",cursor:"pointer"},"& .chevron-icon":{color:"white",position:"absolute",right:5}},bottomToolbar:{position:"absolute",opacity:0,zIndex:1,transition:"all 0.5s ease",bottom:10,right:10,display:"flex",flexDirection:"row","& .MuiFab-root":{background:"white",marginLeft:"7px",width:25,height:25,minHeight:"auto"},"& .MuiIcon-root":{fontSize:12,color:"text.secondary",height:"auto",width:"auto"}}},Dc=n=>{const{document:e,onDeleteTemplate:s,onCopyTemplate:o,setPublishingTemp:a,viewDocument:i,disableEdit:l}=n,{id:r,displayName:d,iconImageUrl:c,type:u,previewUrl:p}=e,h=Nm,g=u!=="contract"&&u!=="proposal"?"custom/templates":"templates",{data:x}=He({queryKey:["isThumbnailValid",{iconImageUrl:c}],queryFn:()=>Vh(c),retry:!1,refetchOnWindowFocus:!1,refetchOnMount:!1,staleTime:600*1e3,cacheTime:1200*1e3});return t.jsx(pe,{children:t.jsxs(N,{sx:h.templateItem,children:[t.jsx(N,{className:"cardContainer",children:t.jsxs(Wr,{children:[t.jsxs(he,{direction:"row",className:"templateToolbar",sx:h.toolbar,children:[!l&&t.jsx(Q,{title:"Edit Template",children:t.jsx(Hn,{"aria-label":"editTemplate",component:Do,to:`/documents/${g}/${u}/edit/${r}`,children:t.jsx(At,{baseClassName:"fa-regular",className:"fa-pen-to-square"})})}),p&&i&&t.jsx(Q,{title:"Preview Template",children:t.jsx(Hn,{"aria-label":"previewTemplate",onClick:()=>i(p),children:t.jsx(At,{baseClassName:"fa-regular",className:"fa-eye"})})}),s&&t.jsx(Q,{title:"Delete Template",children:t.jsx(Hn,{"aria-label":"deleteTemplate",onClick:()=>{_o({title:`Delete template "${d}"`,titleColor:"error",confirmText:"Delete",confirmBtnColor:"error",msg:`Are you sure you want to delete the template "${d}"? This action cannot be undone.`,onConfirm:async()=>{s(r)}})},children:t.jsx(At,{baseClassName:"fa-regular",className:"fa-trash",color:"primary"})})})]}),(o||a)&&t.jsxs(he,{direction:"row",className:"bottomToolbar",sx:h.bottomToolbar,children:[o&&t.jsx(Q,{title:"Copy Template",children:t.jsx(Hn,{"aria-label":"copyTemplate",onClick:()=>o(r),children:t.jsx(At,{baseClassName:"fa-regular",className:"fa-copy"})})}),a&&t.jsx(Q,{title:"Publish Template",children:t.jsx(Hn,{"aria-label":"publishTemplate",onClick:()=>a({templateId:r,templateName:d}),children:t.jsx(At,{baseClassName:"fa-regular",className:"fa-upload",color:"primary"})})})]}),x&&c?t.jsx("img",{className:"templateThumbnail",src:c,alt:d}):t.jsx(At,{sx:h.templateIcon,baseClassName:"fa-regular",className:"fa-light fa-file-invoice"}),t.jsx(N,{component:"div",className:"mask"})]})}),t.jsx(N,{sx:h.title,children:t.jsx(z,{className:"display-name",onClick:()=>{p&&i&&i(p)},sx:{"&:hover":{textDecoration:"underline"}},children:d})})]})})},Mm=async n=>
1await Tm(n),Lm=async n=>(await Kh).variation("clone-template-new",!1)?await km(n):(await wm(n)).id,Em=async n=>await Pm(n),Oc=()=>{const n=_n(),{templateType:e="contract"}=n,s=Hr(),{setSnackbar:o}=Ws(),a=Rs(),i=d=>{let c=d;return d.match(/^https?:\/\//i)||(c=`http://${d}`),window.open(c,"_blank")},l=Vt({mutationKey:["copyTemplate",{templateType:e}],mutationFn:async d=>await Lm({templateType:e,objectId:d}),onError:d=>{o({children:`Error copying Template ${d.message}`,severity:"error"})},onSuccess:d=>{s.push(`/documents/templates/${e}/edit/${d}`),a.invalidateQueries({queryKey:["contractObjects"]}),o({children:"Template copied successfully",severity:"success"})}}),r=Vt({mutationKey:["deleteTemplate"],mutationFn:Em,onError:d=>{o({children:`Error deleting Template ${d.message}`,severity:"error"})},onSuccess:d=>{a.setQueriesData(["contractObjects"],(c=[])=>c.length?c.filter(p=>p.id!==d):c),o({children:"Template deleted successfully",severity:"success"})}});return{copyTemplate:l.mutate,isCopyingTemplate:l.isLoading,deleteTemplate:r.mutate,isDeletingTemplate:r.isLoading,viewDocument:i}},Nc=()=>t.jsx(pe,{container:!0,gap:"30px",children:[...Array(21)].map((n,e)=>t.jsx(pe,{children:t.jsx(qr,{variant:"rectangular",sx:{height:"168px",width:"168px",borderRadius:"32px"}})},`skeleton-documents-${e}`))}),Am=[{id:"default",field:"order",title:"Default",direction:"asc"},{id:"name-asc",field:"displayName",title:"A - Z",direction:"asc"},{id:"name-desc",field:"displayName",title:"Z - A",direction:"desc"},{id:"createdAt-asc",field:"_created_at",title:"By Earliest Date",direction:"asc"},{id:"createdAt-desc",field:"_created_at",title:"By Latest Date",direction:"desc"}],Mc=n=>{const{setSortState:e,sortState:s}=n,[o,a]=J.useState(null),i=!!o,l=c=>{a(c.currentTarget)},r=()=>{a(null)},d=(c,u)=>{e({field:c,direction:u}),r()};return t.jsxs("div",{children:[t.jsx(we,{id:"sort-dropdown","aria-controls":i?"sort-menu":void 0,"aria-haspopup":"true","aria-expanded":i?"true":void 0,variant:"outlined",color:"secondary",onClick:l,sx:{minHeight:"40px",minWidth:"auto",px:1},children:t.jsx(zu,{})}),t.jsx(kt,{id:"sort-menu",anchorEl:o,open:i,onClose:r,children:Am.map(({title:c,field:u,direction:p})=>{const h=s.field===u&&s.direction===p;return t.jsxs(ue,{onClick:()=>d(u,p),sx:{backgroundColor:h?"lightgray":"inherit"},children:[t.jsx($e,{children:h&&t.jsx(Wu,{})}),c]},c)})})]})},Fm=()=>{const{search:n}
1=Hu(),{copyTemplate:e,viewDocument:s,isCopyingTemplate:o}=Oc(),{breadCrumbs:a=[],documents:i,fetchingDocuments:l,sortState:r,setSortState:d}=Om();return t.jsxs(Bo,{sx:{height:"100%"},children:[t.jsxs($o,{alignItems:"flex-end",sx:{mb:2},children:[t.jsx(he,{flexDirection:"row",gap:2,children:t.jsx(Vr,{"aria-label":"breadcrumb",sx:{display:"flex",alignItems:"bottom"},children:a.map((c,u)=>a.length-1===u?t.jsx(z,{color:"text.primary",sx:{fontWeight:"bold"},children:c.title}):t.jsx(qu,{component:Do,color:"inherit",to:{pathname:c.link,search:n},sx:{textTransform:"capitalize"},children:c.title}))})}),t.jsx(he,{flexDirection:"row",gap:2,children:t.jsx(Mc,{setSortState:d,sortState:r})})]}),t.jsxs(N,{children:[t.jsx(Tn,{sx:{zIndex:9,position:"absolute",backgroundColor:"rgba(0, 0, 0, 0.2)"},open:o,children:t.jsx(vt,{color:"primary",size:50})}),l?t.jsx(Nc,{}):t.jsx(pe,{container:!0,gap:"30px",children:i.map(c=>t.jsx(Dc,{document:c,onCopyTemplate:e,viewDocument:s,disableEdit:!0},`document-${c.id}`))})]})]})},Lc={documentsWrap:{overflowY:"auto",scrollbarGutter:"stable",height:"100%",".sortable-item":{"&:hover .drag-handle":{opacity:1}}},tablePagination:{".MuiTablePagination-toolbar":{minHeight:"30px"},".MuiTablePagination-selectLabel":{marginBottom:"2.5px"},".MuiTablePagination-displayedRows":{marginBottom:"0px"},"&::-webkit-scrollbar":{display:"none"}},grabContainer:{cursor:"grab",position:"absolute",zIndex:10,top:14,left:15},dragHandle:{width:25,height:25,minHeight:25,cursor:"grab",opacity:0}},Rm=({id:n,children:e,disabled:s=!1})=>{const{attributes:o,listeners:a,setNodeRef:i,transform:l,transition:r,isDragging:d}=Oo({id:n,disabled:s}),c=Lc,u={transform:l?`translate3d(${l.x}px, ${l.y}px, 0)`:void 0,transition:r,position:"relative",opacity:d?.5:1};return t.jsxs("div",{ref:i,style:u,className:"sortable-item",children:[t.jsx("div",{...o,...a,style:c.grabContainer,children:t.jsx(Q,{title:s?"Default sort + one category to reorder":"Drag to reorder",children:t.jsx("span",{children:t.jsx(Hn,{"aria-label":"drag-handle",className:"drag-handle",sx:c.dragHandle,disabled:s,children:t.jsx(Uu,{fontSize:"small",sx:{color:s?"gray5.main":"black",fontSize:"14px"}})})})})}),e]})},_m=n=>{const{children:e,items:s,page:o,limit:a}=n,i=Rs(),{setSnackbar:l}=Ws(),[r,d]=y.useState(!1),[c,u]=y.useState(null),p=Qn(In(es)),h=x=>{const{active:m}=x,f=s.find(j=>j.id===m.id);u({id:m.id,name:(f==null?void 0:f.displayName)||"Untitled Document"})},g=async x=>{const{active:m,over:f}=x;try{if(d(!0),f&&m.id!==f.id){const j=s.findIndex(C=>C.id===m.id),S=s.findIndex(C=>C.id===f.id);i.setQueriesData(["contractObjects"],(C=[])=>C.length?Gu(C,j,S):C);const w=await vm({documentId:m.id,newOrder:o*a+S});l({children:w,severity:"success"})}}catch(j){l({children:`Document reorder failed. Please try again: ${j.message}`,severity:"error"})}finally{u(null),d(!1)}};return t.jsxs(ts,{sensors:p,collisionDetection:Sn,onDragStart:h,onDragEnd:g,children:[t.jsx(Tn,{sx:{zIndex:7,position:"absolute",backgroundColor:"rgba(0, 0, 0, 0.3)"},open:r,children:t.jsxs(he,{justifyContent:"center",alignItems:"center",children:[t.jsx(vt,{color:"secondary"}),t.jsx(z,{variant:"subtitle2",color:"secondary",sx:{mt:2},children:"Updating order..."})]})}),t.jsx(_s,{items:s,strategy:Vu,children:e}),t.jsx(Kr,{dropAnimation:{duration:500,easing:"cubic-bezier(0.18, 0.67, 0.6, 1.22)"},children:c?t.jsxs(Je,{elevation:4,sx:{padding:"8px",display:"flex",alignItems:"center"},children:[t.jsx(Ku,{color:"secondary"}),t.jsx(z,{variant:"body2",sx:{ml:1,maxWidth:"100px",fontWeight:"bold",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},noWrap:!0,children:c.name})]},c.id):null})]})},Bm=n=>{const{publishingTemp:e,setPublishingTemp:s}=n,{setSnackbar:o}=Ws(),[a,i]=y.useState(!1),[l,r]=y.useState({name:(e==null?void 0:e.templateName)||"",author:""});He({queryKey:"author",queryFn:async()=>{const p=await yc,h=await Uh(p);if(!h)throw new Error("User not found!");const{nameFirst:g,nameLast:x}=h;return`${g} ${x}`},onSuccess:p=>{r({name:(e==null?void 0:e.templateName)||"",author:p})},enabled:!!e,refetchOnWindowFocus:!1,retry:!1,staleTime:600*1e3,cacheTime:1200*1e3,keepPreviousData:!0});const d=()=>{s(void 0),i(!1)},c=Vt({mutationKey:"publishTemplate",mutationFn:Mm,onError:p=>{o({children:`Error publishing Template ${p.message}`,severity:"error"})},onSuccess:()=>{o({children:"Template published successfully",severity:"success"})},onSettled:()=>d()}),u=(p,h)=>{r(g=>({...g,[h]:p}))};return t.jsx(zo,{title:"Publish Template",open:!!(e!=null&&e.templateId),onClose:d,modalContainerProps:{sx:{maxWidth:600,minWidth:600}},children:t.jsxs(N,{children:[t.jsxs(z,{textAlign:"center",variant:"subtitle2",color:"error",children:["You are making this template public. ",t.jsx("br",{})]}),t.jsxs(z,{textAlign:"center",sx:{mt:1},children:["By publishing this template to the Shared Template Library you are allowing ",t.jsx("br",{}),"access for any user within the SalesPro Ecosystem to download this template into ",t.jsx("br",{}),"their account, modify it, and/or use as they see fit."]}),t.jsx(ie,{sx:{my:2}}),t.jsxs(he,{direction:"row",gap:2,children:[t.jsx(tl,{fullWidth:!0,children:t.jsx(Le,{label:"Name",value:(l==null?void 0:l.name)||"",onChange:p=>u(p.target.value,"name"),error:!(l!=null&&l.name),helperText:l!=null&&l.name?" ":"Name is required",size:"small",color:"secondary",sx:{width:"100%"}})}),t.jsx(tl,{fullWidth:!0,children:t.jsx(Le,{label:"Author",value:(l==null?void 0:l.author)||"",onChange:p=>u(p.target.value,"author"),error:!(l!=null&&l.author),helperText:l!=null&&l.author?" ":"Author is required",size:"small",color:"secondary",sx:{width:"100%"}})})]}),t.jsxs(Ur,{severity:"warning",sx:{my:1},children:[t.jsx(z,{id:"acknowledge-modal-description",sx:{fontSize:12},children:"By checking this box you agree to make this template public. This action cannot be undone."}),t.jsx(Ft,{control:t.jsx(Rt,{checked:a,onChange:()=>i(p=>!p)}),label:"I understand this is permanent action",sx:{mt:1,"& .MuiFormControl
1Label-label":{fontSize:10}}})]}),t.jsx(ie,{sx:{my:2}}),t.jsxs(he,{direction:"row",justifyContent:"space-between",sx:{mt:2},children:[t.jsx(we,{color:"secondary",variant:"outlined",size:"small",sx:{minWidth:"100px"},onClick:d,"data-cy":"cancel",children:"Cancel"}),t.jsx(Os,{loading:c.isLoading,onClick:()=>{c.mutate({templateId:e==null?void 0:e.templateId,author:l.author,name:l.name})},variant:"contained",sx:{width:100},disabled:!(e!=null&&e.templateId)||!(l!=null&&l.author)||!(l!=null&&l.name)||!a,"data-cy":"publish",children:"Publish"})]})]})})},$m=n=>{const{documents:e,page:s,limit:o,isSortable:a}=n,[i,l]=y.useState(),{copyTemplate:r,isCopyingTemplate:d,deleteTemplate:c,isDeletingTemplate:u,viewDocument:p}=Oc();return t.jsxs(pe,{container:!0,gap:"30px",children:[e.length===0&&t.jsx(z,{variant:"body2",children:"No resources found. Please adjust your filters or add new resources."}),t.jsx(Tn,{sx:{zIndex:9,position:"absolute",backgroundColor:"rgba(0, 0, 0, 0.2)"},open:u||d,children:t.jsx(vt,{color:"primary",size:50})}),t.jsx(_m,{items:e,page:s,limit:o,children:e.map(h=>t.jsx(Rm,{id:h.id,disabled:!a,children:t.jsx(Dc,{document:h,onDeleteTemplate:c,onCopyTemplate:r,setPublishingTemp:l,viewDocument:p},`document-${h.id}`)},h.id))}),t.jsx(Bm,{publishingTemp:i,setPublishingTemp:l})]})},zm=()=>({folderItem:{width:"168px",margin:"0 auto",borderRadius:"16px",cursor:"pointer","& .MuiCard-root":{height:"160px",borderRadius:"16px",display:"flex",justifyContent:"center",alignItems:"center",position:"relative",backgroundColor:"background.default","& .mask":{backgroundColor:"rgba(0, 0, 0, 0.5)",position:"absolute",top:0,right:0,bottom:0,left:0,opacity:0,borderRadius:"16px",width:"100%",height:"100%"}},"& .cardContainer":{padding:"4px",borderRadius:"16px"},"&:hover":{backgroundColor:"primary.main","& .cardContainer":{backgroundColor:"primary.main"},"& .mask":{opacity:1}}},folderIcon:{color:"primary.main",width:"45px",height:"auto",display:"flex",alignItems:"center","& svg":{width:"100%",height:"auto"}},title:{color:"text.primary",padding:"5px 24px 10px 24px",position:"relative",textAlign:"center",".display-name":{margin:"0 auto",cursor:"pointer",wordBreak:"break-word"},"& .chevron-icon":{color:"text.secondary",position:"absolute",right:5,top:6}}}),Wm=n=>{const{folders:e,onFolderClick:s}=n,o=zm();return e.length===0?t.jsx(z,{variant:"body2",children:'No categories found. Documents without a category appear under "Uncategorized".'}):t.jsx(pe,{container:!0,gap:"30px",children:e.map(a=>t.jsx(pe,{children:t.jsxs(N,{sx:o.folderItem,onClick:()=>s(a.value),"data-cy":`documentFolder-${a.value}`,children:[t.jsx(N,{className:"cardContainer",children:t.jsxs(Wr,{children:[t.jsx(At,{sx:o.folderIcon,baseClassName:"fa-regular",className:"fa-folder"}),t.jsx(N,{component:"div",className:"mask"})]})}),t.jsx(N,{sx:o.title,children:t.jsxs(z,{className:"display-name",children:[a.label,t.jsx(Ju,{className:"chevron-icon"})]})})]})},a.value))})},Hm=()=>{const{params:n,setParam:e}=wc(),o=zt()["office-level-country"],{officeOptions:a,fetchingOfficeOption:i}=Ha({includeNoOffice:!0}),{stateOptions:l,fetchingStateOption:r}=pm(),{countryMap:d}=kc(),c=y.useMemo(()=>{if(!o)return[];const de=a.filter(oe=>!(n!=null&&n.officeFilter)||n.officeFilter.includes(oe.value)).map(oe=>oe.value).filter(oe=>oe!=="**no-office**");return hm(de,d)},[o,a,n==null?void 0:n.officeFilter,d]),{stateOptions:u,fetchingStateOption:p}=mm(c),h=o?u:l,g=o?p:r,x=_n(),{templateType:m="contract"}=x,f=y.useMemo(()=>(n==null?void 0:n.page)||0,[n==null?void 0:n.page]),j=y.useMemo(()=>(n==null?void 0:n.limit)||25,[n==null?void 0:n.limit]),[S,w]=y.useState(!1),[C,v]=y.useState((n==null?void 0:n.search)||""),[I,D]=y.useState({field:"order",direction:"asc"}),F=(n==null?void 0:n.view)==="folder"?"folder":"flat",M=y.useCallback(de=>{e("view",de),e("folder",""),e("page",0)},[e]),{data:R}=He({queryKey:["documentCategories",m],queryFn:()=>tm({templateType:m}),refetchOnWindowFocus:!1,retry:!1,staleTime:600*1e3}),P=y.useMemo(()=>{const de=((R==null?void 0:R.categories)||[]).map(oe=>({label:oe,value:oe}));return R!=null&&R.hasUncategorized&&de.push({label:"Uncategorized",value:"**no-category**"}),de},[R]),k=y.useMemo(()=>{let de=[];return n!=null&&n.categoryFilter&&P.length>0&&(de=P.filter(oe=>{var Ie;return(Ie=n==null?void 0:n.categoryFilter)==null?void 0:Ie.includes(oe.value)})),de},[n==null?void 0:n.categoryFilter,P]),T=y.useCallback((de,oe)=>{const Ie=oe.map(Ue=>Ue.value);e("categoryFilter",Ie),e("page",0)},[e]),B=(n==null?void 0:n.folder)||"",L=F==="folder"&&!B,H=y.useMemo(()=>{var de;return((de=P.find(oe=>oe.value===B))==null?void 0:de.label)||B},[P,B]),G=y.useCallback(de=>{e("folder",de),e("page",0)},[e]),ne=y.useCallback(()=>{e("folder",""),e("page",0)},[e]),le=y.useMemo(()=>
1{if(k.length===0)return P;const de=new Set(k.map(oe=>oe.value));return P.filter(oe=>de.has(oe.value))},[P,k]),re=y.useMemo(()=>le.slice(f*j,f*j+j),[le,f,j]),O=y.useMemo(()=>F==="folder"?B?[B]:[]:k.map(de=>de.value),[F,B,k]),K=y.useMemo(()=>I.field==="order"&&O.length===1,[I.field,O.length]),U=y.useMemo(()=>(n==null?void 0:n.search)||"",[n==null?void 0:n.search]),A=(de,oe="Document Error")=>{an({title:oe,showVerbose:!0,error:de})},q=y.useMemo(()=>{let de=[];return n!=null&&n.officeFilter&&a.length>0&&(de=a.filter(oe=>{var Ie;return(Ie=n==null?void 0:n.officeFilter)==null?void 0:Ie.includes(oe.value)})),de},[n==null?void 0:n.officeFilter,a]),Y=y.useCallback((de,oe)=>{const Ie=oe.map(Ue=>Ue.value);e("officeFilter",Ie),e("page",0)},[e]),ce=y.useMemo(()=>{let de=[];return n!=null&&n.stateFilter&&h.length>0&&(de=h.filter(oe=>{var Ie;return(Ie=n==null?void 0:n.stateFilter)==null?void 0:Ie.includes(oe.value)})),de},[n==null?void 0:n.stateFilter,h]),be=y.useCallback((de,oe)=>{const Ie=oe.map(Ue=>Ue.value);e("stateFilter",Ie),e("page",0)},[e]),Se=y.useMemo(()=>at.debounce(de=>e("search",de),1e3),[e]),te=y.useCallback(de=>{v(de),(de.trim().length>=3||de==="")&&(Se(de),f!==0&&e("page",0))},[Se,e,f]),ge=y.useMemo(()=>({selectedOffices:q.map(de=>de.value),selectedStates:ce.map(de=>de.value),selectedCategories:O,page:f,limit:j,templateType:m,searchText:U,sortState:I}),[q,f,j,U,m,ce,O,I]),{data:me=[],isFetching:De,refetch:Pe}=He({queryKey:["contractObjects",ge],queryFn:({queryKey:de})=>nm(de[1]),onError:de=>A(de,"Error fetching documents"),enabled:!L,refetchOnWindowFocus:!1,retry:!1,staleTime:600*1e3,cacheTime:1200*1e3,keepPreviousData:!0});return{documents:me,fetchingDocuments:De,page:f,limit:j,setParam:e,officeOptions:a,fetchingOfficeOption:i,selectedOffices:q,onOfficeFilterChange:Y,selectedStates:ce,onStateFilterChange:be,searchText:C,handleSearch:te,templateType:m,stateOptions:h,fetchingStateOption:g,sortState:I,setSortState:D,categoryOptions:P,selectedCategories:k,onCategoryFilterChange:T,viewMode:F,setVie
1wMode:M,showFolders:L,folderTiles:re,folderCount:le.length,selectedFolder:B,selectedFolderLabel:H,onFolderClick:G,onFolderBack:ne,isSortable:K,showSnapshotModal:S,setShowSnapShotModal:w,refetchContractObjects:Pe}},qm=n=>{const{onOpenSnapshot:e}=n,{templateType:s}=_n(),[o,a]=y.useState(null),i=!!o,l=c=>{a(c.currentTarget)},r=()=>{a(null)},{data:d=[]}=He({queryKey:["addNewOptions",{templateType:s}],queryFn:async()=>{const p=(await sm()).filter(g=>g.get("name")!=="Lite").map(g=>{const m=`${g.get("name")} Template`,f=`/documents/templates/${s}/${g.id}${window.location.search}`;return{label:m,to:f,kind:"template"}});return[{label:"Scratch",to:`/documents/templates/${s}/edit/new${window.location.search}`,kind:"scratch"},...p]},onError:c=>{an({title:"Error fetching menu item",showVerbose:!0,error:c})},refetchOnWindowFocus:!1,refetchOnMount:!1,retry:!1,staleTime:600*1e3,cacheTime:1200*1e3,keepPreviousData:!0});return t.jsxs("div",{children:[t.jsx(we,{id:"document-tools-button","aria-controls":i?"document-tools-menu":void 0,"aria-haspopup":"true","aria-expanded":i?"true":void 0,color:"secondary",variant:"outlined",size:"small",onClick:l,sx:{minHeight:"40px"},"data-cy":"documentToolsMenu",children:"Tools"}),t.jsxs(kt,{id:"document-tools-menu",anchorEl:o,open:i,onClose:r,MenuListProps:{"aria-labelledby":"document-tools-button"},children:[d.map(({label:c,to:u,kind:p})=>t.jsxs(ue,{component:Do,to:u,onClick:r,children:[t.jsx($e,{children:p==="scratch"?t.jsx(Yu,{fontSize:"small"}):t.jsx(Xu,{fontSize:"small"})}),t.jsx(Te,{children:c})]},c)),t.jsx(ie,{}),t.jsxs(ue,{onClick:()=>{e(),r()},"data-cy":"restoreDocument",children:[t.jsx($e,{children:t.jsx(Zu,{fontSize:"small"})}),t.jsx(Te,{children:"Restore"})]})]})]})},Vm=async n=>{try{return await se.Cloud.run("getContractSnapshots",n)}catch(e){throw await rn(e),e}},Km=async n=>{const{templateId:e,type:s="contract",limit:o=10,page:a=1,deletedDocs:i=!1}=n,l=new se.Query("ContractObjectSnapshot");if(i)l.equalTo("type",s);else if(e){const p=new se.Object("ContractObject");p.id=e,l.equalTo("contractObject",p)}const r=se.User.current(),d=r==null?void 0:r.get("company");l.equalTo("company",d),l.equalTo("isDeleted",i),l.descending("createdAt"),l.select(["createdBy","createdAt","objectId","displayName"]),l.include(["createdBy"]),l.limit(o);const c=(a-1)*o;return l.skip(c),await l.find()},Um=async n=>{const{templateId:e,type:s="contract",deletedDocs:o=!1}=n,a=new se.Query("ContractObjectSnapshot");if(o)a.equalTo("type",s);else if(e){const l=new se.Object("ContractObject");l.id=e,a.equalTo("contractObject",l)}return a.equalTo("isDeleted",o),a.descending("createdAt"),a.select(["createdBy","createdAt","objectId","displayName"]),a.include(["createdBy"]),await a.count()},Gm=async n=>n.map(s=>{const o=s.get("createdBy"),a=s.get("createdAt"),i=s.get("displayName"),l=o?`, ${o.get("nameFirst")}`:"unknown",d=`${o?o.get("nameLast"):""}${l}`,c=Qt(a).format("MM/DD/YYYY @ h:mm a");return{id:s.id,displayName:i,user:d,timeStamp:c}}),Jm=async n=>{try{await se.Cloud.run("restoreContractObject",{objectId:n})}catch(e){throw await rn(e),e}},Ec={snapshotTable:{my:2,border:"1px solid",borderColor:"divider",borderTopLeftRadius:8,borderTopRightRadius:8,overflow:"hidden",position:"relative"},snapshotTableHeader:{backgroundColor:"gray1.main",padding:"0 36px 0 32px",alignItems:"center",minHeight:"48px"},snapshotTableBody:{height:"400px",overflowY:"auto",scrollbarGutter:"stable",".snapshotTableRow":{padding:"0 32px",cursor:"pointer",borderBottom:"1px solid",borderColor:"divider",alignItems:"center",minHeight:"48px","&:hover":{backgroundColor:"gray2.main"}}},tablePagination:{".MuiTablePagination-toolbar":{minHeight:"30px"},".MuiTablePagination-selectLabel":{marginBottom:"2.5px"},".MuiTablePagination-displayedRows":{marginBottom:"0px"}}},Ym=()=>{const n=Ec;return t.jsxs(pe,{container:!0,flexWrap:"nowrap",gap:2,sx:n.snapshotTableHeader,children:[t.jsx(pe,{size:"grow",children:t.jsx(z,{variant:"subtitle2",children:"Template"})}),t.jsx(pe,{width:200,children:t.jsx(z,{variant:"subtitle2",children:"User"})}),t.jsx(pe,{width:200,children:t.jsx(z,{variant:"subtitle2",children:"Date Archived"})}),t.jsx(pe,{width:50,children:t.jsx(z,{variant:"subtitle2"})})]})},Xm=({snapshot:n,restoreThisVersion:e})=>t.jsxs(pe,{id:n.id,container:!0,flexWrap:"nowrap",gap:2,className:"snapshotTableRow",children:[t.jsx(pe,{size:"grow",children:n.displayName}),t.jsx(pe,{width:200,children:n.lastEditedBy}),t.jsx(pe,{width:200,children:n.archivedDate}),t.jsx(pe,{width:50,children:t.jsx(Q,{title:"Restore deleted version",placement:"right",enterDelay:3e3,children:t.jsx(ye,{color:"secondary","aria-label":"Restore deleted version",onClick:()=>e({snapshotId:n.id,archivedDate:n.archivedDate}),children:t.jsx(Gr,{color:"secondary"})})})})]},n.id),Zm=n=>{const{onClose:e,refetchContractObjects:s}=n,o=Ec,{templateType:a="contract"}=_n(),[i,l]=y.useState(0),[r,d]=y.useState(10),{data:c=[],isFetching:u,refetch:p}=He({queryKey:["docSnapshots",{page:i,limit:r,templateType:a}],queryFn:async()=>await Vm({page:i,limit:r,templateType:a,deletedDocs:!0}),retry:!1,refetchOnWindowFocus:!1,onError:x=>an({title:"Error Fetching Document Snapshots",error:x}),staleTime:1/0,cacheTime:1/0}),{mutateAsync:h,isLoading:g}=Vt({mutationKey:["restoreDocSnapshot"],mutationFn:async({snapshotId:x,archivedDate:m})=>(await Jm(x),p(),s(),{snapshotId:x,archivedDate:m}),onError:x=>an({title:"Error Restoring Document Snapshot",error:x}),onSuccess:x=>{e(),Ns({title:"Document Restored",msg:`Document has been restored to the version from ${x.archivedDate}.`})}});return t.jsxs(N,{sx:o.snapshotTable,children:[(g||u)&&t.jsx(Tn,{sx:{zIndex:7,position:"absolute",backgroundColor:"rgba(0, 0, 0, 0.1)"},open:g||u,children:t.jsx(vt,{color:"primary",size:50})}),t.jsx(Ym,{}
1),t.jsx(N,{sx:o.snapshotTableBody,children:c.map(x=>t.jsx(Xm,{snapshot:x,restoreThisVersion:h},`snapshot-${x.id}`))}),t.jsx(ie,{}),t.jsx(ns,{component:"div",sx:o.tablePagination,count:c.length<r?c.length:-1,page:i,onPageChange:(x,m)=>l(m),rowsPerPage:r,onRowsPerPageChange:x=>{l(0),d(parseInt(x.target.value,10))},rowsPerPageOptions:[10,25,50,100]})]})},Qm=n=>{const{open:e=!1,onClose:s=()=>{},refetchContractObjects:o}=n;return t.jsx(zo,{modalContainerProps:{sx:{minWidth:1e3,width:1e3}},title:"Restore deleted version",open:e,onClose:s,children:t.jsx(Zm,{onClose:s,refetchContractObjects:o})})},eg=()=>{const{documents:n=[],fetchingDocuments:e,page:s,limit:o,setParam:a,officeOptions:i,fetchingOfficeOption:l,selectedOffices:r,onOfficeFilterChange:d,selectedStates:c,onStateFilterChange:u,searchText:p,handleSearch:h,stateOptions:g,fetchingStateOption:x,setSortState:m,sortState:f,categoryOptions:j,selectedCategories:S,onCategoryFilterChange:w,viewMode:C,setViewMode:v,showFolders:I,folderTiles:D,folderCount:F,selectedFolder:M,selectedFolderLabel:R,onFolderClick:P,onFolderBack:k,isSortable:T,showSnapshotModal:B,setShowSnapShotModal:L,refetchContractObjects:H}=Hm(),G=y.useMemo(()=>i.filter(K=>K.value!=="**no-office**"),[i]),ne=y.useMemo(()=>r==null?void 0:r.filter(K=>K.value!=="**no-office**"),[r]),le=Lc;let re=-1;I?re=F:n.length<o&&(re=n.length+s*o);const O=t.jsx(Un,{label:"Select Category(s)",value:S,options:j,onChange:w,showSelectedCount:!0,disableCloseOnSelect:!0,chipDisabled:!0,showSelectAll:(j==null?void 0:j.length)>1,selectAllValues:j,size:"small",sx:{m:0,width:220},isOptionEqualToValue:(K,U)=>K.value===(U==null?void 0:U.value),showSelectedCountLimit:3,selectedCountLabel:(S==null?void 0:S.length)===j.length?"Categories: All":`Categories: ${S==null?void 0:S.length}`,"data-cy":"categoryFilter"});return t.jsxs(Bo,{sx:{height:"100%",pt:2},children:[t.jsxs($o,{alignItems:"flex-end",sx:{mb:2},children:[t.jsxs(he,{flexDirection:"row",gap:2,children:[I&&O,!I&&t.jsxs(t.Fragment,{children:[t.jsx(Un,{label:"Select Office(s)",value:r,loading:l,options:i,onChange:d,showSelectedCount:!0,disableCloseOnSelect:!0,chipDisabled:!0,showSelectAll:(i==null?void 0:i.length)>1,selectAllValues:i,size:"small",sx:{m:0,width:220},isOptionEqualToValue:(K,U)=>K.value===(U==null?void 0:U.value),showSelectedCountLimit:3,selectedCountLabel:(ne==null?void 0:ne.length)===G.length?"Offices: All":`Offices: ${ne==null?void 0:ne.length}`,"data-cy":"officeFilter"}),t.jsx(Un,{label:"Select State(s)",value:c,loading:x,options:g,onChange:u,showSelectedCount:!0,disableCloseOnSelect:!0,chipDisabled:!0,showSelectAll:(g==null?void 0:g.length)>1,selectAllValues:g,size:"small",sx:{m:0,width:220},isOptionEqualToValue:(K,U)=>K.value===(U==null?void 0:U.value),showSelectedCountLimit:3,selectedCountLabel:(c==null?void 0:c.length)===g.length?"States: All":`States: ${c==null?void 0:c.length}`,"data-cy":"stateFilter"}),C==="flat"&&O,t.jsx(Tc,{id:"search-documents",placeholder:"Search Documents",searchedText:p,handleSearch:h,"data-cy":"searchDocuments"})]})]}),t.jsxs(he,{flexDirection:"row",gap:2,children:[!I&&t.jsx(Mc,{setSortState:m,sortState:f}),t.jsxs(Gt,{value:C,exclusive:!0,size:"small",color:"secondary",onChange:(K,U)=>{U&&v(U)},"data-cy":"documentViewToggle",children:[t.jsx(Ve,{value:"flat","aria-label":"grid view",children:t.jsx(Q,{title:"Grid view",children:t.jsx(Qu,{fontSize:"small"})})}),t.jsx(Ve,{value:"folder","aria-label":"category folder view",children:t.jsx(Q,{title:"Folder view",children:t.jsx(ep,{fontSize:"small"})})})]}),t.jsx(qm,{onOpenSnapshot:()=>L(!0)})]})]}),t.jsxs(N,{sx:le.documentsWrap,children:[C==="folder"&&M&&t.jsxs(Vr,{"aria-label":"breadcrumb",sx:{display:"flex",alignItems:"center",mb:2},"data-cy":"documentFolderBreadcrumbs",children:[t.jsx(we,{variant:"text",color:"inherit",onClick:k,"data-testid":"documentFolderBack",sx:{minWidth:"auto",p:0,font:"inherit",textTransform:"none","&:hover":{backgroundColor:"transparent",textDecoration:"underline"}},children:"Documents"}),t.jsx(z,{children:R})]}),I&&t.jsx(Wm,{folders:D,onFolderClick:P}),!I&&(e?t.jsx(Nc,{}):t.jsx($m,{documents:n,page:s,limit:o,isSortable:T}))]}
1),t.jsx(ns,{rowsPerPageOptions:[10,25,50,100],component:"div",sx:le.tablePagination,count:re,page:s,onPageChange:(K,U)=>a("page",U),rowsPerPage:o,onRowsPerPageChange:K=>{a("limit",parseInt(K.target.value,10)),a("page",0)}}),t.jsx(Qm,{open:B,onClose:()=>L(!1),refetchContractObjects:H})]})},Va={customDocumentTable:{".custom-document-table-row, .custom-document-table-header":{"& .MuiGrid-item":{px:2}}},customDocumentTableHeader:{height:"52px",alignItems:"center","& .MuiGrid-item":{borderRight:"2px solid",borderColor:"divider","&:last-child":{borderRight:"none"}}},customDocumentTableRow:{borderTop:"2px solid",borderColor:"divider",height:"52px",alignItems:"center","&:last-child":{borderBottom:"2px solid",borderColor:"divider"}},customDocIcon:{height:"auto",width:"auto",display:"flex",alignItems:"center","& svg":{height:"16px",width:"auto"}},customDocLink:{textTransform:"none",textDecoration:"underline"},customTextField:{width:"100%",".MuiOutlinedInput-notchedOutline":{borderRadius:0,borderColor:"transparent"},".MuiInputBase-input":{px:2}}},tg=()=>{const n=Va;return t.jsxs(mt,{container:!0,item:!0,flexWrap:"nowrap","aria-label":"Custom Document header",sx:n.customDocumentTableHeader,className:"custom-document-table-header",children:[t.jsx(mt,{id:"custom-document-type",item:!0,xs:3,children:t.jsx(z,{variant:"subtitle2",children:"Document Type"})}),t.jsx(mt,{id:"custom-document-icon",item:!0,xs:3,children:t.jsx(z,{variant:"subtitle2",textAlign:"center",children:"Icon"})}),t.jsx(mt,{id:"custom-document-delete",item:!0,xs:3,children:t.jsx(z,{variant:"subtitle2",textAlign:"center",children:"Delete Doc Type"})}),t.jsx(mt,{id:"custom-document-manage-templates",item:!0,xs:3,children:t.jsx(z,{variant:"subtitle2",children:" "})})]})},ng=n=>{var p,h,g,x,m;const{index:e,field:s,handleIconModalOpen:o,removeCustomDocument:a}=n,{formState:{errors:i},register:l}=tp(),r=Va,[d,c]=y.useState(!1),u=f=>{_o({title:"Remove Custom Document",msg:`Are you sure you want to delete Custom Document Type: ${s.title||"New Document Type"}?`,titleColor:"error",onConfirm:async()=>{c(!0);try{await a(f||"",e)}catch{c(!1)}finally{c(!1)}}})};return t.jsxs(mt,{id:s.id,container:!0,item:!0,flexWrap:"nowrap","aria-label":"Custom Document header",sx:r.customDocumentTableRow,className:"custom-document-table-row",children:[t.jsx(mt,{"aria-labelledby":"custom-document-type",item:!0,xs:3,sx:{p:"0 !important"},children:t.jsx(Le,{...l(`mainMenuOptions.${e}.title`,{required:!0}),color:"secondary",sx:r.customTextField,"data-cy":"customDocumentType",error:!!((h=(p=i==null?void 0:i.mainMenuOptions)==null?void 0:p[e])!=null&&h.title),helperText:(m=(x=(g=i==null?void 0:i.mainMenuOptions)==null?void 0:g[e])==null?void 0:x.title)==null?void 0:m.message})}),t.jsx(mt,{"aria-labelledby":"custom-document-icon",item:!0,xs:3,textAlign:"center",children:s!=null&&s.icon?t.jsx(ye,{color:"secondary",onClick:()=>o(s,e),"data-cy":"customDocumentIcon","data-testid":"customDocumentIcon",children:t.jsx(At,{baseClassName:"fa-regular",className:s.icon.startsWith("fa-")?s.icon:`fa-${s.icon}`,sx:r.customDocIcon})}):t.jsx(we,{variant:"text",color:"secondary",onClick:()=>o(s,e),"data-cy":"selectIcon",children:t.jsx(z,{sx:r.customDocLink,children:"Select an Icon"})})}),t.jsx(mt,{"aria-labelledby":"custom-document-delete",item:!0,xs:3,textAlign:"center",children:d?t.jsx(vt,{size:20,color:"error"}):t.jsx(ye,{color:"error","aria-label":"delete",onClick:()=>u(s.objectId),"data-cy":"deleteCustomDocumentType",children:t.jsx(At,{baseClassName:"fa-regular",className:"fa-trash",sx:r.customDocIcon})})}),t.jsx(mt,{"aria-labelledby":"custom-document-manage-templates",item:!0,xs:3,children:t.jsx(we,{component:Do,to:{pathname:`custom/templates/${s.objectId}`},disabled:s.isNew,variant:"text",color:"secondary","data-cy":"manageTemplates",endIcon:t.jsx(At,{baseClassName:"fa-regular",className:"fa-chevron-right",sx:r.customDocIcon}),children:t.jsx(z,{sx:{...r.customDocLink,opacity:s.isNew?.5:1},children:"Manage Templates"})})})]},s.id)},sg={customDocIcon:{height:"auto",width:"auto",display:"flex",alignItems:"center",fontSize:"16px"}},og=[{tag:"archive"},{tag:"book"},{tag:"briefcase"},{tag:"cabinet-filing"},{tag:"chart-bar"},{tag:"chart-pie"},{tag:"city"},{tag:"clipboard"},{tag:"globe"},{tag:"industry-alt"},{tag:"laptop-house"},{tag:"presentation"},{tag:"tasks-alt"},{tag:"thumbtack"},{tag:"user-chart"},{tag:"broadcast-tower"},{tag:"paper-plane"},{tag:"drafting-compass"},{tag:"pencil-ruler"},{tag:"user-hard-hat"},{tag:"award"},{tag:"file-certificate"},{tag:"books"},{tag:"house-day"},{tag:"leaf"},{tag:"lightbulb"},{tag:"seedling"},{tag:"solar-panel"},{tag:"wind-turbine"},{tag:"analytics"},{tag:"receipt"},{tag:"hard-hat"},{tag:"bath"},{tag:"house"},{tag:"window-frame"},{tag:"window-frame-open"},{tag:"alarm-clock"},{tag:"shield-alt"},{tag:"forklift"},{tag:"pallet-alt"},{tag:"shipping-fast"},{tag:"anchor"},{tag:"magnet"},{tag:"map-signs"},{tag:"newspaper"},{tag:"rocket"},{tag:"umbrella"},{tag:"university"},{tag:"money-check-edit"},{tag:"user-lock"},{tag:"user-shield"},{tag:"space-station-moon-alt"},{tag:"cat-space"},{tag:"frog"},{tag:"ruler-combined"},{tag:"scroll-old"},{tag:"album-collection"},{tag:"flux-capacitor"}],ag=n=>{const{openIconModal:e,handleIconModalClose:s,selectedDoc:o,handleIconUpdate:a}=n,i=sg,[l,r]=y.useState();return t.jsxs(zo,{open:e,onClose:()=>{s(),r(void 0)},title:`Select Icon For ${(o==null?void 0:o.title)||""}`,children:[t.jsx(N,{children:t.jsx(mt,{container:!0,children:og.map(d=>t.jsx(mt,{item:!0,sx:{width:"40px",height:"40px"},children:t.jsx(ye,{onClick:()=>r(d.tag),sx:{color:l===d.tag?"secondary.main":"body1.main","&:hover":{color:"secondary.main"}},children:t.jsx(At,{baseClassName:"fa-regular",className:`fa-${d.tag}`,sx:i.customDocIcon})})},d.tag))})}),t.jsx(N,{textAlign:"right",children:t.jsx(we,{variant:"contained",size:"small",disabled:!l,onClick:()=>{s(),r(void 0),l&&a(l)},children:"Use This Icon"})})]})},ig=n=>{const{removeCustomDocument:e,fields:s,fetching:o,update:a,watchMainMenuOptions:i,currentOffice:l}=n,r=Va,[d,c]=y.useState(!1),[u,p]=y.useState(),[h,g]=y.useState(),x=(j,S)=>{c(!0),p(j),g(S)},m=()=>{c(!1),p(void 0),g(void 0)},f=j=>{h!==void 0&&a(h,{...i[h],icon:j})};return t.jsxs(mt,{container:!0,"aria-label":"Custom Document Table",sx:r.customDocumentTable,children:[t.jsx(ag,{openIconModal:d,handleIconModalClose:m,selectedDoc:u,handleIconUpdate:f}),t.jsx(tg,{}),t.jsx(Tn,{sx:{zIndex:9,position:"absolute",backgroundColor:"rgba(0, 0, 0, 0.2)"},open:o,children:t.jsx(vt,{color:"primary",size:50})}),!l&&t.jsx(z,{variant:"body1",children:"No Office Selected"}),!o&&s.length===0?t.jsx(z,{variant:"body1",children:"No Document Type Found"}):s.map((j,S)=>t.jsx(ng,{index:S,removeCustomDocument:e,field:j,handleIconModalOpen:x,update:a,currentOffice:l},j.id))]})},lg=n=>{const{children:e,fields:s,moveItems:o,setSnackbar:a}=n,i=Qn(In(es),In(Jr,{coordinateGetter:np})),l=async r=>{var u,p;const{active:d,over:c}=r;if(c&&d.id!==c.id)try{o((u=d.data.current)==null?void 0:u.sortable.index,(p=c.data.current)==null?void 0:p.sortable.index)}catch{a({children:"There was an error updating the order",severity:"error"})}};return t.jsx(ts,{sensors:i,collisionDetection:Sn,onDragEnd:l,modifiers:[sp],children:t.jsx(_s,{items:s,strategy:No,children:e})})},rg=()=>{var R;const{officeOptions:n}=Ha(),{params:e,setParam:s}=wc(),{setSnackbar:o}=Ws(),a=Rs(),i=y.useMemo(()=>{var P;return((P=e==null?void 0:e.currentOffices)==null?void 0:P[0])||""},[e==null?void 0:e.currentOffices]),{fetching:l,mainMenuOptions:r,onError:d,refetchMainMenuOptions:c,removeCustomDocument:u}=qa(i),p=Yr({mode:"all",defaultValues:{mainMenuOptions:r||[]}}),{control:h,reset:g,handleSubmit:x,watch:m,formState:{isSubmitting:f,isDirty:j},getValues:S}=p,w=async P=>{try{const{mainMenuOptions:k=[]}=P;if(!i)return;await vc(i,k),a.invalidateQueries({queryKey:["mainMenuOptions",i]}),o({severity:"success",children:"Successfully saved Document Types"})}catch(k){d(k,"Save Custom Document Error")}};y.useEffect(()=>{g({mainMenuOptions:r})},[r,i,g]);const{fields:C,append:v,move:I,update:D}=Xr({control:h,name:"mainMenuOptions"}),{mainMenuOptions:F}=m(),M=P=>{const k=S(),T=k.mainMenuOptions.filter((B,L)=>L!==P);if(j){g({...k,mainMenuOptions:T},{keepDefaultValues:!0});return}g({...k,mainMenuOptions:T})};return t.jsxs(Bo,{children:[t.jsxs($o,{alignItems:"flex-end",children:[t.jsx(he,{flexDirection:"row",columnGap:2,children:t.jsx(_t,{sx:{m:0,minWidth:200},label:"Select Office",size:"small",options:n,value:((R=n.find(P=>i===P.value))==null?void 0:R.value)||"",onChange:P=>{const k=P.target.value;
1s("offices",[k])},"data-cy":"selectOffice"})}),t.jsxs(he,{flexDirection:"row",columnGap:2,children:[t.jsx(rm,{copyToOfficeId:i,configKeys:dm.mainMenuOptions,appTitle:cm.mainMenuOptions,"data-cy":"copyFromAnotherOffice",onCopyComplete:()=>c()}),t.jsx(we,{color:"primary",variant:"outlined",size:"small",onClick:()=>{const P=ss();v({id:P,objectId:P,isNew:!0,uploadSettings:{includedOffices:[i]}})},sx:{minWidth:"100px"},"data-cy":"addNewDocType",children:"Add New Doc Type +"}),t.jsx(Os,{loading:f,disabled:!j,onClick:x(w),sx:{minWidth:"100px"},"data-cy":"save",children:"Save"})]})]}),t.jsx(lg,{fields:C,moveItems:I,setSnackbar:o,children:t.jsx(op,{...p,children:t.jsx(ig,{fields:C,fetching:l,update:D,watchMainMenuOptions:F,currentOffice:i,removeCustomDocument:async(P,k)=>await u(P,{onSuccess:()=>M(k)})})})})]})},cg=n=>e=>async s=>{if(s.type==="LOGIN"){const{config:o,user:a,isCorporateAdmin:i}=s,l=o.toJSON(),{company:r}=l,{isDemo:d}=r;window.dataLayer.push({isDemo:d});const c=new se.Query("SentDocuSign");c.equalTo("company",o.get("company"));const u=await c.count(),p={userId:a.id,"Account ID":r.objectId,"Account Name":r.name,Docusigns:u,"Account Size":r.maxActiveUsers};i&&window.dataLayer.push({event:"isCorporateAdminEvent",isCorporateAdmin:!0}),window.dataLayer.push(p)}if(s.type==="PUSH_TO_DATA_LAYER"){const{variablesForLayer:o}=s;window.dataLayer&&window.dataLayer.push(o)}return e(s)},dg=(n={},e)=>{switch(e.type){case"CREATE_COMPANY":return{...n,...e.result};case"FETCH_PACKAGE_CATEGORIES":return{...n,packageCategories:e.packageCategories};default:return n}},ug=(n={},e)=>{switch(e.type){case"SHOW_SUCCESS":return{show:!0,type:"success",title:e.title,confirm:e.onConfirm,message:e.message};case"SHOW_ERROR":return{show:!0,type:"error",title:e.title,confirm:e.onConfirm,message:e.message};case"SHOW_WARNING":return{show:!0,type:"warning",title:e.title,confirm:e.onConfirm,message:e.message};case"HIDE_ALERT":return{show:!1};default:return n}},pg={allMainMenuOptions:[]},hg=n=>{const e=n?n.toJSON():[];return e.mainMenuOptions=e.mainMenuOptions||[],e},mg=(n=pg,e)=>{switch(e.type){case"SET_AUTH_SLICE":{const{config:s={}}=e;return{...n,offices:e.offices||[],config:{...s,categories_:[]},user:e.user,officeCountry:e.officeCountry,officeLevelCountry:!!e.officeLevelCountry}}case"LOGIN":{const{favicon:s,pageTitle:o}=e.favicon;return{...n,loading:!1,user:e.user,company:e.user.get("company"),apiKey:e.user.get("company").get("apiKey"),offices:e.offices||[],selectedOffice:e.selectedOffice,config:hg(e.config),isCorporateAdmin:e.isCorporateAdmin||!1,groupMeGroups:[],partnerLogo:e.partnerLogo?{url:e.partnerLogo._url}:void 0,favicon:s?{...s,pageTitle:o}:void 0,partnerTags:e.partnerTags||[],plan:e.plan}}case"SET_COMPANY":return{...n,company:e.company};case"SET_LOADING":return{...n,loading:e.loading};case"LOGOUT":{let s;if(e.partnerLogo&&e.partnerLogo._url){const{_url:a}=e.partnerLogo;s={url:a}}else n.config&&(s=n.config.companyLogo);let o;if(e.favicon){const{favicon:a,pageTitle2:i}=e.favicon;o={...a,pageTitle:i}}else n.config&&(o=n.config.favicon);return{query:n.query,partnerLogo:s,favicon:o,config:{placeholders:[],waterMark:{}},offices:[]}}case"SELECTED_OFFICE":return{...n,selectedOffice:e.selectedOffice,config:e.config.toJSON(),groupMeGroups:n.groupMeGroups||[]};case"UPDATE_CONFIG_STATE":return{...n,config:{...n.config,...e.updates}};case"SET_API_KEY":return{...n,apiKey:e.apiKey};case"SET_GROUP_ME_GROUPS":return{...n,groupMeGroups:e.groups||[]};case"OFFICE_DELETE":return{...n,offices:n.offices.filter(({id:s})=>s!==e.officeId)};case"SET_QUERY":return{...n,query:e.query};case"SET_OFFICES":return{...n,offices:e.offices};case"SET_ALL_MAIN_MENU_OPTIONS":return{...n,allMainMenuOptions:e.options};default:return n}},gg={contractSendingAPIs:[]},xg=(n=gg,e)=>{switch(e.type){case"CONTRACT_SENDING_APIS":return e.loaded?{...n,contractSendingAPIs:e.apis}:n;case"FETCH_COMPANIES":return{...n,companies:e.companies};case"FETCH_OFFICES":switch(e.descriptor){case"source":return{...n,sourceOffices:e.offices};case"destination":return{...n,destinationOffices:e.offices};default:return n}case"FETCH_CATEGORIES":return{...n,categories:e.categories};case"FETCH_STYLES":return{...n,styles:e.styles};case"FETCH_STATES":return{...n,states:e.states,stateOptions:e.stateOptions};default:return n}},fg=(n={show:!1,message:"loading"},e)=>{switch(e.type){case"SHOW_LOADER":return{...n,show:!0,message:e.message||"loading"};case"HIDE_LOADER":return{...n,show:!1};default:return n}},bg=(n={},{type:e,...s})=>{switch(e){case"PASTEBOARD_SET_VALUE":return{...n,[s.key]:s.value};case"PASTEBOARD_SET_VALUES":return{...n,...s.values};default:return n}},yg={},jg=(n=yg,e)=>{switch(e.type){case"SET_TEMPLATE_SCROLL_REF":{const{mainTemplatesRef:s}=e;return{...n,mainTemplatesRef:s}}case"ON_TEMPLATE_SCROLL":{const{scrollEventData:s}=e;return{...n,scrollEventData:s}}default:return n}},rl={viewSelection:1,isDragging:!1,builderOverride:null},Cg=(n=rl,{type:e,...s})=>{switch(e){case"SET_FEATURE_FLAGS":return{...n,featureFlags:s.featureFlags};case"TEMPLATES_EDIT_SET_CURRENT_WORKING_TEMPLATE":return{...n,currentWorkingId:s.objectId};case"TEMPLATES_EDIT_SET_INITIAL_STATE":return{...n,[s.template.objectId]:s.template};case"LOGOUT":return rl;
1case"TEMPLATES_EDIT_SET_CHANGES":return{...n,[s.templateObjectId]:{...n[s.templateObjectId],...s.changes}};case"TEMPLATE_EDIT_SET_SHOW_WATERMARK_TOOLBAR":return{...n,[s.template]:{...n[s.template],showWatermarkToolbar:s.show}};case"TEMPLATES_SET_EDIT_CELL_ITEM":return{...n,editCellItem:s.editCellItem};case"TEMPLATE_EDIT_SET_ON_DRAG_END_CALLBACK":return{...n,onDragEndCallbacks:{[s.identifier]:s.callback}};case"TEMPLATE_EDIT_SET_SCALE":return{...n,scale:s.scale};case"TEMPLATES_SET_CONTRACT_DATA":return{...n,[s.templateObjectId]:{...n[s.templateObjectId],contractData:s.contractData}};case"TEMPLATE_EDIT_SET_SHOW_MEASURE_SHEET_ITEMS":return{...n,linkMeasureSheetItemsShow:s.show,linkMeasuresheetItemsKey:s.key,linkMeasureSheetItemsSingleSelect:s.singleSelect,linkMeasureSheetItemsTitle:s.title,linkMeasureSheetItemsShowCustomProduct:s.showCustomProduct};case"TEMPLATE_EDIT_SET_SHOW_MANAGE_IMAGES":return{...n,showManageImages:s.show};case"TEMPLATE_SET_MEASURE_SHEET_ITEMS":return{...n,measureSheetItems:s.items};case"TEMPLATE_EDIT_SET_SUBCATEGORY_FILTER":return{...n,subCategoryFilter:s.subCategory};case"TEMPLATE_EDIT_SET_CATEGORY_FILTER":return{...n,categoryFilter:s.category};case"TEMPLATE_SET_DRAGGABLE_TYPE":return{...n,draggableType:s.draggableType};case"TEMPLATE_SET_VIEW_SELECTION":return{...n,viewSelection:s.viewSelection};case"TEMPLATE_SET_IS_DRAGGING":return{...n,isDragging:s.payload};case"TEMPLATE_SET_BUILDER_OVERRIDE":return{...n,builderOverride:s.builderOverride};case"SET_VALID_LINKED_COUNT":return{...n,validLinkedItemCounts:{...n.validLinkedItemCounts,...s.newCount}};case"SET_SHOW_ALERT_MODAL":return{...n,showAlertModal:s.showAlertModal};default:return n}},cl={templateGroups:{items:[],selectedGroup:{contractsObjects:[]}}},Ig=(n=cl,{type:e,...s})=>{switch(e){case"TEMPLATES_SET_TEMPLATES":return{...n,[s.templateType]:{...n[s.templateType],templates:s.templates}};case"LOGOUT":return cl;case"SET_SELECTED_CONTRACT_OBJECT_GROUPS":return{...n,templateGroups:{...n.templateGroups,selectedGroup:s.contractObjectGroup}};case"SET_CONTRACT_OBJECT_GROUPS":return{...n,templateGroups:{items:[...s.contractObjectGroups]}};case"TEMPLATES_SET_INCLUDED_OFFICES_FILTER":return{...n,[s.templateType]:{...n[s.templateType],includedOfficesFilter:s.includedOfficesFilter}};case"TEMPLATES_SET_INCLUDED_STATES_FILTER":return{...n,[s.templateType]:{...n[s.templateType],includedStatesFilter:s.includedStatesFilter}};case"TEMPLATES_SET_PAGE":return{...n,[s.templateType]:{...n[s.templateType],page:s.page}};case"TEMPLATES_SET_LIMIT":return{...n,[s.templateType]:{...n[s.templateType],limit:s.limit}};case"TEMPLATES_SET_COUNT":return{...n,[s.templateType]:{...n[s.templateType],count:s.count}};default:return n}},Sg=Zr().subtract(30,"days").startOf("day").toISOString(),vg=Zr().endOf("day").toISOString(),Tg={startDate:Sg,endDate:vg,count:0,limit:10,skip:0,items:[{id:1},{id:2},{id:3}],details:{}},wg=(n={...Tg},e)=>{switch(e.type){case"SET_PLAN_CONFIG":return{...n,...e.config};case"SET_PLANS":return console.log("plan reducer:",e),{...n,items:[...e.items]};case"SET_PLANS_DATE_FILTER":return{...n,...e.params};case"SET_PLANS_FILTER":return{...n,...e.params};case"SET_PLAN_DETAILS":return{...n,details:{...e.details}};default:return n}},kg=ap({admin:dg,alert:ug,auth:mg,config:xg,loading:fg,pasteBoard:bg,templates:Ig,templateScrollContext:jg,templatesEdit:Cg,plan:wg}),Pg=rp,Ac=ip(kg,Pg(lp(cp,cg))),Ot=n=>({type:"PUSH_TO_DATA_LAYER",variablesForLayer:n}),Dg=({title:n,message:e,onConfirm:s=()=>{}})=>o=>(o(Ot({event:"leapErrorEvent",eventCategory:"Errors",eventAction:window.location.pathname,eventLabel:`${n} - ${e}`})),o({type:"SHOW_ERROR",title:n,message:e,onConfirm:s})),Fc=({title:n,message:e,onConfirm:s=()=>{}})=>o=>o({type:"SHOW_WARNING",title:n,message:e,onConfirm:s}),Ka=()=>({type:"HIDE_ALERT"}),Jo=n=>({type:"SHOW_LOADER",message:n}),Ss=()=>({type:"HIDE_LOADER"}),Ce=n=>{let e="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let o=0;o<n;o+=1)e+=s.charAt(Math.floor(Math.random()*s.length));return e},Rc=(n,e,s)=>{const o=Array.from(n),[a]=o.splice(e,1);return o.splice(s,0,a),o},fa=([n,...e],[s,...o])=>n===void 0&&s===void 0?[]:n===void 0?[s,...o]:s===void 0?[n,...e]:[n,s,...fa(e,o)],as=(n,e="thumbnail",s)=>new Promise((o,a)=>
1{if(!s){a(new Error("Cannot create new file with no file source"));return}const i=new window.FileReader;i.onload=l=>{const r=n.name.split(".").pop(),c=`${e.split(".").join("")}.${r}`,u=new se.File(c,n);u.addTag("fileSource",s),u._url=l.target.result,u.isNew=!0,o(u)},i.readAsDataURL(n)}),Og=(n,e="thumbnail",s="thumbnail")=>as(n.target.files[0],e,s),_c={datePicker:"MM/dd/yyyy",dateTimePicker:"MM/dd/yyyy hh:mm a",timePicker:"h:mm a"},Ng=(n,e)=>{try{if(n&&n.length>0){const s=new Image;s.src=n,s.complete?e(!0):(s.onload=()=>{e(!0)},s.onerror=()=>{e(!1)})}else e(!1)}catch(s){e(!1),console.error("Broken image:",s)}},Kt=(n,e=!1,s=()=>{})=>async(o,a)=>{console.log("🚀 ~ file: auth.js ~ line 29 ~ error",n);const i=a();if(i&&i.alert&&i.alert.show)return;const{message:l,code:r,errors:d=[]}=n,c=l||r||d.map(p=>p.message||p.code||"");o(Ot({event:"leapErrorEvent",eventCategory:"Errors",eventAction:window.location.pathname,eventLabel:c}));const u=()=>{o(Dg({title:"Error!",message:c,onConfirm:()=>{s&&s(),o(Ka()),o(Ss())}}))};if(o(Ss()),n.code===209||!se.User.current()){e&&u();return}u()},Mg=n=>({type:"SET_COMPANY",company:n}),Lg=async()=>{const e=await se.User.current().get("company").fetch(),s=await se.Object.fetchAllWithInclude(e.get("offices"),"config"),o=lt.orderBy(s,r=>{var d;return(d=r.get("name"))==null?void 0:d.toLowerCase()},"asc");let a,i=!1;o.forEach(r=>{r.id===a&&(i=!0)}),(!a||a==="null"||!i)&&(a=o[0].id);const l=new se.Object("Office");return l.id=a,await l.fetch(),{selectedOffice:l,allOffices:o}},Be=(()=>{let n=null;return{ToasterComponent:()=>{const[o,a]=y.useState(!1),[i,l]=y.useState(""),[r,d]=y.useState("info"),[c,u]=y.useState(3e3);n=({message:h,timeout:g=3e3,severity:x="info"})=>{l(h),d(x),u(g),a(!0)};const p=()=>{a(!1)};return t.jsx(dp,{open:o,onClose:p,anchorOrigin:{vertical:"top",horizontal:"center"},autoHideDuration:c,children:t.jsx(Ur,{onClose:p,severity:r,sx:{width:"100%"},children:i})})},show:o=>{n?n(o):console.error("AppToaster.show() was called before the ToasterComponent was mounted.")}}})(),Eg=n=>({type:"SET_FEATURE_FLAGS",featureFlags:n}),Bc=n=>({type:"TEMPLATES_EDIT_SET_CURRENT_WORKING_TEMPLATE",objectId:n}),ee=n=>({type:"TEMPLATES_EDIT_SET_INITIAL_STATE",template:n}),Ne=n=>e=>e({type:"TEMPLATES_SET_EDIT_CELL_ITEM",editCellItem:n}),Ut=(n,e,s,o,a=!1)=>({type:"TEMPLATE_EDIT_SET_SHOW_MEASURE_SHEET_ITEMS",show:n,key:e,singleSelect:s,title:o,showCustomProduct:a}),jo=n=>({type:"TEMPLATE_EDIT_SET_SHOW_MANAGE_IMAGES",show:n}),Ag=n=>({type:"TEMPLATE_SET_DRAGGABLE_TYPE",draggableType:n}),Fg=(n,e)=>s=>(s(Ot({event:"documentView",eventCategory:"Documents",eventAction:"DocumentView",eventLabel:e})),s({type:"TEMPLATE_SET_VIEW_SELECTION",viewSelection:n})),Rg=n=>e=>(e(Ot({event:"documentBuilderMode",eventCategory:"Documents",eventAction:"BuilderMode",eventLabel:n?"Modern":"Legacy"})),e({type:"TEMPLATE_SET_BUILDER_OVERRIDE",builderOverride:n})),$c=(n=[],e)=>async s=>{try{if(!n.length||!e)return;const{cellItems:o=[]}=e.toJSON()||{},a={sourceObjectIds:n,cells:o},i=await se.Cloud.run("add_missing_placeholders",a);Be.show({message:i,timeout:3e3})}catch(o){s(Kt(o))}},_g=n=>({type:"ON_TEMPLATE_SCROLL",scrollEventData:n}),Bg=(n=!1)=>({type:"TEMPLATE_SET_IS_DRAGGING",payload:n}),$g=n=>({type:"SET_VALID_LINKED_COUNT",newCount:n}),zg=n=>({type:"SET_SHOW_ALERT_MODAL",showAlertModal:n});let dl;const zc={},bt=(n,e)=>{zc[n]=e},Wc=({children:n})=>{const e=ft(),[s,o]=[a=>e(Ag(a)),a=>e(Bg(a))];return t.jsx(up,{onDragUpdate:(a,i)=>{a.destination&&a.destination!=null&&(dl={...a.destination})},onDragEnd:(a,i)=>{const{reason:l,destination:r={},combine:d}=a,c=d?d.droppableId:r&&r.droppableId;if(l!=="DROP"||!c)return;const u=zc[c];u&&u({...a,destination:a.destination&&a.destination!=null?a.destination:dl}),o(!1)},onDragStart:a=>{o(!0);const{droppableId:i}=a.source,l=i.split("-").pop();s(l)},children:n})};Wc.propTypes={children:b.oneOfType([b.arrayOf(b.node),b.node]).isRequired};const Wg=n=>{const{children:e}=n;return t.jsx(pp,{store:Ac,children:t.jsx(Wc,{children:t.jsx(hp,{children:e})})})},Hg={size:"fontSize",bold:"fontBold",underline:"fontUnderline",name:"fontName",color:"fontColor",align:"alignment",file:"image",value:"value"},ul="header_cell",pl="header_cell";var mn;let tn=(mn=class{constructor(e,s,o){this.JSON=e,this.keys=["objectId","alignment","fontSize","fontBold","fontUnderline","fontName","fontColor","logoHeight","value","cellType","emptySpaceHeight","image"],this.containerKey=ul,this.pasteKey=pl,this.parent=s,this.groupIndex=o,this.showToolbar=!0,this.toolbarKey="sectionTitle",this.toolbarKeyMaps=Hg,this.toolboxKey="header-cell",e?(Object.assign(this,e),this.objectId=this.objectId||Ce(10)):(this.alignment=0,this.fontSize=10,this.fontBold=!1,this.fontUnderline=!1,this.fontName="",this.fontColor="0-0-0-1",this.logoHeight=40,this.value="New Item",this.cellType="default",this.emptySpaceHeight=4,this.image=void 0),this.objectId||(this.objectId=Ce(10));const a=this.getSourceObject();a&&(a.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),a.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.groupIndex}-${this.objectId}`}getPath(){if(!this.parent)return;const e=this.parent.cellItems.findIndex(({objectId:s})=>s===this.objectId);return[...this.parent.getPath(),e]}get toolbarKeys(){switch(this.cellType){case"image":return["align","file"];case"emptySpace":return[];default:switch(this.value){case"%companyLogo%":case"%image%":return["align"];default:return["size","bold","underline","name","color","align"]}}}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}clone(){const e=this.toJSON(),{image:s,...o}=e,a=at.cloneDeep(o);return a.objectId=Ce(10),a.image={...s},new mn(a,this.parent,this.groupIndex)}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e}async convertNewFiles(){if(this.image&&this.image.isNew){const{file:e}=this.image,o=`image.${e.type.split("/")[1]}`,a=new se.File(o,e);return await a.save(),this.image=a,this.image}return this.image}},W(mn,"ContainerKey",ul),W(mn,"PasteKey",pl),mn);const hl="header_item_group",ml="header_item_group",ws=class ws{constructor(e,s,o=Ce(10)){this.JSON=e,this.keys=[],this.parent=s,this.showToolbar=!0,this.toolbarKey="",this.toolbarKeys=[],this.toolbarKeyMaps={},this.toolboxKey="",this.containerKey=hl,this.pasteKey=ml,this.objectId=s?`${s.objectId}_${o}`:`${Ce(10)}_${o}`,e?this.cellItems=e.map(i=>new tn(i,this)):this.cellItems=[new tn(void 0,this,0)];const a=this.getSourceObject();a&&(a.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),a.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.objectId}`}getPath(){if(!this.parent)return;const e=this.parent.cellItems.findIndex(({objectId:s})=>s===this.objectId);return[...this.parent.getPath(),e]}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}clone(){const e=new ws([],this.parent);return e.cellItems=this.cellItems.map(s=>s.clone()),e}toJSON(){return this.cellItems.map(e=>e.toJSON())}async convertNewFiles(){const e=this.cellItems.map(s=>s.convertNewFiles());
1return this.cellItems.forEach(s=>{e.push(s.convertNewFiles())}),Promise.all(e)}};W(ws,"ContainerKey",hl),W(ws,"PasteKey",ml);let ht=ws;const qg={size:"valueFontSize",bold:"valueFontBold",underline:"valueFontUnderline",name:"valueFontName",color:"valueFontColor"},Vg={size:"noteFontSize",bold:"noteFontBold",underline:"noteFontUnderline",name:"noteFontName",color:"noteFontColor"},gl="signature_additional_line",xl="signature_additional_line";var gn;let yn=(gn=class{constructor(e,s){this.JSON=e,this.keys=["objectId","underline","value","note","valueFontSize","valueFontBold","valueFontUnderline","valueFontName","valueFontColor","noteFontSize","noteFontBold","noteFontUnderline","noteFontName","noteFontColor"],this.containerKey=gl,this.pasteKey=xl,this.parent=s,this.toolbarKey="sectionTitle",this.toolbarKeyMaps=qg,this.toolboxKey="signature-detail",this.secondaryToolbarKeyMaps=Vg,this.titleValueControlTitles=["Value","Note"],this.toolbarKeys=["size","bold","underline","name","color","titleValueControl"],e?(Object.assign(this,e),this.objectId=this.objectId||Ce(10)):(this.underline=!0,this.value="%date%",this.note="Date",this.valueFontSize=12,this.valueFontBold=!0,this.valueFontUnderline=!1,this.valueFontName="",this.valueFontColor="0-0-0-1",this.noteFontSize=8,this.noteFontBold=!1,this.noteFontUnderline=!1,this.noteFontName="",this.noteFontColor="0-0-0-1"),this.objectId||(this.objectId=Ce(10));const o=this.getSourceObject();o&&(o.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),o.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.objectId}`}getPath(){if(!this.parent)return;const e=this.parent.additionalLines.findIndex(({objectId:s})=>s===this.objectId);return[...this.parent.getPath(),e]}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}clone(){const e=this.toJSON(),s=at.cloneDeep(e);return s.objectId=Ce(10),new gn(s,this.parent)}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e}},W(gn,"ContainerKey",gl),W(gn,"PasteKey",xl),gn);const Kg={size:"contractNoteFontSize",bold:"contractNoteBold",underline:"contractNoteUnderline",name:"contractNoteFontName",color:"contractNoteFontColor"},fl="signature_item",bl="signature_item",ks=class ks{constructor(e,s){this.JSON=e,this.keys=["objectId","appNote","contractNote","contractNoteFontSize","contractNoteBold","contractNoteUnderline","contractNoteFontName","contractNoteFontColor","footerNote","underline","column","additionalLines"],this.containerKey=fl,this.pasteKey=bl,this.parent=s,this.toolbarKey="sectionTitle",this.toolbarKeyMaps=Kg,this.toolboxKey="signature-title",this.toolbarKeys=["size","bold","underline","name","color"],e?(Object.assign(this,e),this.objectId=this.objectId||Ce(10),this.additionalLines=e.additionalLines.map(a=>new yn(a,this))):(this.appNote="",this.contractNote="%customerName%",this.contractNoteFontSize=8,this.contractNoteBold=!0,this.contractNoteUnderline=!1,this.contractNoteFontName="",this.contractNoteFontColor="0-0-0-1",this.footerNote="%customerName%",this.underline=!0,this.column=1,this.additionalLines=[new yn(void 0,this)]),this.objectId||(this.objectId=Ce(10));const o=this.getSourceObject();o&&(o.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),o.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.objectId}`}getPath(){if(!this.parent)return;if(this.parent.containerKey===X.ContainerKey){const s=this.parent.signatures.findIndex(({objectId:o})=>o===this.objectId);return[...this.parent.getPath(),s]}const e=this.parent.data.findIndex(({objectId:s})=>s===this.objectId);return[...this.parent.getPath(),e]}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}clone(){const e=this.toJSON(),s=at.cloneDeep(e);s.objectId=Ce(10);const o=new ks(s,this.parent);return o.additionalLines=o.additionalLines.map(a=>a.clone()),o}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e.additionalLines=this.additionalLines.map(s=>s.toJSON()),e}};W(ks,"ContainerKey",fl),W(ks,"PasteKey",bl);let Ye=ks;const yl="signature_section",jl="index_section",Ps=class Ps{constructor(e,s){if(this.JSON=e,this.keys=["objectId","data","groupType"],this.containerKey=yl,this.pasteKey=jl,this.parent=s,this.toolboxKey="",e)Object.assign(this,e),this.objectId=this.objectId||Ce(10),this.data=e.data.map(a=>new Ye(a,this));else{this.groupType="signature";const a={column:0,contractNote:"%customerName%",appNote:"",additionalLines:[{noteFontSize:8,note:"Date",noteFontBold:!1,valueFontBold:!0,value:"%date%",valueFontSize:12,underline:!0}],contractNoteBold:!0,footerNote:"%customerName%",underline:!0,contractNoteFontSize:8},i={column:1,contractNote:"%customerSpouseName%",appNote:"",additionalLines:[{noteFontSize:8,note:"Date",noteFontBold:!1,valueFontBold:!0,value:"%date%",valueFontSize:12,underline:!0}],contractNoteBold:!0,footerNote:"%customerSpouseName%",underline:!0,contractNoteFontSize:8};this.data=[new Ye(a,this),new Ye(i,this)]}this.objectId||(this.objectId=Ce(10));const o=this.getSourceObject();o&&(o.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),o.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.objectId}`}getPath(){return this.parent?[this.parent.contractData.findIndex(({objectId:s})=>s===this.objectId)]:void 0}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}clone(){const e=this.toJSON(),s=at.cloneDeep(e);s.objectId=Ce(10);const o=new Ps(s,this.parent);return o.data=o.data.map(a=>a.clone()),o}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e.data=this.data.map(s=>s.toJSON()),e}convertNewFiles(){return this}};W(Ps,"ContainerKey",yl),W(Ps,"PasteKey",jl);let nn=Ps;const Cl="image_object",Po=class Po{constructor(e,s){this.JSON=e,this.keys=["id","title","value","file"],this.parent=s,this.containerKey=Cl,e?(this.title="",this.value="",Object.assign(this,e),this.id=this.id||Ce(10)):(this.id=Ce(10),this.title="",this.value="")}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e}clone(){const e=this.toJSON(),s=at.cloneDeep(e);return s.id=Ce(10),this.file&&(this.file={...this.file}),new Po(s,this.parent)}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}async convertNewFiles(){var s,o;const{file:e}=this;if(e&&e.isNew){if(e instanceof se.File)return delete this.file.isNew,delete this.file._url,await this.file.save(),this.file;const a=e.file,i=((s=a.name)==null?void 0:s.split("."))||[],r=`image.${i.length>1?i.pop():((o=a.type.split("/")[1])==null?void 0:o.split("+")[0])||"png"}`,d=new se.File(r,a);return await d.save(),this.file=d,this.file}return this.file}get objectId(){return this.id}set objectId(e){this.id=e}};W(Po,"ContainerKey",Cl);let gt=Po;const Il="body_cell",Sl="body_cell",vl="detail_body_cell",Ug={size:"titleFontSize",bold:"titleFontBold",underline:"titleFontUnderline",name:"titleFontName",color:"titleFontColor",value:"contractTitle"},Tl={size:"valueFontSize",bold:"valueFontBold",underline:"valueFontUnderline",name:"valueFontName",color:"valueFontColor",value:"value"},Gg={textOnly:"Text Only",textShort:"Text (Words)",textLong:"Text (Sentence)",textXLong:"Text (Paragraph)",switched:"Switched",detailCell:"Detail Image/Line Item",provia:"ProVia",drawing:"Sketch",emptySpace:"Empty Space",imagePicker:"Image Picker",photoPickerCell:"Photo Selector",measureSheetItemDetail:"Measure Sheet Item Detail",header:"Header",signatures:"Signature",creditCardCell:"Secure Credit Card Capture",securePaymentCaptureAll:"Secure Payment Capture",bankAccountCell:"Secure eCheck Capture"},Jg={default:"Keyboard",picker:"Picker",multiSelectPicker:"Multi-Select Picker",keypad:"Keypad (1)",keypadDecimal:"Keypad (1.00)",phone:"Phone Number",currency:"Currency ($1.00)",currencyWhole:"Currency ($1)",email:"Email Address",numbers:"Number Keyboard",sizePicker:"Size Picker","3DSizePicker":"3D Size Picker",datePicker:"Date Picker",dateTimePicker:"Date & Time",timePicker:"Time",formula:"Formula (1.00)",formulaWhole:"Formula (1)",textFormula:"Text Formula",dateFormula:"Date Formula",formulaCurrency:"Formula Currency ($1.00)",formulaCurrencyWhole:"Formula Currency ($1)",credit
1Card:"Credit Card",ccExpDate:"Credit Card Exp. Date",dynamic:"Dynamic",financeOptionsPicker:"Finance Options Picker",unitedInchPicker:"United Inch Picker"},Yg=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Xg={inch:"Inch",quarter:'1/4"',eighth:'1/8"',sixteenth:'1/16"'},Et=class Et{constructor(e,s){if(this.JSON=e,this.keys=["objectId","cellId","cellType","appTitle","contractTitle","appNote","inputType","fractionDigits","dynamicInputType","pickerValues","multiSelectorSeparator","required","appOnly","drawIfEmpty","photoTag","titleLinked","titleFontSize","titleFontBold","titleFontUnderline","titleFontName","titleFontColor","valueFontSize","dateDisplayFormat","dateFormula","dateFormulaDaysOut","dateFormulaWeekdays","valueFontBold","valueFontUnderline","valueFontName","valueFontColor","imageHeight","detailItems","allowReportPhotos","images","imagesSource","defaultImageId","initialsRequired","drawingBackgroundImage","initialsNote","emptyValue","measureSheetItemQuantityIds","measueSheetItemTotalIds","linkedValueSettings","linkedMeasureSheetItem","linkedMeasureSheetItemConfig","value","formula","emptySpaceHeight","switchValueOn","switchValueOff","header","signatures","hasBeenAdded","inputDisabled","hidden","clearValueIfZero","isTotalSaleAmount","disableImageLink","disablePaymentRequest","disableCaptureAndCharge","defaultPaymentMode","paymentRequestText","unitedInchSuffix","minSizePickerWidth","maxSizePickerWidth","minSizePickerHeight","maxSizePickerHeight","minSizePickerDepth","maxSizePickerDepth"],this.parent=s,this.pasteKey=Sl,this.toolbarKey="sectionTitle",this.secondaryToolbarKeyMaps=Tl,this.toolboxKey=this.isDetailItem?"body-detail-cell":"body-cell",e){Object.assign(this,e),this.objectId=this.objectId||Ce(10);const{header:a,detailItems:i=[],signatures:l=[],images:r=[]}=e;this.detailItems=i.map(d=>new Et(d,this)),this._value=e.value,this.signatures=l.map(d=>new Ye(d,this)),this.images=r.map(d=>new gt(d,this)),a&&(this.header=new dt(e.header,this))}else this.objectId=Ce(10),this.cellId="",this.cellType="textShort",this.appTitle="New Title",this.contractTitle="New Title",this.appNote="",this.inputType="default",this.fractionDigits="inch",this.dynamicInputType=void 0,this.pickerValues=[],this.multiSelectorSeparator=",",this.required=!1,this.appOnly=!1,this.drawIfEmpty=!1,this.titleFontSize=10,this.titleFontBold=!0,this.titleFontUnderline=!1,this.titleFontName="",this.titleFontColor="0-0-0-1",this.valueFontSize=10,this.valueFontBold=!1,this.valueFontUnderline=!1,this.valueFontName="",this.valueFontColor="0-0-0-1",this.imageHeight=40,this.detailItems=[],this.allowReportPhotos=!1,this.images=[],this.imagesSource="unique",this.defaultImageId="",this.initialsRequired=!1,this.initialsNote="(Customer's Initials)",this.emptyValue="",this.measureSheetItemQuantityIds=[],this.measueSheetItemTotalIds=[],this.linkedMeasureSheetItem="",this.linkedMeasureSheetItemConfig=void 0,this._value="New Value",this.formula="",this.emptySpaceHeight=4,this.switchValueOn="YES",this.switchValueOff="NO",this.header=void 0,this.signatures=void 0,this.inputDisabled=!1,this.hidden=!1,this.clearValueIfZero=!1,this.isTotalSaleAmount=!1,this.disableImageLink=!1,this.paymentRequestText="";this.objectId||(this.objectId=Ce(10)),this.titleLinked===void 0&&(this.titleLinked=this.appTitle===this.contractTitle);const o=this.getSourceObject();o&&(o.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),o.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.objectId}`}get containerKey(){return this.isDetailItem?vl:Il}get value(){if(this._value)return this._value;switch(this.cellType){case"signatures":case"header":this._value=" ";break;case"imagePicker":case"drawing":return}return this._value}set value(e){this._value=e}set cellType(e){switch(e){case"header":{this.header||(this.header=new dt);break}case"signatures":{if(!this.signatures||!this.signatures.length){const s=new nn;this.signatures=s.data}break}case"imagePicker":case"drawing":delete this._value;break}this._cellType=e}get cellType(){return this._cellType}get appTitle(){return this._appTitle}set appTitle(e){this._appTitle=e,this.titleLinked&&(this._contractTitle=e)}get contractTitle(){return this._contractTitle}set contractTitle(e){this._contractTitle=e,this.titleLinked&&(this._appTitle=e)}getPath(){if(!this.parent)return;if(this.isDetailItem||this.isProVia){const s=this.parent.detailItems.findIndex(({objectId:o})=>o===this.objectId);return[...this.parent.getPath(),s]}const e=this.parent.cellItems.findIndex(({objectId:s})=>s===this.objectId);return[...this.parent.getPath(),e]}get toolbarKeys(){switch(this.cellType){case"detailCell":case"measureSheetItemDetail":return["size","bold","underline","name","color"];case"emptySpace":case"header":case"signatures":return[];default:return["size","bold","underline","name","color","value","titleValueControl"]}}get toolbarKeyMaps(){return this.cellType==="measureSheetItemDetail"?Tl:Ug}get isDetailItem(){return this.parent&&this.parent.cellType==="detailCell"}get isProVia(){return this.parent&&this.parent.cellType==="provia"}isEqualTo(e){return JSON.stringify(this.toJSON())===JSON.stringify(e.toJSON())}updateUniqueId(){}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}clone(){var l;const e=this.toJSON(),s=at.cloneDeep(e);s.objectId=Ce(10);const o=new Et(s,this.parent),{detailItems:a=[]}=o;a.length&&(o.detailItems=a.map(r=>r.clone()));const i=r=>r&&typeof r.clone=="function"?r.clone():at.cloneDeep(r);if(this.header&&(o.header=i(this.header)),this.signatures&&(o.signatures=this.signatures.map(i)),(l=this.images)!=null&&l.length&&this.imagesSource!=="default"){const r=new Map;o.images=this.images.map(d=>{const c=d.id,u=i(d);return c&&(u!=null&&u.id)&&r.set(c,u.id),u}),o.defaultImageId&&(o.defaultImageId=r.get(o.defaultImageId)??"")}else this.images&&(o.images=this.images.map(i));return o}getCellIds(){const e=this.toJSON(),{cellId:s,detailItems:o=[]}=e;return[s,...o.map(i=>i.cellId)].filter(i=>i)}toJSON(){const{header:e,detailItems:s=[],signatures:o=[],images:a=[]}=this,i={};this.keys.forEach(r=>{i[r]=this[r]});const l=r=>r&&typeof r.toJSON=="function"?r.toJSON():r;return i.detailItems=s.map(l),i.signatures=o.map(l),i.images=a.map(l),e&&(i.header=l(e)),i}get cellTypes(){return this.isProVia?["textShort","textLong","textXLong","switched"]:this.isDetailItem?["textShort","textLong","textXLong","switched","imagePicker"]:["textShort","textLong","textXLong","textOnly","switched","detailCell","provia","drawing","emptySpace","photoPickerCell","measureSheetItemDetail","header","signatures","credit
1CardCell","bankAccountCell","securePaymentCaptureAll"]}get isFormulaCell(){switch(this.inputType){case"formula":case"formulaWhole":case"formulaCurrency":case"formulaCurrencyWhole":return!0;default:return!1}}get isCurrencyCell(){switch(this.inputType){case"currency":case"currencyWhole":case"formulaCurrency":case"formulaCurrencyWhole":case"dynamic":return!0;default:return!1}}async convertDrawingBackgroundImage(){this.drawingBackgroundImage&&this.drawingBackgroundImage.isNew&&(delete this.drawingBackgroundImage.isNew,delete this.drawingBackgroundImage._url,await this.drawingBackgroundImage.save())}async convertNewFiles(){const e=this.images.map(s=>s.convertNewFiles());this.cellType==="header"&&e.push(this.header.convertNewFiles()),this.detailItems.forEach(s=>{e.push(s.convertNewFiles())}),this.drawingBackgroundImage&&e.push(this.convertDrawingBackgroundImage()),await Promise.all(e)}static cellTypeLabelForCellType(e){return Gg[e]||""}static inputTypeLabelForInputType(e){return Jg[e]||""}static fractionDigitsLabelForFractionDigits(e){return Xg[e]||""}};W(Et,"inputTypes",["default","email","phone","creditCard","ccExpDate","keypad","keypadDecimal","numbers","currency","currencyWhole","picker","multiSelectPicker","financeOptionsPicker","unitedInchPicker","sizePicker","3DSizePicker","datePicker","timePicker","dateTimePicker","formula","formulaWhole","textFormula","formulaCurrency","formulaCurrencyWhole","dynamic"]),W(Et,"CellTypes",["textShort","textLong","textXLong","textOnly","switched","detailCell","provia","drawing","emptySpace","photoPickerCell","measureSheetItemDetail","header","signatures","creditCardCell","bankAccountCell","securePaymentCaptureAll"]),W(Et,"DetailCellTypes",["textShort","textLong","textXLong","textOnly","switched","emptySpace","imagePicker"]),W(Et,"fractionDigits",["inch","quarter","eighth","sixteenth"]),W(Et,"ContainerKey",Il),W(Et,"DetailContainerKey",vl),W(Et,"PasteKey",Sl);let X=Et;const Zg=["size","bold","underline","name","color"],Qg={size:"titleFontSize",bold:"titleFontBold",underline:"titleFontUnderline",name:"titleFontName",color:"titleFontColor"},wl="header_group",kl="header_group";var xn;let dt=(xn=class{constructor(e,s){this.JSON=e,this.keys=["objectId","border","appTitle","title","titleFontName","titleFontSize","titleFontBold","titleFontUnderline","titleFontColor","cellItems"],this.parent=s,this.showToolbar=!0,this.toolbarKey="sectionTitle",this.toolbarKeys=Zg,this.toolbarKeyMaps=Qg,this.toolboxKey="header-title",this.containerKey=wl,this.pasteKey=kl,e?(Object.assign(this,e),this.objectId=this.objectId||Ce(10),this.cellItems=e.cellItems.map((a,i)=>new ht(a,this,i))):(this.border=0,this.appTitle="App Title",this.title="New Contract Title",this.titleFontName="",this.titleFontSize=14,this.titleFontBold=!0,this.titleFontUnderline=!1,this.titleFontColor="0-0-0-1",this.cellItems=[new ht(void 0,this,0),new ht(void 0,this,1),new ht(void 0,this,2)]),this.objectId||(this.objectId=Ce(10));const o=this.getSourceObject();o&&(o.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),o.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.objectId}`}getPath(){if(!this.parent)return;if(this.parent.containerKey===X.ContainerKey)return[...this.parent.getPath(),0];const e=this.parent.data.findIndex(({objectId:s})=>s===this.objectId);return[...this.parent.getPath(),e]}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}clone(){const e=this.toJSON(),s=at.cloneDeep(e);return s.objectId=Ce(10),new xn(s,this.parent)}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e.cellItems=this.cellItems.map(s=>s.toJSON()),e}insertHeaderGroupAtIndex(e=this.cellItems.length,s){return[...this.cellItems],s||[new ht(void 0,this),new ht(void 0,this),new ht(void 0,this)]}async convertNewFiles(){const e=this.cellItems.map(s=>s.convertNewFiles());return Promise.all(e)}},W(xn,"ContainerKey",wl),W(xn,"PasteKey",kl),xn);const Pl="header_section",Dl="index_section";var fn;let Bt=(fn=class{constructor(e,s){this.keys=["objectId","data","groupType"],this.containerKey=Pl,this.pasteKey=Dl,this.JSON=e,this.parent=s,this.showToolbar=!1,this.toolboxKey="",e?(Object.assign(this,e),this.objectId=this.objectId||Ce(10),this.data=e.data.map(a=>
1new dt(a,this))):(this.data=[new dt(void 0,this)],this.groupType="header"),this.objectId||(this.objectId=Ce(10));const o=this.getSourceObject();o&&(o.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),o.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.objectId}`}getPath(){return this.parent?[this.parent.contractData.findIndex(({objectId:s})=>s===this.objectId)]:void 0}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}clone(){const e=this.toJSON(),s=at.cloneDeep(e);s.objectId=Ce(10);const o=new fn(s,this.parent);return o.data=o.data.map(a=>a.clone()),o}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e.data=this.data.map(s=>s.toJSON()),e}insertHeaderSectionAtIndex(e=this.data.length,s){return[...this.data],s||new dt(void 0,this)}convertNewFiles(){const s=(this.data||[]).map(o=>o.convertNewFiles());return Promise.all(s)}},W(fn,"ContainerKey",Pl),W(fn,"PasteKey",Dl),fn);const ex=["size","bold","underline","name","color"],tx={size:"fontSize",bold:"fontBold",underline:"fontUnderline",name:"fontName",color:"fontColor"},nx=["drawBorder","shading","userInputRequired","canAddMultiple","newPage","linkedMeasureSheetItemIds","categoryIds"],Ol="body_group",Nl="body_group",Ds=class Ds{constructor(e,s){this.JSON=e,this.keys=["objectId","appTitle","contractTitle","drawBorder","shading","userInputRequired","fontSize","fontBold","fontUnderline","fontName","fontColor","cellItems","canAddMultiple","newPage","linkedMeasureSheetItemIds","categoryIds","groupByCategoryClone","requiresDownload","downloadParams"],this.containerKey=Ol,this.pasteKey=Nl,this.parent=s,this.showToolbar=!0,this.toolbarKey="sectionTitle",this.toolbarKeys=ex,this.toolbarKeyMaps=tx,this.toolboxKey="body-title",this.toolboxKeys=nx,e?(Object.assign(this,e),this.objectId=this.objectId||Ce(10),this.cellItems=e.cellItems.map(a=>new X(a,this))):(this.appTitle="New App Title",this.contractTitle="New Contract Title",this.drawBorder=!0,this.shading=1,this.userInputRequired=!0,this.fontSize=12,this.fontBold=!0,this.fontUnderline=!1,this.fontName="",this.fontColor="0-0-0-1",this.cellItems=[new X(void 0,this)],this.canAddMultiple=!1,this.newPage=!1,this.linkedMeasureSheetItemIds=[],this.categoryIds=[],this.groupByCategoryClone=!1,this.requiresDownload=!1,this.downloadParams={}),this.objectId||(this.objectId=Ce(10));const o=this.getSourceObject();o&&(o.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),o.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.objectId}`}getPath(){if(!this.parent)return;const e=this.parent.data.findIndex(({objectId:s})=>s===this.objectId);return[...this.parent.getPath(),e]}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}getCellIds(){const{cellItems:e=[]}=this;return e.reduce((s,o)=>[...s,...o.getCellIds()],[])}clone(){const e=this.toJSON(),s=at.cloneDeep(e);s.objectId=Ce(10);const o=new Ds(s,this.parent);return o.cellItems=o.cellItems.map(a=>a.clone()),o}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e.cellItems=this.cellItems.map(s=>s.toJSON()),e}convertNewFiles(){const{cellItems:e=[]}=this,s=e.map(o=>o.convertNewFiles());return Promise.all(s)}};W(Ds,"ContainerKey",Ol),W(Ds,"PasteKey",Nl);let ct=Ds;const Ml="body_section",Ll="index_section";var bn;let Gn=(bn=class{constructor(e,s){this.JSON=e,this.keys=["objectId","data","groupType"],this.containerKey=Ml,this.pasteKey=Ll,this.toolboxKey="",this.parent=s,e?(Object.assign(this,e),this.objectId=this.objectId||Ce(10),this.data=e.data.map(a=>new ct(a,this))):(this.groupType="body",this.data=[new ct(void 0,this)]),this.objectId||(this.objectId=Ce(10));const o=this.getSourceObject();o&&(o.hasObjectId(this.objectId)&&(this.objectId=Ce(10)),o.addObjectId(this.objectId))}get identifier(){return`${this.parent.identifier}-${this.objectId}`}getPath(){return this.parent?[this.parent.contractData.findIndex(({objectId:s})=>s===this.objectId)]:void 0}getSourceObject(){if(this.parent)return this.parent.getSourceObject()}getCellIds(){const{data:e=[]}=this;return e.reduce((s,o)=>[...s,...o.getCellIds()],[])}clone(){const e=this.toJSON(),s=at.cloneDeep(e);s.objectId=Ce(10);const o=new bn(s,this.parent);return o.data=o.data.map(a=>a.clone()),o}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e.data=this.data.map(s=>s.toJSON()),e}convertNewFiles(){const{data:e=[]}=this,s=e.map(o=>o.convertNewFiles());return Promise.all(s)}},W(bn,"ContainerKey",Ml),W(bn,"PasteKey",Ll),bn);const El=(n,e)=>{let s=JSON.stringify(n);return Object.keys(e).forEach(i=>
1{s=s.split(i).join(e[i])}),JSON.parse(s)},Al=(n,e)=>{switch(n.groupType){case"header":return new Bt(n,e);case"body":return new Gn(n,e);case"signature":return new nn(n,e);default:return{}}},sx=(n,e)=>{const s=n.split("-");if(s.length===3)e.data=e.data.filter(({objectId:o})=>o!==s[2]);else{const o=e.data.find(({objectId:a})=>a===s[2]);s.length===4?o.cellItems=o.cellItems.filter((a,i)=>i!==parseInt(s[3],10)):s.length===5&&(o.cellItems=o.cellItems.map((a,i)=>i!==parseInt(s[3],10)?a:a.filter(({objectId:l})=>l!==s[4])))}},ox=(n,e)=>{const s=n.split("-");if(s.length===3)e.data=e.data.filter(({objectId:o})=>o!==s[2]);else{const o=e.data.find(({objectId:a})=>a===s[2]);if(s.length===4)o.cellItems=o.cellItems.filter(({objectId:a})=>a!==s[3]);else if(s.length===5){const a=o.cellItems.find(({objectId:i})=>i===s[3]);a.detailItems=a.detailItems.filter(({objectId:i})=>i!==s[4])}}},ax=(n,e)=>{const s=n.split("-");if(s.length===3)e.data=e.data.filter(({objectId:o})=>o!==s[2]);else{const o=e.data.find(({objectId:a})=>a===s[2]);s.length===4&&(o.additionalLines=o.additionalLines.filter(({objectId:a})=>a!==s[3]))}};class ${constructor(e={}){if(this.JSON=e,this.keys=["objectId","canAddMultiplePages","wMargin","hMargin","order","isTemplate","type","sections","pageSize","pageId","category","displayName","iconBackgroundColor","includedStates","pdf","iconImage","watermark","watermarkWidthPercent","watermarkAlpha","useWatermark","images","contractData","includedOffices","photosPerPage","linkedTypes","hooks","linkedIds"],e&&Object.keys(e).length){Object.assign(this,e),this.objectId=this.objectId||Ce(10),this.sections=Array.isArray(this.sections)&&this.sections.length?this.sections:[this.type].filter(Boolean);const{contractData:s=[],images:o=[]}=e;this.contractData=s.map(a=>Al(a,this)),this.images=o.map(a=>new gt(a,this))}else this.canAddMultiplePages=!1,this.wMargin=20,this.hMargin=35,this.order=0,this.isTemplate=!1,this.type="contract",this.sections=["contract"],this.pageSize="612,792",this.pageId="singlePage",this.category="",this.displayName="New Template",this.iconBackgroundColor=[255,255,255,0],this.includedStates=[],this.pdf=void 0,this.iconImage=void 0,this.watermark=void 0,this.watermarkWidthPercent=100,this.watermarkAlpha=.05,this.useWatermark=!0,this.images=[],this.contractData=[new Bt(void 0,this),new Gn(void 0,this),new nn(void 0,this)],this.includedOffices=[],this.photosPerPage=2,this.hooks=[]}get identifier(){return this.objectId}get iconImage(){return this._iconImage}set iconImage(e){if(e){if(e instanceof se.File){this._iconImage=e;return}const s=new se.File;s._url=e.url,s._name=e.name,this._iconImage=s}else delete this._iconImage}get watermark(){return this._watermark}set watermark(e){if(e){if(e instanceof se.File){this._watermark=e;return}const s=new se.File;s._url=e.url,s._name=e.name,this._watermark=s}else delete this._watermark}getSourceObject(){return this}async fetchTemplateTypes({linkedIds:e=[]}){let s=[];if(e.length){const o=new se.Object("LinkedValueObject"),a=new se.Query(o);a.containedIn("objectId",e),(await a.find()).forEach(l=>{s=s.concat(l.get("destinations"))})}return Array.from(new Set(s))}addObjectId(e){if(!e)return;const s=this.objectIds||[];s.push(e),this.objectIds=s}hasObjectId(e){return this.objectIds?this.objectIds.indexOf(e)>-1:!1}toJSON(){const e={};return this.keys.forEach(s=>{e[s]=this[s]}),e.contractData=this.contractData.map(s=>s.toJSON()),e.images=this.images.map(s=>s.toJSON()),e}deleteObject(e){e&&this.deleteObjectAtPath(e.getPath())}getObjectWithId(e){for(let s=0;s<this.contractData.length;s+=1){const o=this.contractData[s];if(o.objectId===e)return o;const{data:a=[]}=o;for(let i=0;i<a.length;i+=1){const l=a[i];if(l.objectId===e)return l;const{cellItems:r=[],additionalLines:d=[]}=l;for(let c=0;c<r.length;c+=1){const u=r[c];if(u.objectId===e)return u;const{detailItems:p=[],signatures:h=[],header:g={},cellItems:x=[]}=u;for(let f=0;f<x.length;f+=1)if(x[f].objectId===e)return x[f];for(let f=0;f<p.length;f+=1)if(p[f].objectId===e)return p[f];for(let f=0;f<h.length;f+=1){if(h[f].objectId===e)return h[f];const{additionalLines:j=[]}=h[f];for(let S=0;S<j.length;S+=1)if(j[S].objectId===e)return j[S]}const{cellItems:m=[]}=g;for(let f=0;f<m.length;f+=1){const j=m[f];if(j.objectId===e)return j;for(let S=0;S<j.cellItems.length;S+=1)if(j.cellItems[S].objectId===e)return j.cellItems[S]}}for(let c=0;c<d.length;
1c+=1){const u=d[c];if(u.objectId===e)return u}}}}getItemAtPath(e=[]){if(!e.length)return;const{groupType:s}=this.contractData[e[0]];switch(e.length){case 1:return this.contractData[e[0]];case 2:return this.contractData[e[0]].data[e[1]];case 3:switch(s){case"header":case"body":return this.contractData[e[0]].data[e[1]].cellItems[e[2]];case"signature":return this.contractData[e[0]].data[e[1]].additionalLines[e[2]];default:return}case 4:switch(s){case"body":{const o=this.contractData[e[0]].data[e[1]].cellItems[e[2]];switch(o.cellType){case"signatures":return o.signatures[e[3]];case"header":return o.header;default:return o.detailItems[e[3]]}}case"header":return this.contractData[e[0]].data[e[1]].cellItems[e[2]].cellItems[e[3]];default:return}case 5:switch(s){case"body":{const o=this.contractData[e[0]].data[e[1]].cellItems[e[2]];switch(o.cellType){case"header":return o.header.cellItems[e[4]];default:return}}default:return}case 6:switch(s){case"body":{const o=this.contractData[e[0]].data[e[1]].cellItems[e[2]];switch(o.cellType){case"header":return o.header.cellItems[e[4]].cellItems[e[5]];default:return}}default:return}default:return}}deleteObjectAtPath(e){const{groupType:s}=this.contractData[e[0]];let o;switch(e.length){case 1:o=this.contractData.splice(e[0],1);break;case 2:o=this.contractData[e[0]].data.splice(e[1],1);break;case 3:switch(s){case"header":case"body":o=this.contractData[e[0]].data[e[1]].cellItems.splice(e[2],1);break;case"signature":o=this.contractData[e[0]].data[e[1]].additionalLines.splice(e[2],1);break}break;case 4:switch(s){case"body":{const a=this.contractData[e[0]].data[e[1]].cellItems[e[2]];switch(a.cellType){case"signatures":o=a.signatures.splice(e[3],1);break;case"header":break;default:o=a.detailItems.splice(e[3],1);break}break}case"header":o=this.contractData[e[0]].data[e[1]].cellItems[e[2]].cellItems.splice(e[3],1);break}break;case 5:switch(s){case"body":{const a=this.contractData[e[0]].data[e[1]].cellItems[e[2]];switch(a.cellType){case"header":o=a.header.cellItems.splice(e[4],1);break;case"signatures":o=a.signatures[e[3]].additionalLines.splice(e[4],1);break}break}}break;case 6:switch(s){case"body":{const a=this.contractData[e[0]].data[e[1]].cellItems[e[2]];switch(a.cellType){case"header":o=a.header.cellItems[e[4]].cellItems.splice(e[5],1);break}break}}break}if(o!=null&&o.length&&o[0].linkedValueSettings){const a=o[0].linkedValueSettings.objectId;this.linkedIds&&(this.linkedIds=this.linkedIds.filter(i=>i!==a))}}insertObjectAtPath(e,s,o=1){const{groupType:a}=this.contractData[e[0]];switch(e.length){case 1:s.parent=this,this.contractData.splice(e[0]+o,0,s);break;case 2:{const i=this.contractData[e[0]];s.parent=i,i.data.splice(e[1]+o,0,s);break}case 3:switch(a){case"header":case"body":{const i=this.contractData[e[0]].data[e[1]];s.parent=i,i.cellItems.splice(e[2]+o,0,s);break}case"signature":{const i=this.contractData[e[0]].data[e[1]];s.parent=i,i.additionalLines.splice(e[2]+o,0,s);break}}break;case 4:switch(a){case"body":{const i=this.contractData[e[0]].data[e[1]].cellItems[e[2]];switch(i.cellType){case"signatures":s.parent=i,i.signatures.splice(e[3]+o,0,s);break;case"header":break;default:s.parent=i,i.detailItems.splice(e[3]+o,0,s);break}break}case"header":{const i=this.contractData[e[0]].data[e[1]].cellItems[e[2]];s.parent=i,i.cellItems.splice(e[3]+o,0,s);break}}break;case 5:switch(a){case"body":{const i=this.contractData[e[0]].data[e[1]].cellItems[e[2]];switch(i.cellType){case"header":s.cellItems.forEach(l=>{l.parent=i.header}),i.header.cellItems.splice(e[4]+o,0,s);break;case"signatures":s.parent=i.signatures[e[3]],i.signatures[e[3]].additionalLines.splice(e[4]+o,0,s);break}break}}break;case 6:switch(a){case"body":{const i=this.contractData[e[0]].data[e[1]].cellItems[e[2]];switch(i.cellType){case"header":{const l=i.header;s.parent=l,l.cellItems[e[4]].cellItems.splice(e[5]+o,0,s);break}}break}}break}}pasteObjectAfterNode({object:e},s,o=1){this.insertObjectAtPath(s,e,o)}addHeaderSection(){this.contractData.push(new Bt(void 0,this))}addBodySection(){this.contractData.push(new Gn(void 0,this))}addSignatureSection(){this.contractData.push(new nn(void 0,this))}hasBodySection(){return this.contractData.some(({groupType:e})=>e==="body")}insertNewObjectAtPath(e){const{groupType:s}=this.contractData[e[0]];let o;switch(e.length){case 1:switch(s){case"header":o=new Bt;break;case"body":o=new Gn;break;case"signature":o=new nn;break}break;case 2:switch(s){case"header":o=new dt;break;case"body":o=new ct;break;case"signature":o=new Ye;break}break;case 3:switch(s){case"header":o=new ht;break;case"body":o=new X;break}break}o&&this.insertObjectAtPath(e,o)}deleteObjectWithId(e){const s=e.split("-");if(s.length===2)this.contractData=this.contractData.filter(({objectId:o})=>o!==s[1]);else{const o=this.contractData.find(({objectId:i})=>i===s[1]),{groupType:a}=o;switch(a){case"header":sx(e,o);break;case"body":ox(e,o);break;case"signature":ax(e,o);break}}}objectFromIdentifier(e=""){const s=e.split("-"),o=this.contractData.find(({objectId:a})=>a===s[1]);if(o)switch(s.length){case 2:return o;case 3:return o.data.find(({objectId:a})=>a===s[2]);case 4:switch(o.groupType){case"header":return o.data.find(({objectId:a})=>a===s[2]).cellItems.find((a,i)=>i===parseInt(s[3],10));case"body":return o.data.find(({objectId:a})=>a===s[2]).cellItems.find(({objectId:a})=>a===s[3]);case"signature":return o.data.find(({objectId:a})=>a===s[2]).additionalLines.find(({objectId:a})=>a===s[3]);default:return}case 5:switch(o.groupType){case"header":return o.data.find(({objectId:a})=>a===s[2]).cellItems.find((a,i)=>i===parseInt(s[3],10)).find(({objectId:a})=>a===s[4]);case"body":{const i=o.data.find(({objectId:l})=>l===s[2]).cellItems.find(({objectId:l})=>l===s[3]);switch(i.cellType){case"signatures":return i.signatures.find(({objectId:l})=>l===s[4]);default:return i.detailItems.find(({objectId:l})=>l===s[4])}}default:return}case 6:switch(o.groupType){case"body":{const i=o.data.find(({objectId:l})=>l===s[2]).cellItems.find(({objectId:l})=>l===s[3]);switch(i.cellType){case"header":return;case"signatures":return i.signatures.find(({objectId:r})=>r===s[4]).additionalLines.find(({objectId:r})=>r===s[5]);default:return}}default:return}case 7:switch(o.groupType){case"body":{const i=o.data.find(({objectId:l})=>l===s[2]).cellItems.find(({objectId:l})=>l===s[3]);switch(i.cellType){case"header":return i.header.cellItems.find((l,r)=>r===parseInt(s[5],10)).find(({objectId:l})=>l===s[6]);default:return}}default:return}default:return}}dynamicValueOptionsForCellId(e){const s=this.contractData.find(({groupType:a})=>a==="body")||{},{data:o=[]}=s;for(let a=0;a<o.length;a+=1){const{cellItems:i=[]}=o[a];let l=i.find(({cellId:r})=>r===e);
1if(l||i.forEach(r=>{r.cellType==="detailCell"&&!l&&(l=r.detailItems.find(({cellId:d})=>d===e))}),l){if(l.cellType==="switched")return[l.switchValueOn,l.switchValueOff];if(l.inputType==="picker")return l.pickerValues}}return[]}async convertNewFiles(){this.iconImage&&this.iconImage.isNew&&(delete this.iconImage.isNew,delete this.iconImage._url,await this.iconImage.save()),this.watermark&&this.watermark.isNew&&(delete this.watermark.isNew,delete this.watermark._url,await this.watermark.save()),this.pdf&&this.pdf.isNew&&(delete this.pdf.isNew,delete this.pdf._url,await this.pdf.save());const e=this.contractData.map(s=>s.convertNewFiles());return this.images.forEach(s=>{e.push(s.convertNewFiles())}),Promise.all(e)}getAllCellIdentifiers(e){const s=[],o=this.contractData.find(({groupType:i})=>i==="body")||{},{data:a=[]}=o;return a.forEach(({cellItems:i=[]})=>{i.forEach(({cellId:l,detailItems:r=[]})=>{l&&s.indexOf(l)===-1&&l!==e&&s.push(l),r.forEach(({cellId:d})=>{d&&s.indexOf(d)===-1&&d!==e&&s.push(d)})})}),s.sort((i,l)=>l-i)}async saveToServer(){await this.convertNewFiles();const e=this.toJSON();e!=null&&e.linkedTypes&&delete e.linkedTypes,e.objectId.split("_").length>1&&delete e.objectId;const s=new se.Object("ContractObject",e);return e.iconImage||s.unset("iconImage"),e.watermark||s.unset("watermark"),await s.save(),this.objectId=s.id,this.linkedTypes=await this.fetchTemplateTypes({linkedIds:s.get("linkedIds")}),this}async saveCopyToServer(){await this.convertNewFiles();const e=this.toJSON();delete e.objectId,e!=null&&e.linkedTypes&&delete e.linkedTypes;const s=new se.Object("ContractObject",e);await s.save();const o=s.toJSON(),a=new $(o);return a.linkedTypes=await this.fetchTemplateTypes({linkedIds:s.get("linkedIds")}),a}async revert(){const e=new se.Object("ContractObject");e.id=this.objectId,e.revert(),await e.fetch();const s=e.toJSON();Object.assign(this,s);const{contractData:o=[],images:a=[]}=s;return this.contractData=o.map(i=>Al(i,this)),this.images=a.map(i=>new gt(i,this)),this}}const Hc=({cellItem:n})=>t.jsx(ot,{cellItem:n,children:t.jsx("div",{style:{minHeight:`${n.emptySpaceHeight||0}px`,maxHeight:`${n.emptySpaceHeight||0}px`}})});Hc.propTypes={cellItem:b.instanceOf(X).isRequired};const rt=({isDragging:n},e,s)=>({userSelect:"none",background:n?"white":void 0,boxShadow:s?"-5px 5px 5px darkgray, 5px 5px 5px darkgray":void 0,position:"relative",opacity:n?.8:void 0,...e}),tt=(n,e)=>({background:n?"rgba(230, 230, 230, 0.5)":void 0,boxShadow:e?"-5px 5px 5px darkgray, 5px 5px 5px darkgray":void 0}),Fl=(n,e)=>{const o=document.createElement("canvas").getContext("2d");return o.font=e,o.measureText(n).width};class Ua extends J.Component{constructor(e){super(e),this.inputRef=J.createRef()}render(){const{note:e,style:s,showPopover:o,onChange:a,onDoubleClick:i,onMouseDown:l}=this.props;return t.jsx("div",{style:{height:"34px",padding:"3px 5px"},children:t.jsx(Ge,{content:t.jsx("textarea",{onContextMenu:r=>r.stopPropagation(),fill:!0,ref:this.inputRef,defaultValue:e,className:"ignore-react-onclickoutside"}),isOpen:o,position:La.RIGHT_TOP,onClose:()=>{e!==this.inputRef.current.value&&a(this.inputRef.current.value)},children:t.jsxs("div",{style:{...s,position:"absolute",display:"flex",right:"0px",bottom:"0px"},onMouseDown:l,onDoubleClick:i,className:"templates-pdf__text",children:[e,t.jsx("div",{style:{borderBottom:"1px solid black",width:"54.6875px"}})]})})})}}Ua.propTypes={note:b.string,style:b.shape({}),showPopover:b.bool,onChange:b.func.isRequired,onDoubleClick:b.func.isRequired,onMouseDown:b.func.isRequired};Ua.defaultProps={note:"",style:void 0,showPopover:!1};const qc=["Copperplate","Copperplate-Bold","AppleSDGothicNeo-Thin","AppleSDGothicNeo-Light","AppleSDGothicNeo-Regular","AppleSDGothicNeo-Bold","AppleSDGothicNeo-SemiBold","AppleSDGothicNeo-UltraLight","AppleSDGothicNeo-Medium","Thonburi","Thonburi-Light","Thonburi-Bold","GillSans-Italic","GillSans-SemiBold","GillSans-UltraBold","GillSans-Light","GillSans-Bold","GillSans","GillSans-SemiBoldItalic","GillSans-BoldItalic","GillSans-LightItalic","MarkerFelt-Thin","MarkerFelt-Wide","HiraMaruProN-W4","CourierNewPS-ItalicMT","CourierNewPSMT","CourierNewPS-BoldItalicMT","CourierNewPS-BoldMT","KohinoorTelugu-Regular","KohinoorTelugu-Medium","KohinoorTelugu-Light","AvenirNextCondensed-Heavy","AvenirNextCondensed-MediumItalic","AvenirNextCondensed-Regular","AvenirNextCondensed-UltraLightItalic","AvenirNextCondensed-Medium","AvenirNextCondensed-HeavyItalic","AvenirNextCondensed-DemiBoldItalic","AvenirNextCondensed-Bold","AvenirNextCondensed-DemiBold","AvenirNextCondensed-BoldItalic","AvenirNextCondensed-Italic","AvenirNextCondensed-UltraLight","TamilSangamMN","TamilSangamMN-Bold","HelveticaNeue-UltraLightItalic","HelveticaNeue-Medium","HelveticaNeue-MediumItalic","HelveticaNeue-UltraLight","HelveticaNeue-Italic","HelveticaNeue-Light","HelveticaNeue-ThinItalic","HelveticaNeue-LightItalic","HelveticaNeue-Bold","HelveticaNeue-Thin","HelveticaNeue-CondensedBlack","HelveticaNeue","HelveticaNeue-CondensedBold","HelveticaNeue-BoldItalic","GurmukhiMN-Bold","GurmukhiMN","Georgia-BoldItalic","Georgia-Italic","Georgia","Georgia-Bold","TimesNewRomanPS-ItalicMT","TimesNewRomanPS-BoldItalicMT","TimesNewRomanPS-BoldMT","TimesNewRomanPSMT","SinhalaSangamMN-Bold","SinhalaSangamMN","ArialRoundedMTBold","Kailasa-Bold","Kailasa","KohinoorDevanagari-Regular","KohinoorDevanagari-Light","KohinoorDevanagari-Semibold","KohinoorBangla-Regular","KohinoorBangla-Semibold","KohinoorBangla-Light","ChalkboardSE-Bold","ChalkboardSE-Light","ChalkboardSE-Regular","Helvetica-Condensed-Light","AppleColorEmoji","PingFangTC-Regular","PingFangTC-Thin","PingFangTC-Medium","PingFangTC-Semibold","PingFangTC-Light","PingFangTC-Ultralight","GujaratiSangamMN","GujaratiSangamMN-Bold","GeezaPro-Bold","GeezaPro","DamascusBold","DamascusLight","Damascus","DamascusMedium","DamascusSemiBold","Noteworthy-Bold","Noteworthy-Light","Avenir-Oblique","Avenir-HeavyOblique","Avenir-Heavy","Avenir-
1BlackOblique","Avenir-BookOblique","Avenir-Roman","Avenir-Medium","Avenir-Black","Avenir-Light","Avenir-MediumOblique","Avenir-Book","Avenir-LightOblique","DiwanMishafi","AcademyEngravedLetPlain","Futura-CondensedExtraBold","Futura-Medium","Futura-Bold","Futura-CondensedMedium","Futura-MediumItalic","PartyLetPlain","KannadaSangamMN-Bold","KannadaSangamMN","ArialHebrew-Bold","ArialHebrew-Light","ArialHebrew","Farah","Arial-BoldMT","Arial-BoldItalicMT","Arial-ItalicMT","ArialMT","Chalkduster","Kefa-Regular","HoeflerText-Italic","HoeflerText-Black","HoeflerText-Regular","HoeflerText-BlackItalic","Optima-ExtraBlack","Optima-BoldItalic","Optima-Italic","Optima-Regular","Optima-Bold","Palatino-Italic","Palatino-Roman","Palatino-BoldItalic","Palatino-Bold","MalayalamSangamMN-Bold","MalayalamSangamMN","AlNile","AlNile-Bold","Helvetica-Condensed","Helvetica-Condensed-Bold","BradleyHandITCTT-Bold","HiraMinProN-W3","HiraMinProN-W6","PingFangHK-Medium","PingFangHK-Thin","PingFangHK-Regular","PingFangHK-Ultralight","PingFangHK-Semibold","PingFangHK-Light","Helvetica-Oblique","Helvetica-BoldOblique","Helvetica","Helvetica-Light","Helvetica-Bold","Helvetica-LightOblique","Courier-BoldOblique","Courier-Oblique","Courier","Courier-Bold","Cochin-Italic","Cochin-Bold","Cochin","Cochin-BoldItalic","TrebuchetMS-Bold","TrebuchetMS-Italic","Trebuchet-BoldItalic","TrebuchetMS","LaoSangamMN","DevanagariSangamMN","DevanagariSangamMN-Bold","OriyaSangamMN","OriyaSangamMN-Bold","SnellRoundhand","SnellRoundhand-Bold","SnellRoundhand-Black","ZapfDingbatsITC","BodoniSvtyTwoITCTT-Bold","BodoniSvtyTwoITCTT-BookIta","BodoniSvtyTwoITCTT-Book","Verdana-Italic","Verdana","Verdana-Bold","Verdana-BoldItalic","AmericanTypewriter-CondensedBold","AmericanTypewriter-Condensed","AmericanTypewriter-CondensedLight","AmericanTypewriter","AmericanTypewriter-Bold","AmericanTypewriter-Semibold","AmericanTypewriter-Light","AvenirNext-Medium","AvenirNext-DemiBoldItalic","AvenirNext-DemiBold","AvenirNext-HeavyItalic","AvenirNext-Regular","AvenirNext-Italic","AvenirNext-MediumItalic","AvenirNext-UltraLightItalic","AvenirNext-BoldItalic","AvenirNext-Heavy","AvenirNext-Bold","AvenirNext-UltraLight","Baskerville-SemiBoldItalic","Baskerville-SemiBold","Baskerville-BoldItalic","Baskerville","Baskerville-Bold","Baskerville-Italic","KhmerSangamMN","Didot-Bold","Didot","Didot-Italic","SavoyeLetPlain","BodoniOrnamentsITCTT","Symbol","Menlo-BoldItalic","Menlo-Bold","Menlo-Italic","Menlo-Regular","NotoNastaliqUrdu","BodoniSvtyTwoSCITCTT-Book","Papyrus-Condensed","Papyrus","HiraginoSans-W3","HiraginoSans-W6","PingFangSC-Medium","PingFangSC-Semibold","PingFangSC-Light","PingFangSC-Ultralight","PingFangSC-Regular","PingFangSC-Thin","MyanmarSangamMN","MyanmarSangamMN-Bold","Zapfino","BodoniSvtyTwoOSITCTT-BookIt","BodoniSvtyTwoOSITCTT-Book","BodoniSvtyTwoOSITCTT-Bold","EuphemiaUCAS","EuphemiaUCAS-Italic","EuphemiaUCAS-Bold"],Zt=n=>qc.indexOf(n)>-1;b.oneOf(["",...qc]),b.func.isRequired;const Rl=n=>{const{cellItemId:e,onBlur:s,onClose:o,inputRef:a,defaultValue:i,children:l}=n,[r,d]=y.useState(null),c=g=>{d({top:g.clientY,left:g.clientX})},u=()=>{d(null),s(),o()},p=!!r,h=p?`${e}-popover`:void 0;return t.jsxs(N,{children:[t.jsx(Mo,{id:h,open:p,onClose:u,anchorReference:"anchorPosition",anchorPosition:r,transformOrigin:{vertical:"top",horizontal:"left"},sx:{".MuiPaper-root":{border:"1px solid #afafaf",borderRightBottomRadius:"0px",display:"flex"}},children:t.jsx("textarea",{onContextMenu:g=>g.stopPropagation(),autoFocus:!0,fill:!0,ref:a,defaultValue:i,className:"ignore-react-onclickoutside",style:{minWidth:"400px",minHeight:"150px",maxHeight:"600px",maxWidth:"800px",border:"none",background:"none",padding:"10px 15px"}})}),t.jsx(N,{id:h,onDoubleClick:c,children:l})]})},ix=n=>({display:n===!1?void 0:"flex",flexWrap:"wrap",overflow:"hidden",textOverflow:"ellipsis"}),lx=({contractTitle:n,titleFontSize:e,titleFontBold:s,titleFontUnderline:o,titleFontName:a,titleFontColor:i,isForDetailCell:l})=>{const r=i?i.split("-"):[],[d,c,u,p]=r;return{display:n?void 0:"none",cursor:"pointer",padding:l?"0px 5px":"3px 5px",fontSize:e,fontWeight:s?900:void 0,fontFamily:Zt(a)?a:"HelveticaNeue",color:i?`rgba(${d},${c},${u},${p})`:void 0,textDecoration:o?"underline":void 0}},rx=({valueFontSize:n,valueFontBold:e,valueFontUnderline:s,valueFontName:o,valueFontColor:a,isForDetailCell:i})=>{const l=a?a.split("-"):[],[r,d,c,u]=l;return{color:a?`rgba(${r},${d},${c},${u})`:void 0,cursor:"pointer",fontFamily:Zt(o)?o:"HelveticaNeue",fontSize:n,fontWeight:e?900:void 0,minWidth:20,overflow:i?"hidden":void 0,padding:i?"0px 5px":"3px 5px",textDecoration:s?"underline":void 0,textOverflow:i?"ellipsis":void 0,whiteSpace:i?"nowrap":void 0}};class Ga extends J.Component{constructor(s){super(s);W(this,"onMouseDown",s=>{this.props.cellItem.editKey=s,this.props.setEditItem(this.props.cellItem)});
1W(this,"onDoubleClick",s=>{const o=`${s}ShowPopover`,{openPopover:a}=this.state;a!==o?this.setState({[o]:!0,[a]:!1,openPopover:o}):this.setState({[o]:!0,openPopover:o})});W(this,"handleClickOutside",()=>{this.setState({titleShowPopover:!1,valueShowPopover:!1,initialsShowPopover:!1})});W(this,"onValuePopOverClose",()=>{if(this.props.cellItem.value!==this.contractValueRef.current.value){this.props.cellItem.value=this.contractValueRef.current.value;const s=this.props.cellItem.getSourceObject();this.props.setTemplateState(new $(s.toJSON()))}});W(this,"onTitlePopOverClose",()=>{if(this.props.cellItem.contractTitle!==this.contractTitleRef.current.value){this.props.cellItem.contractTitle=this.contractTitleRef.current.value;const s=this.props.cellItem.getSourceObject();this.props.setTemplateState(new $(s.toJSON()))}});this.state={titleShowPopover:!1,valueShowPopover:!1},this.contractTitleRef=J.createRef(),this.contractValueRef=J.createRef()}shouldComponentUpdate(s){const{objectId:o}=this.props.cellItem,a=s.editCellItem.objectId,i=this.props.editCellItem.objectId,d=o===a||o===i;return!this.props.cellItem.isEqualTo(s.cellItem)||d}render(){const{cellItem:s,template:o,setTemplateState:a,isForDetailCell:i,lockedTitle:l,lockedValue:r}=this.props,{appOnly:d=!1,contractTitle:c="",value:u="",valueFontName:p="",valueFontSize:h=10,titleFontSize:g=10,titleFontName:x="",initialsRequired:m=!1,initialsNote:f=""}=s;if(d)return null;const j=l||c,S=r||u,{wMargin:w,pageSize:C}=o,v=parseInt(C.split(",")[0],10)-w*2-10,I=Fl(j,`${g}px${x?` ${x}`:""}`),D=Fl(S,`${h}px${p?` ${p}`:""}`),F=I+D<v,M=ix(F),R=lx({...s,contractTitle:j,isForDetailCell:i}),P=rx({...s,isForDetailCell:i});return t.jsx(ot,{cellItem:s,children:t.jsxs("div",{className:"text-short-wrapper",style:{...M},children:[t.jsx("div",{style:{...R},className:"templates-pdf__text",children:t.jsx(Rl,{onBlur:this.handleClickOutside,cellItemId:s.objectId,inputRef:this.contractTitleRef,defaultValue:j,lockedTitle:l,onClose:this.onTitlePopOverClose,children:t.jsx("div",{className:"templates-pdf__text templates-single_line",onClick:()=>this.onMouseDown("title"),onDoubleClick:()=>this.onDoubleClick("title"),style:{fontFamily:R.fontFamily,textDecoration:R.textDecoration,overflow:"hidden",textOverflow:"ellipsis"},children:t.jsxs("span",{children:[" ",j||" "," "]})})})}),t.jsx("div",{style:{...P,flex:1,textAlign:"end"},className:"templates-pdf__text",children:t.jsx(Rl,{onBlur:this.handleClickOutside,cellItemId:s.objectId,inputRef:this.contractValueRef,defaultValue:S,lockedTitle:l,onClose:this.onValuePopOverClose,children:t.jsx("div",{onClick:()=>this.onMouseDown("value"),onDoubleClick:()=>this.onDoubleClick("value"),style:{textDecoration:P.textDecoration,textOverflow:"ellipsis",overflow:"hidden",width:"100%"},className:"templates-pdf__text",children:S.split(`
2`).length>1?S.split(`
3`).map((k,T,B)=>T<B.length?t.jsx("p",{style:{textAlign:"start",whiteSpace:"normal",margin:0,minHeight:`${h}px`},children:k},`${s.objectId}-${T}`):k):t.jsxs("div",{className:"one-line-wrap",style:{display:"flex"},children:[t.jsx("div",{id:`${s.objectId}-value-spacer`,className:"line-spacer",style:{flex:1}}),t.jsx("p",{ref:k=>{if(k){const T=k.getBoundingClientRect();let B=k.parentElement.parentElement.parentElement.parentElement;B.className==="bp3-popover-wrapper"&&(B=B.parentNode.parentNode);const L=B.getBoundingClientRect();T.width/L.width<.75?document.getElementById(`${s.objectId}-value-spacer`).style.display="block":document.getElementById(`${s.objectId}-value-spacer`).style.display="none"}},className:"one-line",style:{textAlign:"start",whiteSpace:"normal",margin:0},children:S})]})})})}),m&&t.jsx(Ua,{note:f,style:P,onMouseDown:()=>this.onMouseDown("value"),onDoubleClick:()=>this.onDoubleClick("initials"),showPopover:this.state.initialsShowPopover,onChange:k=>{s.initialsNote=k;const T=s.getSourceObject();a(new $(T.toJSON()))}})]})})}}Ga.propTypes={cellItem:b.instanceOf(X).isRequired,template:b.shape({}).isRequired,setEditItem:b.func.isRequired,setTemplateState:b.func.isRequired,isForDetailCell:b.bool,lockedTitle:b.string,lockedValue:b.string};Ga.defaultProps={isForDetailCell:!1,lockedTitle:void 0,lockedValue:void 0};const cx={},dx=new $,ux=({templatesEdit:n})=>({editCellItem:n.editCellItem||cx,template:n[n.currentWorkingId]||dx}),px=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),hx=Jt(Ga),qt=Z(ux,px)(hx),mx=({contractTitle:n,titleFontSize:e,titleFontBold:s,titleFontUnderline:o,titleFontName:a,titleFontColor:i},l)=>{const r=i?i.split("-"):[],[d,c,u,p]=r;return{display:n?void 0:"none",cursor:"pointer",padding:"0px 5px",fontSize:e,fontWeight:s?900:void 0,fontFamily:Zt(a)?a:"HelveticaNeue",color:i?`rgba(${d},${c},${u},${p})`:void 0,textDecoration:o?"underline":void 0,opacity:l?"0.7":void 0}},Jn=(n,e,s,o)=>{bt(n,a=>{const i=e.getSourceObject(),l=new $(i.toJSON()),r=a.draggableId===`new-${X.DetailContainerKey}`;let d;if(r)d=new X,o(d);else{let w=a.draggableId.split("-");w.pop(),w.pop(),w=w.map(C=>parseInt(C,10)),d=l.getItemAtPath(w)}if(!r){const{parent:w}=d,C=[],v=[],I=[];
3w.detailItems.forEach((R,P)=>{const{appOnly:k,cellType:T}=R;if(k){C.push(P,R);return}if(T==="textXLong"){v.push(R);return}I.push(R)});const D=I.filter((R,P)=>P%2===0),F=I.filter((R,P)=>P%2===1);let M=a.source.droppableId.split("-");switch(M.pop(),M.pop(),M.pop(),M=M.map(R=>parseInt(R,10)).pop(),M){case 0:D.splice(a.source.index,1);break;case 1:F.splice(a.source.index,1);break;default:v.splice(a.source.index,1);break}for(;F.length>D.length;)D.push(F.pop());w.detailItems=[...fa(D,F),...v];for(let R=0;R<C.length;R+=2){const P=C[R],k=C[R+1];w.detailItems.splice(P,0,k)}}let c=a.destination.droppableId.split("-");c.pop(),c.pop(),c.pop(),c=c.map(w=>parseInt(w,10));const u=c.pop(),p=l.getItemAtPath(c),{index:h}=a.destination,g=[],x=[],m=[];p.detailItems.forEach((w,C)=>{const{appOnly:v,cellType:I}=w;if(v){g.push(C,w);return}if(I==="textXLong"){x.push(w);return}m.push(w)});const f=m.filter((w,C)=>C%2===0),j=m.filter((w,C)=>C%2===1);switch(u){case 0:d.cellType=d.cellType==="textXLong"?"textLong":d.cellType,f.splice(h,0,d);break;case 1:d.cellType=d.cellType==="textXLong"?"textLong":d.cellType,j.splice(h,0,d);break;default:d.cellType="textXLong",x.splice(h,0,d);break}for(d.parent=e;j.length>f.length;)f.push(j.pop());const S=fa(f,j);for(let w=g.length;w>0;w-=2){const C=g[w-2],v=g[w-1];S.splice(C,0,v)}p.detailItems=[...S,...x],p.detailItems.length===0&&l.deleteObjectAtPath(p.getPath()),s(l)})};class Ja extends J.Component{constructor(s){super(s);W(this,"onMouseDown",()=>{this.props.cellItem.editKey="title",this.props.setEditItem(this.props.cellItem)});W(this,"onMouseOver",()=>{this.setState({isHovering:!0})});W(this,"onMouseOut",()=>{this.setState({isHovering:!1})});W(this,"onDoubleClick",()=>{this.setState({showPopover:!0})});W(this,"handleClickOutside",()=>{this.state.showPopover&&this.setState({showPopover:!1})});this.state={showPopover:!1},this.titleRef=J.createRef()}render(){const{cellItem:s,editCellItem:o,setTemplateState:a,templateValues:i,draggableType:l,setEditItem:r}=this.props,d=new $(i.toJSON()),c=d.getObjectWithId(s.objectId)||{},{imageHeight:u=0,detailItems:p=[]}=c,h=p.filter(({appOnly:I})=>I!==!0),g=h.filter(({cellType:I})=>I==="textXLong"),x=h.filter(({cellType:I})=>I!=="textXLong"),m=x.filter((I,D)=>D%2===0),f=x.filter((I,D)=>D%2>0),j=p.find(({cellType:I})=>I==="imagePicker"),S=mx(c,this.state.isHovering),w=`${[...s.getPath(),0].join("-")}-${s.objectId}-pdf-${X.DetailContainerKey}`,C=`${[...s.getPath(),1].join("-")}-${s.objectId}-pdf-${X.DetailContainerKey}`,v=`${[...s.getPath(),2].join("-")}-${s.objectId}-pdf-${X.DetailContainerKey}`;return Jn(w,s,a,r),Jn(C,s,a,r),Jn(v,s,a,r),t.jsxs("div",{style:{width:"100%"},children:[t.jsx("div",{style:{...S,overflow:"hidden",textOverflow:"ellipsis",width:"100%"},children:t.jsx(Ge,{content:t.jsx("textarea",{onContextMenu:I=>I.stopPropagation(),fill:!0,ref:this.titleRef,defaultValue:c.contractTitle,className:"ignore-react-onclickoutside"}),isOpen:this.state.showPopover,onClose:()=>{c.contractTitle=this.titleRef.current.value,a(d)},children:t.jsx("div",{onMouseDown:()=>this.onMouseDown(),onDoubleClick:()=>this.onDoubleClick(),onMouseOver:()=>this.onMouseOver(),onMouseOut:()=>this.onMouseOut(),style:S,children:c.contractTitle})})}),t.jsxs("div",{style:{position:"relative",width:"100%",display:"flex"},children:[j&&u>0&&t.jsx("div",{style:{paddingLeft:"3px",paddingTop:"3px",paddingBottom:"3px",height:`${u}px`,maxHeight:`${u}px`,minWidth:`${u}px`,maxWidth:`${u}px`},onClick:()=>this.onMouseDown(),children:t.jsx("img",{src:"/images/no_image.png",style:{objectFit:"contain",maxWidth:"100%",maxHeight:"100%"},alt:"thumbnail"})}),t.jsx(We,{droppableId:w,isDropDisabled:l!==X.DetailContainerKey,children:(I,D)=>t.jsxs("div",{style:{...tt(D.isDraggingOver),position:"relative",flex:1,width:0,minHeight:20},ref:I.innerRef,...I.droppableProps,children:[m.map((F,M)=>t.jsx(Ke,{draggableId:`${F.getPath().join("-")}-pdf-${F.objectId}`,index:M,children:(R,P)=>t.jsxs("div",{ref:R.innerRef,...R.draggableProps,...R.dragHandleProps,style:rt(P,R.draggableProps.style,F.objectId===o.objectId),children:[t.jsx(qt,{cellItem:F,isForDetailCell:!0}),R.placeholder]},F.objectId)},F.objectId)),I.placeholder]})}),t.jsx(We,{droppableId:C,isDropDisabled:l!==X.DetailContainerKey,children:(I,D)=>t.jsxs("div",{style:{...tt(D.isDraggingOver),position:"relative",flex:1,width:0,minHeight:20},ref:I.innerRef,...I.droppableProps,children:[f.map((F,M)=>t.jsx(Ke,{draggableId:`${F.getPath().join("-")}-pdf-${F.objectId}`,index:M,children:(R,P)=>t.jsxs("div",{ref:R.innerRef,...R.draggableProps,...R.dragHandleProps,style:rt(P,R.draggableProps.style,F.objectId===o.objectId),children:[t.jsx(qt,{cellItem:F,isForDetailCell:!0}),R.placeholder]},F.objectId)},F.objectId)),I.placeholder]})})]}),t.jsx(We,{droppableId:v,isDropDisabled:l!==X.DetailContainerKey,children:(I,D)=>t.jsxs("div",{style:{...tt(D.isDraggingOver),minHeight:20},ref:I.innerRef,...I.droppableProps,children:[g.map((F,M)=>t.jsx(Ke,{draggableId:`${F.getPath().join("-")}-pdf-${F.objectId}`,index:M,children:(R,P)=>t.jsxs("div",{ref:R.innerRef,...R.draggableProps,...R.dragHandleProps,style:rt(P,R.draggableProps.style,F.objectId===o.objectId),children:[t.jsx(qt,{cellItem:F}),R.placeholder]},F.objectId)},F.objectId)),I.placeholder]})})]})}}Ja.propTypes={editCellItem:b.any,cellItem:b.instanceOf(X).isRequired,setTemplateState:b.func.isRequired,templateValues:b.shape({}).isRequired,setEditItem:b.func.isRequired,draggableType:b.string};Ja.defaultProps={editCellItem:{},draggableType:void 0};const gx=({templatesEdit:n})=>
3({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,draggableType:n.draggableType}),xx=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),fx=Jt(Ja),bx=Z(gx,xx)(fx),Vc=({cellItem:n,setInitialStateForTemplate:e,setEditItem:s})=>{let o="";n.drawingBackgroundImage&&(n.drawingBackgroundImage.url&&(o=n.drawingBackgroundImage.url),n.drawingBackgroundImage._url&&(o=n.drawingBackgroundImage._url));const{imageHeight:a=100}=n;return t.jsx(ot,{cellItem:n,children:t.jsxs("div",{children:[t.jsx("div",{className:"drawing-text-container",children:t.jsx(qt,{cellItem:n})}),t.jsx("div",{style:{height:`${a}px`},className:"drawing-img-container",children:t.jsx("img",{className:"drawing-background-img",src:o})}),t.jsx(Ea,{onDrop:async i=>{try{const l=await as(i[0],"document","drawingBackgroundImage");n.drawingBackgroundImage=l;const r=n.getSourceObject();e(new $(r.toJSON()))}catch(l){Be.show({message:l.message,timeout:5e3})}},accept:"image/*",children:({getRootProps:i,getInputProps:l,isDragActive:r})=>t.jsxs("div",{onClick:()=>{s(n)},className:"drawing-background-input-containter",children:[t.jsx("input",{...l()}),t.jsx(we,{...i(),variant:"contained",color:"primary",children:"Drop Background Image Here..."})]})})]})})};Vc.propTypes={setEditItem:b.func.isRequired,setInitialStateForTemplate:b.func.isRequired,cellItem:b.instanceOf(X).isRequired};const yx=n=>({setInitialStateForTemplate:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),jx=Z(void 0,yx)(Vc),Cx=(n,e,s,o)=>{bt(n,a=>{const i=e.getSourceObject(),l=new $(i.toJSON()),r=a.draggableId===`new-${X.DetailContainerKey}`;let d;if(r)d=new X,o(d);
3else{let g=a.draggableId.split("-");g.pop(),g.pop(),g=g.map(x=>parseInt(x,10)),d=l.getItemAtPath(g)}if(!r){const{parent:g}=d,x=[],m=[];g.detailItems.forEach(j=>{m.push(j)});let f=a.source.droppableId.split("-");f.pop(),f.pop(),f.pop(),f=f.map(j=>parseInt(j,10)).pop(),m.splice(a.source.index,1),g.detailItems=m;for(let j=0;j<x.length;j+=2){const S=x[j],w=x[j+1];g.detailItems.splice(S,0,w)}}let c=a.destination.droppableId.split("-");c.pop(),c.pop(),c.pop(),c=c.map(g=>parseInt(g,10)),c.pop();const u=l.getItemAtPath(c),{index:p}=a.destination,h=[];u.detailItems.forEach(g=>{h.push(g)}),d.cellType="textXLong",h.splice(p,0,d),d.parent=e,u.detailItems=h,u.detailItems.length===0&&l.deleteObjectAtPath(u.getPath()),s(l)})},Kc=({cellItem:n,editCellItem:e,setTemplateState:s,draggableType:o,setEditItem:a})=>{const i=()=>{a(n)},{detailItems:l=[]}=n,r=`${[...n.getPath(),2].join("-")}-${n.objectId}-pdf-${X.DetailContainerKey}`;return Cx(r,n,s,a),t.jsxs(ot,{cellItem:n,children:[t.jsxs("div",{className:"templates-app__provia",children:[t.jsxs("div",{style:{display:"flex"},onClick:()=>i(),children:[t.jsxs("div",{style:{minWidth:"50%",maxWidth:"50%"},children:[t.jsx("img",{style:{objectFit:"contain",width:"100%"},src:"/images/provia_door.png",alt:"Provia Door"}),t.jsxs("div",{style:{display:"flex",width:"100%"},children:[t.jsx("span",{className:"templates-app__provia_image_label",children:"Inside View"}),t.jsx("span",{className:"templates-app__provia_image_label",children:"Outside View"})]})]}),t.jsxs("div",{style:{minWidth:"50%",maxWidth:"50%"},children:[t.jsx("p",{className:"templates-app__provia_details_bold",children:"Signet Single Entry Door in Full Wood Frame"}),t.jsx("p",{className:"templates-app__provia_details",children:'-36" x 80" Nominal Size'}),t.jsx("p",{className:"templates-app__provia_details",children:'-14" Sidelite Width'}),t.jsx("p",{className:"templates-app__provia_details",children:'-Unit Size: 68 1/16" x 81 5/8" -Frame Depth: 4 9/16"'}),t.jsx("p",{className:"templates-app__provia_details",children:'-2" Standard Brickmold'}),t.jsx("p",{className:"templates-app__provia_details",children:"-Right Hand Inswing - Inside Looking Out"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Frame"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Snow Mist White Aluminum Frame Cladding"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Chestnut Inside Frame"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Cherry Inside Mull Cover - Chestnut"}),t.jsx("p",{className:"templates-app__provia_details",children:'-Bronze Sahara Threshold (6 1/16" Depth)'}),t.jsx("p",{className:"templates-app__provia_details",children:"-Satin Nickel Ball Bearing Hinges"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Security Plate"}),t.jsx("p",{className:"templates-app__provia_details",children:'-Cherry Colonial 2 1/2" Casing - Chestnut'}),t.jsx("p",{className:"templates-app__provia_details_bold",children:"Entry Door"}),t.jsx("p",{className:"templates-app__provia_details",children:"-449 Style Signet Cherry Fiberglass Door"}),t.jsx("p",{className:"templates-app__provia_details",children:"-With Panel Planks"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Somerset Decorative Glass with Zinc Caming and Low-E (SOM)"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Chestnut Inside and Outside"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Hardware"}),t.jsx("p",{className:"templates-app__provia_details",children:"-All Hardware in Satin Nickel Finish"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Camelot Grip Entrance Handle Outside"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Flair Handle Inside"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Thumbturn Deadbolt"}),t.jsx("p",{className:"templates-app__provia_details_bold",children:"Sidelites on Both Sides"}),t.jsx("p",{className:"templates-app__provia_details",children:"-160 Style Signet Cherry Fiberglass Sidelite"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Somerset Decorative Glass with Zinc Caming and Low-E (SOM)"}),t.jsx("p",{className:"templates-app__provia_details",children:"-Chestnut Inside and Outside"})]})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"templates-app__provia_quantity_box",children:[t.jsx("div",{className:"templates-app__provia_quantity_label",children:"Quantity"}),t.jsx("div",{className:"templates-app__provia_quantity_number",children:"2"})]}),t.jsx("div",{className:"templates-app__provia_image_label",children:"40123456"})]})]}),t.jsx(We,{droppableId:r,isDropDisabled:o!==X.DetailContainerKey,children:(d,c)=>t.jsxs("div",{style:{...tt(c.isDraggingOver),minHeight:20},ref:d.innerRef,...d.droppableProps,children:[l.map((u,p)=>t.jsx(Ke,{draggableId:`${u.getPath().join("-")}-pdf-${u.objectId}`,index:p,children:(h,g)=>t.jsxs("div",{ref:h.innerRef,...h.draggableProps,...h.dragHandleProps,style:rt(g,h.draggableProps.style,e&&u.objectId===e.objectId),children:[t.jsx(qt,{cellItem:u}),h.placeholder]},u.objectId)},u.objectId)),d.placeholder]})})]})};Kc.propTypes={cellItem:b.instanceOf(X).isRequired};const Ix=({templatesEdit:n})=>
3({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,draggableType:n.draggableType}),Sx=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),vx=Z(Ix,Sx)(Kc),Tx={display:"flex"},wx=n=>{const e=new se.Query("SSMeasureSheetItem");return e.select(["subCategory","itemName","measurementType","items.subCategory2","items.displayTitle"]),e.equalTo("objectId",n),e.first()};class Uc extends J.Component{constructor(s){super(s);W(this,"onMouseOver",()=>{this.setState({isHovering:!0})});W(this,"onMouseOut",()=>{this.setState({isHovering:!1})});W(this,"onClick",()=>{this.props.setEditItem(this.props.cellItem)});W(this,"cellStyleForCell",({valueFontSize:s,valueFontBold:o,valueFontUnderline:a,valueFontName:i,valueFontColor:l},r,d)=>{const c=l?l.split("-"):[],[u,p,h,g]=c;return{minWidth:`${r}%`,maxWidth:`${r}%`,cursor:"pointer",padding:"3px 5px",fontSize:s,fontWeight:o?900:void 0,fontFamily:Zt(i)?i:"HelveticaNeue",color:l?`rgba(${u},${p},${h},${g})`:void 0,textDecoration:a?"underline":void 0,textAlign:d||void 0,opacity:this.state.isHovering?"0.7":void 0}});W(this,"loadMeasureSheetItemData",async()=>{try{const s=await wx(this.props.cellItem.linkedMeasureSheetItem);if(this.linkedMeasureSheetItemId=this.props.cellItem.linkedMeasureSheetItem,!s)throw new se.Error(500,"Could not find item");let o=s.get("itemName");s.get("subCategory")&&(o=`${s.get("subCategory")} - ${o}`);const i=(s.get("items")||[])[0];let l;i&&(i.get("subCategory2")?l=`${i.get("subCategory2")} - ${i.get("displayTitle")}`:l=i.get("displayTitle")),this.setState({title:o,subtitle:l,measurementType:s.get("measurementType"),quantity:"99",unitTotal:"$100.00",total:"$999.00"})}catch(s){this.setState({title:"Error loading item",subtitle:s.message,measurementType:"",quantity:"",unitTotal:"",total:""})}});this.state={title:"Loading...",subtitle:"",measurementType:"",quantity:"",unitTotal:"",total:"",isHovering:!1},this.linkedMeasureSheetItemId=s.cellItem.linkedMeasureSheetItem}componentWillMount(){this.loadMeasureSheetItemData()}componentDidUpdate(){this.props.cellItem.linkedMeasureSheetItem!==this.linkedMeasureSheetItemId&&this.loadMeasureSheetItemData()}render(){const{cellItem:s}=this.props,{linkedMeasureSheetItemConfig:o={}}=s,{measurementType:a=!1,quantity:i=!1,subtitle:l=!1,title:r=!1,total:d=!1,unitTotal:c=!1}=o,{title:u,subtitle:p,measurementType:h,quantity:g,unitTotal:x,total:m}=this.state;return t.jsx(ot,{cellItem:s,children:t.jsxs("div",{style:Tx,onMouseOver:this.onMouseOver,onMouseOut:this.onMouseOut,onClick:this.onClick,children:[t.jsx("div",{style:this.cellStyleForCell(s,100/2/2),children:r?u:""}),t.jsx("div",{style:this.cellStyleForCell(s,100/2/2),children:l?p:""}),t.jsx("div",{style:this.cellStyleForCell(s,100/2/16*3,"right"),children:i?g:""}),t.jsx("div",{style:this.cellStyleForCell(s,100/2/16*6,"right"),children:a?h:""}),t.jsx("div",{style:this.cellStyleForCell(s,100/2/16*3,"right"),children:c?x:""}),t.jsx("div",{style:this.cellStyleForCell(s,100/2/16*4,"right"),children:d?m:""})]})})}}Uc.propTypes={cellItem:b.instanceOf(X).isRequired,setEditItem:b.func.isRequired};const kx=({templatesEdit:n})=>({template:n[n.currentWorkingId]}),Px=n=>({setEditItem:e=>n(Ne(e)),setTemplateState:e=>n(ee(e))}),Dx=Z(kx,Px)(Uc),Ya=n=>{const[e,s,o,a]=n.split("-");return`rgba(${e},${s},${o},${a})`},Ox=({contractNoteFontSize:n,contractNoteBold:e,contractNoteUnderline:s,contractNoteFontName:o,contractNoteFontColor:a},i)=>({paddingLeft:"10px",fontSize:n,fontWeight:e?"900":"400",textDecoration:s?"underline":void 0,fontFamily:Zt(o)?o:"HelveticaNeue",color:a?Ya(a):void 0,opacity:i?"0.7":void 0,cursor:"pointer"}),Nx=({valueFontSize:n,valueFontBold:e,valueFontUnderline:s,valueFontName:o,valueFontColor:a},i)=>({paddingLeft:"15px",fontSize:n||12,fontWeight:e?"900":"400",textDecoration:s?"underline":void 0,fontFamily:Zt(o)?o:"HelveticaNeue",color:a?Ya(a):void 0,opacity:i?"0.7":void 0,cursor:"pointer"}),Mx=({noteFontSize:n,noteFontBold:e,noteFontUnderline:s,noteFontName:o,noteFontColor:a},i)=>({paddingLeft:"10px",fontSize:n||8,fontWeight:e?"900":"400",textDecoration:s?"underline":void 0,fontFamily:Zt(o)?o:"HelveticaNeue",color:a?Ya(a):void 0,opacity:i?"0.7":void 0,cursor:"pointer"});let Xa=class extends J.Component{constructor(s){super(s);W(this,"onMouseOver",s=>{const o={...this.state.hovering};o[s]=!0,this.setState({hovering:o})});W(this,"onMouseOut",s=>{const o={...this.state.hovering};o[s]=!1,this.setState({hovering:o})});W(this,"onMouseDown",s=>{this.props.setEditItem(s)});
3W(this,"onDoubleClick",s=>{this.setState({showPopover:s})});W(this,"handleClickOutside",()=>{this.setState({showPopover:""})});W(this,"updateDraggableCallback",()=>{const{cell:s,setTemplateState:o,setEditItem:a}=this.props;bt(this.droppableId,i=>{const{destination:l,draggableId:r,source:d}=i;let c=l.droppableId.split("-");c.pop(),c.pop(),c=c.map(x=>parseInt(x,10)),c.push(l.index);const u=s.getSourceObject(),p=new $(u.toJSON());if(d.droppableId===`new-${yn.ContainerKey}`){const x=new yn;p.insertObjectAtPath(c,x,0),o(p),a(x);return}let h=r.split("-");if(h.pop(),h=h.map(x=>parseInt(x,10)),h.every((x,m)=>x===c[m]))return;const g=p.getItemAtPath(h);p.deleteObjectAtPath(h),p.insertObjectAtPath(c,g,0),o(p)})});this.state={hovering:{},showPopover:""},this.noteRef=J.createRef(),this.droppableId=`${s.cell.getPath().join("-")}-${s.cell.objectId}-${yn.ContainerKey}`,this.updateDraggableCallback()}componentDidUpdate(){this.updateDraggableCallback()}render(){const{cell:s,editCellItem:o,setTemplateState:a,draggableType:i}=this.props,l=Ox(s,this.state.hovering[s.objectId]);return t.jsxs("div",{children:[t.jsx("div",{style:{minHeight:"50px",maxHeight:"50px",width:"100%",borderBottom:s.underline?"1px solid":void 0}}),t.jsx("div",{style:l,onMouseOver:()=>this.onMouseOver(s.objectId),onMouseOut:()=>this.onMouseOut(s.objectId),onDoubleClick:()=>this.onDoubleClick(s.objectId),onMouseDown:()=>this.onMouseDown(s),children:t.jsx(Ge,{content:t.jsx("textarea",{onContextMenu:r=>r.stopPropagation(),fill:!0,ref:this.noteRef,defaultValue:s.contractNote,className:"ignore-react-onclickoutside"}),isOpen:this.state.showPopover===s.objectId,onClose:()=>{if(s.contractNote!==this.noteRef.current.value){s.contractNote=this.noteRef.current.value;const r=s.getSourceObject();a(new $(r.toJSON()))}},children:t.jsx("div",{style:l,children:s.contractNote})})}),t.jsx(We,{droppableId:this.droppableId,isDropDisabled:i!==yn.ContainerKey,children:(r,d)=>t.jsxs("div",{ref:r.innerRef,...r.droppableProps,style:tt(d.isDraggingOver,o.objectId===s.objectId),children:[s.additionalLines.map((c,u)=>{const p=`${c.objectId}-value`,h=`${c.objectId}-note`,g=Nx(c,this.state.hovering[p]),x=Mx(c,this.state.hovering[h]),m=`${c.getPath().join("-")}-${c.objectId}`;return t.jsx(Ke,{draggableId:m,index:u,children:(f,j)=>t.jsxs("div",{ref:f.innerRef,...f.draggableProps,...f.dragHandleProps,style:rt(j,f.draggableProps.style,o.objectId===c.objectId),children:[t.jsx("div",{style:{width:"100%",borderBottom:c.underline?"1px solid":void 0},children:t.jsx("div",{style:g,onMouseOver:()=>this.onMouseOver(p),onMouseOut:()=>this.onMouseOut(p),onDoubleClick:()=>this.onDoubleClick(p),onMouseDown:()=>this.onMouseDown(c),children:t.jsx(Ge,{content:t.jsx("textarea",{onContextMenu:S=>S.stopPropagation(),fill:!0,ref:S=>{this[p]=S},defaultValue:c.value,className:"ignore-react-onclickoutside"}),isOpen:this.state.showPopover===p,onClose:()=>{if(c.value!==this[p].value){c.value=this[p].value;const S=c.getSourceObject();a(new $(S.toJSON()))}},children:t.jsx("div",{style:g,children:c.value})})})}),t.jsx("div",{style:x,onMouseOver:()=>this.onMouseOver(h),onMouseOut:()=>this.onMouseOut(h),onDoubleClick:()=>this.onDoubleClick(h),onMouseDown:()=>this.onMouseDown(c),children:t.jsx(Ge,{content:t.jsx(fe,{onContextMenu:S=>S.stopPropagation(),fill:!0,inputRef:S=>{this[h]=S},defaultValue:c.note,className:"ignore-react-onclickoutside"}),isOpen:this.state.showPopover===h,onClose:()=>{c.note=this[h].value;const S=c.getSourceObject();a(new $(S.toJSON()))},children:t.jsx("div",{style:x,children:c.note})})}),f.placeholder]})},c.objectId)}),r.placeholder]})})]})}};Xa.propTypes={setTemplateState:b.func.isRequired,setEditItem:b.func.isRequired,cell:b.instanceOf(Ye).isRequired,draggableType:b.string,editCellItem:b.any};Xa.defaultProps={draggableType:void 0,editCellItem:{}};const Lx=({templatesEdit:n})=>({draggableType:n.draggableType,editCellItem:n.editCellItem}),Ex=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),Ax=Jt(Xa),_l=Z(Lx,Ex)(Ax),Fx={display:"flex",border:"3px solid transparent"},Za=({data:n,setTemplateState:e,parentPath:s,draggableType:o,editCellItem:a,setEditCellItem:i})=>{const l=p=>{bt(p,h=>{const{destination:g,draggableId:x,source:m}=h,f=n[0].getSourceObject(),j=new $(f.toJSON());let S=g.droppableId.split("-");S.pop(),S=S.map(v=>parseInt(v,10));const w=S.pop(),C=j.getItemAtPath(s);if(S.push(g.index),m.droppableId===`new-${Ye.ContainerKey}`){const v=new Ye;v.column=w,i(v),j.insertObjectAtPath(S,v,0)}else{let v=x.split("-");v.pop(),v=v.map(D=>parseInt(D,10));const I=j.getItemAtPath(v);I.column=w,j.deleteObjectAtPath(v),j.insertObjectAtPath(S,I,0),C.containerKey===X.ContainerKey?C.signatures.length||j.deleteObjectAtPath(C.getPath()):C.data.length||j.deleteObjectAtPath(C.getPath())}e(j)})},r=n.filter(({column:p})=>p===0),d=n.filter(({column:p})=>p===1),c=`${[...s,0].join("-")}-${Ye.ContainerKey}`,u=`${[...s,1].join("-")}-${Ye.ContainerKey}`;return l(c),l(u),t.jsxs("div",{style:Fx,children:[t.jsx(We,{droppableId:c,isDropDisabled:o!==Ye.ContainerKey,children:(p,h)=>t.jsxs("div",{ref:p.innerRef,style:{...tt(h.isDraggingOver),width:"50%",paddingRight:"5px"},...p.droppableProps,children:[r.map((g,x)=>t.jsx(Ke,{draggableId:`${g.getPath().join("-")}-${g.objectId}`,index:x,children:(m,f)=>t.jsx("div",{ref:m.innerRef,...m.draggableProps,...m.dragHandleProps,style:{...rt(f,m.draggableProps.style,a.objectId===g.objectId)},children:t.jsx(_l,{cell:g},g.objectId)})},g.objectId)),p.placeholder]})}),t.jsx(We,{droppableId:u,isDropDisabled:o!==Ye.ContainerKey,children:(p,h)=>t.jsxs("div",{ref:p.innerRef,style:{...tt(h.isDraggingOver),width:"50%",paddingRight:"5px"},...p.droppableProps,children:[d.map((g,x)=>t.jsx(Ke,{draggableId:`${g.getPath().join("-")}-${g.objectId}`,index:x,children:(m,f)=>t.jsx("div",{ref:m.innerRef,...m.draggableProps,...m.dragHandleProps,style:{...rt(f,m.draggableProps.style,a.objectId===g.objectId)},children:t.jsx(_l,{cell:g},g.objectId)})},g.objectId)),p.placeholder]})})]})};Za.propTypes={data:b.arrayOf(b.instanceOf(Ye)).isRequired,setTemplateState:b.func.isRequired,setEditCellItem:b.func.isRequired,parentPath:b.arrayOf(b.number).isRequired,draggableType:b.string,editCellItem:b.any};Za.defaultProps={draggableType:void 0,editCellItem:{}};const Rx=({templatesEdit:n={}})=>({draggableType:n.draggableType,editCellItem:n.editCellItem}),_x=n=>({setTemplateState:e=>n(ee(e)),setEditCellItem:e=>n(Ne(e))}),Gc=Z(Rx,_x)(Za),Jc={},Qa=(n,e="default")=>{Jc[e||"default"]=n},sn=(n="default")=>Jc[n||"default"],Us=n=>{const e=document.createElement("textarea");e.value=n,e.setAttribute("readonly",""),e.style.position="absolute",e.style.left="-9999px",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)},ei=({onInsert:n,insertDisabled:e,onDelete:s,deleteDisabled:o,onCut:a,cutDisabled:i,onCopy:l,copyDisabled:r,onPasteAbove:d,pasteAboveDisabled:c,onPasteBelow:u,pasteBelowDisabled:p})=>t.jsxs(xe,{children:[n&&t.jsx(_,{onClick:n,icon:"insert",text:"New",disabled:e}),s&&t.jsx(_,{onClick:s,icon:"small-cross",text:"Delete",disabled:o}),n&&t.jsx(en,{}),a&&t.jsx(_,{onClick:a,icon:"cut",text:"Cut",disabled:i}),l&&t.jsx(_,{onClick:l,icon:"duplicate",text:"Copy",disabled:r}),d&&t.jsx(_,{onClick:d,icon:"clipboard",text:"Paste Above",disabled:c}),t.jsx(_,{onClick:u,icon:"clipboard",text:"Paste Below",disabled:p})]});ei.propTypes={onInsert:b.func,insertDisabled:b.bool,onDelete:b.func,deleteDisabled:b.bool,onCut:b.func,cutDisabled:b.bool,onCopy:b.func,copyDisabled:b.bool,onPasteAbove:b.func,pasteAboveDisabled:b.bool,onPasteBelow:b.func,pasteBelowDisabled:b.bool};ei.defaultProps={onInsert:void 0,insertDisabled:!1,onDelete:void 0,deleteDisabled:!1,onCut:void 0,cutDisabled:!1,onCopy:void 0,copyDisabled:!1,onPasteAbove:void 0,pasteAboveDisabled:!1,onPasteBelow:void 0,pasteBelowDisabled:!1};class ti extends J.Component{constructor(s){super(s);W(this,"onMouseDown",s=>{let{clientX:o,clientY:a}=s;const{touches:i}=s;i&&(o=i[0].clientX,a=i[0].clientY),s.clientX=o,s.clientY=a;const{startTimeout:l}=this.props;this.setState({initEvent:s}),this.clearTimeout(),this.longPressTimeout=setTimeout(this.longPressStart,l)});W(this,"onMouseOut",s=>{this.clearTimeout(),this.isCurrentlyPressed()&&this.setState({isPressed:!1})});W(this,"clearTimeout",()=>{clearTimeout(this.longPressTimeout),clearInterval(this.pressInterval),this.longPressTimeout=void 0,this.pressInterval=void 0});W(this,"isCurrentlyPressed",()=>{const{isPressed:s}=this.state;return s});W(this,"longPressStart",()=>{const{longPressStart:s,finite:o,pressCallback:a,pressCallbackTimeout:i}=this.props;s(),o?o&&(this.pressInterval=setTimeout(this.longPressEnd,i)):(a(),this.pressInterval=setInterval(a,i)),this.setState({isPressed:!0})});W(this,"longPressEnd",()=>{const{initEvent:s}=this.state;this.onMouseOut(s);const{longPressEnd:o=()=>{},onContextMenu:a=()=>{}}=this.props;o(s),a(s),this.setState({initEvent:void 0})});this.state={isPressed:!1,initEvent:void 0},window.document.body.addEventListener("touchmove",()=>{this.onMouseOut()})}render(){const{children:s,onContextMenu:o}=this.props;return t.jsx(J.Fragment,{children:J.Children.map(s,a=>t.jsx(J.Fragment,{children:J.cloneElement(a,{onContextMenu:o,onTouchMove:i=>this.onMouseOut(i),onTouchCancel:i=>this.onMouseOut(i),onTouchStart:i=>this.onMouseDown(i),onTouchEnd:i=>this.onMouseOut(i)})}))})}}ti.defaultProps={startTimeout:300,longPressStart:()=>{},longPressEnd:()=>{},pressCallbackTimeout:300,pressCallback:void 0,finite:!0};ti.propTypes={startTimeout:b.number,longPressStart:b.func,longPressEnd:b.func,pressCallbackTimeout:b.number,pressCallback:b.func,finite:b.bool,children:b.node.isRequired,onContextMenu:b.func.isRequired};const Bx=n=>{const{cellType:e=""}=n;switch(e){case"emptySpace":return t.jsx(Hc,{cellItem:n});case"textShort":case"textLong":case"switched":case"textOnly":case"textXLong":return t.jsx(qt,{cellItem:n});case"header":return t.jsx(ed,{section:n.header,noBorder:!0});case"detailCell":return t.jsx(bx,{cellItem:n});case"photoPickerCell":return t.jsxs("div",{children:[t.jsx(qt,{cellItem:n,lockedTitle:`${n.photoTag||"Image "} 1.1`,lockedValue:"(Placeholder Image Note)"}),t.jsx(qt,{cellItem:n,lockedTitle:`${n.photoTag||"Image "} 1.2`,lockedValue:"(Placeholder Image Note)"})]});
3case"securePaymentCaptureAll":case"creditCardCell":return t.jsx(qt,{cellItem:n,lockedValue:"XXXX-XXXX-XXXX-1234"});case"bankAccountCell":return t.jsx(qt,{cellItem:n,lockedValue:"XXXXX1234"});case"drawing":return t.jsx(jx,{cellItem:n});case"measureSheetItemDetail":return t.jsx(Dx,{cellItem:n});case"signatures":return t.jsx(Gc,{data:n.signatures,parentPath:n.getPath()});case"provia":return t.jsx(vx,{cellItem:n});default:return t.jsx("div",{children:e})}},Yc=({template:n,cellItem:e,setTemplateState:s})=>{var i;let o=[...n==null?void 0:n.linkedIds],a=new $(n.toJSON());n.deleteObject(e),(o==null?void 0:o.length)!==((i=n==null?void 0:n.linkedIds)==null?void 0:i.length)?(async r=>{a=new $({...r.toJSON()});const d=await a.fetchTemplateTypes({linkedIds:r.linkedIds});a.linkedTypes=d,s(a)})(n):(a=new $(n.toJSON()),s(a))},Xc=({cellItem:n})=>{Qa(n)},$x=n=>{Xc(n),Yc(n)},ba=(n,e,{template:s,setTemplateState:o,showAlertModal:a,cellItem:i})=>{if(n){const l=i.getPath(),r=s.getAllCellIdentifiers([]);if(n.getCellIds){const u=n.getCellIds().filter(p=>r.indexOf(p)>-1);if(u.length)return a({level:"error",title:"Identifier Conflict",msg:`Cannot paste due to cells already existing with identifiers: ${u.join(", ")}`})}s.insertObjectAtPath(l,n.clone(),e);const d=new $(s.toJSON());o(d)}},zx=n=>{const e=new X;ba(e,1,n)},Wx=(n,e)=>{n.preventDefault(),e.setEditItem(e.cellItem);const s=sn()||{},o=t.jsx(ei,{onInsert:()=>zx(e),onDelete:()=>Yc(e),onCut:()=>$x(e),onCopy:()=>Xc(e),onPasteAbove:()=>ba(sn(),0,e),pasteAboveDisabled:s.containerKey!==e.cellItem.containerKey,onPasteBelow:()=>ba(sn(),1,e),pasteBelowDisabled:s.containerKey!==e.cellItem.containerKey});Qr.show(o,{left:n.clientX,top:n.clientY})},Zc=({children:n,...e})=>J.Children.map(n,s=>t.jsx(ti,{onContextMenu:o=>Wx(o,e),children:J.cloneElement(s)}));Zc.propTypes={};const Hx=({templatesEdit:n})=>({template:n[n.currentWorkingId],showAlertModal:n.showAlertModal}),qx=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),ot=Z(Hx,qx)(Zc),Vx={0:"left",1:"center",2:"right"},Bl=(n,e,s=40)=>{switch(n){case"emptySpace":return`${e}px`;case"companyLogo":case"image":return`${s||0}px`;default:return}},Kx=n=>{const[e,s,o,a]=n.split("-");return`rgba(${e},${s},${o},${a})`},Ux=({fontSize:n,logoHeight:e,fontBold:s,fontUnderline:o,fontName:a,alignment:i,emptySpaceHeight:l,cellType:r,fontColor:d},c)=>({color:d?Kx(d):void 0,cursor:"pointer",fontSize:n,fontFamily:Zt(a)?a:"HelveticaNeue",minHeight:Bl(r,l,e),maxHeight:Bl(r,l,e),textAlign:Vx[i],textDecoration:o?"underline":void 0,fontWeight:s?"900":"400",width:"100%",opacity:c?"0.7":void 0}),$l=(n,e)=>t.jsx("div",{id:"header-cell-item",style:e,children:t.jsx("img",{alt:"Header",src:n,style:{objectFit:"contain",maxWidth:"100%",maxHeight:e.maxHeight}})});let ni=class extends J.Component{constructor(s){super(s);W(this,"onMouseOver",()=>{this.setState({isHovering:!0})});W(this,"onMouseOut",()=>{this.setState({isHovering:!1})});W(this,"onMouseDown",()=>{this.props.setEditItem(this.props.cell)});W(this,"onDoubleClick",()=>{this.setState({showPopover:!this.state.showPopover})});W(this,"handleClickOutside",()=>{this.state.showPopover&&this.setState({showPopover:!1})});this.state={isHovering:!1,showPopover:!1},this.inputRef=J.createRef()}render(){const s=Ux(this.props.cell,this.state.isHovering),{cell:o={},setTemplateState:a,companyLogo:i}=this.props,{cellType:l,image:r,value:d=""}=o;return d==="%image%"||l==="image"?t.jsx(ot,{cellItem:o,children:t.jsx("div",{onMouseOver:this.onMouseOver,onMouseOut:this.onMouseOut,onMouseDown:this.onMouseDown,children:$l(r?typeof r.url=="string"?r.url:typeof r.url=="function"?r.url():void 0:void 0,s)})}):d==="%companyLogo%"||l==="companyLogo"?t.jsx(ot,{cellItem:o,children:t.jsx("div",{onMouseOver:this.onMouseOver,onMouseOut:this.onMouseOut,onMouseDown:this.onMouseDown,children:$l(i.url,s)})}):l==="emptySpace"?t.jsx(ot,{cellItem:o,children:t.jsx("div",{onMouseOver:this.onMouseOver,onMouseOut:this.onMouseOut,onMouseDown:this.onMouseDown,children:t.jsx("div",{style:s})})}):t.jsx(ot,{cellItem:o,children:t.jsx("div",{onMouseOver:this.onMouseOver,onMouseOut:this.onMouseOut,onMouseDown:this.onMouseDown,onDoubleClick:this.onDoubleClick,style:s,children:t.jsx(Ge,{content:t.jsx("textarea",{onContextMenu:c=>c.stopPropagation(),fill:!0,ref:this.inputRef,defaultValue:d,className:"ignore-react-onclickoutside"}),position:La.BOTTOM,isOpen:this.state.showPopover,onClose:()=>{if(o.value!==this.inputRef.current.value){o.value=this.inputRef.current.value;const c=o.getSourceObject();a(new $(c.toJSON()))}},children:t.jsx("div",{style:s,children:d.split(/[\r\n]/).map((c,u)=>t.jsxs("span",{children:[c,t.jsx("br",{})]},u))})})})})}};ni.propTypes={cell:b.instanceOf(tn).isRequired,setEditItem:b.func.isRequired,setTemplateState:b.func.isRequired,companyLogo:b.shape({url:b.string.isRequired})};ni.defaultProps={companyLogo:{url:""}};const Gx=({auth:n={},plan:e={}})=>{const{config:s={}}=n,{planId:o=""}=e,{companyLogo:a={}}=s;let i=a._url;return Ng(i,l=>{l||(i=window.location.origin+(o==="lite"?"/images/leap_logo_lite.png":"/images/leap_logo.png"))}
3),{companyLogo:{url:i}}},Jx=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),Yx=Jt(ni),Xx=Z(Gx,Jx)(Yx),Zx=(n,e)=>({border:n?"1px solid black":void 0,padding:"2px",position:"relative",height:"100%"}),si=({cells:n,border:e,widthPercent:s,setTemplateState:o,editCellItem:a,setEditCellItem:i,templateValues:l,draggableType:r})=>{const d=`${n.getPath().join("-")}-${n.objectId}-${tn.ContainerKey}`;return bt(d,c=>{let u=c.destination.droppableId.split("-");u.pop(),u.pop(),u=u.map(f=>parseInt(f,10)),u.push(c.destination.index);const p=new $(l.toJSON());if(c.source.droppableId===`new-${tn.ContainerKey}`){const f=new tn;p.insertObjectAtPath(u,f,0),o(p),i(f);return}let h=c.draggableId.split("-");if(h.pop(),h=h.map(f=>parseInt(f,10)),h.every((f,j)=>f===u[j]))return;const g=p.getItemAtPath(h),x=[...h];x.pop();const m=p.getItemAtPath(x);if(p.deleteObjectAtPath(h),p.insertObjectAtPath(u,g,0),!m.length){const f=[...x];f.pop(),p.getItemAtPath(f).cellItems.every((S=[])=>S.length===0)&&p.deleteObjectAtPath(f)}o(p)}),t.jsx(We,{droppableId:d,isDropDisabled:r!==tn.ContainerKey,children:(c,u)=>t.jsxs("div",{ref:c.innerRef,style:{...tt(u.isDraggingOver),...Zx(e)},...c.droppableProps,children:[n.cellItems.map((p,h)=>t.jsx(Ke,{draggableId:`${p.getPath().join("-")}-${p.objectId}`,index:h,children:(g,x)=>t.jsxs("div",{ref:g.innerRef,...g.draggableProps,style:rt(x,g.draggableProps.style,a.objectId===p.objectId),children:[t.jsx(Xx,{cell:p}),t.jsx("div",{...g.dragHandleProps,style:{...g.draggableProps.style,position:"absolute",left:"0",top:"0",height:"50%",maxHeight:"20px",backgroundColor:"transparent",width:"100%"}}),g.placeholder]})},p.objectId)),c.placeholder]})})};si.propTypes={templateValues:b.instanceOf($).isRequired,cells:b.instanceOf(ht),border:b.bool,widthPercent:b.number,setTemplateState:b.func.isRequired,setEditCellItem:b.func.isRequired,editCellItem:b.any,draggableType:b.string};si.defaultProps={cells:[],border:!1,widthPercent:100,editCellItem:{},draggableType:void 0};const Qx=({templatesEdit:n={}})=>({editCellItem:n.editCellItem,templateValues:n[n.currentWorkingId]||new $,draggableType:n.draggableType}),ef=n=>({setTemplateState:e=>n(ee(e)),setEditCellItem:e=>n(Ne(e))}),tf=Z(Qx,ef)(si),nf=n=>{switch(n){case 1:case"1":return{border:"1px solid black",display:"flex"};case 3:case"3":return{borderTop:"1px solid black",borderBottom:"1px solid black",display:"flex"};case 0:case"0":case 2:case"2":default:return{border:"0",display:"flex"}}},oi=({section:n,editCellItem:e,setTemplateState:s,templateValues:o,setEditItem:a,draggableType:i})=>{const{noBorder:l=!1,border:r=0,cellItems:d=[]}=n,c=`${n.getPath().join("-")}-${n.objectId}-${dt.ContainerKey}`;return bt(c,u=>{const{draggableId:p,destination:h,source:g}=u;let x=h.droppableId.split("-");x.pop(),x.pop(),x=x.map(C=>parseInt(C,10)),x.push(h.index);const m=new $(o.toJSON());if(g.droppableId===`new-${dt.ContainerKey}`){const C=new ht;a(C.cellItems[0]),m.insertObjectAtPath(x,C,0),s(m);return}let f=p.split("-");if(f.pop(),f=f.map(C=>parseInt(C,10)),f.every((C,v)=>C===x[v]))return;const j=m.getItemAtPath(f),S=[...f];S.pop();const w=m.getItemAtPath(S);m.deleteObjectAtPath(f),m.insertObjectAtPath(x,j,0),w.cellItems.length||m.deleteObjectAtPath(w.getPath()),s(m)}),t.jsx(We,{droppableId:c,direction:"horizontal",isDropDisabled:i!==dt.ContainerKey,children:(u,p)=>t.jsxs("div",{ref:u.innerRef,style:{...nf(l?0:r),...tt(p.isDraggingOver)},...u.droppableProps,children:[d.map((h,g)=>{const x=`${n.objectId}-${g}`,m=100/d.length,f=`${h.getPath().join("-")}-header_row_group`;return t.jsx(Ke,{draggableId:f,index:g,children:(j,S)=>t.jsxs("div",{ref:j.innerRef,...j.draggableProps,...j.dragHandleProps,style:{...rt(S,j.draggableProps.style,h.objectId===e.objectId),minWidth:S.isDragging?void 0:`${m}%`,maxWidth:S.isDragging?void 0:`${m}%`},children:[t.jsx(tf,{cells:h,border:r===2||r==="2"}),j.placeholder]})},x)}),u.placeholder]})})};oi.propTypes={section:b.instanceOf(dt).isRequired,setTemplateState:b.func.isRequired,setEditItem:b.func.isRequired,editCellItem:b.any,templateValues:b.instanceOf($).isRequired,draggableType:b.string};oi.defaultProps={editCellItem:{},draggableType:void 0};const sf=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem,draggableType:n.draggableType}),of=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),af=Z(sf,of)(oi);class ai extends J.PureComponent{constructor(s){super(s);W(this,"onDoubleClick",()=>{const{showPopover:s}=this.state;this.setState({showPopover:!s})});W(this,"handleClickOutside",()=>{this.setState({showPopover:!1})});this.state={showPopover:!1},this.titleRef=J.createRef()}render(){const{style:s,onChange:o,onClick:a}=this.props;return t.jsx("div",{onDoubleClick:i=>{this.onDoubleClick(i)},className:"outer sectin ",style:{...s,overflow:"hidden",textOverflow:"ellipsis"},children:t.jsx(Ge,{content:t.jsx("textarea",{onContextMenu:i=>i.stopPropagation(),fill:!0,ref:this.titleRef,defaultValue:this.props.title,className:"ignore-react-onclickoutside"}),isOpen:this.state.showPopover,onClose:()=>{this.titleRef.current.value!==this.props.title&&o(this.titleRef.current.value)},children:t.jsx("div",{className:"templates-pdf__text templates-single_line",onClick:i=>{a(i)},style:{...s,height:s.fontSize,width:768},children:this.props.title})})})}}ai.propTypes={title:b.string,style:b.shape({}).isRequired,onChange:b.func.isRequired,onClick:b.func.isRequired};ai.defaultProps={title:""};const hn=Jt(ai),lf=({title:n,titleFontBold:e=!0,titleFontColor:s,titleFontName:o=void 0,titleFontSize:a=12,titleFontUnderline:i=!1})=>{const l=s?s.split("-"):[],[r,d,c,u]=l;return{fontWeight:e?900:void 0,color:s?`rgba(${r},${d},${c},${u})`:void 0,fontSize:`${a}px`,textDecoration:i?"underline":void 0,fontFamily:Zt(o)?o:"HelveticaNeue",cursor:"pointer",maxHeight:n?void 0:"1px"}},rf={value:"title",bold:"titleFontBold",border:"border",underline:"titleFontUnderline",size:"titleFontSize",font:"titleFontName",color:"titleFontColor",cellItems:"cellItems"},Qc=({section:n={}
3,setTemplateState:e,setEditItem:s})=>{const{title:o,...a}=n;return t.jsxs("div",{id:"header-section",style:{position:"relative"},children:[t.jsx(hn,{title:o,keyMaps:rf,toolbarKey:"headerTitle",style:lf(n),onChange:i=>{n.title=i;const l=n.getSourceObject();e(new $(l.toJSON()))},onClick:()=>s(n),...a}),t.jsx(af,{section:n})]})};Qc.propTypes={section:b.instanceOf(dt).isRequired,setTemplateState:b.func.isRequired,setEditItem:b.func.isRequired};const cf=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),ed=Z(void 0,cf)(Qc),ii=({section:n,setTemplateState:e,editCellItem:s,draggableType:o,setEditCellItem:a})=>{const i=`${n.objectId}-${Bt.ContainerKey}`;return bt(i,l=>{const{source:r,destination:d}=l,c=n.getSourceObject();let u;if(r.droppableId===`new-${Bt.ContainerKey}`)u=new dt,n.data.splice(d.index,0,u);else{const g=r.droppableId.split("-")[0],x=c.getObjectWithId(g),m=x.data[r.index];x.data.splice(r.index,1);const f=d.droppableId.split("-")[0];c.getObjectWithId(f).data.splice(d.index,0,m)}const p=new $(c.toJSON()),[h]=p.contractData.filter(g=>g.objectId===n.objectId);e(p),u&&a(h.data[d.index])}),t.jsx(We,{droppableId:i,isDropDisabled:o!==Bt.ContainerKey,children:(l,r)=>t.jsxs("div",{ref:l.innerRef,style:tt(r.isDraggingOver,s.objectId===n.objectId),...l.droppableProps,className:"header-container",children:[n.data.map((d,c)=>t.jsx(Ke,{draggableId:d.objectId,index:c,children:(u,p)=>t.jsxs("div",{ref:u.innerRef,...u.draggableProps,style:{...rt(p,u.draggableProps.style,s.objectId===d.objectId)},children:[t.jsx(ed,{section:d}),t.jsx("div",{...u.dragHandleProps,style:{...u.draggableProps.style,position:"absolute",left:"-15px",top:"0",height:"100%",backgroundColor:"transparent",width:"15px"}}),u.placeholder]})},d.objectId)),l.placeholder]})})};ii.propTypes={section:b.instanceOf(Bt).isRequired,setTemplateState:b.func.isRequired,editCellItem:b.any,setEditCellItem:b.func.isRequired,draggableType:b.string};ii.defaultProps={editCellItem:{},draggableType:void 0};const df=({templatesEdit:n})=>({editCellItem:n.editCellItem,draggableType:n.draggableType}),uf=n=>({setTemplateState:e=>n(ee(e)),setEditCellItem:e=>n(Ne(e))}),pf=Z(df,uf)(ii),hf=({shading:n},e,s)=>({backgroundColor:n===2||n===1&&s%2!==0?"rgb(224, 224, 224, 0.7)":void 0}),td=(n,e,s,o)=>{bt(n,a=>{const{source:i,destination:l,draggableId:r}=a,d=e.getSourceObject();if(i.droppableId===`new-${X.ContainerKey}`){const h=new X(void 0,e);e.cellItems.splice(l.index,0,h);const g=new $(d.toJSON());s(g),o(h);return}let c=r.split("-");c.pop(),c=c.map(h=>parseInt(h,10));const u=d.getItemAtPath(c);u.parent.cellItems.splice(i.index,1),e.cellItems.splice(l.index,0,u),u.parent.cellItems.length||d.deleteObjectAtPath(u.parent.getPath());const p=new $(d.toJSON());s(p)})},li=({section:n,setTemplateState:e,editCellItem:s,draggableType:o,setEditCellItem:a,scale:i})=>{const{cellItems:l,...r}=n,d=`${n.objectId}-${X.ContainerKey}`;return td(d,n,e,a),t.jsx(We,{droppableId:d,isDropDisabled:o!==X.ContainerKey,children:(c,u)=>t.jsxs("div",{ref:c.innerRef,style:{border:r.drawBorder?"1px solid black":void 0,...tt(u.isDraggingOver)},...c.droppableProps,children:[l.map((p,h)=>t.jsx(Ke,{draggableId:`${p.getPath().join("-")}-${p.objectId}`,index:h,children:(g,x)=>t.jsxs("div",{ref:g.innerRef,...g.draggableProps,...g.dragHandleProps,style:{...rt(x,g.draggableProps.style,s.objectId===p.objectId),translate:"translateX(-100%)"},children:[t.jsx("div",{style:hf(r,p,h),children:Bx(p)}),g.placeholder]})},p.objectId)),c.placeholder]})})};li.propTypes={section:b.instanceOf(ct).isRequired,setTemplateState:b.func.isRequired,setEditCellItem:b.func.isRequired,editCellItem:b.any,draggableType:b.string};li.defaultProps={editCellItem:{},draggableType:void 0};const mf=({templatesEdit:n})=>({editCellItem:n.editCellItem,draggableType:n.draggableType,scale:n.scale}),gf=n=>({setTemplateState:e=>n(ee(e)),setEditCellItem:e=>n(Ne(e))}),xf=Z(mf,gf)(li),nd=({enabled:n=!0}={})=>{const{data:e=[],isLoading:s,error:o,refetch:a}=He({queryKey:["fenevision-manufacturers"],queryFn:async()=>{try{return await se.Cloud.run("fenevision-manufacturers")}catch(i){throw console.error("Failed to fetch Fenevision manufacturers:",i),new Error(`Failed to fetch manufacturers: ${i instanceof Error?i.message:"Unknown error"}`)}},refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,staleTime:3e5,cacheTime:18e5,enabled:n});return{manufacturers:e,isLoading:s,error:o,refetch:a}};function ff(n){const e=new Set;
3return!n||n.length===0||n.forEach(s=>{var i;const o=s.get("config"),a=o==null?void 0:o.get("fenetech");a!=null&&a.enabled&&((i=a.manufacturers)==null||i.forEach(({id:l})=>l&&e.add(l)))}),e}const ri=({enabled:n=!0}={})=>{const e=ze(d=>{var c;return((c=d==null?void 0:d.auth)==null?void 0:c.offices)||[]}),{manufacturers:s=[],isLoading:o,error:a,refetch:i}=nd({enabled:n&&((e==null?void 0:e.length)??0)>0}),l=y.useMemo(()=>ff(e),[e]);return{manufacturers:y.useMemo(()=>{if(!s||s.length===0)return[];const d=s.filter(u=>l.has(u.id)),c=new Map;return d.forEach(u=>{c.has(u.id)||c.set(u.id,u)}),at.sortBy(Array.from(c.values()),"name")},[s,l]),isLoading:o,error:a,refetch:i}},bf=({section:n,keyMaps:e,style:s,onClick:o,...a})=>{const{downloadParams:i={}}=n,{headers:l={}}=i,{"x-manufacturer-id":r}=l,{manufacturers:d,isLoading:c,error:u}=nd({enabled:!!r});if(c)return t.jsx(hn,{title:"Loading...",keyMaps:e,toolbarKey:"bodyTitle",style:s,onClick:o,...a});if(u)return t.jsx(hn,{title:u.message||"Failed to fetch manufacturers",keyMaps:e,toolbarKey:"bodyTitle",style:s,onClick:o,...a});if(!r)return t.jsx(hn,{title:"No manufacturer ID provided",keyMaps:e,toolbarKey:"bodyTitle",style:s,onClick:o,...a});const p=d.find(m=>m.id===r);if(!p)return t.jsx(hn,{title:"Manufacturer not found",keyMaps:e,toolbarKey:"bodyTitle",style:s,onClick:o,...a});const h=p.name,g=`${h} - Quote 4567`,x=h?n.fontColor:"255-0-0-1";return t.jsxs(t.Fragment,{children:[t.jsx(hn,{title:g,keyMaps:e,toolbarKey:"bodyTitle",style:{...s,fontColor:x},onClick:o,...a}),t.jsx("div",{style:{border:n.drawBorder?"1px solid black":void 0,...tt(!1,!1)},children:t.jsx("div",{children:t.jsx("img",{src:p.imageURL,alt:p.name,style:{height:"200px",display:"block",margin:"0 auto"},onError:m=>{const f=m.target;f.style.display="none"}})})})]})},ci={value:"contractTitle",bold:"fontBold",border:"drawBorder",underline:"fontUnderline",size:"fontSize",font:"fontName",color:"fontColor",cellItems:"cellItems",shading:"shading",newPage:"newPage",linkedMeasureSheetItemIds:"linkedMeasureSheetItemIds"},yf={position:"relative"},ya=({contractTitle:n,fontBold:e=!0,fontColor:s,fontName:o=void 0,fontSize:a=14,fontUnderline:i=!1})=>{const l=s?s.split("-"):[],[r,d,c,u]=l;return{fontWeight:e?900:void 0,color:s?`rgba(${r},${d},${c},${u})`:void 0,fontSize:a,textDecoration:i?"underline":void 0,fontFamily:Zt(o)?o:"HelveticaNeue",cursor:"pointer",maxHeight:n?void 0:"1px"}},jf=({section:n})=>t.jsx(hn,{title:"Unknown Integration in Body Section",keyMaps:ci,toolbarKey:"bodyTitle",style:ya({...n,fontColor:"255-0-0-1"})}),Cf=({section:n,onClick:e,style:s,...o})=>{var a;switch((a=n.downloadParams)==null?void 0:a.endpoint){case"/fenetech/documents/section":return t.jsx(bf,{section:n,keyMaps:ci,onClick:e,style:s,...o});default:return t.jsx(jf,{section:n})}};let sd=class extends J.Component{render(){const{section:e,setTemplateState:s,setEditItem:o}=this.props,{contractTitle:a,cellItems:i,requiresDownload:l,...r}=e;return l?t.jsx(Cf,{section:e,onClick:()=>o(e),style:ya(e),...r}):t.jsxs("div",{id:"body-section",style:yf,children:[t.jsx(hn,{title:a,keyMaps:ci,toolbarKey:"bodyTitle",style:ya(e),onChange:d=>{e.contractTitle=d;const c=e.getSourceObject();s(new $(c.toJSON()))},onClick:()=>o(e),...r}),t.jsx(xf,{section:e})]})}};sd.propTypes={section:b.instanceOf(ct).isRequired,setEditItem:b.func.isRequired,setTemplateState:b.func.isRequired};const If=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),Sf=Z(void 0,If)(sd),di=({section:n,setTemplateState:e,editCellItem:s,setEditCellItem:o,draggableType:a})=>{const i=`${n.objectId}-${ct.ContainerKey}`;return bt(i,l=>{const{source:r,destination:d}=l;let c;r.droppableId===`new-${ct.ContainerKey}`?(c=new ct,n.data.splice(d.index,0,c)):n.data=Rc(n.data,l.source.index,l.destination.index);const u=n.getSourceObject(),p=new $(u.toJSON());e(p);const[h]=p.contractData.filter(g=>g.groupType==="body");c&&o(h.data[d.index])}),Cs.expectedSections.initCount=n.data.length,Cs.expectedSections.count=0,t.jsx(We,{droppableId:i,isDropDisabled:a!==ct.ContainerKey,children:(l,r)=>t.jsxs("div",{ref:l.innerRef,style:tt(r.isDraggingOver,s.objectId===n.objectId),...l.droppableProps,className:"body-container",children:[n.data.map((d,c
3)=>{const u=Cs.getBound(d);return t.jsx(Ke,{draggableId:`${d.objectId}`,index:c,children:(p,h)=>t.jsxs("div",{ref:p.innerRef,...p.draggableProps,style:rt(h,p.draggableProps.style,s.objectId===d.objectId),children:[t.jsx("div",{ref:g=>{g&&Cs.addSectionRef(d,g)},children:u&&u.rect&&!u.inBound?t.jsx("div",{style:{height:u.rect.height,width:u.rect.width}}):t.jsx(Sf,{index:c,section:d})}),t.jsx("div",{...p.dragHandleProps,style:{...p.draggableProps.style,position:"absolute",left:"-15px",top:"0",height:"100%",backgroundColor:"transparent",width:"15px"}}),p.placeholder]})},d.objectId)}),l.placeholder]})})};di.propTypes={section:b.instanceOf(Gn).isRequired,setTemplateState:b.func.isRequired,setEditCellItem:b.func.isRequired,editCellItem:b.any,draggableType:b.string};di.defaultProps={editCellItem:{},draggableType:void 0};const vf={},Tf=({templatesEdit:n,templateScrollContext:e})=>({editCellItem:n.editCellItem,draggableType:n.draggableType,templateScrollContext:e||vf}),wf=n=>({setTemplateState:e=>n(ee(e)),setEditCellItem:e=>n(Ne(e))}),kf=Z(Tf,wf)(di);let zl=null;class Pf{constructor(){W(this,"sectionData",{});W(this,"sections",[]);W(this,"expectedSections",{count:0});W(this,"setMainRef",(e,s)=>{this.mainTemplatesRef=e,this.update=()=>{s({})},this.mainTemplatesRef.onscroll=o=>{const{isDragging:a}=Ac.getState().templatesEdit;a||(window.clearTimeout(zl),zl=setTimeout(()=>{this.pageContract()},100))},this.pageContract()});W(this,"addSectionRef",(e,s)=>{this.sectionData[e.objectId]||this.sections.push(e),this.sectionData[e.objectId]={...this.sectionData[e.objectId],ref:s},this.expectedSections.initCount&&!this.initSet&&(this.expectedSections.count++,this.expectedSections.initCount===this.expectedSections.count&&(this.expectedSections.initCount=null,setTimeout(()=>{this.update&&!this.initSet&&this.pageContract(),this.initSet=!0},250)))});W(this,"inBounds",(e,s=0,o,a=0)=>e<o+a&&e>s-a);W(this,"getBound",e=>{const s=this.sectionData[e.objectId];return s&&s.rect?s:{inBound:!0}});W(this,"calcSectionPage",e=>{if(e&&this.mainTemplatesRef){const s=e.getBoundingClientRect(),o=this.mainTemplatesRef.getBoundingClientRect();let a=this.inBounds(s.top,o.top,o.bottom,100),i=this.inBounds(s.bottom,o.top,o.bottom,100);return s.height>o.height&&(a=this.inBounds(o.top,s.top,s.bottom,100),i=this.inBounds(o.bottom,s.top,s.bottom,100)),a||i?{rect:s,ref:e,inBound:!0}:{rect:s,ref:e,inBound:!1}}});W(this,"pageContract",()=>{this.sections.forEach(e=>{const{ref:s}=this.sectionData[e.objectId],o=this.calcSectionPage(s);this.sectionData[e.objectId]=o}),this.update()})}}class $t extends J.Component{constructor(s){super(s);W(this,"onMouseDown",s=>{let{clientX:o,clientY:a}=s;const{touches:i}=s;i&&(o=i[0].clientX,a=i[0].clientY);const l={clientX:o,clientY:a,preventDefault:s.preventDefault},{startTimeout:r}=this.props;this.setState({initEvent:l}),this.clearTimeout(),this.longPressTimeout=setTimeout(this.longPressStart,r)});W(this,"onMouseOut",()=>{this.clearTimeout(),this.isCurrentlyPressed()&&this.setState({isPressed:!1})});W(this,"clearTimeout",()=>{clearTimeout(this.longPressTimeout),clearInterval(this.pressInterval),this.longPressTimeout=void 0,this.pressInterval=void 0});W(this,"isCurrentlyPressed",()=>{const{isPressed:s}=this.state;return s});W(this,"longPressStart",()=>{const{longPressStart:s,finite:o,pressCallback:a,pressCallbackTimeout:i}=this.props;s(),o?o&&(this.pressInterval=setTimeout(this.longPressEnd,i)):(a(),this.pressInterval=setInterval(a,i)),this.setState({isPressed:!0})});W(this,"longPressEnd",()=>{this.onMouseOut();const{longPressEnd:s}=this.props,{initEvent:o}=this.state;s(o),this.setState({initEvent:void 0})});this.state={isPressed:!1,initEvent:void 0}}render(){const{children:s,className:o}=this.props;return t.jsx("span",{className:o,onTouchCancel:this.onMouseOut,onTouchStart:this.onMouseDown,onTouchEnd:this.onMouseOut,children:s})}}$t.defaultProps={startTimeout:300,longPressStart:()=>{},longPressEnd:()=>{},pressCallbackTimeout:300,pressCallback:void 0,finite:!0,className:""};$t.propTypes={startTimeout:b.number,longPressStart:b.func,longPressEnd:b.func,pressCallbackTimeout:b.number,pressCallback:b.func,finite:b.bool,className:b.string,children:b.node.isRequired};const Df=n=>{const{contractData:e=[]}=n;for(let s=0;s<e.length;s+=1){const{groupType:o}=e[s];if(o==="body")return!0}return!1},od=({template:n,setTemplateState:e})=>t.jsxs(Ge,{popoverClassName:"add-button-popover",className:"add-button-pop",position:La.RIGHT_TOP,content:t.jsxs(xe,{className:"add-button-menu",children:[t.jsx(en,{title:"Add New Section"}),t.jsx(_,{icon:"widget-header",text:"Header",onClick:()=>{const s=new $(n.toJSON());s.addHeaderSection(),e(s)}}),t.jsx(_,{icon:"widget-button",text:"Body",disabled:Df(n),onClick:()=>{const s=new $(n.toJSON());s.addBodySection(),e(s)}}),t.jsx(_,{icon:t.jsx(Ct,{icon:["far","file-signature"]}),text:"Signature",onClick:()=>{const s=new $(n.toJSON());s.addSignatureSection(),e(s)}})]}),children:[t.jsx(vn,{color:"dark",variant:"plain",icon:["far","plus"],className:"document-tree__add-button"}),"123123"]});od.propTypes={template:b.shape({objectId:b.isRequired}).isRequired,setTemplateState:b.func.isRequired};const Of=({templatesEdit:n})=>{const{currentWorkingId:e}=n;return{template:n[e]||{}}},Nf=n=>({setTemplateState:e=>n(ee(e))}),Mf=Z(Of,Nf)(od),Lf={body:"Body",header:"Header",signature:"Signature"},ad=(n,e,s,o,a,i,l)=>({id:n.objectId,type:"header",pasteKey:"header-2",object:n,hasCaret:n.cellItems.length>0,label:t.jsx($t,{longPressEnd:r=>{l({id:n.objectId,type:"header",pasteKey:"header-2",object:n},r)},children:`Group ${e+1}`}),isExpanded:o.indexOf(n.objectId)>-1,isSelected:n.objectId===a.objectId,secondaryLabel:t.jsx(Ae,{icon:"small-cross",onClick:()=>i(n),minimal:!0}),childNodes:n.cellItems.map(r=>{const{objectId:d,value:c}=r;return{id:r.objectId,object:r,type:"header",pasteKey:"header-3",hasCaret:!1,label:t.jsx($t,{longPressEnd:u=>
3{l({id:r.objectId,object:r,type:"header",pasteKey:"header-3"},u)},children:c||"(undefined)"}),isExpanded:o.indexOf(d)>-1,isSelected:r.objectId===a.objectId,secondaryLabel:t.jsx(Ae,{icon:"small-cross",onClick:()=>i(r),minimal:!0})}})}),Ef=(n,e,s,o,a)=>n.map(i=>{const{objectId:l,appTitle:r,cellItems:d=[]}=i;return{id:l,object:i,type:"header",pasteKey:"header-1",hasCaret:d.length>0,label:t.jsx($t,{longPressEnd:c=>{a({id:l,object:i,type:"header",pasteKey:"header-1"},c)},children:r}),isExpanded:s.indexOf(l)>-1,isSelected:l===o.objectId,secondaryLabel:t.jsx(Ae,{icon:"small-cross",onClick:()=>e(i),minimal:!0}),childNodes:d.map((c,u)=>ad(c,u,l,s,o,e,a))}}),id=(n,e,s,o,a)=>n.map(i=>{const{objectId:l,contractNote:r,additionalLines:d}=i;return{id:i.objectId,object:i,type:"signature",pasteKey:"signature-1",hasCaret:d.length>0,label:t.jsx($t,{longPressEnd:c=>{a({id:i.objectId,object:i,type:"signature",pasteKey:"signature-1"},c)},children:r}),isExpanded:s.indexOf(l)>-1,isSelected:i.objectId===o.objectId,secondaryLabel:t.jsx(Ae,{icon:"small-cross",onClick:()=>e(i),minimal:!0}),childNodes:d.map(c=>{const{objectId:u,note:p}=c;return{id:c.objectId,object:c,type:"signature",pasteKey:"signature-2",hasCaret:!1,label:t.jsx($t,{longPressEnd:h=>{a({id:c.objectId,object:c,type:"signature",pasteKey:"signature-2"},h)},children:p}),isExpanded:s.indexOf(u)>-1,isSelected:c.objectId===o.objectId,secondaryLabel:t.jsx(Ae,{icon:"small-cross",onClick:()=>e(c),minimal:!0})}})}}),Af=(n,e,s,o,a)=>{const{cellType:i}=n;switch(i){case"header":return n.header.cellItems.map((l,r)=>ad(l,r,n.objectId,e,s,o,a));case"signatures":return id(n.signatures,o,e,s,a);default:return n.detailItems.map(l=>{const{objectId:r,appTitle:d}=l;return{id:l.objectId,object:l,type:"body",pasteKey:"body-3",hasCaret:!1,label:t.jsx($t,{longPressEnd:c=>{a({id:l.objectId,object:l,type:"body",pasteKey:"body-3"},c)},children:d}),isExpanded:e.indexOf(r)>-1,isSelected:l.objectId===s.objectId,secondaryLabel:t.jsx(Ae,{icon:"small-cross",onClick:()=>o(l),minimal:!0})}})}},Ff=(n,e,s,o,a)=>n.map(i=>{const{objectId:l,appTitle:r,cellItems:d=[]}=i;return{id:l,object:i,type:"body",pasteKey:"body-1",hasCaret:d.length>0,label:t.jsx($t,{longPressEnd:c=>{a({id:l,object:i,type:"body",pasteKey:"body-1"},c)},children:r}),isExpanded:s.indexOf(l)>-1,isSelected:i.objectId===o.objectId,secondaryLabel:t.jsx(Ae,{icon:"small-cross",onClick:()=>e(i),minimal:!0}),childNodes:d.map(c=>{const u=Af(c,s,o,e,a);return{id:c.objectId,object:c,type:"body",pasteKey:"body-2",hasCaret:u.length>0,label:t.jsx($t,{longPressEnd:h=>{a({id:c.objectId,object:c,type:"body",pasteKey:"body-2",hasCaret:u.length>0},h)},children:c.appTitle}),isExpanded:s.indexOf(c.objectId)>-1,isSelected:c.objectId===o.objectId,secondaryLabel:t.jsx(Ae,{icon:"small-cross",onClick:()=>e(c),minimal:!0}),childNodes:u}})}}),Rf=(n,e,s,o,a,i)=>{switch(e){case"header":return Ef(n.data,s,o,a,i);case"body":return Ff(n.data,s,o,a,i);case"signature":return id(n.data,s,o,a,i);default:return[]}},Wl=({contractData:n},e,s,o={},a)=>n.map(i=>({id:i.objectId,object:i,type:i.groupType,pasteKey:"index",hasCaret:i.data.length>0,label:t.jsx($t,{longPressEnd:l=>{a({id:i.objectId,object:i,type:i.groupType,pasteKey:"index"},l)},children:Lf[i.groupType]}),isExpanded:s.indexOf(i.objectId)>-1,isSelected:i.objectId===o.objectId,secondaryLabel:t.jsx(Ae,{icon:"small-cross",onClick:()=>e(i),minimal:!0}),childNodes:Rf(i,i.groupType,e,s,o,a)}));class ui extends J.Component{constructor(s){super(s);W(this,"handleNodeClick",s=>{const{editCellItem:o={}}=this.props;s.object.objectId===o.objectId&&o.objectId?this.props.setEditItem(void 0):this.props.setEditItem(s.object)});W(this,"handleNodeCollapse",s=>{s.isExpanded=!1;const o=this.state.expandedIds.filter(a=>a!==s.id);this.setState({expandedIds:o})});W(this,"handleNodeExpand",s=>{s.isExpanded=!0;const o=[...this.state.expandedIds,s.id];this.setState({expandedIds:o})});W(this,"handleOnDelete",s=>{const o=this.state.expandedIds.filter(i=>s.objectId!==i);this.setState({expandedIds:o}),this.contractObject.deleteObject(s);const a=new $(this.contractObject.toJSON());this.props.setTemplateState(a)});W(this,"handleCut",s=>{this.handleCopy(s),this.handleOnDelete(s)});W(this,"handleCopy",s=>{Qa(s)});W(this,"handlePaste",(s,o)=>{const a=sn();if(s&&a){const i=s.getPath(),l=a.clone(),r=this.contractObject.getAllCellIdentifiers([]);if(l.getCellIds){const u=l.getCellIds().filter(p=>r.indexOf(p)>-1);if(u.length)return this.props.showAlertModal({level:"error",title:"Identifier Conflict",msg:`Cannot paste due to cells already existing with identifiers: ${u.join(", ")}`})}this.contractObject.insertObjectAtPath(i,l,o);const d=new $(this.contractObject.toJSON());this.props.setTemplateState(d)}});W(this,"handleOnInsert",s=>{this.contractObject.insertNewObjectAtPath(s),this.props.setTemplateState(this.contractObject)});W(this,"handleNodeContextMenu",(s,o,a)=>{a.preventDefault();const i=sn()||{};let l=s.object.pasteKey===i.pasteKey;l&&i.groupType==="body"&&(l=!this.contractObject.hasBodySection());let r=o.length<4;s.type==="signature"&&(r=o.length<3);const d=t.jsxs(xe,{className:"tree-context-menu",children:[r&&t.jsx(_,{onClick:()=>this.handleOnInsert(o),icon:t.jsx(Ct,{icon:["far","square-plus"],size:"sm"}),text:"New"}),t.jsx(_,{onClick:()=>this.handleCut(s.object),icon:t.jsx(Ct,{icon:["far","cut"],size:"sm"}),text:"Cut"}),t.jsx(_,{onClick:()=>this.handleCopy(s.object),icon:t.jsx(Ct,{icon:["far","copy"],size:"sm"}),text:"Copy"}),t.jsx(_,{onClick:()=>this.handlePaste(s.object,0),icon:t.jsx(Ct,{icon:["far","paste"],size:"sm"}),text:"Paste Above",disabled:!l}),t.jsx(_,{onClick:()=>this.handlePaste(s.object,1),icon:t.jsx(Ct,{icon:["far","paste"],size:"sm"}),text:"Paste Below",disabled:!l})]});Qr.show(d,{left:a.clientX,top:a.clientY})});
3if(s.template){this.contractObject=new $(s.template.toJSON());const o=Wl(this.contractObject,this.handleOnDelete,[],s.editCellItem,(a,i)=>{this.handleNodeContextMenu(a,a.object.getPath(),i)});this.state={nodes:o,expandedIds:[],isOpen:!1}}else this.state={nodes:[],expandedIds:[],isOpen:!1}}componentWillReceiveProps(s){if(s.template){const{editCellItem:o={}}=s,{identifier:a="",objectId:i}=o;let l=this.state.expandedIds.filter(d=>d!==i);if(a){const d=a.split("-");l=l.filter(c=>d.indexOf(c)===-1),l=[...l,...d]}this.contractObject=new $(s.template.toJSON());const r=Wl(this.contractObject,this.handleOnDelete,l,s.editCellItem,(d,c)=>{this.handleNodeContextMenu(d,d.object.getPath(),c)});this.setState({nodes:r,expandedIds:l})}}componentDidUpdate(){const{isOpen:s}=this.state;s&&this.props.pushToDataLayer({event:"contractSideDrawerEvent",eventCategory:"Documents",eventAction:"Side Drawer Open",eventLabel:"DocumentTree"})}forEachNode(s,o){s!=null&&s.forEach(a=>{o(a),this.forEachNode(a.childNodes,o)})}render(){const{isOpen:s}=this.state;return t.jsxs("div",{style:{overflow:"visible",height:"32px"},children:[t.jsx(vn,{color:"dark",icon:"chevron-right",type:"button",className:`expand-button document-tree__expand${s?"_open":"_closed"}`,onClick:()=>this.setState({isOpen:!0}),children:t.jsx("i",{className:"fas fa-arrow-right"})}),t.jsxs("div",{className:`document-tree__container${s?" slide_right":" slide_left"}`,children:[t.jsxs("div",{className:"document-tree__header",children:[t.jsx(vn,{color:"dark",icon:"chevron-left",type:"button",className:" document-tree__collapse",onClick:()=>this.setState({isOpen:!1}),variant:"plain",children:t.jsx("i",{className:"fas fa-arrow-left"})}),"Document Tree",this.state.isOpen&&t.jsx(Mf,{})]}),t.jsx("div",{className:"document-tree__body",children:this.state.isOpen&&t.jsx(mp,{contents:this.state.nodes,onNodeClick:this.handleNodeClick,onNodeCollapse:this.handleNodeCollapse,onNodeExpand:this.handleNodeExpand,onNodeContextMenu:this.handleNodeContextMenu,className:gp})})]})]})}}ui.propTypes={template:b.shape({objectId:b.string.isRequired}),setTemplateState:b.func.isRequired,setEditItem:b.func.isRequired,pasteBoardObject:b.shape({sectionType:b.oneOf(["header","body","signature"]),id:b.string,object:b.any})};ui.defaultProps={template:void 0,pasteBoardObject:void 0};const _f=({templatesEdit:n})=>({template:n[n.currentWorkingId]||new $,pasteBoardObject:n.pasteBoardObject,editCellItem:n.editCellItem}),Bf=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e)),pushToDataLayer:e=>n(Ot(e)),showWarningAlert:e=>n(Fc(e)),hideAlert:()=>n(Ka())}),$f=Z(_f,Bf)(ui),Hl=n=>{try{n({propertyName:"transform"})}catch(e){console.log("error",e)}},yt=({containerKey:n,index:e,title:s,onSelected:o,disabled:a})=>a?t.jsx(_,{text:s,disabled:a}):t.jsx(Ke,{disabled:a,draggableId:`new-${n}`,index:e,children:(i,l)=>t.jsxs("div",{onTouchEnd:()=>{Hl(i.draggableProps.onTransitionEnd)},className:l.isDragging?"cell-draw-menu-item":"",ref:i.innerRef,...i.draggableProps,...i.dragHandleProps,children:[t.jsx(_,{text:s,onTouchEnd:()=>{Hl(i.draggableProps.onTransitionEnd)},onTouchStart:()=>o(n),onMouseDown:()=>o(n),disabled:a}),i.placeholder]})});class zf extends J.PureComponent{constructor(s){super(s);W(this,"onCellSelected",s=>{this.setState({droppableType:s})});this.state={droppableType:"new",isOpen:!1}}componentDidUpdate(){const{isOpen:s}=this.state;s&&this.props.pushToDataLayer({event:"contractSideDrawerEvent",eventCategory:"Documents",eventAction:"Side Drawer Open",eventLabel:"CellToolDrawer"})}render(){const{isOpen:s}=this.state,o=this.props.templateValues&&this.props.templateValues.hasBodySection();return t.jsxs("div",{style:{overflow:"visible",height:"32px"},children:[t.jsx(vn,{color:"secondary",icon:"chevron-left",type:"button",className:`expand-button cell-tool-drawer__expand${s?"_open":"_closed"}`,onClick:()=>this.setState({isOpen:!0}),children:t.jsx("i",{className:"fas fa-arrow-left"})}),t.jsxs("div",{className:`cell-tool-drawer${s?"_slide_right":"_slide_left"}`,children:[t.jsxs("div",{className:"cell-tool-drawer__header",children:[t.jsx("div",{style:{width:"100%",display:"flex",justifyContent:"center",paddingLeft:32},children:"Cell Tool Drawer"}),t.jsx(vn,{type:"button",color:"dark",icon:"chevron-right",className:"cell-tool-drawer__collapse",onClick:()=>this.setState({isOpen:!1}),variant:"plain",children:t.jsx("i",{className:"fas fa-arrow-right"})})]}),t.jsx(We,{droppableId:"safe-no-drop",children:a=>t.jsx("div",{ref:a.innerRef,...a.droppableProps,children:t.jsx(We,{droppableId:`new-${this.state.droppableType}`,isDropDisabled:!0,children:i=>t.jsxs("div",{ref:i.innerRef,...i.droppableProps,children:[t.jsxs(xe,{children:[t.jsx(xe.Divider,{title:"Header"}),t.jsx(yt,{containerKey:"header-root",index:0,title:"Container",onSelected:this.onCellSelected}),t.jsx(yt,{containerKey:Bt.ContainerKey,index:1,title:"Section",onSelected:this.onCellSelected}),t.jsx(yt,{containerKey:dt.ContainerKey,index:2,title:"Group",onSelected:this.onCellSelected}),t.jsx(yt,{containerKey:tn.ContainerKey,index:3,title:"Line Item",onSelected:this.onCellSelected}),t.jsx(xe.Divider,{title:"Body"}),t.jsx(yt,{containerKey:"body-root",index:4,title:"Container",onSelected:this.onCellSelected,id:"body_container",disabled:o}),t.jsx(yt,{containerKey:ct.ContainerKey,index:5,title:"Section",onSelected:this.onCellSelected}),t.jsx(yt,{containerKey:X.ContainerKey,index:6,title:"Line Item",onSelected:this.onCellSelected}),t.jsx(yt,{containerKey:X.DetailContainerKey,index:7,title:"Detail Line Item",onSelected:this.onCellSelected}),this.props.editCellItem&&this.props.editCellItem.cellType==="imagePicker"&&t.jsx(yt,{containerKey:gt.ContainerKey,index:8,title:"Image Icon",onSelected:this.onCellSelected}),t.jsx(xe.Divider,{title:"Signatures"}),t.jsx(yt,{containerKey:"signature-root",index:8,title:"Container",onSelected:this.onCellSelected,id:"signature_container"}),t.jsx(yt,{containerKey:Ye.ContainerKey,index:10,title:"Capture",onSelected:this.onCellSelected}),t.jsx(yt,{containerKey:yn.ContainerKey,index:11,title:"Note",onSelected:this.onCellSelected})]}),i.placeholder]})})})})]})]})}}const Wf={},Hf=({templatesEdit:n=Wf})=>
3({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem}),qf=n=>({pushToDataLayer:e=>n(Ot(e))}),Vf=Z(Hf,qf)(zf);let ld=class extends J.Component{constructor(s){super(s);W(this,"onMouseDown",()=>{this.props.setEditItem(this.props.section)});W(this,"onDoubleClick",()=>{this.setState({showPopover:!this.state.showPopover})});W(this,"handleClickOutside",()=>{this.setState({showPopover:!1})});this.state={showPopover:!1},this.titleRef=J.createRef()}render(){const{section:s,setTemplateState:o}=this.props;return t.jsx(ot,{cellItem:s,children:t.jsxs("div",{className:"templates-app__header_cell",children:[t.jsx(Ge,{content:t.jsx("textarea",{onContextMenu:a=>a.stopPropagation(),fill:!0,ref:this.titleRef,defaultValue:s.appTitle,className:"ignore-react-onclickoutside"}),isOpen:this.state.showPopover,onClose:()=>{s.appTitle=this.titleRef.current.value;const a=s.getSourceObject();o(new $(a.toJSON()))},children:t.jsx("div",{onMouseDown:()=>this.onMouseDown(),onDoubleClick:()=>this.onDoubleClick(),children:s.appTitle})}),t.jsx("div",{className:"templates-app__cell_bottom_border"}),s.canAddMultiple&&t.jsx("i",{className:"fas fa-plus"})]})})}};ld.propTypes={setEditItem:b.func.isRequired,setTemplateState:b.func.isRequired,section:b.instanceOf(ct).isRequired};const Kf=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),Uf=Jt(ld),Gf=Z(void 0,Kf)(Uf);class pi extends J.Component{constructor(s){super(s);W(this,"onMouseDown",s=>{this.props.cellItem.editKey=s,this.props.setEditItem(this.props.cellItem)});W(this,"onDoubleClick",s=>{const o=`${s}ShowPopover`,{openPopover:a}=this.state;a!==o?this.setState({[o]:!0,[a]:!1,openPopover:o}):this.setState({[o]:!0,openPopover:o})});W(this,"handleClickOutside",()=>{this.setState({titleShowPopover:!1,valueShowPopover:!1,noteShowPopover:!1})});W(this,"valueItem",()=>{const{cellItem:s,setTemplateState:o,isSwitch:a,isCreditCard:i,isBankAccount:l}=this.props,{inputType:r,switchValueOn:d,switchValueOff:c,value:u="",inputDisabled:p}=s;if(a)return t.jsx(Aa,{name:"valueitem",checked:d===u,handleColor:"rgb(92, 183, 91)",offColor:"white",onColor:"black",onChange:g=>{s.value=g?d:c;const x=s.getSourceObject();o(new $(x.toJSON()))}});if(i)return t.jsx("div",{className:"templates-app__value templates-app__disabled",onMouseDown:()=>this.onMouseDown("value"),onDoubleClick:()=>this.onDoubleClick("value"),children:"####-####-####-9999"});if(l)return t.jsx("div",{className:"templates-app__value templates-app__disabled",onMouseDown:()=>this.onMouseDown("value"),onDoubleClick:()=>this.onDoubleClick("value"),children:"1234567890"});const h=r==="formula"||r==="formulaWhole"||r==="textFormula"||r==="formulaCurrency"||r==="formulaCurrencyWhole"||r==="creditCard"||r==="ccExpDate"||p;return t.jsx(Ge,{content:t.jsx("textarea",{onContextMenu:g=>g.stopPropagation(),fill:!0,ref:this.valueRef,defaultValue:u,className:"ignore-react-onclickoutside"}),isOpen:this.state.valueShowPopover,onClose:()=>{s.value=this.valueRef.current.value;const g=s.getSourceObject();o(new $(g.toJSON()))},children:t.jsx("div",{className:`templates-app__value${h?" templates-app__disabled":""}`,onMouseDown:()=>this.onMouseDown("value"),onDoubleClick:()=>this.onDoubleClick("value"),children:u.split(`
4`).map((g,x,m)=>x<m.length-1?t.jsx("p",{style:{margin:0,minHeight:"20px"},children:g},`${s.objectId}-${x}`):g)})})});this.state={titleShowPopover:!1,valueShowPopover:!1,noteShowPopover:!1},this.titleRef=J.createRef(),this.valueRef=J.createRef(),this.noteRef=J.createRef()}shouldComponentUpdate(s){return!this.props.cellItem.isEqualTo(s.cellItem)}render(){const{cellItem:s,setTemplateState:o,isParagraph:a}=this.props,{required:i}=s,l=(s.appTitle||"").split(`
5`)[0];return t.jsx(ot,{cellItem:s,children:t.jsxs("div",{className:`templates-app__text_cell${a?"_paragraph":""}`,children:[t.jsxs("div",{className:"templates-app__stacked",children:[t.jsx(Ge,{className:`templates-app__title${i?"_required":""}`,content:t.jsx(fe,{onContextMenu:r=>r.stopPropagation(),fill:!0,inputRef:this.titleRef,defaultValue:s.appTitle,className:"ignore-react-onclickoutside"}),isOpen:this.state.titleShowPopover,onClose:()=>{if(s.appTitle!==this.titleRef.current.value){s.appTitle=this.titleRef.current.value;const r=s.getSourceObject();o(new $(r.toJSON()))}},children:t.jsx("div",{className:"templates-app__line-text",onMouseDown:()=>this.onMouseDown("title"),onDoubleClick:()=>this.onDoubleClick("title"),children:l})}),s.appNote&&t.jsx(Ge,{className:"templates-app__note",content:t.jsx(fe,{onContextMenu:r=>r.stopPropagation(),fill:!0,inputRef:this.noteRef,defaultValue:s.appNote,className:"ignore-react-onclickoutside"}),isOpen:this.state.noteShowPopover,onClose:()=>{if(s.appNote!==this.noteRef.current.value){s.appNote=this.noteRef.current.value;const r=s.getSourceObject();o(new $(r.toJSON()))}},children:t.jsx("div",{onMouseDown:()=>this.onMouseDown("note"),onDoubleClick:()=>this.onDoubleClick("note"),children:s.appNote})})]}),this.valueItem(),t.jsx("div",{className:"templates-app__cell_bottom_border"})]})})}}pi.propTypes={cellItem:b.instanceOf(X).isRequired,setTemplateState:b.func.isRequired,setEditItem:b.func.isRequired,isParagraph:b.bool,isSwitch:b.bool,isCreditCard:b.bool,isBankAccount:b.bool};pi.defaultProps={isParagraph:!1,isSwitch:!1,isCreditCard:!1,isBankAccount:!1};const Jf=({templatesEdit:n})=>({template:n[n.currentWorkingId]}),Yf=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),Xf=Jt(pi),us=Z(Jf,Yf)(Xf);class hi extends J.Component{constructor(s){super(s);W(this,"onMouseDown",s=>{this.props.cellItem.editKey=s,this.props.setEditItem(this.props.cellItem)});
5W(this,"onDoubleClick",s=>{const o=`${s}ShowPopover`,{openPopover:a}=this.state;a!==o?this.setState({[o]:!0,[a]:!1,openPopover:o}):this.setState({[o]:!0,openPopover:o})});W(this,"handleClickOutside",()=>{this.setState({titleShowPopover:!1,valueShowPopover:!1})});this.state={titleShowPopover:!1,valueShowPopover:!1},this.titleRef=J.createRef(),this.valueRef=J.createRef()}shouldComponentUpdate(s){return!this.props.cellItem.isEqualTo(s.cellItem)}render(){const{cellItem:s,setTemplateState:o}=this.props,{required:a,inputType:i,inputDisabled:l}=s,r=i==="formula"||i==="formulaWhole"||i==="textFormula"||i==="formulaCurrency"||i==="formulaCurrencyWhole"||l,d=`templates-app__detail_title${a?"_required":""}`,c=`templates-app__detail_value${r?" templates-app__disabled":""}`;return t.jsxs("div",{className:"templates-app__detail_text_cell",children:[t.jsx(Ge,{className:d,content:t.jsx("textarea",{onContextMenu:u=>u.stopPropagation(),fill:!0,ref:this.titleRef,defaultValue:s.appTitle,className:"ignore-react-onclickoutside"}),isOpen:this.state.titleShowPopover,onClose:()=>{s.appTitle=this.titleRef.current.value;const u=s.getSourceObject();o(new $(u.toJSON()))},children:t.jsx("div",{onMouseDown:()=>this.onMouseDown("title"),onDoubleClick:()=>this.onDoubleClick("title"),children:s.appTitle})}),t.jsx(Ge,{className:c,content:t.jsx(fe,{onContextMenu:u=>u.stopPropagation(),fill:!0,inputRef:this.valueRef,defaultValue:s.value,className:"ignore-react-onclickoutside"}),isOpen:this.state.valueShowPopover,onClose:()=>{s.value=this.valueRef.current.value;const u=s.getSourceObject();o(new $(u.toJSON()))},children:t.jsx("div",{onMouseDown:()=>this.onMouseDown("value"),onDoubleClick:()=>this.onDoubleClick("value"),children:s.value})})]})}}hi.propTypes={cellItem:b.instanceOf(X).isRequired,setTemplateState:b.func.isRequired,setEditItem:b.func.isRequired};hi.defaultProps={};const Zf=({templatesEdit:n})=>({template:n[n.currentWorkingId]}),Qf=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),eb=Jt(hi),ql=Z(Zf,Qf)(eb);class tb extends J.Component{constructor(s){super(s);W(this,"onMouseDown",s=>{this.props.cellItem.editKey=s,this.props.setEditItem(this.props.cellItem)});W(this,"onDoubleClick",s=>{const o=`${s}ShowPopover`,{openPopover:a}=this.state;a!==o?this.setState({[o]:!0,[a]:!1,openPopover:o}):this.setState({[o]:!0,openPopover:o})});W(this,"handleClickOutside",()=>{this.setState({titleShowPopover:!1,valueShowPopover:!1})});this.state={titleShowPopover:!1,valueShowPopover:!1},this.titleRef=J.createRef(),this.valueRef=J.createRef()}shouldComponentUpdate(s){return!this.props.cellItem.isEqualTo(s.cellItem)}render(){const{cellItem:s,setTemplateState:o}=this.props,{required:a,appTitle:i,value:l,inputDisabled:r,inputType:d}=s,c=d==="formula"||d==="formulaWhole"||d==="textFormula"||d==="formulaCurrency"||d==="formulaCurrencyWhole"||r;return t.jsxs("div",{className:"templates-app__stacked",children:[t.jsx(Ge,{className:`templates-app__detail_title${a?"_required":""}`,content:t.jsx("textarea",{onContextMenu:u=>u.stopPropagation(),fill:!0,ref:this.titleRef,defaultValue:i,className:"ignore-react-onclickoutside"}),isOpen:this.state.titleShowPopover,onClose:()=>{s.appTitle=this.titleRef.current.value;const u=s.getSourceObject();o(new $(u.toJSON()))},children:t.jsx("div",{style:{width:"100%"},onMouseDown:()=>this.onMouseDown("title"),onDoubleClick:()=>this.onDoubleClick("title"),children:i})}),t.jsx(Ge,{className:`templates-app__value${c?" templates-app__disabled":""}`,content:t.jsx(fe,{onContextMenu:u=>u.stopPropagation(),fill:!0,inputRef:this.valueRef,defaultValue:l,className:"ignore-react-onclickoutside"}),isOpen:this.state.valueShowPopover,onClose:()=>{s.value=this.valueRef.current.value;const u=s.getSourceObject();o(new $(u.toJSON()))},children:t.jsx("div",{style:{width:"100%"},onMouseDown:()=>this.onMouseDown("value"),onDoubleClick:()=>this.onDoubleClick("value"),children:l})})]})}}const nb=({templatesEdit:n})=>({template:n[n.currentWorkingId]}),sb=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),ob=Jt(tb),ab=Z(nb,sb)(ob);class mi extends J.Component{constructor(s){super(s);W(this,"onMouseDown",()=>{this.props.cellItem.editKey="title",this.props.setEditItem(this.props.cellItem)});W(this,"onContainerDoubleClick",()=>{this.props.onDoubleClick(this.props.cellItem)});
5W(this,"onDoubleClick",s=>{const o=`showPopover${s}`;this.setState({[o]:!0})});W(this,"handleClickOutside",()=>{this.setState({showPopoverTitle:!1,showPopoverNote:!1})});this.state={showPopoverTitle:!1,showPopoverNote:!1},this.titleRef=J.createRef(),this.noteRef=J.createRef()}render(){const{cellItem:s,editCellItem:o,setTemplateState:a,templateValues:i,draggableType:l,setEditItem:r}=this.props,d=new $(i.toJSON()),c=d.getObjectWithId(s.objectId)||{},{imageHeight:u,detailItems:p}=c,h=p.filter(({appOnly:v})=>v!==!0),g=h.filter(({cellType:v})=>v==="textXLong"),x=h.filter(({cellType:v})=>v!=="textXLong"),m=x.filter((v,I)=>I%2===0),f=x.filter((v,I)=>I%2>0),j=p.find(({cellType:v})=>v==="imagePicker"),S=`${[...s.getPath(),0].join("-")}-${s.objectId}-app-${X.DetailContainerKey}`,w=`${[...s.getPath(),1].join("-")}-${s.objectId}-app-${X.DetailContainerKey}`,C=`${[...s.getPath(),m.length+f.length-1].join("-")}-${s.objectId}-app-${X.DetailContainerKey}`;return Jn(S,s,a,r),Jn(w,s,a,r),Jn(C,s,a,r),t.jsxs("div",{className:"templates-app__detail_cell",onDoubleClick:this.onContainerDoubleClick,children:[t.jsxs("div",{className:"templates-app__stacked",children:[t.jsx(Ge,{content:t.jsx("textarea",{onContextMenu:v=>v.stopPropagation(),fill:!0,ref:this.titleRef,defaultValue:c.appTitle,className:"ignore-react-onclickoutside"}),isOpen:this.state.showPopoverTitle,onClose:()=>{c.appTitle=this.titleRef.current.value,a(d)},children:t.jsx("div",{className:`templates-app__title${s.required?"_required":""}`,onMouseDown:()=>this.onMouseDown(),onDoubleClick:()=>this.onDoubleClick("title"),children:c.appTitle})}),c.appNote&&t.jsx(Ge,{className:"templates-app__note",content:t.jsx(fe,{onContextMenu:v=>v.stopPropagation(),fill:!0,inputRef:this.noteRef,defaultValue:c.appNote,className:"ignore-react-onclickoutside"}),isOpen:this.state.showPopoverNote,onClose:()=>{c.appNote=this.noteRef.current.value,a(new $(d.toJSON()))},children:t.jsx("div",{onMouseDown:()=>this.onMouseDown(),onDoubleClick:()=>this.onDoubleClick("note"),children:c.appNote})})]}),t.jsxs("div",{style:{display:"flex"},children:[j&&u>0&&t.jsx("div",{style:{paddingLeft:"3px",paddingTop:"3px",paddingBottom:"3px",height:`${u}px`,maxHeight:`${u}px`,width:`${u}px`,maxWidth:`${u}px`},onClick:()=>this.onMouseDown(),children:t.jsx("img",{src:"/images/no_image.png",style:{objectFit:"contain",maxWidth:"100%",maxHeight:"100%"},alt:"thumbnail"})}),t.jsx(We,{droppableId:S,isDropDisabled:l!==X.DetailContainerKey,children:(v,I)=>t.jsxs("div",{style:{...tt(I.isDraggingOver),width:"50%"},ref:v.innerRef,...v.droppableProps,children:[m.map((D,F)=>t.jsx(Ke,{draggableId:`${D.getPath().join("-")}-app-${D.objectId}`,index:F,children:(M,R)=>t.jsxs("div",{ref:M.innerRef,...M.draggableProps,...M.dragHandleProps,style:rt(R,M.draggableProps.style,D.objectId===o.objectId),children:[t.jsx(ql,{cellItem:D}),M.placeholder]},D.objectId)},D.objectId)),v.placeholder]})}),t.jsx(We,{droppableId:w,isDropDisabled:l!==X.DetailContainerKey,children:(v,I)=>t.jsxs("div",{style:{...tt(I.isDraggingOver),width:"50%"},ref:v.innerRef,...v.droppableProps,children:[f.map((D,F)=>t.jsx(Ke,{draggableId:`${D.getPath().join("-")}-app-${D.objectId}`,index:F,children:(M,R)=>t.jsxs("div",{ref:M.innerRef,...M.draggableProps,...M.dragHandleProps,style:rt(R,M.draggableProps.style,D.objectId===o.objectId),children:[t.jsx(ql,{cellItem:D}),M.placeholder]},D.objectId)},D.objectId)),v.placeholder]})})]}),t.jsx(We,{droppableId:C,isDropDisabled:l!==X.DetailContainerKey,children:(v,I)=>t.jsxs("div",{style:tt(I.isDraggingOver),ref:v.innerRef,...v.droppableProps,children:[g.map((D,F)=>t.jsx(Ke,{draggableId:`${D.getPath().join("-")}-app-${D.objectId}`,index:F,children:(M,R)=>t.jsx("div",{ref:M.innerRef,...M.draggableProps,...M.dragHandleProps,style:rt(R,M.draggableProps.style,D.objectId===o.objectId),children:t.jsx(ab,{cellItem:D})},D.objectId)},D.objectId)),v.placeholder]})}),t.jsx("div",{className:"templates-app__cell_bottom_border"})]})}}mi.propTypes={editCellItem:b.any,cellItem:b.instanceOf(X).isRequired,setTemplateState:b.func.isRequired,templateValues:b.shape({}).isRequired,setEditItem:b.func.isRequired,draggableType:b.string,onDoubleClick:b.func.isRequired};mi.defaultProps={editCellItem:{},draggableType:void 0};const ib=({templatesEdit:n})=>
5({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,draggableType:n.draggableType}),lb=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),rb=Jt(mi),cb=Z(ib,lb)(rb),rd=({cellItem:n,setEditItem:e})=>t.jsx(ot,{cellItem:n,children:t.jsxs("div",{className:"templates-app__photo_selector_cell",onClick:()=>e(n),children:[t.jsx("img",{src:"/images/no_image.png",className:"templates-app__photo_selector_cell_image",alt:"phoo selector"}),"Add New",t.jsx("div",{className:"templates-app__cell_bottom_border"})]})});rd.propTypes={cellItem:b.instanceOf(X).isRequired,setEditItem:b.func.isRequired};const db=n=>({setEditItem:e=>n(Ne(e))}),ub=Z(void 0,db)(rd),cd=({cellItem:n,template:e,setInitialStateForTemplate:s,setEditItem:o})=>{const{pageSize:a}=e,[i]=a.split(","),l=768/parseInt(i,10),r=n.imageHeight*l;let d="";return n.drawingBackgroundImage&&(n.drawingBackgroundImage.url&&(d=n.drawingBackgroundImage.url),n.drawingBackgroundImage._url&&(d=n.drawingBackgroundImage._url)),t.jsx(ot,{cellItem:n,children:t.jsxs("div",{className:"templates-app__drawing_cell",style:{height:`${r}px`},onClick:()=>{o(n)},children:[t.jsx("div",{className:`"drawing-text-container templates-app__title${n.required?"_required":""}`,children:n.appTitle}),t.jsx("div",{className:"drawing-img-container",children:t.jsx("img",{className:"drawing-background-img",src:d})}),t.jsx(Ea,{onDrop:async c=>{try{const u=await as(c[0],"document","drawingBackgroundImage");n.drawingBackgroundImage=u;const p=n.getSourceObject();s(new $(p.toJSON()))}catch(u){Be.show({message:u.message,timeout:5e3})}},accept:"image/*",children:({getRootProps:c,getInputProps:u,isDragActive:p})=>t.jsxs("div",{className:"drawing-background-input-containter",children:[t.jsx("input",{...u()}),t.jsx(we,{...c(),variant:"contained",color:"primary",children:"Drop Background Image Here..."})]})}),t.jsx("div",{className:"templates-app__cell_bottom_border"})]})})};cd.propTypes={setInitialStateForTemplate:b.func.isRequired,cellItem:b.instanceOf(X).isRequired,template:b.instanceOf($).isRequired};const pb=({templatesEdit:n})=>({template:n[n.currentWorkingId]}),hb=n=>({setInitialStateForTemplate:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),mb=Z(pb,hb)(cd),gb=n=>{const e=new se.Query("SSMeasureSheetItem");return e.select(["subCategory","itemName","measurementType","items.subCategory2","items.displayTitle"]),e.equalTo("objectId",n),e.first()};class dd extends J.Component{constructor(s){super(s);W(this,"onClick",()=>{this.props.setEditItem(this.props.cellItem)});W(this,"cellStyleForCell",(s,o)=>({minWidth:`${s}%`,maxWidth:`${s}%`,textAlign:o||void 0}));W(this,"loadMeasureSheetItemData",async()=>{try{const s=await gb(this.props.cellItem.linkedMeasureSheetItem);if(this.linkedMeasureSheetItemId=this.props.cellItem.linkedMeasureSheetItem,!s)throw new se.Error(500,"Could not find item");let o=s.get("itemName");s.get("subCategory")&&(o=`${s.get("subCategory")} - ${o}`);const i=(s.get("items")||[])[0];let l;i&&(i.get("subCategory2")?l=`${i.get("subCategory2")} - ${i.get("displayTitle")}`:l=i.get("displayTitle")),this.setState({title:o,subtitle:l,measurementType:s.get("measurementType"),quantity:"99",unitTotal:"$100.00",total:"$999.00"})}catch(s){this.setState({title:"Error loading item",subtitle:s.message,measurementType:"",quantity:"",unitTotal:"",total:""})}});this.state={title:"Loading...",subtitle:"",measurementType:"",quantity:"",unitTotal:"",total:""},this.linkedMeasureSheetItemId=s.cellItem.linkedMeasureSheetItem}componentWillMount(){this.loadMeasureSheetItemData()}shouldComponentUpdate(s){return!this.props.cellItem.isEqualTo(s.cellItem)}componentDidUpdate(){this.props.cellItem.linkedMeasureSheetItem!==this.linkedMeasureSheetItemId&&this.loadMeasureSheetItemData()}render(){const{cellItem:s}=this.props,{linkedMeasureSheetItemConfig:o={}}=s,{measurementType:a=!1,quantity:i=!1,subtitle:l=!1,title:r=!1,total:d=!1,unitTotal:c=!1}=o,{title:u,subtitle:p,measurementType:h,quantity:g,unitTotal:x,total:m}=this.state;return t.jsx(ot,{cellItem:s,children:t.jsxs("div",{className:"templates-app__measure_sheet_detail",onClick:this.onClick,children:[t.jsx("div",{style:this.cellStyleForCell(100/2/2),children:r?u:""}),t.jsx("div",{style:this.cellStyleForCell(100/2/2),children:l?p:""}),t.jsx("div",{style:this.cellStyleForCell(100/2/16*3,"right"),children:i?g:""}),t.jsx("div",{style:this.cellStyleForCell(100/2/16*6,"right"),children:a?h:""}),t.jsx("div",{style:this.cellStyleForCell(100/2/16*3,"right"),children:c?x:""}),t.jsx("div",{style:this.cellStyleForCell(100/2/16*4,"right"),children:d?m:""}),t.jsx("div",{className:"templates-app__cell_bottom_border"})]})})}}dd.propTypes={cellItem:b.instanceOf(X).isRequired,setEditItem:b.func.isRequired};const xb=({templatesEdit:n})=>({template:n[n.currentWorkingId]}),fb=n=>({setEditItem:e=>n(Ne(e)),setTemplateState:e=>n(ee(e))}),bb=Z(xb,fb)(dd),ud=({cellItem:n,setEditItem:e})=>
5t.jsx(ot,{cellItem:n,children:t.jsxs("div",{className:"templates-app__text_cell",onClick:()=>e(n),children:[t.jsx("span",{className:`templates-app__title${n.required?"_required":""}`,children:n.appTitle}),t.jsx("i",{style:{color:"lightgray"},className:"fas fa-chevron-right"}),t.jsx("div",{className:"templates-app__cell_bottom_border"})]})});ud.propTypes={cellItem:b.instanceOf(X).isRequired,setEditItem:b.func.isRequired};const yb=n=>({setEditItem:e=>n(Ne(e))}),jb=Z(void 0,yb)(ud);class gi extends J.Component{constructor(s){super(s);W(this,"onDoubleClick",()=>{this.setState({showPopover:!0})});W(this,"updateThumnail",async s=>{const o=await Og(s);this.props.imageObject.file=o,this.props.onChange(this.props.imageObject)});this.titleRef=J.createRef(),this.valueRef=J.createRef(),this.defaultRef=J.createRef(),this.state={showPopover:!1}}render(){const{title:s,value:o,file:a,id:i}=this.props.imageObject;let l=a?a.url:"/images/no_image.png";return a instanceof se.File&&(l=a.url()),t.jsx(Ge,{content:t.jsxs("div",{style:{padding:8},children:[t.jsx(Go,{label:"Title",labelFor:"title-input",children:t.jsx(nl,{id:"title-input",inputRef:this.titleRef,defaultValue:s})}),t.jsx(Go,{label:"Value",labelFor:"value-input",children:t.jsx(nl,{id:"value-input",inputRef:this.valueRef,defaultValue:o})}),t.jsx(Go,{label:"Image",labelFor:"file-input",children:t.jsx(fp,{text:"Image",inputProps:{id:"file-input",accept:"image/*"},onInputChange:this.updateThumnail})}),t.jsx(Aa,{defaultChecked:this.props.isDefault,label:"Make Default",inputRef:this.defaultRef,onChange:r=>{this.props.onDefaultChanged(i,r.target.checked)}}),t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>this.props.onDelete({}),children:[" ","delete"," "]})]}),isOpen:this.state.showPopover,onClose:()=>{this.setState({showPopover:!1}),this.props.imageObject.title=this.titleRef.current.value,this.props.imageObject.value=this.valueRef.current.value,this.props.onChange(this.props.imageObject)},children:t.jsxs("div",{onContextMenu:r=>r.stopPropagation(),className:`templates-app__image_selector_tile${this.props.isDefault?"_default":""}`,onDoubleClick:this.onDoubleClick,children:[t.jsx("img",{onContextMenu:r=>r.stopPropagation(),src:l||"/images/no_image.png",className:"templates-app__image_selector_image",alt:"template selector"}),t.jsx(xp.Textfit,{mode:"single",max:17,children:t.jsx("div",{className:"templates-app__image_selector_label",children:o})})]})})}}gi.propTypes={imageObject:b.instanceOf(gt).isRequired,isDefault:b.bool,onChange:b.func.isRequired,onDefaultChanged:b.func.isRequired};gi.defaultProps={isDefault:!1};const xi=({cellItem:n,setTemplateState:e,contractObject:s,draggableType:o,setEditItem:a})=>{let{images:i,imagesSource:l}=n;l==="default"&&(i=s.images);const r=`${n.objectId}-${gt.ContainerKey}`;return bt(r,async d=>{const c={},u=await se.Config.get();if(u&&u.attributes&&u.attributes.defaultPickerImage){const h=u.attributes.defaultPickerImage;c.file=h}const p=new $(s.toJSON());if(l==="default"){let h;d.draggableId==="new-image_object"?h=new gt(c):(h=p.images[d.source.index],p.images.splice(d.source.index,1)),p.images.splice(d.destination.index,0,h),h.parent=p,e(p),a(n)}else{const[h]=d.destination.droppableId.split("-"),g=p.getObjectWithId(h);let x;if(d.draggableId==="new-image_object")x=new gt(c),a(g);else{const[m]=d.source.droppableId.split("-"),f=p.getObjectWithId(m);x=f.images[d.source.index],f.images.splice(d.source.index,1)}g.images.splice(d.destination.index,0,x),x.parent=g,e(p)}}),t.jsx(ot,{cellItem:n,children:t.jsxs("div",{className:"templates-app__image_selector_container",onClick:()=>a(n),children:[t.jsx(We,{droppableId:r,direction:"horizontal",isDropDisabled:o!==gt.ContainerKey,children:(d,c)=>t.jsxs("div",{ref:d.innerRef,...d.droppableProps,className:"templates-app__image_selector_scroll-view",children:[i.map((u,p)=>t.jsx(Ke,{draggableId:u.id,index:p,children:(h,g)=>t.jsxs("div",{ref:h.innerRef,...h.draggableProps,...h.dragHandleProps,children:[t.jsx(gi,{imageObject:u,isDefault:u.id===n.defaultImageId,onDelete:x=>{if(l!=="default"){n.images=n.images.filter((f,j)=>j!==p);const m=n.getSourceObject();e(new $(m.toJSON()))}else{const m=new $(s.toJSON());m.images=s.images.filter((f,j)=>j!==p),e(new $(m.toJSON()))}},onChange:x=>{const m=n.getSourceObject();e(new $(m.toJSON()))},onDefaultChanged:(x,m)=>{m?n.defaultImageId=x:delete n.defaultImageId,e(new $(s.toJSON()))}}),h.placeholder]})},u.id)),d.placeholder]})}),t.jsx("div",{className:"templates-app__cell_bottom_border"})]})})};xi.propTypes={contractObject:b.instanceOf($).isRequired,cellItem:b.instanceOf(X).isRequired,setTemplateState:b.func.isRequired,draggableType:b.string};xi.defaultProps={draggableType:void 0};const Cb=({templatesEdit:n})=>({contractObject:n[n.currentWorkingId],draggableType:n.draggableType}),Ib=n=>({setTemplateState:e=>n(ee(e)),setEditItem:e=>n(Ne(e))}),Sb=Z(Cb,Ib)(xi),vb=({cellItem:n,isOpen:e,setTemplateState:s,setEditCellItem:o,draggableType:a})=>{const i=`templates-app__content_more${e?"_offset":""}`;if(!e)return t.jsx("div",{className:i});const l=`${n.objectId}-app-${X.DetailContainerKey}`;return bt(l,r=>{const{source:d,destination:c}=r;if(d.droppableId===`new-${X.DetailContainerKey}`){const h=new X;n.detailItems.splice(c.index,0,h),h.parent=n,o(h)}else{const h=n.detailItems[d.index];n.detailItems.splice(d.index,1),n.detailItems.splice(c.index,0,h),h.parent=n}const u=n.getSourceObject(),p=new $(u.toJSON());s(p)}),t.jsx("div",{className:i,children:t.jsx(We,{droppableId:l,isDropDisabled:a!==X.DetailContainerKey,children:(r,d)=>t.jsxs("div",{ref:r.innerRef,...r.droppableProps,children:[n.detailItems.map((c,u)=>hd(c)?null:t.jsx(Ke,{draggableId:`${c.getPath().join("-")}-app_${c.objectId}`,index:u,children:(p,h)=>t.jsxs("div",{ref:p.innerRef,...p.draggableProps,...p.dragHandleProps,children:[pd(c),p.placeholder]})},`app_${c.objectId}`)),r.placeholder]})},`app_${n.objectId}`)})},Tb=({templatesEdit:n})=>({draggableType:n.draggableType}),wb=n=>({setTemplateState:e=>n(ee(e)),setEditCellItem:e=>n(Ne(e))}),kb=Z(Tb,wb)(vb),pd=(n,e)=>{switch(n.cellType){case"textShort":case"textLong":return t.jsx(us,{cellItem:n});case"textXLong":return t.jsx(us,{cellItem:n,isParagraph:!0});case"switched":return t.jsx(us,{cellItem:n,isSwitch:!0});
5case"securePaymentCaptureAll":case"creditCardCell":return t.jsx(us,{cellItem:n,isCreditCard:!0});case"bankAccountCell":return t.jsx(us,{cellItem:n,isBankAccount:!0});case"detailCell":return t.jsx(cb,{cellItem:n,onDoubleClick:e});case"photoPickerCell":return t.jsx(ub,{cellItem:n});case"drawing":return t.jsx(mb,{cellItem:n});case"measureSheetItemDetail":return t.jsx(bb,{cellItem:n});case"provia":return t.jsx(jb,{cellItem:n});case"imagePicker":return t.jsx(Sb,{cellItem:n});default:return t.jsx("h5",{children:n.cellType})}},hd=n=>{if(n.hidden)return!0;switch(n.cellType){case"textOnly":case"emptySpace":case"header":case"signatures":return!0;default:return!1}};class fi extends J.Component{constructor(s){super(s);W(this,"onDoubleClick",s=>{this.setState({selectedDetailCell:s.objectId})});W(this,"onBackClicked",()=>{this.setState({selectedDetailCell:void 0})});this.state={selectedDetailCell:void 0}}render(){const{contractObject:s,draggableType:o,setTemplateState:a,setEditCellItem:i}=this.props,{contractData:l=[]}=s||{},r=l.find(({groupType:c})=>c==="body")||{},{data:d=[]}=r;return t.jsxs("div",{className:"templates-app__container",children:[t.jsxs("div",{className:"templates-app__navbar",children:[t.jsx("button",{type:"button",onClick:this.onBackClicked,className:"templates-app__navbar-back-button",disabled:!this.state.selectedDetailCell,children:t.jsxs("span",{children:[t.jsx("i",{className:"fas fa-chevron-left",style:{marginRight:"5px"}}),"Back"]})}),s==null?void 0:s.displayName]}),t.jsxs("div",{style:{display:"flex"},children:[t.jsx("div",{className:`templates-app__content${this.state.selectedDetailCell?"_offset":""}`,children:d.map(c=>{const{cellItems:u=[],userInputRequired:p}=c;if(!p)return null;const h=`${c.objectId}-app-${X.ContainerKey}`;return td(h,c,a,i),t.jsx(We,{droppableId:h,isDropDisabled:o!==X.ContainerKey,children:(g,x)=>t.jsxs("div",{ref:g.innerRef,...g.droppableProps,children:[t.jsx(Gf,{section:c}),u.map((m,f)=>hd(m)?null:t.jsx(Ke,{draggableId:`${m.getPath().join("-")}-app_${m.objectId}`,index:f,children:(j,S)=>t.jsxs("div",{ref:j.innerRef,...j.draggableProps,...j.dragHandleProps,children:[t.jsx("div",{style:{boxShadow:this.props.editCellItem&&m.objectId===this.props.editCellItem.objectId?" -5px 5px 5px darkgrey, 5px 5px 5px darkgrey":void 0,margin:this.props.editCellItem&&m.objectId===this.props.editCellItem.objectId?7:0},children:pd(m,this.onDoubleClick)}),j.placeholder]})},`app_${m.objectId}`)),g.placeholder]})},`app_${c.objectId}`)})}),t.jsx(kb,{cellItem:s==null?void 0:s.getObjectWithId(this.state.selectedDetailCell),isOpen:!!this.state.selectedDetailCell})]})]})}}fi.propTypes={contractObject:b.instanceOf($),draggableType:b.string,setTemplateState:b.func.isRequired,setEditCellItem:b.func.isRequired};fi.defaultProps={draggableType:void 0};const Pb=({templatesEdit:n})=>({contractObject:n[n.currentWorkingId],editCellItem:n.editCellItem,draggableType:n.draggableType}),Db=n=>({setTemplateState:e=>n(ee(e)),setEditCellItem:e=>n(Ne(e))}),ja=Z(Pb,Db)(fi),md=(n=[],e)=>{if(!(e!=null&&e.length))return n;const s=new Set(e.map(o=>o.id));return n.filter(o=>s.has(o.id))},Vl=[{code:"US",key:"statesUS",label:"United States"},{code:"CA",key:"statesCA",label:"Canada"}],gd=(n=[])=>Array.from(new Set(n.map(e=>e.get("country")||"US"))),xd=(n,e)=>{const s=n.includes("CA"),o=n.some(d=>d!=="CA"),a=Vl.filter(d=>d.code==="CA"?s:o),i=a.length?a:[Vl[0]],l=i.length>1,r=[];return i.forEach(d=>{(e(d.key)||[]).forEach(c=>{r.push({value:c,label:c,...l?{group:d.label}:{}})})}),r},Ob=(n,e)=>({type:"TEMPLATES_SET_TEMPLATES",templateType:n,templates:e}),fd=async(n,e)=>{var g;const{auth:s,templates:o}=e,a=o[n]||{},{offices:i=[]}=s,{includedStatesFilter:l=[],page:r=1,limit:d=10}=a,{auth:{offices:c},plan:u={}}=e;let{includedOfficesFilter:p=[]}=a;u.maxOfficeCount===1&&(p=[c[0].id]);const h=new se.Query("ContractObject");if(h.equalTo("type",n),h.notEqualTo("isTemplate",!0),h.ascending("order"),h.limit(d),h.skip(d*(r-1)),p.length){const x=p.map(m=>{const f=new se.Object("Office");return f.id=m,f});h.containedIn("includedOffices",x)}else h.notContainedIn("includedOffices",i);if(l.length)h.containedIn("includedStates",l);else{const x=await se.Config.get(),m=S=>x.attributes[S]||[],f=md(s.offices,(g=s.user)==null?void 0:g.get("allowedOffices")),j=s.officeLevelCountry?xd(gd(f),m).map(S=>S.value):m(s.company.get("statesKey"));h.notContainedIn("includedStates",j)}return h},Nb=(n,e)=>({type:"TEMPLATES_SET_COUNT",templateType:n,count:e}),bi=n=>async(e,s)=>{try{const a=await(await fd(n,s())).count();e(Nb(n,a))}catch(o){e(Kt(o))}},bd=n=>async(e,s)=>{try{const o=await fd(n,s());
5o.select(["displayName","iconImage","iconBackgroundColor","order","type"]);const a=await o.find();e(Ob(n,a))}catch(o){e(Kt(o))}},Mb=(n,e)=>({type:"TEMPLATES_SET_INCLUDED_OFFICES_FILTER",templateType:n,includedOfficesFilter:e}),Lb=(n,e)=>async s=>{try{await s(Mb(n,e)),s(bi(n)),s(bd(n))}catch(o){s(Kt(o))}},Eb=(n,e)=>({type:"TEMPLATES_SET_INCLUDED_STATES_FILTER",templateType:n,includedStatesFilter:e}),Ab=(n,e)=>async s=>{try{await s(Eb(n,e)),s(bi(n)),s(bd(n))}catch(o){s(Kt(o))}},Fb={customCreditApplicationsAllowed:!1,customMainMenuOptionsAllowed:!0,customPermissionGroupsAllowed:!0,docuSignEnabled:!0,attachmentsAsLinksRequired:!1,groupMeEnabled:!0,hoverEnabled:!0,isDefault:!0,jobNimbusEnabled:!0,leadPerfectionEnabled:!0,logsAllowed:!0,mainMenuLabelOverrides:{estimates:{title:"ESTIMATES",enabled:!0,locked:!1},contracts:{title:"CONTRACTS",enabled:!0,locked:!1},proposals:{title:"PROPOSALS",enabled:!0,locked:!1},financeCalculator:{title:"FINANCE CALCULATOR",enabled:!0,locked:!1},priceGuide:{title:"PRICE GUIDE",enabled:!0,locked:!1},availableManagers:{title:"AVAILABLE CONTACTS",enabled:!0,locked:!1},pitchBooks:{title:"RESOURCES",enabled:!0,locked:!1},settings:{title:"SETTINGS",enabled:!0,locked:!1},creditApplication:{title:"CREDIT APPLICATION",enabled:!0,locked:!1}},marketsharpEnabled:!0,maxAdditionalDetailsPerItemCount:-1,maxCategoryCount:-1,maxCommissionFormulasCount:-1,maxContractTemplateCount:-1,maxCustomTemplateCount:-1,maxEmailRecipientCount:-1,maxFinanceOptionCount:-1,maxMeasureSheetItemCount:-1,maxOfficeCount:-1,maxOptionCount:-1,maxOptionsPerItem:-1,maxPackageCount:-1,maxPriceFormulasCount:-1,maxProposalTemplateCount:-1,maxTemplateCount:-1,maxUpChargeCount:-1,maxUpChargesPerItem:-1,partnerCreditApplicationSourcesAllowed:["enerBank","dividend","amerifirst","foundation","fortiva","green_sky","service_finance"],paymentCaptureEnabled:!0,paymentGatewaysAllowed:["acapture","adyen","alternative_payments","authorize_net","bambora_apac","banco_sabadell","barclaycard_smartpay","barclays_epdq_extra_plus","beanstream","blue_pay","blue_snap","borgun","bpoint","braintree","bridge_pay","card_connect","card_stream","cardprocess","cayan","cecabank","cenpos","checkout_v2","clearhaus","conekta","creditcall","credorax","ct_payment","culqi","cyber_source","d_local","data_cash","decidir","diamond_mind","dibs","digitzs","ebanx","elavon","element","epay","eway","eway_rapid","ezic","fat_zebra","first_data_e4","first_data_e4_v27","first_giving","first_pay","flo2cash","flo2cash_simple","forte","global","global_collect","global_iris","global_transport","hps","iats_payments","iridium","iveri","ixopay","jabstry","jetpay","jetpay_v2","kushki","latitude19","litle","maxipago","mercado_pago","merchant_e_solutions","merchant_partners","merchant_warrior","mercury","migs","moneris","mundipagg","nab_transact","ncr_secure_pay","net_pay","netbilling","nmi","ogone","openpay","optimal_payments","orbital","pay_conex","pay_junction_v2","payeezy","payex","payflow_pro","payment_express","paymentez","paymill","paypal","paystation","payu_latam","pin","pro_pay","psi_gate","qbms","quantum","quickbooks","quickpay","quickpay_v10","qvalent","realex","redsys","s5","safe_charge","sage","sage_pay","secure_net","secure_pay_au","securion_pay","stripe","stripe_payment_intents","test","tns","trans_first","trans_first_transaction_express","trust_commerce","usa_epay","vanco","visanet_peru","wepay","wirecard","worldpay","worldpay_us"],proviaEnabled:!0,salesforceEnabled:!0,templateTypesAllowed:["contract","proposal","custom"]},jt=class jt{static collectIntegrations({docuSignEnabled:e,groupMeEnabled:s,hoverEnabled:o,jobNimbusEnabled:a,leadPerfectionEnabled:i,marketsharpEnabled:l,partnerCreditApplicationSourcesAllowed:r,paymentCaptureEnabled:d,proviaEnabled:c,roofScopeEnabled:u,salesforceEnabled:p,jobProgressEnabled:h,zapierEnabled:g}){const x=[];return e&&x.push("docusign"),s&&x.push("groupme"),o&&x.push("hover"),a&&x.push("jobnimbus"),i&&x.push("leadperfection"),l&&x.push("marketsharp"),d&&x.push("payment_capture"),c&&x.push("provia"),u&&x.push("roofscope"),p&&x.push("salesforce"),h&&x.push("jobprogress"),g&&x.push("zapier"),x.push(...r),x.sort((f,j)=>{const S=f.charCodeAt(0),w=j.charCodeAt(0);return S-w})}
5static collectAppSettings(e){const{maxCustomTemplateCount:s,maxPriceFormulasCount:o,maxCategoryCount:a,maxContractTemplateCount:i,maxProposalTemplateCount:l,maxCommissionFormulasCount:r,availableContactsEnabled:d,webhooksEnabled:c,customCreditApplicationsAllowed:u}=e,p=[];return c&&p.push("api_access"),p.push("app_appearance","appointments"),a&&p.push("categories"),p.push("company_logo","email_links","new_user_defaults","placeholders","report_sending","results","watermark"),d&&p.push("available_contacts"),i!==0&&p.push("contract_sending"),l!==0&&(p.push("proposal_sending"),p.push("credit_app_sending")),u&&p.push("credit_app_upload"),s&&p.push("custom_options"),o&&p.push("price_formulas"),r&&p.push("commission_formulas"),p.sort((g,x)=>{const m=g.charCodeAt(0),f=x.charCodeAt(0);return m-f})}static collectMainFeatures(e){const{maxMeasureSheetItemCount:s,maxContractTemplateCount:o,maxPackageCount:a,maxProposalTemplateCount:i,maxResourceCount:l}=e,r=["estimates"];return s&&r.push("price_guide"),r.push("finance_options"),l&&r.push("resources"),a&&r.push("packages"),o!==0&&r.push("contract"),i!==0&&r.push("proposal"),r.push("credit_applications"),r}static planKeyMap(e){return{resources:"pitchBooks",contract:"contracts",proposal:"proposals",creditApplications:"creditApplication"}[e]||e}static collectAllowedRoutes(e,s){return[...s].map(a=>a==="green_sky"?"greensky":a)}static setPlanConfig(e){return async s=>{const o=e.toJSON(),a=[];o.partnerCreditApplicationSourcesAllowed=a.map(u=>u.get("source"));const i=jt.collectIntegrations(o),l=jt.collectAppSettings(o),r=jt.collectMainFeatures(o),d=[...i,...l,...r],c=jt.collectAllowedRoutes(o,d);s({type:"SET_PLAN_CONFIG",config:{...o,allowedIntegration:i,allowedAppSettings:l,allowedMainFeatures:r,allowedRoutes:c}})}}};W(jt,"getSettingsLabel",(e,s)=>(o,a)=>{const{plan:i={}}=a(),{mainMenuLabelOverrides:l={}}=i,r=e.anchor==="available_contacts"?"availableManagers":`${e.anchor.split("_")[0]}s`,d=l[r]&&l[r].locked;let c=l[r]?l[r].settingsLabel:e.title;return r==="availableManagers"&&(c=l.availableManagers.settingsLabel||"Available Contacts"),d?l[`${r}`].settingsLabel:c}),W(jt,"getLabelByAnchor",e=>(s,o)=>{const{plan:a={},auth:i={}}=o(),{mainMenuLabelOverrides:l={}}=a,{config:r={}}=i,{appTitles:d={}}=r,c=e.anchor.split("_").map((x,m)=>m>0?`${x.charAt(0).toUpperCase()}${x.substring(1)}`:x).join("").replace("templates/",""),u=jt.planKeyMap(c),p=l[u]&&l[u].locked,h=l[u]?l[u].title:e.title,g=p?l[u].title:d[u]||h;return g.charAt(0).toUpperCase()+g.substr(1).toLowerCase()}),W(jt,"deletePlan",(e,s)=>async o=>{try{return o(Fc({title:"Delete Plan",message:"Are You sure you want to delete this plan",onConfirm:async()=>{o(Ka()),o(Jo("Deleting Plan...")),await e.destroy(),s&&s()}}))}catch(a){o(Kt(a))}finally{o(Ss())}}),W(jt,"getPlanDetails",e=>async(s,o)=>{s(Jo("Fetching Plan Details"));try{return s({type:"SET_PLAN_DETAILS",details:{...Fb}})}catch(a){s(Kt(a))}finally{s(Ss())}}),W(jt,"getPlans",()=>async(e,s)=>{e(Jo("Fetching Plans..."));try{const a=await new se.Query("PlanObject").find();return e({type:"SET_PLANS",items:a})}catch(o){e(Kt(o))}finally{e(Ss())}});let Co=jt;const Fe={toolbarContainerTemp:{maxWidth:"100vw",overflowX:"auto",whiteSpace:"nowrap",background:"#F4F4F4",boxShadow:"0px 8px 12px rgba(0, 0, 0, 0.15)","&::-webkit-scrollbar":{display:"none"},".Mui-disabled":{color:"rgba(0, 0, 0, 0.26) !important",borderColor:"rgba(0, 0, 0, 0.12) !important"}},toolbar:{height:"45px",padding:"4px 32px",columnGap:"16px",borderBottom:"1px solid",borderColor:"divider",button:{fontSize:11,color:"#2e2e2e"}},menuPopperStyle:{scrollbarGutter:"stable","&::-webkit-scrollbar":{width:"4px !important",height:"4px !important"}},headerMenu:{hr:{margin:"4px 8px"},".MuiPaper-root":{minWidth:"220px",maxHeight:"500px"},".MuiMenuItem-root":{height:"26px"},".MuiListItemButton-root":{height:"26px",padding:"0px 16px"},".MuiListItemText-primary, .MuiMenuItem-root":{fontSize:11},".subMenuIcon":{marginRight:"-8px"},".MuiListItemIcon-root":{minWidth:"auto !important",width:"auto",marginRight:"8px",".MuiSvgIcon-root":{width:"16px"}}},menuSubHeader:{lineHeight:"2",color:"#2e2e2e",fontWeight:600,fontSize:11},menuLabel:{flexDirection:"row",justifyContent:"space-between",alignItems:"flex-end",flexGrow:1,marginRight:"8px",fontSize:11,".selected-value":{color:"#646464",fontSize:9.5,maxWidth:"80px"}},subMenuItem:{fontSize:11,justifyContent:"space-between",height:"26px"}
5,radioMenuItem:{p:0,height:"26px",".MuiFormControlLabel-root":{width:"100%",margin:0,pr:"16px",pl:"6px",".MuiTypography-root":{fontSize:11}}},switchMenuItem:{px:0,height:"26px",".MuiFormControlLabel-root":{px:"16px",width:"100%",display:"flex",justifyContent:"space-between",margin:0,".MuiFormControlLabel-label":{fontSize:11}}},selectMenuItem:{px:0,height:"26px",".MuiTypography-root":{fontSize:11},".MuiListItemIcon-root":{minWidth:"auto",width:"auto"},".MuiCheckbox-root":{py:"6px",pr:"10px",pl:"10px",m:0}},fileUploadMenuItem:{height:"26px",py:0,".thumbnailImg":{height:"20px",width:"20px",objectFit:"contain",objectPosition:"center"}}},Hs=({rowNumber:n})=>t.jsxs(he,{spacing:.5,sx:{padding:1},children:[t.jsx(on,{sx:{lineHeight:"25px",color:"#2e2e2e",fontWeight:600,pl:0},children:"Loading..."}),[...Array(n)].map((e,s)=>t.jsx(qr,{variant:"rectangular",height:25},s))]}),qe=n=>{const{label:e,onTemplateChange:s,options:o,templateKey:a,selectedValue:i,valueType:l="string",disabled:r=!1,isIndented:d=!1,disableSelection:c=!1,isLoading:u=!1,error:p=null,emptyMessage:h="No options available"}=n,g=Fe,[x,m]=y.useState(!1),f=y.useRef(null),j=y.useCallback(w=>{const C=o.find(v=>v.value===w);return C?C.label:""},[o]),S=y.useCallback(w=>{const C=w.target.value;s(a,C,l)},[s,a,l]);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:f,"aria-describedby":a,onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),disabled:r,sx:{pl:d?5:2},children:[t.jsxs(he,{sx:g.menuLabel,children:[t.jsx("span",{children:e}),t.jsx(z,{className:"selected-value",noWrap:!0,sx:{width:"59px",textAlign:"right"},children:j(i)})]}),t.jsx(Yt,{className:"subMenuIcon"})]}),t.jsx(Ze,{id:a,sx:{zIndex:1300},open:x,anchorEl:f.current,placement:"right-start",transition:!0,onMouseEnter:()=>m(!0),onMouseLeave:w=>m(!1),children:({TransitionProps:w})=>t.jsx(Qe,{...w,timeout:350,children:t.jsxs(Je,{sx:{minWidth:"220px",maxHeight:"400px",overflowY:"auto"},elevation:4,children:[u&&t.jsx(Hs,{rowNumber:4}),!u&&p&&t.jsx(Tt,{children:t.jsx(ue,{disabled:!0,children:t.jsx(Te,{primary:p instanceof Error?p.message:"Error loading options",sx:{color:"#b00020"}})})}),!u&&!p&&t.jsx(Tt,{children:o.length===0?t.jsx(ue,{disabled:!0,children:t.jsx(Te,{primary:h})}):t.jsxs(t.Fragment,{children:[c&&o.map(C=>t.jsx(ue,{sx:{...g.radioMenuItem,pl:"16px",".MuiTypography-root":{fontSize:11}},onClick:()=>s(a,C.value,l),children:t.jsx(Te,{children:C.label})},C.value)),t.jsx(Bs,{value:i,onChange:S,children:!c&&o.map(C=>t.jsx(ue,{sx:g.radioMenuItem,children:t.jsx(Ft,{value:C.value,color:"secondary",control:t.jsx(An,{size:"small",color:"secondary"}),label:t.jsx(Te,{primary:C.label})})},C.value))})]})})]})})})]})},yd=[{label:"Letter",value:"612,792"},{label:"Letter (Landscape)",value:"792,612"},{label:"Legal",value:"612,1008"},{label:"Legal (Landscape)",value:"1008,612"},{label:"A4",value:"495,842"},{label:"A4 (Landscape)",value:"842,495"}],Rb=[{value:"singlePage",label:"Standard"},{value:"pdfPage",label:"PDF"}],_b=[{value:1,label:"(1) One"},{value:2,label:"(2) Two"},{value:3,label:"(3) Three"}],ke=n=>{const{label:e="",onChange:s,value:o,disabled:a=!1,tooltip:i="",isIndented:l=!1}=n,r=Fe;return t.jsx(Q,{title:i,placement:"right",disableFocusListener:!a,disableHoverListener:!a,disableTouchListener:!a,children:t.jsx("span",{children:t.jsx(ue,{sx:{...r.switchMenuItem,pl:l?3:0},disabled:a,children:t.jsx(Ft,{labelPlacement:"start",control:t.jsx(xt,{checked:o,disabled:a,color:"secondary",sx:{scale:.75},onChange:d=>{const{checked:c}=d.target;s(c)},edge:"end"}),label:e})})})})},$n=["textShort","textLong","textXLong","switched","textOnly","drawing","detailCell","provia","securePaymentCaptureAll","creditCardCell","bankAccountCell","emptySpace","photoPickerCell","measureSheetItemDetail","imagePicker","header"],Ca=[{value:"inch",label:"Inch"},{value:"quarter",label:'1/4"'},{value:"eighth",label:'1/8"'},{value:"sixteenth",label:'1/16"'}],Kl=[{value:0,label:"None"},{value:1,label:"Outside"},{value:2,label:"Inside & Outside"},{value:3,label:"Top & Bottom"}],Lt={identifier:["textShort","textLong","textXLong","switched"],inputType:["textShort","textLong","textXLong","switched"],pickerOption:["textShort","textLong"],required:lt.without($n,"emptySpace","measureSheetItemDetail","header"),hideInApp:["textShort","textLong","textXLong","switched"],hideOnPDF:["textShort","textLong","textXLong","switched"],inputDisabled:["textShort","textLong","textXLong","switched"],appTitle:lt.without($n,"emptySpace"),pdfTitle:lt.without($n,"emptySpace"),border:["header"],appNote:lt.without($n,"textOnly","drawing","emptySpace","photoPickerCell","measureSheetItemDetail","header"),defaultValue:["textShort","textLong","textXLong","switched","textOnly"],hideIfLeftBlank:["textShort","textLong","textXLong","switched","drawing","detailCell"],valueIfLeftBlank:["textShort","textLong","textXLong","switched","drawing","detailCell"],clearValueIfZero:["textShort","textLong"],initialRequired:lt.without($n,"provia","emptySpace","photoPickerCell","measureSheetItemDetail","header"),initialNote:lt.without($n,"drawing","provia","emptySpace","photoPickerCell","measureSheetItemDetail","header"),value:["textOnly"],onValue:["switched"],offValue:["switched"],imageSize:["detailCell","provia"],imagesSource:["imagePicker"],sketchHeight:["drawing"],emptySpaceHeight:["emptySpace"],dynamic:["switched","drawing","photoPickerCell","securePaymentCaptureAll","credit
5CardCell","bankAccountCell"],defaultTag:["photoPickerCell"],linkReportPhotos:["photoPickerCell"],showTitle:["measureSheetItemDetail"],showSelectedOption:["measureSheetItemDetail"],showQuantity:["measureSheetItemDetail"],showMeasureType:["measureSheetItemDetail"],showUnitTotal:["measureSheetItemDetail"],showGrandTotal:["measureSheetItemDetail"],formula:["measureSheetItemDetail"],hideUnlessAddedToEstimate:["measureSheetItemDetail"],captureLaterEnabled:["securePaymentCaptureAll","creditCardCell","bankAccountCell"],captureAndChargeEnabled:["securePaymentCaptureAll","creditCardCell","bankAccountCell"],defaultPaymentMode:["securePaymentCaptureAll","creditCardCell","bankAccountCell"],successValue:["securePaymentCaptureAll","creditCardCell","bankAccountCell"]},Bb=[{label:"%selectedTotal%",value:"%selectedTotal%"},{label:"%selectedTotalWholeNumber%",value:"%selectedTotalWholeNumber%"},{label:"%financeOptionDealerFee%",value:"%financeOptionDealerFee%"},{label:"%financeOptionInterestRate%",value:"%financeOptionInterestRate%"},{label:"%financeOptionMinAmount%",value:"%financeOptionMinAmount%"},{label:"%financeOptionMaxAmount%",value:"%financeOptionMaxAmount%"},{label:"%financeOptionPaymentMultiplier%",value:"%financeOptionPaymentMultiplier%"},{label:"%financeOptionNumberOfPayments%",value:"%financeOptionNumberOfPayments%"},{label:"%financeOptionDownPayment%",value:"%financeOptionDownPayment%"},{label:"%financeOptionDownPaymentNoZero%",value:"%financeOptionDownPaymentNoZero%"}],$b=n=>new Promise(e=>{var a;const s=(a=n.target.files)==null?void 0:a[0];if(!s)return;const o=new FileReader;o.onload=i=>{var c;const r=`image.${s.type.split("/")[1]}`,d=new se.File(r,s);d.isNew=!0,d._url=(c=i==null?void 0:i.target)==null?void 0:c.result,e(d)},o.readAsDataURL(s)}),zb=n=>{const{contractObject:e,value:s,categoryFormulaIds:o=[],currentCellIdentifier:a}=n,i=e.getAllCellIdentifiers(a),d=[...["B","T","CP","DP","UA","FP"],...i].includes(s),c=o.includes(s);return!d&&!c},V=(n,e,s="")=>{var a;const o=e;switch(e){case"pickerValues":return!Lt.inputType.includes(n)||!["picker","multiSelectPicker"].includes(s);case"multiSelectorSeparator":return!Lt.inputType.includes(n)||!["multiSelectPicker"].includes(s);case"fractionDigits":return!Lt.inputType.includes(n)||!["sizePicker","3DSizePicker"].includes(s);case"unitedInchSuffix":return!Lt.inputType.includes(n)||s!=="unitedInchPicker";case"minSizePickerWidth":case"maxSizePickerWidth":case"minSizePickerHeight":case"maxSizePickerHeight":return!Lt.inputType.includes(n)||!["sizePicker","3DSizePicker","unitedInchPicker"].includes(s);case"minSizePickerDepth":case"maxSizePickerDepth":return!Lt.inputType.includes(n)||s!=="3DSizePicker";case"isTotalSaleAmount":return!Lt.inputType.includes(n)||s!=="currency";case"dateDisplayFormat":return!Lt.inputType.includes(n)||!["datePicker","dateTimePicker","timePicker"].includes(s);case"formulaSettings":return!Lt.inputType.includes(n)||!["formula","formulaWhole","formulaCurrency","formulaCurrencyWhole","textFormula"].includes(s);case"clearValueIfZero":return!Lt.inputType.includes(n)||!["formula","formulaWhole","formulaCurrency","formulaCurrencyWhole","keypad","keypadDecimal","currency","currencyWhole"].includes(s);default:return!((a=Lt[o])!=null&&a.includes(n))}},Wb=tc("input")({clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,overflow:"hidden",position:"absolute",bottom:0,left:0,whiteSpace:"nowrap",width:100}),jd=n=>{const{onTemplateChange:e,file:s,templateKey:o,label:a,icon:i}=n,l=Fe,[r,d]=y.useState(!1),c=y.useRef(null),u=async p=>{const h=await $b(p);e(o,h,"file")};return t.jsxs(ue,{component:"label",role:void 0,sx:l.fileUploadMenuItem,tabIndex:-1,children:[t.jsx(Wb,{type:"file",onChange:u,accept:"image/*"}),t.jsx($e,{children:i||t.jsx(ec,{})}),t.jsx(Te,{children:a}),s&&t.jsxs(N,{children:[t.jsx("img",{ref:c,className:"thumbnailImg","aria-describedby":"thumbnailPreview",src:s._url,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1)}),t.jsx(Ze,{id:"thumbnailPreview",sx:{zIndex:1301},open:r,anchorEl:c.current,transition:!0,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:({TransitionProps:p})=>t.jsx(Qe,{...p,timeout:350,children:t.jsx(Je,{sx:{".thumbnailPreview":{width:"80px",height:"auto",objectFit:"contain",objectPosition:"center",padding:"12px"}},elevation:4,children:t.jsx("img",{className:"thumbnailPreview",src:s._url})})})})]}),t.jsx(ye,{"aria-label":`Remove ${a}`,size:"small",disabled:!s,onClick:()=>{e(o,void 0,"undefined")},children:t.jsx(Q,{title:`Remove ${a}`,children:t.jsx(Lo,{fontSize:"inherit"})})})]})},Oe=n=>{const{label:e,value:s,templateKey:o,onTemplateChange:a,disabled:i=!1,isIndented:l=!1,errorMsg:r="",multiline:d=!1,rows:c=3,placeholder:u=""}=n,p=Fe,[h,g]=y.useState(!1),x=y.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:x,"aria-describedby":`${o}-submenu`,onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),disabled:i,disableRipple:!0,sx:{pl:l?5:2},children:[t.jsxs(he,{sx:p.menuLabel,children:[t.jsx("span",{children:e}),t.jsx(z,{className:"selected-value",noWrap:!0,children:s})]}),t.jsx(Yt,{className:"subMenuIcon"})]}),t.jsx(Ze,{id:`${o}-submenu`,sx:{zIndex:1300},open:h,anchorEl:x.current,placement:d?"right-start":"right",transition:!0,onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),children:({TransitionProps:m})=>t.jsx(Qe,{...m,timeout:350,children:t.jsx(Je,{sx:{minWidth:"260px"},elevation:4,children:t.jsx(Cn,{sx:{p:1},onKeyDown:f=>f.stopPropagation(),children:d?t.jsx("textarea",{"aria-label":"minimum height",style:{borderColor:"rgba(0, 0, 0, 0.23)",width:"100%",borderRadius:"8px",padding:"8.5px 14px",resize:"both",minWidth:"238px"},rows:c,placeholder:u||`Enter ${e}`,value:s,onChange:f=>{const j=f.target.value;a(o,j,"string")}}):t.jsx(Le,{variant:"outlined",placeholder:u||`Enter ${e}`,color:"secondary",size:"small",fullWidth:!0,value:s==null?void 0:s.toString(),onChange:f=>a(o,f.target.value,"string"),slotProps:{input:{sx:{height:32,fontSize:12}}},error:!!r,helperText:r})})})})})]})},Yn=n=>{const{label:e="",options:s=[],selectedValues:o=[],templateKey:a="",onTemplateChange:i,disabled:l=!1,isValid:r=!0}=n,d=Fe,[c,u]=y.useState(!1),p=y.useRef(null),h=y.useCallback(m=>{const f=o.includes(m)?o.filter(j=>j!==m):[...o,m];i(a,f,"array")},[o,a,i]),g=y.useCallback(()=>{const f=o.length===s.length?[]:s.map(j=>j.value);i(a,f,"array")},[s,o,a,i]),x=y.useCallback(m=>{const f=s.filter(w=>w.group===m).map(w=>w.value),S=f.every(w=>o.includes(w))?o.filter(w=>!f.includes(w)):Array.from(new Set([...o,...f]));i(a,S,"array")},[s,o,a,i]);return t.jsxs(t.Fragment,{children:[t.jsx(ue,{ref:p,"aria-describedby":"nameSubmenu",onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),disabled:l,children:t.jsxs(he,{sx:{...d.menuLabel,color:r?"inherit":"error.main"},children:[t.jsx("span",{children:e}),t.jsx(z,{className:"selected-value",noWrap:!0,children:o.length})]})}),t.jsx(Ze,{id:"nameSubmenu",sx:{zIndex:1300},open:c,anchorEl:p.current,placement:"right-start",transition:!0,onMouseEnter:()=>u(!0),onMouseLeave:m=>u(!1),children:({TransitionProps:m})=>t.jsx(Qe,{...m,timeout:350,children:t.jsx(Je,{sx:{minWidth:"260px",maxHeight:450,overflowY:"scroll"},elevation:4,children:t.jsxs(Xt,{children:[t.jsx(Cn,{disablePadding:!0,sx:d.selectMenuItem,children:t.jsxs(St,{role:void 0,onClick:()=>g(),dense:!0,sx:{padding:"0px 8px"},children:[t.jsx($e,{children:t.jsx(Rt,{edge:"start",checked:o.length===s.length,indeterminate:o.length>0&&o.length<s.length,color:"secondary",disableRipple:!0})}),t.jsx(Te,{id:"selectAll",primary:"Select All"})]})},"selectAll"),t.jsx(ie,{sx:{my:1}}),s.map(({value:f,label:j,group:S},w)=>{var P,k;const C=o.includes(f),v=!!S&&S!==((P=s[w-1])==null?void 0:P.group),I=v?s.filter(T=>T.group===S).map(T=>T.value):[],D=I.filter(T=>o.includes(T)).length,F=I.length>0&&D===I.length,M=D>0&&D<I.length,R=S===((k=s.find(T=>T.group))==null?void 0:k.group);return t.jsxs(J.Fragment,{children:[v&&S&&t.jsxs(t.Fragment,{children:[!R&&t.jsx(ie,{}),t.jsx(Cn,{disablePadding:!0,sx:d.selectMenuItem,children:t.jsxs(St,{role:void 0,onClick:()=>x(S),dense:!0,sx:{padding:"4px 8px"},children:[t.jsx($e,{children:t.jsx(Rt,{edge:"start",checked:F,indeterminate:M,color:"secondary",disableRipple:!0})}),t.jsx(Te,{primary:S,primaryTypographyProps:{fontWeight:600}})]})}),t.jsx(ie,{})]}),t.jsx(Cn,{disablePadding:!0,sx:d.selectMenuItem,children:t.jsxs(St,{role:void 0,onClick:()=>h(f),dense:!0,sx:{padding:"0px 8px"},children:[t.jsx($e,{children:t.jsx(Rt,{edge:"start",checked:C,tabIndex:-1,
5color:"secondary",disableRipple:!0})}),t.jsx(Te,{id:f,primary:j})]})})]},f)})]})})})})]})},Hb=n=>{const{color:e,onChange:s}=n,o=Fe,[a,i]=y.useState(!1),l=y.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsx(ue,{ref:l,"aria-describedby":"nameSubmenu",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:t.jsxs(he,{sx:o.menuLabel,children:[t.jsx("span",{children:"Icon Color"}),t.jsx(z,{className:"selected-value",noWrap:!0,children:t.jsx(N,{sx:{height:"20px",width:"30px",borderRadius:"4px",border:"1px solid #C4C4C4",backgroundColor:`rgb(${e.r}, ${e.g}, ${e.b})`,opacity:e.a}})})]})}),t.jsx(Ze,{id:"nameSubmenu",sx:{zIndex:1300},open:a,anchorEl:l.current,placement:"right-start",transition:!0,onMouseEnter:()=>i(!0),onMouseLeave:r=>i(!1),children:({TransitionProps:r})=>t.jsx(Qe,{...r,timeout:350,children:t.jsx(Je,{sx:{minWidth:"auto"},elevation:4,children:t.jsx(Eo,{color:e,onChange:s})})})})]})},qb=n=>{const{categories:e=[],selectedCategory:s="",onTemplateChange:o}=n,a=Fe,[i,l]=y.useState(!1),r=y.useRef(null),d=y.useCallback(c=>{const u=c.target.value;o("category",u,"string")},[o]);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:r,"aria-describedby":"categorySubmenu",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[t.jsxs(he,{sx:a.menuLabel,children:[t.jsx("span",{children:"Category"}),t.jsx("span",{className:"selected-value",children:s})]}),t.jsx(Yt,{className:"subMenuIcon"})]}),t.jsx(Ze,{id:"categorySubmenu",sx:{zIndex:1300},open:i,anchorEl:r.current,placement:"right-start",transition:!0,onMouseEnter:()=>l(!0),onMouseLeave:c=>l(!1),children:({TransitionProps:c})=>t.jsx(Qe,{...c,timeout:350,children:t.jsx(Je,{sx:{width:"320px",maxHeight:550,overflowY:"scroll",overflowX:"hidden"},elevation:4,children:t.jsxs(Tt,{children:[t.jsx(Cn,{sx:{py:2},onKeyDown:u=>u.stopPropagation(),children:t.jsx(Le,{variant:"outlined",placeholder:"Enter Category",color:"secondary",size:"small",fullWidth:!0,value:s,slotProps:{input:{sx:{height:32,fontSize:12}}},onChange:d})}),t.jsx(Bs,{value:s,onChange:d,children:e.map(u=>t.jsx(ue,{sx:a.radioMenuItem,children:t.jsx(Q,{title:u,placement:"right",disableFocusListener:u.length<40,disableHoverListener:u.length<40,disableTouchListener:u.length<40,children:t.jsx(Ft,{value:u,control:t.jsx(An,{size:"small",color:"secondary"}),label:t.jsx(z,{sx:{width:"230px"},noWrap:!0,children:u})})})},u))})]})})})})]})},Vb=(n,e)=>{let s=(Array.isArray(e)?e:[]).filter(a=>typeof a=="string"&&a.length>0);s.length===0&&n&&(s=[n]);const o=n&&s.includes(n)?n:s[0];return o&&!s.includes(o)&&(s=[o,...s]),{sections:s,type:o}},Kb=(n,e,s)=>{const o=(Array.isArray(s)?s:[]).filter(a=>typeof a=="string"&&a.length>0&&a!==n&&a!==e);return{sections:e?[e,...o]:o,type:e}},Yo=(n,e,s)=>{const o=(Array.isArray(n)?n:[]).filter(r=>typeof r=="string"&&r.length>0),i=(o.length>0?o:e?[e]:[]).filter(r=>s.includes(r));if(i.length===0)return{sections:[],type:e,hasValid:!1};const l=i.includes(e)?e:i[0];return{sections:i,type:l,hasValid:!0}},Ub="share-document-templates-across-sections",Xo=(n,e="contract")=>{const s=window.location.pathname.replace(`/${n}/`,`/${e}/`);window.history.replaceState(e,e,s)},Gb=n=>{const[e,s,o,a]=n||[0,0,0,1];return{r:e,g:s,b:o,a}},Jb=b.shape({title:b.string,objectId:b.string.isRequired,order:b.number.isRequired,uploadSettings:b.shape({disableRequireEmail:b.bool,disableRequirePhone:b.bool,disableVerifyEmail:b.bool,disableReviewButton:b.bool,disablePrintButton:b.bool,leadPerfection:b.shape({fileName:b.string,fileDescription:b.string,backupRecipients:b.arrayOf(b.string)}),salesforce:b.shape({fileName:b.string,fileDescription:b.string,backupRecipients:b.arrayOf(b.string)}),webhook:b.shape({includePDF:b.bool,url:b.string,authHeader:b.string}),endpoints:b.arrayOf(b.string),fillEmptyWhiteSpace:b.bool,emptyWhiteSpaceNote:b.string,useBrochures:b.bool,useVerifyEmail:b.bool,from:b.string,subjectLine:b.string,recipients:b.arrayOf(b.string),ccRecipients:b.arrayOf(b.string),bccRecipients:b.arrayOf(b.string),emailHTML:b.string,emailFileName:b.string,backupRecipients:b.arrayOf(b.string),fileName:b.string})}),yi=n=>{var K,U;const{template:e={},setTemplateState:s,offices:o,stateOptions:a,maxTemplateCount:i,urlParam
5s:l,startCountTemplates:r,setCurrentWorkingTemplate:d,pushToDataLayer:c,maxProposalTemplateCount:u,showSnapshotModal:p,onDocumentSave:h}=n,g=Fe,m=zt()[Ub]??!1,[f,j]=y.useState(null),S=!!f,[w,C]=y.useState(!1),[v,I]=y.useState(!1),D=y.useMemo(()=>((e==null?void 0:e.includedOffices)||[]).map(A=>(A==null?void 0:A.id)||(A==null?void 0:A.objectId)).filter(Boolean),[e==null?void 0:e.includedOffices]),F=bp(D.map(A=>({queryKey:["doc-editor-two","officeMainMenuOptions",A],queryFn:async()=>{const Y=(await new se.Query("Office").get(A)).get("config");return Y?(await Y.fetch(),(Y.get("mainMenuOptions")||[]).map(be=>({...be,id:be.objectId}))):[]},enabled:!!A,refetchOnWindowFocus:!1,retry:!1}))),M=new Map;F.forEach(A=>{(A.data??[]).forEach(Y=>{const ce=Y.objectId??Y.id;ce&&!M.has(ce)&&M.set(ce,Y)})});const R=Array.from(M.values()),P=A=>{j(A.currentTarget)},k=()=>{j(null)},{data:T=[]}=He({queryKey:["allTemplateCategories"],queryFn:async()=>{const{type:A}=e,{type:q,id:Y}=l;let ce=[];if(A)return ce=await se.Cloud.run("all_template_categories",{type:A}),ce;if(Y==="new"){const be=`${q}_new`;d(be)}return i!==-1&&r(q),ce},enabled:!!e,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,staleTime:1e3*60*5,cacheTime:1e3*60*15}),B=A=>{var ce,be,Se,te,ge;const q=((ce=A.iconImage)==null?void 0:ce._url)||((be=A.iconImage)==null?void 0:be.url)||"",Y=((Se=A.preview)==null?void 0:Se._url)||((te=A.preview)==null?void 0:te.url)||"";h({id:A.objectId,isNew:!0,displayName:A.displayName,type:A.type,iconImageUrl:q,previewUrl:Y,includedOfficeIds:(ge=A.includedOffices)==null?void 0:ge.map(({objectId:me})=>me)})},L=async(A,q)=>{const Y=O.map(be=>be.value),ce=Yo(A!=null&&A.get?A.get("sections"):A==null?void 0:A.sections,A!=null&&A.get?A.get("type"):A==null?void 0:A.type,Y);if(q===void 0&&!ce.hasValid){re(()=>{L(A,"contract")});return}C(!0);try{const be=new $(A.toJSON()),Se=be.type;q?(be.type=q,be.sections=[q]):(be.type=ce.type,be.sections=ce.sections),Se&&Se!==be.type&&Xo(Se,be.type);const te=window.location.href.indexOf("new")>-1;if(!be.isTemplate){c({event:"documentTemplateEvent",eventCategory:"Documents",eventAction:"Edit",eventLabel:be.displayName});const ge=await be.saveToServer();if(s(ge),d(ge.objectId),te&&n.history.push(window.location.pathname.replace("new",ge.objectId)),i!==-1){const{type:me}=l;r(me)}B(ge),Ns({title:"Saved Successfully!",msg:"Your template has been saved successfully."})}}catch(be){wt({title:"Error saving template",showVerbose:!0,error:be})}finally{C(!1)}},H=async(A,q)=>{I(!0);try{const Y=new $(A.toJSON()),ce=O.map(te=>te.value);if(q)Y.type=q,Y.sections=[q];else{const te=Yo(Y.sections,Y.type,ce);Y.type=te.type,Y.sections=te.sections}const be=Y.isTemplate;Y.isTemplate=!1;const Se=await Y.saveCopyToServer(be);if(Y.id==="contract_new"){const te=await Y.revert();await s(te)}if(await s(Se),await d(Se.objectId),n.history.push(`/documents/templates/${Se.type}/edit/${Se.objectId}`),i!==-1){const{type:te}=l;r(te)}B(Se),Ns({title:"Saved Successfully!",msg:"Your template has been saved successfully."})}catch(Y){wt({title:"Error saving template",showVerbose:!0,error:Y})}finally{I(!1)}},G=async(A,q)=>{const Y=O.map(be=>be.value),ce=Yo(A!=null&&A.get?A.get("sections"):A==null?void 0:A.sections,A!=null&&A.get?A.get("type"):A==null?void 0:A.type,Y);if(q===void 0&&!ce.hasValid){re(()=>{G(A,"contract")});return}A.displayName=`${A.displayName} (Copy)`,Gh({title:`Save As ${A.displayName}`,msg:"Are you sure you want to save this template as a new template?",onConfirm:async()=>await H(A,q)})},ne=A=>A.map(q=>({__type:"Pointer",className:"Office",objectId:q})),le=y.useCallback(async(A,q,Y)=>{const ce=new $(e.toJSON());let be=q;if(A==="sections"){const Se=e.type,{sections:te,type:ge}=Vb(Se,q);ce.sections=te,ce.type=ge,s(ce),ge&&ge!==Se&&Xo(Se,ge);return}if(A==="type"){const Se=e.type,{sections:te,type:ge}=Kb(Se,(q==null?void 0:q.toString())??"",e.sections);ce.sections=te,ce.type=ge,s(ce),Xo(Se,ge);return}A==="includedOffices"&&(be=ne(Array.isArray(q)?q.map(String):[])),ce[A]=be,s(ce)},[e,s]),re=A=>{_o({title:"No Document Type Selected",msg:"This template no longer has a valid document type. Save it as a Contract?",confirmText:"Save as Contract",cancelText:"Cancel",onConfirm:A})},O=y.useMemo(()=>{let A=[{value:"contract",label:"Contracts"}];return u!==0&&A.push({value:"proposal",label:"Proposals"}),R.length>0&&(A=A.concat(R.filter(q=>!!q.objectId).map(q=>({value:q.objectId,label:q.title??""})))),A},[R,u]);return t.jsxs("div",{children:[t.jsx(we,{id:"file-menu-button",color:"secondary","aria-controls":S?"file-menu":void 0,"aria-haspopup":"true","aria-expanded":S?"true":void 0,onClick:P,"data-cy":"file-menu-button",sx:{textTransform:"none"},children:"File"}),t.jsxs(kt,{id:"file-menu",anchorEl:f,open:S,onClose:k,sx:g.headerMenu,slotProps:{paper:{sx:g.menuPopperStyle}},children:[t.jsxs(ue,{onClick:async()=>{await L(e),k()},disabled:!Object.keys(e).length||w||v,"data-testid":"doc-editor-save",children:[t.jsx($e,{children:t.jsx(yp,{})}),t.jsx(Te,{children:"Save"}),w&&t.jsx(vt,{color:"secondary",size:12})]}),t.jsxs(ue,{onClick:async()=>{await G(e),k()},disabled:!Object.keys(e).length||w||v,children:[t.jsx($e,{children:t.jsx(jp,{})}),t.jsx(Te,{children:"Save As New"}),v&&t.jsx(vt,{color:"secondary",size:12})]}),t.jsxs(ue,{disabled:e.objectId==="contract_new",onClick:async()=>{p(),k()},children:[t.jsx($e,{children:t.jsx(Cp,{})}),t.jsx(Te,{children:"Restore From Previous Version"})]}),t.jsx(ie,{sx:{mx:1}}),t.jsx(qb,{categories:T,selectedCategory:e.category,onTemplateChange:le}),t.jsx(Oe,{label:"Name",value:e.displayName,templateKey:"displayName",onTemplateChange:le}),t.jsx(ie,{sx:{mx:1}}),t.jsx(Yn,{label:"Included States",options:a,selectedValues:e.includedStates,templateKey:"includedStates",onTemplateChange:le}),t.jsx(Yn,{label:"Included Offices",options:o.map(A=>({value:A.id,label:A.get("name")}
5)),selectedValues:((K=e.includedOffices)==null?void 0:K.map(({objectId:A,id:q})=>q||A))||[],templateKey:"includedOffices",onTemplateChange:le}),t.jsx(ie,{sx:{mx:1}}),t.jsx(ke,{label:"Allow Multiple",value:!!e.canAddMultiplePages,onChange:A=>le("canAddMultiplePages",A,"boolean")}),t.jsx(ie,{sx:{mx:1}}),t.jsx(jd,{label:"Thumbnail",file:e.iconImage,templateKey:"iconImage",onTemplateChange:le,icon:t.jsx(Ip,{})}),m?t.jsx(Yn,{label:"App Sections",options:O,selectedValues:(U=e.sections)!=null&&U.length?e.sections:[e.type].filter(Boolean),templateKey:"sections",onTemplateChange:le}):t.jsx(qe,{label:"App Section",onTemplateChange:le,options:O,templateKey:"type",selectedValue:e.type,valueType:"string"}),t.jsx(Hb,{color:Gb(e==null?void 0:e.iconBackgroundColor),onChange:A=>{const{rgb:{r:q,g:Y,b:ce,a:be}}=A;le("iconBackgroundColor",[q,Y,ce,be],"array")}})]})]})};yi.propTypes={urlParams:b.shape({type:b.string.isRequired,id:b.string.isRequired}).isRequired,maxOfficeCount:b.number.isRequired,getLabelByAnchor:b.func.isRequired,template:b.instanceOf($),offices:b.arrayOf(b.instanceOf(se.Object)),setTemplateState:b.func.isRequired,handleError:b.func.isRequired,pushToDataLayer:b.func.isRequired,customDocTypes:b.arrayOf(Jb),setCurrentWorkingTemplate:b.func.isRequired,stateOptions:b.arrayOf(b.shape({value:b.string,label:b.string,group:b.string})),history:b.shape({}),maxProposalTemplateCount:b.number.isRequired,startCountTemplates:b.func.isRequired};yi.defaultProps={offices:[],template:void 0,stateOptions:[],customDocTypes:[]};const Yb=({templatesEdit:n,auth:{offices:e=[]}={},config:s,plan:o={},templates:a})=>({template:n[n.currentWorkingId],offices:e,stateOptions:s.stateOptions,maxOfficeCount:o.maxOfficeCount||0,maxProposalTemplateCount:o.maxProposalTemplateCount||0,templates:a}),Xb=n=>({getLabelByAnchor:e=>n(Co.getLabelByAnchor(e)),setTemplateState:e=>n(ee(e)),setCurrentWorkingTemplate:e=>n(Bc(e)),handleError:e=>n(Kt(e)),pushToDataLayer:e=>n(Ot(e)),startCountTemplates:e=>n(bi(e))}),Zb=Z(Yb,Xb)(yi),Qb=Zb,ey=n=>{const{onClickTemplateChange:e,watermark:{useWatermark:s,watermark:o,watermarkWidthPercent:a=100,watermarkAlpha:i=.5}}=n,l=Fe,[r,d]=y.useState(!1),c=y.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsx(jd,{label:"Watermark",file:o,templateKey:"watermark",onTemplateChange:e,icon:t.jsx(ec,{})}),t.jsx(ue,{ref:c,"aria-describedby":"watermarkSubmenu",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:t.jsxs(he,{sx:l.menuLabel,children:[t.jsx("span",{children:"Watermark Settings"}),t.jsx("span",{className:"selected-value",children:s?"Yes":"No"})]})}),t.jsx(Ze,{id:"watermarkSubmenu",sx:{zIndex:1300},open:r,anchorEl:c.current,placement:"right-start",transition:!0,onMouseEnter:()=>d(!0),onMouseLeave:u=>d(!1),children:({TransitionProps:u})=>t.jsx(Qe,{...u,timeout:350,children:t.jsx(Je,{sx:{minWidth:"260px"},elevation:4,children:t.jsxs(Tt,{children:[t.jsx(ke,{label:"Use Watermark",value:s,onChange:p=>{e("useWatermark",p,"boolean")}}),t.jsxs(ue,{disableRipple:!0,sx:l.subMenuItem,disabled:!s,children:["Width:",t.jsx(go,{sx:{width:140},size:"small",color:"secondary",defaultValue:100,"aria-label":"Default",valueLabelDisplay:"auto",value:a,onChange:(p,h)=>e("watermarkWidthPercent",Number(h),"number")})]}),t.jsxs(ue,{disableRipple:!0,sx:l.subMenuItem,disabled:!s,children:["Transparency:",t.jsx(go,{sx:{width:140},size:"small",color:"secondary",defaultValue:50,"aria-label":"Default",valueLabelDisplay:"auto",value:i*100,onChange:(p,h)=>e("watermarkAlpha",Number(h)%100/100,"number")})]})]})})})})]})},ji=n=>{const{template:e={},setTemplateState:s}=n,o=Fe,[a,i]=y.useState(null),l=!!a,r=u=>{i(u.currentTarget)},d=()=>{i(null)},c=y.useCallback((u,p,h)=>{const g=new $(e.toJSON());g[u]=h==="number"?Number(p):p,u==="watermark"&&(g.useWatermark=!!p),s(g)},[e,s]);return t.jsxs("div",{children:[t.jsx(we,{id:"page-menu-button",color:"secondary","aria-controls":l?"page-menu":void 0,"aria-haspopup":"true","aria-expanded":l?"true":void 0,onClick:r,"data-cy":"page-menu-button",sx:{textTransform:"none"},children:"Page"}),t.jsxs(kt,{id:"page-menu",anchorEl:a,open:l,onClose:d,sx:o.headerMenu,slotProps:{paper:{sx:o.menuPopperStyle}},children:[t.jsx(qe,{label:"Page Type",onTemplateChange:c,options:Rb,templateKey:"pageId",selectedValue:e.pageId,valueType:"string"}),t.jsx(qe,{label:"Page Size",onTemplateChange:c,options:yd,templateKey:"pageSize",selectedValue:e.pageSize,valueType:"string"}),t.jsx(ie,{sx:{mx:1}}),t.jsx(ey,{onClickTemplateChange:c,watermark:{useWatermark:!!e.useWatermark,watermark:e.watermark,watermarkWidthPercent:e.watermarkWidthPercent,watermarkAlpha:e.w
5atermarkAlpha}}),t.jsx(qe,{label:"Photos Per Page",onTemplateChange:c,options:_b,templateKey:"photosPerPage",selectedValue:e.photosPerPage,valueType:"number"}),t.jsx(ie,{sx:{mx:1}}),t.jsxs(ue,{disableRipple:!0,sx:{justifyContent:"space-between"},children:["Left/Right Margins",t.jsxs(xo,{size:"small",children:[t.jsx(ye,{"aria-label":"Remove Margin",size:"small",disabled:e.wMargin<=0,onClick:()=>{const u=e.wMargin-4,p=u<0?0:u;c("wMargin",p,"number")},children:t.jsx(fo,{fontSize:"inherit"})}),t.jsx(ie,{orientation:"vertical",sx:{height:"15px",alignSelf:"center"}}),t.jsx(ye,{"aria-label":"Add Margin",size:"small",disabled:e.wMargin>=parseFloat(e.pageSize)/4,onClick:()=>{const u=e.wMargin+4,p=parseFloat(e.pageSize)/4,h=u>p?p:u;c("wMargin",h,"number")},children:t.jsx(bo,{fontSize:"inherit"})})]})]}),t.jsxs(ue,{disableRipple:!0,sx:{justifyContent:"space-between"},children:["Top/Bottom Margins",t.jsxs(xo,{size:"small",children:[t.jsx(ye,{"aria-label":"Remove Margin",size:"small",disabled:e.hMargin<=0,onClick:()=>{const u=e.hMargin-4,p=u<0?0:u;c("hMargin",p,"number")},children:t.jsx(fo,{fontSize:"inherit"})}),t.jsx(ie,{orientation:"vertical",sx:{height:"15px",alignSelf:"center"}}),t.jsx(ye,{"aria-label":"Add Margin",size:"small",disabled:e.hMargin>=parseFloat(e.pageSize)/4,onClick:()=>{const u=e.hMargin+4,p=parseFloat(e.pageSize)/4,h=u>p?p:u;c("hMargin",h,"number")},children:t.jsx(bo,{fontSize:"inherit"})})]})]})]})]})};ji.propTypes={template:b.instanceOf($),setTemplateState:b.func.isRequired,watermarkWidthPercent:b.number,watermarkAlpha:b.number,pushToDataLayer:b.func.isRequired};ji.defaultProps={template:void 0,watermarkWidthPercent:0,watermarkAlpha:0};const ty=({templatesEdit:n,auth:{config:{watermarkAlpha:e=0,watermarkWidthPercent:s=0}={}}={}})=>({template:n[n.currentWorkingId],watermarkWidthPercent:s,watermarkAlpha:e}),ny=n=>({setTemplateState:e=>n(ee(e)),pushToDataLayer:e=>n(Ot(e))}),sy=Z(ty,ny)(ji),Ci=n=>{const{viewSelection:e,setView:s,template:o}=n,a=(i,l)=>{const r=parseInt(l||"0",10);s(r,r===0?"App":r===1?"PDF":"Both")};return t.jsxs(Gt,{value:e.toString(),exclusive:!0,onChange:a,"aria-label":"text alignment",sx:{".MuiButtonBase-root":{fontSize:"10px",height:"30px",padding:"4px 10px"},".Mui-selected":{backgroundColor:"rgba(120, 157, 255, 0.25)"}},children:[t.jsx(Ve,{value:"0",disabled:!o||o.pageId==="pdfPage",children:t.jsx(Q,{title:"App View",children:t.jsx(sl,{fontSize:"small"})})}),t.jsx(Ve,{value:"1",disabled:!o,children:t.jsx(Q,{title:"PDF View",children:t.jsx(ol,{fontSize:"small"})})}),t.jsx(Ve,{value:"2",disabled:!o||o.pageId==="pdfPage",children:t.jsx(Q,{title:"Both",children:t.jsxs(he,{direction:"row",children:[t.jsx(sl,{fontSize:"small"}),t.jsx(ol,{fontSize:"small"})]})})})]})};Ci.propTypes={viewSelection:b.oneOf([0,1,2]).isRequired,setView:b.func.isRequired,template:b.instanceOf($)};Ci.defaultProps={template:void 0};const oy=({templatesEdit:n})=>({template:n[n.currentWorkingId],viewSelection:n.viewSelection}),ay=n=>({setView:(e,s)=>n(Fg(e,s))}),iy=Z(oy,ay)(Ci),Cd="enable-doc-builder-two",Wo=320,qs=72,Ia="doc-builder-canvas-droppable",Sa="doc-builder-navigator-droppable",ly=1300,Ms=90,Io=.25,So=2,En=32,vo=48,ry=()=>{const n=ft(),s=zt()[Cd]??!1,o=ze(({templatesEdit:l})=>l.builderOverride);if(!s)return null;const a=o??s?"modern":"legacy",i=(l,r)=>{r&&n(Rg(r==="modern"))};return t.jsxs(Gt,{value:a,exclusive:!0,onChange:i,"aria-label":"builder mode",sx:{".MuiButtonBase-root":{fontSize:"10px",height:"30px",padding:"4px 10px"},".Mui-selected":{backgroundColor:"rgba(120, 157, 255, 0.25)"}},children:[t.jsx(Ve,{value:"modern",children:t.jsx(Q,{title:"Modern Builder",children:t.jsx(nc,{fontSize:"small"})})}),t.jsx(Ve,{value:"legacy",children:t.jsx(Q,{title:"Legacy Builder",children:t.jsx(sc,{fontSize:"small"})})})]})},cy=[{divider:!0,title:"General"},{placeholder:"%date%",replacement:"The date inside of the application (12-31-25)"},{placeholder:"%stateLicense%",replacement:"State License of Company"},{placeholder:"%usersLicense%",replacement:"Users License Number"},{placeholder:"%usersName%",replacement:"Users First and Last Name"},{placeholder:"%usersNameFirst%",replacement:"Users First Name"},{placeholder:"%usersNameLast%",replacement:"Users Last Name"},{placeholder:"%usersPhone%",replacement:"Users Phone Number"},{placeholder:"%userEmail%",replacement:"Users Email Address"},{placeholder:"%userIdentifier%",replacement:"The user identifier used within the application"},{placeholder:"%selectedTotal%",replacement:"The selected total at the bottom of the Estimates tab"},{placeholder:"%selectedTotalWholeNumber%",replacement:"The selected total at the bottom of the Estimates tab rounded to the whole dollar"},{placeholder:"%selectedTotalName%",replacement:"The name of the total selected at the bottom of the Estimates tab"},{placeholder:"%randomNumber%",replacement:"An eight-digit random number"},{placeholder:"%randomNumber<number 1 - 10>%",replacement:"A random number between one and ten digits in length. Example: %randomNumber5% = 12345"},{placeholder:"%year%",replacement:"The current year"},{placeholder:"%day%",replacement:"The day of the date. Example: 21"},{placeholder:"%month%",replacement:"The current numeric representation of the month. Example: 09"},{placeholder:"%monthName%",replacement:"The name of the current month. Example: September"},{placeholder:"%monthNameAbbv%",replacement:"The name of the current month abbreviated. Example: Sep"},{placeholder:"%weekday%",replacement:"The written out day of the week. Example: Friday"},{placeholder:"%weekdayAbbv%",replacement:"Abbreviated day of the week. Example: Fri"},{placeholder:"%estimateName%",replacement:"The name of the saved estimate"}
5],dy=[{divider:!0,title:"App"},{placeholder:"%companyLogo%",replacement:"Company Logo"},{placeholder:"%date%",replacement:`The Current Date (${Qt().format("MM/DD/YY")})`},{placeholder:"%year%",replacement:`Year - ${Qt().format("YYYY")}`},{placeholder:"%day%",replacement:`Day - ${Qt().format("D")}`},{placeholder:"%weekday%",replacement:`Weekday - ${Qt().format("dddd")}`},{placeholder:"%weekdayAbbv%",replacement:`Weekday (Abbv.)  - ${Qt().format("ddd")}`},{placeholder:"%month%",replacement:`Month - ${Qt().format("MM")}`},{placeholder:"%monthName%",replacement:`Month Name - ${Qt().format("MMMM")}`},{placeholder:"%monthNameAbbv%",replacement:`Month Name (Abbv.) - ${Qt().format("MMM")}`}],uy=[{divider:!0,title:"Customer Information"},{placeholder:"%customerName%",replacement:"First and Last name of Customer"},{placeholder:"%customerNameFirst%",replacement:"First name of Customer"},{placeholder:"%customerNameLast%",replacement:"Last name of Customer"},{placeholder:"%customerSpouseName%",replacement:"First and Last name of Customer’s Spouse"},{placeholder:"%customerSpouseNameFirst%",replacement:"First name of Customer’s Spouse"},{placeholder:"%customerSpouseNameLast%",replacement:"Last name of Customer’s Spouse"},{placeholder:"%customerAddressFull%",replacement:"Street, City, State and Zip Code of Customer"},{placeholder:"%customerAddressLine1%",replacement:"Street Address of Customer"},{placeholder:"%customerAddressLine2%",replacement:"City State and Zip Code of Customer"},{placeholder:"%customerAddressState%",replacement:"State of Customer abbreviated"},{placeholder:"%customerAddressStateFull%",replacement:"State of Customer spelled out"},{placeholder:"%customerAddressCity%",replacement:"City of Customer"},{placeholder:"%customerAddressZip%",replacement:"Zip Code of Customer"},{placeholder:"%customerContacts%",replacement:"All Contacts of Customer (Phone and Emails)"},{placeholder:"%customerEmail%",replacement:"All Emails of Customer"},{placeholder:"%customerPhone%",replacement:"All Phone numbers of Customer"}],py=[{divider:!0,title:"Measure Sheet Item"},{placeholder:"%category%",replacement:"The category of the added measure sheet item"},{placeholder:"%subCategory%",replacement:"The sub category of the added measure sheet item"},{placeholder:"%name%",replacement:"The name of the added measure sheet item"},{placeholder:"%quantity%",replacement:"The quantity entered of the added measure sheet item"},{placeholder:"%itemNote%",replacement:"The note of the added measure sheet item"},{placeholder:"%measurementType%",replacement:"The measurement type of the added measure sheet item"},{placeholder:"%tag%",replacement:"The user entered tag of the added measure sheet item"},{placeholder:jc,replacement:"The auto assigned number of the added measure sheet item"},{placeholder:"%drillDown1%",replacement:"The first drill down of the added measure sheet item"},{placeholder:"%drillDown<any number>%",replacement:"Any subsequent drill downs of the added measure sheet item"}],hy=[{divider:!0,title:"Option"},{placeholder:"%selectionBrand%",replacement:"The brand of the selected price guide option"},{placeholder:"%selectionName%",replacement:"The name of the selected price guide option"},{placeholder:"%selectedOption.<custom placeholder>%",replacement:"The replacement value for the specified custom placeholder of the selected price guide option."},{placeholder:"%unitPrice%",replacement:"The unit price of the selected price guide item of the added measure sheet item including accessories"},{placeholder:"%unitPriceWholeNumber%",replacement:"The unit price of the selected price guide item of the added measure sheet item including accessories rounded to the whole dollar"},{placeholder:"%unitPriceWithoutAccessories%",replacement:"The unit price of the selected price guide item of the added measure sheet item excluding accessories"},{placeholder:"%totalPrice%",replacement:"The unit price of the selected price guide item of the added measure sheet item multiplied by the quantity"},{placeholder:"%totalPriceWholeNumber%",replacement:"The unit price of the selected price guide item of the added measure sheet item multiplied by the quantity rounded to the whole number"},{placeholder:"%totalPriceWithoutAccessories%",replacement:"The unit price of the selected price guide item of the added measure sheet item, without cost of added accessories, multiplied by the quantity"},{placeholder:"%totalPriceWithoutAccessoriesWholeNumber%",replacement:"The unit price of the selected price guide item of the added measure sheet item, without cost of added accessories, multiplied by the quantity rounded to the whole dollar"},{placeholder:"%accessoriesTotal%",replacement:"The total of all added accessories of the selected price guide item of the added measure sheet item"},{placeholder:"%accessoriesTotalWholeNumber%",replacement:"The total of all added accessories of the selected price guide item of the added measure sheet item rounded to the whole dollar"}],my=[{divider:!0,title:"UpCharge"},{placeholder:"%<identifier>.name%",replacement:"The name of the upcharge"},{placeholder:"%<identifier>.note%",replacement:"The note of the upcharge"},{placeholder:"%<identifier>.measurementType%",replacement:"The measurement Type of the upcharge"},{placeholder:"%<identifier>.quantity%",replacement:"The quantity of the added upcharge including 0"},{placeholder:"%<identifier>.quantityNoZero%",replacement:"The quantity of the added upcharge where 0 will be blank"},{placeholder:"%<identifier>.unitPrice%",replacement:"The unit price of the upcharge"},{placeholder:"%<identifier>.unitPriceNoZero%",replacement:"The unit price of the upcharge where 0 will be blank"},{placeholder:"%<identifier>.unitPriceWholeNumber%",replacement:"The unit price of the upcharge rounded to the whole dollar"},{placeholder:"%<identifier>.unitPriceWholeNumberNoZero%",replacement:"The unit price of the upcharge rounded to the whole dollar where 0 will be blank"},{placeholder:"%<identifier>.totalPrice%",replacement:"The total price of the upcharge (unit price x quantity)"},{placeholder:"%<identifier>.totalPriceNoZero%",replacement:"The total price of the upcharge (unit price x quantity) where 0 will be blank"},{placeholder:"%<identifier>.totalPriceWholeNumber%",replacement:"The total price of the upcharge (unit price x quantity) rounded to the whole dollar"},{placeholder:"%<identifier>.totalPriceWholeNumberNoZero%",replacement:"The total price of the upcharge (unit price x quantity) rounded to the whole dollar where 0 will be blank"},{placeholder:"%<identifier>.grandTotalPrice%",replacement:"The grand total of the upcharge (unit price x quantity x parent item quantity)"},{placeholder:"%<identifier>.grandTotalPriceNoZero%",replacement:"The grand total of the upcharge (unit price x quantity x parent item quantity) where 0 will be blank"},{placeholder:"%<identifier>.grandTotalPriceWholeNumber%",replacement:"The grand total of the upcharge (unit price x quantity x parent item quantity) rounded to the whole dollar"},{placeholder:"%<identifier>.grandTotalPriceWholeNumberNoZero%",replacement:"The grand total of the upcharge (unit price x quantity x parent item quantity) rounded to the whole dollar where 0 will be blank"},{placeholder:"%<identifier>.<any placeholder from additional details>%",replacement:"The entered values for any additional details added to the upcharge"},{placeholder:"%<identifier>.<any placeholder from custom placeholders>%",replacement:"The value from any custom placeholders of the upcharge"}],gy=[{divider:!0,title:"Custom Product"},{placeholder:"%name%",replacement:"The name of the Custom Product"},{placeholder:"%itemNote%",replacement:"The description of the Custom Product"},{placeholder:"%quantity%",replacement:"The quantity of the Custom Product"},{placeholder:"%unitPrice%",replacement:"The unit price of the Custom Product"},{placeholder:"%totalPrice%",replacement:"The unit price of the Custom Product multiplied by the quantity"}],xy=[{divider:!0,title:"Finance Option"},{placeholder:"%financeOptionCategory%",replacement:"The category of the selected finance option"},{placeholder:"%financeOptionBankName%",replacement:"The bank name of the selected finance option"},{placeholder:"%financeOptionName%",replacement:"The name of the selected finance option"},{placeholder:"%financeOptionDealerFee%",replacement:"The dealer fee of the selected finance option"},{placeholder:"%financeOptionInterestRate%",replacement:"The interest rate of the selected finance option"},{placeholder:"%financeOptionMinAmount%",replacement:"The minimum amount of the selected finance option"},{placeholder:"%financeOptionMaxAmount%",replacement:"The maximum amount of the selected finance option"},{placeholder:"%financeOptionPaymentMultiplier%",replacement:"The payment multiplier of the selected finance option"},{placeholder:"%financeOptionPlanCode%",replacement:"The plan code of the selected finance option"},{placeholder:"%financeOptionNumberOfPayments%",replacement:"The number of payments (term) of the selected finance option"},{placeholder:"%financeOptionDownPayment%",replacement:"The entered down payment for the selected finance option"},{placeholder:"%financeOptionDownPaymentNoZero%",replacement:"The entered down payment for the selected finance option where 0 will be blank"}],fy=[{divider:!0,title:"User"},{placeholder:"%usersLicense%",replacement:"License Number"},{placeholder:"%usersName%",replacement:"First and Last Name"},{placeholder:"%usersPhone%",replacement:"Phone Number"},{placeholder:"%userEmail%",replacement:"Email Address"},{placeholder:"%userJobTitle%",replacement:"Job Title"},{divider:!0,title:"Customer Names"},{placeholder:"%customerName%",replacement:"Primary - First and Last name"},{placeholder:"%customerSpouseName%",replacement:"Secondary - First and Last name"}],by=[{divider:!0,title:"Customer Address"},{placeholder:"%customerAddressFull%",replacement:"Street, City, State and Zip Code"},{placeholder:"%customerAddressLine1%",replacement:"Street Address"},{placeholder:"%customerAddressLine2%",replacement:"City State and Zip Code"},{placeholder:"%customerAddressCity%",replacement:"City"},{placeholder:"%customerAddressState%",replacement:"State"},{placeholder:"%customerAddressZip%",replacement:"Zip Code"}],yy=[{divider:!0,title:"Customer Contacts"},{placeholder:"%customerContacts%",replacement:"All Contacts (Email and Phone)"},{placeholder:"%customerEmail%",replacement:"All Emails"},{placeholder:"%customerPhone%",replacement:"All Phone Numbers"}],Ul=[...cy,...dy,...uy,...py,...hy,...my,...gy,...xy,...fy,...by,...yy],jy={searchIcon:{marginRight:"8px",color:"gray5.main"}},Id=n=>{const{searchedText:e,handleSearch:s,...o}=n,a=jy;return t.jsx(he,{flexDirection:"row",sx:{position:"relative"},children:t.jsx(Le,{size:"small",variant:"outlined",color:"secondary",value:e,onCh
5ange:i=>s(i.target.value),slotProps:{input:{startAdornment:t.jsx(Sp,{sx:a.searchIcon})}},...o})})},Ii=n=>{const{customPlaceholders:e}=n,s=Fe,[o,a]=y.useState(null),i=!!o,[l,r]=y.useState(""),[,d]=y.useState(""),c=m=>{a(m.currentTarget)},u=()=>{a(null)},p=y.useCallback(m=>{m&&(navigator.clipboard.writeText(m),d(m),Be.show({message:`${m} Copied to clipboard!`,timeout:1e3}))},[]),h=zt(),g=(h["category-auto-numbering"]??!1)&&(h["auto-number-placeholder"]??!1),x=y.useMemo(()=>{let m=g?[...Ul]:Ul.filter(S=>!("placeholder"in S)||S.placeholder!==jc);if(e.length>0){const S={divider:!0,title:"Custom"};m=[...m,S,...e]}if(!l)return m;const f=m.filter(S=>{var w,C;return"divider"in S&&S.divider?!0:((w=S.replacement)==null?void 0:w.toLowerCase().includes(l.toLowerCase()))||((C=S.placeholder)==null?void 0:C.toLowerCase().includes(l.toLowerCase()))}),j=[];for(let S=0;S<f.length;S++){const w=f[S];if("divider"in w&&w.divider){const C=f[S+1];if(!C||"divider"in C&&C.divider)continue}j.push(w)}return j},[g,e,l]);return t.jsxs("div",{children:[t.jsx(we,{id:"placeholder-menu-button",color:"secondary","aria-controls":i?"placeholder-menu":void 0,"aria-haspopup":"true","aria-expanded":i?"true":void 0,onClick:c,"data-cy":"placeholder-menu-button",sx:{textTransform:"none"},children:"Placeholders"}),t.jsxs(kt,{id:"placeholder-menu",anchorEl:o,open:i,onClose:u,sx:{...s.headerMenu,".MuiPaper-root":{maxWidth:"400px",minWidth:"370px"}},slotProps:{paper:{sx:{...s.menuPopperStyle,overflowY:"hidden",scrollbarGutter:"normal"}}},children:[t.jsxs(N,{sx:{px:1},children:[t.jsx(Id,{searchedText:l,handleSearch:m=>r(m),onKeyDown:m=>m.stopPropagation(),size:"small",sx:{flex:1},placeholder:"Search placeholders..."}),t.jsx(ie,{sx:{margin:"4px 0 0 0 !important"}})]},"search-placeholders"),t.jsx(N,{sx:{maxHeight:"500px",overflowY:"auto",scrollbarGutter:"stable"},children:x.map(({placeholder:m,replacement:f="",divider:j,title:S},w)=>j?t.jsxs(J.Fragment,{children:[w!==0&&t.jsx(ie,{sx:{mx:1}},`divider-${w}`),t.jsx(on,{sx:{lineHeight:"26px",color:"black",fontWeight:600,fontSize:12},children:S},S)]},`section-${S}-${w}`):t.jsx(Q,{title:f,placement:"right",disableFocusListener:f.length<30,disableHoverListener:f.length<30,disableTouchListener:f.length<30,children:t.jsx("span",{children:t.jsx(ue,{onClick:()=>p(m),children:t.jsxs(pe,{container:!0,justifyContent:"space-between",alignItems:"center",sx:{width:"100%"},spacing:"16px",children:[t.jsx(pe,{size:"grow",children:t.jsx(z,{noWrap:!0,textAlign:"right",fontSize:11,children:f})}),t.jsx(pe,{width:10,children:t.jsx(ie,{sx:{borderColor:"black",m:"0 !important",opacity:.3}})}),t.jsx(pe,{size:"grow",children:t.jsx(z,{noWrap:!0,fontSize:11,children:m})})]})},m)})},`tooltip-${m}-${w}`))})]})]})};Ii.propTypes={customPlaceholders:b.arrayOf(b.shape({placeholder:b.string.isRequired,replacement:b.string.isRequired})),pushToDataLayer:b.func};Ii.defaultProps={customPlaceholders:[],pushToDataLayer:()=>{}};const Cy=({templatesEdit:n,auth:e={}})=>{const{config:s={}}=e;return{customPlaceholders:s.placeholders}},Iy=n=>({pushToDataLayer:e=>n(Ot(e))}),Sy=Z(Cy,Iy)(Ii),st="create_worksheet",Gs="update_financials",Sd=[{value:"contracts",label:"Contracts"},{value:"estimates",label:"Estimates"},{value:"proposals",label:"Proposals/Documents"},{value:"materials",label:"Materials"},{value:"work_orders",label:"Work Orders"},{value:"measurements",label:"Measurements"}],vy=n=>({id:ss(10),module:"jobProgress",action:{hookName:"create_worksheet",params:{createWorksheet:!0,createMeasureSheet:!1,worksheetFileName:"Worksheet for %customerName%",measuresheetFileName:"MeasurementSheet for %customerName%",destination:Sd[2].value,macros:[]}},backupRecipients:[n]}),Ty=n=>({id:ss(10),module:"jobProgress",action:{hookName:"update_financials",params:{}},backupRecipients:[n]}),wy={createWorksheet:"action.params.createWorksheet",worksheetFileName:"action.params.worksheetFileName",destination:"action.params.destination",createMeasureSheet:"action.params.createMeasureSheet",measuresheetFileName:"action.params.measuresheetFileName",macros:"action.params.macros"},ky={macroTable:{borderRadius:1,border:"1px solid",borderColor:"gray1.main",overflow:"hidden",height:"300px",flexDirection:"column",flexWrap:"nowrap"},macroTableHeader:{backgroundColor:"gray1.main",alignItems:"center",py:"12px",".grid-item":{px:"8px"}}
5,macroTableBody:{height:300,overflowY:"auto",overflowX:"hidden"},macroTableRow:{alignItems:"center",borderBottom:"1px solid",borderColor:"gray1.main",cursor:"pointer","&:hover":{backgroundColor:"gray1.main"},".grid-item":{px:"8px"}},tablePagination:{".MuiTablePagination-toolbar":{minHeight:"50px",height:"50px"},".MuiTablePagination-selectLabel":{marginBottom:"2.5px"},".MuiTablePagination-displayedRows":{marginBottom:"0px"},"&::-webkit-scrollbar":{display:"none"}}},Py=vp`
6  0% { transform: scale(1); }
7  50% { transform: scale(1.05); }
8  100% { transform: scale(1); }
9`,Dy=n=>{const{createWorksheet:e,isWorksheetValid:s,selectedMacroIds:o,onTemplateChange:a,leapCrmOfficeIds:i=[]}=n,l=Fe,r=ky,[d,c]=y.useState(!1),[u,p]=y.useState(o),[h,g]=y.useState(null),[x,m]=y.useState(0),[f,j]=y.useState(25);y.useEffect(()=>{d&&p(o)},[d,o]);const{data:S=[]}=He({queryKey:["macroIds",{leapCrmOfficeIds:i}],queryFn:async()=>{const I=await se.Cloud.run("jobProgress_macros",{officeIds:i});return console.log("Macro IDs:",I),(I==null?void 0:I.map(F=>({value:(F==null?void 0:F.macro_id)||"",label:(F==null?void 0:F.macro_name)||""})))||[]},onError:I=>wt({title:"Error fetching Macro IDs",showVerbose:!0,error:I})}),w=y.useCallback(()=>{if(u.length===0){g("Please select at least one Macro ID.");return}a("macros",u,st),g(null),c(!1)},[u,a]),C=y.useCallback(I=>{const D=[...u],F=D.findIndex(M=>M.id===I.id);F!==-1?D.splice(F,1):D.push(I),p(D)},[u]),v=y.useMemo(()=>[...S].slice(x*f,x*f+f),[x,S,f]);return t.jsxs(t.Fragment,{children:[t.jsx(Q,{title:"at least one Macro ID is required!",placement:"right",children:t.jsx("span",{children:t.jsx(ue,{disabled:!e,onClick:()=>c(!0),sx:{animation:s?"none":`${Py} 1s infinite`,animationTimingFunction:"ease-in-out"},children:t.jsxs(he,{sx:{...l.menuLabel,color:s?"inherit":"error.main"},children:[t.jsx("span",{children:"Assign Macro ID"}),t.jsx(z,{className:"selected-value",noWrap:!0,children:o.length})]})})})}),t.jsxs($s,{title:"Assign Macro ID",open:d,onClose:()=>c(!1),children:[t.jsxs(pe,{container:!0,"aria-label":"Macro ID Table",sx:r.macroTable,children:[t.jsxs(pe,{container:!0,flexWrap:"nowrap","aria-label":"Macro ID Table header",sx:r.macroTableHeader,children:[t.jsx(pe,{width:40}),t.jsx(pe,{size:6,className:"grid-item",children:t.jsx(z,{variant:"subtitle2",color:"subtitle2",children:"Macro ID Name"})}),t.jsx(pe,{size:6,className:"grid-item"})]}),t.jsx(N,{sx:r.macroTableBody,children:v.map(({value:I,label:D})=>{const F={id:I,name:D},M=u.some(R=>R.id===I);return t.jsxs(pe,{container:!0,flexWrap:"nowrap","aria-label":"Macro ID Table body",sx:r.macroTableRow,onClick:()=>C(F),children:[t.jsx(pe,{width:40,children:t.jsx(Rt,{checked:M})}),t.jsx(pe,{size:6,className:"grid-item",children:t.jsx(z,{sx:{fontSize:13},children:D})}),t.jsx(pe,{size:6,className:"grid-item"})]},I)})})]}),t.jsx(ns,{rowsPerPageOptions:[25,50,100],component:"div",sx:r.tablePagination,count:S.length,page:x,onPageChange:(I,D)=>m(D),rowsPerPage:f,onRowsPerPageChange:I=>j(parseInt(I.target.value,10))}),t.jsx(N,{children:t.jsxs(he,{direction:"row",justifyContent:"flex-end",alignItems:"center",gap:2,mt:2,children:[t.jsx(z,{variant:"caption",color:"error.main",sx:{display:h?"block":"none"},children:h}),t.jsx(we,{variant:"contained",onClick:w,children:"Update"})]})})]})]})},Oy=n=>{const{onTemplateChange:e,hookDict:s,isWorksheetValid:o,leapCrmOfficeIds:a}=n,i=Fe,[l,r]=y.useState(!1),d=y.useRef(null),c=!!s[st].action.params.createWorksheet,u=s[st].action.params.macros||[];return t.jsxs(t.Fragment,{children:[t.jsx(ue,{ref:d,"aria-describedby":"worksheetSubmenu",onMouseEnter:()=>r(!0),onMouseLeave:()=>{o&&r(!1)},children:t.jsxs(he,{sx:i.menuLabel,children:[t.jsx("span",{children:"Create Worksheet"}),t.jsx(z,{className:"selected-value",noWrap:!0,children:c?"Yes":"No"})]})}),t.jsx(Ze,{id:"worksheetSubmenu",sx:{zIndex:1300},open:l,anchorEl:d.current,placement:"right-start",transition:!0,onMouseEnter:()=>r(!0),onMouseLeave:()=>{o&&r(!1)},children:({TransitionProps:p})=>t.jsx(Qe,{...p,timeout:350,children:t.jsx(Je,{sx:{minWidth:"260px"},elevation:4,children:t.jsxs(Tt,{children:[t.jsxs(on,{sx:{lineHeight:"1.5",color:"black",fontWeight:600,justifyContent:"space-between",display:"flex"},children:["Worksheet Settings",t.jsx(Q,{title:"For a worksheet to be created in Leap CRM, this document must be assigned to at least one Macro ID.",placement:"right",children:t.jsx(Tp,{sx:{color:"gray6.main",width:"18px"}})})]},"document-actions-header"),t.jsx(ie,{sx:{m:1}}),t.jsx(ke,{label:"Create Worksheet",value:c,onChange:h=>e("createWorksheet",h,st)}),t.jsx(Oe,{label:"Name",value:s[st].action.params.worksheetFileName,templateKey:"worksheetFileName",onTemplateChange:(h,g)=>e(h,g,st),disabled:!c}),t.jsx(qe,{label:"Destination",onTemplateChange:(h,g,x)=>e(h,g,st),options:Sd,templateKey:"destination",selectedValue:s[st].action.params.destination,disabled:!c}),t.jsx(Dy,{createWorksheet:c,selectedMacroIds:u,isWorksheetValid:o,onTemplateChange:e,leapCrmOfficeIds:a})]})})})})]})},Ny=n=>{const{onTemplateChange:e,hookDict:s,disabled:o=!1}=n,a=Fe,[i,l]=y.useState(!1),r=y.useRef(null),d=!!s[st].action.params.createMeasureSheet;return t.jsxs(t.Fragment,{children:[t.jsx(Q,{title:"This document must be linked to one or more Leap CRM measurement attributes and saved to enable this.",placement:"right",disableFocusListener:!o,disableHoverListener:!o,disableTouchListener:!o,children:t.jsx("span",{children:t.jsx(ue,{ref:r,"aria-describedby":"measurementSettings",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),disabled:o,children:t.jsxs(he,{sx:a.menuLabel,children:[t.jsx("span",{children:"Measurement Settings"}),t.jsx(z,{className:"selected-value",noWrap:!0,children:d?"Yes":"No"})]})})})}),t.jsx(Ze,{id:"measurementSettings",sx:{zIndex:1300},open:i,anchorEl:r.current,placement:"right-start",transition:!0,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:({TransitionProps:c})=>t.jsx(Qe,{...c,timeout:350,children:t.jsx(Je,{sx:{minWidth:"260px"},elevation:4,children:t.jsxs(Tt,{children:[t.jsx(on,{sx:{lineHeight:"1.5",color:"black",fontWeight:600,justifyContent:"space-between",display:"flex"},children:"Measurement Settings"},"document-actions-header"),t.jsx(ie,{sx:{m:1}}),t.jsx(ke,{label:"Create Measurement Sheet",value:d,onChange:u=>e("createMeasureSheet",u,st)}),t.jsx(Oe,{label:"File Name",value:s[st].action.params.measuresheetFileName,templateKey:"measuresheetFileName",onTemplateChange:(u,p)=>e(u,p,st),disabled:!d})]})})})})]})},My=n=>{var S,w;const{template:e={}
9,userEmail:s,setTemplateState:o,offices:a}=n,i=Fe,[l,r]=y.useState(null),d=!!l,[c,u]=y.useState({}),p=C=>{r(C.currentTarget)},h=y.useMemo(()=>{var v;const C=[];return(v=e.includedOffices)==null||v.map(I=>{const D=I==null?void 0:I.objectId;a.some(M=>{var P;const R=((P=M.get("config").get("appointmentsConfig"))==null?void 0:P.endpoint)||"";return M.id===D&&R==="JobProgress"})&&C.push(D)}),C},[a,e.includedOffices]),g=y.useMemo(()=>{var I,D,F,M,R,P,k;const C=!!((F=(D=(I=c==null?void 0:c[st])==null?void 0:I.action)==null?void 0:D.params)!=null&&F.createWorksheet),v=(k=(P=(R=(M=c==null?void 0:c[st])==null?void 0:M.action)==null?void 0:R.params)==null?void 0:P.macros)==null?void 0:k.length;return!(C&&!v)},[c]),x=y.useCallback(()=>{const C=Object.values(c);if(!e||!C.length)return;const v=new $(e.toJSON());let I=(v==null?void 0:v.hooks)||[];C.forEach(D=>{const F=I.findIndex(M=>M.id===D.id||M.action.hookName===D.action.hookName);F!==-1?I[F]=D:I.push(D)}),v.hooks=I,o(v)},[e,o,c]),m=()=>{g&&(r(null),x())};y.useMemo(()=>{if(!(e!=null&&e.objectId))return;const C=(e==null?void 0:e.hooks)||[];let v={[st]:vy(s)};C.forEach(I=>{var D,F;if([st,Gs].includes((D=I==null?void 0:I.action)==null?void 0:D.hookName)){const M=(F=I==null?void 0:I.action)==null?void 0:F.hookName;v[M]={id:(I==null?void 0:I.id)||ss(10),...I}}}),u(v)},[s,e]);const f=y.useCallback(async(C,v,I)=>{const D=wy[C];D&&u(F=>{const M={...F[I]};return at.set(M,D,v),{...F,[I]:M}})},[e,u]),j=y.useCallback(C=>{u(v=>{const I={...v};return C?I[Gs]=Ty(s):delete I[Gs],I})},[u,s]);return t.jsxs("div",{children:[t.jsx(Q,{title:"To enable this feature, include at least one Leap CRM office to this document.",disableFocusListener:!!h.length,disableHoverListener:!!h.length,disableTouchListener:!!h.length,children:t.jsx("span",{children:t.jsx(we,{id:"action-menu-button",color:"secondary","aria-controls":d?"action-menu":void 0,"aria-haspopup":"true","aria-expanded":d?"true":void 0,onClick:p,"data-cy":"action-menu-button",sx:{textTransform:"none"},disabled:!h.length,children:"Action"})})}),t.jsxs(kt,{id:"action-menu",anchorEl:l,open:d,onClose:m,sx:i.headerMenu,slotProps:{paper:{sx:i.menuPopperStyle}},children:[t.jsxs(on,{sx:{lineHeight:"1.5",color:"black",fontWeight:600},children:["Document Actions",t.jsxs(z,{variant:"body2",sx:{color:"gray6.main",mt:"4px",fontSize:"11.5px"},children:["Tell SalesPro what action to take in",t.jsx("br",{}),"Leap CRM after sending this document."]})]},"document-actions-header"),t.jsx(ie,{sx:{m:1}}),t.jsx(Oy,{onTemplateChange:f,hookDict:c,isWorksheetValid:g,leapCrmOfficeIds:h}),t.jsx(Ny,{onTemplateChange:f,hookDict:c,disabled:!((S=e==null?void 0:e.linkedTypes)!=null&&S.includes("jobProgressMeasureSheet"))}),t.jsx(ke,{label:"Update Financials",tooltip:"This document must be linked to one or more Leap CRM financial fields and saved to enable this.",value:!!c[Gs],disabled:!((w=e==null?void 0:e.linkedTypes)!=null&&w.includes("jobProgressFinancials")),onChange:C=>j(C)})]})]})},Ly=({templatesEdit:n,auth:{user:e,offices:s=[]}})=>({userEmail:(e==null?void 0:e.get("email"))||"",offices:s,template:n[n.currentWorkingId]}),Ey=n=>({setTemplateState:e=>n(ee(e)),pushToDataLayer:e=>n(Ot(e))}),Ay=Z(Ly,Ey)(My),Fy=n=>{const{urlParams:e,showSnapshotModal:s,showAlertModal:o,showLoader:a,onDocumentSave:i,history:l,hideLoader:r,customDocTypes:d,planId:c,maxTemplateCount:u,documentActionButton:p=!1}=n,h=Fe;return t.jsx(N,{sx:h.toolbarContainerTemp,children:t.jsxs(he,{direction:"row",alignItems:"center",sx:h.toolbar,children:[t.jsx(Qb,{history:l,showSnapshotModal:s,showAlertModal:o,showLoader:a,hideLoader:r,onDocumentSave:i,urlParams:e,customDocTypes:d,planId:c,maxTemplateCount:u}),t.jsx(sy,{}),t.jsx(Sy,{}),p&&t.jsx(Ay,{}),t.jsx(iy,{}),t.jsx(ry,{})]})})},Ry=({templatesEdit:n})=>{var e;return{documentActionButton:!!((e=n.featureFlags)!=null&&e.documentActionButton)}},_y=Z(Ry)(Fy),vd=n=>{const{children:e}=n,[s,o]=y.useState(!1);return t.jsxs("div",{onMouseDown:()=>o(!0),onMouseUp:()=>o(!1),children:[s&&t.jsx("div",{className:"net-wrapper-inner-net"}),e]})};vd.propTypes={children:b.oneOfType([b.arrayOf(b.node),b.node]).isRequired};const ve=n=>t.jsx(vd,{children:t.jsx(Ht.DebounceInput,{...n})}),By={0:"None",1:"Outside",2:"Inside & Outside",3:"Top & Bottom"},$y=[0,1,2,3],zy=({templateValues:n,editCellItem:e,setTemplateState:s})=>{const o=new $(n.toJSON()),a=o.getObjectWithId(e.objectId)||{};return t.jsxs(xe,{className:os,children:[t.jsx(_,{text:"App Title",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:a.appTitle,onChange:i=>{a.appTitle=i.target.value,s(o)}})}),t.jsx(_,{text:"PDF Title",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:a.title,onChange:i=>{a.title=i.target.value,s(o)}})}),t.jsx(_,{text:"Border",children:$y.map(i=>t.jsx(_,{text:By[i],active:a.border===i,onClick:()=>{a.border=0,s(o)}},`border-${i}`))})]})},Wy=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId]||new $({}),editCellItem:n.editCellItem}),Hy=n=>({setTemplateState:e=>n(ee(e))}),qy=Z(Wy,Hy)(zy);let va;
9const Ta=(n,e,s)=>{if(va=n,!n)return;const o=s(e);setTimeout(()=>{Ta(va,o,s)},10)},Zo=()=>{va=!1},Fn=({small:n,value:e,minValue:s,maxValue:o,onChange:a,increment:i,fill:l})=>t.jsx("div",{onMouseOut:()=>Zo(),children:t.jsxs(oc,{minimal:!0,fill:l,children:[t.jsx(Ae,{icon:"minus",disabled:e<=s,small:n,onMouseDown:()=>{Ta(!0,e,r=>{const d=s!==void 0?Math.max(r-i,s):r-i;return a(d),d})},onMouseUp:()=>Zo()}),t.jsx(Ae,{icon:"plus",disabled:e>=o,small:n,onMouseDown:()=>{Ta(!0,e,r=>{const d=o!==void 0?Math.min(r+i,o):r+i;return a(d),d})},onMouseUp:()=>Zo()})]})});Fn.propTypes={small:b.bool,value:b.number,minValue:b.number,maxValue:b.number,onChange:b.func.isRequired,increment:b.number,fill:b.bool};Fn.defaultProps={small:!1,value:0,minValue:void 0,maxValue:void 0,increment:1,fill:!1};const Vy={default:"Text",emptySpace:"Empty Space",image:"Image",companyLogo:"Company Logo"},Ky=()=>t.jsx(_,{style:{display:"none"},children:t.jsx(_,{})}),Uy=({templateValues:n,editCellItem:e,setTemplateState:s})=>{const o=new $(n.toJSON()),a=o.getObjectWithId(e.objectId)||{};return t.jsxs(xe,{className:os,children:[t.jsx(Ky,{}),t.jsxs(_,{text:"Cell Type",label:Vy[a.cellType],children:[t.jsx(_,{text:"Text",active:a.cellType==="default",onClick:()=>{a.cellType="default",(a.value==="%companyLogo%"||a.value==="%image%")&&(a.value=""),s(o)}}),t.jsx(_,{text:"Empty Space",active:a.cellType==="emptySpace",onClick:()=>{a.cellType="emptySpace",a.value="",a.emptySpaceHeight<1&&(a.emptySpaceHeight=4),s(o)}}),t.jsx(_,{text:"Image",active:a.cellType==="image",onClick:()=>{a.cellType="image",a.value="%image%",s(o)}}),t.jsx(_,{text:"Logo",active:a.cellType==="companyLogo",onClick:()=>{a.cellType="companyLogo",a.value="%companyLogo%",a.logoHeight<1&&(a.logoHeight=40),s(o)}})]}),a.cellType==="emptySpace"&&t.jsx(_,{text:"Empty Space Height",labelElement:t.jsx(Fn,{value:a.emptySpaceHeight,minValue:1,maxValue:1e3,increment:1,small:!0,onChange:i=>{console.log(i),a.emptySpaceHeight=i;const l=new $(o.toJSON());s(l)}})}),(a.cellType==="companyLogo"||a.cellType==="image")&&t.jsx(_,{text:"Image Height",labelElement:t.jsx(Fn,{value:a.logoHeight,minValue:1,maxValue:1e3,increment:1,small:!0,onChange:i=>{a.logoHeight=i;const l=new $(o.toJSON());s(l)}})})]})},Gy=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem}),Jy=n=>({setTemplateState:e=>n(ee(e))}
9),Yy=Z(Gy,Jy)(Uy),je=({text:n,active:e,onChange:s})=>t.jsx(_,{shouldDismissPopover:!1,text:n,label:t.jsx(Aa,{name:n,checked:e,onChange:()=>s(!e),className:"toggle-switch"})});je.propTypes={text:b.string,active:b.bool,onChange:b.func.isRequired};je.defaultProps={text:"",active:!1};const Xy=(n=[])=>n.sort((e,s)=>{const o=e.name.toUpperCase(),a=s.name.toUpperCase();return o<a?-1:o>a?1:0}),Js=(...n)=>{let e=[];return n.forEach(s=>{e=e.concat(s)}),e=e.filter(({placeholder:s})=>s),Xy(e)};class Zn extends J.Component{constructor(s){super(s);W(this,"fetchPlaceholders",async(s=[])=>{try{if(!s.length){this.setState({misc:[],items:[],options:[],upCharges:[]});return}const o=await se.Cloud.run("getPlaceholdersForMeasureSheetItems",{objectIds:s}),{miscDefault:a,itemDefault:i,itemPlaceholders:l,itemAdditionalDetails:r,optionDefault:d,optionPlaceholders:c,upChargeDefault:u,upChargePlaceholders:p,upChargeAdditionalDetails:h}=o,g={misc:Js(a),items:Js(i,l,r),options:Js(d,c),upCharges:Js(u,p,h)};this.setState(g)}catch(o){Be.show({message:o.message,timeout:5e3})}});this.state={selectedIndex:0,misc:[],items:[],options:[],upCharges:[]},this.fetchPlaceholders(s.itemIds)}componentWillReceiveProps(s){JSON.stringify(s.itemIds)!==JSON.stringify(this.props.itemIds)&&this.fetchPlaceholders(s.itemIds)}render(){return t.jsx(_,{text:"Linked Placeholders",disabled:this.props.disabled,className:this.props.disabled?"menu-item-disabled":"",children:t.jsxs("div",{className:"placeholders",children:[t.jsxs(oc,{className:"placeholders-buttons",fill:!0,children:[t.jsx(vn,{variant:this.state.selectedIndex===0?"solid":"outline",color:"dark",onClick:()=>this.setState({selectedIndex:0}),children:"Values"}),t.jsx(vn,{variant:this.state.selectedIndex===1?"solid":"outline",color:"dark",onClick:()=>this.setState({selectedIndex:1}),children:"Placeholders"})]}),t.jsxs("div",{className:"menu-items",style:{maxHeight:"90vh",maxWidth:"400px",overflowY:"auto",overflowX:"clip"},children:[this.state.misc.length>0&&t.jsxs(J.Fragment,{children:[t.jsx(xe.Divider,{title:"Misc"}),this.state.misc.map(({placeholder:s,name:o})=>t.jsx(_,{shouldDismissPopover:!1,text:this.state.selectedIndex===1?s:o,onClick:()=>{Us(s),Be.show({message:"Copied to clipboard!",timeout:1e3})}},s))]}),this.state.items.length>0&&t.jsxs(J.Fragment,{children:[t.jsx(xe.Divider,{title:"Item"}),this.state.items.map(({placeholder:s,name:o})=>t.jsx(_,{shouldDismissPopover:!1,text:this.state.selectedIndex===1?s:o||"(Blank Value)",onClick:()=>{Us(s),Be.show({message:"Copied to clipboard!",timeout:1e3})}},s))]}),this.state.options.length>0&&t.jsxs(J.Fragment,{children:[t.jsx(xe.Divider,{title:"Option"}),this.state.options.map(({placeholder:s,name:o})=>t.jsx(_,{shouldDismissPopover:!1,text:this.state.selectedIndex===1?s:o,onClick:()=>{Us(s),Be.show({message:"Copied to clipboard!",timeout:1e3})}},s))]}),this.state.upCharges.length>0&&t.jsxs(J.Fragment,{children:[t.jsx(xe.Divider,{title:"Up-Charge"}),this.state.upCharges.map(({placeholder:s,name:o})=>t.jsx(_,{shouldDismissPopover:!1,text:this.state.selectedIndex===1?s:o,onClick:()=>{Us(s),Be.show({message:"Copied to clipboard!",timeout:1e3})}},s))]})]})]})})}}Zn.propTypes={itemIds:b.arrayOf(b.string),disabled:b.bool};Zn.defaultProps={itemIds:[],disabled:!1};const Zy=async(n=[],e={})=>{if(!n.length)return[];const{enableShareablePriceGuide:s}=e;if(s)return[...n];const o=se.User.current();if(!o)throw new Error("User not found");const a=o.get("company"),i=100,l=[];for(let c=0;c<n.length;c+=i)l.push(n.slice(c,c+i));const d=(await Promise.all(l.map(async c=>{const u=new se.Query("SSMeasureSheetItem");return u.containedIn("objectId",c),u.equalTo("company",a),u.select([]),(await u.find()).map(h=>h.id)}))).flat();return n.includes("custom_product")&&d.push("custom_product"),d},Qy=async n=>{const{itemIds:e=[],enableShareablePriceGuide:s}=n;if(s)return e.includes("custom_product")?e.length-1:e.length;const o=se.User.current(),a=new se.Query("SSMeasureSheetItem");return a.containedIn("objectId",e),a.equalTo("company",o.get("company")),await a.count()},Td=(n={})=>{const{linkedMeasureSheetItemIds:e=[],objectId:s}=n,o=ft(),a=ze(d=>{var c,u;return(u=(c=d.templatesEdit)==null?void 0:c.featureFlags)==null?void 0:u.enableShareablePriceGuide}),[i,l]=y.useState(0),r=async d=>{try{const c=await Qy({itemIds:d,enableShareablePriceGuide:a}),p=(d==null?void 0:d.includes("custom_product"))?c+1:c;o($g({[s]:p})),l(p)}catch(c){o(Kt(c))}};return y.useEffect(()=>{r(e)},[s]),i},ej=n=>{switch(n){case 0:return"None";case 1:return"Alternate Rows";case 2:return"All Rows";default:return"None"}},qn={fenevision:"/fenetech/documents/section"},tj=n=>{switch(n){case qn.fenevision:return"Fenevision";default:return"None"}},nj=n=>{switch(n){case 0:return"Warning";case 1:return"Acknowledge";case 2:return"Block";default:return"Acknowledge"}},sj=({templateValues:n,editCellItem:e,setTemplateState:s,setShowLinkItems:o,syncPlacehoders:a,disableDocLinkingRestriction:i})=>{var j,S,w,C,v,I,D,F,M,R,P,k,T,B,L,H,G,ne,le,re,O,K,U;const l=new $(n.toJSON()),r=l.getObjectWithId(e.objectId)||{},{linkedMeasureSheetItemIds:d=[],objectId:c}=r,u=Td({objectId:c,linkedMeasureSheetItemIds:d}),p=y.useMemo(()=>{var q;return i?!1:!!((q=r==null?void 0:r.cellItems)!=null&&q.some(Y=>{var be,Se;return(be=Y==null?void 0:Y.linkedValueSettings)!=null&&be.objectId?!0:!!((Se=Y==null?void 0:Y.detailItems)!=null&&Se.some(te=>{var ge;return!!((ge=te==null?void 0:te.linkedValueSettings)!=null&&ge.objectId)}))}))},[r,i]),h="We do not support using this feature in the same content block as a 
9Linked Field at this time.",{manufacturers:g,isLoading:x,error:m}=ri({enabled:((j=r.downloadParams)==null?void 0:j.endpoint)===qn.fenevision}),f=g==null?void 0:g.find(A=>{var q,Y;return A.id===((Y=(q=r.downloadParams)==null?void 0:q.headers)==null?void 0:Y["x-manufacturer-id"])});return t.jsxs(xe,{className:os,children:[t.jsx(_,{text:"App Title",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:r.appTitle,onChange:A=>{r.appTitle=A.target.value,s(l)}})}),t.jsx(_,{text:"PDF Title",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:r.contractTitle,onChange:A=>{r.contractTitle=A.target.value,s(l)}})}),t.jsx(en,{}),t.jsx(je,{text:"Begin on New Page",active:r.newPage,onChange:A=>{r.newPage=A,s(l)}}),t.jsx(je,{text:"Draw Border",active:r.drawBorder,onChange:A=>{r.drawBorder=A,s(l)}}),t.jsx(je,{text:"Hidden In App",active:!r.userInputRequired,onChange:A=>{r.userInputRequired=!A,s(l)}}),t.jsx(je,{text:"Allow Copy/Paste",active:r.canAddMultiple,onChange:A=>{r.canAddMultiple=A,s(l)}}),t.jsxs(_,{text:"Shading Style",label:ej(r.shading),children:[t.jsx(_,{text:"None",shouldDismissPopover:!1,active:r.shading===0,onClick:A=>{r.shading=0,s(l)}}),t.jsx(_,{text:"Alternate Rows",shouldDismissPopover:!1,active:r.shading===1,onClick:A=>{r.shading=1,s(l)}}),t.jsx(_,{text:"All Rows",shouldDismissPopover:!1,active:r.shading===2,onClick:A=>{r.shading=2,s(l)}})]}),t.jsx(en,{}),t.jsxs(_,{text:"Integration",label:tj((S=r.downloadParams)==null?void 0:S.endpoint),children:[t.jsx(_,{text:"None",active:!((w=r.downloadParams)!=null&&w.endpoint),onClick:()=>{delete r.downloadParams,r.requiresDownload=!1,s(l)}}),t.jsx(_,{text:"Fenevision",active:((C=r.downloadParams)==null?void 0:C.endpoint)===qn.fenevision,onClick:()=>{r.requiresDownload=!0,r.downloadParams={...r.downloadParams,endpoint:qn.fenevision,body:{settings:{showTotals:!0,exceptionHandling:1}}},s(l)}})]}),((v=r.downloadParams)==null?void 0:v.endpoint)===qn.fenevision&&t.jsxs(t.Fragment,{children:[t.jsxs(_,{text:"Manufacturer",label:(f==null?void 0:f.name)||"None",children:[x&&t.jsx(Hs,{rowNumber:4}),!x&&m&&t.jsx(_,{text:"Error loading manufacturers",disabled:!0}),!x&&!m&&t.jsx(t.Fragment,{children:g&&g.length>0?g.map(A=>t.jsx(_,{text:A.name,active:(f==null?void 0:f.id)===A.id,onClick:()=>{r.downloadParams={...r.downloadParams,endpoint:qn.fenevision,headers:{"x-manufacturer-id":A.id}},s(l)}},A.id)):t.jsx(_,{text:"No manufacturers available",disabled:!0})})]}),t.jsx(je,{text:"Show Totals",active:(F=(D=(I=r.downloadParams)==null?void 0:I.body)==null?void 0:D.settings)==null?void 0:F.showTotals,onChange:A=>{var Y;const q=r.downloadParams||{};r.downloadParams={...q,body:{...q.body||{},settings:{...((Y=q.body)==null?void 0:Y.settings)||{},showTotals:A}}},s(l)}}),t.jsxs(_,{text:"Exception Handling",label:nj((P=(R=(M=r.downloadParams)==null?void 0:M.body)==null?void 0:R.settings)==null?void 0:P.exceptionHandling),children:[t.jsx(_,{text:"Warning",active:((B=(T=(k=r.downloadParams)==null?void 0:k.body)==null?void 0:T.settings)==null?void 0:B.exceptionHandling)===0,onClick:()=>{var q;const A=r.downloadParams||{};r.downloadParams={...A,body:{...A.body||{},settings:{...((q=A.body)==null?void 0:q.settings)||{},exceptionHandling:0}}},s(l)}}),t.jsx(_,{text:"Acknowledge",active:((G=(H=(L=r.downloadParams)==null?void 0:L.body)==null?void 0:H.settings)==null?void 0:G.exceptionHandling)===1||((re=(le=(ne=r.downloadParams)==null?void 0:ne.body)==null?void 0:le.settings)==null?void 0:re.exceptionHandling)===void 0,onClick:()=>{var q;const A=r.downloadParams||{};r.downloadParams={...A,body:{...A.body||{},settings:{...((q=A.body)==null?void 0:q.settings)||{},exceptionHandling:1}}},s(l)}}),t.jsx(_,{text:"Block",active:((U=(K=(O=r.downloadParams)==null?void 0:O.body)==null?void 0:K.settings)==null?void 0:U.exceptionHandling)===2,onClick:()=>{var q;const A=r.downloadParams||{};r.downloadParams={...A,body:{...A.body||{},settings:{...((q=A.body)==null?void 0:q.settings)||{},exceptionHandling:2}}},s(l)}})]})]}),t.jsx(en,{}),t.jsx(Q,{title:h,placement:"right",disableHoverListener:!p,disableFocusListener:!p,disableTouchListener:!p,children:t.jsx("span",{children:t.jsx(_,{text:"Linked Measure Sheet Items",label:u,disabled:p,className:p?"menu-item-disabled":"",onClick:()=>o(!0,"linkedMeasureSheetItemIds",!1,"Linked Items",!0)})})}),t.jsx(Q,{title:h,placement:"right",disableHoverListener:!p,disableFocusListener:!p,disableTouchListener:!p,children:t.jsx("span",{children:t.jsx(Zn,{itemIds:d,disabled:!d.length||p})})}),t.jsx(_,{text:"Sync Placeholders",disabled:!d.length,onClick:()=>a(d,e)})]})},oj=({templatesEdit:n={}})=>{var e;
9return{templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,disableDocLinkingRestriction:(e=n.featureFlags)==null?void 0:e.disableDocLinkingRestriction}},aj=n=>({setTemplateState:e=>n(ee(e)),setShowLinkItems:(e,s,o,a,i)=>n(Ut(e,s,o,a,i)),syncPlacehoders:(e,s)=>n($c(e,s))}),ij=Z(oj,aj)(sj),lj=document.createElement("div");document.body.appendChild(lj);class Ho extends J.Component{constructor(s){super(s);W(this,"onDragEnd",s=>{if(!s.destination)return;const o=Rc(this.props.values,s.source.index,s.destination.index);this.props.onChange(o)});W(this,"onClickPaste",()=>{const s=document.getElementById("picker-text-input");s.focus();const o=sn("picker-clip-board");o&&(s.value=o)});W(this,"onDeleteValue",s=>{const o=[...this.props.values];o.splice(s,1),this.props.onChange(o)});W(this,"onDrag",(s,o)=>{this.state.isDragging?o&&(this.isDragging||this.setState(()=>({isDragging:void 0}))):s&&!o&&this.setState(()=>({isDragging:!0}))});this.droppableId=Ce(10),bt(this.droppableId,o=>{const{destination:a={}}=o;if(a===null)return;const{droppableId:i}=a;i===this.droppableId&&this.onDragEnd(o)}),this.state={}}render(){return t.jsx(_,{popoverProps:{isOpen:this.state.isDragging},...this.props.menuItemProps,children:t.jsxs("div",{style:{maxWidth:"400px"},children:[t.jsx("span",{style:{margin:5},children:this.props.values.length?`(${this.props.values.length}) values enter`:""}),t.jsx("br",{}),t.jsx(ve,{element:fe,id:"picker-text-input",className:"form-control",placeholder:"Enter Picker Option",style:{minHeight:100,margin:"5px 0"},value:this.props.values.join(`
10`),onChange:s=>{const o=s.target.value.split(`
11`);this.props.onChange(o)}})]})})}}Ho.propTypes={values:b.arrayOf(b.string),onChange:b.func.isRequired};Ho.defaultProps={values:[]};const rj=["%selectedTotal%","%selectedTotalWholeNumber%","%financeOptionDealerFee%","%financeOptionInterestRate%","%financeOptionMinAmount%","%financeOptionMaxAmount%","%financeOptionPaymentMultiplier%","%financeOptionNumberOfPayments%","%financeOptionDownPayment%","%financeOptionDownPaymentNoZero%"];class Si extends J.Component{constructor(s){super(s);W(this,"onIdentifierSelected",async s=>{const o=`[${s}]`;this.insertStringAtCursorPosition(o)});W(this,"onPlaceholderSelected",s=>{this.insertStringAtCursorPosition(s)});W(this,"insertStringAtCursorPosition",async s=>{const{value:o}=this.props;let a=this.inputRef.selectionStart||o.length;const i=o.substring(0,a),l=o.substring(a),r=`${i}${s}${l}`;await this.props.onChange(r),this.inputRef.focus(),a+=s.length+2,this.inputRef.selectionStart=a,this.inputRef.selectionEnd=a});this.state={isOpen:void 0,showError:!1}}render(){const{contractObject:s,editCellItem:o,value:a,onChange:i,title:l="Formula"}=this.props;return t.jsxs(_,{text:l,shouldDismissPopover:!1,popoverProps:{isOpen:this.state.isOpen},onClick:()=>this.setState({isOpen:this.state.isOpen?void 0:!0}),children:[t.jsx(ve,{style:{backgroundColor:this.state.showError?"red":"transparent",color:this.state.showError?"white":"black"},element:"textarea",minLength:0,debounceTimeout:300,value:a,inputRef:r=>{this.inputRef=r},onChange:r=>{r.target.value.indexOf(`[${o.cellId}]`)===-1?(i(r.target.value),this.setState({showError:!1})):(i(r.target.value),this.setState({showError:!0}))}}),this.state.showError&&t.jsxs("p",{style:{color:"red"},children:['You can not reference the current cell "[',o.cellId,']"!']}),t.jsx(xe.Divider,{}),t.jsx(_,{text:"Identifiers",shouldDismissPopover:!1,children:s.getAllCellIdentifiers(this.props.excluding).map(r=>t.jsx(_,{text:r,shouldDismissPopover:!1,onClick:()=>this.onIdentifierSelected(r)},`cell-identifier-${r}`))}),t.jsx(_,{text:"Placeholders",shouldDismissPopover:!1,children:rj.map(r=>t.jsx(_,{text:r,shouldDismissPopover:!1,onClick:()=>this.onPlaceholderSelected(r)},`cell-placeholder-${r}`))})]})}}Si.propTypes={onChange:b.func.isRequired,value:b.string,contractObject:b.instanceOf($).isRequired,excluding:b.string};Si.defaultProps={value:"",excluding:void 0};const cj=({templatesEdit:n})=>({editCellItem:n.editCellItem}),dj=()=>({}),wa=Z(cj,dj)(Si),Gl=[{value:"default",text:"Standard Keyboard"},{value:"ccExpDate",text:"Credit Card Exp Date"},{value:"creditCard",text:"Credit Card Number"},{value:"currency",text:"Currency ($1.00)"},{value:"currencyWhole",text:"Currency ($1)"},{value:"datePicker",text:"Date Picker"},{value:"dateTimePicker",text:"Date & Time"},{value:"timePicker",text:"Time"},{value:"email",text:"Email Address"},{value:"numbers",text:"Number Keyboard"},{value:"keypad",text:"Number Pad (1)"},{value:"keypadDecimal",text:"Number Pad (1.00)"},{value:"phone",text:"Phone Number"},{value:"picker",text:"Picker"},{value:"sizePicker",text:"Size Picker"},{value:"3DSizePicker",text:"3D Size Picker"},{value:"financeOptionsPicker",text:"Finance Options Picker"},{value:"statePicker",text:"State Picker"},{value:"zipCode",text:"Zip Code"}],To=({hideValues:n,options:e,title:s,object:o,onChange:a,inactiveOptions:i,onDelete:l,hideInputType:r,hideDefaultValue:d})=>{const c={...o};return t.jsx("div",{className:"dy-object-editor",children:t.jsx(_,{shouldDismissPopover:!1,text:s,labelElement:l&&t.jsx(Ae,{icon:"small-cross",minimal:!0,small:!0,onClick:l}),children:t.jsxs("div",{children:[!n&&t.jsxs(_,{shouldDismissPopover:!1,text:"Dependent Values",label:`${c.values.length}`,children:[e.length>0&&e.map((u,p)=>t.jsx(_,{shouldDismissPopover:!1,text:u,active:o.values.indexOf(u)>-1,disabled:i.indexOf(u)>-1,onClick:()=>{const h=c.values||[],g=h.filter(x=>x!==u);h.length===g.length&&g.push(u),c.values=g,a(c)}},`${u}-${p}`)),!e.length&&t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:c.values[0],onChange:u=>{const p=c.values||[];p[0]=u.target.value,c.values=p,a(c)}})]}),!n&&t.jsx(xe.Divider,{}),t.jsx(je,{text:"Show Cell",active:c.enabled,onChange:u=>{c.enabled=u,a(c)}}),t.jsx(je,{text:"Required",active:c.required,onChange:u=>{c.required=u,a(c)}}),c.enabled&&!r&&t.jsx(_,{shouldDismissPopover:!1,text:"Input Type",label:(Gl.find(({value:u})=>u===c.inputType)||{text:c.inputType}).text,children:Gl.map(({value:u,text:p})=>t.jsx(_,{text:p,shouldDismissPopover:!1,active:c.inputType===u,onClick:()=>{c.inputType=u,a(c)}},u))}),(c.inputType==="picker"||c.inputType==="multiSelectPicker")&&!r&&t.jsx(Ho,{values:c.pickerValues,onChange:u=>{c.pickerValues=u,a(c)},menuItemProps:{text:"Picker Options",label:c.pickerValues?c.pickerValues.length:"0",shouldDismissPopover:!1}}),(c.inputType==="sizePicker"||c.inputType==="3DSizePicker")&&!r&&t.jsx(_,{text:"Fraction Digits",label:X.fractionDigitsLabelForFractionDigits(o.fractionDigits),children:X.fractionDigits.map(u=>t.jsx(_,{text:X.fractionDigitsLabelForFractionDigits(u),shouldDismissPopover:!1,active:c.fractionDigits===u,icon:c.fractionDigits===u?"dot":"blank",onClick:()=>{c.fractionDigits=u,a(c)}},u))}),!d&&t.jsx("div",{children:t.jsx(_,{text:"Default Value",label:c.defaultValue,shouldDismissPopover:!1,children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:c.defaultValue,onChange:u=>{c.defaultValue=u.target.value,a(c)}})})})]})})})};To.propTypes={hideValues:b.bool,object:b.shape({inputType:b.string.isRequired,enabled:b.bool,required:b.bool,values:b.arrayOf(b.string),fractionDigits:b.string,pickerValues:b.arrayOf(b.string)}).isRequired,onChange:b.func.isRequired,title:b.oneOfType([b.string,b.arrayOf(b.string)]).isRequired,options:b.arrayOf(b.string),inactiveOptions:b.arrayOf(b.string),onDelete:b.func,hideInputType:b.bool,hideDefaultValue:b.bool};To.defaultProps={hideValues:!1,options:[],inactiveOptions:[],onDelete:void 0,hideInputType:!1,hideDefaultValue:!1};const uj=(n,e)=>e.length&&n.length&&n.filter(s=>!e.includes(s)).length===0;class is extends J.Component{constructor(e){super(e),this.inputRef=J.createRef(),this.state={isOpen:void 0,showDefault:!0}}render(){const{contractObject:e,cellItem:s,onChange:o}=this.props,a={...s},i=a.dynamicInputType?{...a.dynamicInputType}:{};i.objects=i.objects||[];let l=i.objects.find(({values:u=[]})=>u.indexOf("default")===0);l||(l={inputType:"default",enabled:!1,required:!1,values:["default"],fractionDigits:"",pickerValues:[]},i.objects.unshift(l));const r=i.objects.filter(({values:u=[]})=>u.indexOf("default")===-1),d=e.dynamicValueOptionsForCellId(i.cellId),c=[];return r.forEach(({values:u=[]})=>{u.forEach(p=>c.push(p))}),t.jsx("div",{className:"dy-object-editor",children:t.jsxs(_,{text:"Dynamic Settings",shouldDismissPopover:!1,popoverProps:{isOpen:this.state.isOpen},onClick:()=>this.setState({isOpen:this.state.isOpen?void 0:!0}),children:[t.jsx(_,{text:"Dependent Cell",label:i.cellId,shouldDismissPopover:!1,children:e.getAllCellIdentifiers(s.cellId).slice(0).reverse().map(u=>t.jsx(_,{shouldDismissPopover:!1,text:u,active:u===i.cellId,onClick:()=>{o({...i,cellId:u})}},`dynamic-${u}`))}),t.jsx(xe.Divider,{}),t.jsx(_,{text:"Conditions",shouldDismissPopover:!1,labelElement:t.jsx(Ae,{icon:"plus",minimal:!0,small:!0,disabled:uj(d,c),onClick:()=>{i.objects.push({inputType:"default",enabled:!0,required:!1,values:[],fractionDigits:"",pickerValues:[]}),o(i)}})}),t.jsx(xe.Divider,{}),this.state.showDefault&&t.jsx(To,{title:"Default",menuKey:"Default",openSubMenu:this.openSubMenu,object:l,hideValues:!0,onChange:u=>{i.objects[0]=u,o(i)}}),this.state.showDefault&&r.map((u,p)=>{const{values:h=[]}=u,g=h.length>1?h.join(", "):h.join(""),x=c.filter(j=>h.indexOf(j)===-1),m=s.cellType!=="textShort"&&s.cellType!=="textLong"&&s.cellType!=="textXLong",f=s.cellType==="imagePicker";return t.jsx(To,{title:g,object:u,options:d,inactiveOptions:x,hideInputType:m,hideDefaultValue:f,onChange:j=>{i.objects[p+1]=j,o(i)},onDelete:()=>{i.objects.splice(p+1,1),o(i)}},`dynamic-${s.objectId}-${p}`)})]})})}}is.propTypes={onChange:b.func.isRequired,cellItem:b.instanceOf(X).isRequired,contractObject:b.instanceOf($).isRequired};const wd=({children:n,condition:e})=>e?t.jsx(J.Fragment,{children:n}):t.jsx(J.Fragment,{});wd.propTypes={children:b.shape({}).isRequired,condition:b.bool.isRequired};const Vs=n=>{const{object:e,contractObject:s}=n;return t.jsxs(wd,{condition:e.toolboxKey!=="body-detail-cell",children:[t.jsx(xe.Divider,{}),t.jsx(je,{text:"Initials Required",active:e.initialsRequired,onChange:o=>{e.initialsRequired=o,n.setTemplateState(s)}}),t.jsx(_,{text:"Initials Note",disabled:!e.initialsRequired,children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:e.initialsNote,onChange:o=>{e.initialsNote=o.target.value,n.setTemplateState(s)}})})]})};Vs.propTypes={object:b.shape({toolboxKey:b.string.isRequired,initialsNote:b.string.isRequired,initialsRequired:b.bool.isRequired}).isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired};const pj=(n,e)=>{const s=e[n];return s&&(s>1e3||s<1)?"value must be between 1 and 1000":hj(n,e)},hj=(n,e)=>{const s=e[n];if(s||s==0)if(n.indexOf("min")==0){const a=n.replace("min","max"),i=e[a];if(i==0||i)return parseFloat(i)<parseFloat(s)?`${n} must be less than ${a}`:""}else{const a=n.replace("max","min"),i=e[a];if(i==0||i)return parseFloat(i)>parseFloat(s)?`${n} must be greater than ${a}`:""}return""},Ln=n=>{const[e,s]=y.useState(!1),{name:o,onChange:a=()=>{},sizeSpec:i={},...l}=n;return t.jsxs(J.Fragment,{children:[e&&t.jsxs("p",{className:"danger",children:[" ",e]}),t.jsx(Ht.DebounceInput,{...l,minLength:0,debounceTimeout:300,onChange:r=>{const{target:{value:d}}=r,c={...i,[o]:d},u=pj(o,c);u?s(u):(a(r),s(void 0))}})]})};Ln.propTypes={name:b.string.isRequired,onChange:b.func.isRequired,sizeSpec:b.shape({}).isRequired};const kd=n=>{const{object:e,setTemplateState:s,contractObject:o}=n,a=(i,l)=>{const{value:r}=i.target;e[l]=isNaN(parseFloat(r))?"":parseFloat(r),s(o)};return t.jsxs(J.Fragment,{children:[e.inputType==="unitedInchPicker"&&t.jsx(_,{text:"United Inch Suffix",shouldDismissPopover:!1,label:e.unitedInchSuffix,children:t.jsx(Ht.DebounceInput,{minLength:0,debounceTimeout:300,value:e.unitedInchSuffix,onChange:i=>{e.unitedInchSuffix=i.target.value,s(o)}})}
11),t.jsx(_,{text:"Min Width",shouldDismissPopover:!1,label:e.minSizePickerWidth,children:t.jsx(Ln,{sizeSpec:e,name:"minSizePickerWidth",minLength:0,debounceTimeout:300,value:e.minSizePickerWidth,onChange:i=>{a(i,"minSizePickerWidth")}})}),t.jsx(_,{text:"Max Width",shouldDismissPopover:!1,label:e.maxSizePickerWidth,children:t.jsx(Ln,{sizeSpec:e,name:"maxSizePickerWidth",minLength:0,debounceTimeout:300,value:e.maxSizePickerWidth,onChange:i=>{a(i,"maxSizePickerWidth")}})}),t.jsx(_,{text:"Min Height",shouldDismissPopover:!1,label:e.minSizePickerHeight,children:t.jsx(Ln,{sizeSpec:e,name:"minSizePickerHeight",minLength:0,debounceTimeout:300,value:e.minSizePickerHeight,onChange:i=>{a(i,"minSizePickerHeight")}})}),t.jsx(_,{text:"Max Height",shouldDismissPopover:!1,label:e.maxSizePickerHeight,children:t.jsx(Ln,{sizeSpec:e,name:"maxSizePickerHeight",minLength:0,debounceTimeout:300,value:e.maxSizePickerHeight,onChange:i=>{a(i,"maxSizePickerHeight")}})}),e.inputType==="3DSizePicker"&&t.jsxs(J.Fragment,{children:[t.jsx(_,{text:"Min Depth",shouldDismissPopover:!1,label:e.minSizePickerDepth,children:t.jsx(Ln,{sizeSpec:e,name:"minSizePickerDepth",minLength:0,debounceTimeout:300,value:e.minSizePickerDepth,onChange:i=>{a(i,"minSizePickerDepth")}})}),t.jsx(_,{text:"Max Depth",shouldDismissPopover:!1,label:e.maxSizePickerDepth,children:t.jsx(Ln,{sizeSpec:e,name:"maxSizePickerDepth",minLength:0,debounceTimeout:300,value:e.maxSizePickerDepth,onChange:i=>{a(i,"maxSizePickerDepth")}})})]})]})};kd.propTypes={object:b.any.isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired};const Ls=n=>{const{value:e={},disabled:s,onLinkedFieldDelete:o,enableLinkingGroups:a}=n,{objectId:i="",overwritePriority:l=1e3}=e,[r,d]=y.useState([]),[c,u]=y.useState(""),[p,h]=y.useState(""),[g,x]=y.useState(""),[m,f]=y.useState(""),[j,S]=y.useState(""),[w,C]=y.useState(!1),[v,I]=y.useState(!1),{showConfirmationModal:D,setLoa
11ding:F,hideConfirmationModal:M}=Jh(),R=O=>O.sort((K,U)=>{const A=K.get("name").toUpperCase(),q=U.get("name").toUpperCase();return A<q?-1:A>q?1:0}),P=async()=>{try{const O=se.User.current(),K=O==null?void 0:O.get("company"),U=new se.Query("LinkedValueObject");U.equalTo("company",K),U.select("name","cellTypes","inputTypes");const A=[];await U.each(ce=>{A.push(ce),ce.id===i&&x(ce.get("name"))});const q=R(A),Y=lt.uniqBy(q,ce=>ce.get("name"));d(Y)}catch(O){Be.show({message:O.message,timeout:5e3})}},k=y.useCallback(async O=>{try{if(!r.some(U=>U.get("name")===O)){const U=new se.Object("LinkedValueObject");await U.save({name:O});const A=R([...r,U]);d(A),G(U)}}catch(K){Be.show({message:K.message,timeout:5e3})}},[r]),T=async(O,K)=>{try{if(!r.some(A=>A.get("name")===K)){O.get("name")===g&&x(K);const A=await new se.Query("LinkedValueObject").get(O.id);A.set("name",K),await A.save(),n.onChange({objectId:A.id,overwritePriority:l})}h(""),S("")}catch(U){Be.show({message:U.message,timeout:5e3})}},B=y.useCallback(async O=>{try{const K=r.filter(A=>A.id!==O),U=new se.Object("LinkedValueObject");U.id=O,await U.destroy(),d(K),await o(O),Be.show({message:"Deleted Item Successfully!",timeout:5e3})}catch(K){Be.show({message:K.message,timeout:5e3})}},[r]),L=()=>{const O=r.find(K=>K.id===m);return O?O.get("name"):""},H=O=>{const K=L();D({title:`Delete ${K}?`,msg:`Deleting ${K} will remove the Linked
12              Value from all document templates for all users and remove the
13              option from Results forms.`,titleColor:"error",cancelText:"Cancel",confirmText:"Delete",confirmBtnColor:"error",disableCloseOnConfirm:!0,onConfirm:async()=>{F(!0),await B(O),F(!1),M()}})},G=O=>{O.id?(f(O.id),x(O.get("name")),n.onChange({objectId:O.id,cellTypes:O.get("cellTypes"),inputTypes:O.get("inputTypes"),overwritePriority:l})):(x(""),f(""),n.onChange({objectId:"",overwritePriority:l}))},ne=y.useCallback(O=>{p.length>0&&T(O,p)},[p]),le=y.useCallback((O,K)=>{O.key==="Enter"&&ne(K)},[ne]),re=({id:O,name:K})=>t.jsxs("div",{className:"linked-menu-icons-container",children:[t.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),h(K),S(O)},className:"linked-menu-edit-item-icons",children:t.jsx(Ct,{icon:["far","edit"],className:"linked-menu-icon-disk"})}),t.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),H(O)},className:"linked-menu-edit-item-icons",children:t.jsx(Ct,{icon:["far","trash"],className:"linked-menu-icon-trash"})})]});return y.useEffect(()=>{P()},[]),t.jsx(J.Fragment,{children:a?t.jsxs("div",{className:s?"menu-item-disabled":"",onMouseLeave:()=>u(""),children:[t.jsx("div",{className:"linked-menu-header",children:g&&t.jsxs("span",{children:["Selected: ",t.jsx("em",{children:g})]})}),t.jsx("div",{className:"linked-menu-container",children:t.jsxs("div",{className:"linked-menu-input-wrapper",children:[t.jsx("input",{type:"text",placeholder:"Create Linked Field",onChange:O=>u(O.target.value),value:c,onMouseEnter:()=>C(!0),onMouseLeave:()=>C(!1),onKeyDown:O=>{C(!0),O.key==="Enter"&&O.target.value.length>0&&(k(c),u(""))},className:"linked-menu-input-main"}),w&&t.jsx("button",{type:"button",onMouseEnter:()=>C(!0),onMouseLeave:()=>C(!1),onClick:()=>{c.length>0&&(k(c),u(""))},className:"linked-menu-button-icon",children:t.jsx(Ct,{icon:["far","floppy-disk"],className:"linked-menu-icon-disk"})})]})}),t.jsxs("div",{className:"linked-menu-list-container",children:[!!lt.size(r)&&t.jsx(_,{text:"None",active:g==="",onClick:()=>G(""),onMouseEnter:()=>f(""),textClassName:"linked-object-none"},"linked-object-none"),lt.size(r)?r.map(O=>t.jsx("div",{onClick:()=>G(O),onMouseEnter:()=>f(O.id),className:"linked-menu-list",children:j!==O.id?t.jsx(_,{text:O.get("name"),active:g===O.get("name"),onClick:()=>x(O.get("name")),label:m===O.id?t.jsx(re,{id:O.id,name:O.get("name")}):null,textClassName:"linked-object-text"},m):t.jsxs("div",{className:"linked-menu-input-wrapper",children:[t.jsx("input",{type:"text",placeholder:"Create Linked Field",onChange:K=>{h(K.target.value)},defaultValue:O.get("name"),onKeyDown:K=>{I(!0),le(K,O)},onMouseEnter:()=>{I(!0)},onMouseLeave:()=>I(!1),className:"linked-menu-input-secondary"}),v&&t.jsx("button",{type:"button",onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),onClick:()=>ne(O),className:"linked-menu-button-icon",children:t.jsx(Ct,{icon:["far","floppy-disk"],className:"linked-menu-icon-disk"})})]})},O.id)):t.jsx("p",{className:"linked-menu-no-objects",children:"No Linked Field"})]})]}):t.jsxs(_,{text:"Linked Field",label:g,onMouseLeave:()=>u(""),disabled:s,className:s?"menu-item-disabled":"",children:[t.jsx("div",{className:"linked-menu-container",children:t.jsxs("div",{className:"linked-menu-input-wrapper",children:[t.jsx("input",{type:"text",placeholder:"Create Linked Field",onChange:O=>u(O.target.value),value:c,onMouseEnter:()=>C(!0),onMouseLeave:()=>C(!1),onKeyDown:O=>
13{C(!0),O.key==="Enter"&&O.target.value.length>0&&(k(c),u(""))},className:"linked-menu-input-main"}),w&&t.jsx("button",{type:"button",onMouseEnter:()=>C(!0),onMouseLeave:()=>C(!1),onClick:()=>{c.length>0&&(k(c),u(""))},className:"linked-menu-button-icon",children:t.jsx(Ct,{icon:["far","floppy-disk"],className:"linked-menu-icon-disk"})})]})}),t.jsxs("div",{className:"linked-menu-list-container",children:[!!lt.size(r)&&t.jsx(_,{text:"None",active:g==="",onClick:()=>G(""),onMouseEnter:()=>f(""),textClassName:"linked-object-none"},"linked-object-none"),lt.size(r)?r.map(O=>t.jsx("div",{onClick:()=>G(O),onMouseEnter:()=>f(O.id),className:"linked-menu-list",children:j!==O.id?t.jsx(_,{text:O.get("name"),active:g===O.get("name"),onClick:()=>x(O.get("name")),label:m===O.id?t.jsx(re,{id:O.id,name:O.get("name")}):null,textClassName:"linked-object-text"},m):t.jsxs("div",{className:"linked-menu-input-wrapper",children:[t.jsx("input",{type:"text",placeholder:"Create Linked Field",onChange:K=>{h(K.target.value)},defaultValue:O.get("name"),onKeyDown:K=>{I(!0),le(K,O)},onMouseEnter:()=>{I(!0)},onMouseLeave:()=>I(!1),className:"linked-menu-input-secondary"}),v&&t.jsx("button",{type:"button",onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),onClick:()=>ne(O),className:"linked-menu-button-icon",children:t.jsx(Ct,{icon:["far","floppy-disk"],className:"linked-menu-icon-disk"})})]})},O.id)):t.jsx("p",{className:"linked-menu-no-objects",children:"No Linked Field"})]})]})})};Ls.propTypes={value:b.shape({objectId:b.string.isRequired,overwritePriority:b.number.isRequired}).isRequired,onChange:b.func.isRequired,enableLinkingGroups:b.bool};Ls.defaultProps={enableLinkingGroups:!1};const mj=({cellType:n,inputType:e})=>{const s=["textShort","textLong","textXLong"],o=["picker","multiSelectPicker"];return s.indexOf(n)>-1&&o.indexOf(e)>-1},gj=n=>{const{inputType:e}=n;switch(e){case"timePicker":return"Time Format";default:return"Date Format"}},xj=(n,e)=>{const{cellType:s}=n;switch(s){case"textXLong":return["default","textFormula"];default:return e}};let vi=class extends J.Component{constructor(e){super(e),this.state={slideOutIsOpen:!1,slideOutKey:"",elementState:[]}}render(){var S,w,C,v,I,D,F,M,R,P,k,T,B,L,H,G,ne,le,re;const{object:e,contractObject:s,setTemplateState:o,setShowLinkItems:a,enableDocLinking:i,enableLinkingGroups:l,disableDocLinkingRestriction:r,showDaysOutSetting:d}=this.props;let c=e!=null&&e.dateFormulaWeekdays?[...e.dateFormulaWeekdays]:["Monday","Tuesday","Wednesday","Thursday","Friday"];const u=(O,K)=>{O?c.push(K):c=lt.pull(c,K),e.dateFormulaWeekdays=c,o(s)},p=xj(e,X.inputTypes),h=!!(e.linkedMeasureSheetItem||(S=e.measureSheetItemQuantityIds)!=null&&S.length||(w=e.measueSheetItemTotalIds)!=null&&w.length||(C=e.parent.linkedMeasureSheetItemIds)!=null&&C.length||(v=e.parent.parent.linkedMeasureSheetItemIds)!=null&&v.length),g="We do not support using this feature in the same content block as a Linked Field at this time.",x=r?!0:!((I=e.linkedValueSettings)!=null&&I.objectId),m="We do not support using a Linked Field in the same content block as another Linked Item type at this time.",f=r?!0:!h,j=O=>{var K,U,A,q;return((U=(K=e==null?void 0:e.linkedValueSettings)==null?void 0:K.inputTypes)==null?void 0:U.length)&&!((q=(A=e==null?void 0:e.linkedValueSettings)==null?void 0:A.inputTypes)!=null&&q.includes(O))};return t.jsxs(y.Fragment,{children:[e.cellType!=="switched"&&t.jsx(_,{text:"Input Type",label:X.inputTypeLabelForInputType(e.inputType),children:p.map(O=>t.jsx(Q,{placement:"right",title:"This is incompatible with the selected linked field.",disableHoverListener:!j(O),disableFocusListener:!j(O),disableTouchListener:!j(O),children:t.jsx("span",{children:t.jsx(_,{className:j(O)?"menu-item-disabled":"",disabled:j(O),text:X.inputTypeLabelForInputType(O),shouldDismissPopover:!1,active:e.inputType===O,onClick:()=>{e.inputType=O,o(s)}})})},O))}),(e.inputType==="datePicker"||e.inputType==="dateTimePicker"||e.inputType==="timePicker")&&t.jsx(_,{text:gj(e),label:e.dateDisplayFormat,children:t.jsx(Ht.DebounceInput,{minLength:0,placeholder:_c[e.inputType],debounceTimeout:300,value:e.dateDisplayFormat,onChange:O=>{e.dateDisplayFormat=O.target.value,o(s)}})}),e.inputType==="dateFormula"&&t.jsxs(_,{text:"Date Formula Settings",label:d&&e.dateFormulaDaysOut?e.dateFormulaDaysOut:"",children:[d&&t.jsxs("div",{children:[t.jsx("div",{children:t.jsx("p",{className:"inputLabel",children:t.jsx("b",{children:"Days Out"})})}),t.jsx(Ht.DebounceInput,{minLength:0,placeholder:"Days Out",debounceTimeout:300,value:e.dateFormulaDaysOut,type:"number",onChange:O=>{e.dateFormulaDaysOut=parseInt(O.target.value),o(s)}}),t.jsx(xe.Divider,{})]}),t.jsx("div",{children:t.jsx("p",{className:"inputLabel",children:t.jsx("b",{children:"Business Day(s)"})})}),Yg.map(O=>{const K=c.indexOf(O)>-1;return t.jsx(_,{text:t.jsxs("div",{className:"weekday-item",children:[t.jsx(Rt,{onChange:U=>{const A=U.target.checked;u(A,O)},checked:!!K,className:"submenu-checkbox"}),t.jsx("div",{className:"weekday-label",onClick:()=>{u(!K,O)},children:O})]}),shouldDismissPopover:!1},O)})]}),mj(e)&&t.jsx(Ho,{values:e.pickerValues,onChange:O=>{e.pickerValues=O,o(s)},menuItemProps:{text:"Picker Options",label:e.pickerValues?e.pickerValues.length:"0",shouldDismissPopover:!1}}
13),e.inputType==="multiSelectPicker"&&t.jsx(_,{text:"Multi-Select Separator",label:e.multiSelectorSeparator,children:t.jsx(Ht.DebounceInput,{minLength:0,debounceTimeout:300,value:e.multiSelectorSeparator,placeholder:'i.e. ", "',onChange:O=>{e.multiSelectorSeparator=O.target.value,o(s)}})}),(e.inputType==="sizePicker"||e.inputType==="3DSizePicker")&&t.jsx(_,{text:"Fraction Digits",label:X.fractionDigitsLabelForFractionDigits(e.fractionDigits),children:X.fractionDigits.map(O=>t.jsx(_,{text:X.fractionDigitsLabelForFractionDigits(O),shouldDismissPopover:!1,active:e.fractionDigits===O,onClick:()=>{e.fractionDigits=O,o(s)}},O))}),(e.inputType==="unitedInchPicker"||e.inputType==="sizePicker"||e.inputType==="3DSizePicker")&&t.jsx(kd,{object:e,setTemplateState:o,contractObject:s}),e.cellType==="switched"&&t.jsx(je,{text:"Dynamic",active:e.inputType==="dynamic",onChange:O=>{e.inputType=O?"dynamic":"",o(s)}}),e.inputType==="dynamic"&&t.jsx(is,{contractObject:s,cellItem:e,onChange:O=>{e.dynamicInputType=O,o(s)}}),e.isCurrencyCell&&t.jsx(je,{text:"Is Total Sale Amount",active:e.isTotalSaleAmount,onChange:O=>{e.isTotalSaleAmount=O,o(s)}}),t.jsx(xe.Divider,{}),e.cellType==="switched"&&t.jsx(_,{text:"On Value",shouldDismissPopover:!1,label:e.switchValueOn,children:t.jsx(Ht.DebounceInput,{minLength:0,debounceTimeout:300,value:e.switchValueOn,placeholder:"YES",onChange:O=>{e.switchValueOn=O.target.value,o(s)}})}),e.cellType==="switched"&&t.jsx(_,{text:"Off Value",shouldDismissPopover:!1,label:e.switchValueOff,children:t.jsx(Ht.DebounceInput,{minLength:0,debounceTimeout:300,value:e.switchValueOff,placeholder:"NO",onChange:O=>{e.switchValueOff=O.target.value,o(s)}})}),e.cellType==="switched"&&t.jsx(xe.Divider,{}),t.jsx(je,{text:"Required",active:e.required,onChange:O=>{e.required=O,o(s)}}),t.jsx(je,{text:"Hide In App",active:e.hidden,onChange:O=>{e.hidden=O,o(s)}}),t.jsx(je,{text:"Hide On PDF",active:e.appOnly,onChange:O=>{e.appOnly=O,o(s)}}),t.jsx(je,{text:"Disable Editing",active:e.inputDisabled,onChange:O=>{e.inputDisabled=O,o(s)}}),t.jsx(xe.Divider,{}),!e.titleLinked&&t.jsxs(J.Fragment,{children:[t.jsx(_,{text:t.jsxs("span",{children:["App Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{e.titleLinked=!0,e.contractTitle=e.appTitle,o(s)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:e.appTitle,onChange:O=>{e.appTitle=O.target.value,o(s)}})}),t.jsx(_,{text:t.jsxs("span",{children:["PDF Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{e.titleLinked=!0,e.appTitle=e.contractTitle,o(s)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:e.contractTitle,onChange:O=>{e.contractTitle=O.target.value,o(s)}})})]}),e.titleLinked&&t.jsx(_,{text:t.jsxs("span",{children:["Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"lock",onClick:()=>{e.titleLinked=!1,o(s)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:e.contractTitle,onChange:O=>{e.contractTitle=O.target.value,o(s)}})}),t.jsx(_,{text:"App Note",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:e.appNote,onChange:O=>{e.appNote=O.target.value,o(s)}})}),t.jsx(xe.Divider,{}),e.isFormulaCell&&t.jsxs(J.Fragment,{children:[t.jsx(wa,{contractObject:s,value:e.formula,onChange:O=>{e.formula=O,o(s)},excluding:e.cellId}),t.jsx(je,{text:"Clear Value If Zero",active:!!e.clearValueIfZero,onChange:O=>{e.clearValueIfZero=O,o(s)}})]}),!e.isFormulaCell&&(e.inputType==="textFormula"?t.jsx(wa,{title:"Default Value",contractObject:s,value:e.value,onChange:O=>{e.value=O,o(s)},excluding:e.cellId}):t.jsx(_,{text:"Default Value",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:e.value,onChange:O=>{e.value=O.target.value,o(s)}})})),t.jsx(je,{text:"Hide If Left Blank",active:!e.drawIfEmpty,onChange:O=>{e.drawIfEmpty=!O,o(s)}}),t.jsx(_,{text:"Value If Left Blank",disabled:!e.drawIfEmpty,children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:e.emptyValue,onChange:O=>{e.emptyValue=O.target.value,o(s)}})}),t.jsx(Vs,{object:e,setTemplateState:o,contractObject:s}),t.jsx(xe.Divider,{}),l?t.jsxs(t.Fragment,{children:[t.jsxs(_,{text:"Link from Estimate",children:[t.jsx(Q,{title:g,placement:"right",disableHoverListener:x,disableFocusListener:x,disableTouchListener:x,children:t.jsx("span",{children:t.jsx(_,{text:"Link Measure Sheet Item",onClick:()=>a(!0,"linkedMeasureSheetItem",!0,"Link Measure Sheet Item"),label:e.linkedMeasureSheetItem?"Linked":"",disabled:r?!1:(D=e.linkedValueSettings)==null?void 0:D.objectId,className:(F=e.linkedValueSettings)!=null&&F.objectId&&
13!r?"menu-item-disabled":""})})}),t.jsx(Q,{title:g,placement:"right",disableHoverListener:x,disableFocusListener:x,disableTouchListener:x,children:t.jsx("span",{children:t.jsx(Zn,{itemIds:[e.linkedMeasureSheetItem],disabled:!e.linkedMeasureSheetItem||(r?!1:(M=e.linkedValueSettings)==null?void 0:M.objectId)})})}),t.jsx(Q,{title:g,placement:"right",disableHoverListener:x,disableFocusListener:x,disableTouchListener:x,children:t.jsx("span",{children:t.jsx(_,{text:"Link Quantities",onClick:()=>a(!0,"measureSheetItemQuantityIds",!1,"Link Quantities"),label:e.measureSheetItemQuantityIds?e.measureSheetItemQuantityIds.length:"",disabled:r?!1:(R=e.linkedValueSettings)==null?void 0:R.objectId,className:(P=e.linkedValueSettings)!=null&&P.objectId&&!r?"menu-item-disabled":""})})}),t.jsx(Q,{title:g,placement:"right",disableHoverListener:x,disableFocusListener:x,disableTouchListener:x,children:t.jsx("span",{children:t.jsx(_,{text:"Link Totals",onClick:()=>a(!0,"measueSheetItemTotalIds",!1,"Link Totals"),label:e.measueSheetItemTotalIds?e.measueSheetItemTotalIds.length:"",disabled:r?!1:(k=e.linkedValueSettings)==null?void 0:k.objectId,className:(T=e.linkedValueSettings)!=null&&T.objectId&&!r?"menu-item-disabled":""})})})]}),e.cellType!=="switched"&&i&&t.jsx(_,{text:"Link to Documents or Results",children:t.jsx(Q,{title:m,placement:"right",disableHoverListener:f,disableFocusListener:f,disableTouchListener:f,children:t.jsx("span",{children:t.jsx(Ls,{disabled:r?!1:h,value:e.linkedValueSettings,enableLinkingGroups:l,onChange:({objectId:O,overwritePriority:K,cellTypes:U,inputTypes:A})=>{e.linkedValueSettings={objectId:O,overwritePriority:K,cellTypes:U,inputTypes:A},o(s)},onLinkedFieldDelete:O=>{const{contractData:K}=s,U=El(K,{[O]:""});s.contractData=U,o(new $(s))}})})})})]}):t.jsxs(t.Fragment,{children:[e.cellType!=="switched"&&i&&t.jsx(Q,{title:"We do not support using a Linked Field in the same content block as another Linked Item type at this time.",placement:"right",disableHoverListener:!h,disableFocusListener:!h,disableTouchListener:!h,children:t.jsx("span",{children:t.jsx(Ls,{disabled:r?!1:h,value:e.linkedValueSettings,enableLinkingGroups:l,onChange:({objectId:O,overwritePriority:K,cellTypes:U,inputTypes:A})=>{e.linkedValueSettings={objectId:O,overwritePriority:K,cellTypes:U,inputTypes:A},o(s)},onLinkedFieldDelete:O=>{const{contractData:K}=s,U=El(K,{[O]:""});s.contractData=U,o(new $(s))}})})}),t.jsx(Q,{title:g,placement:"right",disableHoverListener:x,disableFocusListener:x,disableTouchListener:x,children:t.jsx("span",{children:t.jsx(_,{text:"Link Measure Sheet Item",onClick:()=>a(!0,"linkedMeasureSheetItem",!0,"Link Measure Sheet Item"),label:e.linkedMeasureSheetItem?"Linked":"",disabled:r?!1:(B=e.linkedValueSettings)==null?void 0:B.objectId,className:(L=e.linkedValueSettings)!=null&&L.objectId&&!r?"menu-item-disabled":""})})}),t.jsx(Q,{title:g,placement:"right",disableHoverListener:x,disableFocusListener:x,disableTouchListener:x,children:t.jsx("span",{children:t.jsx(Zn,{itemIds:[e.linkedMeasureSheetItem],disabled:!e.linkedMeasureSheetItem||(r?!1:(H=e.linkedValueSettings)==null?void 0:H.objectId)})})}),t.jsx(Q,{title:g,placement:"right",disableHoverListener:x,disableFocusListener:x,disableTouchListener:x,children:t.jsx("span",{children:t.jsx(_,{text:"Link Quantities",onClick:()=>a(!0,"measureSheetItemQuantityIds",!1,"Link Quantities"),label:e.measureSheetItemQuantityIds?e.measureSheetItemQuantityIds.length:"",disabled:r?!1:(G=e.linkedValueSettings)==null?void 0:G.objectId,className:(ne=e.linkedValueSettings)!=null&&ne.objectId&&!r?"menu-item-disabled":""})})}),t.jsx(Q,{title:g,placement:"right",disableHoverListener:x,disableFocusListener:x,disableTouchListener:x,children:t.jsx("span",{children:t.jsx(_,{text:"Link Totals",onClick:()=>a(!0,"measueSheetItemTotalIds",!1,"Link Totals"),label:e.measueSheetItemTotalIds?e.measueSheetItemTotalIds.length:"",disabled:r?!1:(le=e.linkedValueSettings)==null?void 0:le.objectId,className:(re=e.linkedValueSettings)!=null&&re.objectId&&!r?"menu-item-disabled":""})})})]})]})}};vi.propTypes={object:b.any.isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired,secureCaptureEnabled:b.bool,setShowLinkItems:b.func.isRequired,enableDocLinking:b.bool,enableLinkingGroups:b.bool,disableDocLinkingRestriction:b.bool};vi.defaultProps={secureCaptureEnabled:!1,enableDocLinking:!1,enableLinkingGroups:!1,disableDocLinkingRestriction:!1};const fj=({templatesEdit:n={},auth:e})=>{var s,o,a,i,l;
13return{templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,secureCaptureEnabled:(s=e.company)==null?void 0:s.get("spreedlyEnabled"),enableDocLinking:(o=n.featureFlags)==null?void 0:o.enableDocLinking,enableLinkingGroups:(a=n.featureFlags)==null?void 0:a.enableLinkingGroups,disableDocLinkingRestriction:(i=n.featureFlags)==null?void 0:i.disableDocLinkingRestriction,showDaysOutSetting:(l=n.featureFlags)==null?void 0:l.showDaysOutSetting}},bj=n=>({setTemplateState:e=>n(ee(e)),setShowLinkItems:(e,s,o,a)=>n(Ut(e,s,o,a))}),yj=Z(fj,bj)(vi),Ti=({object:n,contractObject:e,setTemplateState:s})=>t.jsxs(J.Fragment,{children:[t.jsx(_,{text:"Sketch Pad Height",shouldDismissPopover:!1,labelElement:t.jsx(Fn,{value:n.imageHeight,minValue:20,maxValue:parseInt(e.pageSize.split(",")[1],10)-e.hMargin*2-20,increment:10,small:!0,onChange:o=>{n.imageHeight=o,s(new $(e.toJSON()))}})}),t.jsx(je,{text:"Dynamic",active:n.inputType==="dynamic",onChange:o=>{n.inputType=o?"dynamic":"",s(e)}}),n.inputType==="dynamic"&&t.jsx(is,{contractObject:e,cellItem:n,onChange:o=>{n.dynamicInputType=o,s(e)}}),t.jsx(xe.Divider,{}),t.jsx(je,{text:"Required",active:n.required,onChange:o=>{n.required=o,s(e)}}),t.jsx(xe.Divider,{}),!n.titleLinked&&t.jsxs(J.Fragment,{children:[t.jsx(_,{text:t.jsxs("span",{children:["App Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{n.titleLinked=!0,n.contractTitle=n.appTitle,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.appTitle,onChange:o=>{n.appTitle=o.target.value,s(e)}})}),t.jsx(_,{text:t.jsxs("span",{children:["PDF Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{n.titleLinked=!0,n.appTitle=n.contractTitle,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.contractTitle,onChange:o=>{n.contractTitle=o.target.value,s(e)}})})]}),n.titleLinked&&t.jsx(_,{text:t.jsxs("span",{children:["Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"lock",onClick:()=>{n.titleLinked=!1,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.contractTitle,onChange:o=>{n.contractTitle=o.target.value,s(e)}})}),t.jsx(xe.Divider,{}),!n.isFormulaCell&&t.jsx(je,{text:"Hide If Left Blank",active:!n.drawIfEmpty,onChange:o=>{n.drawIfEmpty=!o,s(e)}}),t.jsx(Vs,{object:n,setTemplateState:s,contractObject:e})]});Ti.propTypes={object:b.any.isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired};Ti.defaultProps={};const jj=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem}),Cj=n=>({setTemplateState:e=>n(ee(e))}),Ij=Z(jj,Cj)(Ti),wi=({object:n,contractObject:e,setTemplateState:s,secureCaptureEnabled:o,setShowLinkItems:a,enableDocLinking:i})=>t.jsxs(J.Fragment,{children:[t.jsx(xe.Divider,{}),t.jsx(je,{text:"Required",active:n.required,onChange:l=>{n.required=l,s(e)}}),t.jsx(xe.Divider,{}),!n.titleLinked&&t.jsxs(J.Fragment,{children:[t.jsx(_,{text:t.jsxs("span",{children:["App Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{n.titleLinked=!0,n.contractTitle=n.appTitle,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.appTitle,onChange:l=>{n.appTitle=l.target.value,s(e)}})}),t.jsx(_,{text:t.jsxs("span",{children:["PDF Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{n.titleLinked=!0,n.appTitle=n.contractTitle,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.contractTitle,onChange:l=>{n.contractTitle=l.target.value,s(e)}})})]}),n.titleLinked&&t.jsx(_,{text:t.jsxs("span",{children:["Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"lock",onClick:()=>{n.titleLinked=!1,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.contractTitle,onChange:l=>{n.contractTitle=l.target.value,s(e)}})}),t.jsx(xe.Divider,{}),t.jsx(_,{text:"Value",shouldDismissPopover:!1,children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.value,onChange:l=>{n.value=l.target.value,s(e)}})}),t.jsx(Vs,{object:n,setTemplateState:s,contractObject:e}),t.jsx(xe.Divider,{}),i&&t.jsx(Ls,{value:n.linkedValueSettings,onChange:({objectId:l,overwritePriority:r})=>{n.linkedValueSettings={objectId:l,overwritePriority:r},s(e)}}),t.jsx(_,{text:"Link Measure Sheet Item",shouldDismissPopover:!1,onClick:()=>a(!0,"linkedMeasureSheetItem",!0,"Link Measure Sheet Item"),label:n.linkedMeasureSheetItem?"Linked":""}),t.jsx(Zn,{itemIds:[n.linkedMeasureSheetItem],disabled:!n.linkedMeasureSheetItem}),t.jsx(_,{text:"Link Quantities",shouldDismissPopover:!1,onClick:()=>a(!0,"measureSheetItemQuantityIds",!1,"Link Quantities"),label:n.measureSheetItemQuantityIds?n.measureSheetItemQuantityIds.length:""}),t.jsx(_,{text:"Link Totals",shouldDismissPopover:!1,onClick:()=>a(!0,"measueSheetItemTotalIds",!1,"Link Totals"),label:n.measueSheetItemTotalIds?n.measueSheetItemTotalIds.length:""})]});wi.propTypes={object:b.any.isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired,secureCaptureEnabled:b.bool,setShowLinkItems:b.func.isRequired,enableDocLinking:b.bool};wi.defaultProps={secureCaptureEnabled:!1,enableDocLinking:!1};const Sj=({templatesEdit:n={},auth:e})=>{var s;
13return{templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,secureCaptureEnabled:e.company.get("spreedlyEnabled"),enableDocLinking:(s=n.featureFlags)==null?void 0:s.enableDocLinking}},vj=n=>({setTemplateState:e=>n(ee(e)),setShowLinkItems:(e,s,o,a)=>n(Ut(e,s,o,a))}),Tj=Z(Sj,vj)(wi),ki=({object:n,contractObject:e,setTemplateState:s,setShowLinkItems:o,disableImageHeight:a})=>{const{linkedMeasureSheetItemIds:i=[]}=n;return t.jsxs(J.Fragment,{children:[t.jsx(_,{text:"Image Size",shouldDismissPopover:!1,labelElement:t.jsx(Fn,{value:n.imageHeight,minValue:0,maxValue:1e3,increment:1,small:!0,onChange:l=>{n.imageHeight=l,s(new $(e.toJSON()))}})}),t.jsx(en,{}),t.jsx(je,{text:"Hide If Left Blank",active:!n.drawIfEmpty,onChange:l=>{n.drawIfEmpty=!l,s(e)}}),t.jsx(en,{}),t.jsx(je,{text:"Required",active:n.required,onChange:l=>{n.required=l,s(e)}}),t.jsx(en,{}),!n.titleLinked&&t.jsxs(J.Fragment,{children:[t.jsx(_,{text:t.jsxs("span",{children:["App Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{n.titleLinked=!0,n.contractTitle=n.appTitle,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.appTitle,onChange:l=>{n.appTitle=l.target.value,s(e)}})}),t.jsx(_,{text:t.jsxs("span",{children:["PDF Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{n.titleLinked=!0,n.appTitle=n.contractTitle,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.contractTitle,onChange:l=>{n.contractTitle=l.target.value,s(e)}})})]}),n.titleLinked&&t.jsx(_,{text:t.jsxs("span",{children:["Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"lock",onClick:()=>{n.titleLinked=!1,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.contractTitle,onChange:l=>{n.contractTitle=l.target.value,s(e)}})}),t.jsx(_,{text:"App Note",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.appNote,onChange:l=>{n.appNote=l.target.value,s(e)}})}),t.jsx(en,{}),t.jsx(_,{text:"Link Measure Sheet Item",label:i.length||"",onClick:()=>o(!0,"linkedMeasureSheetItem",!0,"Linked Measure Sheet Item",!0)})]})};ki.propTypes={object:b.any.isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired,disableImageHeight:b.bool};ki.defaultProps={disableImageHeight:!1};const wj=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem}),kj=n=>({setShowLinkItems:(e,s,o,a,i)=>n(Ut(e,s,o,a,i)),setTemplateState:e=>n(ee(e))}),Jl=Z(wj,kj)(ki),Pi=({object:n,contractObject:e,setTemplateState:s})=>t.jsxs(J.Fragment,{children:[t.jsx(je,{text:"Dynamic",active:n.inputType==="dynamic",onChange:o=>{n.inputType=o?"dynamic":"",s(e)}}),n.inputType==="dynamic"&&t.jsx(is,{contractObject:e,cellItem:n,onChange:o=>{n.dynamicInputType=o,s(e)}}),t.jsx(je,{text:"Send Payment Request",active:!n.disablePaymentRequest,onChange:o=>{n.disablePaymentRequest=!o,s(e)}}),!n.disablePaymentRequest&&t.jsx(_,{text:"Success Value",children:t.jsx(ve,{placeholder:"Pending Capture via Email",element:fe,minLength:0,debounceTimeout:300,value:n.paymentRequestText,onChange:o=>{n.paymentRequestText=o.target.value,s(e)}})}),t.jsx(je,{text:"Capture and Charge Enabled",active:!n.disableCaptureAndCharge,onChange:o=>{n.disableCaptureAndCharge=!o,s(e)}}),!n.disableCaptureAndCharge&&t.jsx(je,{text:"Default to Capture and Charge",active:n.defaultPaymentMode!=="captureOnly",onChange:o=>{n.defaultPaymentMode=o?"captureAndCharge":"captureOnly",s(e)}}),t.jsx(xe.Divider,{}),t.jsx(je,{text:"Required",active:n.required,onChange:o=>{n.required=o,s(e)}}),t.jsx(xe.Divider,{}),!n.titleLinked&&t.jsxs(J.Fragment,{children:[t.jsx(_,{text:t.jsxs("span",{children:["App Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{n.titleLinked=!0,n.contractTitle=n.appTitle,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.appTitle,onChange:o=>{n.appTitle=o.target.value,s(e)}})}),t.jsx(_,{text:t.jsxs("span",{children:["PDF Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"unlock",onClick:()=>{n.titleLinked=!0,n.appTitle=n.contractTitle,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.contractTitle,onChange:o=>{n.contractTitle=o.target.value,s(e)}})})]}),n.titleLinked&&t.jsx(_,{text:t.jsxs("span",{children:["Title",t.jsx(Ae,{small:!0,minimal:!0,icon:"lock",onClick:()=>{n.titleLinked=!1,s(e)}})]}),children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.contractTitle,onChange:o=>{n.contractTitle=o.target.value,s(e)}})}),t.jsx(_,{text:"App Note",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.appNote,onChange:o=>{n.appNote=o.target.value,s(e)}})}),t.jsx(Vs,{object:n,setTemplateState:s,contractObject:e})]});Pi.propTypes={object:b.any.isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired};Pi.defaultProps={};const Pj=({templatesEdit:n={},auth:e})=>
13({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,secureCaptureEnabled:e.company.get("spreedlyEnabled")}),Dj=n=>({setTemplateState:e=>n(ee(e))}),Oj=Z(Pj,Dj)(Pi),Di=({object:n,contractObject:e,setTemplateState:s})=>t.jsx(J.Fragment,{children:t.jsx(_,{text:"Empty Space Height",shouldDismissPopover:!1,labelElement:t.jsx(Fn,{value:n.emptySpaceHeight,minValue:1,maxValue:1e3,increment:1,small:!0,onChange:o=>{n.emptySpaceHeight=o,s(new $(e.toJSON()))}})})});Di.propTypes={object:b.any.isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired};Di.defaultProps={};const Nj=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem}),Mj=n=>({setTemplateState:e=>n(ee(e))}),Lj=Z(Nj,Mj)(Di),Pd=({object:n,contractObject:e,setTemplateState:s})=>t.jsxs(J.Fragment,{children:[t.jsx(je,{text:"Dynamic",active:n.inputType==="dynamic",onChange:o=>{n.inputType=o?"dynamic":"",s(e)}}),n.inputType==="dynamic"&&t.jsx(is,{contractObject:e,cellItem:n,onChange:o=>{n.dynamicInputType=o,s(e)}}),t.jsx(xe.Divider,{}),t.jsx(_,{text:"Default Tag",children:t.jsx(ve,{element:fe,minLength:0,placeholder:"Image: ",debounceTimeout:300,value:n.photoTag,onChange:o=>{n.photoTag=o.target.value,s(e)}})}),t.jsx(xe.Divider,{}),n.cellType==="switched"&&t.jsx(xe.Divider,{}),t.jsx(je,{text:"Required",active:n.required,onChange:o=>{n.required=o,s(e)}}),t.jsx(je,{text:"Link Report Photos",active:n.allowReportPhotos,onChange:o=>{n.allowReportPhotos=o,s(e)}}),t.jsx(xe.Divider,{}),t.jsx(_,{text:"App Title",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.appTitle,onChange:o=>{n.appTitle=o.target.value,s(e)}})})]});Pd.propTypes={object:b.any.isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired};const Ej=({templatesEdit:n={},auth:e})=>({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,secureCaptureEnabled:e.company.get("spreedlyEnabled")}),Aj=n=>({setTemplateState:e=>n(ee(e))}),Fj=Z(Ej,Aj)(Pd),Oi=({object:n,contractObject:e,setTemplateState:s,setShowLinkItems:o})=>{const{linkedMeasureSheetItemConfig:a={}}=n;return t.jsxs(J.Fragment,{children:[t.jsx(xe.Divider,{}),t.jsx(_,{text:"Title",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:n.appTitle,onChange:i=>{n.appTitle=i.target.value,s(e)}})}),t.jsx(je,{text:"Show Title",active:a.title,onChange:i=>{n.linkedMeasureSheetItemConfig={...a,title:i},s(e)}}),t.jsx(je,{text:"Show Selected Option",active:a.subtitle,onChange:i=>{n.linkedMeasureSheetItemConfig={...a,subtitle:i},s(e)}}),t.jsx(je,{text:"Show Quantity",active:a.quantity,onChange:i=>{n.linkedMeasureSheetItemConfig={...a,quantity:i},s(e)}}),t.jsx(je,{text:"Show Measure Type",active:a.measurementType,onChange:i=>{n.linkedMeasureSheetItemConfig={...a,measurementType:i},s(e)}}),t.jsx(je,{text:"Show Unit Total",active:a.unitTotal,onChange:i=>{n.linkedMeasureSheetItemConfig={...a,unitTotal:i},s(e)}}),t.jsx(je,{text:"Show Grand Total",active:a.total,onChange:i=>{n.linkedMeasureSheetItemConfig={...a,total:i},s(e)}}),t.jsx(xe.Divider,{}),t.jsx(wa,{contractObject:e,value:n.formula,onChange:i=>{n.formula=i,s(e)},excluding:n.cellId}),t.jsx(je,{text:"Hide Unless Added to Estimate",active:!n.drawIfEmpty,onChange:i=>{n.drawIfEmpty=!i,s(e)}}),t.jsx(xe.Divider,{}),t.jsx(_,{text:"Link Measure Sheet Item",onClick:()=>o(!0,"linkedMeasureSheetItem",!0,"Link Measure Sheet Item"),label:n.linkedMeasureSheetItem?"Linked":""})]})};Oi.propTypes={object:b.any.isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired,secureCaptureEnabled:b.bool,setShowLinkItems:b.func.isRequired};Oi.defaultProps={secureCaptureEnabled:!1};const Rj=({templatesEdit:n={},auth:e})=>({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,secureCaptureEnabled:e.company.get("spreedlyEnabled")}),_j=n=>({setTemplateState:e=>n(ee(e)),setShowLinkItems:(e,s,o,a)=>n(Ut(e,s,o,a))}),Bj=Z(Rj,_j)(Oi),Ni=({object:n,contractObject:e,setTemplateState:s})=>t.jsxs(J.Fragment,{children:[t.jsx(je,{text:"Use Shared Images",active:n.imagesSource==="default",onChange:o=>{n.imagesSource=o?"default":"unique",s(e)}}),t.jsx(je,{text:"Dynamic",active:n.inputType==="dynamic",onChange:o=>{n.inputType=o?"dynamic":"",s(e)}}),n.inputType==="dynamic"&&t.jsx(is,{contractObject:e,cellItem:n,onChange:o=>{n.dynamicInputType=o,s(e)}}),t.jsx(xe.Divider,{}),t.jsx(je,{text:"Required",active:n.required,onChange:o=>{n.required=o,s(e)}}),t.jsx(xe.Divider,{}),t.jsx(_,{text:"App Title",children:t.jsx(Ht.DebounceInput,{element:fe,minLength:0,debounceTimeout:300,value:n.appTitle,onChange:o=>{n.titleLinked=!1,n.appTitle=o.target.value,s(e)}})}),t.jsx(je,{text:"Link Price Guide Image",active:!n.disableImageLink,onChange:o=>{n.disableImageLink=!o,s(e)}})]});Ni.propTypes={object:b.instanceOf(X).isRequired,contractObject:b.instanceOf($).isRequired,setTemplateState:b.func.isRequired,secureCaptureEnabled:b.bool};Ni.defaultProps={secureCaptureEnabled:!1};const $j=({templatesEdit:n={},auth:e})=>
13({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem,secureCaptureEnabled:e.company.get("spreedlyEnabled")}),zj=n=>({setTemplateState:e=>n(ee(e))}),Wj=Z($j,zj)(Ni),Mi=({contractObject:n,object:e,setTemplateState:s})=>t.jsx("div",{children:" "});Mi.propTypes={contractObject:b.instanceOf($).isRequired,object:b.instanceOf(X).isRequired,setTemplateState:b.func.isRequired};Mi.defaultProps={};const Hj=n=>({setTemplateState:e=>n(ee(e))}),qj=Z(void 0,Hj)(Mi),Vj={0:"None",1:"Outside",2:"Inside & Outside",3:"Top & Bottom"},Kj=[0,1,2,3],Li=({contractObject:n,object:e,setTemplateState:s})=>t.jsxs(J.Fragment,{children:[t.jsx(xe.Divider,{}),t.jsx(_,{text:"App Title",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:e.header.appTitle,onChange:o=>{e.header.appTitle=o.target.value,s(n)}})}),t.jsx(_,{text:"PDF Title",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:e.header.title,onChange:o=>{e.header.title=o.target.value,s(n)}})}),t.jsx(_,{text:"Border",children:Kj.map(o=>t.jsx(_,{text:Vj[o],active:e.header.border===o,onClick:()=>{e.header.border=o,s(n)}},`border-${o}`))})]});Li.propTypes={contractObject:b.instanceOf($).isRequired,object:b.instanceOf(X).isRequired,setTemplateState:b.func.isRequired};Li.defaultProps={};const Uj=n=>({setTemplateState:e=>n(ee(e))}),Gj=Z(void 0,Uj)(Li),Dd=({updatedObject:n,contractObject:e})=>{switch(n.cellType){case"textShort":case"textLong":case"textXLong":case"switched":return t.jsx(yj,{object:n,contractObject:e});case"textOnly":return t.jsx(Tj,{object:n,contractObject:e});case"drawing":return t.jsx(Ij,{object:n,contractObject:e});case"detailCell":return t.jsx(Jl,{object:n,contractObject:e});case"provia":return t.jsx(Jl,{disableImageHeight:!0,object:n,contractObject:e});case"securePaymentCaptureAll":case"creditCardCell":case"bankAccountCell":return t.jsx(Oj,{object:n,contractObject:e});case"emptySpace":return t.jsx(Lj,{object:n,contractObject:e});case"photoPickerCell":return t.jsx(Fj,{object:n,contractObject:e});case"measureSheetItemDetail":return t.jsx(Bj,{object:n,contractObject:e});case"imagePicker":return t.jsx(Wj,{object:n,contractObject:e});case"header":return t.jsx(Gj,{object:n,contractObject:e});case"signatures":return t.jsx(qj,{object:n,contractObject:e});default:return null}};Dd.propTypes={contractObject:b.instanceOf($).isRequired,updatedObject:b.instanceOf(X).isRequired};const Jj=n=>{switch(n.cellType){case"header":case"signatures":return X.CellTypes;default:return n.cellTypes}},Yj=(n,e)=>{switch(n.cellType=e,e){case"textXLong":n.inputType="default";break;case"provia":n.inputType="picker",n.pickerValues=[""];break}},Od=({updatedObject:n,setTemplateState:e,secureCaptureEnabled:s,contractObject:o})=>t.jsx(_,{text:"Cell Type",label:X.cellTypeLabelForCellType(n.cellType),shouldDismissPopover:!1,children:Jj(n).map(a=>{var r,d;const i=X.cellTypeLabelForCellType(a);let l=!0;return(a==="creditCardCell"||a==="bankAccountCell"||a==="securePaymentCaptureAll")&&(l=s),((d=(r=n==null?void 0:n.linkedValueSettings)==null?void 0:r.cellTypes)==null?void 0:d.length)>0&&(l=n.linkedValueSettings.cellTypes.includes(a)),t.jsx(Q,{title:"This is incompatible with the selected linked field.",placement:"right",disableHoverListener:l,disableFocusListener:l,disableTouchListener:l,children:t.jsx("span",{children:t.jsx(_,{text:i,disabled:!l,shouldDismissPopover:!1,className:l?"":"menu-item-disabled",active:n.cellType===a,onClick:()=>{Yj(n,a),e(o)}})})},a)})});Od.propTypes={contractObject:b.instanceOf($).isRequired,updatedObject:b.instanceOf(X).isRequired,setTemplateState:b.func.isRequired,secureCaptureEnabled:b.bool.isRequired};const Xj=()=>t.jsx(_,{style:{display:"none"},children:t.jsx(_,{})}),Zj=n=>{switch(n.cellType){case"textShort":case"textLong":case"textXLong":case"switched":return!0;default:return!1}},Yl=n=>{const{contractObject:e,value:s,categoryFormulaIds:o=[],currentCellIdentifier:a}=n,i=e.getAllCellIdentifiers(a),d=[...["B","T","CP","DP","UA","FP"],...i].includes(s),c=o.includes(s);return!d&&!c},Nd=({templateValues:n,editCellItem:e,secureCaptureEnabled:s,setTemplateState:o,setEditCellItem:a,categoryFormulaIds:i})=>{const l=new $(n.toJSON()),r=l.getObjectWithId(e.objectId)||{},[d,c]=y.useState(!1),[u,p]=y.useState(r.cellId);return t.jsxs(xe,{className:`${os} settings-popover`,children:[t.jsx(Xj,{}),t.jsx(Od,{updatedObject:r,setTemplateState:o,secureCaptureEnabled:s,contractObject:l}),Zj(r)&&t.jsxs(_,{popoverProps:{onClose:()=>{Yl({contractObject:l,value:u,categoryFormulaIds:i,currentCellIdentifier:r.cellId})&&(r.cellId=u,o(l),a(r))}},text:"Identifier",label:r.cellId,children:[d&&t.jsxs("p",{className:"danger",children:[" ",d]}),t.jsx(Ht.DebounceInput,{className:"identifier-input",minLength:0,debounceTimeout:300,value:u,onChange:h=>{Yl({contractObject:l,value:h.target.value,categoryFormulaIds:i,currentCellIdentifier:r.cellId})?(p(h.target.value),c(void 0)):(p(h.target.value),c("Invalid: Identifier already exists"))}})]}),t.jsx(Dd,{updatedObject:r,contractObject:l})]})};Nd.propTypes={templateValues:b.instanceOf($).isRequired,editCellItem:b.instanceOf(X).isRequired,setTemplateState:b.func.isRequired,secureCaptureEnabled:b.bool.isRequired,setEditCellItem:b.bool.isRequired,categoryFormulaIds:b.arrayOf(b.string).isRequired};const Qj=({auth:n,templatesEdit:e={}})=>{const{company:s,config:o}=n;
13return{templateValues:e[e.currentWorkingId],editCellItem:e.editCellItem,secureCaptureEnabled:s==null?void 0:s.get("spreedlyEnabled"),categoryFormulaIds:o==null?void 0:o.categories_.filter(({formulaId:a})=>a).map(({formulaId:a})=>a)}},eC=n=>({setTemplateState:e=>n(ee(e)),setEditCellItem:e=>n(Ne(e))}),Xl=Z(Qj,eC)(Nd),Md=({templateValues:n,editCellItem:e,setTemplateState:s})=>{const o=new $(n.toJSON()),a=o.getObjectWithId(e.objectId)||{};return t.jsxs(xe,{className:os,children:[t.jsx(_,{text:"App Note",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:a.appNote,onChange:i=>{a.appNote=i.target.value,s(o)}})}),t.jsx(_,{text:"Contract Note",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:a.contractNote,onChange:i=>{a.contractNote=i.target.value,s(o)}})}),t.jsx(_,{text:"Footer Note",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:a.footerNote,onChange:i=>{a.footerNote=i.target.value,s(o)}})}),t.jsx(xe.Divider,{}),t.jsx(je,{text:"Underline",active:a.underline,onChange:i=>{a.underline=i,s(o)}}),t.jsxs(_,{text:"Column",shouldDismissPopover:!1,label:a.column===0?"Left":"Right",children:[t.jsx(_,{text:"Left",shouldDismissPopover:!1,active:a.column===0,onClick:()=>{a.column=0,s(o)}}),t.jsx(_,{text:"Right",shouldDismissPopover:!1,active:a.column===1,onClick:()=>{a.column=1,s(o)}})]})]})};Md.propTypes={templateValues:b.instanceOf($).isRequired,editCellItem:b.instanceOf(Ye).isRequired,setTemplateState:b.func.isRequired};const tC=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem}),nC=n=>({setTemplateState:e=>n(ee(e))}),sC=Z(tC,nC)(Md),Ld=({templateValues:n,editCellItem:e,setTemplateState:s})=>{const o=new $(n.toJSON()),a=o.getObjectWithId(e.objectId)||{};return t.jsxs(xe,{className:os,children:[t.jsx(_,{text:"Above Line (Value)",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:a.value,onChange:i=>{a.value=i.target.value,s(o)}})}),t.jsx(_,{text:"Below Line (Note)",children:t.jsx(ve,{element:fe,minLength:0,debounceTimeout:300,value:a.note,onChange:i=>{a.note=i.target.value,s(o)}})}),t.jsx(xe.Divider,{}),t.jsx(je,{text:"Underline",active:a.underline,onChange:i=>{a.underline=i,s(o)}})]})};Ld.propTypes={templateValues:b.instanceOf($).isRequired,editCellItem:b.instanceOf(yn).isRequired,setTemplateState:b.func.isRequired};const oC=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem}),aC=n=>({setTemplateState:e=>n(ee(e))}),iC=Z(oC,aC)(Ld),qo=n=>{typeof pendo>"u"||pendo.track(n)},et={toolbarButton:{borderColor:"#2e2e2e",color:"#2e2e2e",fontSize:11,fontWeight:600,height:"30px",borderWidth:"1.5px !important"},toggleButtonGroup:{".MuiButtonBase-root":{fontSize:9.5,height:"30px",padding:"4px 10px"},".Mui-selected":{backgroundColor:"rgba(120, 157, 255, 0.25)"}},fontSizeContainer:{".font-size-adjustment-btn":{padding:0,height:"30px",width:"30px",borderRadius:"0px"},".font-size-input":{width:"40px",height:"30px",".MuiInputBase-input":{padding:"0 6px",height:"30px",textAlign:"center"}}},fontSelector:{width:"200px",".MuiInputBase-root":{height:"30px"}},imageInput:{borderColor:"#2e2e2e",color:"#2e2e2e",fontSize:11,fontWeight:600,height:"30px",borderWidth:"1.5px !important",minWidth:"130px"},textColor:{borderColor:"#2e2e2e",color:"#2e2e2e",borderWidth:"1.5px !important",height:"30px",minWidth:"40px",padding:0},collapseList:{backgroundColor:"#f5f5f5",py:1}},lC=n=>{if(!n)return null;switch(n){case"header-title":return t.jsx(qy,{});case"header-cell":return t.jsx(Yy,{});case"body-title":return t.jsx(ij,{});case"body-cell":case"body-detail-cell":return t.jsx(Xl,{});case"signature-title":return t.jsx(sC,{});case"signature-detail":return t.jsx(iC,{});default:return t.jsx(Xl,{})}},rC=()=>{const n=ft(),e=p=>n(Ot(p)),s=et,{templatesEdit:o={}}=ze(p=>{const{templatesEdit:h}=p;return{templatesEdit:h}}),[a,i]=y.useState(null),l=!!a,r=p=>{i(p.currentTarget),e({event:"contractMenuEvent",eventCategory:"Documents",eventAction:"Menu Open",eventLabel:"Settings"}),qo("doc_editor_legacy_settings_used")},d=()=>{i(null)},{linkMeasureSheetItemsShow:c,editCellItem:u}=o;return t.jsxs(t.Fragment,{children:[t.jsx(we,{id:"settings-legacy-button",variant:"outlined",sx:s.toolbarButton,"aria-controls":l?"settings-legacy-menu":void 0,"aria-haspopup":"true","aria-expanded":l?"true":void 0,onClick:r,disabled:!(u!=null&&u.toolboxKey),children:"Legacy Settings"}),t.jsx(kt,{id:"settings-legacy-menu",anchorEl:a,open:l,onClose:d,sx:{".MuiList-root":{padding:0}},slotProps:{paper:{sx:{overflow:"unset"}}},children:lC(u==null?void 0:u.toolboxKey)})]})},cC=n=>{var c;const{keys:e,updatedObject:s,keyMaps:o,contractObject:a,setTemplateState:i}=n,l=et,r=y.useCallback((u,p)=>{s[o.align]=parseInt(p||"0",10),i(a)},[s]),d=e.indexOf("align")>-1;return t.jsxs(Gt,{value:((c=s==null?void 0:s[o==null?void 0:o.align])==null?void 0:c.toString())||null,exclusive:!0,onChange:r,disabled:!d,"aria-label":"text alignment",sx:l.toggleButtonGroup,children:[t.jsx(Ve,{value:"0",children:t.jsx(Q,{title:"Left Align",children:t.jsx(ac,{fontSize:"small"})})}),t.jsx(Ve,{value:"1",children:t.jsx(Q,{title:"Center Align",children:t.jsx(ic,{fontSize:"small"})})}),t.jsx(Ve,{value:"2",children:t.jsx(Q,{title:"Right Align",children:t.jsx(lc,{fontSize:"small"})})})]})},dC=n=>({setTemplateState:e=>n(ee(e))}),uC=Z(null,dC)(cC),pC=n=>
13{const{keys:e,updatedObject:s,keyMaps:o,contractObject:a,setTemplateState:i}=n,[l,r]=y.useState([]),d=et;y.useEffect(()=>{const h=[];s!=null&&s[o==null?void 0:o.bold]&&h.push("bold"),s!=null&&s[o==null?void 0:o.underline]&&h.push("underline"),r(h)},[s]);const c=y.useCallback((h,g)=>{s[o.bold]=g.includes("bold"),s[o.underline]=g.includes("underline"),i(a)},[s]),u=e.indexOf("bold")>-1,p=e.indexOf("underline")>-1;return t.jsxs(Gt,{value:l,onChange:c,"aria-label":"text format",sx:d.toggleButtonGroup,children:[t.jsx(Ve,{value:"bold",disabled:!u,children:t.jsx(Q,{title:"Text bold",children:t.jsx(Ao,{fontSize:"small"})})}),t.jsx(Ve,{value:"underline",disabled:!p,children:t.jsx(Q,{title:"Text underline",children:t.jsx(Fo,{fontSize:"small"})})})]})},hC=n=>({setTemplateState:e=>n(ee(e))}),mC=Z(null,hC)(pC),gC=n=>{const{keys:e,keyMaps:s,updatedObject:o,contractObject:a,setTemplateState:i}=n,l=et,r=(o==null?void 0:o[s==null?void 0:s.color])||"0-0-0-1",[d,c,u,p]=r.split("-"),[h,g]=y.useState(!1),x=y.useRef(null),m=e.indexOf("
13color")>-1,f=y.useCallback(({rgb:j})=>{const S=`${j.r}-${j.g}-${j.b}-${j.a}`;o[s.color]=S,i(a)},[o]);return t.jsxs(t.Fragment,{children:[t.jsx(we,{ref:x,"aria-describedby":"textColor",variant:"outlined",sx:l.textColor,onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),disabled:!m,children:t.jsx(wp,{sx:{color:`rgba(${d}, ${c}, ${u}, ${p})`}})}),t.jsx(Ze,{id:"textColor",sx:{zIndex:1300},open:h,anchorEl:x.current,placement:"bottom-start",transition:!0,onMouseEnter:()=>g(!0),onMouseLeave:j=>g(!1),children:({TransitionProps:j})=>t.jsx(Qe,{...j,timeout:350,children:t.jsx(Je,{sx:{minWidth:"auto"},elevation:4,children:t.jsx(Eo,{color:{r:d,g:c,b:u,a:p},onChange:f})})})})]})},xC=n=>({setTemplateState:e=>n(ee(e))}),fC=Z(null,xC)(gC),Zl=1,bC=n=>{const{keys:e,updatedObject:s,keyMaps:o,contractObject:a,setTemplateState:i}=n,l=et,r=e.indexOf("size")>-1,d=u=>{const p=u>0?u:void 0;s[o.size]=p,i(a)},c=(u,p)=>{const h=parseFloat(s[o.size])||0;switch(u){case"increase":d(h+1);break;case"decrease":d(h-1);break;case"number":d(parseFloat(p||"0"));break}};return t.jsxs(he,{direction:"row",alignItems:"center",sx:l.fontSizeContainer,children:[t.jsx(ye,{"aria-label":"increase font size",disabled:!r,className:"font-size-adjustment-btn",onClick:()=>c("increase"),children:t.jsx(wn,{})}),t.jsx(Le,{variant:"outlined",color:"secondary",size:"small",type:"number",value:s==null?void 0:s[o==null?void 0:o.size],disabled:!r,className:"font-size-input",slotProps:{htmlInput:{min:Zl}},onChange:u=>c("number",u.target.value)}),t.jsx(ye,{"aria-label":"decrease font size",disabled:!r||s[o.size]<=Zl,className:"font-size-adjustment-btn",onClick:()=>c("decrease"),children:t.jsx(rc,{})})]})},yC=n=>({setTemplateState:e=>n(ee(e))}),jC=Z(null,yC)(bC),CC=["Copperplate","Copperplate-Bold","AppleSDGothicNeo-Thin","AppleSDGothicNeo-Light","AppleSDGothicNeo-Regular","AppleSDGothicNeo-Bold","AppleSDGothicNeo-SemiBold","AppleSDGothicNeo-UltraLight","AppleSDGothicNeo-Medium","Thonburi","Thonburi-Light","Thonburi-Bold","GillSans-Italic","GillSans-SemiBold","GillSans-UltraBold","GillSans-Light","GillSans-Bold","GillSans","GillSans-SemiBoldItalic","GillSans-BoldItalic","GillSans-LightItalic","MarkerFelt-Thin","MarkerFelt-Wide","HiraMaruProN-W4","CourierNewPS-ItalicMT","CourierNewPSMT","CourierNewPS-BoldItalicMT","CourierNewPS-BoldMT","KohinoorTelugu-Regular","KohinoorTelugu-Medium","KohinoorTelugu-Light","AvenirNextCondensed-Heavy","AvenirNextCondensed-MediumItalic","AvenirNextCondensed-Regular","AvenirNextCondensed-UltraLightItalic","AvenirNextCondensed-Medium","AvenirNextCondensed-HeavyItalic","AvenirNextCondensed-DemiBoldItalic","AvenirNextCondensed-Bold","AvenirNextCondensed-DemiBold","AvenirNextCondensed-BoldItalic","AvenirNextCondensed-Italic","AvenirNextCondensed-UltraLight","TamilSangamMN","TamilSangamMN-Bold","HelveticaNeue-UltraLightItalic","HelveticaNeue-Medium","HelveticaNeue-MediumItalic","HelveticaNeue-UltraLight","HelveticaNeue-Italic","HelveticaNeue-Light","HelveticaNeue-ThinItalic","HelveticaNeue-LightItalic","HelveticaNeue-Bold","HelveticaNeue-Thin","HelveticaNeue-CondensedBlack","HelveticaNeue","HelveticaNeue-CondensedBold","HelveticaNeue-BoldItalic","GurmukhiMN-Bold","GurmukhiMN","Georgia-BoldItalic","Georgia-Italic","Georgia","Georgia-Bold","TimesNewRomanPS-ItalicMT","TimesNewRomanPS-BoldItalicMT","TimesNewRomanPS-BoldMT","TimesNewRomanPSMT","SinhalaSangamMN-Bold","SinhalaSangamMN","ArialRoundedMTBold","Kailasa-Bold","Kailasa","KohinoorDevanagari-Regular","KohinoorDevanagari-Light","KohinoorDevanagari-Semibold","KohinoorBangla-Regular","KohinoorBangla-Semibold","KohinoorBangla-Light","ChalkboardSE-Bold","ChalkboardSE-Light","ChalkboardSE-Regular","Helvetica-Condensed-Light","AppleColorEmoji","PingFangTC-Regular","PingFangTC-Thin","PingFangTC-Medium","PingFangTC-Semibold","PingFangTC-Light","PingFangTC-Ultralight","GujaratiSangamMN","GujaratiSangamMN-Bold","GeezaPro-Bold","GeezaPro","DamascusBold","DamascusLight","Damascus","DamascusMedium","DamascusSemiBold","Noteworthy-Bold","Noteworthy-Light","Avenir-Oblique","Avenir-HeavyOblique","Avenir-Heavy","Avenir-BlackOblique","Avenir-
13BookOblique","Avenir-Roman","Avenir-Medium","Avenir-Black","Avenir-Light","Avenir-MediumOblique","Avenir-Book","Avenir-LightOblique","DiwanMishafi","AcademyEngravedLetPlain","Futura-CondensedExtraBold","Futura-Medium","Futura-Bold","Futura-CondensedMedium","Futura-MediumItalic","PartyLetPlain","KannadaSangamMN-Bold","KannadaSangamMN","ArialHebrew-Bold","ArialHebrew-Light","ArialHebrew","Farah","Arial-BoldMT","Arial-BoldItalicMT","Arial-ItalicMT","ArialMT","Chalkduster","Kefa-Regular","HoeflerText-Italic","HoeflerText-Black","HoeflerText-Regular","HoeflerText-BlackItalic","Optima-ExtraBlack","Optima-BoldItalic","Optima-Italic","Optima-Regular","Optima-Bold","Palatino-Italic","Palatino-Roman","Palatino-BoldItalic","Palatino-Bold","MalayalamSangamMN-Bold","MalayalamSangamMN","AlNile","AlNile-Bold","Helvetica-Condensed","Helvetica-Condensed-Bold","BradleyHandITCTT-Bold","HiraMinProN-W3","HiraMinProN-W6","PingFangHK-Medium","PingFangHK-Thin","PingFangHK-Regular","PingFangHK-Ultralight","PingFangHK-Semibold","PingFangHK-Light","Helvetica-Oblique","Helvetica-BoldOblique","Helvetica","Helvetica-Light","Helvetica-Bold","Helvetica-LightOblique","Courier-BoldOblique","Courier-Oblique","Courier","Courier-Bold","Cochin-Italic","Cochin-Bold","Cochin","Cochin-BoldItalic","TrebuchetMS-Bold","TrebuchetMS-Italic","Trebuchet-BoldItalic","TrebuchetMS","LaoSangamMN","DevanagariSangamMN","DevanagariSangamMN-Bold","OriyaSangamMN","OriyaSangamMN-Bold","SnellRoundhand","SnellRoundhand-Bold","SnellRoundhand-Black","ZapfDingbatsITC","BodoniSvtyTwoITCTT-Bold","BodoniSvtyTwoITCTT-BookIta","BodoniSvtyTwoITCTT-Book","Verdana-Italic","Verdana","Verdana-Bold","Verdana-BoldItalic","AmericanTypewriter-CondensedBold","AmericanTypewriter-Condensed","AmericanTypewriter-CondensedLight","AmericanTypewriter","AmericanTypewriter-Bold","AmericanTypewriter-Semibold","AmericanTypewriter-Light","AvenirNext-Medium","AvenirNext-DemiBoldItalic","AvenirNext-DemiBold","AvenirNext-HeavyItalic","AvenirNext-Regular","AvenirNext-Italic","AvenirNext-MediumItalic","AvenirNext-UltraLightItalic","AvenirNext-BoldItalic","AvenirNext-Heavy","AvenirNext-Bold","AvenirNext-UltraLight","Baskerville-SemiBoldItalic","Baskerville-SemiBold","Baskerville-BoldItalic","Baskerville","Baskerville-Bold","Baskerville-Italic","KhmerSangamMN","Didot-Bold","Didot","Didot-Italic","SavoyeLetPlain","BodoniOrnamentsITCTT","Symbol","Menlo-BoldItalic","Menlo-Bold","Menlo-Italic","Menlo-Regular","NotoNastaliqUrdu","BodoniSvtyTwoSCITCTT-Book","Papyrus-Condensed","Papyrus","HiraginoSans-W3","HiraginoSans-W6","PingFangSC-Medium","PingFangSC-Semibold","PingFangSC-Light","PingFangSC-Ultralight","PingFangSC-Regular","PingFangSC-Thin","MyanmarSangamMN","MyanmarSangamMN-Bold","Zapfino","BodoniSvtyTwoOSITCTT-BookIt","BodoniSvtyTwoOSITCTT-Book","BodoniSvtyTwoOSITCTT-Bold","EuphemiaUCAS","EuphemiaUCAS-Italic","EuphemiaUCAS-Bold"],IC={label:"Default",value:""},SC=CC.map(n=>({label:n,value:n})),Es=[IC,...SC],ka=[{value:"default",label:"Standard Keyboard"},{value:"ccExpDate",label:"Credit Card Exp Date"},{value:"creditCard",label:"Credit Card Number"},{value:"currency",label:"Currency ($1.00)"},{value:"currencyWhole",label:"Currency ($1)"},{value:"datePicker",label:"Date Picker"},{value:"dateTimePicker",label:"Date & Time"},{value:"timePicker",label:"Time"},{value:"email",label:"Email Address"},{value:"numbers",label:"Number Keyboard"},{value:"keypad",label:"Number Pad (1)"},{value:"keypadDecimal",label:"Number Pad (1.00)"},{value:"phone",label:"Phone Number"},{value:"picker",label:"Picker"},{value:"sizePicker",label:"Size Picker"},{value:"3DSizePicker",label:"3D Size Picker"},{value:"financeOptionsPicker",label:"Finance Options Picker"},{value:"statePicker",label:"State Picker"},{value:"zipCode",label:"Zip Code"}],vC=n=>{const{keys:e,updatedObject:s,keyMaps:o,contractObject:a,setTemplateState:i}=n,l=et,r=e.indexOf("name")>-1;return t.jsx(kp,{options:Es,size:"small",sx:l.fontSelector,disabled:!r,value:(s==null?void 0:s[o==null?void 0:o.name])||Es[0],onChange:(d,c)=>{s[o.name]=c==null?void 0:c.value,i(a)},filterSelectedOptions:!1,renderOption:(d,c)=>t.jsx(Q,{title:c.label,placement:"right",children:t.jsx("li",{...d,children:t.jsx(z,{sx:{fontFamily:c.value,maxWidth:"100%",overflow:"hidden",
13whiteSpace:"nowrap",textOverflow:"ellipsis"},children:c.label})})}),renderInput:d=>t.jsx(Le,{...d,color:"secondary",variant:"outlined"})})},TC=n=>({setTemplateState:e=>n(ee(e))}),wC=Z(null,TC)(vC),kC=tc("input")({clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,overflow:"hidden",position:"absolute",bottom:0,left:0,whiteSpace:"nowrap",width:1}),PC=n=>{const{keys:e,keyMaps:s,updatedObject:o,contractObject:a,setTemplateState:i,openManageImages:l}=n,r=et,d=(o==null?void 0:o.cellType)==="imagePicker",c=e.indexOf("file")>-1,u=p=>{if(p.preventDefault(),!p.target.files||p.target.files.length===0)return;const h=p.target.files[0],g=new FileReader;g.onload=x=>{var m;o[s.file]={url:(m=x==null?void 0:x.target)==null?void 0:m.result,isNew:!0,file:h},i(a)},g.readAsDataURL(h)};return d?t.jsx(we,{variant:"outlined",color:"info",tabIndex:-1,startIcon:t.jsx(Pp,{}),onClick:l,sx:r.imageInput,children:"Manage Images"}):t.jsxs(we,{component:"label",role:void 0,variant:"outlined",color:"info",tabIndex:-1,startIcon:t.jsx(cc,{}),disabled:!c,sx:r.imageInput,children:["Upload Image",t.jsx(kC,{accept:"image/*",type:"file",onChange:u,multiple:!0})]})},DC=n=>({setTemplateState:e=>n(ee(e)),openManageImages:()=>n(jo(!0))}),OC=Z(null,DC)(PC),NC=[{value:0,label:"None"},{value:1,label:"Outside"},{value:2,label:"Inside & Outside"},{value:3,label:"Top & Bottom"}],MC=n=>{const{setTemplateState:e,templateValues:s,editCellItem:o}=n,a=new $(s.toJSON()),i=a.getObjectWithId(o.objectId)||{},l=y.useCallback((r,d,c)=>{const u=c==="number"?Number(d):d;i[r]=u,e(a)},[a,e,i]);return t.jsxs("div",{children:[t.jsx(Oe,{label:"App Title",value:(i==null?void 0:i.appTitle)||"",templateKey:"appTitle",onTemplateChange:l}),t.jsx(Oe,{label:"PDF Title",value:(i==null?void 0:i.title)||"",templateKey:"title",onTemplateChange:l}),t.jsx(qe,{label:"Border",options:NC,templateKey:"border",selectedValue:(i==null?void 0:i.border)||0,valueType:"number",onTemplateChange:l})]})},LC=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem}),EC=n=>({setTemplateState:e=>n(ee(e))}),AC=Z(LC,EC)(MC),FC=[{value:"default",label:"Text"},{value:"emptySpace",label:"Empty Space"},{value:"image",label:"Image"},{value:"companyLogo",label:"Logo"}],RC={emptySpace:"emptySpaceHeight",image:"logoHeight",companyLogo:"logoHeight"},_C=n=>{const{setTemplateState:e,templateValues:s,editCellItem:o}=n,a=new $(s.toJSON()),i=a.getObjectWithId(o.objectId)||{},{cellType:l="default"}=i,r=y.useCallback((c,u,p)=>{const h=p==="number"?Number(u):u;switch(h){case"default":i.value="";break;case"emptySpace":i.value="",i.emptySpaceHeight<1&&(i.emptySpaceHeight=4);break;case"image":i.value="%image%";break;case"companyLogo":i.value="%companyLogo%",i.logoHeight<1&&(i.logoHeight=40);break}i.cellType=h,e(a)},[a,e,i]),d=y.useMemo(()=>RC[l],[l]);return t.jsxs("div",{children:[t.jsx(qe,{label:"Cell Type",options:FC,templateKey:"cellType",selectedValue:l,valueType:"string",onTemplateChange:r}),t.jsxs(ue,{disableRipple:!0,sx:{justifyContent:"space-between"},disabled:l==="default",children:[l==="emptySpace"?"Empty Space Height":"Image Height",t.jsxs(xo,{size:"small",children:[t.jsx(ye,{"aria-label":"Decrease Height",size:"small",disabled:(i==null?void 0:i[d])<=1,onClick:()=>{i[d]-=4,i[d]<1&&(i[d]=1),e(a)},children:t.jsx(fo,{fontSize:"inherit"})}),t.jsx(ie,{orientation:"vertical",sx:{height:"15px",alignSelf:"center"}}),t.jsx(ye,{"aria-label":"Increase Height",size:"small",onClick:()=>{i[d]+=4,e(a)},children:t.jsx(bo,{fontSize:"inherit"})})]})]})]})},BC=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem}),$C=n=>({setTemplateState:e=>n(ee(e))}),zC=Z(BC,$C)(_C),WC=[{value:0,label:"None"},{value:1,label:"Alternate Rows"},{value:2,label:"All Rows"}],HC=[{value:0,label:"Left"},{value:1,label:"Right"}];function qC(n){const e=new Map,s=new Map;if(!n||n.length===0)return[];n.forEach(a=>{const i=a.get("config"),l=i==null?void 0:i.get("categories_");l&&Array.isArray(l)&&l.forEach(r=>{r!=null&&r.objectId&&!e.has(r.objectId)&&e.set(r.objectId,r)})}),e.forEach(a=>{const i=a.name||a.objectId;s.has(i)||s.set(i,new Set);const l=s.get(i);l&&l.add(a.objectId)});const o=Array.from(s.entries()).map(([a,i])=>({name:a,objectIds:Array.from(i)}));return at.sortBy(o,a=>a.name.toLowerCase())}const Ei=()=>{const n=ze(i=>{var l;return((l=i==null?void 0:i.auth)==null?void 0:l.offices)||[]}),e=y.useMemo(()=>["categories",{officeIds:((n==null?void 0:n.map(l=>
13l.id).filter(Boolean))||[]).sort().join(",")}],[n]),{data:s=[],isLoading:o,error:a}=He({queryKey:e,queryFn:()=>qC(n),refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,staleTime:300*1e3,cacheTime:1800*1e3,enabled:((n==null?void 0:n.length)??0)>0});return{categories:s,isLoading:o,error:a}},Vn={fenevision:"/fenetech/documents/section"},VC=[{value:"_none_",label:"None"},{value:Vn.fenevision,label:"Fenevision"}],KC=[{value:0,label:"Warning"},{value:1,label:"Acknowledge"},{value:2,label:"Block"}],UC=n=>{var I,D,F,M,R,P,k,T,B;const{setTemplateState:e,templateValues:s,editCellItem:o}=n,a=new $(s.toJSON()),i=a.getObjectWithId(o==null?void 0:o.objectId)||{},{categoryIds:l=[],linkedMeasureSheetItemIds:r=[]}=i,{categories:d,isLoading:c,error:u}=Ei(),{manufacturers:p,isLoading:h,error:g}=ri({enabled:((I=i.downloadParams)==null?void 0:I.endpoint)===Vn.fenevision}),x=y.useMemo(()=>p==null?void 0:p.find(L=>{var H,G;return L.id===((G=(H=i.downloadParams)==null?void 0:H.headers)==null?void 0:G["x-manufacturer-id"])}),[p,i.downloadParams]),m=y.useMemo(()=>p?p.map(L=>({value:L.id,label:L.name})):[],[p]),f=y.useCallback((L,H,G)=>{const ne=G==="number"?Number(H):H;i[L]=ne,L==="categoryIds"&&Array.isArray(ne)&&ne.length>0&&(i.linkedMeasureSheetItemIds=[]),L==="linkedMeasureSheetItemIds"&&Array.isArray(ne)&&ne.length>0&&(i.categoryIds=[]),e(a)},[a,e,i]),j=y.useCallback(L=>{L===Vn.fenevision?(i.requiresDownload=!0,i.downloadParams={...i.downloadParams,endpoint:Vn.fenevision,body:{settings:{showTotals:!0,exceptionHandling:1}}}):(delete i.downloadParams,i.requiresDownload=!1),e(a)},[a,e,i]),S=y.useCallback(L=>{var H;i.downloadParams={...i.downloadParams,endpoint:Vn.fenevision,headers:{...(H=i.downloadParams)==null?void 0:H.headers,"x-manufacturer-id":L}},e(a)},[a,e,i]),w=y.useCallback(L=>{var G;const H=i.downloadParams||{};i.downloadParams={...H,body:{...H.body||{},settings:{...((G=H.body)==null?void 0:G.settings)||{},showTotals:L}}},e(a)},[a,e,i]),C=y.useCallback(L=>{var G;const H=i.downloadParams||{};i.downloadParams={...H,body:{...H.body||{},settings:{...((G=H.body)==null?void 0:G.settings)||{},exceptionHandling:L}}},e(a)},[a,e,i]),v=y.useCallback((L,H,G)=>{const le=(Array.isArray(H)?H:H?[H]:[]).filter(O=>typeof O=="string");let re=l.filter(O=>le.some(U=>{const A=d.find(q=>q.name===U);return A==null?void 0:A.objectIds.includes(O)}));le.forEach(O=>{const K=d.find(U=>U.name===O);K&&K.objectIds.forEach(U=>{re.includes(U)||re.push(U)})}),i.categoryIds=re,re.length>0&&(i.linkedMeasureSheetItemIds=[]),e(a)},[d,l,a,e,i]);return t.jsxs("div",{children:[t.jsx(Oe,{label:"App Title",value:(i==null?void 0:i.appTitle)||"",templateKey:"appTitle",onTemplateChange:f}),t.jsx(Oe,{label:"PDF Title",value:(i==null?void 0:i.contractTitle)||"",templateKey:"contractTitle",onTemplateChange:f}),t.jsx(ie,{sx:{mx:1}}),t.jsx(ke,{label:"Begin on New Page",value:!!(i!=null&&i.newPage),onChange:L=>f("newPage",L,"boolean")}),t.jsx(ke,{label:"Draw Border",value:!!(i!=null&&i.drawBorder),onChange:L=>f("drawBorder",L,"boolean")}),t.jsx(ke,{label:"Hidden In App",value:!(i!=null&&i.userInputRequired),onChange:L=>f("userInputRequired",!L,"boolean")}),t.jsx(ke,{label:"Allow Copy/Paste",value:!!(i!=null&&i.canAddMultiple),onChange:L=>f("canAddMultiple",L,"boolean")}),t.jsx(qe,{label:"Shading Style",options:WC,templateKey:"shading",selectedValue:(i==null?void 0:i.shading)||0,valueType:"number",onTemplateChange:f}),t.jsx(ie,{sx:{mx:1}}),c&&t.jsx(Hs,{rowNumber:4}),!c&&u&&t.jsx("div",{style:{padding:"8px 16px",color:"error.main"},children:"Error loading categories"}),!c&&!u&&t.jsx(Yn,{label:"Linked Categories",options:d.map(L=>({value:L.name,label:L.name})),selectedValues:d.filter(L=>L.objectIds.every(H=>l.includes(H))).map(L=>L.name),templateKey:"categoryIds",onTemplateChange:v,disabled:r.length>0}),t.jsx(ie,{sx:{mx:1}}),t.jsxs(t.Fragment,{children:[t.jsx(qe,{label:"Integration",options:VC,templateKey:"integration",selectedValue:((D=i==null?void 0:i.downloadParams)==null?void 0:D.endpoint)||"_none_",valueType:"string",onTemplateChange:(L,H)=>j(H)}),((F=i.downloadParams)==null?void 0:F.endpoint)===Vn.fenevision&&t.jsxs(t.Fragment,{children:[t.jsx(qe,{label:"Manufacturer",options:m,templateKey:"manufacturer",selectedValue:(x==null?void 0:x.id)||"",valueType:"string",onTemplateChange:(L,H)=>S(H),isLoading:h,error:g,emptyMessage:"No manufacturers available"}),t.jsx(ke,{label:"Show Totals",value:!!((P=(R=(M=i==null?void 0:i.downloadParams)==null?void 0:M.body)==null?void 0:R.settings)!=null&&P.showTotals),onChange:w}),t.jsx(qe,{label:"Exception Handling",options:KC,templateKey:"exceptionHandling",selectedValue:((B=(T=(k=i==null?void 0:i.downloadParams)==null?void 0:k.body)==null?void 0:T.settings)==null?void 0:B.exceptionHandling)??1,valueType:"number",onTemplateChange:(L,H)=>{C(Number(H))}})]})]})]})},GC=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem}),JC=n=>({setTemplateState:e=>n(ee(e))}),YC=Z(GC,JC)(UC),XC=n=>{const{setTemplateState:e,templateValues:s,editCellItem:o}=n,a=new $(s.toJSON()),i=a.getObjectWithId(o.objectId)||{},l=y.useCallback((r,d,c)=>{const u=c==="number"?Number(d):d;i[r]=u,e(a)},[a,e,i]);return t.jsxs("div",{children:[t.jsx(Oe,{label:"Above Line (Value)",value:(i==null?void 0:i.value)||"",templateKey:"value",onTemplateChange:l}),t.jsx(Oe,{label:"Below Line (Note)",value:(i==null?void 0:i.note)||"",templateKey:"note",onTemplateChange:l}),t.jsx(ie,{sx:{mx:1}}),t.jsx(ke,{label:"Underline",value:!!(i!=null&&i.underline),onChange:r=>l("underline",r,"boolean")})]})},ZC=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem}),QC=n=>({setTemplateState:e=>n(ee(e))}),eI=Z(ZC,QC)(XC),tI=n=>{const{setTemplateState:e,templateValues:s,editCellItem:o}=n,a=new $(s.toJSON()),i=a.getObjectWithId(o.objectId)||{},l=y.useCallback((r,d,c)=>{const u=c==="number"?Number(d):d;i[r]=u,e(a)},[a,e,i]);return t.jsxs("div",{children:[t.jsx(Oe,{label:"App Note",value:(i==null?void 0:i.appNote)||"",templateKey:"appNote",onTemplateChange:l}),t.jsx(Oe,{label:"Contract Note",value:(i==null?void 0:i.contractNote)||"",templateKey:"contractNote",onTemplateChange:l}),t.jsx(Oe,{label:"Footer Note",value:(i==null?void 0:i.footerNote)||"",templateKey:"footerNote",onTemplateChange:l}),t.jsx(ie,{sx:{mx:1}}),t.jsx(ke,{label:"Underline",value:!!(i!=null&&i.underline),onChange:r=>l("underline",r,"boolean")}),t.jsx(qe,{label:"Column",options:HC,templateKey:"column",selectedValue:(i==null?void 0:i.column)||0,valueType:"number",onTemplateChange:l})]})},nI=({templatesEdit:n={}})=>
13({templateValues:n[n.currentWorkingId],editCellItem:n.editCellItem}),sI=n=>({setTemplateState:e=>n(ee(e))}),oI=Z(nI,sI)(tI),aI=n=>{switch(n.cellType){case"header":case"signatures":return X.CellTypes;default:return n.cellTypes}},iI=n=>{const{contractObject:e,secureCaptureEnabled:s,setTemplateState:o,updatedObject:a}=n,i=Fe,[l,r]=y.useState(!1),d=y.useRef(null),c=y.useCallback(u=>{const p=u.target.value;switch(a.cellType=p,p){case"textXLong":a.inputType="default";break;case"provia":a.inputType="picker",a.pickerValues=[""];break}o(e)},[e,a]);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:d,"aria-describedby":"cell-type-menu",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[t.jsxs(he,{sx:i.menuLabel,children:[t.jsx("span",{children:"Cell Type"}),t.jsx(z,{className:"selected-value",noWrap:!0,sx:{width:"59px",textAlign:"right"},children:X.cellTypeLabelForCellType(a==null?void 0:a.cellType)})]}),t.jsx(Yt,{className:"subMenuIcon"})]}),t.jsx(Ze,{id:"cell-type-menu",sx:{zIndex:1300},open:l,anchorEl:d.current,placement:"right-start",transition:!0,onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:({TransitionProps:u})=>{var p;return t.jsx(Qe,{...u,timeout:350,children:t.jsx(Je,{sx:{minWidth:"220px"},elevation:4,children:t.jsx(Tt,{children:t.jsx(Bs,{value:(a==null?void 0:a.cellType)||null,onChange:c,children:(p=aI(a))==null?void 0:p.map(h=>{var m,f;const g=X.cellTypeLabelForCellType(h);let x=!0;return(h==="creditCardCell"||h==="bankAccountCell"||h==="securePaymentCaptureAll")&&(x=s),((f=(m=a==null?void 0:a.linkedValueSettings)==null?void 0:m.cellTypes)==null?void 0:f.length)>0&&(x=a.linkedValueSettings.cellTypes.includes(h)),t.jsx(Q,{title:"This is incompatible with the selected linked field.",placement:"right",disableHoverListener:x,disableFocusListener:x,disableTouchListener:x,children:t.jsx("span",{children:t.jsx(ue,{sx:i.radioMenuItem,disabled:!x,children:t.jsx(Ft,{value:h,control:t.jsx(An,{size:"small",color:"secondary"}),label:t.jsx(Te,{primary:g})})})})},h)})})})})})}})]})},lI=({auth:{company:n}})=>({secureCaptureEnabled:n==null?void 0:n.get("spreedlyEnabled")}),rI=n=>({setTemplateState:e=>n(ee(e))}),cI=Z(lI,rI)(iI),dI=n=>{const{templateValues:e,editCellItem:s,setTemplateState:o,disabled:a,isIndented:i,updateKey:l}=n,r=new $(e.toJSON()),d=r.getObjectWithId(s.objectId)||{},c=d[l],u=Fe,[p,h]=y.useState(!1),[g,x]=y.useState(!0),m=y.useRef(null),f=y.useRef(null),j=y.useMemo(()=>r.getAllCellIdentifiers(d.cellId).map(C=>({value:C,label:C})),[r]),S=y.useCallback(w=>{const C=f.current;if(!C)return;const v=C.selectionStart,I=C.selectionEnd,D=d[l]||"",F=D.substring(0,v)+w+D.substring(I);d[l]=F,o(r),requestAnimationFrame(()=>{C.focus(),C.selectionStart=C.selectionEnd=v+w.length})},[d,o]);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:m,"aria-describedby":"dynamic-conditions-submenu",onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),disableRipple:!0,disabled:a,sx:{pl:i?5:2},children:[t.jsxs(he,{sx:u.menuLabel,children:[t.jsx("span",{children:"Formula"}),t.jsx(z,{className:"selected-value",noWrap:!0,children:c})]}),t.jsx(Yt,{className:"subMenuIcon"})]}),t.jsx(Ze,{id:"dynamic-conditions-submenu",sx:{zIndex:1300},open:p,anchorEl:m.current,placement:"right-start",transition:!0,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:({TransitionProps:w})=>t.jsx(Qe,{...w,timeout:350,children:t.jsx(Je,{sx:{minWidth:"260px"},elevation:4,children:t.jsxs(Tt,{children:[t.jsx(Cn,{sx:{p:1,focus:"visible"},onKeyDown:C=>C.stopPropagation(),children:t.jsxs("div",{children:[t.jsx("textarea",{"aria-label":"minimum height",ref:f,style:{borderColor:"rgba(0, 0, 0, 0.23)",width:"100%",borderRadius:"8px",padding:"8.5px 14px",resize:"both",minWidth:"238px",...!g&&{outline:"red auto 2px"}},rows:3,placeholder:"Enter Formula",value:c||"",onChange:C=>{const v=C.target.value;x(!v.includes(`[${s.cellId}]`)),d[l]=v,o(r)}}),!g&&t.jsxs(Dp,{sx:{color:"error.main",mt:0},children:['You can not reference the current cell "[',s.cellId,']"!']})]})}),t.jsx(ie,{}),t.jsx(qe,{label:"Identifiers",options:j,templateKey:"inputType",selectedValue:"",valueType:"string",onTemplateChange:(C,v)=>S(`[${v}]`),disableSelection:!0}
13),t.jsx(qe,{label:"Placeholders",options:Bb,templateKey:"placeholders",selectedValue:"",valueType:"string",onTemplateChange:(C,v)=>S(v),disableSelection:!0})]})})})})]})},uI=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem}),pI=n=>({setTemplateState:e=>n(ee(e))}),Ed=Z(uI,pI)(dI),hI=n=>{const{templateValues:e,editCellItem:s,setTemplateState:o,onChange:a}=n,i=new $(e.toJSON()),l=i.getObjectWithId(s.objectId)||{},{cellType:r,linkedMeasureSheetItemConfig:d={},inputType:c}=l,u=et,[p,h]=y.useState(!1),g=()=>{h(!p)},x=y.useMemo(()=>!V(r,"showTitle")||!V(r,"showSelectedOption")||!V(r,"showQuantity")||!V(r,"showMeasureType")||!V(r,"showUnitTotal")||!V(r,"showGrandTotal")||!V(r,"formula")||!V(r,"hideUnlessAddedToEstimate"),[r]),m=(f,j)=>{l.linkedMeasureSheetItemConfig={...d,[f]:j},o(i)};return t.jsxs("div",{children:[t.jsxs(St,{onClick:g,disabled:!x,children:[t.jsx(Te,{primary:"Measure Item Detail Settings"}),p?t.jsx(kn,{}):t.jsx(Pt,{})]}),t.jsx(Dt,{in:x?p:!1,timeout:"auto",unmountOnExit:!0,children:t.jsxs(Xt,{component:"div",disablePadding:!0,sx:u.collapseList,children:[t.jsx(ke,{label:"Show Title",value:d==null?void 0:d.title,onChange:f=>m("title",f),isIndented:!0,disabled:V(r,"showTitle")}),t.jsx(ke,{label:"Show Selected Option",value:d==null?void 0:d.subtitle,onChange:f=>m("subtitle",f),isIndented:!0,disabled:V(r,"showSelectedOption")}),t.jsx(ke,{label:"Show Quantity",value:d.quantity,onChange:f=>m("quantity",f),isIndented:!0,disabled:V(r,"showQuantity")}),t.jsx(ke,{label:"Show Measure Type",value:d.measurementType,onChange:f=>m("measurementType",f),isIndented:!0,disabled:V(r,"showMeasureType")}),t.jsx(ke,{label:"Show Unit Total",value:d.unitTotal,onChange:f=>m("unitTotal",f),isIndented:!0,disabled:V(r,"showUnitTotal")}),t.jsx(ke,{label:"Show Grand Total",value:d.total,onChange:f=>m("total",f),isIndented:!0,disabled:V(r,"showGrandTotal")}),t.jsx(ie,{sx:{m:1}}),t.jsx(Ed,{disabled:V(r,"formula"),updateKey:"formula",isIndented:!0}),t.jsx(ke,{label:"Hide Unless Added to Estimate",value:!(l!=null&&l.drawIfEmpty),onChange:f=>a("drawIfEmpty",!f,"boolean"),isIndented:!0,disabled:V(r,"hideUnlessAddedToEstimate")})]})})]})},mI=({auth:n,templatesEdit:e={}})=>({templateValues:e[e.currentWorkingId]||new $,editCellItem:e.editCellItem}),gI=n=>({setTemplateState:e=>n(ee(e))}),xI=Z(mI,gI)(hI),fI=[{value:"captureAndCharge",label:"Capture and Charge"},{value:"captureOnly",label:"Capture Only"}],bI=n=>{const{cellType:e,updatedObject:s,onChange:o}=n,[a,i]=y.useState(!1),l=et,r=()=>{i(!a)},d=y.useMemo(()=>!V(e,"captureLaterEnabled")||!V(e,"successValue")||!V(e,"captureAndChargeEnabled"),[e]);return t.jsxs("div",{children:[t.jsxs(St,{onClick:r,disabled:!d,children:[t.jsx(Te,{primary:"Payment Settings"}),a?t.jsx(kn,{}):t.jsx(Pt,{})]}),t.jsx(Dt,{in:d?a:!1,timeout:"auto",unmountOnExit:!0,children:t.jsxs(Xt,{component:"div",disablePadding:!0,sx:l.collapseList,children:[t.jsx(ke,{label:"Send Payment Request",value:!(s!=null&&s.disablePaymentRequest),onChange:c=>o("disablePaymentRequest",!c,"boolean"),isIndented:!0,disabled:V(e,"captureLaterEnabled")}),t.jsx(Oe,{label:"Success Value",value:s==null?void 0:s.paymentRequestText,templateKey:"paymentRequestText",onTemplateChange:o,isIndented:!0,disabled:V(e,"successValue")||(s==null?void 0:s.disablePaymentRequest)}),t.jsx(ke,{label:"Capture and Charge Enabled",value:!(s!=null&&s.disableCaptureAndCharge),onChange:c=>o("disableCaptureAndCharge",!c,"boolean"),isIndented:!0,disabled:V(e,"captureAndChargeEnabled")}),t.jsx(qe,{label:"Default Payment Mode",templateKey:"defaultPaymentMode",onTemplateChange:o,options:fI,selectedValue:(s==null?void 0:s.defaultPaymentMode)||"captureAndCharge",isIndented:!0,disabled:V(e,"defaultPaymentMode")||!!(s!=null&&s.disableCaptureAndCharge)})]})})]})},ro=n=>{const{label:e,minSize:s=1,maxSize:o,disabled:a=!1,onChange:i,value:l=1,stepper:r=4,isIndented:d,hideMinus:c}=n,u=p=>{const h=l;switch(p){case"increase":const g=o&&h+r>=o?o:h+r;i(g);break;case"decrease":const x=h-r<=s?s:h-r;i(x);break}};return t.jsxs(ue,{disableRipple:!0,sx:{justifyContent:"space-between",pl:d?5:2},disabled:a,children:[e,t.jsxs(xo,{size:"small",children:[t.jsx(ye,{"aria-label":"Decrease Height",size:"small",disabled:l<=s,onClick:()=>u("decrease"),sx:{visibility:c?"hidden":"visible"},children:t.jsx(rc,{fontSize:"inherit"})}),t.jsx(ie,{orientation:"vertical",sx:{height:"15px",alignSelf:"center",visibility:c?"hidden":"visible"}}),t.jsx(ye,{"aria-label":"Increase Height",size:"small",disabled:o?l>=o:!1,onClick:()=>u("increase"),children:t.jsx(wn,{fontSize:"inherit"})})]})]})},yI=n=>{const{cellType:e,updatedObject:s,onChange:o}=n,{photoTag:a,imageHeight:i,emptySpaceHeight:l,allowReportPhotos:r}=s,[d,c]=y.useState(!1),u=et,p=()=>{c(!d)},h=y.useMemo(()=>!V(e,"imageSize")||!V(e,"sketchHeight")||!V(e,"emptySpaceHeight")||!V(e,"defaultTag"),[e]);return t.jsxs("div",{children:[t.jsx(ke,{label:"Link Report Photos",value:r,onChange:g=>o("allowReportPhotos",g,"boolean"),disabled:V(e,"linkReportPhotos")}),t.jsxs(St,{onClick:p,disabled:!h,children:[t.jsx(Te,{primary:"Media Size Settings"}),d?t.jsx(kn,{}):t.jsx(Pt,{})]}),t.jsx(Dt,{in:h?d:!1,timeout:"auto",unmountOnExit:!0,children:t.jsxs(Xt,{component:"div",disablePadding:!0,sx:u.collapseList,children:[t.jsx(ro,{label:"Image Size",minSize:1,maxSize:1e3,stepper:1,value:i,onChange:g=>o("imageHeight",g,"number"),isIndented:!0,disabled:V(e,"imageSize")}),t.jsx(ro,{label:"Sketch Pad Height",minSize:1,stepper:10,value:i,onChange:g=>o("imageHeight",g,"number"),isIndented:!0,disabled:V(e,"sketchHeight")}),t.jsx(ro,{label:"Empty Space Height",minSize:1,maxSize:1e3,stepper:4,value:l,onCh
13ange:g=>o("emptySpaceHeight",g,"number"),isIndented:!0,disabled:V(e,"emptySpaceHeight")}),t.jsx(Oe,{label:"Default Tag",value:a,multiline:!0,templateKey:"photoTag",onTemplateChange:o,isIndented:!0,disabled:V(e,"defaultTag")})]})})]})},jI=n=>{const{cellType:e,updatedObject:s,onChange:o}=n,a=et,[i,l]=y.useState(!1),r=()=>{l(!i)},d=y.useMemo(()=>!V(e,"hideInApp")||!V(e,"hideOnPDF"),[e]);return t.jsxs("div",{children:[t.jsx(ke,{label:"Required",value:s.required,onChange:c=>o("required",c,"boolean"),disabled:V(e,"required")}),t.jsx(ke,{label:"Disable Editing",value:s.inputDisabled,onChange:c=>o("inputDisabled",c,"boolean"),disabled:V(e,"inputDisabled")}),t.jsxs(St,{onClick:r,disabled:!d,children:[t.jsx(Te,{primary:"Input Rules"}),i?t.jsx(kn,{}):t.jsx(Pt,{})]}),t.jsx(Dt,{in:d?i:!1,timeout:"auto",unmountOnExit:!0,children:t.jsxs(Xt,{component:"div",disablePadding:!0,sx:a.collapseList,children:[t.jsx(ke,{label:"Hide In App",value:s==null?void 0:s.hidden,onChange:c=>o("hidden",c,"boolean"),isIndented:!0,disabled:V(e,"hideInApp")}),t.jsx(ke,{label:"Hide On PDF",value:s==null?void 0:s.appOnly,onChange:c=>o("appOnly",c,"boolean"),isIndented:!0,disabled:V(e,"hideOnPDF")})]})})]})},CI=n=>{const{updatedObject:e,onTemplateChange:s,disabled:o=!1,isIndented:a=!1,errorMsg:i=""}=n,l=Fe,[r,d]=y.useState(!1),c=y.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:c,"aria-describedby":"app-title-submenu",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),disabled:o,disableRipple:!0,sx:{pl:a?5:2},children:[t.jsxs(he,{sx:{...l.menuLabel,alignItems:"center"},children:[t.jsx("span",{children:"Title"}),t.jsx(Q,{title:e!=null&&e.titleLinked?"Unlink Document title":"Link Document title",children:t.jsx("span",{children:t.jsx(ye,{"aria-label":"Link Document title",onClick:()=>{s("titleLinked",!(e!=null&&e.titleLinked),"boolean")},sx:{padding:"2px 4px",borderRadius:1},color:"secondary",children:e!=null&&e.titleLinked?t.jsx(Op,{}):t.jsx(Np,{})})})}),t.jsx(z,{className:"selected-value",noWrap:!0,children:e==null?void 0:e.appTitle})]}),t.jsx(Yt,{className:"subMenuIcon"})]}),t.jsx(Ze,{id:"app-title-submenu",sx:{zIndex:1300},open:r,anchorEl:c.current,placement:"right",transition:!0,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:({TransitionProps:u})=>t.jsx(Qe,{...u,timeout:350,children:t.jsx(Je,{sx:{minWidth:"260px"},elevation:4,children:t.jsx(Cn,{sx:{p:1},onKeyDown:p=>p.stopPropagation(),children:t.jsx(Le,{variant:"outlined",placeholder:"Enter Title",color:"secondary",size:"small",fullWidth:!0,value:e==null?void 0:e.appTitle,onChange:p=>{s("appTitle",p.target.value,"string")},slotProps:{input:{sx:{height:32,fontSize:12}}},error:!!i,helperText:i})})})})})]})},II=n=>{const{cellType:e,updatedObject:s,onChange:o}=n,{contractTitle:a,appNote:i,titleLinked:l}=s,r=et,[d,c]=y.useState(!1),u=()=>{c(!d)},p=y.useMemo(()=>!V(e,"pdfTitle")||!V(e,"appNote")||!V(e,"border"),[e]);return t.jsxs("div",{children:[t.jsx(CI,{updatedObject:s,onTemplateChange:o,disabled:V(e,"appTitle")}),t.jsxs(St,{onClick:u,disabled:!p,children:[t.jsx(Te,{primary:"Title Settings"}),d?t.jsx(kn,{}):t.jsx(Pt,{})]}),t.jsx(Dt,{in:p?d:!1,timeout:"auto",unmountOnExit:!0,children:t.jsxs(Xt,{component:"div",disablePadding:!0,sx:r.collapseList,children:[t.jsx(Oe,{label:"PDF Title",value:a,templateKey:"contractTitle",onTemplateChange:o,isIndented:!0,disabled:V(e,"pdfTitle")||l}),t.jsx(Oe,{label:"App Note",value:i,templateKey:"appNote",onTemplateChange:o,isIndented:!0,disabled:V(e,"appNote")}),t.jsx(qe,{label:"Border",options:Kl,templateKey:"border",selectedValue:Kl[0].value,valueType:"number",onTemplateChange:()=>{},isIndented:!0,disabled:V(e,"border")})]})})]})},SI=n=>{const{cellType:e,updatedObject:s,onChange:o}=n,{drawIfEmpty:a,switchValueOn:i,switchValueOff:l,value:r,emptyValue:d,inputType:c,clearValueIfZero:u}=s,p=et,[h,g]=y.useState(!1),x=()=>{g(!h)},m=y.useMemo(()=>V(e,"hideIfLeftBlank")||!V(e,"valueIfLeftBlank")||!V(e,"onValue")||!V(e,"offValue"),[e]);return t.jsxs("div",{children:[V(e,"formulaSettings",c)?t.jsx(Oe,{label:"Value",value:r,templateKey:"value",onTemplateChange:o,multiline:!0,disabled:V(e,"defaultValue")}):t.jsx(Ed,{disabled:V(e,"formulaSettings",c),updateKey:c==="textFormula"?"value":"formula"}),t.jsxs(St,{onClick:x,disabled:!m,children:[t.jsx(Te,{primary:"Value Settings"}),h?t.jsx(kn,{}):t.jsx(Pt,{})]}),t.jsx(Dt,{in:m?h:!1,timeout:"auto",unmountOnExit:!0,children:t.jsxs(Xt,{component:"div",disablePadding:!0,sx:p.collapseList,children:[t.jsx(ke,{label:"Hide If Left Blank",value:!a,onChange:f=>o("drawIfEmpty",!f,"boolean"),isIndented:!0,disabled:V(e,"hideIfLeftBlank")}),t.jsx(Oe,{label:"Value If Left Blank",value:d,templateKey:"emptyValue",onTemplateChange:o,isIndented:!0,disabled:V(e,"valueIfLeftBlank")||!a}),t.jsx(ke,{label:"Clear Value If Zero",value:u,onChange:f=>o("clearValueIfZero",f,"boolean"),isIndented:!0,disabled:V(e,"clearValueIfZero",c)}),t.jsx(Oe,{label:"On Value",value:i,templateKey:"switchValueOn",onTemplateChange:o,isIndented:!0,disabled:V(e,"onValue")}),t.jsx(Oe,{label:"Off Value",value:l,templateKey:"switchValueOff",onTemplateChange:o,isIndented:!0,disabled:V(e,"offValue")})]})})]})},Ad=n=>{const{label:e,value:s,templateKey:o,onTemplateChange:a,disabled:i=!1,isIndented:l=!1,errorMsg:r="",rows:d=3,placeholder:c=""}
13=n,u=Fe,[p,h]=y.useState(!1),g=y.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:g,"aria-describedby":`${o}-submenu`,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),disabled:i,disableRipple:!0,sx:{pl:l?5:2},children:[t.jsxs(he,{sx:u.menuLabel,children:[t.jsx("span",{children:e}),t.jsx(z,{className:"selected-value",noWrap:!0,children:s==null?void 0:s.length})]}),t.jsx(Yt,{className:"subMenuIcon"})]}),t.jsx(Ze,{id:`${o}-submenu`,sx:{zIndex:1300},open:p,anchorEl:g.current,placement:"right-start",transition:!0,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:({TransitionProps:x})=>t.jsx(Qe,{...x,timeout:350,children:t.jsx(Je,{sx:{minWidth:"260px"},elevation:4,children:t.jsx(Cn,{sx:{p:1},onKeyDown:m=>m.stopPropagation(),children:t.jsx("textarea",{"aria-label":"minimum height",style:{borderColor:"rgba(0, 0, 0, 0.23)",width:"100%",borderRadius:"8px",padding:"8.5px 14px",resize:"both",minWidth:"238px"},rows:d,placeholder:c||`Enter ${e}`,value:s==null?void 0:s.join(`
14`),onChange:m=>{var j;const f=(j=m.target.value)==null?void 0:j.split(`
15`);a(o,f,"array")}})})})})})]})},vI=(n,e)=>{const{cellType:s}=n;switch(s){case"textXLong":return["default","textFormula"];default:return e}},TI=n=>{const{setTemplateState:e,templateValues:s,editCellItem:o,isIndented:a,disabled:i=!1}=n,l=Fe,[r,d]=y.useState(!1),c=y.useRef(null),u=new $(s.toJSON()),p=u.getObjectWithId(o.objectId)||{},{inputType:h,linkedValueSettings:g}=p,x=y.useMemo(()=>vI(p,X.inputTypes),[p]),m=y.useCallback(j=>{const S=j.target.value;p.inputType=S,e(u)},[u,p]),f=y.useCallback(j=>{var S,w;return((S=g==null?void 0:g.inputTypes)==null?void 0:S.length)&&!((w=g==null?void 0:g.inputTypes)!=null&&w.includes(j))},[g]);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:c,"aria-describedby":"input-type-menu",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),sx:{pl:a?5:2},disabled:i,children:[t.jsxs(he,{sx:l.menuLabel,children:[t.jsx("span",{children:"Input Type"}),t.jsx(z,{className:"selected-value",noWrap:!0,sx:{width:"59px",textAlign:"right"},children:X.inputTypeLabelForInputType(h)})]}),t.jsx(Yt,{className:"subMenuIcon"})]}),t.jsx(Ze,{id:"input-type-menu",sx:{zIndex:1300},open:r,anchorEl:c.current,placement:"right-start",transition:!0,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:({TransitionProps:j})=>t.jsx(Qe,{...j,timeout:350,children:t.jsx(Je,{sx:{minWidth:"220px"},elevation:4,children:t.jsx(Tt,{children:t.jsx(Bs,{value:h||null,onChange:m,children:x.map(S=>{const w=X.inputTypeLabelForInputType(S);return t.jsx(Q,{placement:"right",title:"This is incompatible with the selected linked field.",disableHoverListener:!f(S),disableFocusListener:!f(S),disableTouchListener:!f(S),children:t.jsx("span",{children:t.jsx(ue,{sx:l.radioMenuItem,disabled:f(S),children:t.jsx(Ft,{value:S,control:t.jsx(An,{size:"small",color:"secondary"}),label:t.jsx(Te,{primary:w})})})})},S)})})})})})})]})},wI=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem}),kI=n=>({setTemplateState:e=>n(ee(e))}),PI=Z(wI,kI)(TI),DI=n=>{const{cellType:e,updatedObject:s,onChange:o}=n,{isTotalSaleAmount:a,inputType:i,minSizePickerHeight:l,maxSizePickerHeight:r,minSizePickerDepth:d,maxSizePickerDepth:c,dateDisplayFormat:u,isCurrencyCell:p}=s,h=et,[g,x]=y.useState(!1),m=()=>{x(!g)},f=y.useMemo(()=>!V(e,"isTotalSaleAmount",p?"currency":"non-currency")||!V(e,"pickerValues",i)||!V(e,"multiSelectorSeparator",i)||!V(e,"fractionDigits",i)||!V(e,"unitedInchSuffix",i)||!V(e,"minSizePickerWidth",i)||!V(e,"maxSizePickerWidth",i)||!V(e,"minSizePickerHeight",i)||!V(e,"maxSizePickerHeight",i)||!V(e,"minSizePickerDepth",i)||!V(e,"maxSizePickerDepth",i)||!V(e,"dateDisplayFormat",i),[e,i,p]);return t.jsxs("div",{children:[t.jsx(PI,{disabled:V(e,"inputType")}),t.jsxs(St,{onClick:m,disabled:!f,children:[t.jsx(Te,{primary:"Input Settings"}),g?t.jsx(kn,{}):t.jsx(Pt,{})]}),t.jsx(Dt,{in:f?g:!1,timeout:"auto",unmountOnExit:!0,children:t.jsxs(Xt,{component:"div",disablePadding:!0,sx:h.collapseList,children:[!V(e,"isTotalSaleAmount",p?"currency":"non-currency")&&t.jsx(ke,{label:"Is Total Sale Amount",value:a,onChange:j=>o("isTotalSaleAmount",j,"boolean"),disabled:V(e,"isTotalSaleAmount",p?"currency":"non-currency")}),!V(e,"pickerValues",i)&&t.jsx(Ad,{label:"Picker Options",value:s==null?void 0:s.pickerValues,templateKey:"pickerValues",onTemplateChange:o,disabled:V(e,"pickerValues",i)}),!V(e,"multiSelectorSeparator",i)&&t.jsx(Oe,{label:"Multi Select Separator",value:s==null?void 0:s.multiSelectorSeparator,templateKey:"multiSelectorSeparator",onTemplateChange:o,disabled:V(e,"multiSelectorSeparator",i)}),!V(e,"fractionDigits",i)&&t.jsx(qe,{label:"Fraction Digits",options:Ca,templateKey:"fractionDigits",selectedValue:(s==null?void 0:s.fractionDigits)||Ca[0].value,valueType:"string",onTemplateChange:o,disabled:V(e,"fractionDigits",i)}),!V(e,"unitedInchSuffix",i)&&t.jsx(Oe,{label:"United Inch Suffix",value:s==null?void 0:s.unitedInchSuffix,templateKey:"unitedInchSuffix",onTemplateChange:o,disabled:V(e,"unitedInchSuffix",i)}
15),!V(e,"minSizePickerWidth",i)&&t.jsx(Oe,{label:"Min Width",value:s==null?void 0:s.minSizePickerWidth,templateKey:"minSizePickerWidth",onTemplateChange:o,disabled:V(e,"minSizePickerWidth",i)}),!V(e,"maxSizePickerWidth",i)&&t.jsx(Oe,{label:"Max Width",value:s==null?void 0:s.maxSizePickerWidth,templateKey:"maxSizePickerWidth",onTemplateChange:o,disabled:V(e,"maxSizePickerWidth",i)}),!V(e,"minSizePickerHeight",i)&&t.jsx(Oe,{label:"Min Height",value:l,templateKey:"minSizePickerHeight",onTemplateChange:o,disabled:V(e,"minSizePickerHeight",i)}),!V(e,"maxSizePickerHeight",i)&&t.jsx(Oe,{label:"Max Height",value:r,templateKey:"maxSizePickerHeight",onTemplateChange:o,disabled:V(e,"maxSizePickerHeight",i)}),!V(e,"minSizePickerDepth",i)&&t.jsx(Oe,{label:"Min Depth",value:d,templateKey:"minSizePickerDepth",onTemplateChange:o,disabled:V(e,"minSizePickerDepth",i)}),!V(e,"maxSizePickerDepth",i)&&t.jsx(Oe,{label:"Max Depth",value:c,templateKey:"maxSizePickerDepth",onTemplateChange:o,disabled:V(e,"maxSizePickerDepth",i)}),!V(e,"dateDisplayFormat",i)&&t.jsx(Oe,{label:i==="timePicker"?"Time Format":"Date Format",placeholder:_c[i],value:u,templateKey:"dateDisplayFormat",onTemplateChange:o,disabled:V(e,"dateDisplayFormat",i)})]})})]})},OI=n=>{const{cellType:e,updatedObject:s,onChange:o}=n;return V(e,"imagesSource")?null:t.jsxs("div",{children:[t.jsx(ke,{label:"Use Shared Images",value:s.imagesSource==="default",onChange:a=>o("imagesSource",a?"default":"unique","string")}),t.jsx(ie,{})]})},NI=n=>{const{cellType:e,updatedObject:s,onChange:o}=n,{initialsRequired:a,initialsNote:i}=s;return t.jsxs("div",{children:[t.jsx(ke,{label:"Initial Required",value:a,onChange:l=>o("initialsRequired",l,"boolean"),disabled:V(e,"initialRequired")}),t.jsx(Oe,{label:"Initial Note",value:i,templateKey:"initialsNote",onTemplateChange:o,disabled:V(e,"initialNote")||!a})]})},MI=n=>{const{object:e,index:s,onChange:o,onDelete:a,options:i=[]}=n,{values:l=[],enabled:r,required:d,defaultValue:c,inputType:u,pickerValues:p,fractionDigits:h}=e,g=Fe,x=l.length>0?l.join(", "):[`Condition ${s+1}`],[m,f]=y.useState(!1),j=y.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:j,"aria-describedby":"dynamic-conditions-submenu",onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),sx:{pl:5},disableRipple:!0,children:[t.jsx(he,{sx:g.menuLabel,children:t.jsx(z,{noWrap:!0,sx:{maxWidth:80,fontSize:11},children:x})}),s!==0&&t.jsx(ye,{"aria-label":"Decrease Height",size:"small",onClick:()=>a(s),children:t.jsx(Mp,{fontSize:"inherit"})})]}),t.jsx(Ze,{id:"dynamic-conditions-submenu",sx:{zIndex:1300},open:m,anchorEl:j.current,placement:"right-start",transition:!0,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:({TransitionProps:S})=>t.jsx(Qe,{...S,timeout:350,children:t.jsx(Je,{sx:{minWidth:"260px"},elevation:4,children:t.jsxs(Tt,{children:[s!==0&&t.jsxs(t.Fragment,{children:[i.length?t.jsx(Yn,{label:"Dependent Values",options:i,templateKey:"values",selectedValues:l,onTemplateChange:(w,C=[])=>{o(w,C)}}):t.jsx(Oe,{label:"Dependent Values",value:l[0]||"",templateKey:"values",multiline:!0,onTemplateChange:(w,C)=>{o(w,[C])}}),t.jsx(ie,{})]}),t.jsx(ke,{label:"Show Cell",value:r,onChange:w=>{o("enabled",w)}}),r&&t.jsx(qe,{label:"Input Type",options:ka,templateKey:"inputType",selectedValue:u||"",valueType:"string",onTemplateChange:(w,C)=>{o(w,C)}}),r&&(u==="picker"||u==="multiSelectPicker")&&t.jsx(Ad,{label:"Picker Options",value:p,templateKey:"pickerValues",onTemplateChange:o}),r&&(u==="sizePicker"||u==="3DSizePicker")&&t.jsx(qe,{label:"Fraction Digits",options:Ca,templateKey:"fractionDigits",selectedValue:h||"",valueType:"string",onTemplateChange:(w,C)=>{o(w,C)}}),t.jsx(ke,{label:"Required",value:d,onChange:w=>{o("required",w)}}),t.jsx(Oe,{label:"Default Value",value:c,templateKey:"defaultValue",onTemplateChange:(w,C)=>{o(w,C)}})]})})})})]})},LI=n=>{var f,j;const{editCellItem:e,templateValues:s,setTemplateState:o,onChange:a}=n,i=et,l=new $(s.toJSON()),r=l.getObjectWithId(e.objectId)||{},{cellType:d}=r,[c,u]=y.useState(!1),p=()=>{u(!c)},h=y.useMemo(()=>{let S=r!=null&&r.dynamicInputType?{...r.dynamicInputType}:{};S.objects=S.objects||[];let w=S.objects.find(({values:C=[]})=>C.indexOf("default")===0);return w||(w={inputType:"default",enabled:!1,required:!1,values:["default"],fractionDigits:"",pickerValues:[]},S.objects.unshift(w)),S},[r]),g=y.useMemo(()=>l.dynamicValueOptionsForCellId(h.cellId).map(w=>({value:w,label:w})),[l,h.cellId]),x=y.useMemo(()=>r.inputType==="dynamic",[r]),m=y.useMemo(()=>l.getAllCellIdentifiers(r==null?void 0:r.cellId).slice(0).reverse().map(w=>({value:w,label:w})),[]);return t.jsxs("div",{children:[t.jsx(ke,{label:"Dynamic",value:r.
15inputType==="dynamic",onChange:S=>a("inputType",S?"dynamic":"","string"),disabled:V(d,"dynamic")}),t.jsxs(St,{onClick:p,disabled:r.inputType!=="dynamic",children:[t.jsx(Te,{primary:"Dynamic Settings"}),c?t.jsx(kn,{}):t.jsx(Pt,{})]}),t.jsx(Dt,{in:x?c:!1,timeout:"auto",unmountOnExit:!0,children:t.jsxs(Xt,{component:"div",disablePadding:!0,sx:i.collapseList,children:[t.jsx(qe,{label:"Dependent Cell",options:m,templateKey:"dynamicInputType.cellId",selectedValue:(h==null?void 0:h.cellId)||"",valueType:"string",onTemplateChange:(S,w,C)=>{r.dynamicInputType={...r==null?void 0:r.dynamicInputType,cellId:w},o(l)},isIndented:!0}),t.jsx(ie,{}),t.jsx(ro,{label:"Conditions",minSize:0,maxSize:100,stepper:1,value:((f=h==null?void 0:h.objects)==null?void 0:f.length)||0,hideMinus:!0,onChange:()=>{var w;const S=((w=r.dynamicInputType)==null?void 0:w.objects)||[];S.push({inputType:"default",enabled:!0,required:!1,values:[],fractionDigits:"",pickerValues:[]}),r.dynamicInputType={...r.dynamicInputType,objects:S},o(l)},isIndented:!0}),t.jsx(ie,{}),(j=h==null?void 0:h.objects)==null?void 0:j.map((S,w)=>t.jsx(MI,{index:w,object:S,options:g,onChange:(C,v)=>{r.dynamicInputType={...h},r.dynamicInputType.objects[w][C]=v,o(l)},onDelete:C=>{r.dynamicInputType.objects.splice(C,1),o(l)}},w))]})})]})},EI=({auth:n,templatesEdit:e={}})=>({templateValues:e[e.currentWorkingId]||new $,editCellItem:e.editCellItem}),AI=n=>({setTemplateState:e=>n(ee(e))}),FI=Z(EI,AI)(LI),RI=n=>{const{setTemplateState:e,templateValues:s,editCellItem:o,categoryFormulaIds:a}=n,i=new $(s.toJSON()),l=i.getObjectWithId(o.objectId)||{},{cellType:r}=l,[d,c]=y.useState(""),[u,p]=y.useState(l.cellId),h=y.useCallback((m,f,j)=>{const S=j==="number"?Number(f):f;l[m]=S,e(i)},[i,e,l]),g=y.useMemo(()=>
15({cellType:r,updatedObject:l,onChange:h}),[r,l,h]),x=y.useCallback((m,f,j)=>{const S=zb({contractObject:i,value:f,categoryFormulaIds:a,currentCellIdentifier:l.cellId});p(f),S?(c(""),h(m,f,j)):c("Invalid: Identifier already exists")},[i,a,l.cellId]);return t.jsxs("div",{children:[t.jsx(cI,{updatedObject:l,contractObject:i}),t.jsx(ie,{}),t.jsx(Oe,{label:"Identifier",value:u,templateKey:"cellId",errorMsg:d,onTemplateChange:x,disabled:V(r,"identifier")}),t.jsx(ie,{}),t.jsx(DI,{...g}),t.jsx(ie,{}),t.jsx(FI,{onChange:h}),t.jsx(ie,{}),t.jsx(jI,{...g}),t.jsx(ie,{}),t.jsx(SI,{...g}),t.jsx(ie,{}),t.jsx(II,{...g}),t.jsx(ie,{}),t.jsx(NI,{...g}),t.jsx(ie,{}),t.jsx(yI,{...g}),t.jsx(ie,{}),t.jsx(OI,{...g}),t.jsx(xI,{onChange:h}),t.jsx(bI,{...g})]})},_I=({auth:n,templatesEdit:e={}})=>{var s;return{templateValues:e[e.currentWorkingId]||new $,editCellItem:e.editCellItem,categoryFormulaIds:(s=n==null?void 0:n.config)==null?void 0:s.categories_.filter(({formulaId:o})=>o).map(({formulaId:o})=>o)}},BI=n=>({setTemplateState:e=>n(ee(e))}),$I=Z(_I,BI)(RI),zI=({toolboxKey:n})=>{switch(n){case"header-title":return t.jsx(AC,{});case"header-cell":return t.jsx(zC,{});case"body-title":return t.jsx(YC,{});case"body-cell":case"body-detail-cell":return t.jsx($I,{});case"signature-title":return t.jsx(oI,{});case"signature-detail":return t.jsx(eI,{});default:return null}},WI=n=>{const{editCellItem:e}=n,s=Fe,o=et,[a,i]=y.useState(null),l=!!a,r=c=>{i(c.currentTarget),qo("doc_editor_new_settings_used")},d=()=>{i(null)};return t.jsxs("div",{children:[t.jsx(we,{id:"settings-button",variant:"outlined",sx:o.toolbarButton,"aria-controls":l?"settings-menu":void 0,"aria-haspopup":"true","aria-expanded":l?"true":void 0,onClick:r,disabled:!(e!=null&&e.toolboxKey),children:"Settings"}),t.jsx(kt,{id:"settings-menu",anchorEl:a,open:l,onClose:d,sx:s.headerMenu,slotProps:{paper:{sx:s.menuPopperStyle}},children:zI({toolboxKey:e==null?void 0:e.toolboxKey})})]})},HI=({templatesEdit:n={}})=>({editCellItem:n.editCellItem}),qI=n=>({setTemplateState:e=>n(ee(e))}),VI=Z(HI,qI)(WI),KI=n=>{var p,h;const{keys:e,updatedObject:s,editKey:o,contractObject:a,setTemplateState:i,editCellItem:l,setEditCellItem:r}=n,d=et,c=y.useCallback((g,x)=>
15{!x||x===null||(s.editKey=x,l.editKey=x,r(s),i(a))},[s]),u=e.indexOf("titleValueControl")>-1;return t.jsxs(Gt,{value:o||null,exclusive:!0,onChange:c,disabled:!u,"aria-label":"Title Value Tool",sx:d.toggleButtonGroup,children:[t.jsx(Ve,{value:"title",children:t.jsx(Q,{title:((p=s==null?void 0:s.titleValueControlTitles)==null?void 0:p[0])||"Title",children:t.jsx(dc,{fontSize:"small"})})}),t.jsx(Ve,{value:"value",children:t.jsx(Q,{title:((h=s==null?void 0:s.titleValueControlTitles)==null?void 0:h[1])||"Value",children:t.jsx(Lp,{fontSize:"small"})})})]})},UI=({templatesEdit:n={}})=>({editCellItem:n.editCellItem}),GI=n=>({setTemplateState:e=>n(ee(e)),setEditCellItem:e=>n(Ne(e))}),JI=Z(UI,GI)(KI),Ys=(...n)=>n.flat().filter(({placeholder:e})=>e).sort((e,s)=>e.name.localeCompare(s.name,void 0,{sensitivity:"base"})),Fd=n=>{const{disabled:e,itemIds:s}=n,[o,a]=y.useState(""),[i,l]=y.useState(!1),r=y.useRef(null),{data:d=[],isFetching:c}=He({queryKey:["getPlaceholdersForMeasureSheetItems",{itemIds:s}],queryFn:async()=>{const h=await se.Cloud.run("getPlaceholdersForMeasureSheetItems",{objectIds:s}),{miscDefault:g,itemDefault:x,itemPlaceholders:m,itemAdditionalDetails:f,optionDefault:j,optionPlaceholders:S,upChargeDefault:w,upChargePlaceholders:C,upChargeAdditionalDetails:v}=h,I=Ys(g),D=Ys(x,m,f),F=Ys(j,S),M=Ys(w,C,v);return[{divider:!0,title:"Misc"},...I,{divider:!0,title:"Items"},...D,{divider:!0,title:"Options"},...F,{divider:!0,title:"UpCharges"},...M]},enabled:!!(s!=null&&s.length)&&i,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,staleTime:1e3*60*5,cacheTime:1e3*60*15,onError:h=>Be.show({message:h.message,timeout:5e3})}),u=y.useCallback(h=>{h&&(navigator.clipboard.writeText(h),Be.show({message:"Copied to clipboard!",timeout:1e3}))},[]),p=y.useMemo(()=>{if(!o)return d;const h=d.filter(x=>{var m,f;return"divider"in x&&x.divider?!0:((m=x.replacement)==null?void 0:m.toLowerCase().includes(o.toLowerCase()))||((f=x.placeholder)==null?void 0:f.toLowerCase().includes(o.toLowerCase()))}),g=[];for(let x=0;x<h.length;x++){const m=h[x];if("divider"in m&&m.divider){const f=h[x+1];if(!f||"divider"in f&&f.divider)continue}g.push(m)}return g},[d,o]);return t.jsxs(t.Fragment,{children:[t.jsxs(ue,{ref:r,"aria-describedby":"linked-placeholders",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),disabled:e,children:[t.jsx(Te,{children:"Linked Placeholders"}),c?t.jsx(vt,{color:"secondary",size:12}):t.jsx(Yt,{className:"subMenuIcon"})]}),t.jsx(Ze,{id:"linked-placeholders",sx:{zIndex:1300},open:i,anchorEl:r.current,placement:"right-start",transition:!0,onMouseEnter:()=>l(!0),onMouseLeave:h=>l(!1),children:({TransitionProps:h})=>t.jsx(Qe,{...h,timeout:350,children:t.jsxs(Je,{sx:{maxWidth:"400px",minWidth:"370px",maxHeight:"600px",overflow:"auto"},elevation:4,children:[c&&t.jsx(Hs,{rowNumber:4}),!c&&t.jsxs(Tt,{children:[t.jsxs(N,{sx:{px:1},children:[t.jsx(Id,{searchedText:o,handleSearch:g=>a(g),onKeyDown:g=>g.stopPropagation(),size:"small",sx:{flex:1},placeholder:"Search placeholders..."}),t.jsx(ie,{sx:{margin:"4px 0 0 0 !important"}})]},"search-placeholders"),t.jsx(N,{sx:{maxHeight:"500px",overflowY:"auto",scrollbarGutter:"stable"},children:p.map(({placeholder:g,name:x="",divider:m,title:f=""},j)=>m?t.jsxs(t.Fragment,{children:[j!==0&&t.jsx(ie,{sx:{mx:1}}),t.jsx(on,{sx:{lineHeight:"33px",color:"black",fontWeight:600,fontSize:12,whiteSpace:"nowrap"},children:f},f)]}):t.jsx(Q,{title:x,placement:"right",disableFocusListener:x.length<33,disableHoverListener:x.length<33,disableTouchListener:x.length<33,children:t.jsx("span",{children:t.jsx(ue,{onClick:()=>u(g),children:t.jsxs(pe,{container:!0,justifyContent:"space-between",alignItems:"center",sx:{width:"100%"},spacing:"8px",children:[t.jsx(pe,{size:"grow",children:t.jsx(z,{noWrap:!0,textAlign:"right",fontSize:11,children:x||"(Blank Name)"})}),t.jsx(pe,{width:10,children:t.jsx(ie,{sx:{borderColor:"black"}})}),t.jsx(pe,{size:"grow",children:t.jsx(z,{noWrap:!0,fontSize:11,children:g})})]})},g)})},`tooltip-${g}-${j}`))})]})]})})})]})},YI=(n,e)=>n.filter(s=>s.objectIds.length>0&&s.objectIds.every(o=>e.includes(o))).map(s=>s.name),Rd=(n,e,s)=>s.length===0&&YI(n,e).length===1,XI=(n,e)=>{if(n.length>0||e.length===0)return!1;const s=e[0].trim();return s?e.every(o=>o.trim()===s):!1},ZI=async n=>{if(n.length===0)return{};try{return await gm(n)}catch(e){throw await rn(e),e}},QI="custom_product",eS=n=>{const e=y.useMemo(()=>n.filter(i=>i&&i!==QI),[n]),s=y.useMemo(()=>["linkedItemCategories",{ids:[...e].sort().join(",")}],[e]),{data:o={},isLoading:a}=He({queryKey:s,queryFn:()=>ZI(e),enabled:e.length>0,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,staleTime:300*1e3,cacheTime:1800*1e3});return{categoryByItemId:o,isLoading:a}},tS="enable-group-by-category-clone",nS="Available only when this 
15section is linked to a single product category — either directly, or through linked items that all belong to one category.",sS="Checking linked item categories…",oS=({templateValues:n,editCellItemId:e,categories:s,categoryIds:o,linkedMeasureSheetItemIds:a,groupByCategoryClone:i,setTemplateState:l})=>{const d=!!zt()[tS],{categoryByItemId:c,isLoading:u}=eS(a),p=y.useMemo(()=>a.map(f=>c[f]??""),[a,c]),h=XI(o,p),g=Rd(s,o,a)||h,x=o.length===0&&a.length>0&&u,m=f=>{const j=new $(n.toJSON()),S=j.getObjectWithId(e);S&&(S.groupByCategoryClone=f,l(j))};return y.useEffect(()=>{i&&o.length===0&&a.length>0&&!u&&!h&&m(!1)},[u,h]),{show:d,value:!!i,disabled:x||!g,tooltip:g?"":x?sS:nS,onToggle:f=>m(f)}},Ql="This section can't be linked because it contains linked line items.",Qo="Categories and linked items cannot be used together. Please clear categories to use linked items.",aS=n=>{const{editCellItem:e,syncPlaceholders:s,templateValues:o,disableDocLinkingRestriction:a,setShowLinkItems:i,setTemplateState:l,handleClose:r}=n,d=Fe,c=new $(o.toJSON()),u=c.getObjectWithId(e==null?void 0:e.objectId)||{},{linkedMeasureSheetItemIds:p=[],categoryIds:h=[],objectId:g}=u,{categories:x,isLoading:m,error:f}=Ei(),j=oS({templateValues:o,editCellItemId:e==null?void 0:e.objectId,categories:x,categoryIds:h,linkedMeasureSheetItemIds:p,groupByCategoryClone:u.groupByCategoryClone,setTemplateState:l}),S=Td({objectId:g,linkedMeasureSheetItemIds:p}),w=y.useMemo(()=>{var I;return a?!1:!!((I=u==null?void 0:u.cellItems)!=null&&I.some(D=>{var M,R;return!!((M=D==null?void 0:D.linkedValueSettings)!=null&&M.objectId)||!!(D!=null&&D.linkedMeasureSheetItem)?!0:!!((R=D==null?void 0:D.detailItems)!=null&&R.some(P=>{var k;return!!((k=P==null?void 0:P.linkedValueSettings)!=null&&k.objectId)||!!(P!=null&&P.linkedMeasureSheetItem)}))}))},[u,a]),C=y.useCallback((v,I,D)=>{const M=(Array.isArray(I)?I:I?[I]:[]).filter(P=>typeof P=="string");let R=h.filter(P=>M.some(T=>{const B=x.find(L=>L.name===T);return B==null?void 0:B.objectIds.includes(P)}));M.forEach(P=>{const k=x.find(T=>T.name===P);k&&k.objectIds.forEach(T=>{R.includes(T)||R.push(T)})}),u.categoryIds=R,R.length>0&&(u.linkedMeasureSheetItemIds=[]),u.groupByCategoryClone=!!u.groupByCategoryClone&&Rd(x,R,u.linkedMeasureSheetItemIds),l(c)},[x,h,c,l,u]);return t.jsxs("div",{children:[t.jsx(on,{sx:{lineHeight:"2",color:"#2e2e2e",fontWeight:600,fontSize:12},children:"Link From Estimates"},"document-actions-header"),t.jsx(ie,{sx:{width:"25%"}}),t.jsx(Q,{title:h.length>0?Qo:w?Ql:"",placement:"right",disableHoverListener:!w&&h.length===0,disableFocusListener:!w&&h.length===0,disableTouchListener:!w&&h.length===0,children:t.jsx("span",{children:t.jsx(ue,{onClick:()=>{i(!0,"linkedMeasureSheetItemIds",!1,"Linked Items",!0),r()},disabled:w||h.length>0,children:t.jsxs(he,{sx:d.menuLabel,children:[t.jsxs(he,{alignItems:"flex-end",direction:"row",children:[t.jsx($e,{children:t.jsx(Is,{})}),t.jsx(Te,{children:"Linked Items"})]}),t.jsx(z,{className:"selected-value",noWrap:!0,sx:{fontWeight:"bold",lineHeight:"17px"},children:S})]})})})}),t.jsx(Q,{title:h.length>0?Qo:w?Ql:"",placement:"right",disableHoverListener:p.length===0&&!w&&h.length===0,disableFocusListener:p.length===0&&!w&&h.length===0,disableTouchListener:p.length===0&&!w&&h.length===0,children:t.jsx("span",{children:t.jsx(Fd,{itemIds:p,disabled:!p.length||w||h.length>0})})}),t.jsx(ie,{sx:{mx:1}}),m?t.jsx(ue,{disabled:!0,children:t.jsx(Te,{primary:"Loading categories..."})}):f?t.jsx(ue,{disabled:!0,children:t.jsx(Te,{primary:"Error loading categories",primaryTypographyProps:{sx:{color:"error.main"}}})}):t.jsx(Yn,{label:"Link Categories",options:x.map(v=>({value:v.name,label:v.name})),selectedValues:x.filter(v=>v.objectIds.every(I=>h.includes(I))).map(v=>v.name),templateKey:"categoryIds",onTemplateChange:C,disabled:p.length>0}),j.show&&t.jsx(ke,{label:"Group by Category Clone",value:j.value,disabled:j.disabled,tooltip:j.tooltip,onChange:j.onToggle}),t.jsx(Q,{title:h.length>0?Qo:"",placement:"right",disableHoverListener:h.length===0,disableFocusListener:h.length===0,disableTouchListener:h.length===0,children:t.jsx("span",{children:t.jsxs(ue,{onClick:async()=>{await s(p,e),r()},disabled:!p.length||h.length>0,children:[t.jsx($e,{children:t.jsx(Ep,{})}),t.jsx(Te,{children:"Sync Placeholders"})]})})})]})},iS=({templatesEdit:n={}})=>{var e;return{templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem,disableDocLinkingRestriction:(e=n.featureFlags)==null?void 0:e.disableDocLinkingRestriction}},lS=n=>({setTemplateState:e=>n(ee(e)),syncPlaceholders:(e,s)=>n($c(e,s)),setShowLinkItems:(e,s,o,a,i)=>n(Ut(e,s,o,a,i))}),rS=Z(iS,lS)(aS),ea=100,cS=async()=>{try{const n=se.User.current(),e=n==null?void 0:n.get("company");if(!e)throw new Error("Company not found");const s=[];let o=!0,a=0;for(;o;){const l=new se.Query("LinkedValueObject");l.equalTo("company",e),l.select("name","cellTypes","inputTypes"),l.ascending("name"),l.limit(ea),l.skip(a);const r=await l.find();s.push(...r),o=r.length===ea,a+=ea}return lt.uniqBy(s,l=>l.get("name"))}catch(n){throw console.error("Error fetching LinkedValueObjects:",n),n}},er={linkedFieldMenuWrapper:{maxWidth:"400px",minWidth:"370px",maxHeight:500,overflowY:"auto",overflowX:"hidden"},linkedFieldMenuItemLabel:{".MuiTypography-root":{overflow:"hidden",
15whiteSpace:"nowrap",textOverflow:"ellipsis",maxWidth:"300px"}}},dS=n=>{const{templateValues:e,editCellItem:s,setTemplateState:o,tooltipText:a="",disabled:i=!1}=n,l=Fe,r=new $(e.toJSON()),d=r.getObjectWithId(s==null?void 0:s.objectId)||{},{linkedValueSettings:c={}}=d,{objectId:u}=c,[p,h]=y.useState(!1),g=y.useRef(null),{data:x=[],isFetching:m}=He({queryKey:["fetchLinkedValueObjects"],queryFn:cS,enabled:p,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,staleTime:1e3*60*5,cacheTime:1e3*60*15,onError:j=>Be.show({message:j.message,timeout:5e3})}),f=y.useMemo(()=>{var j;return((j=x.find(S=>S.id===u))==null?void 0:j.get("name"))||""},[x,u]);return t.jsxs(t.Fragment,{children:[t.jsx(Q,{title:a,placement:"right",disableHoverListener:!i,disableFocusListener:!i,disableTouchListener:!i,children:t.jsx("span",{children:t.jsxs(ue,{ref:g,"aria-describedby":"dynamic-conditions-submenu",onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),disableRipple:!0,disabled:i,children:[t.jsxs(he,{sx:l.menuLabel,children:[t.jsxs(he,{alignItems:"flex-end",direction:"row",children:[t.jsx($e,{children:t.jsx(Is,{})}),t.jsx(Te,{children:"Link Field"})]}),t.jsx(z,{className:"selected-value",noWrap:!0,sx:{fontWeight:"bold",lineHeight:"17px"},children:f})]}),t.jsx(Yt,{className:"subMenuIcon"})]})})}),t.jsx(Ze,{id:"dynamic-conditions-submenu",sx:{zIndex:1300},open:p,anchorEl:g.current,placement:"right-start",transition:!0,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:({TransitionProps:j})=>t.jsx(Qe,{...j,timeout:350,children:t.jsxs(Je,{sx:er.linkedFieldMenuWrapper,elevation:4,children:[m&&t.jsx(Hs,{rowNumber:4}),!m&&t.jsx(Tt,{children:t.jsxs(Bs,{value:u,onChange:S=>{const w=S.target.value;d.linkedValueSettings={...c,objectId:w},o(r)},children:[t.jsx(ue,{sx:l.radioMenuItem,children:t.jsx(Ft,{value:"",control:t.jsx(An,{size:"small",color:"secondary"}),label:t.jsx(Te,{primary:"None"})})},"none"),x.map(S=>t.jsx(ue,{sx:l.radioMenuItem,children:t.jsx(Ft,{value:S.id,control:t.jsx(An,{size:"small",color:"secondary"}),label:t.jsx(Te,{sx:er.linkedFieldMenuItemLabel,primary:S.get("name")})})},S.id))]})})]})})})]})},uS=({templatesEdit:n={}})=>({templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem}),pS=n=>({setTemplateState:e=>n(ee(e))}),hS=Z(uS,pS)(dS),ps="This line item can’t be linked because its section is already linked.",mS=n=>{const{editCellItem:e,templateValues:s,disableDocLinkingRestriction:o,setShowLinkItems:a,handleClose:i}=n,l=Fe,d=new $(s.toJSON()).getObjectWithId(e==null?void 0:e.objectId)||{},{linkedMeasureSheetItemIds:c=[],linkedMeasureSheetItem:u="",measureSheetItemQuantityIds:p=[],measueSheetItemTotalIds:h=[],linkedValueSettings:g={},parent:x}=d,m=y.useMemo(()=>{var S,w,C;return o?!1:!!((S=x.linkedMeasureSheetItemIds)!=null&&S.length||(C=(w=x.parent)==null?void 0:w.linkedMeasureSheetItemIds)!=null&&C.length)},[x,o]),f=y.useMemo(()=>o?!1:!!(c.length||u||p.length||h.length),[c,u,p,h]),j=g==null?void 0:g.objectId;return t.jsxs("div",{children:[t.jsx(on,{sx:l.menuSubHeader,children:"Link to Price Guide"},"document-actions-header"),t.jsx(ie,{sx:{width:"25%"}}),t.jsx(Q,{title:ps,placement:"right",disableHoverListener:!(m||j),disableFocusListener:!(m||j),disableTouchListener:!(m||j),children:t.jsx("span",{children:t.jsx(ue,{onClick:()=>{a(!0,"linkedMeasureSheetItem",!0,"Link Measure Sheet Item"),i()},disabled:m||j,children:t.jsxs(he,{sx:l.menuLabel,children:[t.jsxs(he,{alignItems:"flex-end",direction:"row",children:[t.jsx($e,{children:t.jsx(Is,{})}),t.jsx(Te,{children:"Link Item"})]}),t.jsx(z,{className:"selected-value",noWrap:!0,sx:{fontWeight:"bold",lineHeight:"17px"},children:u?"Linked":"Unlinked"})]})})})}),t.jsx(Q,{title:ps,placement:"right",disableHoverListener:!(m||j),disableFocusListener:!(m||j),disableTouchListener:!(m||j),children:t.jsx("span",{children:t.jsx(Fd,{itemIds:[u],disabled:!u||m})})}),t.jsx(Q,{title:ps,placement:"right",disableHoverListener:!(m||j),disableFocusListener:!(m||j),disableTouchListener:!(m||j),children:t.jsx("span",{children:t.jsx(ue,{onClick:()=>{a(!0,"measureSheetItemQuantityIds",!1,"Link Quantities"),i()},disabled:m||j,children:t.jsxs(he,{sx:l.menuLabel,children:[t.jsxs(he,{alignItems:"flex-end",direction:"row",children:[t.jsx($e,{children:t.jsx(Is,{})}),t.jsx(Te,{children:"Link Quantities"})]}),t.jsx(z,{className:"selected-value",noWrap:!0,sx:{fontWeight:"bold",lineHeight:"17px"},children:p.length})]})})})}),t.jsx(Q,{title:ps,placement:"right",disableHoverListener:!(m||j),disableFocusListener:!(m||j),disableTouchListener:!(m||j),children:t.jsx("span",{children:t.jsx(ue,{onClick:()=>{a(!0,"measueSheetItemTotalIds",!1,"Link Totals"),i()},disabled:m||j,children:t.jsxs(he,{sx:l.menuLabel,children:[t.jsxs(he,{alignItems:"flex-end",direction:"row",children:[t.jsx($e,{children:t.jsx(Is,{})}),t.jsx(Te,{children:"Link Totals"})]}),t.jsx(z,{className:"selected-value",noWrap:!0,sx:{fontWeight:"bold",lineHeight:"17px"},children:h.length})]})})})}),t.jsx(ie,{}),t.jsx(on,{sx:l.menuSubHeader,children:"Link to Documents/Results"},"document-actions-header"),t.jsx(ie,{sx:{width:"25%"}}),t.jsx(hS,{disabled:m||f,tooltipText:ps})]})},gS=({templatesEdit:n={}})=>{var e;return{templateValues:n[n.currentWorkingId]||new $,editCellItem:n.editCellItem,disableDocLinkingRestriction:(e=n.featureFlags)==null?void 0:e.disableDocLinkingRestriction}},xS=n=>({setTemplateState:e=>n(ee(e)),setShowLinkItems:(e,s,o,a)=>n(Ut(e,s,o,a))}),fS=Z(gS,xS)(mS),bS=({toolboxKey:n,handleClose:e})=>{switch(n){case"body-title":return t.jsx(rS,{handleClose:e});case"body-cell":case"body-detail-cell":return t.jsx(fS,{handleClose:e});default:return null}},yS=n=>{const{editCellItem:e}=n,s=Fe,o=et,[a,i]=y.useState(null),l=!!a,r=c=>{i(c.currentTarget)},d=()=>{i(null)};return t.jsxs("div",{children:[t.jsx(we,{id:"link-button",variant:"outlined",sx:o.toolbarButton,"aria-controls":l?"link-menu":void 0,"aria-haspopup":"true","aria-expanded":l?"true":void 0,onClick:r,disabled:!["body-detail-cell","body-title","body-cell"].includes(e==null?void 0:e.toolboxKey),children:"Link"}),t.jsx(kt,{id:"link-menu",anchorEl:a,open:l,onClose:d,sx:s.headerMenu,slotProps:{paper:{sx:s.menuPopperStyle}},children:bS({toolboxKey:e==null?void 0:e.toolboxKey,handleClose:d})})]})},jS=({templatesEdit:n={}})=>({editCellItem:n.editCellItem}),CS=Z(jS,null)(yS),IS=n=>{const{templateValues:e,object:s,hideLegacySettingsButton:o}=n,a=Fe,i=new $(e.toJSON()),l=i.getObjectWithId(s.objectId)||{},r=y.useMemo(()=>(s==null?void 0:s.editKey)!=="value"?l.toolbarKeyMaps:l.secondaryToolbarKeyMaps||{},[s,l]),d=y.useMemo(()=>({keys:(l==null?void 0:l.toolbarKeys)||[],contractObject:i,updatedObject:l,keyMaps:r}),[i,l,r]);return t.jsx(N,{sx:a.toolbarContainerTemp,children:t.jsxs(he,{direction:"row",alignItems:"center",sx:a.toolbar,children:[t.jsx(VI,{}),t.jsx(CS,{}),!o&&t.jsx(rC,{}),t.jsx(ie,{flexItem:!0,orientation:"vertical",sx:{my:1}}),t.jsx(JI,{...d,editKey:s==null?void 0:s.editKey}),t.jsx(ie,{flexItem:!0,orientation:"vertical",sx:{my:1}}),t.jsx(jC,{...d}),t.jsx(ie,{flexItem:!0,orientation:"vertical",sx:{my:1}}),t.jsx(wC,{...d}),t.jsx(ie,{flexItem:!0,orientation:"vertical",sx:{my:1}}),t.jsx(mC,{...d}),t.jsx(ie,{flexItem:!0,orientation:"vertical",sx:{my:1}}),t.jsx(uC,{...d}),t.jsx(ie,{flexItem:!0,orientation:"vertical",sx:{my:1}}),t.jsx(fC,{...d}),t.jsx(ie,{flexItem:!0,orientation:"vertical",sx:{my:1}}),t.jsx(OC,{...d})]})})},SS=({templatesEdit:n={}})=>{var e;return{templateValues:n[n.currentWorkingId]||new $({}),hideLegacySettingsButton:(e=n.featureFlags)==null?void 0:e.hideLegacySettingsButton}},vS=Z(SS,null)(IS),_d={snapshotTable:{my:2,border:"1px solid",borderColor:"divider",borderTopLeftRadius:8,borderTopRightRadius:8,overflow:"hidden",position:"relative"},snapshotTableHeader:{backgroundColor:"gray1.main",padding:"0 36px 0 32px",alignItems:"center",minHeight:"48px"}
15,snapshotTableBody:{height:"400px",overflowY:"auto",scrollbarGutter:"stable",".snapshotTableRow":{padding:"0 32px",cursor:"pointer",borderBottom:"1px solid",borderColor:"divider",alignItems:"center",minHeight:"48px","&:hover":{backgroundColor:"gray2.main"}}},tablePagination:{".MuiTablePagination-toolbar":{minHeight:"30px"},".MuiTablePagination-selectLabel":{marginBottom:"2.5px"},".MuiTablePagination-displayedRows":{marginBottom:"0px"}}},TS=()=>{const n=_d;return t.jsxs(pe,{container:!0,flexWrap:"nowrap",gap:2,sx:n.snapshotTableHeader,children:[t.jsx(pe,{size:"grow",children:t.jsx(z,{variant:"subtitle2",children:"Template"})}),t.jsx(pe,{width:200,children:t.jsx(z,{variant:"subtitle2",children:"User"})}),t.jsx(pe,{width:200,children:t.jsx(z,{variant:"subtitle2",children:"Date Archived"})}),t.jsx(pe,{width:50,children:t.jsx(z,{variant:"subtitle2"})})]})},wS=({snapshot:n,restoreThisVersion:e})=>t.jsxs(pe,{container:!0,flexWrap:"nowrap",gap:2,className:"snapshotTableRow",children:[t.jsx(pe,{size:"grow",children:n.displayName}),t.jsx(pe,{width:200,children:n.lastEditedBy}),t.jsx(pe,{width:200,children:n.archivedDate}),t.jsx(pe,{width:50,children:t.jsx(Q,{title:"Restore previous version",placement:"right",enterDelay:3e3,children:t.jsx(ye,{color:"secondary","aria-label":"Restore previous version",onClick:()=>e({snapshotId:n.id,archivedDate:n.archivedDate}),children:t.jsx(Gr,{color:"secondary"})})})})]},n.id),kS=async({docId:n,page:e=0,limit:s=10})=>await se.Cloud.run("fetchContractSnapshots",{docId:n,page:e,limit:s}),PS=async n=>{try{return await se.Cloud.run("restoreContractObject",{objectId:n})}catch(e){throw e}},DS=n=>{const{docId:e,docType:s,onClose:o}=n,a=_d,i=ft(),[l,r]=y.useState(0),[d,c]=y.useState(10),{data:u=[],isFetching:p,refetch:h}=He({queryKey:["docSnapshots",{docId:e,page:l,limit:d,docType:s}],queryFn:async()=>await kS({docId:e,page:l,limit:d}),retry:!1,enabled:!!e,refetchOnWindowFocus:!1,refetchOnMount:!1,onError:m=>wt({title:"Error Fetching Document Snapshots",error:m}),staleTime:1/0,cacheTime:1/0}),{mutateAsync:g,isLoading:x}=Vt({mutationKey:["restoreDocSnapshot",e],mutationFn:async({snapshotId:m,archivedDate:f})=>{const j=await PS(m);return i(ee(new $(j.toJSON()))),h(),{snapshotId:m,archivedDate:f}},onError:m=>wt({title:"Error Restoring Document Snapshot",error:m}),onSuccess:m=>{o(),Ns({title:"Document Restored",msg:`Document has been restored to the version from ${m.archivedDate}.`})}});return t.jsxs(N,{sx:a.snapshotTable,children:[(x||p)&&t.jsx(Tn,{sx:{zIndex:7,position:"absolute",backgroundColor:"rgba(0, 0, 0, 0.1)"},open:x||p,children:t.jsx(vt,{color:"primary",size:50})}),t.jsx(TS,{}),t.jsx(N,{sx:a.snapshotTableBody,children:u.map(m=>t.jsx(wS,{snapshot:m,restoreThisVersion:g}))}),t.jsx(ie,{}),t.jsx(ns,{component:"div",sx:a.tablePagination,count:u.length<d?u.length:-1,page:l,onPageChange:(m,f)=>r(f),rowsPerPage:d,onRowsPerPageChange:m=>{r(0),c(parseInt(m.target.value,10))},rowsPerPageOptions:[10,25,50,100]})]})},OS=n=>{const{open:e=!1,onClose:s=()=>{},docId:o="",docType:a=""}=n;return t.jsx($s,{modalContainerProps:{sx:{minWidth:1e3,width:1e3}},title:"Restore From Previous Save",open:e,onClose:s,children:t.jsx(DS,{docId:o,docType:a,onClose:s})})},NS=n=>{const{newContractObject:e,template:s,setInitialState:o}=n,[a,i]=y.useState(null),l=y.useMemo(()=>{var c,u,p;return((c=e==null?void 0:e.pdf)!=null&&c.isNew?(u=e==null?void 0:e.pdf)==null?void 0:u._url:(p=e==null?void 0:e.pdf)==null?void 0:p.url)||null},[e==null?void 0:e.pdf]);y.useEffect(()=>()=>{a&&URL.revokeObjectURL(a)},[a]);const r=async d=>{try{if(!d)return;const c=new $(s.toJSON()),u=await as(d,"document","template_pdf");c.pdf=u,o(c);const p=URL.createObjectURL(d);i(p)}catch(c){const u=c;Be.show({message:u.message,timeout:5e3})}};return e.pdf?t.jsx(N,{sx:{minHeight:"750px"},children:t.jsx("embed",{style:{width:"100%",minHeight:"750px"},src:a||l,type:"application/pdf"})}):t.jsx("div",{id:"page-content",children:t.jsx(Ea,{onDrop:d=>r(d[0]),accept:"application/pdf",children:({getRootProps:d,getInputProps:c,isDragActive:u})=>t.jsxs("div",{...d(),style:{width:"100%",height:"100%"},children:[t.jsx("input",{...c()}),t.jsxs(N,{sx:{backgroundColor:u?"rgba(71,121,255, 0.2)":"rgba(71,121,255, 0.03)",minHeight:"255px",border:"2px dashed rgba(71,121,255, 0.5)",borderRadius:"5px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:[t.jsx(cc,{color:"secondary",sx:{fontSize:"36px",mb:2}}
15),t.jsx(we,{color:"secondary",variant:"outlined",children:"Drop PDF file here..."})]})]})})})},MS=n=>({companyLogoUrl:void 0,setCompanyLogoUrl:e=>n({companyLogoUrl:e})}),LS={element:"doc_editor_edit_button_side_panel_used",navigator:"doc_editor_document_tree_button_used",page:"doc_editor_page_setup_button_side_panel_used"},ES=(n,e)=>({drawerOpen:!0,activePanel:"elements",openDrawer:()=>n({drawerOpen:!0}),closeDrawer:()=>n({drawerOpen:!1}),toggleDrawer:()=>n(s=>({drawerOpen:!s.drawerOpen})),setActivePanel:s=>n({activePanel:s}),showPanel:s=>{const{drawerOpen:o,activePanel:a}=e(),i=o&&a===s,l=LS[s];!i&&l&&qo(l),n({activePanel:s,drawerOpen:!0})}}),AS=n=>({expandedKeys:{},toggleNavExpanded:e=>n(s=>{const o={...s.expandedKeys};return o[e]?delete o[e]:o[e]=!0,{expandedKeys:o}}),setNavExpanded:(e,s)=>n(o=>{if(s===!!o.expandedKeys[e])return o;const a={...o.expandedKeys};return s?a[e]=!0:delete a[e],{expandedKeys:a}}),expandAllNav:e=>n(()=>{const s={};return e.forEach(o=>{s[o]=!0}),{expandedKeys:s}}),collapseAllNav:()=>n({expandedKeys:{}})}),ta=n=>{const e=n[n.length-1];return{selectedNodeId:(e==null?void 0:e.id)??null,selectedNodeType:(e==null?void 0:e.type)??null}},FS=n=>({selectedNodes:[],selectedNodeId:null,selectedNodeType:null,selectedReservedDetailId:null,selectNode:(e,s)=>{const o=[{id:e,type:s}];n({selectedNodes:o,...ta(o),selectedReservedDetailId:null})},selectReservedImage:e=>n({selectedNodes:[],selectedNodeId:null,selectedNodeType:null,selectedReservedDetailId:e}),toggleNode:(e,s)=>n(o=>{var r;const a=o.selectedNodes.some(d=>d.id===e),i=(r=o.selectedNodes[0])==null?void 0:r.type;if(!a&&o.selectedNodes.length>0&&s!==i){const d=[{id:e,type:s}];return{selectedNodes:d,...ta(d),selectedReservedDetailId:null}}const l=a?o.selectedNodes.filter(d=>d.id!==e):[...o.selectedNodes,{id:e,type:s}];return{selectedNodes:l,...ta(l),selectedReservedDetailId:null}}),clearSelection:()=>n({selectedNodes:[],selectedNodeId:null,selectedNodeType:null,selectedReservedDetailId:null})}),Bd=["textWords","textSentence","textParagraph","textOnly","switched","emptySpace","imagePicker"],RS=n=>typeof n=="string"&&Bd.includes(n),_S=n=>`region:${n}`,tr=n=>typeof n=="string"&&n.startsWith("region:"),$d=n=>n.level==="cell"?`dropzone:cell:${n.groupId}:${n.index}`:n.level==="row"?`dropzone:row:${n.sectionId}:${n.index}`:n.level==="column"?`dropzone:column:${n.groupId}:${n.index}`:n.level==="headerCell"?`dropzone:headerCell:${n.columnId}:${n.index}`:n.level==="capture"?`dropzone:capture:${n.cellId}:${n.column}:${n.index}`:n.level==="note"?`dropzone:note:${n.captureId}:${n.index}`:n.level==="detail"?`dropzone:detail:${n.cellId}:${n.column}:${n.index}`:`dropzone:section:${n.index}`,zd={textOnly:"default",headerImage:"image",emptySpace:"emptySpace",companyLogo:"companyLogo"},Wd={image:"%image%",companyLogo:"%companyLogo%"},Ai=(n,e,s)=>e==="headerCell"?n.move!==!0&&typeof n.kind=="string"&&n.kind in zd:e==="detail"?n.move===!0?n.level==="detail":RS(n.kind):n.move!==!0&&n.kind==="imagePicker"?!1:n.move!==!0&&n.kind==="headerImage"?e==="cell":n.move!==!0&&n.kind==="signatures"?e==="section"||e==="cell":e==="row"&&n.move!==!0&&s!==void 0&&s!=="body"?!1:n.level===e,BS=(n,e)=>{const s=[],o=Math.max(n.length,e.length);for(let a=0;a<o;a+=1)a<n.length&&s.push(n[a]),a<e.length&&s.push(e[a]);return s},ls=n=>{const e=n.filter(o=>o.cellType==="textXLong"),s=n.filter(o=>o.cellType!=="textXLong");return{left:s.filter((o,a)=>a%2===0),right:s.filter((o,a)=>a%2===1),bottom:e}},Hd=n=>[...BS(n.left,n.right),...n.bottom],qd=(n,e)=>{n.cellType!=="imagePicker"&&(e==="bottom"?n.cellType="textXLong":n.cellType==="textXLong"&&(n.cellType="textLong"))},$S=(n,e,s,o)=>{const a=ls(n);qd(o,e);const i=a[e];return i.splice(Math.min(Math.max(s,0),i.length),0,o),Hd(a)},nr=(n,e,s,o)=>{const a=ls(n),i=["left","right","bottom"];let l,r=-1;if(i.forEach(p=>{const h=a[p].findIndex(g=>g.objectId===e);h>=0&&(l=p,r=h)}),!l)return null;let d=o;if(l===s&&r<d&&(d-=1),l===s&&d===r)return null;const[c]=a[l].splice(r,1);qd(c,s);const u=a[s];return u.splice(Math.min(Math.max(d,0),u.length),0,c),Hd(a)},bs={width:612,height:792,marginX:20,marginY:35},_e=(n,e)=>{var s,o,a,i;return((s=n.cellsById[e])==null?void 0:s.data)??((o=n.groupsById[e])==null?void 0:o.data)??((a=n.capturesById[e])==null?void 0:a.data)??((i=n.notesById[e])==null?void 0:i.data)??n.sectionsById[e]},zS=(n,e)=>{var s;return((s=Object.entries(n.cellIdsByGroup).find(([,o])=>o.includes(e)))==null?void 0:s[0])??null},Fi=(n,e)=>{var s;return((s=Object.entries(n.detailItemIdsByCell).find(([,o])=>o.includes(e)))==null?void 0:s[0])??null},WS=(n,e,s)=>{const o=a=>{const i=(a==null?void 0:a.indexOf(e))??-1;return i<0?null:i+1};if(s==="section"){const a=o(n.sectionIds);return a===null?null:{level:"section",index:a}}if(s==="row"){const a=Object.entries(n.groupIdsBySection).find(([,l])=>l.includes(e)),i=o(a==null?void 0:a[1]);return a&&i!==null?{level:"row",sectionId:a[0],index:i}:null}if(s==="column"){const a=Object.entries(n.columnIdsByGroup).find(([,l])=>l.includes(e)),i=o(a==null?void 0:a[1]);return a&&i!==null?{level:"column",groupId:a[0],index:i}:null}if(s==="cell"){const a=Fi(n,e);if(a){const d=ls((n.detailItemIdsByCell[a]??[]).map(u=>{var p;return{objectId:u,cellType:(p=n.cellsById[u])==null?void 0:p.cellType}})),c=["left","right","bottom"];for(const u of c){const p=d[u].findIndex(h=>h.objectId===e);if(p>=0)return{level:"detail",cellId:a,column:u,index:p+1}}return null}const i=Object.entries(n.cellIdsByColumn).find(([,d])=>d.includes(e));if(i){const d=o(i[1]);return d===null?null:{level:"headerCell",columnId:i[0],index:d}}const l=Object.entries(n.cellIdsByGroup).find(([,d])=>d.includes(e)),r=o(l==null?void 0:l[1]);return l&&r!==null?{level:"cell",groupId:l[0],index:r}:null}return null},HS=(n,e,s)=>{if(s==="cell"){const o=Object.entries(n.cellIdsByColumn).find(([,i])=>i.includes(e));if(o)return{nodeId:o[0],nodeType:"column"};const a=Object.entries(n.cellIdsByGroup).find(([,i])=>i.includes(e));return a?{nodeId:a[0],nodeType:"row"}:null}if(s==="column"){const o=Object.entries(n.columnIdsByGroup).find(([,a])=>a.includes(e));return o?{nodeId:o[0],nodeType:"row"}:null}if(s==="row"){const o=Object.entries(n.groupIdsBySection).find(([,a])=>a.includes(e));return o?{nodeId:o[0],nodeType:"section"}:null}return null},Xs=(n,e)=>{var s;return((s=Object.entries(n.groupIdsBySection).find(([,o])=>o.includes(e)))==null?void 0:s[0])??null},qS=(n,e)=>{var s,o;if(!e)return null;if(e.level==="row")return e.sectionId;if(e.level==="cell")return Xs(n,e.groupId);if(e.level==="headerCell"){const a=(s=Object.entries(n.columnIdsByGroup).find(([,i])=>i.includes(e.columnId)))==null?void 0:s[0];return a?Xs(n,a):null}if(e.level==="capture"){if(n.sectionsById[e.cellId])return e.cellId;const a=(o=Object.entries(n.cellIdsByGroup).find(([,i])=>i.includes(e.cellId)))==null?void 0:o[0];return a?Xs(n,a):null}return e.level==="detail"?Xs(n,zS(n,e.cellId)??""):null},jn=(n,e)=>{var i;if(n.sectionsById[e])return n.sectionsById[e].groupType;const s=Object.entries(n.groupIdsBySection).find(([,l])=>l.includes(e));if(s)return(i=n.sectionsById[s[0]])==null?void 0:i.groupType;const o=Object.entries(n.cellIdsByGroup).find(([,l])=>l.includes(e));if(o)return jn(n,o[0]);const a=Object.entries(n.cellIdsByColumn).find(([,l])=>l.includes(e));if(a){const l=Object.entries(n.columnIdsByGroup).find(([,r])=>r.includes(a[0]));return l?jn(n,l[0]):void 0}},Vd=(n,e,s)=>{var a,i;const o=e.level==="row"?(a=s.sectionsById[e.sectionId])==null?void 0:a.groupType:void 0;if(!Ai(n,e.level,o))return!1;if(e.level==="detail")return n.move!==!0?!0:typeof n.nodeId=="string"&&Fi(s,n.nodeId)===e.cellId;if(n.move===!0&&(e.level==="cell"||e.level==="row")){const l=e.level==="row"?(i=s.sectionsById[e.sectionId])==null?void 0:i.groupType:jn(s,e.groupId);if(jn(s,n.nodeId)!==l)return!1}return!0},Pa={contractId:null,pageId:null,page:bs,sectionIds:[],sectionsById:{},groupsById:{},cellsById:{},groupIdsBySection:{},cellIdsByGroup:{},columnIdsByGroup:{},cellIdsByColumn:{},detailItemIdsByCell:{},capturesById:{},captureIdsByCell:{},notesById:{},noteIdsByCapture:{}},VS=n=>({tree:Pa,setTree:e=>n({tree:e}),resetTree:()=>n({tree:Pa}),setPage:e=>n(s=>({tree:{...s.tree,page:e}})),updateCell:(e,s)=>n(o=>{const a=o.tree.cellsById[e];if(a)return{tree:{...o.tree,cellsById:{...o.tree.cellsById,[e]:{...a,data:{...a.data,...s}}}}};const i=o.tree.groupsById[e];if(i)return{tree:{...o.tree,groupsById:{...o.tree.groupsById,[e]:{...i,data:{...i.data,...s}}}}};const l=o.tree.capturesById[e];if(l)return{tree:{...o.tree,capturesById:{...o.tree.capturesById,[e]:{...l,data:{...l.data,...s}}}}};const r=o.tree.notesById[e];
15return r?{tree:{...o.tree,notesById:{...o.tree.notesById,[e]:{...r,data:{...r.data,...s}}}}}:o})}),sr=n=>Math.min(So,Math.max(Io,n)),KS=(n,e)=>n.length===e.length&&n.every((s,o)=>s.top===e[o].top&&s.height===e[o].height),US=n=>({zoom:1,pageBoxes:[],currentPage:1,canvasEl:null,blockedDropSectionId:null,setZoom:e=>n({zoom:sr(e)}),zoomBy:e=>n(s=>({zoom:sr(s.zoom+e)})),setPageBoxes:e=>n(s=>KS(s.pageBoxes,e)?s:{pageBoxes:e}),setCurrentPage:e=>n({currentPage:Math.max(1,e)}),setCanvasEl:e=>n({canvasEl:e}),setBlockedDropSection:e=>n(s=>s.blockedDropSectionId===e?s:{blockedDropSectionId:e}),resetViewport:()=>n({zoom:1,pageBoxes:[],currentPage:1,blockedDropSectionId:null})}),E=Ap()((...n)=>({...MS(...n),...ES(...n),...AS(...n),...FS(...n),...VS(...n),...US(...n)})),or="#2979ff",GS={zone:n=>({position:"relative",height:0,"&::after":{content:'""',position:"absolute",left:0,right:0,top:0,transform:"translateY(-50%)",height:0,borderTop:`3px dashed ${or}`,filter:`drop-shadow(0 0 3px ${or})`,opacity:n?1:0,transition:e=>e.transitions.create("opacity",{duration:e.transitions.duration.shortest})}})},ut=({target:n})=>{const e=$d(n),{setNodeRef:s,isOver:o,active:a}=zs({id:e,data:n}),i=E(r=>{var d;return n.level==="row"?(d=r.tree.sectionsById[n.sectionId])==null?void 0:d.groupType:void 0}),l=o&&Ai((a==null?void 0:a.data.current)??{},n.level,i);return t.jsx(N,{ref:s,sx:GS.zone(l),"data-testid":`doc-builder-${e}`})},ar={borderRadius:1,border:"1px dashed",borderColor:"grey.300",backgroundColor:"grey.50"},ir={borderBottom:"1px solid",borderColor:"text.secondary",mt:.5},It={root:{display:"flex",flexDirection:"column",width:"100%",padding:"6px 10px"},columns:{display:"flex",width:"100%",gap:3},column:{flex:1,minWidth:0,display:"flex",flexDirection:"column",minHeight:40},capture:{display:"flex",flexDirection:"column"},notes:{display:"flex",flexDirection:"column",mt:1.5},signArea:{...ar,height:56},signRule:ir,signLabel:{color:"text.secondary",mt:.5},extraLine:{display:"flex",flexDirection:"column",minWidth:140},extraValue:{...ar,display:"flex",alignItems:"center",minHeight:32,px:1},extraRule:ir,extraNote:{color:"text.secondary",mt:.5}},JS=[],Kd=({nodeId:n,renderChild:e})=>{const s=E(l=>l.tree.captureIdsByCell[n]??JS),o=E(l=>l.tree.capturesById),a=l=>{var r;return((r=o[l])==null?void 0:r.data.column)===1?1:0},i=l=>{const r=s.filter(d=>a(d)===l);return t.jsxs(N,{sx:It.column,"data-testid":`doc-builder-capture-column-${l}`,children:[t.jsx(ut,{target:{level:"capture",cellId:n,column:l,index:0}}),r.map((d,c)=>t.jsxs(y.Fragment,{children:[e({nodeId:d,nodeType:"capture"}),t.jsx(ut,{target:{level:"capture",cellId:n,column:l,index:c+1}})]},d))]})};return t.jsx(N,{sx:It.root,"data-testid":"doc-builder-widget-signatures",children:t.jsxs(N,{sx:It.columns,children:[i(0),i(1)]})})},YS=()=>{},Ud=y.createContext(YS),Ee=()=>y.useContext(Ud),XS=()=>{},Gd=y.createContext(XS),ZS=()=>y.useContext(Gd),QS={marginTopFor:()=>0,reportRowHeight:()=>{},registerRow:()=>{},isOverflowing:()=>!1},Jd=y.createContext(QS),Yd=()=>y.useContext(Jd),ev=()=>{const[n,e]=y.useState({}),s=y.useRef((o,a)=>{e(i=>i[o]===a?i:{...i,[o]:a})}).current;return[n,s]},tv=n=>{const{reportRowHeight:e,registerRow:s}=Yd(),o=y.useRef(null);return y.useLayoutEffect(()=>{const a=o.current;if(!a)return;s(n,a);const i=()=>e(n,a.offsetHeight);i();const l=new ResizeObserver(i);return l.observe(a),()=>{l.disconnect(),s(n,null)}},[n,e,s]),o},Ri=24,nv=(n,e,s=Ri)=>{const o=e.height-2*e.marginY,a={},i=[],l=[];let r=0;return n.forEach(({id:d,height:c,forceBreak:u})=>{if(c>o&&l.push(d),r>0&&(u||r+c>o)){const h=Math.max(0,o-r);a[d]=h+s+2*e.marginY,i.push(d),r=c}else a[d]=0,r+=c}),{marginTops:a,breakRowIds:i,overflowRowIds:l,pageCount:i.length+1}},Zs={root:{position:"relative"},overflowBadge:{position:"absolute",top:2,right:2,zIndex:2,fontSize:"1.05rem",borderRadius:"50%",backgroundColor:"background.paper"},chipAnchor:n=>({position:"absolute",top:-n,left:0,right:0,display:"flex",justifyContent:"center",transform:"translateY(-50%)",pointerEvents:"none"}),chip:{pointerEvents:"auto",backgroundColor:"common.white",border:"1px solid",borderColor:"divider"}},lr=({rowId:n,leadingDropZone:e,children:s})=>{const{marginTopFor:o,isOverflowing:a}=Yd(),i=tv(n),l=E(g=>{var x,m;return!!((m=(x=g.tree.groupsById[n])==null?void 0:x.data)!=null&&m.newPage)}),r=E(g=>g.tree.page.marginY),d=Ee(),c=o(n),u=c>0&&l,p=a(n),h=2*r+Ri/2;return t.jsxs(N,{ref:i,style:{marginTop:c},sx:Zs.root,children:[u&&t.jsx(N,{sx:Zs.chipAnchor(h),children:t.jsx(uc,{size:"small",label:"Page break",sx:Zs.chip,onClick:g=>g.stopPropagation(),onDelete:()=>d(n,"newPage",!1),"data-testid":"doc-builder-page-break-chip"})}),p&&t.jsx(Q,{title:"This block is taller than one page — it will flow across pages in the final PDF.",children:t.jsx(Fp,{color:"warning",sx:Zs.overflowBadge,"data-testid":`doc-builder-overflow-${n}`})}),e,s]})},na={root:{position:"relative",display:"flex",flexDirection:"column",gap:1,width:"100%"},blockedOverlay:{position:"absolute",inset:-4,borderRadius:1,border:"1.5px dashed",borderColor:n=>Kn(n.palette.error.main,.55),backgroundColor:n=>Kn(n.palette.error.main,.05),pointerEvents:"none",zIndex:4}},sv=[],Xd=({nodeId:n,renderChild:e})=>{const s=E(r=>{var d;return(d=r.tree.sectionsById[n])==null?void 0:d.groupType}),o=E(r=>r.tree.groupIdsBySection[n]??sv),i=E(r=>r.blockedDropSectionId===n)?t.jsx(N,{sx:na.blockedOverlay,"data-testid":"doc-builder-section-blocked"}):null,{setNodeRef:l}=zs({id:_S(n),data:{level:"region",sectionId:n,zone:s}});return s==="signature"?t.jsx(lr,{rowId:n,children:t.jsxs(N,{ref:l,sx:na.root,"data-testid":"doc-builder-section",children:[t.jsx(Kd,{nodeId:n,renderChild:e}),i]})}):t.jsxs(N,{ref:l,sx:na.root,"data-testid":"doc-builder-section",children:[i,o.map((r,d)=>t.jsx(lr,{rowId:r,leadingDropZone:t.jsx(ut,{target:{level:"row",sectionId:n,index:d}}),children:e({nodeId:r,nodeType:"row"})},r)),t.jsx(ut,{target:{level:"row",sectionId:n,index:o.length}})]})},Zd=n=>typeof n=="object"&&n!==null&&"nodes"in n&&Array.isArray(n.nodes),_i=n=>{if(Array.isArray(n))return n;if(Zd(n))return n.nodes},ov=n=>{if(Zd(n))return n.sourceTemplateId},Da=n=>{let e=!1;return typeof n.cellId=="string"&&n.cellId!==""&&(n.cellId="",e=!0),[n.detailItems,n.cellItems,n.data].forEac
15h(s=>{Array.isArray(s)&&s.forEach(o=>{e=Da(o)||e})}),e},Qd=(n,e)=>{let s=!1;return typeof n.cellId=="string"&&n.cellId!==""&&e.has(n.cellId)&&(n.cellId="",s=!0),[n.detailItems,n.cellItems,n.data].forEach(o=>{Array.isArray(o)&&o.forEach(a=>{s=Qd(a,e)||s})}),s},av=(n,e)=>{const s=new Set(e),o=[];return n.forEach(a=>{s.has(a)&&!o.includes(a)&&o.push(a)}),o},iv=n=>{const e=[];return n.forEach(s=>{var o;(o=s.getCellIds)==null||o.call(s).forEach(a=>{a&&!e.includes(a)&&e.push(a)})}),e},Bi=new Rp(void 0),lv=n=>{Bi.next(n)},co=()=>{Bi.next(void 0)},rv=()=>{const n=_p(Bi,void 0);if(!n)return null;const e=()=>{co()},s=()=>{n.onClear(),co()},o=()=>{n.onKeep(),co()},a=n.conflicts.length>0?`These identifiers already exist in this document: ${n.conflicts.join(", ")}`:"No duplicate identifiers found in this document.";return t.jsxs(zo,{"aria-labelledby":"paste-identifiers-modal-title","aria-describedby":"paste-identifiers-modal-description",open:!0,onClose:e,modalContainerProps:{sx:{maxWidth:"640px",minWidth:"540px"}},children:[t.jsx(z,{id:"paste-identifiers-modal-title",textAlign:"center",variant:"subtitle1",color:"text",children:"Paste Options"}),t.jsx(z,{id:"paste-identifiers-modal-description",mt:1,textAlign:"center",children:"You are pasting from another template. Choose how to handle identifiers on the pasted copy."}),t.jsx(z,{mt:1,textAlign:"center",children:a}),t.jsxs(he,{direction:"row",justifyContent:"center",gap:2,mt:3,children:[t.jsx(we,{"data-testid":"doc-builder-paste-identifiers-clear",onClick:s,variant:"outlined",color:"secondary",children:"Clear"}),t.jsx(we,{"data-testid":"doc-builder-paste-identifiers-keep",onClick:o,variant:"contained",color:"primary",children:"Keep"})]})]})},eu=n=>{const[e,s]=typeof n.pageSize=="string"?n.pageSize.split(",").map(Number):[],o=(a,i)=>typeof a=="number"&&a>=0?a:i;return{width:e>0?e:bs.width,height:s>0?s:bs.height,marginX:o(n.wMargin,bs.marginX),marginY:o(n.hMargin,bs.marginY)}},$i=n=>typeof n=="object"&&n!==null&&!("cellType"in n)&&Array.isArray(n.cellItems),rr=n=>Array.isArray(n)||$i(n),As=n=>Array.isArray(n)?n.flatMap(e=>Array.isArray(e)?As(e):$i(e)?As(e.cellItems):[e]):[],cr=n=>typeof n.toJSON=="function"?n.toJSON():n,dr=n=>$i(n)?As(n.cellItems):As(n),zi=n=>{if(!n)return Pa;const e=[],s={},o={},a={},i={},l={},r={},d={},c={},u={},p={},h={},g={},x=m=>{const f=m.objectId;if(!f)return null;const j=cr(m);if(a[f]={objectId:f,cellType:m.cellType??null,data:j},m.cellType==="signatures"&&Array.isArray(j.signatures)){const v=[];j.signatures.forEach(I=>{const D=I==null?void 0:I.objectId;if(typeof D!="string"||!D)return;v.push(D),u[D]={objectId:D,cellId:f,data:I};const F=[];(Array.isArray(I.additionalLines)?I.additionalLines:[]).forEach(M=>{const R=M==null?void 0:M.objectId;typeof R!="string"||!R||(F.push(R),h[R]={objectId:R,captureId:D,data:M})}),F.length>0&&(g[D]=F)}),v.length>0&&(p[f]=v)}const S=[];(Array.isArray(m.detailItems)?m.detailItems:[]).forEach(v=>{const I=v.objectId;I&&(S.push(I),a[I]={objectId:I,cellType:v.cellType??null,data:cr(v)})}),S.length>0&&(c[f]=S);const w=m.header,C=w==null?void 0:w.cellItems;if(m.cellType==="header"&&Array.isArray(C)&&C.length>0&&rr(C[0])){const v=[];C.forEach((I,D)=>{const F=I==null?void 0:I.objectId,M=typeof F=="string"&&F?F:`${f}__col${D}`,R=[];dr(I).forEach(P=>{const k=x(P);k&&R.push(k)}),v.push(M),d[M]=R}),r[f]=v}return f};return(n.contractData??[]).forEach(m=>{const f=m.objectId;if(!f)return;e.push(f),s[f]={objectId:f,groupType:m.groupType??""};const j=[];if(m.groupType==="signature"){const S=[];(m.data??[]).forEach(w=>{const C=w==null?void 0:w.objectId;if(typeof C!="string"||!C)return;S.push(C),u[C]={objectId:C,cellId:f,data:w};const v=[];(Array.isArray(w.additionalLines)?w.additionalLines:[]).forEach(I=>{const D=I==null?void 0:I.objectId;typeof D!="string"||!D||(v.push(D),h[D]={objectId:D,captureId:C,data:I})}),v.length>0&&(g[C]=v)}),S.length>0&&(p[f]=S),i[f]=[];return}(m.data??[]).forEach(S=>{const w=S.objectId;if(!w)return;j.push(w),o[w]={objectId:w,data:S};const C=[],v=S.cellItems??S.additionalLines;if(Array.isArray(v)&&v.length>0&&rr(v[0])){const I=[];v.forEach((D,F)=>
15{const M=D==null?void 0:D.objectId,R=typeof M=="string"&&M?M:`${w}__col${F}`,P=[];dr(D).forEach(k=>{const T=x(k);T&&(P.push(T),C.push(T))}),I.push(R),d[R]=P}),r[w]=I}else As(v).forEach(I=>{const D=x(I);D&&C.push(D)});l[w]=C}),i[f]=j}),{contractId:n.objectId??null,pageId:n.pageId??null,page:eu(n),sectionIds:e,sectionsById:s,groupsById:o,cellsById:a,groupIdsBySection:i,cellIdsByGroup:l,columnIdsByGroup:r,cellIdsByColumn:d,detailItemIdsByCell:c,capturesById:u,captureIdsByCell:p,notesById:h,noteIdsByCapture:g}},wo="doc-builder",ur=(n,e)=>{var l,r,d,c;const s=(l=n.getObjectWithId)==null?void 0:l.call(n,e),o=(r=s==null?void 0:s.getPath)==null?void 0:r.call(s);if(!s||!o||!n.deleteObjectAtPath)return!1;const a=s;if(a.pasteKey==="index_section"&&a.groupType==="body")return!1;const i=s;return i.containerKey==="header_item_group"&&(((c=(d=i.parent)==null?void 0:d.cellItems)==null?void 0:c.length)??0)<=1?!1:(n.deleteObjectAtPath(o),!0)},pr=(n,e,s)=>{var o;return!(!(n!=null&&n.pasteKey)||n.pasteKey!==(e==null?void 0:e.pasteKey)||n.pasteKey==="index_section"&&n.groupType!==(e==null?void 0:e.groupType)||n.groupType==="body"&&((o=s==null?void 0:s.hasBodySection)!=null&&o.call(s)))},hr=()=>_i(sn(wo)),mr=(n,e)=>{const s=Math.min(n.length,e.length);for(let o=0;o<s;o+=1)if(n[o]!==e[o])return n[o]-e[o];return n.length-e.length},cv=(n,e,s,o,a)=>{const i=e.map(d=>{const c=n.findIndex(u=>o(u)===d);return c>=0?{idx:c,item:n[c]}:null}).filter(d=>d!==null).sort((d,c)=>d.idx-c.idx);if(!i.length)return!1;const l=i.filter(d=>d.idx<s).length,r=Math.max(0,s-l);return[...i].sort((d,c)=>c.idx-d.idx).forEach(d=>n.splice(d.idx,1)),i.forEach((d,c)=>{a==null||a(d.item),n.splice(r+c,0,d.item)}),!0},cn=()=>{const n=ft(),e=E(P=>P.setTree),s=E(P=>P.clearSelection),o=ze(P=>{var k;return(k=P.templatesEdit)==null?void 0:k.currentWorkingId}),a=ze(P=>{var k;return o?(k=P.templatesEdit)==null?void 0:k[o]:void 0}),i=y.useCallback(P=>{e(zi(P)),n(ee(P))},[e,n]),l=y.useCallback(P=>{const k=a;!k||!ur(k,P)||(E.getState().selectedNodeId===P&&s(),i(k))},[a,s,i]),r=y.useCallback(P=>{var G,ne;const k=a,T=(G=k==null?void 0:k.getObjectWithId)==null?void 0:G.call(k,P),B=(ne=T==null?void 0:T.getPath)==null?void 0:ne.call(T);if(!k||!T||!B||!T.clone||!k.insertObjectAtPath)return;const L=T.clone(),H=Da(L);k.insertObjectAtPath(B,L,1),i(k),H&&Be.show({message:"Identifier removed from the copy to keep it unique.",severity:"info"})},[a,i]),d=y.useCallback((P,k)=>{var L;const T=a,B=(L=T==null?void 0:T.getObjectWithId)==null?void 0:L.call(T,P);!T||!B||(B.cellType=k,k==="textXLong"&&B.inputType!=="default"&&B.inputType!=="textFormula"&&(B.inputType="default"),i(T))},[a,i]),c=y.useCallback((P,k)=>{var O,K,U,A,q,Y,ce,be,Se,te,ge,me,De;const T=a;if(k.level==="detail"){const Pe=(O=T==null?void 0:T.getObjectWithId)==null?void 0:O.call(T,k.cellId),de=Pe==null?void 0:Pe.detailItems;if(!T||!Pe||!Array.isArray(de))return;const oe=nr(de,P,k.column,k.index);if(!oe)return;Pe.detailItems=oe,i(T);return}const B=(K=T==null?void 0:T.getObjectWithId)==null?void 0:K.call(T,P),L=(U=B==null?void 0:B.getPath)==null?void 0:U.call(B);if(!T||!B||!L||!T.deleteObjectAtPath||!T.insertObjectAtPath)return;const{tree:H}=E.getState();if(k.level==="cell"||k.level==="row"){const Pe=k.level==="row"?(A=H.sectionsById[k.sectionId])==null?void 0:A.groupType:jn(H,k.groupId);if(jn(H,P)!==Pe)return}if(k.level==="column"&&!(H.columnIdsByGroup[k.groupId]??[]).includes(P))return;let G;if(k.level==="cell"||k.level==="column"?G=(ce=(Y=(q=T.getObjectWithId)==null?void 0:q.call(T,k.groupId))==null?void 0:Y.getPath)==null?void 0:ce.call(Y):k.level==="row"?G=(te=(Se=(be=T.getObjectWithId)==null?void 0:be.call(T,k.sectionId))==null?void 0:Se.getPath)==null?void 0:te.call(Se):k.level==="note"?G=(De=(me=(ge=T.getObjectWithId)==null?void 0:ge.call(T,k.captureId))==null?void 0:me.getPath)==null?void 0:De.call(me):G=[],!G)return;const ne=L[L.length-1],le=L.length===G.length+1&&G.every((Pe,de)=>Pe===L[de]);let{index:re}=k;if(le&&ne<re&&(re-=1),!(le&&re===ne)){if(T.deleteObjectAtPath(L),k.level==="section"){const Pe=T.contractData??[];Object.assign(B,{parent:T}),Pe.splice(Math.min(re,Pe.length),0,B)}else T.insertObjectAtPath([...G,re],B,0);i(T)}},[a,i]),u=y.useCallback((P,k)=>{var A,q,Y,ce,be,Se,te,ge;const T=a;if(!T)return;if(k.level==="detail"){const me=(A=T.getObjectWithId)==null?void 0:A.call(T,k.cellId),De=me==null?void 0:me.detailItems;if(!me||!Array.isArray(De))return;let Pe=De,{index:de}=k,oe=!1;P.forEach(Ie=>{const Ue=nr(Pe,Ie,k.column,de);Ue&&(Pe=Ue,de+=1,oe=!0)}),oe&&(me.detailItems=Pe,i(T));return}if(k.level==="section"){const me=T.contractData??[];cv(me,P,k.index,Pe=>Pe.objectId,Pe=>Object.assign(Pe,{parent:T}))&&i(T);return}if(k.level!=="cell"&&k.level!=="row"&&k.level!=="column")return;const{tree:B}=E.getState();let L;k.level==="row"?L=(q=B.sectionsById[k.sectionId])==null?void 0:q.groupType:k.level==="cell"&&(L=jn(B,k.groupId));const H=me=>k.level==="cell"||k.level==="row"?jn(B,me)===L:k.level==="column"?(B.columnIdsByGroup[k.groupId]??[]).includes(me):!0,G=k.level==="row"?k.sectionId:k.groupId;if(!T.deleteObjectAtPath||!T.insertObjectAtPath)return;const ne=P.filter(H).map(me=>{var de,oe;const De=(de=T.getObjectWithId)==null?void 0:de.call(T,me),Pe=(oe=De==null?void 0:De.getPath)==null?void 0:oe.call(De);return De&&Pe?{node:De,path:Pe}:null}).filter(me=>me!==null).sort((me,De)=>mr(me.path,De.path)),le=(be=(ce=(Y=T.getObjectWithId)==null?void 0:Y.call(T,G))==null?void 0:ce.getPath)==null?void 0:be.call(ce);if(!ne.length||!le)return;const re=me=>me.length===le.length+1&&le.every((De,Pe)=>De===me[Pe]),O=ne.filter(me=>re(me.path)&&me.path[me.path.length-1]<k.index).length,K=Math.max(0,k.index-O);[...ne].sort((me,De)=>
15mr(De.path,me.path)).forEach(me=>T.deleteObjectAtPath(me.path));const U=(ge=(te=(Se=T.getObjectWithId)==null?void 0:Se.call(T,G))==null?void 0:te.getPath)==null?void 0:ge.call(te);U&&ne.forEach((me,De)=>T.insertObjectAtPath([...U,K+De],me.node,0)),i(T)},[a,i]),p=y.useCallback((P,k)=>{var A,q;const T=a,B=(A=T==null?void 0:T.getObjectWithId)==null?void 0:A.call(T,P),L=(q=T==null?void 0:T.getObjectWithId)==null?void 0:q.call(T,k.cellId),H=(L==null?void 0:L.signatures)??(L==null?void 0:L.data);if(!T||!B||!Array.isArray(H))return;const G=H.indexOf(B);if(G<0)return;const ne=Y=>Number(Y.column)||0,le=ne(B);let re=0;for(let Y=0;Y<G;Y+=1)ne(H[Y])===le&&(re+=1);let O=k.index;if(le===k.column&&re<O&&(O-=1),le===k.column&&O===re)return;H.splice(G,1),B.column=k.column;const K=[];H.forEach((Y,ce)=>{ne(Y)===k.column&&K.push(ce)});const U=O<K.length?K[O]:H.length;H.splice(U,0,B),i(T)},[a,i]),h=y.useCallback(P=>{var G,ne;const k=a,T=(G=k==null?void 0:k.getObjectWithId)==null?void 0:G.call(k,P),B=(ne=T==null?void 0:T.getPath)==null?void 0:ne.call(T),L=(T==null?void 0:T.signatures)??(T==null?void 0:T.data);if(!k||!T||!B||!Array.isArray(L)||!k.insertObjectAtPath)return;const H=new Ye(void 0,T);k.insertObjectAtPath([...B,L.length],H,0),i(k)},[a,i]),g=y.useCallback((P,k,T)=>{var ne;const B=a,L=(ne=B==null?void 0:B.getObjectWithId)==null?void 0:ne.call(B,P),H=(L==null?void 0:L.signatures)??(L==null?void 0:L.data);if(!B||!Array.isArray(H)||k<0||k>=H.length||T<0||T>=H.length||k===T)return;const[G]=H.splice(k,1);H.splice(T,0,G),i(B)},[a,i]),x=y.useCallback((P,k)=>{var G,ne;const T=a,B=(G=T==null?void 0:T.getObjectWithId)==null?void 0:G.call(T,P),L=(ne=B==null?void 0:B.getPath)==null?void 0:ne.call(B);if(!T||!B||!L||!Array.isArray(B.cellItems)||!T.insertObjectAtPath)return;const H=new ht(void 0,B);T.insertObjectAtPath([...L,k],H,0),i(T)},[a,i]),m=y.useCallback((P,k,T)=>{var ne;const B=a,L=(ne=B==null?void 0:B.getObjectWithId)==null?void 0:ne.call(B,P),H=L==null?void 0:L.cellItems;if(!B||!Array.isArray(H)||k<0||k>=H.length||T<0||T>=H.length||k===T)return;const[G]=H.splice(k,1);H.splice(T,0,G),i(B)},[a,i]),f=y.useCallback(P=>{var L,H,G,ne;const k=a,T=(L=k==null?void 0:k.getObjectWithId)==null?void 0:L.call(k,P),B=(H=T==null?void 0:T.getPath)==null?void 0:H.call(T);!k||!T||!B||!k.deleteObjectAtPath||(((ne=(G=T.parent)==null?void 0:G.cellItems)==null?void 0:ne.length)??0)<=1||(k.deleteObjectAtPath(B),i(k))},[a,i]),j=y.useCallback(P=>{const k=a,T=P.map(B=>{var L;return(L=k==null?void 0:k.getObjectWithId)==null?void 0:L.call(k,B)}).filter(B=>!!B);T.length&&o&&Qa({sourceTemplateId:o,nodes:T},wo)},[a,o]),S=y.useCallback(P=>j([P]),[j]),w=y.useCallback(()=>j(E.getState().selectedNodes.map(P=>P.id)),[j]),C=y.useCallback(P=>{S(P),l(P)},[S,l]),v=y.useCallback(()=>{const P=a;!P||!E.getState().selectedNodes.map(B=>B.id).filter(B=>ur(P,B)).length||(s(),i(P))},[a,s,i]),I=y.useCallback(()=>{j(E.getState().selectedNodes.map(P=>P.id)),v()},[j,v]),D=y.useCallback(P=>{var L;const k=a,T=(L=k==null?void 0:k.getObjectWithId)==null?void 0:L.call(k,P),B=hr();return!(B!=null&&B.length)||!T?!1:B.every(H=>pr(H,T,k))},[a]),F=(P,k,T)=>k==="keep-unique"?Qd(P,T):Da(P),M=y.useCallback((P,k,T=[],B)=>{var re;const L=a,H=B??hr(),G=(re=L==null?void 0:L.getObjectWithId)==null?void 0:re.call(L,P);if(!L||!(H!=null&&H.length)||!G||!L.insertObjectAtPath||!H.every(O=>pr(O,G,L))){B!==void 0&&Be.show({message:"Could not paste — the target was removed or is no longer valid.",severity:"warning"});return}const ne=new Set(T);let le=!1;[...H].reverse().forEach(O=>{var U,A,q;const K=(q=(A=(U=L.getObjectWithId)==null?void 0:U.call(L,P))==null?void 0:A.getPath)==null?void 0:q.call(A);if(O.clone&&K){const Y=O.clone();le=F(Y,k,ne)||le,L.insertObjectAtPath(K,Y,1)}}),i(L),le&&Be.show({message:"Identifier removed from the copy to keep it unique.",severity:"info"})},[a,i]),R=y.useCallback(P=>{var U,A;const k=a,T=(U=k==null?void 0:k.getObjectWithId)==null?void 0:U.call(k,P),B=sn(wo),L=_i(B),H=ov(B);if(!k||!(T!=null&&T.getPath)||!(L!=null&&L.length)||!k.insertObjectAtPath||!D(P))return;if(!(!!H&&!!o&&H!==o)){M(P,"clear-all");return}const ne=iv(L),le=((A=k.getAllCellIdentifiers)==null?void 0:A.call(k,""))??[],re=av(ne,le),O=[...L],K=P;lv({conflicts:re,onClear:()=>M(K,"clear-all",re,O),onKeep:()=>M(K,"keep-unique",re,O)})},[a,o,D,M]);return{deleteNode:l,duplicateNode:r,changeCellType:d,moveNode:c,moveNodes:u,moveCapture:p,addCapture:h,reorderCapture:g,addColumn:x,reorderColumn:m,deleteColumn:f,copyNode:S,copySelection:w,cutNode:C,cutSelection:I,deleteSelection:v,canPasteBelow:D,pasteBelow:R}},Me=n=>typeof n=="string"?n:"",Nt=n=>Me(n==null?void 0:n.data.contractTitle),Wi=(n,e,s)=>{var a,i;if(s==="section"){const l=((a=n.sectionsById[e])==null?void 0:a.groupType)??"";return l?l.charAt(0).toUpperCase()+l.slice(1):""}if(s==="row")return Me((i=n.groupsById[e])==null?void 0:i.data.contractTitle);const o=n.cellsById[e];if((o==null?void 0:o.cellType)==="header"){const l=o.data.header,r=Me(l==null?void 0:l.title);if(r)return r}return Nt(o)||Me(o==null?void 0:o.data.appTitle)},sa={"& .MuiInputLabel-outlined.MuiInputLabel-sizeSmall":{fontSize:"0.8rem"},"& .MuiInputLabel-outlined.MuiInputLabel-sizeSmall:not(.MuiInputLabel-shrink)":{transform:"translate(14px, 9px) scale(1)"},"& .MuiInputLabel-outlined.MuiInputLabel-sizeSmall.MuiInputLabel-shrink":{transform:"translate(14px, -6px) scale(0.75)"}},ae={empty:{px:1.5,py:1.5,fontSize:"0.78rem",color:"text.secondary"},tabs:{borderBottom:"1px solid",borderColor:"divider",minHeight:48},tab:{minHeight:48,minWidth:0,py:.75,px:1,gap:.25,fontSize:"0.7rem",textTransform:"none","& .MuiTab-iconWrapper":{fontSize:"1.1rem",mb:.25}},fields:{display:"flex",flexDirection:"column",gap:1.25,px:1.5,pt:1.75,pb:2},section:{borderBottom:"1px solid",borderColor:"divider","&:last-of-type":{borderBottom:"none"}},sectionHeader:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",px:1.5,py:1,border:"none",cursor:"pointer",color:"text.primary",backgroundColor:"grey.50","&:hover":{backgroundColor:"grey.100"}},sectionTitle:{fontWeight:600,fontSize:"0.8rem",px:1.5,pt:1.25},sectionIcon:n=>({color:"text.secondary",transform:n?"rotate(180deg)":"rotate(0deg)",transition:e=>e.transitions.create("transform",{duration:e.transitions.duration.shortest})}),rowInline:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:1,height:30},rowStacked:{display:"flex",flexDirection:"column",gap:.5},fieldLabel:{fontSize:"0.72rem",fontWeight:500,color:"text.secondary"},controlInline:{display:"flex",alignItems:"center"},conditionHeader:{display:"flex",alignItems:"center",justifyContent:"space-between",px:1.5,py:.5,backgroundColor:"grey.50"},conditionToggle:{display:"flex",alignItems:"center",gap:.5,flex:1,minWidth:0,p:0,border:"none",background:"none",cursor:"pointer",color:"text.primary",textAlign:"left"},switch:{transform:"scale(0.8)",transformOrigin:"center right"},commonSelect:{width:"100%",m:0,"& .MuiOutlinedInput-root":{height:34},"& .MuiOutlinedInput-input":{py:0,fontSize:"0.85rem"},"& .MuiSelect-select":{py:0,minHeight:"unset"},"& .MuiAutocomplete-inputRoot":{py:"1px"},...sa},compactLabeledField:{"& .MuiOutlinedInput-root":{height:34},"& .MuiOutlinedInput-input":{py:0,fontSize:"0.85rem"}
15,...sa},resizableMultiline:{"& .MuiOutlinedInput-root":{p:0,pr:"5px",pb:"5px",alignItems:"flex-start"},"& textarea":{resize:"vertical",minHeight:64,maxHeight:240,overflow:"auto",boxSizing:"border-box",p:"8.5px 14px",fontSize:"0.85rem",lineHeight:1.4},...sa},toggleGroup:{"& .MuiToggleButton-root":{px:1.25,py:.5},"& .MuiSvgIcon-root":{fontSize:"1.15rem"}},sliderRow:{display:"flex",alignItems:"center",gap:1.5},sliderInput:{width:48,flexShrink:0,"& .MuiOutlinedInput-root":{height:30},"& input":{p:"0 6px",fontSize:"0.78rem",textAlign:"center",MozAppearance:"textfield"},"& input::-webkit-outer-spin-button, & input::-webkit-inner-spin-button":{WebkitAppearance:"none",margin:0}},colorButton:{minWidth:0,px:1.25,py:.5,borderColor:"#2e2e2e",borderWidth:"1.5px","&:hover":{borderColor:"#2e2e2e",borderWidth:"1.5px"},"& .MuiSvgIcon-root":{fontSize:"1.15rem"}}},dv=[],uv=({captureId:n,index:e,onDelete:s})=>{const a=E(p=>{var h;return Me((h=p.tree.capturesById[n])==null?void 0:h.data.appNote)})||`Signer ${e+1}`,{attributes:i,listeners:l,setNodeRef:r,transform:d,transition:c,isDragging:u}=Oo({id:n});return t.jsx(N,{ref:r,sx:ae.section,style:{transform:Fa.Transform.toString(d),transition:c,opacity:u?.5:1},children:t.jsxs(N,{sx:ae.conditionHeader,children:[t.jsxs(N,{sx:{display:"flex",alignItems:"center",gap:.5,minWidth:0},children:[t.jsx(ye,{size:"small","aria-label":`Drag ${a}`,sx:{cursor:"grab"},...i,...l,children:t.jsx(Ro,{fontSize:"small"})}),t.jsx(z,{variant:"subtitle2",sx:{fontWeight:600},noWrap:!0,children:a})]}),t.jsx(ye,{size:"small","aria-label":`Delete ${a}`,onClick:s,children:t.jsx(Lo,{fontSize:"small"})})]})})},tu=({nodeId:n})=>{const e=E(r=>r.tree.captureIdsByCell[n]??dv),{deleteNode:s,addCapture:o,reorderCapture:a}=cn(),i=Qn(In(es,{activationConstraint:{distance:4}})),l=r=>{const{active:d,over:c}=r;if(!c||d.id===c.id)return;const u=e.indexOf(String(d.id)),p=e.indexOf(String(c.id));u>=0&&p>=0&&a(n,u,p)};return t.jsxs(t.Fragment,{children:[e.length===0&&t.jsx(z,{variant:"body2",sx:ae.empty,children:"No signers yet."}),t.jsx(ts,{sensors:i,collisionDetection:Sn,onDragEnd:l,children:t.jsx(_s,{items:e,strategy:No,children:t.jsx(N,{sx:{display:"flex",flexDirection:"column",gap:1},children:e.map((r,d)=>t.jsx(uv,{captureId:r,index:d,onDelete:()=>s(r)},r))})})}),t.jsx(we,{size:"small",color:"secondary",startIcon:t.jsx(wn,{}),onClick:()=>o(n),children:"Add signer"})]})},pv={kind:"section",label:"Section",category:"layout",icon:Bp,searchKeywords:["section","container","layout","group"],legacyCellTypes:[],Render:Xd,settings:{content:[{title:"Signers",collapsible:!0,fields:[{kind:"custom",id:"captureAccordions",render:tu,visible:n=>n.groupType==="signature"}]}]}},hv={kind:"letterheadSection",label:"Letterhead",category:"layout",icon:$p,searchKeywords:["letterhead","header","container","columns","banner"],legacyCellTypes:[],Render:Xd},oa={resting:{width:"100%"},placeholder:{color:"text.disabled",fontStyle:"italic",minWidth:"2em"},input:(n,e)=>({p:0,maxWidth:"100%",typography:n,"& .MuiInputBase-input":{p:0,height:"auto",...e?{}:{width:"auto"}}})},ko=({value:n,onCommit:e,variant:s="body2",multiline:o=!1,placeholder:a,sx:i,style:l,testId:r})=>{const[d,c]=y.useState(!1),[u,p]=y.useState(n);y.useEffect(()=>{d||p(n)},[n,d]);const h=()=>{c(!1),u!==n&&e(u)},g=()=>{c(!1),p(n)},x=j=>{j.key==="Enter"&&(!o||j.metaKey||j.ctrlKey)?(j.preventDefault(),h()):j.key==="Escape"&&(j.preventDefault(),g())},m=(Array.isArray(i)?i:[i]).filter(Boolean);if(d)return t.jsx(zp,{autoFocus:!0,fullWidth:o,multiline:o,value:u,onChange:j=>p(j.target.value),onBlur:h,onKeyDown:x,onClick:j=>j.stopPropagation(),sx:[oa.input(s,o),...m],style:l,inputProps:{"data-testid":r,...o?{}:{size:Math.max(u.length,1)}}});const f=!n;return t.jsx(z,{variant:s,sx:[oa.resting,...m,f&&oa.placeholder],style:f?{...l,color:void 0}:l,onDoubleClick:()=>c(!0),"data-testid":r,children:n||a})},mv="HelveticaNeue",gv="'Helvetica Neue', Helvetica, Arial, sans-serif",xv=new Set(["","Default","Default-Bold"]),Hi=n=>{if(typeof n!="string")return;const e=n.split("-");if(e.length!==4)return;const[s,o,a,i]=e.map(l=>Number(l)||0);return`rgba(${s}, ${o}, ${a}, ${i})`},nu=n=>{if(typeof n=="string"){const e=n.split("-");if(e.length===4){const[s,o,a,i]=e.map(Number);return{r:Number.isFinite(s)?s:0,g:Number.isFinite(o)?o:0,b:Number.isFinite(a)?a:0,a:Number.isFinite(i)?i:1}}}return{r:0,g:0,b:0,a:1}},su=({r:n,g:e,b:s,a:o})=>`${n}-${e}-${s}-${o}`,fv=n=>`"${typeof n=="string"&&!xv.has(n)?n:mv}", ${gv}`,qi=n=>({fontSize:typeof n.fontSize=="number"?n.fontSize:void 0,fontWeight:n.bold?700:400,textDecoration:n.underline?"underline":"none",fontFamily:fv(n.name),color:Hi(n.color)}),pt=n=>qi({fontSize:n.titleFontSize,bold:n.titleFontBold,underline:n.titleFontUnderline,name:n.titleFontName,color:n.titleFontColor}),Bn=n=>qi({fontSize:n.valueFontSize,bold:n.valueFontBold,underline:n.valueFontUnderline,name:n.valueFontName,color:n.valueFontColor}),ou=n=>qi({fontSize:n.fontSize,bold:n.fontBold,underline:n.fontUnderline,name:n.fontName,color:n.fontColor}),bv=n=>n.drawBorder?{border:"1px solid black"}:{},yv=n=>{switch(Number(n)){case 1:return{border:"1px solid black"};case 3:return{borderTop:"1px solid black",borderBottom:"1px solid black"};default:return{}}},jv=n=>Number(n)===2?{border:"1px solid black"}:{},Cv=(n,e)=>{const s=typeof n=="number"?n:0;return s===2||s===1&&e%2!==0?"rgba(224, 224, 224, 0.7)":void 0},hs={root:{display:"flex",flexDirection:"column",gap:0,width:"100%"},title:{fontWeight:600},cells:{display:"flex",flexDirection:"column",gap:0,width:"100%"},columns:{width:"100%",position:"relative","&:hover .doc-builder-add-column":{opacity:1}},addColumn:{position:"absolute",top:"50%",right:-14,transform:"translateY(-50%)",zIndex:2,opacity:0,backgroundColor:"common.white",border:"1px solid",borderColor:"divider",transition:"opacity 120ms","&:hover":{backgroundColor:"grey.100"}}},gr=[],Iv={},Sv=({nodeId:n,renderChild:e})=>{var g;const s=E(x=>x.tree.groupsById[n]),o=E(x=>x.tree.cellIdsByGroup[n]??gr),a=E(x=>x.tree.columnIdsByGroup[n]??gr),{addColumn:i}=cn(),l=Ee(),r=(s==null?void 0:s.data)??Iv,d=((g=r.parent)==null?void 0:g.groupType)==="header",c=d?"title":"contractTitle",u=Me(d?r.title:r.contractTitle),p=d?pt(r):ou(r),h=d?yv(r.border):bv(r);return t.jsxs(N,{sx:hs.root,"data-testid":"doc-builder-row",children:[u&&t.jsx(ko,{value:u,onCommit:x=>l(n,c,x),variant:"subtitle2",sx:hs.title,style:p,testId:"doc-builder-row-title"}),t.jsx(N,{sx:hs.cells,style:h,"data-testid":"doc-builder-row-cells",children:a.length>0?t.jsxs(he,{direction:"row",spacing:2,alignItems:"flex-start",sx:hs.columns,"data-testid":"doc-builder-row-columns",children:[a.map(x=>e({nodeId:x,nodeType:"column"})),t.jsx(Q,{title:"Add column",children:t.jsx(ye,{size:"small",className:"doc-builder-add-column",sx:hs.addColumn,"aria-label":"Add column","data-testid":"doc-builder-add-column",onClick:x=>{x.stopPropagation(),i(n,a.length)},children:t.jsx(wn,{fontSize:"inherit"})})})]}):t.jsxs(t.Fragment,{children:[t.jsx(ut,{target:{level:"cell",groupId:n,index:0}}),o.map((x,m)=>t.jsxs(y.Fragment,{children:[t.jsx(N,{style:{backgroundColor:Cv(r.shading,m)},children:e({nodeId:x,nodeType:"cell"})}),t.jsx(ut,{target:{level:"cell",groupId:n,index:m+1}})]},x))]})})]})},Xe=({label:n,inline:e,children:s})=>e?t.jsxs(N,{sx:ae.rowInline,children:[t.jsx(z,{sx:ae.fieldLabel,children:n}),t.jsx(N,{sx:ae.controlInline,children:s})]}):t.jsxs(N,{sx:ae.rowStacked,children:[t.jsx(z,{sx:ae.fieldLabel,children:n}),s]}),vv=[{value:0,label:"None"},{value:1,label:"Alternate Rows"},{value:2,label:"All Rows"}],Tv=({nodeId:n})=>{const e=E(a=>{var i;return!!((i=_e(a.tree,n))!=null&&i.userInputRequired)}),s=E(a=>{var l;const i=(l=_e(a.tree,n))==null?void 0:l.shading;return typeof i=="number"?i:0}
15),o=Ee();return t.jsxs(t.Fragment,{children:[t.jsx(Xe,{label:"Hidden in App",inline:!0,children:t.jsx(xt,{edge:"end",checked:!e,color:"secondary",onChange:a=>o(n,"userInputRequired",!a.target.checked),inputProps:{"aria-label":"Hidden in App"},sx:ae.switch})}),t.jsx(ie,{sx:{my:1}}),t.jsx(Le,{select:!0,label:"Shading Style",size:"small",color:"secondary",fullWidth:!0,sx:ae.compactLabeledField,value:s,onChange:a=>o(n,"shading",Number(a.target.value)),children:vv.map(a=>t.jsx(ue,{value:a.value,children:a.label},a.value))})]})},au=[],wv=({columnId:n,index:e,canDelete:s,onDelete:o})=>{const a=E(h=>(h.tree.cellIdsByColumn[n]??au).length),i=`Column ${e+1}`,{attributes:l,listeners:r,setNodeRef:d,transform:c,transition:u,isDragging:p}=Oo({id:n});return t.jsx(N,{ref:d,sx:ae.section,style:{transform:Fa.Transform.toString(c),transition:u,opacity:p?.5:1},children:t.jsxs(N,{sx:ae.conditionHeader,children:[t.jsxs(N,{sx:{display:"flex",alignItems:"center",gap:.5,minWidth:0},children:[t.jsx(ye,{size:"small","aria-label":`Drag ${i}`,sx:{cursor:"grab"},...l,...r,children:t.jsx(Ro,{fontSize:"small"})}),t.jsx(z,{variant:"subtitle2",sx:{fontWeight:600},noWrap:!0,children:i}),t.jsxs(z,{variant:"caption",color:"text.secondary",noWrap:!0,children:[a," ",a===1?"item":"items"]})]}),s&&t.jsx(ye,{size:"small","aria-label":`Delete ${i}`,onClick:o,children:t.jsx(Lo,{fontSize:"small"})})]})})},kv=({nodeId:n})=>{const e=E(r=>r.tree.columnIdsByGroup[n]??au),{addColumn:s,deleteColumn:o,reorderColumn:a}=cn(),i=Qn(In(es,{activationConstraint:{distance:4}})),l=r=>{const{active:d,over:c}=r;if(!c||d.id===c.id)return;const u=e.indexOf(String(d.id)),p=e.indexOf(String(c.id));u>=0&&p>=0&&a(n,u,p)};return t.jsxs(t.Fragment,{children:[t.jsx(ts,{sensors:i,collisionDetection:Sn,onDragEnd:l,children:t.jsx(_s,{items:e,strategy:No,children:t.jsx(N,{sx:{display:"flex",flexDirection:"column",gap:1},children:e.map((r,d)=>t.jsx(wv,{columnId:r,index:d,canDelete:e.length>1,onDelete:()=>o(r)},r))})})}),t.jsx(we,{size:"small",color:"secondary",startIcon:t.jsx(wn,{}),onClick:()=>s(n,e.length),children:"Add column"})]})},Pv=[{value:0,label:"None"},{value:1,label:"Outside"},{value:2,label:"Inside & Outside"},{value:3,label:"Top & Bottom"}],Dv=({nodeId:n})=>{const e=E(o=>{var i;const a=(i=_e(o.tree,n))==null?void 0:i.border;return typeof a=="number"?a:0}),s=Ee();return t.jsx(Le,{select:!0,label:"Border",size:"small",color:"secondary",fullWidth:!0,value:e,onChange:o=>s(n,"border",Number(o.target.value)),slotProps:{htmlInput:{"aria-label":"Border"}},children:Pv.map(o=>t.jsx(ue,{value:o.value,children:o.label},o.value))})},iu=n=>[{kind:"slider",key:`${n}FontSize`,label:"Size",min:1,max:100},{kind:"select",key:`${n}FontName`,label:"Font",options:Es},{kind:"toggleGroup",label:"Style",buttons:[{key:`${n}FontBold`,icon:Ao,tooltip:"Bold"},{key:`${n}FontUnderline`,icon:Fo,tooltip:"Underline"}]},{kind:"color",key:`${n}FontColor`,label:"Color"}],dn={title:"Title Font",collapsible:!0,fields:iu("title")},Vo={title:"Value Font",collapsible:!0,fields:iu("value")},lu={title:"Font",collapsible:!0,fields:[{kind:"slider",key:"fontSize",label:"Size",min:1,max:100},{kind:"select",key:"fontName",label:"Font",options:Es},{kind:"toggleGroup",label:"Style",buttons:[{key:"fontBold",icon:Ao,tooltip:"Bold"},{key:"fontUnderline",icon:Fo,tooltip:"Underline"}]},{kind:"color",key:"fontColor",label:"Color"}]},xr=n=>Array.isArray(n)?n.filter(e=>typeof e=="string"):[],Ov=({nodeId:n})=>{const e=E(p=>{var h;return(h=_e(p.tree,n))==null?void 0:h.categoryIds}),s=E(p=>{var h;return(h=_e(p.tree,n))==null?void 0:h.linkedMeasureSheetItemIds}),o=y.useMemo(()=>xr(e),[e]),a=xr(s).length,i=Ee(),{categories:l,isLoading:r,error:d}=Ei(),c=y.useMemo(()=>l.filter(p=>p.objectIds.every(h=>o.includes(h))).map(p=>p.name),[l,o]),u=p=>{const h=new Map(l.map(m=>[m.name,m])),g=new Set(o.filter(m=>p.some(f=>{var j;return(j=h.get(f))==null?void 0:j.objectIds.includes(m)})));p.forEach(m=>{var f;return(f=h.get(m))==null?void 0:f.objectIds.forEach(j=>g.add(j))});const x=Array.from(g);i(n,"categoryIds",x),x.length>0&&a>0&&i(n,"linkedMeasureSheetItemIds",[])};return r?t.jsx(z,{variant:"body2",sx:ae.empty,children:"Loading c
15ategories…"}):d?t.jsx(z,{variant:"body2",sx:ae.empty,children:"Couldn’t load categories."}):t.jsx(Cc,{label:"Linked Categories",hideSelectAll:!0,size:"small",formControlSx:ae.commonSelect,options:l.map(p=>({label:p.name,value:p.name})),value:c,disabled:a>0,helperText:a>0?"Disabled while measure-sheet items are linked.":void 0,onChange:p=>u(p.target.value),inputProps:{"data-testid":"doc-builder-setting-categoryIds"}})},ys="/fenetech/documents/section",ru="_none_",Nv=[{value:ru,label:"None"},{value:ys,label:"Fenevision"}],Mv=[{value:0,label:"Warning"},{value:1,label:"Acknowledge"},{value:2,label:"Block"}],Lv=({nodeId:n})=>{var g,x;const e=E(m=>{var f;return(f=_e(m.tree,n))==null?void 0:f.downloadParams}),s=Ee(),o=(e==null?void 0:e.endpoint)??ru,a=o===ys,i=((g=e==null?void 0:e.body)==null?void 0:g.settings)??{},l=((x=e==null?void 0:e.headers)==null?void 0:x["x-manufacturer-id"])??"",{manufacturers:r,isLoading:d}=ri({enabled:a}),c=y.useMemo(()=>r.map(m=>({value:m.id,label:m.name})),[r]),u=m=>s(n,"downloadParams",{...e,endpoint:ys,...m}),p=m=>{m===ys?(s(n,"requiresDownload",!0),s(n,"downloadParams",{...e,endpoint:ys,body:{settings:{showTotals:!0,exceptionHandling:1}}})):(s(n,"requiresDownload",!1),s(n,"downloadParams",void 0))},h=m=>u({body:{...e==null?void 0:e.body,settings:{...i,...m}}});return t.jsxs(t.Fragment,{children:[t.jsx(_t,{label:"Integration",size:"small",fullWidth:!0,sx:ae.commonSelect,options:Nv,value:o,onChange:m=>p(m.target.value),slotProps:{htmlInput:{"data-testid":"doc-builder-setting-integration"}}}),a&&t.jsxs(t.Fragment,{children:[t.jsx(_t,{label:"Manufacturer",size:"small",fullWidth:!0,sx:ae.commonSelect,options:c,value:l,disabled:d||c.length===0,onChange:m=>u({headers:{...e==null?void 0:e.headers,"x-manufacturer-id":m.target.value}}),slotProps:{htmlInput:{"data-testid":"doc-builder-setting-manufacturer"}}}),t.jsx(Xe,{label:"Show Totals",inline:!0,children:t.jsx(xt,{edge:"end",checked:!!i.showTotals,color:"secondary",onChange:m=>h({showTotals:m.target.checked}),inputProps:{"aria-label":"Show Totals"},sx:ae.switch})}),t.jsx(_t,{label:"Exception Handling",size:"small",fullWidth:!0,sx:ae.commonSelect,options:Mv,value:i.exceptionHandling??1,onChange:m=>h({exceptionHandling:Number(m.target.value)}),slotProps:{htmlInput:{"data-testid":"doc-builder-setting-exceptionHandling"}}})]})]})},js=n=>{var e;return((e=n.parent)==null?void 0:e.groupType)==="header"},un=n=>!js(n),fr=(n,e)=>({...n,fields:n.fields.map(s=>({...s,visible:e}))}),Ev={kind:"row",label:"Block",category:"layout",icon:Wp,searchKeywords:["block","row","group","container","layout"],legacyCellTypes:[],Render:Sv,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"appTitle",label:"App Title"},{kind:"text",key:"contractTitle",label:"PDF Title",visible:un},{kind:"text",key:"title",label:"PDF Title",visible:js},{kind:"divider"},{kind:"switch",key:"newPage",label:"Begin on New Page",visible:un},{kind:"switch",key:"drawBorder",label:"Draw Border",visible:un},{kind:"switch",key:"canAddMultiple",label:"Allow Copy/Paste",visible:un},{kind:"custom",id:"rowExtras",render:Tv,visible:un},{kind:"custom",id:"letterheadColumns",render:kv,visible:js},{kind:"custom",id:"letterheadExtras",render:Dv,visible:js}]}],style:[fr(lu,un),fr(dn,js)],advanced:[{title:"Linked Categories",collapsible:!0,fields:[{kind:"custom",id:"linkedCategories",render:Ov,visible:un}]},{title:"Integration",collapsible:!0,fields:[{kind:"custom",id:"integration",render:Lv,visible:un}]}]}},Av={root:{display:"flex",flexDirection:"column",gap:0,width:"100%"}},Fv=[],Rv=({nodeId:n,renderChild:e})=>{const s=E(a=>a.tree.cellIdsByColumn[n]??Fv),o=E(a=>{var l;const i=Object.keys(a.tree.columnIdsByGroup).find(r=>{var d;return(d=a.tree.columnIdsByGroup[r])==null?void 0:d.includes(n)});return i?(l=a.tree.groupsById[i])==null?void 0:l.data.border:void 0});return t.jsxs(N,{sx:Av.root,style:jv(o),children:[t.jsx(ut,{target:{level:"headerCell",columnId:n,index:0}}),s.map((a,i)=>t.jsxs(y.Fragment,{children:[e({nodeId:a,nodeType:"cell"}),t.jsx(ut,{target:{level:"headerCell",columnId:n,index:i+1}})]},a))]})},_v={kind:"column",label:"Column",category:"layout",icon:pc,searchKeywords:["column","letterhead","header"],legacyCellTypes:[],Render:Rv},Bv={root:{width:"100%"}},$v=({nodeId:n})=>{const e=E(o=>o.tree.cellsById[n]),s=Number(e==null?void 0:e.data.emptySpaceHeight)||0;return t.jsx(N,{sx:Bv.root,style:{height:s,minHeight:s},"data-testid":"doc-builder-widget-empty-space"})},zv={kind:"emptySpace",label:"Empty Space",category:"layout",icon:Hp,searchKeywords:["empty","space","spacer","gap","blank"],legacyCellTypes:["emptySpace"],defaultData:{cellType:"emptySpace",emptySpaceHeight:4},Render:$v,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"number",key:"emptySpaceHeight",label:"Height",min:0}]}]}},br="3px 5px",ms=1.5,Wt={inline:{display:"flex",alignItems:"baseline",gap:1,width:"100%",padding:br},stacked:{display:"flex",flexDirection:"column",width:"100%",padding:br},label:{fontWeight:600,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0,lineHeight:ms},labelSlot:{flex:1,minWidth:0,display:"flex",alignItems:"baseline"},slot:{flex:1,minWidth:0,display:"flex",justifyContent:"flex-end",alignItems:"baseline",textAlign:"right"},slotBlock:{minHeight:"3.6em"},value:{whiteSpace:"pre-wrap",lineHeight:ms,minHeight:ms},valueTruncate:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0,maxWidth:"100%",lineHeight:ms,minHeight:ms}},Ko=({label:n,value:e,variant:s="field",block:o=!1,onLabelCommit:a,onValueCommit:i,labelStyle:l,valueStyle:r,valuePlaceholder:d="Add value",testId:c})=>{const u=s==="static"||o?"subtitle2":"body2",p=s==="static"||o,h=p?Wt.value:Wt.valueTruncate,g=a?t.jsx(ko,{value:n??"",onCommit:a,variant:u,sx:Wt.label,style:l,placeholder:"Untitled",testId:c?`${c}-label`:void 0}):n&&t.jsx(z,{variant:u,sx:Wt.label,style:l,children:n}),x=i?t.jsx(ko,{value:e??"",onCommit:i,variant:"body2",multiline:p,sx:h,style:r,placeholder:d,testId:c?`${c}-value`:void 0}):e&&t.jsx(z,{variant:"body2",sx:h,style:r,children:e});return s==="static"?t.jsxs(N,{sx:Wt.stacked,"data-testid":c,children:[g,x]}):o?t.jsxs(N,{sx:Wt.stacked,"data-testid":c,children:[g,t.jsx(N,{sx:Wt.slotBlock,"data-testid":"doc-builder-field-slot",children:x})]}):t.jsxs(N,{sx:Wt.inline,"data-testid":c,children:[t.jsx(Q,{title:n??"",placement:"top",disableInteractive:!0,children:t.jsx(N,{sx:Wt.labelSlot,"data-testid":"doc-builder-field-label-slot",children:g})}),t.jsx(Q,{title:e??"",placement:"top",disableInteractive:!0,children:t.jsx(N,{sx:Wt.slot,"data-testid":"doc-builder-field-slot",children:x})})]})},Wv={},Hv=({nodeId:n})=>{const e=E(a=>a.tree.cellsById[n]),s=Ee(),o=(e==null?void 0:e.data)??Wv;return t.jsx(Ko,{label:Nt(e),value:Me(e==null?void 0:e.data.value),variant:"static",labelStyle:pt(o),valueStyle:Bn(o),onLabelCommit:a=>s(n,"contractTitle",a),onValueCommit:a=>s(n,"value",a),testId:"doc-builder-widget-text-only"})},it=(...n)=>e=>n.includes(typeof e.inputType=="string"?e.inputType:""),cu={fields:[{kind:"text",key:"cellId",label:"Identifier",validate:"uniqueIdentifier"}]},du={title:"Visibility",collapsible:!0,fields:[{kind:"switch",key:"hidden",label:"Hide in App"},{kind:"switch",key:"appOnly",label:"Hide on PDF"},{kind:"switch",key:"inputDisabled",label:"Disable editing"}]},Vi={title:"Empty Handling",collapsible:!0,fields:[{kind:"switch",key:"drawIfEmpty",label:"Hide if blank",inverted:!0},{kind:"text",key:"emptyValue",label:"Value if blank",visible:n=>!!n.drawIfEmpty},{kind:"switch",key:"clearValueIfZero",label:"Clear Value If Zero",visible:it("formula","formulaWhole","formulaCurrency","formulaCurrencyWhole","keypad","keypadDecimal","currency","currencyWhole")}]},uo=n=>typeof n=="string"?n:"",uu=(n,e)=>{var i;
15const s=uo((i=_e(n,e))==null?void 0:i.cellId),o=[],a=l=>{l&&l!==s&&!o.includes(l)&&o.push(l)};return n.sectionIds.filter(l=>{var r;return((r=n.sectionsById[l])==null?void 0:r.groupType)==="body"}).forEach(l=>{(n.groupIdsBySection[l]??[]).forEach(r=>{(n.cellIdsByGroup[r]??[]).forEach(d=>{var c;a(uo((c=n.cellsById[d])==null?void 0:c.data.cellId)),(n.detailItemIdsByCell[d]??[]).forEach(u=>{var p;a(uo((p=n.cellsById[u])==null?void 0:p.data.cellId))})})})}),o},pu=(n,e,s)=>{const o=s.trim();return o?n.sectionIds.filter(a=>{var i;return((i=n.sectionsById[a])==null?void 0:i.groupType)==="body"}).some(a=>(n.groupIdsBySection[a]??[]).some(i=>(n.cellIdsByGroup[i]??[]).some(l=>[l,...n.detailItemIdsByCell[l]??[]].some(d=>{var c;return d!==e&&uo((c=n.cellsById[d])==null?void 0:c.data.cellId)===o})))):!1},aa=n=>typeof n=="string"?n:"",qv=(n,e)=>{if(!e)return[];const s=Object.values(n.cellsById).find(o=>aa(o.data.cellId)===e);return s?s.cellType==="switched"?[aa(s.data.switchValueOn),aa(s.data.switchValueOff)].filter(Boolean):s.data.inputType==="picker"&&Array.isArray(s.data.pickerValues)?s.data.pickerValues.filter(o=>typeof o=="string"):[]:[]},Vv={},Kv=[{value:"inch",label:"Inch"},{value:"quarter",label:'1/4"'},{value:"eighth",label:'1/8"'},{value:"sixteenth",label:'1/16"'}],Uv=["picker","multiSelectPicker"],Gv=["sizePicker","3DSizePicker"],hu={inputType:"default",enabled:!1,required:!1,values:["default"]},Jv=()=>({inputType:"default",enabled:!0,required:!1,values:[],defaultValue:""}),Qs=n=>typeof n=="string"?n:"",eo=n=>Array.isArray(n)?n.filter(e=>typeof e=="string"):[],Yv=({title:n,onDelete:e,children:s})=>{const[o,a]=y.useState(!0);return t.jsxs(N,{sx:ae.section,children:[t.jsxs(N,{sx:ae.conditionHeader,children:[t.jsxs(N,{component:"button",type:"button",onClick:()=>a(i=>!i),"aria-expanded":o,sx:ae.conditionToggle,children:[t.jsx(Pt,{sx:ae.sectionIcon(o),fontSize:"small"}),t.jsx(z,{variant:"subtitle2",sx:{fontWeight:600},noWrap:!0,children:n})]}),t.jsx(ye,{size:"small","aria-label":`Delete ${n}`,onClick:e,children:t.jsx(Lo,{fontSize:"small"})})]}),t.jsx(Dt,{in:o,unmountOnExit:!0,children:t.jsx(N,{sx:ae.fields,children:s})})]})},mu=({nodeId:n})=>{const e=E(h=>_e(h.tree,n)??Vv),s=E(h=>h.tree),o=Ee(),a=e.dynamicInputType??{},i=Qs(a.cellId),l=Array.isArray(a.objects)&&a.objects.length>0?a.objects:[hu],r=y.useMemo(()=>uu(s,n),[s,n]),d=y.useMemo(()=>qv(s,i),[s,i]),c=h=>o(n,"dynamicInputType",{...a,objects:l,...h}),u=(h,g,x)=>c({objects:l.map((m,f)=>f===h?{...m,[g]:x}:m)}),p=(h,g)=>{const x=!!h.enabled,m=Qs(h.inputType)||"default";return t.jsxs(t.Fragment,{children:[g!==0&&t.jsxs(t.Fragment,{children:[d.length>0?t.jsx(Cc,{label:"Dependent Values",hideSelectAll:!0,size:"small",formControlSx:ae.commonSelect,options:d.map(f=>({label:f,value:f})),value:eo(h.values),onChange:f=>u(g,"values",f.target.value)}):t.jsx(Le,{label:"Dependent Value",size:"small",color:"secondary",fullWidth:!0,sx:ae.compactLabeledField,value:eo(h.values)[0]??"",onChange:f=>u(g,"values",[f.target.value]),slotProps:{inputLabel:{shrink:!0}}}),t.jsx(ie,{})]}),t.jsx(Xe,{label:"Show Cell",inline:!0,children:t.jsx(xt,{edge:"end",checked:x,color:"secondary",onChange:f=>u(g,"enabled",f.target.checked),inputProps:{"aria-label":`Condition ${g+1} show cell`},sx:ae.switch})}),x&&t.jsx(Pc,{label:"Input Type",size:"small",sx:ae.commonSelect,options:ka,value:ka.find(f=>f.value===m)??null,onChange:(f,j)=>u(g,"inputType",(j==null?void 0:j.value)??"")}),x&&Uv.includes(m)&&t.jsx(Le,{label:"Picker Options",size:"small",color:"secondary",fullWidth:!0,sx:ae.resizableMultiline,value:eo(h.pickerValues).join(`
16`),placeholder:"One option per line",onChange:f=>u(g,"pickerValues",f.target.value.split(`
17`)),slotProps:{input:{inputComponent:"textarea"},inputLabel:{shrink:!0}}}),x&&Gv.includes(m)&&t.jsx(_t,{label:"Fraction Digits",size:"small",fullWidth:!0,sx:ae.commonSelect,options:Kv,value:Qs(h.fractionDigits),onChange:f=>u(g,"fractionDigits",f.target.value)}),t.jsx(Xe,{label:"Required",inline:!0,children:t.jsx(xt,{edge:"end",checked:!!h.required,color:"secondary",onChange:f=>u(g,"required",f.target.checked),inputProps:{"aria-label":`Condition ${g+1} required`},sx:ae.switch})}),t.jsx(Le,{label:"Default Value",size:"small",color:"secondary",fullWidth:!0,sx:ae.compactLabeledField,value:Qs(h.defaultValue),onChange:f=>u(g,"defaultValue",f.target.value),slotProps:{inputLabel:{shrink:!0}}})]})};return t.jsxs(t.Fragment,{children:[t.jsx(_t,{label:"Dependent Cell",size:"small",fullWidth:!0,sx:ae.commonSelect,options:r.map(h=>({label:h,value:h})),value:i,disabled:r.length===0,onChange:h=>c({cellId:h.target.value}),slotProps:{htmlInput:{"data-testid":"doc-builder-setting-dynamic-cell"}}}),t.jsx(ie,{}),t.jsx(z,{variant:"subtitle2",sx:{fontWeight:600},children:"Default"}),p(l[0],0),t.jsx(ie,{}),l.slice(1).map((h,g)=>{const x=g+1;return t.jsx(Yv,{title:eo(h.values).join(", ")||`Condition ${x+1}`,onDelete:()=>c({objects:l.filter((m,f)=>f!==x)}),children:p(h,x)},x)}),t.jsx(we,{size:"small",color:"secondary",startIcon:t.jsx(wn,{}),onClick:()=>c({objects:[...l,Jv()]}),children:"Add condition"})]})},Xv={},Zv=({nodeId:n})=>{const e=E(i=>_e(i.tree,n)??Xv),s=Ee(),o=e.inputType==="dynamic",a=i=>{var r;s(n,"inputType",i?"dynamic":"");const l=e.dynamicInputType??{};i&&!(((r=l.objects)==null?void 0:r.length)??0)&&s(n,"dynamicInputType",{objects:[hu]})};return t.jsxs(t.Fragment,{children:[t.jsx(Xe,{label:"Dynamic",inline:!0,children:t.jsx(xt,{edge:"end",checked:o,color:"secondary",onChange:i=>a(i.target.checked),inputProps:{"aria-label":"Dynamic"},sx:ae.switch})}),o&&t.jsx(mu,{nodeId:n})]})},Ks={title:"Dynamic",collapsible:!0,fields:[{kind:"custom",id:"dynamic",render:Zv}]},Qv=["%selectedTotal%","%selectedTotalWholeNumber%","%financeOptionDealerFee%","%financeOptionInterestRate%","%financeOptionMinAmount%","%financeOptionMaxAmount%","%financeOptionPaymentMultiplier%","%financeOptionNumberOfPayments%","%financeOptionDownPayment%","%financeOptionDownPaymentNoZero%"],gu=({nodeId:n})=>{const e=E(c=>{var u;
17return Me((u=_e(c.tree,n))==null?void 0:u.formula)}),s=E(c=>{var u;return Me((u=_e(c.tree,n))==null?void 0:u.cellId)}),o=E(c=>c.tree),a=y.useMemo(()=>uu(o,n),[o,n]),i=Ee(),l=y.useRef(null),r=s!==""&&e.includes(`[${s}]`),d=c=>{const u=l.current,p=(u==null?void 0:u.selectionStart)??e.length,h=(u==null?void 0:u.selectionEnd)??e.length,g=e.slice(0,p)+c+e.slice(h);i(n,"formula",g),requestAnimationFrame(()=>{u&&(u.focus(),u.selectionStart=p+c.length,u.selectionEnd=p+c.length)})};return t.jsxs(t.Fragment,{children:[t.jsx(Le,{label:"Formula",size:"small",color:"secondary",fullWidth:!0,sx:ae.resizableMultiline,value:e,error:r,helperText:r?`A formula can't reference its own cell [${s}].`:void 0,onChange:c=>i(n,"formula",c.target.value),inputRef:l,slotProps:{input:{inputComponent:"textarea"},inputLabel:{shrink:!0},htmlInput:{"data-testid":"doc-builder-setting-formula"}}}),t.jsx(_t,{label:"Insert identifier",size:"small",fullWidth:!0,value:"",disabled:a.length===0,sx:ae.commonSelect,options:a.map(c=>({label:c,value:c})),onChange:c=>d(`[${c.target.value}]`),slotProps:{htmlInput:{"data-testid":"doc-builder-setting-formula-identifier"}}}),t.jsx(_t,{label:"Insert placeholder",size:"small",fullWidth:!0,value:"",sx:ae.commonSelect,options:Qv.map(c=>({label:c,value:c})),onChange:c=>d(c.target.value),slotProps:{htmlInput:{"data-testid":"doc-builder-setting-formula-placeholder"}}})]})},eT=({nodeId:n})=>{const e=E(a=>{var i;return(i=_e(a.tree,n))==null?void 0:i.pickerValues}),s=y.useMemo(()=>Array.isArray(e)?e.filter(a=>typeof a=="string").join(`
18`):"",[e]),o=Ee();return t.jsx(Le,{label:"Picker Options",size:"small",color:"secondary",fullWidth:!0,sx:ae.resizableMultiline,value:s,placeholder:"One option per line",onChange:a=>o(n,"pickerValues",a.target.value.split(`
19`)),onBlur:()=>o(n,"pickerValues",s.split(`
20`).map(a=>a.trim()).filter(Boolean)),slotProps:{input:{inputComponent:"textarea"},inputLabel:{shrink:!0},htmlInput:{"data-testid":"doc-builder-setting-pickerValues"}}})},yr={datePicker:"MM/dd/yyyy",dateTimePicker:"MM/dd/yyyy hh:mm a",timePicker:"h:mm a"},tT=({nodeId:n})=>{const e=E(l=>{var r;return Me((r=_e(l.tree,n))==null?void 0:r.inputType)}),s=E(l=>{var r;return Me((r=_e(l.tree,n))==null?void 0:r.dateDisplayFormat)}),o=Ee(),a=yr[e]??yr.datePicker,i=e==="timePicker"?"Time Format":"Date Format";return t.jsx(Le,{label:i,size:"small",color:"secondary",fullWidth:!0,sx:ae.compactLabeledField,value:s,placeholder:a,helperText:`e.g. ${a}`,onChange:l=>o(n,"dateDisplayFormat",l.target.value),slotProps:{htmlInput:{"data-testid":"doc-builder-setting-dateDisplayFormat"}}})},nT=[{value:"inch",label:"Inch"},{value:"quarter",label:'1/4"'},{value:"eighth",label:'1/8"'},{value:"sixteenth",label:'1/16"'}],sT=["formula","formulaWhole","formulaCurrency","formulaCurrencyWhole","textFormula"],oT=["currency","currencyWhole","formulaCurrency","formulaCurrencyWhole","dynamic"],aT=[{kind:"switch",key:"isTotalSaleAmount",label:"Is Total Sale Amount",visible:it(...oT)},{kind:"custom",id:"pickerValues",render:eT,visible:it("picker","multiSelectPicker")},{kind:"text",key:"multiSelectorSeparator",label:"Multi Select Separator",visible:it("multiSelectPicker")},{kind:"select",key:"fractionDigits",label:"Fraction Digits",options:nT,visible:it("sizePicker","3DSizePicker")},{kind:"text",key:"unitedInchSuffix",label:"United Inch Suffix",visible:it("unitedInchPicker")},{kind:"text",key:"minSizePickerWidth",label:"Min Width",visible:it("sizePicker","3DSizePicker","unitedInchPicker")},{kind:"text",key:"maxSizePickerWidth",label:"Max Width",visible:it("sizePicker","3DSizePicker","unitedInchPicker")},{kind:"text",key:"minSizePickerHeight",label:"Min Height",visible:it("sizePicker","3DSizePicker","unitedInchPicker")},{kind:"text",key:"maxSizePickerHeight",label:"Max Height",visible:it("sizePicker","3DSizePicker","unitedInchPicker")},{kind:"text",key:"minSizePickerDepth",label:"Min Depth",visible:it("3DSizePicker")},{kind:"text",key:"maxSizePickerDepth",label:"Max Depth",visible:it("3DSizePicker")},{kind:"custom",id:"dateDisplayFormat",render:tT,visible:it("datePicker","dateTimePicker","timePicker")},{kind:"custom",id:"formula",render:gu,visible:it(...sT)},{kind:"custom",id:"dynamicConditions",render:mu,visible:it("dynamic")}],iT=n=>({title:"Input Type",collapsible:!0,fields:[{kind:"select",key:"inputType",label:"Input Type",options:n},...aT]}),lT=["textShort","textLong","textXLong"],rT=[lT],cT={textShort:"Text (Words)",textLong:"Text (Sentence)",textXLong:"Text (Paragraph)"},dT=n=>n&&rT.find(e=>e.includes(n))||null,uT=["default","textFormula"],pT=({nodeId:n})=>{const e=E(d=>{var c;return((c=d.tree.cellsById[n])==null?void 0:c.cellType)??null}),s=E(d=>{var u;const c=(u=d.tree.cellsById[n])==null?void 0:u.data.inputType;return typeof c=="string"?c:"default"}),o=ZS(),{showConfirmationModal:a}=qp(),i=dT(e);if(!e||!i||i.length<2)return null;const l=i.map(d=>({value:d,label:cT[d]??d})),r=d=>{if(!d||d===e)return;if(d==="textXLong"&&!uT.includes(s)){a({title:"Change to Paragraph?",msg:"Paragraph fields don’t support the current input type, so it will be reset to Keyboard. Your text and other settings are kept.",cancelText:"Cancel",confirmText:"Change",onConfirm:()=>
20o(n,d)});return}o(n,d)};return t.jsx(_t,{label:"Cell Type",size:"small",fullWidth:!0,sx:ae.commonSelect,options:l,value:e,onChange:d=>r(d.target.value),slotProps:{htmlInput:{"data-testid":"doc-builder-setting-cellType"}}})},Uo=({valueLabel:n="Value",multiline:e=!1,includeRequired:s=!0,inputTypeOptions:o}={})=>{const a=[{kind:"custom",id:"cellType",render:pT},{kind:"text",key:"contractTitle",label:"Title"},{kind:"text",key:"value",label:n,multiline:e}];s&&a.push({kind:"switch",key:"required",label:"Required"});const i=[{title:"Content",collapsible:!0,fields:a}];return o&&i.push(iT(o)),{content:i,style:[dn,Vo],advanced:s?[cu,du,Vi]:[]}},hT={content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"contractTitle",label:"Title"},{kind:"text",key:"switchValueOn",label:"On label"},{kind:"text",key:"switchValueOff",label:"Off label"},{kind:"switch",key:"required",label:"Required"}]}],style:[dn,Vo],advanced:[cu,du,Ks]},mT={kind:"textOnly",label:"Text Only",category:"text",icon:Ra,searchKeywords:["text","label","static","note","read only","paragraph"],legacyCellTypes:["textOnly"],defaultData:{cellType:"textOnly",contractTitle:"New Text",value:""},Render:Hv,settings:Uo({valueLabel:"Text",includeRequired:!1,multiline:!0})},gT={},xT=({nodeId:n})=>{const e=E(a=>a.tree.cellsById[n]),s=Ee(),o=(e==null?void 0:e.data)??gT;return t.jsx(Ko,{label:Nt(e),value:Me(e==null?void 0:e.data.value),labelStyle:pt(o),valueStyle:Bn(o),onLabelCommit:a=>s(n,"contractTitle",a),onValueCommit:a=>s(n,"value",a),testId:"doc-builder-widget-text-words"})},Ki=[{value:"default",label:"Keyboard"},{value:"email",label:"Email Address"},{value:"phone",label:"Phone Number"},{value:"creditCard",label:"Credit Card"},{value:"ccExpDate",label:"Credit Card Exp. Date"},{value:"keypad",label:"Keypad (1)"},{value:"keypadDecimal",label:"Keypad (1.00)"},{value:"numbers",label:"Number Keyboard"},{value:"currency",label:"Currency ($1.00)"},{value:"currencyWhole",label:"Currency ($1)"},{value:"picker",label:"Picker"},{value:"multiSelectPicker",label:"Multi-Select Picker"},{value:"financeOptionsPicker",label:"Finance Options Picker"},{value:"unitedInchPicker",label:"United Inch Picker"},{value:"sizePicker",label:"Size Picker"},{value:"3DSizePicker",label:"3D Size Picker"},{value:"datePicker",label:"Date Picker"},{value:"timePicker",label:"Time"},{value:"dateTimePicker",label:"Date & Time"},{value:"formula",label:"Formula (1.00)"},{value:"formulaWhole",label:"Formula (1)"},{value:"textFormula",label:"Text Formula"},{value:"formulaCurrency",label:"Formula Currency ($1.00)"},{value:"formulaCurrencyWhole",label:"Formula Currency ($1)"},{value:"dynamic",label:"Dynamic"}],fT=Ki.filter(n=>n.value==="default"||n.value==="textFormula"),bT={kind:"textWords",label:"Text (Words)",category:"text",icon:Vp,searchKeywords:["text","words","short","input","field"],legacyCellTypes:["textShort"],defaultData:{cellType:"textShort",contractTitle:"New Text",value:""},Render:xT,settings:Uo({inputTypeOptions:Ki})},yT={},jT=({nodeId:n})=>{const e=E(a=>a.tree.cellsById[n]),s=Ee(),o=(e==null?void 0:e.data)??yT;return t.jsx(Ko,{label:Nt(e),value:Me(e==null?void 0:e.data.value),labelStyle:pt(o),valueStyle:Bn(o),onLabelCommit:a=>s(n,"contractTitle",a),onValueCommit:a=>s(n,"value",a),testId:"doc-builder-widget-text-sentence"})},CT={kind:"textSentence",label:"Text (Sentence)",category:"text",icon:Kp,searchKeywords:["text","sentence","line","input","field"],legacyCellTypes:["textLong"],defaultData:{cellType:"textLong",contractTitle:"New Text",value:""},Render:jT,settings:Uo({multiline:!0,inputTypeOptions:Ki})},IT={},ST=({nodeId:n})=>{const e=E(a=>a.tree.cellsById[n]),s=Ee(),o=(e==null?void 0:e.data)??IT;return t.jsx(Ko,{label:Nt(e),value:Me(e==null?void 0:e.data.value),block:!0,labelStyle:pt(o),valueStyle:Bn(o),onLabelCommit:a=>s(n,"contractTitle",a),onValueCommit:a=>s(n,"value",a),testId:"doc-builder-widget-text-paragraph"})},vT={kind:"textParagraph",label:"Text (Paragraph)",category:"text",icon:sc,searchKeywords:["text","paragraph","multiline","textarea","long"],legacyCellTypes:["textXLong"],defaultData:{cellType:"textXLong",contractTitle:"New Text",value:""},Render:ST,settings:Uo({multiline:!0,inputTypeOptions:fT})},TT={root:{width:"100%"}},wT={},kT={0:"left",1:"center",2:"right"},PT=({nodeId:n})=>{const e=E(i=>i.tree.cellsById[n]),s=Ee(),o=(e==null?void 0:e.data)??wT,a=Number(o.alignment)||0;return t.jsx(ko,{value:Me(o.value),onCommit:i=>s(n,"value",i),multiline:!0,placeholder:"Text",sx:TT.root,style:{...ou(o
20),textAlign:kT[a]??"left"},testId:"doc-builder-widget-header-text"})},DT=[{value:0,icon:ac,label:"Align left"},{value:1,icon:ic,label:"Align center"},{value:2,icon:lc,label:"Align right"}],Ui=({nodeId:n})=>{const e=E(o=>{var a;return Number((a=o.tree.cellsById[n])==null?void 0:a.data.alignment)||0}),s=Ee();return t.jsx(Xe,{label:"Alignment",inline:!0,children:t.jsx(Gt,{exclusive:!0,size:"small",value:e,onChange:(o,a)=>{a!==null&&s(n,"alignment",a)},sx:ae.toggleGroup,children:DT.map(({value:o,icon:a,label:i})=>t.jsx(Ve,{value:o,"aria-label":i,"data-testid":`doc-builder-setting-alignment-${o}`,children:t.jsx(a,{fontSize:"small"})},o))})})},OT={kind:"headerText",label:"Header Text",category:"text",icon:Up,searchKeywords:["header","text","title","subtitle","heading"],legacyCellTypes:["default"],Render:PT,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"value",label:"Text",multiline:!0},{kind:"custom",id:"alignment",render:Ui}]}],style:[lu]}},ia={root:{display:"flex",width:"100%"},image:{objectFit:"contain",width:"auto",maxWidth:"100%"},placeholder:{display:"flex",alignItems:"center",minWidth:80,px:1,border:"1px dashed",borderColor:"grey.300",backgroundColor:"grey.50",borderRadius:1,color:"text.secondary"}},NT=40,jr={0:"flex-start",1:"center",2:"flex-end"},MT=n=>{if(!n||typeof n!="object")return;const{url:e}=n;return typeof e=="string"?e:void 0},LT=({nodeId:n})=>{const e=E(d=>d.tree.cellsById[n]),[s,o]=y.useState(!1),a=(e==null?void 0:e.data)??{},i=Number(a.logoHeight)||NT,l=Number(a.alignment)||0,r=MT(a.image);return!r||s?t.jsx(N,{sx:ia.placeholder,style:{height:i,justifyContent:jr[l]??"flex-start"},"data-testid":"doc-builder-widget-header-image",children:t.jsx(z,{variant:"caption",children:"Image"})}):t.jsx(N,{sx:ia.root,style:{justifyContent:jr[l]},"data-testid":"doc-builder-widget-header-image",children:t.jsx(N,{component:"img",src:r,alt:"Header image",onError:()=>o(!0),sx:ia.image,style:{height:i}})})},ET={kind:"headerImage",label:"Header Image",category:"media",icon:hc,searchKeywords:["image","logo","header","picture"],legacyCellTypes:["image"],Render:LT,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"number",key:"logoHeight",label:"Image Size",min:1},{kind:"custom",id:"alignment",render:Ui}]}]}},AT="3px 5px",Cr=1.5,gs={root:{display:"flex",alignItems:"baseline",gap:1,width:"100%",padding:AT},label:{flex:1,minWidth:0,fontWeight:600,whiteSpace:"nowrap",lineHeight:Cr},options:{flex:1,minWidth:0,display:"flex",justifyContent:"flex-end",alignItems:"baseline",gap:2},option:n=>({color:n?"text.primary":"text.disabled",fontWeight:n?600:400,lineHeight:Cr,whiteSpace:"nowrap"})},Ir="☑",Sr="☐",FT=({label:n,checked:e=!1,onLabel:s="Yes",offLabel:o="No",labelStyle:a,valueStyle:i,testId:l})=>{const r=i?{fontSize:i.fontSize,fontFamily:i.fontFamily}:void 0;return t.jsxs(N,{sx:gs.root,"data-testid":l,children:[n&&t.jsx(z,{variant:"body2",sx:gs.label,style:a,children:n}),t.jsxs(N,{sx:gs.options,children:[t.jsx(z,{variant:"body2",sx:gs.option(e),style:r,children:`${e?Ir:Sr} ${s}`}),t.jsx(z,{variant:"body2",sx:gs.option(!e),style:r,children:`${e?Sr:Ir} ${o}`})]})]})},RT={},_T=({nodeId:n})=>{const e=E(i=>i.tree.cellsById[n]),s=(e==null?void 0:e.data)??RT,o=Me(e==null?void 0:e.data.switchValueOn)||"Yes",a=Me(e==null?void 0:e.data.switchValueOff)||"No";return t.jsx(FT,{label:Nt(e),checked:Me(e==null?void 0:e.data.value)===o,onLabel:o,offLabel:a,labelStyle:pt(s),valueStyle:Bn(s),testId:"doc-builder-widget-switched"})},BT={kind:"switched",label:"Switch",category:"text",icon:Gp,searchKeywords:["switch","toggle","boolean","yes","no","checkbox"],legacyCellTypes:["switched"],defaultData:{cellType:"switched",contractTitle:"New Switch",switchValueOn:"YES",switchValueOff:"NO",value:""},Render:_T,settings:hT},to={root:{display:"flex",flexDirection:"column",gap:.5,width:"100%",padding:"3px 5px"},title:{fontWeight:700},columns:{display:"flex",width:"100%",alignItems:"flex-start"},column:{display:"flex",flexDirection:"column",minWidth:0}},$T={},zT=({nodeId:n,renderChild:e})=>{const s=E(r=>{var d;return(d=r.tree.cellsById[n])==null?void 0:d.data.header}),o=E(r=>r.tree.columnIdsByGroup[n]),a=E(r=>r.tree.cellIdsByColumn),i=Me(s==null?void 0:s.title),l=o??[];return t.jsxs(N,{sx:to.root,"data-testid":"doc-builder-widget-header",children:[i&&t.jsx(z,{variant:"subtitle1",sx:to.title,style:pt(s??$T),children:i}),l.length>0&&t.jsx(N,{sx:to.columns,children:l.map(r=>
20t.jsx(N,{sx:to.column,style:{width:`${100/l.length}%`},children:(a[r]??[]).map(d=>e({nodeId:d,nodeType:"cell"}))},r))})]})},WT=[{value:0,label:"None"},{value:1,label:"Outside"},{value:2,label:"Inside & Outside"},{value:3,label:"Top & Bottom"}],HT={},qT=({nodeId:n})=>{const e=E(i=>{var l;return((l=i.tree.cellsById[n])==null?void 0:l.data.header)??HT}),s=Ee(),o=(i,l)=>s(n,"header",{...e,[i]:l}),a=typeof e.border=="number"?e.border:0;return t.jsxs(t.Fragment,{children:[t.jsx(Le,{label:"Title",size:"small",color:"secondary",fullWidth:!0,sx:ae.compactLabeledField,value:Me(e.title),onChange:i=>o("title",i.target.value),slotProps:{htmlInput:{"data-testid":"doc-builder-setting-header-title"}}}),t.jsx(Le,{select:!0,label:"Border",size:"small",color:"secondary",fullWidth:!0,sx:ae.compactLabeledField,value:a,onChange:i=>o("border",Number(i.target.value)),children:WT.map(i=>t.jsx(ue,{value:i.value,children:i.label},i.value))})]})},VT={},KT=({nodeId:n})=>{const e=E(c=>{var u;return((u=c.tree.cellsById[n])==null?void 0:u.data.header)??VT}),s=Ee(),o=(c,u)=>s(n,"header",{...e,[c]:u}),[a,i]=y.useState(null),l=typeof e.titleFontSize=="number"?e.titleFontSize:"",r=typeof e.titleFontName=="string"?e.titleFontName:"",d=typeof e.titleFontColor=="string"?e.titleFontColor:void 0;return t.jsxs(t.Fragment,{children:[t.jsx(Le,{label:"Size",size:"small",color:"secondary",type:"number",fullWidth:!0,sx:ae.compactLabeledField,value:l,onChange:c=>o("titleFontSize",c.target.value===""?void 0:Number(c.target.value)),slotProps:{htmlInput:{min:1,"data-testid":"doc-builder-setting-header-titleFontSize"}}}),t.jsx(Xe,{label:"Style",inline:!0,children:t.jsxs(Gt,{size:"small",sx:ae.toggleGroup,children:[t.jsx(Ve,{value:"bold",selected:!!e.titleFontBold,onClick:()=>o("titleFontBold",!e.titleFontBold),"aria-label":"Bold","aria-pressed":!!e.titleFontBold,children:t.jsx(Ao,{fontSize:"small"})}),t.jsx(Ve,{value:"underline",selected:!!e.titleFontUnderline,onClick:()=>o("titleFontUnderline",!e.titleFontUnderline),"aria-label":"Underline","aria-pressed":!!e.titleFontUnderline,children:t.jsx(Fo,{fontSize:"small"})})]})}),t.jsx(Le,{select:!0,label:"Font",size:"small",color:"secondary",fullWidth:!0,sx:ae.compactLabeledField,value:r,onChange:c=>o("titleFontName",c.target.value),children:Es.map(c=>t.jsx(ue,{value:c.value,children:c.label},c.value))}),t.jsxs(Xe,{label:"Color",inline:!0,children:[t.jsx(we,{variant:"outlined","aria-label":"Title color",onClick:c=>i(c.currentTarget),sx:ae.colorButton,children:t.jsx(mc,{sx:{color:Hi(d)??"inherit"}})}),t.jsx(Mo,{open:!!a,anchorEl:a,onClose:()=>i(null),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:t.jsx(Eo,{color:nu(d),onChange:({rgb:c})=>o("titleFontColor",su({r:c.r,g:c.g,b:c.b,a:c.a??1}))})})]})]})},UT={kind:"header",label:"Header",category:"layout",icon:dc,searchKeywords:["header","title","heading","logo","banner"],legacyCellTypes:["header"],Render:zT,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"custom",id:"headerSettings",render:qT}]}],style:[{title:"Title Font",collapsible:!0,fields:[{kind:"custom",id:"headerFont",render:KT}]}]}},no={root:n=>({display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:.5,width:"100%",p:.5,border:"1px dashed",borderColor:n?"primary.main":"divider",borderRadius:1,backgroundColor:n?"action.hover":"transparent",color:"text.secondary",textAlign:"center",overflow:"hidden"}),icon:{fontSize:28,color:"text.disabled"},text:{lineHeight:1.3},link:{color:"primary.main",fontWeight:600,textDecoration:"underline",cursor:"pointer"}},GT=90,JT=({height:n,onSelect:e})=>{const s=y.useRef(null),[o,a]=y.useState(!1),i=n<GT,l=u=>{u&&u.type.startsWith("image/")&&e(u)},r=u=>{var p;u.stopPropagation(),(p=s.current)==null||p.click()},d=u=>{var p;l((p=u.target.files)==null?void 0:p[0]),s.current&&(s.current.value="")},c=u=>{var p;u.preventDefault(),a(!1),l((p=u.dataTransfer.files)==null?void 0:p[0])};return t.jsxs(N,{sx:no.root(o),style:{minHeight:n},onDragEnter:u=>{u.preventDefault(),a(!0)},onDragOver:u=>u.preventDefault(),onDragLeave:u=>{u.preventDefault(),a(!1)},onDrop:c,"data-testid":"doc-builder-sketch-dropzone",children:[t.jsx("input",{ref:s,t
20ype:"file",accept:"image/*",onChange:d,style:{display:"none"},"data-testid":"doc-builder-sketch-file-input"}),!i&&t.jsx(ga,{sx:no.icon}),t.jsxs(z,{variant:"caption",sx:no.text,children:[!i&&"Drag & drop or ",t.jsx(N,{component:"span",sx:no.link,onClick:r,children:"browse"}),!i&&" — background image"]})]})},YT="3px 5px",so={root:{display:"flex",flexDirection:"column",gap:.5,width:"100%",padding:YT},label:{fontWeight:600,lineHeight:1.5},sketch:{position:"relative",width:"100%",border:"1px solid",borderColor:"divider",borderRadius:1,overflow:"hidden",backgroundSize:"contain",backgroundPosition:"center",backgroundRepeat:"no-repeat"},removeButton:{position:"absolute",top:4,right:4,color:"error.main",backgroundColor:"background.paper",boxShadow:2,"&:hover":{backgroundColor:"background.paper"}}},XT=120,ZT={},QT=n=>{if(!n||typeof n!="object")return;const e=n,s=e._url;return typeof s=="string"?s:typeof e.url=="string"?e.url:void 0},ew=({nodeId:n})=>{const e=E(r=>r.tree.cellsById[n]),s=Ee(),o=Nt(e),a=Number(e==null?void 0:e.data.imageHeight)||XT,i=QT(e==null?void 0:e.data.drawingBackgroundImage),l=async r=>{if(!r){s(n,"drawingBackgroundImage",void 0);return}try{const d=await as(r,"document","drawingBackgroundImage");s(n,"drawingBackgroundImage",d)}catch(d){wt({title:"Background image upload failed",error:d,showVerbose:!0})}};return t.jsxs(N,{sx:so.root,"data-testid":"doc-builder-widget-drawing",children:[o&&t.jsx(z,{variant:"subtitle2",sx:so.label,style:pt((e==null?void 0:e.data)??ZT),children:o}),i?t.jsx(N,{sx:so.sketch,style:{minHeight:a,backgroundImage:`url("${i}")`},role:"img","aria-label":o||"Sketch background","data-testid":"doc-builder-sketch-image",children:t.jsx(ye,{size:"small",onClick:r=>{r.stopPropagation(),l(null)},sx:so.removeButton,"aria-label":"Remove background image","data-testid":"doc-builder-sketch-remove",children:t.jsx(Jp,{sx:{fontSize:12}})})}):t.jsx(JT,{height:a,onSelect:l})]})},tw={kind:"drawing",label:"Sketch",category:"media",icon:Yp,searchKeywords:["sketch","drawing","draw","canvas","diagram"],legacyCellTypes:["drawing"],defaultData:{cellType:"drawing",contractTitle:"New Sketch",imageHeight:120},Render:ew,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"contractTitle",label:"Title"},{kind:"switch",key:"required",label:"Required"},{kind:"number",key:"imageHeight",label:"Sketch Pad Height",min:1,step:10}]}],style:[dn],advanced:[Vi,Ks]}},nw="3px 5px",sw=168,ow=116,Pn={root:{display:"flex",flexDirection:"column",gap:.5,width:"100%",padding:nw},tiles:{display:"flex",flexWrap:"wrap",gap:1.5},tile:{display:"flex",flexDirection:"column",gap:.5,width:sw},placeholder:{display:"flex",alignItems:"center",justifyContent:"center",height:ow,borderRadius:1.5,border:"1px dashed",borderColor:"grey.300",backgroundColor:"grey.50"},placeholderIcon:{fontSize:40,color:"grey.400"},imageTitle:{lineHeight:1.3},imageNote:{lineHeight:1.3}},aw={},iw="(Placeholder Image Note)",lw=[1,2],rw=({nodeId:n})=>{const e=E(a=>a.tree.cellsById[n]),s=(e==null?void 0:e.data)??aw,o=Me(s.photoTag).trim()||"Image";return t.jsx(N,{sx:Pn.root,"data-testid":"doc-builder-widget-photo-picker",children:t.jsx(N,{sx:Pn.tiles,children:lw.map(a=>t.jsxs(N,{sx:Pn.tile,"data-testid":"doc-builder-photo-slot",children:[t.jsx(N,{sx:Pn.placeholder,"data-testid":"doc-builder-photo-placeholder",children:t.jsx(_a,{sx:Pn.placeholderIcon})}),t.jsx(z,{variant:"caption",sx:Pn.imageTitle,style:pt(s),children:`${o} 1.${a}`}),t.jsx(z,{variant:"caption",sx:Pn.imageNote,style:Bn(s),children:iw})]},a))})})},cw={kind:"photoPicker",label:"Photos",category:"media",icon:Xp,searchKeywords:["photo","photos","image","picker","gallery"],legacyCellTypes:["photoPickerCell"],defaultData:{cellType:"photoPickerCell",contractTitle:"New Photos",images:[]},Render:rw,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"contractTitle",label:"Title"},{kind:"switch",key:"required",label:"Required"},{kind:"text",key:"photoTag",label:"Default Tag",multiline:!0},{kind:"switch",key:"allowReportPhotos",label:"Link Report Photos"}]}],style:[dn,Vo],advanced:[Ks]}},dw={kind:"signatures",label:"Signature",category:"signature",icon:gc,searchKeywords:["signature","sign","initials","esign","autograph","block","container","footer"],legacyCellTypes:["signatures"],defaultData:{cellType:"signatures",contractTitle:"New Title",value:" ",signatures:[{appNote:"Signature 1",contractNote:"%customerName%",contractNoteFontSize:8,contractNoteBold:!0,footerNote:"%customerName%",underline:!0,column:0,additionalLines:[{underline:!0,value:"%date%",note:"Date",valueFontSize:12,valueFontBold:!0,noteFontSize:8,noteFontBold:!1}]},{appNote:"Signature 2",contractNote:"%customerSpouseName%",contractNoteFontSize:8,contractNoteBold:!0,footerNote:"%customerSpouseName%",underline:!0,column:1,additionalLines:[{underline:!0,value:"%date%",note:"Date",valueFontSize:12,valueFontBold:!0,noteFontSize:8,noteFontBold:!1}]}]},Render:Kd,settings:{content:[{title:"Signers",collapsible:!0,fields:[{kind:"custom",id:"captureAccordions",render:tu}]}]}},uw={},pw=[],hw=({nodeId:n,renderChild:e})=>{const s=E(a=>{var i;return((i=a.tree.capturesById[n])==null?void 0:i.data)??uw}),o=E(a=>a.tree.noteIdsByCapture[n]??pw);return t.jsxs(N,{sx:It.capture,"data-testid":`doc-builder-capture-${n}`,children:[t.jsx(N,{sx:It.signArea}
20),t.jsx(N,{sx:It.signRule}),Me(s.contractNote)&&t.jsx(z,{variant:"caption",sx:It.signLabel,children:Me(s.contractNote)}),t.jsxs(N,{sx:It.notes,children:[t.jsx(ut,{target:{level:"note",captureId:n,index:0}}),o.map((a,i)=>t.jsxs(y.Fragment,{children:[e({nodeId:a,nodeType:"note"}),t.jsx(ut,{target:{level:"note",captureId:n,index:i+1}})]},a))]})]})},mw={kind:"capture",label:"Signer",category:"signature",icon:gc,searchKeywords:["signer","capture","signature"],legacyCellTypes:[],Render:hw,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"contractNote",label:"Signature Label"},{kind:"text",key:"footerNote",label:"Footer Note"},{kind:"text",key:"appNote",label:"App Note"},{kind:"switch",key:"underline",label:"Underline"}]}],style:[{title:"Label Font",collapsible:!0,fields:[{kind:"number",key:"contractNoteFontSize",label:"Font Size",min:1},{kind:"switch",key:"contractNoteBold",label:"Bold"}]}]}},gw={},xw=({nodeId:n})=>{const e=E(s=>{var o;return((o=s.tree.notesById[n])==null?void 0:o.data)??gw});return t.jsxs(N,{sx:It.extraLine,"data-testid":`doc-builder-note-${n}`,children:[t.jsx(N,{sx:It.extraValue,children:t.jsx(z,{variant:"body2",children:Me(e.value)})}),t.jsx(N,{sx:It.extraRule}),Me(e.note)&&t.jsx(z,{variant:"caption",sx:It.extraNote,children:Me(e.note)})]})},fw={kind:"note",label:"Note",category:"signature",icon:Ra,searchKeywords:["note","line","date","signature"],legacyCellTypes:[],Render:xw,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"value",label:"Value"},{kind:"text",key:"note",label:"Note"},{kind:"switch",key:"underline",label:"Underline"}]}],style:[{title:"Value Font",collapsible:!0,fields:[{kind:"number",key:"valueFontSize",label:"Font Size",min:1},{kind:"switch",key:"valueFontBold",label:"Bold"}]},{title:"Note Font",collapsible:!0,fields:[{kind:"number",key:"noteFontSize",label:"Font Size",min:1},{kind:"switch",key:"noteFontBold",label:"Bold"}]}]}},bw="3px 5px",vr=1.5,zn={inline:{display:"flex",alignItems:"baseline",gap:1,width:"100%",padding:bw},labelSlot:{flex:1,minWidth:0,display:"flex",alignItems:"baseline"},label:{fontWeight:600,whiteSpace:"nowrap",lineHeight:vr},slot:{flex:1,minWidth:0,display:"flex",justifyContent:"flex-end",alignItems:"baseline",gap:.5,textAlign:"right",color:"text.secondary"},lock:{fontSize:14,color:"text.disabled",alignSelf:"center"},mask:{letterSpacing:1,lineHeight:vr}},yw="•••• •••• •••• ••••",Xn=({label:n,mask:e=yw,labelStyle:s,testId:o})=>t.jsxs(N,{sx:zn.inline,"data-testid":o,children:[t.jsx(N,{sx:zn.labelSlot,children:n&&t.jsx(z,{variant:"body2",sx:zn.label,style:s,children:n})}),t.jsxs(N,{sx:zn.slot,children:[t.jsx(Zp,{sx:zn.lock}),t.jsx(z,{variant:"body2",sx:zn.mask,children:e})]})]}),jw={},Cw=({nodeId:n})=>{const e=E(o=>o.tree.cellsById[n]),s=Nt(e)||"Credit Card";return t.jsx(Xn,{label:s,mask:"•••• •••• •••• ••••",labelStyle:pt((e==null?void 0:e.data)??jw),testId:"doc-builder-widget-credit-card"})},xu=({nodeId:n,fieldKey:e,label:s,multiline:o,validate:a})=>{const i=E(c=>{var u;return Me((u=_e(c.tree,n))==null?void 0:u[e])}),r=E(c=>{var u;return a==="uniqueIdentifier"&&pu(c.tree,n,Me((u=_e(c.tree,n))==null?void 0:u[e]))})?"Identifier already in use":void 0,d=Ee();return t.jsx(Le,{label:s,size:"small",color:"secondary",fullWidth:!0,error:!!r,helperText:r,sx:o?ae.resizableMultiline:ae.compactLabeledField,value:i,onChange:c=>d(n,e,c.target.value),slotProps:{input:o?{inputComponent:"textarea"}:void 0,inputLabel:o?{shrink:!0}:void 0,htmlInput:{"data-testid":`doc-builder-setting-${e}`}}})},Iw=10,fu=({nodeId:n,fieldKey:e,label:s,options:o})=>{const a=E(r=>{var d;return(d=_e(r.tree,n))==null?void 0:d[e]}),i=typeof a=="string"?a:"",l=Ee();return o.length>Iw?t.jsx(Pc,{label:s,size:"small",sx:ae.commonSelect,options:o,value:o.find(r=>r.value===i)??null,onChange:(r,d)=>l(n,e,(d==null?void 0:d.value)??"")}):t.jsx(_t,{label:s,size:"small",fullWidth:!0,sx:ae.commonSelect,options:o,value:i,onChange:r=>l(n,e,r.target.value),slotProps:{htmlInput:{"data-testid":`doc-builder-setting-${e}`}}})},Sw=[{value:"captureAndCharge",label:"Capture and Charge"},{value:"captureOnly",label:"Capture Only"}],vw=({nodeId:n})=>{const e=E(a=>{var i;return!!((i=a.tree.cellsById[n])!=null&&i.data.disablePaymentRequest)}),s=E(a=>{var i;return!!((i=a.tree.cellsById[n])!=null&&i.data.disableCaptureAndCharge)}),o=Ee();return t.jsxs(t.Fragment,{children:[t.jsx(Xe,{label:"Send Payment Request",inline:!0,children:t.jsx(xt,{edge:"end",checked:!e,color:"secondary",onChange:a=>o(n,"disablePaymentRequest",!a.target.checked),inputProps:{"aria-label":"Send Payment Request"},sx:ae.switch})}),!e&&t.jsx(xu,{nodeId:n,fieldKey:"paymentRequestText",label:"Success Value"}),t.jsx(Xe,{label:"Capture and Charge Enabled",inline:!0,children:t.jsx(xt,{edge:"end",checked:!s,color:"secondary",onChange:a=>o(n,"disableCaptureAndCharge",!a.target.checked),inputProps:{"aria-label":"Capture and Charge Enabled"},sx:ae.switch})}),!s&&t.jsx(Xe,{label:"Default Payment Mode",children:t.jsx(fu,{nodeId:n,fieldKey:"defaultPaymentMode",label:"Default Payment Mode",options:Sw})})]})},Gi={content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"contractTitle",label:"Title"},{kind:"switch",key:"required",label:"Required"},{kind:"custom",id:"paymentSettings",render:vw}]}],style:[dn],advanced:[Ks]},Tw={kind:"creditCard",label:"Credit Card",category:"payment",icon:Qp,searchKeywords:["credit card","card","payment","secure","capture"],legacyCellTypes:["creditCardCell"],defaultData:{cellType:"creditCardCell",contractTitle:"Credit Card"},Render:Cw,settings:Gi},ww="3px 5px",Tr={root:{display:"flex",flexDirection:"column",width:"100%"},heading:{fontWeight:600,padding:ww}},kw={},Pw=({nodeId:n})=>{const e=E(i=>i.tree.cellsById[n]),s=(e==null?void 0:e.data)??kw,o=Nt(e),a=pt(s);return t.jsxs(N,{sx:Tr.root,"data-testid":"doc-builder-widget-bank-account",children:[o&&t.jsx(z,{variant:"subtitle2",sx:Tr.heading,style:a,children:o}),t.jsx(Xn,{label:"Routing Number",mask:"••• ••• •••",labelStyle:a}),t.jsx(Xn,{label:"Account Number",mask:"•••• •••• ••••",labelStyle:a})]})},Dw={kind:"bankAccount",label:"Bank Account",category:"payment",icon:eh,searchKeywords:["bank","account","echeck","ach","routing","payment"],legacyCellTypes:["bankAccountCell"],defaultData:{cellType:"bankAccountCell",contractTitle:"Bank Account"},Render:Pw,settings:Gi},wr="3px 5px",la={root:{display:"flex",flexDirection:"column",width:"100%"},heading:{fontWeight:600,padding:wr},note:{color:"text.secondary",padding:wr}},Ow={},Nw=({nodeId:n})=>{const e=E(l=>l.tree.cellsById[n]),s=(e==null?void 0:e.data)??Ow,o=Nt(e)||"Secure Payment Capture",a=Me(e==null?void 0:e.data.paymentRequestText),i=pt(s);return t.jsxs(N,{sx:la.root,"data-testid":"doc-builder-widget-secure-payment",children:[t.jsx(z,{variant:"subtitle2",sx:la.heading,style:i,children:o}),a&&t.jsx(z,{variant:"caption",sx:la.note,children:a}),t.jsx(Xn,{label:"Card Number",mask:"•••• •••• •••• ••••",labelStyle:i}),t.jsx(Xn,{label:"Routing Number",mask:"••• ••• •••",labelStyle:i}),t.jsx(Xn,{label:"Account Number",mask:"•••• •••• ••••",labelStyle:i})]})},Mw={kind:"securePayment",label:"Secure Payment",category:"payment",icon:th,searchKeywords:["payment","secure","capture","card","echeck","pay"],legacyCellTypes:["securePaymentCaptureAll"],defaultData:{cellType:"securePaymentCaptureAll",contractTitle:"Secure Payment Capture",paymentRequestText:""},Render:Nw,settings:Gi},Lw="3px 5px",Ew=1.5,xs={root:{display:"flex",alignItems:"center",gap:.75,width:"100%",minWidth:0,padding:Lw},leadIcon:{color:"grey.500",fontSize:16,flex:"0 0 auto"},label:{flex:1,minWidth:0,lineHeight:Ew,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},previewIcon:{color:"grey.400",fontSize:16,flex:"0 0 auto",cursor:"default"},previewImg:{display:"block",maxWidth:220,maxHeight:220}},Aw={},Fw=n=>{if(!Array.isArray(n)||n.length===0)return;const{file:e}=n[0];if(!e||typeof e!="object")return;const s=e._url;return typeof s=="string"?s:typeof e.url=="string"?e.url:void 0},Rw=({nodeId:n})=>{const e=E(a=>a.tree.cellsById[n]),s=Nt(e),o=Fw(e==null?void 0:e.data.images);return t.jsxs(N,{sx:xs.root,"data-testid":"doc-builder-widget-image-picker",children:[t.jsx(_a,{sx:xs.leadIcon}),t.jsx(z,{variant:"body2",sx:xs.label,style:pt((e==null?void 0:e.data)??Aw),children:s||"Image"}),t.jsx(Q,{placement:"left",title:o?t.jsx(N,{component:"img",src:o,alt:s||"Image",sx:xs.previewImg}):"No image selected yet",children:t.jsx(nh,{sx:xs.previewIcon,"data-testid":"doc-builder-image-picker-preview"})})]})},_w=({nodeId:n})=>{const e=ft(),s=Ee(),o=E(l=>{var r;return((r=l.tree.cellsById[n])==null?void 0:r.data.imagesSource)==="default"}),a=ze(l=>{var d,c;const r=(d=l.templatesEdit)==null?void 0:d.currentWorkingId;return r?(c=l.templatesEdit)==null?void 0:c[r]:void 0}),i=()=>{var r;const l=(r=a==null?void 0:a.getObjectWithId)==null?void 0:r.call(a,n);l&&(e(Ne(l)),e(jo(!0)))};return t.jsxs(t.Fragment,{children:[t.jsx(Xe,{label:"Use Shared Images",inline:!0,children:t.jsx(xt,{edge:"end",color:"secondary",checked:o,onChange:(l,r)=>s(n,"imagesSource",r?"default":"unique"),inputProps:{"aria-label":"Use Shared Images"},sx:ae.switch})}),t.jsx(N,{sx:{px:1.5,pb:1},children:t.jsx(we,{fullWidth:!0,size:"small",variant:"outlined",color:"secondary",startIcon:t.jsx(sh,{fontSize:"small"}),onClick:i,"data-testid":"doc-builder-manage-images",children:"Manage Images"})})]})},Bw={kind:"imagePicker",label:"Image",category:"media",icon:hc,searchKeywords:["image","picker","photo","detail"],legacyCellTypes:["imagePicker"],defaultData:{cellType:"imagePicker",contractTitle:"New Image"},Render:Rw,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"contractTitle",label:"Title"},{kind:"switch",key:"required",label:"Required"},{kind:"switch",key:"disableImageLink",label:"Link Price Guide Image",inverted:!0},{kind:"custom",id:"imageSource",render:_w}]}],style:[dn],advanced:[Ks]}},kr={root:{display:"flex",width:"100%"},image:{objectFit:"contain",width:"auto",maxWidth:"100%"}},$w=56,zw="/images/salesPro_logo.png",Ww={0:"flex-start",1:"center",2:"flex-end"},Hw=({nodeId:n})=>{const e=E(c=>c.tree.cellsById[n]),s=E(c=>c.companyLogoUrl),[o,a]=y.useState(!1),i=Number(e==null?void 0:e.data.logoHeight)||$w,l=Number(e==null?void 0:e.data.alignment)||0,r=Ww[l]??"flex-start",d=s&&!o?s:zw;return t.jsx(N,{sx:kr.root,style:{justifyContent:r},"data-testid":"doc-builder-widget-company-logo",children:t.jsx(N,{component:"img",src:d,alt:"Company logo",sx:kr.image,style:{height:i},onError:()=>a(!0)})})},qw={kind:"companyLogo",label:"Company Logo",category:"media",icon:oh,searchKeywords:["company","logo","brand","image"],legacyCellTypes:["companyLogo"],Render:Hw,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"slider",key:"logoHeight",label:"Logo Size",min:1,max:200,step:1},{kind:"custom",id:"alignment",render:Ui}]}]}},ra={col:{flex:"0 0 auto",pl:"3px",pt:"3px"},box:n=>({display:"flex",alignItems:"center",justifyContent:"center",borderRadius:1,border:"1px dashed",borderColor:n?"success.main":"grey.300",boxShadow:n?e=>`0 0 0 2px ${e.palette.success.main}`:"none",backgroundColor:"grey.50",cursor:"pointer"}),icon:{color:"grey.400",fontSize:28}},Vw=({cellId:n,size:e})=>{const s=E(l=>l.selectedReservedDetailId===n),o=E(l=>l.selectReservedImage),a=E(l=>l.showPanel),i=l=>{l.stopPropagation(),o(n),a("element")};return t.jsx(N,{sx:ra.col,children:t.jsx(N,{sx:ra.box(s),style:{width:e,height:e},role:"button","aria-label":"Image size","data-testid":"doc-builder-detail-reserved-image","data-selected":s||void 0,onClick:i,children:t.jsx(_a,{sx:ra.icon})})})},Dn={root:{display:"flex",flexDirection:"column",width:"100%"},title:{fontWeight:600,px:"5px"},body:{display:"flex",width:"100%",alignItems:"flex-start"},column:{flex:1,width:0,minWidth:0,display:"flex",flexDirection:"column"},bottom:{display:"flex",flexDirection:"column",width:"100%"},empty:{minHeight:40,m:"3px",px:"5px",display:"flex",alignItems:"center",border:n=>`1px dashed ${n.palette.grey[300]}`,borderRadius:1,backgroundColor:"grey.50",color:"text.secondary",fontSize:12}},Kw=70,Uw=[],Gw={},bu=({nodeId:n,renderChild:e})=>{const s=E(x=>Nt(x.tree.cellsById[n])),o=E(x=>{var m;return((m=x.tree.cellsById[n])==null?void 0:m.data)??Gw}),a=E(x=>x.tree.detailItemIdsByCell[n]??Uw),i=E(x=>x.tree.cellsById),l=x=>{var m;return(m=i[x])==null?void 0:m.cellType},r=ls(a.map(x=>({objectId:x,cellType:l(x)??null}))),d=r.left.map(x=>x.objectId),c=r.right.map(x=>x.objectId),u=r.bottom.map(x=>x.objectId),p=a.some(x=>l(x)==="imagePicker"),h=Number(o.imageHeight)||Kw,g=(x,m)=>t.jsxs(t.Fragment,{children:[x.map((f,j)=>t.jsxs(y.Fragment,{children:[t.jsx(ut,{target:{level:"detail",cellId:n,column:m,index:j}}),e({nodeId:f,nodeType:"cell"})]},f)),t.jsx(ut,{target:{level:"detail",cellId:n,column:m,index:x.length}})]});return t.jsxs(N,{sx:Dn.root,"data-testid":"doc-builder-widget-detail-cell",children:[s&&t.jsx(z,{variant:"subtitle2",sx:Dn.title,style:pt(o),children:s}),t.jsxs(N,{sx:Dn.body,children:[p&&t.jsx(Vw,{cellId:n,size:h}),t.jsx(N,{sx:Dn.column,children:g(d,"left")}),t.jsx(N,{sx:Dn.column,children:g(c,"right")})]}),t.jsx(N,{sx:Dn.bottom,children:g(u,"bottom")}),a.length===0&&t.jsx(N,{sx:Dn.empty,children:"No line items yet — add one from the toolbar."})]})},Jw={kind:"detailCell",label:"Detail",category:"layout",icon:ah,searchKeywords:["detail","line item","image","group","nested"],legacyCellTypes:["detailCell"],defaultData:{cellType:"detailCell",contractTitle:"New Detail",imageHeight:70,detailItems:[]},Render:bu,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"contractTitle",label:"Title"},{kind:"switch",key:"required",label:"Required"}]}],style:[dn],advanced:[Vi]}},Yw={kind:"detailImageSection",label:"Detail Image Section",category:"layout",icon:ih,searchKeywords:["detail","image","line item","section","photo","thumbnail"],legacyCellTypes:[],defaultData:{cellType:"detailCell",contractTitle:"New Detail Image Section",imageHeight:70,detailItems:[{cellType:"imagePicker",contractTitle:"New Image"},{cellType:"textShort",contractTitle:"New Line Item"}]},Render:bu},On="Helvetica, Arial, sans-serif",nt={root:{display:"flex",flexDirection:"column",width:"100%"},block:{display:"flex",padding:"3px 6px",fontFamily:On},main:{display:"flex",flex:1,minWidth:0},imageCol:{minWidth:"50%",maxWidth:"50%"},image:{objectFit:"contain",maxWidth:"100%"},viewLabels:{display:"flex",width:"100%"},viewLabel:{flex:1,fontFamily:On,fontSize:"8px",textAlign:"center"},specCol:{minWidth:"50%",maxWidth:"50%"},spec:{fontFamily:On,fontSize:"8px",m:"0 3px"},specBold:{fontFamily:On,fontSize:"9px",fontWeight:"bold",m:"0 3px"}
20,quantityBox:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",width:75,height:75,m:"6px 3px 0",backgroundColor:"rgba(224, 224, 224, 0.7)",borderRadius:"5px"},quantityLabel:{fontFamily:On,fontSize:"18px",lineHeight:1,textAlign:"center"},quantityNumber:{fontFamily:On,fontSize:"40px",fontWeight:"bold",lineHeight:1,mt:"-6px",textAlign:"center"},partLabel:{fontFamily:On,fontSize:"8px",textAlign:"center",width:"100%"},detailItems:{display:"flex",flexDirection:"column",gap:1,padding:"3px 6px"}},Xw=[],Zw=[{text:"Signet Single Entry Door in Full Wood Frame",bold:!0},{text:'-36" x 80" Nominal Size'},{text:'-14" Sidelite Width'},{text:'-Unit Size: 68 1/16" x 81 5/8" -Frame Depth: 4 9/16"'},{text:'-2" Standard Brickmold'},{text:"-Right Hand Inswing - Inside Looking Out"},{text:"-Frame"},{text:"-Snow Mist White Aluminum Frame Cladding"},{text:"-Chestnut Inside Frame"},{text:"-Cherry Inside Mull Cover - Chestnut"},{text:'-Bronze Sahara Threshold (6 1/16" Depth)'},{text:"-Satin Nickel Ball Bearing Hinges"},{text:"-Security Plate"},{text:'-Cherry Colonial 2 1/2" Casing - Chestnut'},{text:"Entry Door",bold:!0},{text:"-449 Style Signet Cherry Fiberglass Door"},{text:"-With Panel Planks"},{text:"-Somerset Decorative Glass with Zinc Caming and Low-E (SOM)"},{text:"-Chestnut Inside and Outside"},{text:"-Hardware"},{text:"-All Hardware in Satin Nickel Finish"},{text:"-Camelot Grip Entrance Handle Outside"},{text:"-Flair Handle Inside"},{text:"-Thumbturn Deadbolt"},{text:"Sidelites on Both Sides",bold:!0},{text:"-160 Style Signet Cherry Fiberglass Sidelite"},{text:"-Somerset Decorative Glass with Zinc Caming and Low-E (SOM)"},{text:"-Chestnut Inside and Outside"}],Qw=({nodeId:n,renderChild:e})=>{const s=E(o=>o.tree.detailItemIdsByCell[n]??Xw);return t.jsxs(N,{sx:nt.root,"data-testid":"doc-builder-widget-pro-via",children:[t.jsxs(N,{sx:nt.block,children:[t.jsxs(N,{sx:nt.main,children:[t.jsxs(N,{sx:nt.imageCol,children:[t.jsx(N,{component:"img",src:"/images/provia_door.png",alt:"Provia Door",sx:nt.image}),t.jsxs(N,{sx:nt.viewLabels,children:[t.jsx(z,{component:"span",sx:nt.viewLabel,children:"Inside View"}),t.jsx(z,{component:"span",sx:nt.viewLabel,children:"Outside View"})]})]}),t.jsx(N,{sx:nt.specCol,children:Zw.map((o,a)=>t.jsx(z,{component:"p",sx:o.bold?nt.specBold:nt.spec,children:o.text},a))})]}),t.jsxs(N,{children:[t.jsxs(N,{sx:nt.quantityBox,children:[t.jsx(z,{sx:nt.quantityLabel,children:"Quantity"}),t.jsx(z,{sx:nt.quantityNumber,children:"2"})]}),t.jsx(z,{sx:nt.partLabel,children:"40123456"})]})]}),s.length>0&&t.jsx(N,{sx:nt.detailItems,children:s.map(o=>e({nodeId:o,nodeType:"cell"}))})]})},ek={kind:"provia",label:"ProVia",category:"layout",icon:nc,searchKeywords:["provia","detail","line item","nested"],legacyCellTypes:["provia"],defaultData:{cellType:"provia",contractTitle:"New ProVia",detailItems:[]},Render:Qw,settings:{content:[{title:"Content",collapsible:!0,fields:[{kind:"text",key:"contractTitle",label:"Title"},{kind:"switch",key:"required",label:"Required"},{kind:"number",key:"imageHeight",label:"Image Size",min:1}]}],style:[dn]}},Pr="3px 5px",Wn={root:{display:"flex",flexDirection:"column",width:"100%"},row:{display:"flex",width:"100%",alignItems:"flex-start"},column:{padding:Pr,overflowWrap:"anywhere"},sample:{display:"block"},empty:{color:"text.secondary",padding:Pr}},tk={},Dr=[{key:"title",width:25,align:"left"},{key:"subtitle",width:25,align:"left"},{key:"quantity",width:9.375,align:"right"},{key:"measurementType",width:18.75,align:"right"},{key:"unitTotal",width:9.375,align:"right"},{key:"total",width:12.5,align:"right"}],nk=[{title:"Item Name 1",subtitle:"Brand 1 - Name 1",quantity:"99",measurementType:"Each",unitTotal:"$100.00",total:"$999.00"},{title:"Item Name 2",subtitle:"Brand 2 - Name 2",quantity:"99",measurementType:"Each",unitTotal:"$100.00",total:"$999.00"}],sk=({nodeId:n})=>{const e=E(l=>l.tree.cellsById[n]),s=(e==null?void 0:e.data)??tk,o=s.linkedMeasureSheetItemConfig??{},a=Dr.some(l=>o[l.key]),i=Bn(s);return a?t.jsx(N,{sx:Wn.root,"data-testid":"doc-builder-widget-measure-sheet-item",children:nk.map(l=>t.jsx(N,{sx:Wn.row,"data-testid":"doc-builder-msi-row",children:Dr.map(r=>
20t.jsx(N,{sx:Wn.column,style:{minWidth:`${r.width}%`,maxWidth:`${r.width}%`,textAlign:r.align},"data-testid":`doc-builder-msi-col-${r.key}`,children:o[r.key]&&t.jsx(z,{variant:"caption",sx:Wn.sample,style:i,children:l[r.key]})},r.key))},l.title))}):t.jsx(N,{sx:Wn.root,"data-testid":"doc-builder-widget-measure-sheet-item",children:t.jsx(z,{variant:"caption",sx:Wn.empty,children:"Measure sheet item"})})},ok=[{key:"title",label:"Show Title"},{key:"subtitle",label:"Show Selected Option"},{key:"quantity",label:"Show Quantity"},{key:"measurementType",label:"Show Measure Type"},{key:"unitTotal",label:"Show Unit Total"},{key:"total",label:"Show Grand Total"}],ak={},ik=({nodeId:n})=>{const e=E(i=>{var l;return((l=i.tree.cellsById[n])==null?void 0:l.data.linkedMeasureSheetItemConfig)??ak}),s=E(i=>{var l;return!!((l=i.tree.cellsById[n])!=null&&l.data.drawIfEmpty)}),o=Ee(),a=(i,l)=>o(n,"linkedMeasureSheetItemConfig",{...e,[i]:l});return t.jsxs(t.Fragment,{children:[ok.map(({key:i,label:l})=>t.jsx(Xe,{label:l,inline:!0,children:t.jsx(xt,{edge:"end",checked:!!e[i],color:"secondary",onChange:r=>a(i,r.target.checked),inputProps:{"aria-label":l},sx:ae.switch})},i)),t.jsx(Xe,{label:"Hide Unless Added to Estimate",inline:!0,children:t.jsx(xt,{edge:"end",checked:!s,color:"secondary",onChange:i=>o(n,"drawIfEmpty",!i.target.checked),inputProps:{"aria-label":"Hide Unless Added to Estimate"},sx:ae.switch})})]})},lk={kind:"measureSheetItem",label:"Measure Sheet Item",category:"advanced",icon:lh,searchKeywords:["measure sheet","measure","quantity","total","linked","item"],legacyCellTypes:["measureSheetItemDetail"],defaultData:{cellType:"measureSheetItemDetail",contractTitle:"Measure Sheet Item",value:""},Render:sk,settings:{content:[{title:"Detail Settings",collapsible:!0,fields:[{kind:"custom",id:"measureSheetColumns",render:ik}]},{title:"Formula",collapsible:!0,fields:[{kind:"custom",id:"formula",render:gu}]}],style:[Vo]}},rk={root:{width:"100%",p:1,border:"1px dashed",borderColor:"divider",borderRadius:1,color:"text.secondary"}},ck=({nodeId:n})=>{const e=E(s=>{var o;return(o=s.tree.cellsById[n])==null?void 0:o.cellType});return t.jsx(N,{sx:rk.root,"data-testid":"doc-builder-widget-unknown",children:t.jsxs(z,{variant:"caption",children:["Unsupported widget: ",e??"unknown"]})})},dk={kind:"unknown",label:"Unsupported",category:"advanced",icon:rh,searchKeywords:[],legacyCellTypes:[],Render:ck},Fs={section:pv,letterheadSection:hv,row:Ev,column:_v,emptySpace:zv,textOnly:mT,textWords:bT,textSentence:CT,textParagraph:vT,headerText:OT,headerImage:ET,switched:BT,header:UT,drawing:tw,photoPicker:cw,signatures:dw,capture:mw,note:fw,creditCard:Tw,bankAccount:Dw,securePayment:Mw,imagePicker:Bw,companyLogo:qw,detailCell:Jw,detailImageSection:Yw,provia:ek,measureSheetItem:lk,unknown:dk},ln=n=>Fs[n]??Fs.unknown,Oa=(n,e)=>{const{detailItems:s=[],...o}=structuredClone(n),a=new X(void 0,e);return Object.assign(a,o),a.detailItems=s.map(i=>Oa(i,a)),a},uk=n=>{const e=new X(void 0,n),s=new dt(void 0,e),[o]=s.cellItems??[];return Object.assign(o.cellItems[0],{cellType:"image",value:Wd.image}),Object.assign(s,{cellItems:[o],title:"",appTitle:""}),e.header=s,e.cellType="header",e},Ji=()=>{const n=ft(),e=E(a=>a.setTree),s=ze(a=>{var i;return(i=a.templatesEdit)==null?void 0:i.currentWorkingId}),o=ze(a=>{var i;return s?(i=a.templatesEdit)==null?void 0:i[s]:void 0});return y.useCallback((a,i)=>{var r,d,c,u,p,h,g,x;const l=o;if(!(!l||!l.insertObjectAtPath)){if(i.level==="cell"){const m=(r=l.getObjectWithId)==null?void 0:r.call(l,i.groupId),f=(d=m==null?void 0:m.getPath)==null?void 0:d.call(m),{defaultData:j}=ln(a);if(!m||!f)return;const S=a==="headerImage"?uk(m):j&&Oa(j,m);if(!S)return;l.insertObjectAtPath([...f,i.index],S,0)}else if(i.level==="detail"){const m=(c=l.getObjectWithId)==null?void 0:c.call(l,i.cellId),{defaultData:f}=ln(a);if(!m||!Array.isArray(m.detailItems)||!f)return;const j=Oa(f,m);m.detailItems=$S(m.detailItems,i.column,i.index,j)}else if(i.level==="headerCell"){const m=(u=l.getObjectWithId)==null?void 0:u.call(l,i.columnId),f=(p=m==null?void 0:m.getPath)==null?void 0:p.call(m),j=zd[a];if(!m||!f||!j)return;const S=new tn(void 0,m,0),w=Wd[j];Object.assign(S,w?{cellType:j,value:w}:{cellType:j}),l.insertObjectAtPath([...f,i.index],S,0)}else if(i.level==="row"){const m=(h=l.getObjectWithId)==null?void 0:h.call(l,i.sectionId),f=(g=m==null?void 0:m.getPath)==null?void 0:g.call(m);if(!m||!f||m.groupType!=="body")return;const j=new ct(void 0,m);l.insertObjectAtPath([...f,i.index],j,0)}else if(i.level==="section"){const m=l.contractData??[];if(a==="letterheadSection"||a==="signatures"){const f=a==="letterheadSection"?new Bt(void 0,l):new nn(void 0,l);m.splice(Math.min(i.index,m.length),0,f)}else{if((x=l.hasBodySection)!=null&&x.call(l)||!l.addBodySection)return;l.addBodySection()}}else return;e(zi(l)),n(ee(l))}},[n,e,o])},pk=Object.values(Fs).reduce((n,e)=>
20(e.legacyCellTypes.forEach(s=>{n[s]=e.kind}),n),{}),rs=n=>n?pk[n]??"unknown":"unknown",yu=(n,e)=>E(s=>{var o;return e==="cell"&&!!n&&pu(s.tree,n,Me((o=_e(s.tree,n))==null?void 0:o.cellId))}),hk={header:"Letterhead",body:"Content",signature:"Signatures"},Yi=n=>n&&hk[n]||"Section",ju=(n,e,s)=>{if(n==="section")return Yi(s);const o=n==="cell"?rs(e):n;return ln(o).label},mk=["headerImage","companyLogo"],gk=["unknown","imagePicker","header","headerText","capture","note","section","column"],xk=[{category:"layout",label:"Layout"},{category:"text",label:"Text"},{category:"media",label:"Media"},{category:"signature",label:"Signature"},{category:"payment",label:"Payment"},{category:"advanced",label:"Advanced"}],Na=()=>Object.values(Fs).filter(n=>!gk.includes(n.kind)),Cu=n=>n==="section"||n==="letterheadSection"?"section":n==="row"?"row":mk.includes(n)?"headerCell":"cell",Iu=n=>{const e=n.trim().toLowerCase();return e?Na().filter(s=>s.label.toLowerCase().includes(e)||s.searchKeywords.some(o=>o.toLowerCase().includes(e))):Na()},fk=(n="")=>{const e=n.trim().toLowerCase();return Bd.map(s=>Fs[s]).filter(s=>!e||s.label.toLowerCase().includes(e)||s.searchKeywords.some(o=>o.toLowerCase().includes(e)))},Su=(n,e,s="")=>n==="detail"?fk(s):Iu(s).filter(o=>Ai({kind:o.kind,level:Cu(o.kind)},n,e)),bk=(n=Na())=>xk.map(({category:e,label:s})=>({category:e,label:s,widgets:n.filter(o=>o.category===e)})).filter(e=>e.widgets.length>0),vu="doc-builder-add-widget-handle",po={handle:{position:"absolute",top:"50%",left:-44,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:22,height:30,borderRadius:1,backgroundColor:"background.paper",color:"text.secondary",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.3), 0 4px 14px rgba(0, 0, 0, 0.22)",cursor:"pointer",zIndex:5,opacity:0,pointerEvents:"none",transition:n=>n.transitions.create("opacity",{duration:n.transitions.duration.shortest}),"&:hover":{backgroundColor:"grey.100"}},popover:{width:300,p:1},list:{mt:.5,maxHeight:320,overflowY:"auto",py:0},empty:{px:2,py:1.5,color:"text.secondary",fontSize:14}},yk=(n,e)=>e.level!=="detail"||n!=="textParagraph"?e:{...e,column:"bottom",index:Number.MAX_SAFE_INTEGER},Tu=({anchorEl:n,onClose:e,target:s,hostZone:o})=>{const a=Ji(),[i,l]=y.useState(""),r=()=>{l(""),e()},d=Su(s.level,o,i);return t.jsx(Mo,{open:!!n,anchorEl:n,onClose:r,onClick:c=>c.stopPropagation(),anchorOrigin:{vertical:"center",horizontal:"left"},transformOrigin:{vertical:"center",horizontal:"right"},children:t.jsxs(N,{sx:po.popover,children:[t.jsx(Le,{autoFocus:!0,size:"small",fullWidth:!0,color:"secondary",placeholder:"Search widgets…",value:i,onChange:c=>l(c.target.value),slotProps:{input:{startAdornment:t.jsx(yo,{position:"start",children:t.jsx(Ba,{fontSize:"small"})})}},"data-testid":"doc-builder-add-widget-search"}),t.jsxs(Xt,{sx:po.list,children:[d.map(c=>{const u=c.icon;return t.jsxs(St,{"data-testid":`doc-builder-add-widget-${c.kind}`,onClick:()=>{a(c.kind,yk(c.kind,s)),r()},children:[t.jsx($e,{sx:{minWidth:34},children:t.jsx(u,{fontSize:"small"})}),t.jsx(Te,{children:c.label})]},c.kind)}),d.length===0&&t.jsx(z,{sx:po.empty,children:"No matching widgets."})]})]})})},jk=({cellId:n})=>{const[e,s]=y.useState(null),o=E(i=>{const l=i.tree.detailItemIdsByCell[n]??[];return ls(l.map(r=>{var d;return{objectId:r,cellType:(d=i.tree.cellsById[r])==null?void 0:d.cellType}})).left.length}),a=i=>{i.stopPropagation(),s(i.currentTarget)};return t.jsxs(t.Fragment,{children:[t.jsx(Q,{title:"Add line item",children:t.jsx(ye,{size:"small",onClick:a,"aria-label":"Add line item","data-testid":"doc-builder-add-detail-item",children:t.jsx(ch,{fontSize:"small",sx:{color:"black"}})})}),t.jsx(Tu,{anchorEl:e,onClose:()=>s(null),target:{level:"detail",cellId:n,column:"left",index:o}})]})},Ck=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent||""),ca=Ck?"⌘":"Ctrl+",oo=n=>t.jsx(z,{component:"span",variant:"body2",sx:{ml:4,color:"text.secondary"},children:n}),wu=(n,e,s)=>{var v;const{duplicateNode:o,deleteNode:a,deleteSelection:i,copyNode:l,copySelection:r,cutNode:d,cutSelection:c,canPasteBelow:u,pasteBelow:p}=cn(),h=u(n),g=E(I=>I.selectedNodes.length>1&&I.selectedNodes.some(D=>D.id===n)),x=E(I=>I.selectedNodes.length),m=E(I=>{var D;return e==="section"&&((D=I.tree.sectionsById[n])==null?void 0:D.groupType)==="body"}),f=I=>()=>{I(),s()},j=g?` ${x} items`:"",S=(v=_i(sn(wo)))==null?void 0:v.length,w=S&&S>1?`Paste ${S} items`:"Paste",C=[t.jsxs(ue,{"data-testid":"doc-builder-menu-copy",onClick:f(()=>g?r():l(n)),children:[t.jsx($e,{children:t.jsx(fc,{fontSize:"small"})}),t.jsx(Te,{children:`Copy${j}`}),oo(`${ca}C`)]},"copy")];return m||C.push(t.jsxs(ue,{"data-testid":"doc-builder-menu-cut",onClick:f(()=>g?c():d(n)),children:[t.jsx($e,{children:t.jsx(dh,{fontSize:"small"})}),t.jsx(Te,{children:`Cut${j}`}),oo(`${ca}X`)]},"cut")),C.push(t.jsxs(ue,{"data-testid":"doc-builder-menu-paste",disabled:!h||g,onClick:f(()=>p(n)),children:[t.jsx($e,{children:t.jsx(uh,{fontSize:"small"})}),t.jsx(Te,{children:w}),oo(`${ca}V`)]},"paste")),m||C.push(t.jsx(ie,{},"divider"),t.jsxs(ue,{"data-testid":"doc-builder-menu-duplicate",disabled:g,onClick:f(()=>o(n)),children:[t.jsx($e,{children:t.jsx(xc,{fontSize:"small"})}),t.jsx(Te,{children:"Duplicate"})]},"duplicate"),t.jsxs(ue,{"data-testid":"doc-builder-menu-delete",onClick:f(()=>g?i():a(n)),children:[t.jsx($e,{children:t.jsx($a,{fontSize:"small"})}),t.jsx(Te,{children:`Delete${j}`}),oo("Del")]},"delete")),C}
20,Ik={pill:{position:"absolute",top:-40,left:"50%",transform:"translateX(-50%)",display:"flex",alignItems:"center",gap:.25,px:.5,py:.25,borderRadius:999,backgroundColor:"background.paper",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.3), 0 4px 14px rgba(0, 0, 0, 0.22)",cursor:"default",zIndex:5}},Sk=({nodeId:n,nodeType:e})=>{var S,w;const{duplicateNode:s,deleteNode:o,deleteSelection:a}=cn(),i=E(C=>C.selectNode),l=E(C=>C.tree),r=HS(l,n,e),d=(r==null?void 0:r.nodeType)==="section"?(S=l.sectionsById[r.nodeId])==null?void 0:S.groupType:void 0,c=e==="section"&&((w=l.sectionsById[n])==null?void 0:w.groupType)==="body",u=E(C=>C.selectedNodes.length>1&&C.selectedNodes.some(v=>v.id===n)),p=E(C=>{var v;return((v=C.tree.cellsById[n])==null?void 0:v.cellType)==="detailCell"}),[h,g]=y.useState(null),x=C=>C.stopPropagation(),m=()=>g(null),f=wu(n,e,m),j=r?`Select ${ju(r.nodeType,void 0,d)}`:"";return t.jsxs(N,{sx:Ik.pill,onClick:x,"data-testid":"doc-builder-element-tools",children:[r&&t.jsx(Q,{title:j,children:t.jsx(ye,{size:"small",onClick:()=>i(r.nodeId,r.nodeType),"aria-label":j,"data-testid":"doc-builder-tool-select-parent",children:t.jsx(ph,{fontSize:"small",sx:{color:"black"}})})}),p&&!u&&t.jsx(jk,{cellId:n}),!c&&t.jsx(Q,{title:"Duplicate",children:t.jsx("span",{children:t.jsx(ye,{size:"small",disabled:u,onClick:()=>s(n),"aria-label":"Duplicate","data-testid":"doc-builder-tool-duplicate",children:t.jsx(xc,{fontSize:"small",sx:{color:"black"}})})})}),!c&&t.jsx(Q,{title:"Delete",children:t.jsx(ye,{size:"small",onClick:()=>u?a():o(n),"aria-label":"Delete","data-testid":"doc-builder-tool-delete",children:t.jsx($a,{fontSize:"small",sx:{color:"black"}})})}),t.jsx(Q,{title:"More",children:t.jsx(ye,{size:"small",onClick:C=>g(C.currentTarget),"aria-label":"More options","data-testid":"doc-builder-tool-more",children:t.jsx(hh,{fontSize:"small",sx:{color:"black"}})})}),t.jsx(kt,{anchorEl:h,open:!!h,onClose:m,children:f})]})},ku=({nodeId:n,nodeType:e,position:s,onClose:o})=>{const a=wu(n,e,o);return t.jsx(kt,{open:!0,onClose:o,anchorReference:"anchorPosition",anchorPosition:s,children:a})},Pu="doc-builder-drag-handle",vk={handle:{position:"absolute",top:"50%",right:-44,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:22,height:30,borderRadius:1,backgroundColor:"background.paper",color:"text.secondary",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.3), 0 4px 14px rgba(0, 0, 0, 0.22)",cursor:"grab",zIndex:5,opacity:0,pointerEvents:"none",transition:n=>n.transitions.create("opacity",{duration:n.transitions.duration.shortest}),"&:active":{cursor:"grabbing"}}},Du=y.forwardRef(({attributes:n,listeners:e},s)=>t.jsx(N,{ref:s,className:Pu,sx:vk.handle,"aria-label":"Drag to reorder","data-testid":"doc-builder-drag-handle",...n,...e,children:t.jsx(Ro,{fontSize:"small",sx:{color:"black"}})}));Du.displayName="DragHandle";const Tk=({target:n,hostZone:e})=>{const[s,o]=y.useState(null),a=i=>{i.stopPropagation(),o(i.currentTarget)};return t.jsxs(t.Fragment,{children:[t.jsx(N,{className:vu,sx:po.handle,role:"button","aria-label":"Add widget below","data-testid":"doc-builder-add-widget",onClick:a,children:t.jsx(wn,{fontSize:"small",sx:{color:"black"}})}),t.jsx(Tu,{anchorEl:s,onClose:()=>o(null),target:n,hostZone:e})]})},Ma="doc-builder-node",ho="doc-builder-identifier-badge",da=n=>`inset 0 0 0 2px ${n.palette.primary.main}`,Or=(n,e)=>`inset 0 0 0 1px ${Kn(n.palette.primary.main,e)}`,ao={duplicateBadge:{position:"absolute",top:2,right:2,zIndex:2,fontSize:"1.05rem",borderRadius:"50%",backgroundColor:"background.paper"},identifierBadge:{position:"absolute",top:-30,right:-44,zIndex:5,width:22,height:22,p:"3px",borderRadius:1,backgroundColor:"background.paper",color:"secondary.main",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.3), 0 4px 14px rgba(0, 0, 0, 0.22)",opacity:0,transition:n=>n.transitions.create("opacity",{duration:n.transitions.duration.shortest})},columnNode:{flex:1,minWidth:0},node:(n,e)=>({position:"relative",cursor:"pointer",opacity:e?.4:1,borderRadius:0,transition:s=>s.transitions.create(["box-shadow","opacity"],{duration:s.transitions.duration.shortest}),[`& > .${Pu}`]:{opacity:n?1:0,pointerEvents:n?"auto":"none"},[`& > .${vu}`]:{opacity:n?1:0,pointerEvents:n?"auto":"none"},[`& > .${ho}`]:{opacity:n?1:0},[`&:hover > .${ho}`]:{opacity:1},[`&:hover:has(.${Ma}:hover) > .${ho}`]:{opacity:n?1:0}
20,boxShadow:s=>n?da(s):"none","&:hover":{boxShadow:s=>n?da(s):Or(s,1)},[`&:hover:has(.${Ma}:hover)`]:{boxShadow:s=>n?da(s):Or(s,.25)}})},Ou=({nodeId:n,nodeType:e})=>{var T,B;const s=E(L=>{var H;return e==="cell"?((H=L.tree.cellsById[n])==null?void 0:H.cellType)??null:null}),o=E(L=>L.selectedNodes.some(H=>H.id===n)),a=E(L=>L.selectedNodeId===n),i=E(L=>L.tree),l=a?WS(i,n,e):null,r=(l==null?void 0:l.level)==="row"?(T=i.sectionsById[l.sectionId])==null?void 0:T.groupType:void 0,d=!!l&&Su(l.level,r).length>0,c=E(L=>L.selectNode),u=E(L=>L.toggleNode),p=E(L=>L.showPanel),g=E(L=>Fi(L.tree,n))?"detail":e,{attributes:x,listeners:m,setNodeRef:f,setActivatorNodeRef:j,isDragging:S}=za({id:`move:${n}`,data:{move:!0,nodeId:n,level:g}});let w;e==="section"?w="section":e==="row"?w="row":e==="column"||e==="capture"||e==="note"?w=e:w=rs(s);const{Render:C}=ln(w),v=L=>{L.stopPropagation(),L.metaKey||L.ctrlKey?u(n,e):c(n,e),p("element")},[I,D]=y.useState(null),F=L=>{L.preventDefault(),L.stopPropagation(),o||c(n,e),D({top:L.clientY,left:L.clientX})},M=e==="column",R=yu(n,e),P=E(L=>{var H;return e==="cell"?Me((H=L.tree.cellsById[n])==null?void 0:H.data.cellId):""}),k=e==="section"&&((B=i.sectionsById[n])==null?void 0:B.groupType)==="body";return t.jsxs(N,{ref:f,onClick:v,onContextMenu:F,className:Ma,sx:[ao.node(o,S),M&&ao.columnNode],"data-testid":`doc-builder-node-${n}`,"data-selected":o||void 0,children:[I&&t.jsx(ku,{nodeId:n,nodeType:e,position:I,onClose:()=>D(null)}),a&&!k&&t.jsx(Sk,{nodeId:n,nodeType:e}),a&&!k&&d&&l&&t.jsx(Tk,{target:l,hostZone:r}),!M&&!k&&t.jsx(Du,{ref:j,attributes:x,listeners:m}),R&&t.jsx(Q,{title:"Identifier already in use",children:t.jsx(Wa,{color:"error",sx:ao.duplicateBadge,"data-testid":`doc-builder-duplicate-${n}`})}),!R&&P!==""&&t.jsx(Q,{title:`Identifier: ${P}`,placement:"right-start",children:t.jsx(mh,{className:ho,sx:ao.identifierBadge,"data-testid":`doc-builder-identifier-${n}`})}),t.jsx(C,{nodeId:n,renderChild:L=>t.jsx(Ou,{nodeId:L.nodeId,nodeType:L.nodeType},L.nodeId)})]})},Nr="4px",Mr="0 1px 5px rgba(0, 0, 0, 0.16)",Nn={stack:(n,e)=>({position:"relative",width:n,minHeight:e,flexShrink:0}),pageBox:n=>({position:"absolute",left:0,right:0,top:n.top,height:n.height,backgroundColor:"common.white",borderRadius:Nr,boxShadow:Mr,pointerEvents:"none",zIndex:0}),content:n=>({position:"relative",zIndex:1,display:"flex",flexDirection:"column",gap:2,padding:`${n.marginY}px ${n.marginX}px`}),page:n=>({position:"relative",width:n.width,minHeight:n.height,padding:`${n.marginY}px ${n.marginX}px`,backgroundColor:"common.white",borderRadius:Nr,boxShadow:Mr,flexShrink:0}),placeholder:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:1,minHeight:"8in",textAlign:"center",color:"text.secondary"}},wk=()=>{const n=E(T=>T.tree.sectionIds),e=E(T=>T.tree.pageId==="pdfPage"),s=E(T=>T.tree.page),o=E(T=>T.tree.sectionsById),a=E(T=>T.tree.groupIdsBySection),i=E(T=>T.tree.groupsById),l=E(T=>T.zoom),r=E(T=>T.pageBoxes),d=E(T=>T.setPageBoxes),c=Ji(),[u,p]=ev(),h=y.useRef(new Map),g=y.useRef(null),x=y.useRef(null),m=y.useCallback((T,B)=>{B?h.current.set(T,B):h.current.delete(T)},[]),f=n.flatMap(T=>{var B;return((B=o[T])==null?void 0:B.groupType)==="signature"?[{id:T,height:u[T]??0,forceBreak:!1}]:(a[T]??[]).map(L=>{var H,G;return{id:L,height:u[L]??0,forceBreak:!!((G=(H=i[L])==null?void 0:H.data)!=null&&G.newPage)}})}),{marginTops:j,breakRowIds:S,overflowRowIds:w}=nv(f,s),C=y.useCallback(T=>j[T]??0,[j]),v=w.join(","),I=y.useMemo(()=>new Set(w),[v]),D=y.useCallback(T=>I.has(T),[I]),F=y.useMemo(()=>({marginTopFor:C,reportRowHeight:p,registerRow:m,isOverflowing:D}),[C,p,m,D]),M=JSON.stringify(u),R=S.join(",");if(y.useLayoutEffect(()=>{const T=g.current,B=x.current;if(!T||!B){d([]);return}const L=T.getBoundingClientRect().top,H=[0];S.forEach(le=>{const re=h.current.get(le);if(re){const O=(re.getBoundingClientRect().top-L)/l-s.marginY;H.push(Math.round(O))}});const G=Math.round((B.getBoundingClientRect().bottom-L)/l),ne=H.map((le,re)=>{const K=re===H.length-1?Math.max(G,le+s.height):H[re+1]-Ri;return{top:le,height:Math.max(K-le,0)}});d(ne)},[M,R,s.height,s.marginY,s.width,l]),e)return t.jsx(N,{sx:Nn.page(s),"data-testid":"doc-builder-page-frame",children:t.jsxs(N,{sx:Nn.placeholder,"data-testid":"doc-builder-pdf-placeholder",children:[t.jsx(z,{variant:"subtitle1",children:"PDF template"}),t.jsx(z,{variant:"body2",children:"PDF-based templates open in the legacy editor."})]})});if(n.length===0)return t.jsx(N,{sx:Nn.page(s),"data-testid":"doc-builder-page-frame",children:t.jsxs(N,{sx:Nn.placeholder,"data-testid":"doc-builder-empty-page",children:[t.jsx(z,{variant:"body2",children:"This document is empty."}),t.jsx(we,{variant:"outlined",color:"secondary",size:"small",onClick:()=>c("section",{level:"section",index:0}),"data-testid":"doc-builder-add-content",children:"Add Content"})]})});const P=r[r.length-1],k=P?P.top+P.height:s.height;
20return t.jsxs(N,{ref:g,sx:Nn.stack(s.width,k),"data-testid":"doc-builder-page-frame",children:[r.map((T,B)=>t.jsx(N,{sx:Nn.pageBox(T),"data-testid":"doc-builder-page-sheet","aria-hidden":!0},`sheet-${B}`)),t.jsx(Jd.Provider,{value:F,children:t.jsxs(N,{ref:x,sx:Nn.content(s),children:[t.jsx(ut,{target:{level:"section",index:0}}),n.map((T,B)=>t.jsxs(y.Fragment,{children:[t.jsx(Ou,{nodeId:T,nodeType:"section"}),t.jsx(ut,{target:{level:"section",index:B+1}})]},T))]})})]})},ua={root:n=>({flex:1,minWidth:0,minHeight:0,overflow:"auto",display:"flex",justifyContent:"safe center",alignItems:"flex-start",p:`${En}px`,backgroundColor:"grey.200",marginTop:`${Ms}px`,marginBottom:`${vo}px`,marginRight:`${qs+(n?Wo:0)}px`,transition:e=>e.transitions.create("margin",{duration:e.transitions.duration.shorter})}),sizer:(n,e)=>({width:n,height:e,flexShrink:0}),scaler:n=>({transform:`scale(${n})`,transformOrigin:"top left"})},Lr=({drawerOpen:n})=>{const{setNodeRef:e}=zs({id:Ia}),s=E(u=>u.clearSelection),o=E(u=>u.zoom),a=E(u=>u.tree.page),i=E(u=>u.pageBoxes),l=E(u=>u.setCanvasEl),r=y.useCallback(u=>{e(u),l(u)},[e,l]),d=i[i.length-1],c=d?d.top+d.height:a.height;return t.jsx(N,{ref:r,sx:ua.root(n),"data-testid":"doc-builder-canvas",onClick:s,children:t.jsx(N,{sx:ua.sizer(a.width*o,c*o),children:t.jsx(N,{sx:ua.scaler(o),children:t.jsx(wk,{})})})})},kk=768,Er=.6,mo={bothRow:{flex:1,minWidth:0,display:"flex",overflowX:"auto"},appPane:n=>({flex:1,minWidth:0,overflow:"auto",display:"flex",justifyContent:"safe center",alignItems:"flex-start",backgroundColor:"grey.200",marginTop:`${Ms}px`,marginBottom:`${vo}px`,marginRight:n?`${qs+Wo}px`:0,p:`${En}px`,transition:e=>e.transitions.create("margin",{duration:e.transitions.duration.shorter})}),appPaneBoth:{width:`${kk*Er+2*En}px`,flexShrink:0,overflow:"auto",display:"flex",justifyContent:"center",alignItems:"flex-start",backgroundColor:"grey.200",marginTop:`${Ms}px`,marginBottom:`${vo}px`,p:`${En}px`},appScaler:{zoom:Er}},Ar=({drawerOpen:n,inBoth:e})=>t.jsx(N,{sx:e?mo.appPaneBoth:mo.appPane(n),"data-testid":"doc-builder-app-view",children:e?t.jsx(N,{sx:mo.appScaler,children:t.jsx(ja,{})}):t.jsx(ja,{})}),Pk=({drawerOpen:n})=>{const e=ze(s=>{var o;return((o=s.templatesEdit)==null?void 0:o.viewSelection)??1});return e===0?t.jsx(Ar,{drawerOpen:n,inBoth:!1}):e===2?t.jsxs(N,{sx:mo.bothRow,"data-testid":"doc-builder-both-view",children:[t.jsx(Ar,{drawerOpen:n,inBoth:!0}),t.jsx(Lr,{drawerOpen:n})]}):t.jsx(Lr,{drawerOpen:n})},Mn={panel:{width:Wo,display:"flex",flexDirection:"column",height:"100%"},header:{display:"flex",alignItems:"center",justifyContent:"space-between",px:2,py:1.5,borderBottom:"1px solid",borderColor:"divider"},heading:{display:"flex",flexDirection:"column",minWidth:0},title:{fontWeight:600,lineHeight:1.2},subtitle:{color:"text.secondary",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},content:{flex:1,minHeight:0,overflowY:"auto"},drawer:{position:"absolute",top:Ms,right:0,bottom:0,left:0,pointerEvents:"none","& .MuiDrawer-paper":{position:"absolute",height:"100%",right:qs,pointerEvents:"auto"}}},pa={card:n=>({display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:.5,px:1,py:1.5,borderRadius:1,border:"1px solid",borderColor:"divider",cursor:"grab",userSelect:"none",boxShadow:1,opacity:n?.4:1,transition:e=>e.transitions.create(["border-color","background-color","opacity"],{duration:e.transitions.duration.shortest}),"&:hover":{borderColor:"primary.main",backgroundColor:"action.hover"}}),icon:{color:"text.secondary"},label:{textAlign:"center",lineHeight:1.2,color:"text.primary"}},Xi=y.forwardRef(({definition:n,dragging:e=!1,...s},o)=>{const{icon:a,label:i,kind:l}=n;return t.jsxs(N,{ref:o,sx:pa.card(e),"data-testid":`doc-builder-palette-card-${l}`,...s,children:[t.jsx(a,{sx:pa.icon,fontSize:"small"}),t.jsx(z,{variant:"caption",sx:pa.label,children:i})]})});Xi.displayName="WidgetCardView";const Dk=({definition:n})=>{const{kind:e}=n,{attributes:s,listeners:o,setNodeRef:a,isDragging:i}=za({id:`palette:${e}`,data:{kind:e,level:Cu(e)}});return t.jsx(Xi,{ref:a,definition:n,dragging:i,...s,...o})},fs={category:{borderBottom:"1px solid",borderColor:"divider"},header:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",px:2,py:1.25,background:"none",border:"none",cursor:"pointer",color:"text.primary","&:hover":{backgroundColor:"action.hover"}},title:{fontWeight:600},icon:n=>({color:"text.secondary",transform:n?"rotate(180deg)":"rotate(0deg)",transition:e=>e.transitions.create("transform",{duration:e.transitions.duration.shortest})}),grid:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:1,px:2,pb:2}},Ok=({group:n,defaultExpanded:e=!0})=>{const[s,o]=y.useState(e);return t.jsxs(N,{sx:fs.category,"data-testid":`doc-builder-palette-group-${n.category}`,children:[t.jsxs(N,{component:"button",type:"button",onClick:()=>o(a=>!a),sx:fs.header,"aria-expanded":s,children:[t.jsx(z,{variant:"subtitle2",sx:fs.title,children:n.label}),t.jsx(Pt,{sx:fs.icon(s),fontSize:"small"})]}),t.jsx(Dt,{in:s,unmountOnExit:!0,children:t.jsx(N,{sx:fs.grid,children:n.widgets.map(a=>t.jsx(Dk,{definition:a},a.kind))})})]})},ha={root:{display:"flex",flexDirection:"column"}
20,searchWrap:{position:"sticky",top:0,zIndex:1,backgroundColor:"background.paper",px:2,pt:1,pb:1,borderBottom:"1px solid",borderColor:"divider"},empty:{px:2,py:2,color:"text.secondary"}},Nk=()=>{const[n,e]=y.useState(""),s=bk(Iu(n));return t.jsxs(N,{sx:ha.root,"data-testid":"doc-builder-widgets-palette",children:[t.jsx(N,{sx:ha.searchWrap,children:t.jsx(Le,{value:n,onChange:o=>e(o.target.value),placeholder:"Search Widget...",size:"small",color:"secondary",fullWidth:!0,slotProps:{input:{startAdornment:t.jsx(yo,{position:"start",children:t.jsx(Ba,{fontSize:"small"})})},htmlInput:{"data-testid":"doc-builder-palette-search","aria-label":"Search widgets"}}})}),s.length===0?t.jsx(z,{variant:"body2",sx:ha.empty,children:"No widgets found."}):s.map(o=>t.jsx(Ok,{group:o},o.category))]})},Mk=({nodeId:n,fieldKey:e,label:s,inverted:o=!1})=>{const a=E(r=>{var d;return!!((d=_e(r.tree,n))!=null&&d[e])}),i=o?!a:a,l=Ee();return t.jsx(Xe,{label:s,inline:!0,children:t.jsx(xt,{edge:"end",checked:i,color:"secondary",onChange:r=>l(n,e,o?!r.target.checked:r.target.checked),inputProps:{"aria-label":s},sx:ae.switch})})},Lk=({nodeId:n,fieldKey:e,label:s,min:o,max:a,step:i})=>{const l=E(u=>{var p;return(p=_e(u.tree,n))==null?void 0:p[e]}),r=typeof l=="number"?l:"",d=Ee(),c=u=>{if(u===""){d(n,e,void 0);return}const p=Number(u);if(Number.isNaN(p))return;const h=o!==void 0?Math.max(o,p):p;d(n,e,a!==void 0?Math.min(a,h):h)};return t.jsx(Le,{label:s,size:"small",color:"secondary",type:"number",fullWidth:!0,value:r,onChange:u=>c(u.target.value),slotProps:{htmlInput:{min:o,max:a,step:i,"data-testid":`doc-builder-setting-${e}`}}})},Ek=({nodeId:n,fieldKey:e,label:s})=>{const o=E(c=>{var u;return(u=_e(c.tree,n))==null?void 0:u[e]}),a=typeof o=="string"?o:void 0,i=Ee(),[l,r]=y.useState(null),d=({rgb:c})=>i(n,e,su({r:c.r,g:c.g,b:c.b,a:c.a??1}));return t.jsxs(Xe,{label:s,inline:!0,children:[t.jsx(we,{variant:"outlined","aria-label":`${s} color`,"data-testid":`doc-builder-setting-${e}`,onClick:c=>r(c.currentTarget),sx:ae.colorButton,children:t.jsx(mc,{sx:{color:Hi(a)??"inherit"}})}),t.jsx(Mo,{open:!!l,anchorEl:l,onClose:()=>r(null),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:t.jsx(Eo,{color:nu(a),onChange:d})})]})},Ak=({nodeId:n,fieldKey:e,label:s,min:o=0,max:a=100,step:i=1})=>{const l=E(u=>{var p;return(p=_e(u.tree,n))==null?void 0:p[e]}),r=Ee(),d=typeof l=="number"?l:void 0,c=u=>{if(u===""){r(n,e,void 0);return}const p=Number(u);Number.isNaN(p)||r(n,e,Math.min(a,Math.max(o,p)))};return t.jsx(Xe,{label:s,children:t.jsxs(N,{sx:ae.sliderRow,children:[t.jsx(go,{size:"small",color:"secondary",min:o,max:a,step:i,value:d??o,onChange:(u,p)=>c(p)}),t.jsx(Le,{size:"small",color:"secondary",type:"number",sx:ae.sliderInput,value:d??"",onChange:u=>c(u.target.value),slotProps:{htmlInput:{min:o,max:a,step:i,"data-testid":`doc-builder-setting-${e}`}}})]})})},Fk={},Rk=({nodeId:n,label:e,buttons:s})=>{const o=E(i=>_e(i.tree,n)??Fk),a=Ee();return t.jsx(Xe,{label:e,inline:!0,children:t.jsx(Gt,{size:"small",sx:ae.toggleGroup,children:s.map(({key:i,icon:l,tooltip:r})=>{const d=!!o[i];return t.jsx(Ve,{value:i,selected:d,onClick:()=>a(n,i,!d),"aria-label":r??i,"aria-pressed":d,"data-testid":`doc-builder-setting-${i}`,children:t.jsx(l,{fontSize:"small"})},i)})})})},_k=({nodeId:n,field:e})=>{switch(e.kind){case"text":return t.jsx(xu,{nodeId:n,fieldKey:e.key,label:e.label,multiline:e.multiline,validate:e.validate});case"switch":return t.jsx(Mk,{nodeId:n,fieldKey:e.key,label:e.label,inverted:e.inverted});case"number":return t.jsx(Lk,{nodeId:n,fieldKey:e.key,label:e.label,min:e.min,step:e.step});case"select":return t.jsx(fu,{nodeId:n,fieldKey:e.key,label:e.label,options:e.options});case"color":return t.jsx(Ek,{nodeId:n,fieldKey:e.key,label:e.label});case"slider":return t.jsx(Ak,{nodeId:n,fieldKey:e.key,label:e.label,min:e.min,max:e.max,step:e.step});case"toggleGroup":return t.jsx(Rk,{nodeId:n,label:e.label,buttons:e.buttons});case"custom":{const s=e.render;return t.jsx(s,{nodeId:n})}case"divider":return t.jsx(ie,{})}},Bk=(n,e)=>n.kind==="custom"?n.id:n.kind==="toggleGroup"?`toggle:${n.label}`:n.kind==="divider"?`divider:${e}`:n.key,$k=({nodeId:n,title:e,collapsible:s,fields:o})=>{const[a,i]=y.useState(!0),l=t.jsx(N,{sx:ae.fields,children:o.map((r,d)=>t.jsx(_k,{nodeId:n,field:r},Bk(r,d)))});return e?s?t.jsxs(N,{sx:ae.section,children:[t.jsxs(N,{component:"button",type:"button",onClick:()=>i(r=>!r),sx:ae.sectionHeader,"aria-expanded":a,children:[t.jsx(z,{variant:"subtitle2",sx:{fontWeight:600},children:e}),t.jsx(Pt,{sx:ae.sectionIcon(a),fontSize:"small"})]}),t.jsx(Dt,{in:a,unmountOnExit:!0,children:l})]}):t.jsxs(N,{sx:ae.section,children:[t.jsx(z,{variant:"subtitle2",sx:ae.sectionTitle,children:e}),l]}):l},zk=["content","style","advanced"],Wk={content:{label:"General",icon:Ra},style:{label:"Design",icon:fh},advanced:{label:"Settings",icon:xh}},Hk={},qk=(n,e)=>(n??[]).map(s=>({...s,fields:s.fields.filter(o=>{var a;return((a=o.visible)==null?void 0:a.call(o,e))??!0})})).filter(s=>s.fields.length>0),Vk=(n,e)=>zk.map(s=>({tab:s,sections:qk(n[s],e)})).filter(s=>s.sections.length>0),Fr=({nodeId:n,schema:e})=>{const s=E(d=>_e(d.tree,n)??Hk),o=y.useMemo(()=>Vk(e,s),[e,s]),[a,i]=y.useState("content");
20if(o.length===0)return t.jsx(z,{variant:"body2",sx:ae.empty,children:"No editable properties yet."});const l=d=>d.map((c,u)=>t.jsx($k,{nodeId:n,title:c.title,collapsible:c.collapsible,fields:c.fields},c.title??u));if(o.length===1)return t.jsx(N,{"data-testid":"doc-builder-element-settings",children:l(o[0].sections)});const r=o.find(d=>d.tab===a)??o[0];return t.jsxs(N,{"data-testid":"doc-builder-element-settings",children:[t.jsx(gh,{value:r.tab,onChange:(d,c)=>i(c),variant:"fullWidth",textColor:"secondary",indicatorColor:"secondary",sx:ae.tabs,children:o.map(d=>{const{label:c,icon:u}=Wk[d.tab];return t.jsx(bh,{value:d.tab,label:c,icon:t.jsx(u,{fontSize:"small"}),sx:ae.tab,"data-testid":`doc-builder-tab-${d.tab}`},d.tab)})}),l(r.sections)]})},io={root:{display:"flex",flexDirection:"column"},empty:{px:2,py:2,color:"text.secondary"}},Kk={content:[{title:"Image",fields:[{kind:"slider",key:"imageHeight",label:"Image Size",min:20,max:200,step:1}]}]},Uk=()=>{const n=E(r=>r.selectedNodeId),e=E(r=>r.selectedNodeType),s=E(r=>r.selectedReservedDetailId&&r.tree.cellsById[r.selectedReservedDetailId]?r.selectedReservedDetailId:null),o=E(r=>{var d;return r.selectedNodeId?((d=r.tree.cellsById[r.selectedNodeId])==null?void 0:d.cellType)??null:null}),a=r=>t.jsx(N,{sx:io.root,"data-testid":"doc-builder-element-panel",children:t.jsx(z,{variant:"body2",sx:io.empty,children:r})});if(s)return t.jsx(N,{sx:io.root,"data-testid":"doc-builder-element-panel",children:t.jsx(Fr,{nodeId:s,schema:Kk},`reserved-${s}`)});if(!n||!e)return a("Select an element to edit its properties.");const i=e==="cell"?rs(o):e,{settings:l}=ln(i);return l?t.jsx(N,{sx:io.root,"data-testid":"doc-builder-element-panel",children:t.jsx(Fr,{nodeId:n,schema:l},n)}):a("No editable properties yet.")},Rn=[],Gk=(n,e,s)=>{const o=ls((n.detailItemIdsByCell[e]??Rn).map(i=>{var l;return{objectId:i,cellType:(l=n.cellsById[i])==null?void 0:l.cellType}})),a=o.left.length+o.right.length;return s>=a?{level:"detail",cellId:e,column:"bottom",index:s-a}:s%2===0?{level:"detail",cellId:e,column:"left",index:s/2}:{level:"detail",cellId:e,column:"right",index:(s-1)/2}},Zi=(n,e,s,o)=>{const a=[];return(n.detailItemIdsByCell[e]??Rn).forEach((i,l)=>{a.push(Zi(n,i,l,r=>Gk(n,e,r)))}),(n.columnIdsByGroup[e]??Rn).forEach((i,l)=>{a.push(Nu(n,i,e,l))}),{key:e,nodeId:e,nodeType:"cell",children:a,reorderTarget:o,index:s}},Nu=(n,e,s,o)=>({key:`col:${e}`,nodeId:e,nodeType:"column",children:(n.cellIdsByColumn[e]??Rn).map((a,i)=>Zi(n,a,i,null)),reorderTarget:a=>({level:"column",groupId:s,index:a}),index:o}),Jk=(n,e,s,o)=>{const a=n.columnIdsByGroup[e]??Rn,i=a.length>0?a.map((l,r)=>Nu(n,l,e,r)):(n.cellIdsByGroup[e]??Rn).map((l,r)=>Zi(n,l,r,d=>({level:"cell",groupId:e,index:d})));return{key:e,nodeId:e,nodeType:"row",children:i,reorderTarget:l=>({level:"row",sectionId:s,index:l}),index:o}},Mu=n=>n.sectionIds.map((e,s)=>({key:e,nodeId:e,nodeType:"section",children:(n.groupIdsBySection[e]??Rn).map((o,a)=>Jk(n,o,e,a)),reorderTarget:o=>({level:"section",index:o}),index:s})),Yk=(n,e)=>{var l,r;if(e.nodeType==="column")return`Column ${e.index+1}`;const s=e.nodeId;if(!s)return"";const o=e.nodeType==="cell"?((l=n.cellsById[s])==null?void 0:l.cellType)??null:null,a=e.nodeType==="cell"?rs(o):e.nodeType,i=e.nodeType==="section"?Yi((r=n.sectionsById[s])==null?void 0:r.groupType):ln(a).label;return`${Wi(n,s,e.nodeType)} ${i}`.trim()},Xk=(n,e,s)=>{const o=e.trim().toLowerCase();if(!o)return n;const a=i=>i.reduce((l,r)=>{if(Yk(s,r).toLowerCase().includes(o))return l.push(r),l;const c=a(r.children);return c.length&&l.push({...r,children:c}),l},[]);return a(n)},Zk=(n,e)=>{const s=[],o=a=>a.forEach(i=>{i.nodeId&&s.push({id:i.nodeId,type:i.nodeType}),i.children.length>0&&e(i.key)&&o(i.children)});return o(n),s},Qk=n=>{const e=[],s=o=>o.forEach(a=>{a.children.length>0&&(e.push(a.key),s(a.children))});return s(n),e},e0=(n,e)=>{const s=new Set;if(!e)return s;const o=(a,i)=>a.some(l=>l.nodeId===e?(i.forEach(r=>s.add(r)),!0):o(l.children,[...i,l.key]));return o(n,[]),s},vs="doc-builder-nav-handle",Rr=14,_r=32,Re={root:{display:"flex",flexDirection:"column",py:.5},header:{position:"sticky",top:0,zIndex:1,display:"flex",alignItems:"center",gap:.5,px:1,py:1,backgroundColor:"background.paper",borderBottom:"1px solid",borderColor:"divider"},search:{flex:1,minWidth:0},empty:{px:2,py:2,color:"text.secondary"},row:(n,e,s)=>({display:"flex",alignItems:"center",gap:.75,minHeight:32,pr:1,pl:`${n*Rr+8}
20px`,cursor:s?"pointer":"default",color:"text.primary",backgroundColor:o=>e?Kn(o.palette.primary.main,.12):"transparent",boxShadow:o=>e?`inset 2px 0 0 ${o.palette.primary.main}`:"none","&:hover":{backgroundColor:o=>e?Kn(o.palette.primary.main,.12):"action.hover"},[`& .${vs}`]:{opacity:0},[`&:hover .${vs}`]:{opacity:s?1:0}}),chevronButton:{display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,p:0,border:"none",background:"none",cursor:"pointer",color:"text.secondary",flexShrink:0},chevronSpacer:{width:18,flexShrink:0},chevron:n=>({transform:n?"rotate(0deg)":"rotate(-90deg)",transition:e=>e.transitions.create("transform",{duration:e.transitions.duration.shortest})}),icon:{color:"text.secondary",flexShrink:0},labelStack:{display:"flex",flexDirection:"column",justifyContent:"center",minWidth:0,flex:1},primaryLabel:{fontWeight:500,lineHeight:1.3,minWidth:0},secondaryLabel:{color:"text.secondary",fontSize:"0.68rem",lineHeight:1.2,minWidth:0},errorIcon:{color:"error.main",flexShrink:0},handle:{display:"flex",alignItems:"center",justifyContent:"center",ml:"auto",color:"text.secondary",cursor:"grab",flexShrink:0,transition:n=>n.transitions.create("opacity",{duration:n.transitions.duration.shortest}),"&:active":{cursor:"grabbing"}},deleteButton:{p:.25,color:"text.secondary",flexShrink:0,transition:n=>n.transitions.create("opacity",{duration:n.transitions.duration.shortest})},dropZone:(n,e)=>({display:"flex",alignItems:"center",height:n?_r:0,overflow:"hidden",pl:`${e*Rr+8}px`,pr:1,transition:s=>s.transitions.create("height",{duration:s.transitions.duration.shortest})}),ghostRow:n=>({display:"flex",alignItems:"center",gap:.75,flex:1,minWidth:0,height:_r-4,px:.75,borderRadius:1,...n==="shadow"?{opacity:.6,border:"1px dashed",borderColor:"primary.main",backgroundColor:e=>Kn(e.palette.primary.main,.08)}:{backgroundColor:"background.paper",boxShadow:3}}),ghostCount:{ml:"auto",px:.75,py:.125,borderRadius:1,fontWeight:600,color:"primary.contrastText",backgroundColor:"primary.main",whiteSpace:"nowrap"}},Lu=({nodeId:n,nodeType:e,variant:s="shadow",count:o=1})=>{var c;const a=E(u=>u.tree),i=e==="cell"?((c=a.cellsById[n])==null?void 0:c.cellType)??null:null,l=ln(e==="cell"?rs(i):e),r=l.icon,d=Wi(a,n,e);return t.jsxs(N,{sx:Re.ghostRow(s),"data-testid":`doc-builder-nav-ghost-${s}`,children:[t.jsx(r,{fontSize:"small",sx:Re.icon}),t.jsx(N,{sx:Re.labelStack,children:d?t.jsxs(t.Fragment,{children:[t.jsx(z,{variant:"body2",sx:Re.primaryLabel,noWrap:!0,children:d}),t.jsx(z,{variant:"caption",sx:Re.secondaryLabel,noWrap:!0,children:l.label})]}):t.jsx(z,{variant:"body2",sx:Re.primaryLabel,noWrap:!0,children:l.label})}),o>1&&t.jsxs(z,{variant:"caption",sx:Re.ghostCount,"data-testid":"doc-builder-nav-ghost-count",children:[o," items"]})]})},Br=({target:n,depth:e})=>{const s=`nav:${$d(n)}`,{setNodeRef:o,isOver:a,active:i}=zs({id:s,data:n}),l=i==null?void 0:i.data.current,r=a&&(l==null?void 0:l.move)===!0&&l.level===n.level;return t.jsx(N,{ref:o,sx:Re.dropZone(r,e),"data-testid":`doc-builder-${s}`,children:r&&t.jsx(Lu,{nodeId:l.nodeId,nodeType:l.nodeType??l.level})})},Eu=({nodes:n,tree:e,depth:s,forceExpanded:o})=>{const a=n.length>0&&n[0].reorderTarget!==null;return t.jsxs(t.Fragment,{children:[a&&t.jsx(Br,{target:n[0].reorderTarget(0),depth:s}),n.map((i,l)=>t.jsxs(y.Fragment,{children:[t.jsx(t0,{node:i,tree:e,depth:s,forceExpanded:o}),a&&t.jsx(Br,{target:i.reorderTarget(l+1),depth:s})]},i.key))]})},t0=({node:n,tree:e,depth:s,forceExpanded:o})=>{var K,U,A;const{key:a,nodeId:i,nodeType:l}=n,r=i!==null,d=n.children.length>0,c=l==="section"&&((K=e.sectionsById[i])==null?void 0:K.groupType)==="body",u=r&&!c,p=E(q=>r&&q.selectedNodes.some(Y=>Y.id===i)),h=E(q=>r&&q.selectedNodeId===i),g=E(q=>q.selectNode),x=E(q=>q.toggleNode),m=yu(i,l),{deleteNode:f,duplicateNode:j}=cn(),S=E(q=>!!q.expandedKeys[a]),w=o??S,C=E(q=>q.toggleNavExpanded),[v,I]=y.useState(null),D=y.useRef(null);y.useEffect(()=>{var q,Y;h&&((Y=(q=D.current)==null?void 0:q.scrollIntoView)==null||Y.call(q,{block:"nearest"}))},[h]);const F=n.reorderTarget?n.reorderTarget(0).level:l,{attributes:M,listeners:R,setNodeRef:P,setActivatorNodeRef:k,isDragging:T}=za({id:r?`nav-move:${i}`:`nav-col:${a}`,data:{move:!0,nodeId:i,level:F,nodeType:l},disabled:!u});let B=pc,L,H="";if(l==="column")L=`Column ${n.index+1}`;else{const q=l==="cell"?((U=e.cellsById[i])==null?void 0:U.cellType)??null:null,Y=l==="cell"?rs(q):l,ce=ln(Y);B=ce.icon,L=l==="section"?Yi((A=e.sectionsById[i])==null?void 0:A.groupType):ce.label,H=Wi(e,i,l)}const G=q=>{q.stopPropagation(),r&&(q.metaKey||q.ctrlKey?x(i,l):g(i,l))},ne=q=>{r&&(q.preventDefault(),q.stopPropagation(),p||g(i,l),I({top:q.clientY,left:q.clientX}))},le=q=>{q.stopPropagation(),C(a)},re=q=>{q.stopPropagation(),f(i)}
20,O=q=>{q.stopPropagation(),j(i)};return t.jsxs(N,{ref:P,style:{opacity:T?.45:1},children:[t.jsxs(N,{ref:D,onClick:G,onContextMenu:ne,sx:Re.row(s,p,r),"data-testid":r?`doc-builder-nav-node-${i}`:void 0,"data-selected":p||void 0,children:[d?t.jsx(N,{component:"button",type:"button",onClick:le,sx:Re.chevronButton,"aria-expanded":w,"aria-label":"Toggle",children:t.jsx(Pt,{sx:Re.chevron(w),fontSize:"small"})}):t.jsx(N,{sx:Re.chevronSpacer}),t.jsx(B,{fontSize:"small",sx:Re.icon}),t.jsx(N,{sx:Re.labelStack,children:H?t.jsxs(t.Fragment,{children:[t.jsx(Q,{title:H,placement:"top-start",enterDelay:500,children:t.jsx(z,{variant:"body2",sx:Re.primaryLabel,noWrap:!0,children:H})}),t.jsx(z,{variant:"caption",sx:Re.secondaryLabel,noWrap:!0,children:L})]}):t.jsx(z,{variant:"body2",sx:Re.primaryLabel,noWrap:!0,children:L})}),m&&t.jsx(Q,{title:"Identifier already in use",children:t.jsx(Wa,{fontSize:"small",color:"error",sx:Re.errorIcon,"data-testid":`doc-builder-nav-duplicate-warning-${i}`})}),u&&t.jsx(N,{ref:k,className:vs,sx:Re.handle,"aria-label":"Drag to reorder","data-testid":"doc-builder-nav-drag-handle",...M,...R,children:t.jsx(Ro,{fontSize:"small"})}),u&&t.jsx(ye,{size:"small",className:vs,sx:Re.deleteButton,onClick:O,"aria-label":"Duplicate","data-testid":"doc-builder-nav-duplicate",children:t.jsx(fc,{fontSize:"small"})}),u&&t.jsx(ye,{size:"small",className:vs,sx:Re.deleteButton,onClick:re,"aria-label":"Delete","data-testid":"doc-builder-nav-delete",children:t.jsx($a,{fontSize:"small"})})]}),v&&r&&t.jsx(ku,{nodeId:i,nodeType:l,position:v,onClose:()=>I(null)}),d&&t.jsx(Dt,{in:w,unmountOnExit:!0,children:t.jsx(Eu,{nodes:n.children,tree:e,depth:s+1,forceExpanded:o})})]})},n0=({expandKeys:n,query:e,onQueryChange:s})=>{const o=E(d=>d.expandedKeys),a=E(d=>d.expandAllNav),i=E(d=>d.collapseAllNav),l=n.length>0&&n.every(d=>o[d]),r=l?"Collapse all":"Expand all";return t.jsxs(N,{sx:Re.header,"data-testid":"doc-builder-nav-header",children:[t.jsx(Q,{title:r,children:t.jsx(ye,{size:"small",onClick:()=>l?i():a(n),"aria-label":r,"data-testid":"doc-builder-nav-toggle-all",children:l?t.jsx(yh,{fontSize:"small"}):t.jsx(jh,{fontSize:"small"})})}),t.jsx(Le,{value:e,onChange:d=>s(d.target.value),placeholder:"Search...",size:"small",color:"secondary",fullWidth:!0,sx:Re.search,slotProps:{input:{startAdornment:t.jsx(yo,{position:"start",children:t.jsx(Ba,{fontSize:"small"})}),endAdornment:e?t.jsx(yo,{position:"end",children:t.jsx(ye,{size:"small",onClick:()=>s(""),"aria-label":"Clear search","data-testid":"doc-builder-nav-search-clear",edge:"end",children:t.jsx(bc,{fontSize:"small"})})}):null},htmlInput:{"data-testid":"doc-builder-nav-search","aria-label":"Search document tree"}}})]})},s0=()=>{const n=E(u=>u.tree),e=E(u=>u.selectedNodeId),s=E(u=>u.setNavExpanded),[o,a]=y.useState(""),{setNodeRef:i}=zs({id:Sa}),l=y.useMemo(()=>Mu(n),[n]),r=y.useMemo(()=>Qk(l),[l]),d=o.trim()!=="",c=y.useMemo(()=>Xk(l,o,n),[l,o,n]);return y.useEffect(()=>{e0(l,e).forEach(u=>s(u,!0))},[l,e,s]),l.length===0?t.jsx(N,{ref:i,sx:Re.empty,"data-testid":"doc-builder-navigator",children:t.jsx(z,{variant:"body2",children:"No document structure yet."})}):t.jsxs(N,{ref:i,sx:Re.root,"data-testid":"doc-builder-navigator",children:[t.jsx(n0,{expandKeys:r,query:o,onQueryChange:a}),d&&c.length===0?t.jsx(N,{sx:Re.empty,children:t.jsx(z,{variant:"body2",children:"No matches."})}):t.jsx(Eu,{nodes:d?c:l,tree:n,depth:0,forceExpanded:d||void 0})]})},o0=()=>{const n=ft(),e=E(a=>a.setPage),s=ze(a=>{var i;return(i=a.templatesEdit)==null?void 0:i.currentWorkingId}),o=ze(a=>{var i;return s?(i=a.templatesEdit)==null?void 0:i[s]:void 0});return y.useCallback(a=>{const i=o;i&&(Object.assign(i,a),e(eu(i)),n(ee(i)))},[o,e,n])},ma={root:{display:"flex",flexDirection:"column",gap:2,p:2},marginRow:{display:"flex",gap:1.5},pageCount:{color:"text.secondary"}},a0=()=>{const n=E(i=>i.tree.page),e=E(i=>i.pageBoxes.length||1),s=o0(),o=`${n.width},${n.height}`,a=(i,l)=>{const r=Number(l);l===""||Number.isNaN(r)||r<0||s({[i]:r})};return t.jsxs(N,{sx:ma.root,"data-testid":"doc-builder-page-panel",children:[t.jsx(_t,{label:"Page size",size:"small",fullWidth:!0,options:yd,value:o,onChange:i=>s({pageSize:i.target.value}),slotProps:{htmlInput:{"data-testid":"doc-builder-page-size"}}}),t.jsxs(N,{sx:ma.marginRow,children:[t.jsx(Le,{label:"Side margins",size:"small",color:"secondary",type:"number",fullWidth:!0,value:n.marginX,onChange:i=>a("wMargin",i.target.value),slotProps:{htmlInput:{min:0,"data-testid":"doc-builder-margin-x"}}}),t.jsx(Le,{label:"Top & bottom",size:"small",color:"secondary",type:"number",fullWidth:!0,value:n.marginY,onCh
20ange:i=>a("hMargin",i.target.value),slotProps:{htmlInput:{min:0,"data-testid":"doc-builder-margin-y"}}})]}),t.jsxs(z,{variant:"caption",sx:ma.pageCount,"data-testid":"doc-builder-page-count",children:[e," ",e===1?"page":"pages"]})]})},i0={elements:"Fields & Elements",element:"Edit",navigator:"Document Tree",page:"Page Setup"},l0=({open:n,onClose:e,activePanel:s,subtitle:o})=>{const a=(s&&i0[s])??"Settings";return t.jsx(Ch,{anchor:"right",variant:"persistent",open:n,sx:Mn.drawer,children:t.jsxs(N,{sx:Mn.panel,"data-testid":"doc-builder-drawer",children:[t.jsxs(N,{sx:Mn.header,children:[t.jsxs(N,{sx:Mn.heading,children:[t.jsx(z,{variant:"h6",sx:Mn.title,children:a}),o&&t.jsx(z,{variant:"caption",sx:Mn.subtitle,"data-testid":"doc-builder-drawer-subtitle",children:o})]}),t.jsx(ye,{onClick:e,size:"small","aria-label":"Close panel","data-testid":"doc-builder-drawer-close",children:t.jsx(bc,{fontSize:"small"})})]}),t.jsxs(N,{sx:Mn.content,children:[s==="elements"&&t.jsx(Nk,{}),s==="element"&&t.jsx(Uk,{}),s==="navigator"&&t.jsx(s0,{}),s==="page"&&t.jsx(a0,{})]})]})})},lo={root:{position:"absolute",top:Ms,right:0,bottom:0,width:qs,display:"flex",flexDirection:"column",alignItems:"center",gap:1.5,pt:1.5,backgroundColor:"background.paper",borderLeft:"1px solid",borderColor:"divider",zIndex:n=>n.zIndex.drawer+2},item:{display:"flex",flexDirection:"column",alignItems:"center",gap:.25},button:n=>({color:n?"secondary.contrastText":"text.secondary",backgroundColor:n?"secondary.main":"transparent",borderRadius:1,"&:hover":{backgroundColor:n?"secondary.dark":"action.hover"}}),label:n=>({fontSize:11,marginTop:.7,fontWeight:n?700:400,lineHeight:1,color:n?"text.main":"text.secondary"})},r0=[{panel:"elements",label:"Add",icon:wn,tooltip:"Add Item"},{panel:"element",label:"Edit",icon:Ih,requiresSelection:!0,tooltip:"Edit Element"},{panel:"navigator",label:"Tree",icon:Sh,tooltip:"Document Tree"},{panel:"page",label:"Page",icon:vh,tooltip:"Page Setup"}],c0=()=>{const n=E(a=>a.activePanel),e=E(a=>a.drawerOpen),s=E(a=>a.showPanel),o=E(a=>a.selectedNodeId!==null);return t.jsx(N,{sx:lo.root,"data-testid":"doc-builder-rail",children:r0.map(({panel:a,label:i,icon:l,disabled:r,requiresSelection:d,tooltip:c})=>{const u=r||d&&!o,p=e&&n===a;return t.jsxs(N,{sx:lo.item,children:[t.jsx(Q,{title:c,placement:"left",children:t.jsx("span",{children:t.jsx(ye,{onClick:()=>s(a),sx:lo.button(p),size:"small",disabled:u,"aria-label":i,"aria-pressed":p,"data-testid":`doc-builder-rail-${a}`,children:t.jsx(l,{fontSize:"medium"})})})}),t.jsx(z,{variant:"caption",sx:lo.label(p),children:i})]},a)})})},d0=n=>Math.min(So,Math.max(Io,n)),u0=(n,e,s,o,a)=>{if(n.length===0)return 1;const i=s+o*.4;let l=1;return n.forEach((r,d)=>{a+r.top*e<=i&&(l=d+1)}),l},p0=(n,e,s,o)=>{if(n.length===0)return 0;const a=n[Math.max(0,Math.min(s,n.length-1))];return s<=0?0:o+a.top*e},h0=(n,e,s,o,a)=>{const i=(n-2*a)/s.width,l=(e-2*a)/s.height;return d0(Math.min(i,l))},m0=()=>{const n=E(a=>a.canvasEl),e=E(a=>a.pageBoxes),s=E(a=>a.zoom),o=E(a=>a.setCurrentPage);y.useEffect(()=>{if(!n)return;let a=0;const i=()=>{a=0,o(u0(e,s,n.scrollTop,n.clientHeight,En))},l=()=>{a||(a=requestAnimationFrame(i))};return i(),n.addEventListener("scroll",l,{passive:!0}),()=>{n.removeEventListener("scroll",l),a&&cancelAnimationFrame(a)}},[n,e,s,o])},pn={root:n=>({position:"absolute",bottom:0,left:0,right:`${qs+(n?Wo:0)}px`,height:`${vo}px`,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:1,px:2,backgroundColor:"common.white",borderTop:"1px solid",borderColor:"divider",transition:e=>e.transitions.create("right",{duration:e.transitions.duration.shorter})}),zoomGroup:{display:"flex",alignItems:"center",gap:.5},slider:{width:110,mx:1},zoomReadout:{width:44,textAlign:"center",cursor:"pointer",userSelect:"none"},divider:{width:"1px",alignSelf:"stretch",my:1.5,backgroundColor:"divider"},pageGroup:{display:"flex",alignItems:"center",gap:.5},pageLabel:{whiteSpace:"nowrap",userSelect:"none"}},$r=.1,g0=({drawerOpen:n})=>{const e=E(g=>g.zoom),s=E(g=>g.setZoom),o=E(g=>g.zoomBy),a=E(g=>g.pageBoxes),i=E(g=>g.currentPage),l=E(g=>g.canvasEl),r=E(g=>g.tree.page),d=E(g=>g.showPanel);m0();const c=a.length||1,u=()=>{l&&s(h0(l.clientWidth,l.clientHeight,r,"page",En))},p=g=>{l==null||l.scrollTo({top:p0(a,e,g,En),behavior:"smooth"})},h=()=>{d("page")};return t.jsxs(N,{sx:pn.root(n),"data-testid":"doc-builder-footer-bar",children:[t.jsxs(N,{sx:pn.zoomGroup,children:[t.jsx(ye,{size:"small","aria-label":"Zoom out",onClick:()=>o(-$r),disabled:e<=Io,children:t.jsx(fo,{fontSize:"small"})}),t.jsx(go,{size:"small",color:"secondary",sx:pn.slider,"aria-label":"Zoom",min:Io*100,max:So*100,value:Math.round(e*100),onChange:(g,x)=>s(x/100)}),t.jsx(ye,{size:"small","aria-label":"Zoom in",onClick:()=>o($r),disabled:e>=So,children:t.jsx(bo,{fontSize:"small"})}),t.jsx(Q,{title:"Reset to 100%",children:t.jsxs(z,{variant:"body2",sx:pn.zoomReadout,onClick:()=>s(1),"data-testid":"doc-builder-zoom-readout",children:[Math.round(e*100),"%"]})}),t.jsx(Q,{title:"Fit page",children:t.jsx(ye,{size:"small","aria-label":"Fit page",onClick:u,children:t.jsx(Th,{fontSize:"small"})})})]}),t.jsx(N,{sx:pn.divider}),t.jsxs(N,{sx:pn.pageGroup,children:[t.jsx(ye,{size:"small","aria-label":"Previous page",onClick:()=>
20p(i-2),disabled:i<=1,children:t.jsx(wh,{fontSize:"small"})}),t.jsxs(z,{variant:"body2",sx:pn.pageLabel,"data-testid":"doc-builder-page-indicator",children:["Page ",Math.min(i,c)," / ",c]}),t.jsx(ye,{size:"small","aria-label":"Next page",onClick:()=>p(i),disabled:i>=c,children:t.jsx(kh,{fontSize:"small"})})]}),t.jsx(N,{sx:pn.divider}),t.jsx(Q,{title:"Page setup",children:t.jsx(ye,{size:"small","aria-label":"Page setup",onClick:h,"data-testid":"doc-builder-page-setup-button",children:t.jsx(Ph,{fontSize:"small"})})})]})},x0=({image:n,isDefault:e,control:s,onDelete:o,onSetDefault:a})=>{const{attributes:i,listeners:l,setNodeRef:r,transform:d,transition:c,isDragging:u}=Oo({id:n.id});return t.jsxs(he,{ref:r,direction:"row",alignItems:"center",gap:2,sx:{p:1,borderBottom:1,borderColor:"divider",opacity:u?.4:1,transform:Fa.Transform.toString(d),transition:c,bgcolor:"background.paper"},children:[t.jsx(N,{...i,...l,sx:{cursor:"grab",color:"text.disabled",display:"flex",alignItems:"center"},children:t.jsx(Dh,{})}),t.jsx(N,{component:"img",src:n.url||"/images/no_image.png",alt:n.title,sx:{width:80,height:80,objectFit:"contain",borderRadius:1,flexShrink:0}}),t.jsx(al,{name:`images.${n.fieldIndex}.title`,control:s,render:({field:p})=>t.jsx(Le,{...p,size:"small",label:"Title",sx:{flex:1}})},`images.${n.fieldIndex}.title`),t.jsx(al,{name:`images.${n.fieldIndex}.value`,control:s,render:({field:p})=>t.jsx(Le,{...p,size:"small",label:"Value",sx:{flex:1}})},`images.${n.fieldIndex}.value`),t.jsxs(he,{alignItems:"center",sx:{minWidth:64},children:[t.jsx(z,{variant:"caption",color:"text.secondary",noWrap:!0,children:"Default"}),t.jsx(xt,{checked:e,onChange:()=>a(n.id)})]}),t.jsx(ye,{onClick:()=>o(n.id),color:"error",children:t.jsx(xa,{})})]})},Au="image/png, image/jpeg, image/tiff",Fu="JPG, PNG, TIFF",f0=100*1024*1024,b0=new Set(Au.split(",").map(n=>n.trim())),y0=n=>Array.from(n).filter(e=>b0.has(e.type)),j0=({control:n,setValue:e})=>{const{fields:s,append:o,remove:a,move:i}=Xr({control:n,name:"images",keyName:"fieldId"}),l=il({control:n,name:"defaultImageId"})??"",r=il({control:n,name:"images"})??[],d=s.reduce((x,m,f)=>{const j=r.find(S=>S.id===m.id);return j&&!j.isDeleted&&x.push({...j,fieldIndex:f}),x},[]),c=async x=>{if(x.some(f=>f.size>f0)){wt({title:"Image file too large!",msg:`Accepted file types: ${Fu}, with max file size of 100MB.`});return}(await Promise.all(x.map(f=>new Promise(j=>{const S=new FileReader;S.onload=w=>{var v;const C=(v=w.target)==null?void 0:v.result;j({id:ss(),title:f.name.replace(/\.[^/.]+$/,""),value:"",url:C,dataURL:C,file:f,isNew:!0,isDeleted:!1})},S.readAsDataURL(f)})))).forEach(f=>o(f))};return{visibleImages:d,defaultImageId:l,handleUpload:async x=>{!x.target.files||x.target.files.length===0||(await c(Array.from(x.target.files)),x.target.value="")},handleFileDrop:c,handleDelete:x=>{const m=s.findIndex(j=>j.id===x);if(m===-1)return;const f=r[m];f&&(f.isNew?a(m):e(`images.${m}.isDeleted`,!0),l===x&&e("defaultImageId",""))},handleSetDefault:x=>{e("defaultImageId",l===x?"":x)},handleDragEnd:(x,m)=>{const f=s.findIndex(S=>S.id===x),j=s.findIndex(S=>S.id===m);f===-1||j===-1||f===j||i(f,j)}}},C0=({manageImagesData:n,onClose:e})=>{const{control:s,setValue:o,handleSubmit:a,formState:{isSubmitting:i}}=Yr({defaultValues:{images:n.images.map(M=>({...M,isNew:!1,isDeleted:!1})),defaultImageId:n.defaultImageId}}),{visibleImages:l,defaultImageId:r,handleUpload:d,handleFileDrop:c,handleDelete:u,handleSetDefault:p,handleDragEnd:h}=j0({control:s,setValue:o}),[g,x]=y.useState(!1),m=y.useRef(0),f=Qn(In(es)),j=()=>{m.current=0,x(!1)},S=M=>{M.preventDefault(),M.stopPropagation(),m.current+=1,m.current===1&&x(!0)},w=M=>{M.preventDefault(),M.stopPropagation()},C=M=>{M.preventDefault(),M.stopPropagation(),m.current-=1,m.current===0&&x(!1)},v=async M=>{M.preventDefault(),M.stopPropagation(),j();const R=y0(M.dataTransfer.files);R.length>0&&await c(R)},I=async M=>{try{n.onSave({images:M.images.map(({id:R,title:P,value:k,isDeleted:T,dataURL:B,file:L})=>({id:R,title:P,value:k,isDeleted:T,dataURL:B,file:L})),defaultImageId:M.defaultImageId}),e()}catch(R){wt({title:"Error saving images",error:R,showVerbose:!0})}},D=()=>{e()},F=M=>{const{active:R,over:P}=M;P&&R.id!==P.id&&h(String(R.id),String(P.id))};return t.jsx($s,{open:!0,onClose:D,title:"Manage Images",children:t.jsx(N,{component:"form",onSubmit:a(I),children:t.jsxs(he,{gap:2,children:[t.jsxs(he,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[t.jsx(z,{variant:"body2",color:"text.secondary",children:"Drag and Drop Images or use the Upload Images button to add more images."}),t.jsxs(we,{variant:"outlined",size:"small",startIcon:t.jsx(Oh,{}),component:"label",children:["Upload Images",t.jsx(N,{component:"input",type:"file",accept:Au,multiple:!0,onChange:d,sx:{clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,overflow:"hidden",position:"absolute",bottom:0,left:0,whiteSpace:"nowrap",width:1}})]})]}),t.jsxs(N,{onDragEnter:S,onDragOver:w,onDragLeave:C,onDrop:v,sx:{position:"relative",border:2,borderColor:g?"success.main":"divider",borderStyle:"dashed",borderRadius:1,backgroundColor:g?"rgba(76, 175, 80, 0.08)":"transparent",transition:"border-color 0.2s ease, background-color 0.2s ease"},children:[g&&l.length>0&&t.jsxs(he,{alignItems:"center",justifyContent:"center",gap:1,sx:{position:"absolute",inset:0,zIndex:10,backgroundColor:"rgba(255, 255, 255, 0.7)",backdropFilter:"blur(3px)",pointerEvents:"none"},children:[t.jsx(ga,{sx:{fontSize:48,color:"success.main"}}),t.jsx(z,{variant:"body2",fontWeight:500,color:"text.primary",sx:{textShadow:"0 0 4px rgba(255, 255, 255, 0.8)"},children:"Drop images here"})]}),t.jsx(N,{sx:{maxHeight:420,overflowY:"auto"},children:l.length===0?t.jsxs(he,{alignItems:"center",justifyContent:"center",gap:1,sx:{height:120},children:[t.jsx(ga,{sx:{fontSize:36,color:g?"success.main":"text.disabled",transition:"color 0.2s ease"}}),t.jsx(z,{variant:"body2",color:"text.secondary",children:g?"Drop images here":"Drag & drop images here"})]}):t.jsx(ts,{sensors:f,collisionDetection:Sn,onDragEnd:F,children:t.jsx(_s,{items:l.map(M=>M.id),strategy:No,children:l.map(M=>t.jsx(x0,{image:M,isDefault:r===M.id,control:s,onDelete:u,onSetDefault:p},M.id))})})})]}),t.jsxs(z,{variant:"caption",color:"text.secondary",textAlign:"center",children:["Accepted: ",Fu,". Max 100 MB."]}),t.jsxs(he,{direction:"row",justifyContent:"flex-end",gap:1,children:[t.jsx(we,{size:"small",variant:"outlined",color:"secondary",onClick:D,children:"Cancel"}),t.jsx(we,{size:"small",variant:"contained",type:"submit",disabled:i,children:"Done"})]})]})})})},Ru=()=>{const n=ft(),{showManageImages:e,currentWorkingId:s,editCellItem:o,template:a}=ze(l=>{const{templatesEdit:r}=l,d=r==null?void 0:r.currentWorkingId;return{showManageImages:!!(r!=null&&r.showManageImages),currentWorkingId:d,editCellItem:r==null?void 0:r.editCellItem,template:d?r==null?void 0:r[d]:void 0}}),i=y.useMemo(()=>
20{if(!e||!s||!o||!a)return null;try{const l=new $(a.toJSON()),r=l.getObjectWithId(o.objectId)||{},d=r.imagesSource==="default";return{images:((d?l.images:r.images)||[]).map(p=>{const{file:h}=p,g=h?typeof h.url=="function"?h.url():h.url||h._url||"":"";return{id:p.id,title:p.title||"",value:p.value||"",url:g}}),defaultImageId:r.defaultImageId||"",onSave:({images:p,defaultImageId:h})=>{const g=d?l:r,x=new Map((d?l.images||[]:r.images||[]).map(m=>[m.id,m]));g.images=p.filter(m=>!m.isDeleted).map(m=>{if(m.file&&m.dataURL)return new gt({id:m.id,title:m.title,value:m.value,file:{url:m.dataURL,isNew:!0,file:m.file}},g);const f=x.get(m.id);return f?(f.title=m.title,f.value=m.value,f):new gt({id:m.id,title:m.title,value:m.value},g)}),r.defaultImageId=h,n(ee(l)),n(jo(!1))}}}catch(l){return wt({title:"Error opening manage images",error:l}),null}},[e,s]);return i?t.jsx(C0,{manageImagesData:i,onClose:()=>n(jo(!1))}):null},I0=()=>{const n=ze(o=>{var a;return(a=o.templatesEdit)==null?void 0:a.currentWorkingId}),e=ze(o=>{var a;return n?(a=o.templatesEdit)==null?void 0:a[n]:void 0}),s=E(o=>o.setTree);y.useEffect(()=>{s(zi(e))},[e,s])},S0="TEMPLATES_SET_EDIT_CELL_ITEM",v0={},T0=()=>{const n=ft(),e=E(i=>i.selectedNodeId),s=E(i=>i.selectedNodeType),o=ze(i=>{var l;return(l=i.templatesEdit)==null?void 0:l.currentWorkingId}),a=ze(i=>{var l;return o?(l=i.templatesEdit)==null?void 0:l[o]:void 0});y.useEffect(()=>{var d;const i=a,r=(s==="cell"||s==="row")&&e?(d=i==null?void 0:i.getObjectWithId)==null?void 0:d.call(i,e):void 0;n({type:S0,editCellItem:r??v0})},[e,s,a,n])},w0=()=>{I0(),T0();const n=E(u=>u.drawerOpen),e=E(u=>u.activePanel),s=E(u=>u.openDrawer),o=E(u=>u.closeDrawer),a=E(u=>u.toggleDrawer),i=E(u=>u.setActivePanel),l=E(u=>u.selectedNodeType),r=E(u=>{var p;return u.selectedNodeId?((p=u.tree.cellsById[u.selectedNodeId])==null?void 0:p.cellType)??null:null}),d=E(u=>{var p;return u.selectedNodeId?(p=u.tree.sectionsById[u.selectedNodeId])==null?void 0:p.groupType:void 0}),c=e==="element"&&l?ju(l,r,d):void 0;return{drawerOpen:n,activePanel:e,drawerSubtitle:c,openDrawer:s,closeDrawer:o,toggleDrawer:a,setActivePanel:i}},_u=n=>typeof n=="string"&&n.startsWith("nav:");let Ts=null;const k0=n=>{var r,d;const e=(r=n.active.data.current)==null?void 0:r.level,s=n.droppableContainers.filter(c=>{var u;return _u(c.id)&&c.node.current&&((u=c.data.current)==null?void 0:u.level)===e}),o=n.pointerCoordinates,a=o&&Ts!==null?s.find(c=>c.id===Ts):void 0;if(a&&o){const c=a.node.current.getBoundingClientRect();if(c.height>0&&o.x>=c.left&&o.x<=c.right&&o.y>=c.top&&o.y<=c.bottom)return[{id:a.id,data:{droppableContainer:a,value:0}}]}const i=new Map;s.forEach(c=>{i.set(c.id,c.node.current.getBoundingClientRect())});const l=Sn({...n,droppableContainers:s,droppableRects:i});return Ts=((d=l[0])==null?void 0:d.id)??null,l},P0=n=>{var p,h,g,x;const e=((p=n.active.data.current)==null?void 0:p.move)===!0,s=ll(n),o=s.some(m=>m.id===Ia),a=s.some(m=>m.id===Sa),i=o?"canvas":a&&e?"navigator":null;if(!i)return Ts=null,[];if(i==="navigator")return k0(n);Ts=null;const l=n.active.data.current??{},{tree:r}=E.getState(),d=n.droppableContainers.filter(m=>{const{id:f}=m;if(f===Ia||f===Sa||_u(f)||tr(f))return!1;const j=m.data.current;return!!j&&Vd(l,j,r)}),c=n.droppableContainers.filter(m=>tr(m.id)),u=((h=ll({...n,droppableContainers:c})[0])==null?void 0:h.id)??null;if(u!==null){const m=(x=(g=c.find(S=>S.id===u))==null?void 0:g.data.current)==null?void 0:x.sectionId,f=d.filter(S=>qS(r,S.data.current)===m);if(f.length>0)return Sn({...n,droppableContainers:f});const j=c.find(S=>S.id===u);return j?[{id:j.id,data:{droppableContainer:j,value:0}}]:[]}return d.length>0?Sn({...n,droppableContainers:d}):[]},D0=()=>{const n=Ji(),{moveNode:e,moveNodes:s,moveCapture:o}=cn(),[a,i]=y.useState(null),[l,r]=y.useState(null),[d,c]=y.useState(1),[u,p]=y.useState(!1),[h,g]=y.useState(!1),x=Qn(In(es,{activationConstraint:{distance:4}}),In(Jr)),m=y.useCallback(w=>{p(!0);const C=w.active.data.current,v=C==null?void 0:C.kind;i(v?ln(v):null);const I=(C==null?void 0:C.move)===!0&&String(w.active.id).startsWith("nav-move:");r(I?{nodeId:C.nodeId,nodeType:C.nodeType??C.level}:null);const{selectedNodes:D}=E.getState(),F=C==null?void 0:C.nodeId;c(I&&F&&D.length>1&&D.some(M=>M.id===F)?D.length:1)},[]),f=y.useCallback(()=>{p(!1),i(null),r(null),c(1),g(!1),E.getState().setBlockedDropSection(null)},[]),j=y.useCallback(w=>{var D;const C=w.active.data.current,v=((D=w.over)==null?void 0:D.data.current)??null,I=!!C&&(v==null?void 0:v.level)==="region";g(I),E.getState().setBlockedDropSection(I?v.sectionId:null)},[]),S=y.useCallback(w=>{var D;p(!1),i(null),r(null),c(1),g(!1),E.getState().setBlockedDropSection(null);const C=w.active.data.current,v=(D=w.over)==null?void 0:D.data.current;if(!C||!v||v.level==="region")return;const I=v;if(Vd(C,I,E.getState().tree))if(C.move)if(I.level==="capture")o(C.nodeId,I);else{const F=C.nodeId,{selectedNodes:M}=E.getState();M.length>1&&M.some(R=>R.id===F)?s(M.map(R=>R.id),I):e(F,I)}else n(C.kind,I),qo("doc_editor_add_fields_and_elements_used")},[n,e,s,o]);return{sensors:x,collisionDetection:P0,onDragStart:m,onDragOver:j,onDragEnd:S,onDragCancel:f,activeDefinition:a,activeNavNode:l,activeNavCount:d,isDragging:u,dropBlocked:h}},O0=()=>{const{copySelection:n,cutSelection:e,deleteSelection:s,pasteBelow:o,canPasteBelow:a}=cn(),i=E(d=>d.selectNode),l=E(d=>d.clearSelection),r=y.useRef(()=>{});r.current=d=>{const c=d.target;if((c==null?void 0:c.tagName)==="INPUT"||(c==null?void 0:c.tagName)==="TEXTAREA"||c!=null&&c.isContentEditable||c!=null&&c.closest(".MuiModal-root")||document.querySelector(".MuiModal-root"))return;const{tree:u,selectedNodes:p,selectedNodeId:h}=E.getState(),g=d.metaKey||d.ctrlKey,x=d.key.toLowerCase();if(g&&x==="c"){p.length&&(n(),d.preventDefault());return}if(g&&x==="x"){p.length&&(e(),d.preventDefault());return}if(g&&x==="v"){h&&a(h)&&(o(h),d.preventDefault());return}if(d.key==="Delete"||d.key==="Backspace"){p.length&&(s(),d.preventDefault());return}if(d.key==="Escape"){p.length&&(l(),d.preventDefault());return}if(d.key==="ArrowDown"||d.key==="ArrowUp"){const m=Zk(Mu(u),()=>!0);if(!m.length)return;const f=m.findIndex(w=>w.id===h),j=d.key==="ArrowDown"?Math.min(m.length-1,f<0?0:f+1):Math.max(0,f<0?m.length-1:f-1),S=m[j];i(S.id,S.type),d.preventDefault()}},y.useEffect(()=>{const d=c=>r.current(c);return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[])},N0=()=>{const n=ft(),e=E(a=>a.updateCell),s=ze(a=>{var i;return(i=a.templatesEdit)==null?void 0:i.currentWorkingId}),o=ze(a=>{var i;return s?(i=a.templatesEdit)==null?void 0:i[s]:void 0});return y.useCallback((a,i,l)=>{var u;const r=o,d=(u=r==null?void 0:r.getObjectWithId)==null?void 0:u.call(r,a);if(!r||!d)return;const c={[i]:l};e(a,c),Object.assign(d,c),n(ee(r))},[e,o,n])},M0={root:{position:"relative",display:"flex",flexDirection:"row",flex:1,minHeight:0,width:"100%",height:"100%",overflow:"hidden",backgroundColor:"grey.100"}},L0=()=>{const{drawerOpen:n,activePanel:e,drawerSubtitle:s,closeDrawer:o}=w0(),{sensors:a,collisionDetection:i,onDragStart:l,onDragOver:r,onDragEnd:d,onDragCancel:c,activeDefinition:u,activeNavNode:p,activeNavCount:h,isDragging:g,dropBlocked:x}=D0(),m=N0(),{changeCellType:f}=cn();return O0(),y.useEffect(()=>()=>co(),[]),t.jsxs(ts,{sensors:a,collisionDetection:i,onDragStart:l,onDragOver:r,onDragEnd:d,onDragCancel:c,children:[g&&t.jsx(Nh,{styles:{"*":{cursor:`${x?"not-allowed":"grabbing"} !important`}}}),t.jsx(Ud.Provider,{value:m,children:t.jsxs(Gd.Provider,{value:f,children:[t.jsxs(N,{sx:M0.root,"data-testid":"doc-builder-root",children:[t.jsx(Pk,{drawerOpen:n}),t.jsx(g0,{drawerOpen:n}
20),t.jsx(l0,{open:n,onClose:o,activePanel:e,subtitle:s}),t.jsx(c0,{})]}),t.jsx(Ru,{}),t.jsx(rv,{})]})}),t.jsx(Kr,{zIndex:ly,children:u?t.jsx(Xi,{definition:u}):p?t.jsx(Lu,{nodeId:p.nodeId,nodeType:p.nodeType,variant:"chip",count:h}):null})]})},E0=({legacy:n})=>{const s=zt()[Cd]??!1;return ze(i=>i.templatesEdit.builderOverride)??s?t.jsx(L0,{}):t.jsx(y.Fragment,{children:n})},A0=n=>{switch(n.groupType){case"header":return t.jsx(pf,{section:n});case"body":return t.jsx(kf,{section:n});case"signature":return t.jsx(Gc,{data:n.data,parentPath:n.getPath()});default:return t.jsx("div",{children:n.groupType})}},F0=({pageSize:n="612,792",wMargin:e=25,hMargin:s=35},o=1)=>{const[a,i]=n.split(",");return{backgroundColor:"white",minHeight:`${i}px`,padding:`${s}px ${e}px`,position:"relative",minWidth:`${a}px`,maxWidth:`${a}px`}};J.createRef();const Cs=new Pf,R0=()=>{setTimeout(()=>{[...document.getElementsByClassName("bp3-menu")].forEach(e=>{const{parentNode:s}=e;if(s){var o=s.parentNode;if(o){var a=o.className;if(a.indexOf("bp3-submenu")===-1){var i=window.innerHeight-50+"px";e.style.maxHeight=i}}}})},500)};class Qi extends J.Component{constructor(s){super(s);W(this,"initializeFromRouteParams",()=>{const{id:s,type:o}=this.props.match.params;if(this.props.setFeatureFlags(this.props.featureFlags),s==="new"){const i=`${o}_new`,l=new $;l.type=o,l.objectId=i,l.includedOffices=[...this.props.offices],l.includedStates=[...this.props.states],this.props.setInitialState(l),this.props.setCurrentWorkingTemplate(i);return}const{template:a={}}=this.props;a.objectId!==s&&(async()=>{const l=new se.Object("ContractObject");l.id=s,await l.fetch();const r=l.get("linkedIds")||[],d=l.get("includedOffices")||[],c=l.get("includedStates")||[],u=l.get("type")||void 0;l.set("includedOffices",d.map(g=>g instanceof se.Object?g.toPointer():g));const p=d.map(g=>g.id);this.props.startSetIncludedOfficesFilter(u,p),this.props.startSetIncludedStatesFilter(u,c);const h=new $(l.toJSON());r.length&&(h.linkedTypes=await h.fetchTemplateTypes({linkedIds:r})),this.props.setInitialState(h)})(),(!this.props.currentWorkingId||this.props.currentWorkingId!==s)&&this.props.setCurrentWorkingTemplate(s)});W(this,"onPDFFileChanged",async s=>{try{const{template:o,setInitialState:a}=this.props,i=new $(o.toJSON()),l=await as(s[0],"document","template_pdf");i.pdf=l,a(i)}catch(o){Be.show({message:o.message,timeout:5e3})}});W(this,"updateOnDragEndCallback",()=>{const{template:s,setInitialState:o,setEditCellItem:a}=this.props;s&&bt(`${s.objectId}-root`,i=>{const{source:l,destination:r,draggableId:d}=i;let c;switch(d){case"new-header-root":c=new Bt;break;case"new-body-root":c=new Gn;break;case"new-signature-root":c=new nn;break}if(c){s.contractData.splice(r.index,0,c);const h=new $(s.toJSON());o(h),a(h.contractData[r.index].data[0]);return}const u=s.contractData[l.index];s.contractData.splice(l.index,1),s.contractData.splice(r.index,0,u);const p=new $(s.toJSON());o(p)})});W(this,"handleRef",s=>{s&&Cs.setMainRef(s,this.props.onTemplateScroll)});this.state={isOfficesLoaded:!1,isIncludedStatesLoaded:!1,showDocSnapshotModal:!1}}componentWillMount(){this.initializeFromRouteParams()}componentDidMount(){const{setToolbar:s,match:o={},template:a,showAlertModal:i,setShowAlertModal:l}=this.props,{params:r}=o;a||this.props.showLoader(),i&&l&&l(i),this.updateOnDragEndCallback()}componentDidUpdate(s){var p,h,g,x,m,f,j;const o=((p=s.match)==null?void 0:p.params)||{},a=((h=this.props.match)==null?void 0:h.params)||{};(o.id!==a.id||o.type!==a.type)&&this.initializeFromRouteParams();const{template:i,match:l={},TADTrigger:r,setInitialState:d}=this.props,{params:c}=l,u=c.id;if(r!==s.TADTrigger&&u&&u!==""){const S=(g=se.User.current())==null?void 0:g.getSessionToken();if(S){const w=new se.Object("ContractObject");w.id=u,w.fetch({sessionToken:S}).then(C=>{if(!C)throw new Error("Template not found");const v=C.toJSON();d(new $(v))}).catch(C=>{wt({title:"Template not Found",showVerbose:!0,error:C})})}else wt({title:"Session Token Missing",showVerbose:!0,error:new Error("Session token is required to fetch the template.")})}if(((x=this.props.offices)==null?void 0:x.length)>0&&!this.state.isOfficesLoaded&&(this.setState({isOfficesLoaded:!0}),((m=i==null?void 0:i.includedOffices)==null?void 0:m.length)===0&&c.id==="new")){i.includedOffices=[...this.props.offices];const S=[...this.props.offices].map(w=>w.id);this.props.startSetIncludedOfficesFilter(c.type,S)}this.props.planId==="lite"&&((f=i==null?void 0:i.includedStates)==null?void 0:f.length)===0&&((j=this.props.states)==null?void 0:j.length)>0&&!this.state.isIncludedStatesLoaded&&c.id==="new"&&(this.setState({isIncludedStatesLoaded:!0}),i.includedStates=[...this.props.states],this.props.startSetIncludedStatesFilter(c.type,[...this.props.states])),i&&!s.template&&this.props.hideLoader(),this.updateOnDragEndCallback()}render(){const{template:s,editCellItem:o,watermark:a={},watermarkAlpha:i=.05,watermarkWidthPercent:l,setShowLinkItems:r,setInitialState:d,linkMeasureSheetItemsShow:c,linkMeasuresheetItemsKey:u,linkMeasureSheetItemsSingleSelect:p,linkMeasureSheetItemsTitle:h,linkMeasureSheetItemsShowCustomProduct:g,draggableType:x,viewSelection:m,match:f={},scale:j,show:S}=this.props,{showDocSnapshotModal:w}=this.state;if(!s)return t.jsx(J.Fragment,{});const{params:C}=f,v=a instanceof se.File?a.url():a.url,I=new $(s.toJSON()),{contractData:D=[],useWatermark:F}=I,M=I.getObjectWithId(o?o.objectId:void 0)||{};M.editKey=o?o.editKey:void 0;const R=F0(I,j);return t.jsxs("div",{onMouseDown:P=>{const{className:k}=P.target;
20k&&typeof k=="string"&&(k.indexOf("bp3-menu-item")>-1||k.indexOf("bp3-text-overflow-ellipsis")>-1)&&P.preventDefault()},onClick:P=>{R0()},className:"templates-pdf__background",children:[t.jsx(OS,{open:w,onClose:()=>this.setState({showDocSnapshotModal:!1}),docId:C.id,docType:C.type}),t.jsx("div",{className:"doc-toolbar-container",children:t.jsxs("div",{style:{position:"absolute",width:"100%",zIndex:3},children:[t.jsx(_y,{history:this.props.history,urlParams:C,showSnapshotModal:()=>this.setState({showDocSnapshotModal:!0}),setRestoreData:this.props.setRestoreData,showAlertModal:this.props.showAlertModal,showLoader:this.props.showLoader,hideLoader:this.props.hideLoader,onDocumentSave:this.props.onDocumentSave,customDocTypes:this.props.customDocTypes,planId:this.props.planId,maxTemplateCount:this.props.maxTemplateCount}),t.jsx(vS,{object:M,disabled:M.toolbarKey!=="sectionTitle"})]})}),t.jsx(E0,{legacy:t.jsxs("div",{className:"doc-canvas-container",children:[t.jsx("div",{className:"templates-pdf__tree-container",children:t.jsx($f,{showAlertModal:this.props.showAlertModal})}),t.jsx("div",{className:"templates-pdf__cell-tool-drawer",children:t.jsx(Vf,{})}),t.jsxs("div",{ref:this.handleRef,className:`templates-pdf__canvas templates-pdf__canvas-doc2${m===2?" both-view":""} ${M.toolbarKey==="sectionTitle"?"toolbar_active":""}`,children:[(m===0||m===2)&&t.jsx(ja,{}),(m===1||m===2)&&t.jsxs("div",{id:"page-container",className:"contract-editor",style:R,children:[I.pageId==="pdfPage"&&t.jsx(NS,{newContractObject:I,template:s,setInitialState:d}),I.pageId!=="pdfPage"&&t.jsxs("div",{id:"page-content",children:[a&&F&&t.jsx("div",{className:"templates-pdf__watermark",children:t.jsx("img",{onMouseDown:P=>{P.preventDefault(),P.stopPropagation(),P.returnValue=!1},onTouchStart:P=>{P.preventDefault(),P.stopPropagation(),P.returnValue=!1},className:"watermark-image",alt:"Watermark",src:v,style:{opacity:`${i}`,width:`${l}%`,margin:"auto",objectFit:"cover",padding:R.padding}})}),t.jsx("div",{className:"templates-pdf__page-count",children:"Page 1 of 1"}),t.jsx(We,{droppableId:`${I.objectId}-root`,isDropDisabled:x!=="root",children:(P,k)=>t.jsxs("div",{ref:P.innerRef,...P.droppableProps,style:{...tt(k.isDraggingOver),minHeight:100},children:[D.map((T,B)=>t.jsx(Ke,{draggableId:`${T.getPath().join("-")}-${T.objectId}`,index:B,type:"root",children:L=>t.jsxs("div",{ref:L.innerRef,...L.draggableProps,...L.dragHandleProps,style:{...L.draggableProps.style},children:[A0(T),L.placeholder]})},T.objectId)),P.placeholder]})})]})]})]})]})})]})}}Qi.propTypes={match:b.shape({params:b.shape({type:b.string.isRequired,id:b.string.isRequired}).isRequired}).isRequired,setEditCellItem:b.func.isRequired,setInitialState:b.func.isRequired,setCurrentWorkingTemplate:b.func.isRequired,editCellItem:b.any,linkMeasureSheetItemsShow:b.bool,linkMeasuresheetItemsKey:b.string,linkMeasureSheetItemsSingleSelect:b.bool,linkMeasureSheetItemsTitle:b.string,linkMeasureSheetItemsShowCustomProduct:b.bool,viewSelection:b.oneOf([0,1,2]).isRequired,draggableType:b.string,watermark:b.shape({url:b.oneOfType([b.string,b.func])}),watermarkAlpha:b.number,watermarkWidthPercent:b.number,setShowLinkItems:b.func.isRequired,template:b.instanceOf($),startSetIncludedOfficesFilter:b.func.isRequired,startSetIncludedStatesFilter:b.func.isRequired,setFeaturedFlags:b.func.isRequired,TADTrigger:b.number};Qi.defaultProps={editCellItem:void 0,linkMeasureSheetItemsShow:!1,linkMeasuresheetItemsKey:void 0,linkMeasureSheetItemsSingleSelect:!1,linkMeasureSheetItemsTitle:"",linkMeasureSheetItemsShowCustomProduct:!1,draggableType:void 0,watermark:void 0,watermarkAlpha:0,watermarkWidthPercent:0,template:void 0,TADTrigger:0};const _0=({templatesEdit:n,auth:{config:e={},offices:s=[]},config:{states:o=[]}}={},a)=>{const{id:i,type:l}=a.match.params,r=i==="new"?`${l}_${i}`:i,d=n[r],{watermark:c}=d||{},u=c||e.watermark||{},p=c?d.watermarkAlpha:e.watermarkAlpha,h=c?d.watermarkWidthPercent:e.watermarkWidthPercent;return{template:d,watermark:u,watermarkAlpha:p,watermarkWidthPercent:h,scale:n.scale,editCellItem:n.editCellItem,linkMeasureSheetItemsShow:n.linkMeasureSheetItemsShow,linkMeasuresheetItemsKey:n.linkMeasuresheetItemsKey,linkMeasureSheetItemsSingleSelect:n.linkMeasureSheetItemsSingleSelect,linkMeasureSheetItemsTitle:n.linkMeasureSheetItemsTitle,linkMeasureSheetItemsShowCustomProduct:n.linkMeasureSheetItemsShowCustomProduct,draggableType:n.draggableType,viewSelection:n.viewSelection,currentWorkingId:n.currentWorkingId,office
20s:s,states:o}},B0=n=>({onTemplateScroll:e=>n(_g(e)),setInitialState:e=>n(ee(e)),setCurrentWorkingTemplate:e=>n(Bc(e)),setShowLinkItems:(e,s,o)=>n(Ut(e,s,o)),setEditCellItem:e=>n(Ne(e)),pushToDataLayer:e=>n(Ot(e)),startSetIncludedOfficesFilter:(e,s)=>n(Lb(e,s)),startSetIncludedStatesFilter:(e,s)=>n(Ab(e,s)),setFeatureFlags:e=>n(Eg(e)),setShowAlertModal:e=>n(zg(e))}),$0=Z(_0,B0)(Qi),z0=async({officeLevelCountry:n=!1}={})=>{const e=se.User.current();if(!e)throw new Error("User not found");const s=e.get("company"),o=e.get("selectedOffice");if(!s||!o)throw new Error("User must have a company and selected office");const[a,i]=await Promise.all([s.fetch(),o.fetch()]),[l,r]=[a.get("plan"),i.get("config")];if(!r)throw new Error("Office config not found");const[d,c,{allOffices:u}]=await Promise.all([r.fetch(),se.Config.get(),Lg()]),p=m=>c.get(m)||[],h=md(u,e.get("allowedOffices")),g=n?xd(gd(h),p):p(a.get("statesKey")).map(m=>({value:m,label:m}));return{states:g.map(m=>m.value),stateOptions:g,company:a,companyLogo:d.get("companyLogo"),plan:l,allOffices:u,user:e}},W0=n=>{const{setLinkedData:e=()=>{},docId:s="",officeCountry:o,officeLevelCountry:a=!1}=n,i=ft(),{templatesEdit:l={}}=ze(j=>{const{templatesEdit:S}=j;return{templatesEdit:S}}),{linkMeasureSheetItemsShow:r,linkMeasuresheetItemsKey:d,linkMeasureSheetItemsSingleSelect:c,linkMeasureSheetItemsTitle:u,linkMeasureSheetItemsShowCustomProduct:p,editCellItem:h,currentWorkingId:g}=l,x=(j,S)=>{wt({title:S,error:j})},{isFetching:m}=He({queryKey:["linkedData",{linkMeasureSheetItemsShow:r,currentWorkingId:g}],queryFn:async()=>{var M;const j=l[g];if(!j)return null;const{includedOffices:S=[]}=j,w=new $(j.toJSON()),C=w.getObjectWithId(h?h.objectId:void 0)||{},v=Array.isArray(C[d])?C[d]:C[d]?[C[d]]:[],I=(M=l.featureFlags)==null?void 0:M.enableShareablePriceGuide,D=await Zy(v,{enableShareablePriceGuide:I});return{includedOffices:S.map(R=>(R==null?void 0:R.id)||(R==null?void 0:R.objectId)),isOpen:r,title:u,singleSelect:c,selectedIds:D||[],showCustomProduct:p,onCancel:()=>{i(Ut(!1))},onDone:R=>{C[d]=R,i(ee(w)),i(Ut(!1))}}},onSuccess:j=>{j&&e(j)},onError:j=>x(j,"Error setting up linked data"),retry:!1,enabled:r&&!!g,refetchOnWindowFocus:!1}),{isFetching:f}=He({queryKey:["authSettings",{docId:s,officeCountry:o,officeLevelCountry:a}],queryFn:()=>z0({officeLevelCountry:a}),onSuccess:j=>{const{states:S,stateOptions:w,company:C,companyLogo:v,plan:I,allOffices:D,user:F}=j;i(Mg(C)),i(Co.setPlanConfig(I)),i({type:"SET_AUTH_SLICE",offices:[...D],config:{companyLogo:v},user:F,officeCountry:o,officeLevelCountry:a}),i({type:"FETCH_STATES",states:S,stateOptions:w})},onError:j=>x(j,"Error fetching auth settings"),retry:!1,enabled:!!se.User.current(),refetchOnWindowFocus:!1,staleTime:0,cacheTime:0});return{fetchingInitialData:f,fetchingLinkedData:m}},H0=n=>{const{docId:e,docType:s,setLinkedData:o,setRestoreData:a,showLoader:i,hideLoader:l,showAlertModal:r,onDocumentSave:d=()=>{},history:c,customDocTypes:u,planId:p,maxTemplateCount:h,featureFlags:g,officeCountry:x,TADTrigger:m}=n,{fetchingInitialData:f,fetchingLinkedData:j}=W0({setLinkedData:o,docId:e,officeCountry:x,officeLevelCountry:!!(g!=null&&g.officeLevelCountry)});return t.jsxs(N,{sx:{position:"relative",height:"100%"},children:[(f||j)&&t.jsx(Tn,{sx:{zIndex:7,position:"absolute",backgroundColor:"rgba(0, 0, 0, 0.2)"},open:f||j,children:t.jsx(vt,{color:"primary",size:50})}),t.jsx($0,{history:c,showAlertModal:r,setRestoreData:a,showLoader:i,hideLoader:l,onDocumentSave:d,customDocTypes:u,match:{params:{id:e,type:s}},planId:p,maxTemplateCount:h,featureFlags:g,TADTrigger:m}),t.jsx(Ru,{})]})},q0=new Lh,V0=n=>t.jsx(Mh,{client:q0,children:t.jsxs(Wg,{children:[t.jsx(Yh,{}),t.jsx(Xh,{}),t.jsx(Zh,{}),t.jsx(Qh,{}),t.jsx(H0,{...n}),t.jsx(Be.ToasterComponent,{})]})}),el={LinkedItemTable:{my:2,border:"1px solid",borderColor:"divider",borderTopLeftRadius:8,borderTopRightRadius:8,overflow:"hidden",position:"relative"},LinkedItemTableHeader:{backgroundColor:"gray1.main",alignItems:"center",minHeight:"48px",paddingRight:1},LinkedItemTableBody:{height:"400px",overflowY:"scroll",".LinkedItemTableRow":{cursor:"pointer",borderBottom:"1px solid",borderColor:"divider",alignItems:"center",minHeight:"48px","&:hover":{backgroundColor:"gray2.main"}}},tablePagination:{".MuiTablePagination-toolbar":{minHeight:"30px"},".MuiTablePagination-selectLabel":{marginBottom:"2.5px"},".MuiTablePagination-displayedRows":{marginBottom:"0px"}}},K0=({singleSelect:n,onSelectAll:e,selectedItems:s,totalRows:o,fetching:a})=>{const[i,l]=y.useState(null),r=!!i,d=y.useRef(null),c=el,u=[{id:"replace",label:"Replace selection",action:()=>e(!0)},{id:"add",label:"Add to selection",action:()=>e(!0,!0)}],p=h=>{l(h?h.currentTarget:null)};return t.jsxs(pe,{container:!0,flexWrap:"nowrap",gap:2,sx:c.LinkedItemTableHeader,children:[t.jsx(pe,{width:60,children:!n&&t.jsxs(he,{direction:"row",spacing:0,alignItems:"center",children:[t.jsx(Rt,{disabled:n||a,sx:{mx:1,opacity:a?.5:1},checked:s.length===o&&o>0,indeterminate:s.length!==o&&s.length!==0,onChange:()=>{d.current&&d.current.click()},"data-cy":"selectAllCheckbox"}),t.jsx(ye,{ref:d,size:"small",onClick:p,disabled:n||a,"aria-label":"Select all options","aria-controls":r?"select-all-menu":void 0,"aria-expanded":r?"true":void 0,"aria-haspopup":"menu",sx:{padding:0,ml:-2},children:t.jsx(Eh,{fontSize:"small"})}),t.jsx(kt,{id:"select-all-menu",anchorEl:i,open:r,onClose:()=>p(),anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},children:u.map(h=>t.jsx(ue,{onClick:()=>{h.action(),p()},children:h.label},h.id))})]})}),t.jsx(pe,{width:80,children:t.jsx(z,{variant:"subtitle2",children:"Image"})}),t.jsx(pe,{width:200,children:t.jsx(z,{variant:"subtitle2",children:"Category"})}),t.jsx(pe,{width:200,children:t.jsx(z,{variant:"subtitle2",children:"SubCategory"})}),t.jsx(pe,{width:150,children:t.jsx(z,{variant:"subtitle2",children:"Office"})}),t.jsx(pe,{size:"grow",children:t.jsx(z,{variant:"subtitle2",children:"Name"})})]})},U0=n=>{var h;const{item:e,officeNameById:s,officeCount:o,selectedItems:a,singleSelect:i,setSelectedItems:l}=n,[r,d]=y.useState(((h=e==null?void 0:e.image)==null?void 0:h.url)||"/images/no_image.png"),c=y.useMemo(()=>a.includes(e.id),[e.id,a]),u=y.useMemo(()=>{const g=e.includedOfficeIds||[];if(!g.length)return"No Office";const x=g.map(m=>
20s[m]).filter(Boolean);return x.length?o>1&&x.length>=o?"All Offices":x.length===1?x[0]:`${x.length} Offices`:"—"},[e.includedOfficeIds,s,o]),p=y.useCallback(()=>{if(i){l([e.id]);return}l(g=>c?g.filter(x=>x!==e.id):[...g,e.id])},[c,e.id,l,i]);return t.jsxs(pe,{container:!0,flexWrap:"nowrap",gap:2,className:"LinkedItemTableRow",sx:{backgroundColor:c?"gray1.main":"transparent"},onClick:p,children:[t.jsx(pe,{width:60,children:i?t.jsx(An,{sx:{mx:1.3},checked:c,value:c}):t.jsx(Rt,{sx:{mx:1},checked:c})}),t.jsx(pe,{width:80,children:t.jsx("img",{alt:e.itemName,src:r,onError:()=>d("/images/no_image.png"),style:{objectFit:"contain",width:"50px",height:"50px"}})}),t.jsx(pe,{width:200,children:e.category}),t.jsx(pe,{width:200,children:e.subCategory}),t.jsx(pe,{width:150,children:u}),t.jsxs(pe,{size:"grow",children:[e.itemName,e.sharedFrom&&t.jsx(uc,{size:"small",label:e.sharedFrom.companyName,color:"info",variant:"outlined",sx:{ml:1}})]})]})},G0=n=>{const{items:e,officeNameById:s,officeCount:o,selectedItems:a,setSelectedItems:i,singleSelect:l,onSelectAll:r,totalRows:d,fetching:c}=n,u=el;return t.jsxs(N,{sx:u.LinkedItemTable,children:[t.jsx(K0,{singleSelect:l,onSelectAll:r,selectedItems:a,totalRows:d,fetching:c}),t.jsx(Tn,{sx:{zIndex:7,position:"absolute",backgroundColor:"rgba(0, 0, 0, 0.07)"},open:c,children:t.jsx(vt,{color:"primary"})}),t.jsx(N,{sx:u.LinkedItemTableBody,children:e.length?e.map(p=>t.jsx(U0,{item:p,officeNameById:s,officeCount:o,selectedItems:a,singleSelect:l,setSelectedItems:i},p.id)):t.jsx(z,{sx:{textAlign:"center",py:4},children:"No items found"})})]})},J0=n=>{var l,r;const{id:e,clientId:s,image:o,companyId:a,...i}=n;return{...i,id:e,accessoriesCount:((l=i==null?void 0:i.accessoryIds)==null?void 0:l.length)||0,clientId:s!=null&&s.startsWith("cid_")?s:e,companyId:a,isDirty:!1,isNew:!1,itemCount:((r=i==null?void 0:i.itemIds)==null?void 0:r.length)||0,hasOrderNumberModified:!1,updatedCategory:void 0,image:o}},zr=async n=>{const e=await yc,s=await xm(n);if(!s)return[];const o=[],a=[];s.forEach(d=>{d.sharedFrom?a.push(d):o.push(d)});const l=(await e.measuresheetitems.find({selector:{isDirty:!0}}).exec()).map(d=>d.id),r=[];if(o.length){const d=[];o.forEach(c=>{const u=J0(c);r.push(u),l.includes(u.id)||d.push(u)}),await e.measuresheetitems.bulkUpsert(d)}return[...r,...a]},Y0=n=>{const s=!!zt()["enable-shareable-price-guide"],[o,a]=y.useState(0),[i,l]=y.useState(10),[r,d]=y.useState([]),[c,u]=y.useState([]),[p,h]=y.useState(!1),[g,x]=y.useState(!1),[m,f]=y.useState([]),[j,S]=y.useState(""),[w,C]=y.useState(""),[v,I]=y.useState([]),[D,F]=y.useState(-1),[M,R]=y.useState(!1),P=te=>{an({title:"Linked Items Error",showVerbose:!0,error:te})},k=y.useMemo(()=>at.debounce(te=>C(te),1e3),[]);y.useEffect(()=>()=>k.cancel(),[k]);const T=y.useCallback((te,ge)=>{if(ge===null)return;R(ge==="shared"),a(0),h(!1),x(!1),k.cancel(),S(""),C(""),f([]),d([]),u([])},[k]),B=y.useCallback(te=>{S(te),(te.trim().length>=3||te==="")&&(a(0),k(te.trim()))},[k]),L=y.useMemo(()=>p?{page:o,limit:i,msItemIds:v}:{page:o,limit:i,categories:r,subCategories:c,includedOffices:m,searchText:w,excludeMsItemIds:g?v:[]},[o,i,r,c,p,g,m,w,v]),{data:H=[],isFetching:G}=He({queryKey:["measureSheetItems",L],queryFn:async()=>await zr(L),onSuccess:te=>{M||(te.length<i?F(o*i+te.length):F(-1))},onError:P,refetchOnWindowFocus:!1,keepPreviousData:!0,enabled:!M}),ne=y.useMemo(()=>({includeShared:!0,officeId:(n==null?void 0:n[0])??""}),[n]),{data:le=[],isFetching:re}=He({queryKey:["sharedMeasureSheetItems",ne],queryFn:async()=>await zr(ne),onError:P,refetchOnWindowFocus:!1,enabled:M&&!!(n!=null&&n.length)}),O=y.useMemo(()=>Array.from(new Set(le.map(ge=>ge.category||""))).sort().map(ge=>({value:ge,label:ge||"(No Category)"})),[le]),K=y.useMemo(()=>{const te=r.length?le.filter(me=>r.includes(me.category||"")):le;return Array.from(new Set(te.map(me=>me.subCategory||""))).sort().map(me=>({value:me,label:me||"(No Subcategory)"}))},[le,r]),U=y.useMemo(()=>{let te=le;if(r.length&&(te=te.filter(ge=>r.includes(ge.category||""))),c.length&&(te=te.filter(ge=>c.includes(ge.subCategory||""))),p&&(te=te.filter(ge=>v.includes(ge.id))),g&&(te=te.filter(ge=>!v.includes(ge.id))),w){const ge=w.toLowerCase();te=te.filter(me=>{var De;return(De=me.itemName)==null?void 0:De.toLowerCase().includes(ge)})}return te},[le,r,c,p,g,w,v]),A=y.useMemo(()=>{const te=o*i;return U.slice(te,te+i)},[U,o,i]);y.useEffect(()=>{M&&F(U.length)},[M,U]),y.useEffect(()=>{g&&o>0&&(M?A.length===0:!G&&H.length===0)&&a(0)},[M,g,o,G,H,A]);const q=M?A:H,Y=y.useMemo(()=>p?{msItemIds:v}:{categories:r,subCategories:c,includedOffices:m,searchText:w},[r,c,m,w,p,v]),ce=Vt({mutationKey:["measureSheetItemSelectAllIds",Y],mutationFn:async te=>{const{checked:ge,add:me}=te;if(ge){const De=M?U.map(Pe=>Pe.id):await fm(Y);if(me){const Pe=Array.from(new Set([...De,...v]));return F(Pe.length),Pe}return F(De.length),De}return[]},onSuccess:te=>{I(te)},onError:P}),be=(te,ge=!1)=>ce.mutateAsync({checked:te,add:ge}),Se=s&&!!(n!=null&&n.length);return{page:o,setPage:a,limit:i,setLimit:l,items:q,categories:r,setCategories:d,subCategories:c,setSubCategories:u,selectedItems:v,setSelectedItems:I,showSelectedItems:p,setShowSelectedItems:h,showUnselectedItems:g,setShowUnselectedItems:x,officeFilter:m,setOfficeFilter:f,searchInput:j,handleSearch:B,onSelectAll:be,totalRows:D,fetching:G||re||ce.isLoading,isSharedView:M,handleViewToggle:T,showSharedToggle:Se,sharedCategoryOptions:O,sharedSubCategoryOptions:K}},X0=n=>{const{linkedData:{isOpen:e,includedOffices:s,singleSelect:o=!1,selectedIds:a,showCustomProduct:i,onDone:l=()=>{}},onClose:r}
20=n,d=el,{items:c,page:u,setPage:p,limit:h,setLimit:g,categories:x,setCategories:m,subCategories:f,setSubCategories:j,selectedItems:S,setSelectedItems:w,showSelectedItems:C,setShowSelectedItems:v,showUnselectedItems:I,setShowUnselectedItems:D,officeFilter:F,setOfficeFilter:M,searchInput:R,handleSearch:P,onSelectAll:k,totalRows:T,fetching:B,isSharedView:L,handleViewToggle:H,showSharedToggle:G,sharedCategoryOptions:ne,sharedSubCategoryOptions:le}=Y0(s),{officeOptions:re,fetchingOfficeOption:O}=Ha({includeNoOffice:!0}),{categoryOptions:K,fetchingCategoryOptions:U}=bm(),{subCategoryOptions:A,fetchingSubCategoryOptions:q,refetchSubCategoriesOptions:Y}=ym(x),ce=y.useMemo(()=>re.reduce((oe,Ie)=>{const Ue=Ie.value.toString();return Ue!=="**no-office**"&&(oe[Ue]=Ie.label),oe},{}),[re]),be=y.useMemo(()=>Object.keys(ce).length,[ce]),Se=L?ne:K,te=L?le:A;y.useMemo(()=>{w(a)},[a,w]);const ge=()=>{if(o){const oe=S[0]||"";l(oe)}else l(S);r()},me=y.useCallback((oe,Ie)=>{u!==0&&p(0);const Ue=Ie.map(({value:cs})=>cs===""?"emptyUrlParam":cs.toString());m(Ue)},[m,p,u]),De=y.useCallback((oe,Ie)=>{u!==0&&p(0);const Ue=Ie.map(({value:cs})=>cs===""?"emptyUrlParam":cs.toString());j(Ue)},[j,p,u]),Pe=y.useCallback((oe,Ie)=>{u!==0&&p(0),M(Ie.map(({value:Ue})=>Ue.toString()))},[M,p,u]),de=y.useMemo(()=>{const oe=!S.length||S.length===1&&S.includes("custom_product");return oe&&(v(!1),D(!1)),oe},[S,v,D]);return t.jsxs($s,{open:e,onClose:r,title:`Linked Items (${S.length})`,modalContainerProps:{sx:{minWidth:1e3,width:1e3}},children:[t.jsxs(he,{direction:"row",useFlexGap:!0,flexWrap:"wrap",gap:2,alignItems:"center",children:[t.jsx(Un,{label:"Select Categories",value:Se.filter(oe=>x.includes(oe.value.toString())),disabled:C,loading:U,options:Se,onChange:me,onClose:()=>Y(),showSelectedCount:!0,disableCloseOnSelect:!0,chipDisabled:!0,showSelectAll:(Se==null?void 0:Se.length)>1,selectAllValues:Se,size:"small",showSelectedCountLimit:3,sx:{m:0,width:215},isOptionEqualToValue:(oe,Ie)=>oe.value===(Ie==null?void 0:Ie.value),"data-testid":"categoryFilter"}),t.jsx(Un,{label:"Select Subcategories",value:te.filter(oe=>f.includes(oe.value.toString())),loading:q,options:te,onChange:De,disabled:C||!x.length,showSelectedCount:!0,disableCloseOnSelect:!0,chipDisabled:!0,showSelectAll:(te==null?void 0:te.length)>1,selectAllValues:te,size:"small",showSelectedCountLimit:3,sx:{m:0,width:215},isOptionEqualToValue:(oe,Ie)=>oe.value===(Ie==null?void 0:Ie.value),"data-testid":"subCategoryFilter"}),t.jsx(Un,{label:"Select Office(s)",value:re.filter(oe=>F.includes(oe.value.toString())),disabled:C||L,loading:O,options:re,onChange:Pe,showSelectedCount:!0,disableCloseOnSelect:!0,chipDisabled:!0,showSelectAll:(re==null?void 0:re.length)>1,selectAllValues:re,size:"small",showSelectedCountLimit:3,sx:{m:0,width:215},isOptionEqualToValue:(oe,Ie)=>oe.value===(Ie==null?void 0:Ie.value),"data-testid":"officeFilter"}),t.jsx(Tc,{label:"Search Items",placeholder:"Search by item name",size:"small",sx:{m:0,width:215},disabled:C,searchedText:R,handleSearch:P,"data-testid":"itemSearch"}),t.jsx(N,{sx:{flexBasis:"100%",height:0,mb:2}}),i&&t.jsx(Ft,{control:t.jsx(Rt,{checked:S.includes("custom_product"),onChange:oe=>{oe.target.checked?w(Ie=>[...Ie,"custom_product"]):w(Ie=>Ie.filter(Ue=>Ue!=="custom_product"))}}),label:"Include custom products"}),t.jsx(Ft,{control:t.jsx(Rt,{disabled:de,sx:{opacity:de?.5:1},checked:C,onChange:oe=>{p(0),v(oe.target.checked),oe.target.checked&&D(!1)},"data-testid":"showSelectedOnly"}),label:"Show selected only"}),t.jsx(Ft,{control:t.jsx(Rt,{disabled:de,sx:{opacity:de?.5:1},checked:I,onChange:oe=>{p(0),D(oe.target.checked),oe.target.checked&&v(!1)},"data-testid":"showUnselectedOnly"}),label:"Show unselected only"})]}),t.jsx(G0,{items:c,officeNameById:ce,officeCount:be,selectedItems:S,singleSelect:o,setSelectedItems:w,onSelectAll:k,totalRows:T,fetching:B}),t.jsx(ns,{component:"div",sx:d.tablePagination,count:T,page:u,onPageChange:(oe,Ie)=>p(Ie),rowsPerPage:h,onRowsPerPageChange:oe=>{p(0),g(parseInt(oe.target.value,10))},rowsPerPageOptions:[10,25,50,100]}),t.jsx(ie,{sx:{my:2}}),t.jsxs(he,{direction:"row",gap:2,justifyContent:"space-between",alignItems:"center",children:[G?t.jsxs(Gt,{value:L?"shared":"yours",exclusive:!0,onChange:H,size:"small",children:[t.jsx(Ve,{value:"yours",children:"Your Items"}),t.jsx(Ve,{value:"shared",children:"Shared Items"})]}):t.jsx("div",{}
20),t.jsxs(he,{direction:"row",gap:2,children:[t.jsx(we,{color:"secondary",variant:"outlined",onClick:()=>{w([]),v(!1),D(!1)},"data-cy":"clearAll",size:"small",children:"Clear All"}),t.jsx(Os,{onClick:ge,size:"small",children:"Done"})]})]})]})},Z0=async n=>{const e=await Km(n);return Gm(e)},Q0=async n=>{try{return await Um(n)}catch(e){return await rn(e),0}},eP=n=>{const{deletedDocs:e,limit:s=10,page:o=1,templateId:a,open:i}=n,[l,r]=y.useState([]),[d,c]=y.useState(0),{templateType:u}=_n(),p=async()=>{if(a||e){const g=await Z0({deletedDocs:e,limit:s,page:o,templateId:a,type:u});r(g)}},h=async()=>{const g=await Q0({deletedDocs:e,limit:0,page:o,templateId:a,type:u});c(g)};return y.useEffect(()=>{h(),p()},[e,a,u]),y.useEffect(()=>{p()},[s,o]),y.useEffect(()=>{i&&(p(),h())},[i]),{snapShots:l,snapShotsCount:d}},tP=n=>{const{selectedDoc:e,open:s,deletedDocs:o,templateId:a,onClose:i=()=>{},onSnapShotSelect:l=()=>{}}=n,[r,d]=y.useState(10),[c,u]=y.useState(1),{snapShots:p=[],snapShotsCount:h=0}=eP({templateId:a,limit:r,page:c,deletedDocs:o,open:s}),{showLoader:g,hideLoader:x}=Ic();return y.useEffect(()=>(p?x():g(),()=>x()),[p]),t.jsxs($s,{modalContainerProps:{sx:{minWidth:1100,maxWidth:"auto"}},onClose:i,open:s,title:o?`Restore Deleted ${e||""} Version`:"Restore From Previous Save",children:[t.jsxs(Mt,{minWidth:"large",children:[t.jsxs(Mt.Header,{children:[t.jsx(Mt.Cell,{size:4,children:"Template"}),t.jsx(Mt.Cell,{size:4,children:"User"}),t.jsx(Mt.Cell,{size:4,children:"Date Archived"}),t.jsx(Mt.Cell,{justifyContent:"center",size:4,children:"Restore Version"})]}),p?p.map(m=>{const{displayName:f,timeStamp:j,user:S,id:w=""}=m;return t.jsxs(Mt.Row,{children:[t.jsx(Mt.Cell,{size:4,children:f}),t.jsx(Mt.Cell,{size:4,children:S}),t.jsx(Mt.Cell,{size:4,children:j}),t.jsx(Mt.Cell,{justifyContent:"center",size:4,children:t.jsx(vn,{variant:"plain",color:"secondary",onClick:()=>{l(w)},icon:["far","download"],"data-cy":"restoreVersion"})})]},w)}):null]}),h>0&&t.jsx(ns,{rowsPerPageOptions:[10,25,50,100],component:"div",sx:jm,count:h,page:c-1,onPageChange:(m,f)=>u(f+1),rowsPerPage:r,onRowsPerPageChange:m=>{d(parseInt(m.target.value,10)),u(1)}})]})},nP=()=>{const{docId:n,templateType:e}=_n(),s=Rs(),{currentOffice:o}=Im(),{countryMap:a}=kc(),{mainMenuOptions:i=[]}=qa(o),{showLoader:l,hideLoader:r}=Ic(),{TADTrigger:d}=Ah(),c=zt(),[u,p]=y.useState(!1),h=Sc(),g=y.useMemo(()=>(p(!u),h==null?void 0:h.planId),[h==null?void 0:h.planId]),x=y.useMemo(()=>(p(!u),h==null?void 0:h.maxTemplateCount),[h==null?void 0:h.maxTemplateCount]),[m,f]=y.useState(void 0),[j,S]=y.useState(),[w,C]=y.useState("");y.useEffect(()=>{Cm().then(P=>{C(P)})},[]);const v=Hr(),I=P=>{P.level==="error"?an({title:P.title,msg:P.msg}):Ns({title:P.title,msg:P.msg})},F={history:v,docId:n,docType:e,companyId:w,setLinkedData:f,showAlertModal:I,setRestoreData:S,showLoader:l,hideLoader:r,onDocumentSave:P=>{P.isNew?s.invalidateQueries({queryKey:["contractObjects"]}):s.setQueriesData(["contractObjects"],(k=[])=>k.map(T=>T.id===P.id?{...T,displayName:P.displayName,previewUrl:P.previewUrl,iconImageUrl:P.iconImageUrl,includedOfficeIds:P.includedOfficeIds}:T))},customDocTypes:i,planId:g,maxTemplateCount:x,TADTrigger:d,officeCountry:o?a.get(o):void 0,featureFlags:{enableDocLinking:c["document-linking"],documentActionButton:c["document-action-button"],enableLinkingGroups:c["enable-linking-groups"],disableDocLinkingRestriction:c["disable-doc-linking-restriction"],showDaysOutSetting:c["document-days-out-date-input"],enableShareablePriceGuide:c["enable-shareable-price-guide"],officeLevelCountry:c["office-level-country"]}},M=V0;return n&&e?t.jsxs(t.Fragment,{children:[t.jsx(M,{...F}),t.jsx(tP,{templateId:n,onSnapShotSelect:async P=>{j&&(await j.restoreDocumentSnapshot({objectId:P,showAlertModal:I,showLoader:l,hideLoader:r}),S(void 0))},onClose:()=>S(void 0),open:!!j}),m&&t.jsx(X0,{linkedData:m,onClose:()=>{m==null||m.onCancel(),f(void 0)}})]}):null},sP=({when:n})=>(y.useEffect(()=>{const e=s=>{n&&(s.preventDefault(),s.returnValue="")};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[n]),null),oP={LinkedFieldTableContainer:{width:"100%",height:"100%",overflow:"hidden",border:"1px solid",borderColor:"divider",borderRadius:"8px"}},aP=new Set(["columnChooser","autoSizeThis","autoSizeAll"]),iP=n=>{const{data:e,deleteLinkedField:s,isTrashIconEnabled:o=!1}=n;return e?e.isFinancial||e.isMeasureSheet?o?t.jsx(ye,{onClick:()=>s(e.id,e.linkedField),size:"small",color:"error",children:t.jsx(xa,{})}):t.jsx(Q,{title:"This field is managed by LeapCRM. Unable to edit or delete.",slotProps:{tooltip:{sx:{maxWidth:175,textAlign:"center"}}},children:t.jsx(Fh,{color:"primary"})}):t.jsx(ye,{onClick:()=>s(e.id,e.linkedField),size:"small",color:"error",children:t.jsx(xa,{})}):null},lP=n=>{const{startFetchLinkedFieldObjects:e,gridRef:s,onCellUpdate:o,deleteLinkedField:a,hasLeapCrmOffice:i,tradeOptionsMap:l,fetchingDestinationData:r}=n,d=oP,c=zt(),u=y.useCallback(({data:C}
20)=>!!(C!=null&&C.isFinancial||C!=null&&C.isMeasureSheet),[]),p=y.useCallback(C=>{var I;const v=((I=C.data)==null?void 0:I.documents)||[];return v.length===0?"0 Documents":`${v.length} Document${v.length>1?"s":""}: ${v.map(({displayName:D})=>D||"Unnamed").join(", ")}`},[]),h=y.useCallback(C=>{const{data:v,colDef:{field:I},newValue:D,rowIndex:F}=C;!I||F==null||o(v.id,I,D)},[o]),g=y.useMemo(()=>[{headerName:"fieldId",field:"id",hide:!0},{headerName:"Linked Field Name",field:"linkedField",suppressMenu:!1,sortable:!0,resizable:!0,filter:"agTextColumnFilter",filterParams:{filterOptions:["contains"],suppressAndOrCondition:!0,debounceMs:200,defaultOption:"contains"},cellClass:"ag-tooltip-cell",tooltipValueGetter:C=>{const{value:v}=C;return!v||v.length<50?null:v},minWidth:250,flex:2,editable:C=>!u(C),cellStyle:C=>({cursor:u(C)?"not-allowed":"text"})},{headerName:"Linked Documents",field:"documents",cellClass:"ag-tooltip-cell",minWidth:200,flex:2,filter:!1,sortable:!1,valueGetter:p,tooltipValueGetter:C=>{const v=p(C);return v==="0 Documents"||v.length<50?null:v},cellStyle:C=>({opacity:(C==null?void 0:C.value)!=="0 Documents"?1:.5})},{headerName:"Type/Trade",field:"tradeType",cellClass:"ag-tooltip-cell",minWidth:150,flex:1,filter:!1,sortable:!1,valueGetter:C=>{var F,M;const{data:{destinationSettings:v,isMeasureSheet:I,isFinancial:D}}=C;if(D)return"Financial";if(I){if(r)return"Loading...";const{subAttributeId:R}=((F=v==null?void 0:v.jobProgressMeasureSheet)==null?void 0:F[0])||{};return((M=l.get(R==null?void 0:R.toString()))==null?void 0:M.tradeName)||"--"}return"Custom"},cellStyle:C=>({opacity:(C==null?void 0:C.value)!=="--"?1:.5}),hide:!i},{headerName:"Attribute/Key",field:"attribute",cellClass:"ag-tooltip-cell",minWidth:150,flex:1,filter:!1,sortable:!1,tooltipValueGetter:C=>{const{value:v}=C;return!v||v.length<20?null:v},valueGetter:C=>{var F,M,R;const{data:{destinationSettings:v,isMeasureSheet:I,isFinancial:D}}=C;if(D){const{key:P}=((F=v==null?void 0:v.jobProgressFinancials)==null?void 0:F[0])||{};return P||"--"}if(I){if(r)return"Loading...";const{subAttributeId:P}=((M=v==null?void 0:v.jobProgressMeasureSheet)==null?void 0:M[0])||{};return((R=l.get(P==null?void 0:P.toString()))==null?void 0:R.attributeName)||"--"}return"--"},cellStyle:C=>({opacity:(C==null?void 0:C.value)!=="--"?1:.5}),hide:!i},{headerName:"Sub-Attribute",field:"subAttribute",cellClass:"ag-tooltip-cell",minWidth:150,flex:1,filter:!1,sortable:!1,tooltipValueGetter:C=>{const{value:v}=C;return!v||v.length<20?null:v},valueGetter:C=>{var F,M;const{data:{destinationSettings:v,isMeasureSheet:I,isFinancial:D}}=C;if(D)return"--";if(I){if(r)return"Loading...";const{subAttributeId:R}=((F=v==null?void 0:v.jobProgressMeasureSheet)==null?void 0:F[0])||{};return((M=l.get(R==null?void 0:R.toString()))==null?void 0:M.subAttributeName)||"--"}return"--"},cellStyle:C=>({opacity:(C==null?void 0:C.value)!=="--"?1:.5}),hide:!i},{headerName:"",field:"actions",pinned:"right",width:60,cellRenderer:y.memo(iP),filter:!1,sortable:!1,cellRendererParams:{deleteLinkedField:a,isTrashIconEnabled:c["trash-icon-LFM"]},cellClass:"ag-cell-icon"}],[u,p,a,i,l,r,c]),x=y.useMemo(()=>({suppressMenu:!0,suppressMovable:!0,suppressColumnsToolPanel:!0,resizable:!1,comparator:(C,v)=>C==null?void 0:C.toLowerCase().localeCompare(v==null?void 0:v.toLowerCase()),pinned:!1,filter:"agTextColumnFilter",cellClass:"ag-custom-cell",cellClassRules:{"ag-error-cell":C=>
20C.data.linkedField_invalid&&C.colDef.field==="linkedField"}}),[]),m=y.useCallback(C=>C.defaultItems.filter(v=>!aP.has(v)),[]),f=y.useCallback(()=>({getRows:v=>{e(v.request).then(I=>{I.success?(v.success({rowData:I.rows,rowCount:I.lastRow}),I.rows.length===0?v.api.showNoRowsOverlay():v.api.hideOverlay()):v.fail()})}}),[e]),j=y.useCallback(C=>{const v=f();C.api.setGridOption("serverSideDatasource",v)},[f]),S=y.useCallback(C=>C.data.id,[]),w={columnDefs:g,defaultColDef:x,rowModelType:"serverSide",pagination:!0,paginationPageSize:25,cacheBlockSize:100,animateRows:!0,getRowId:S,getMainMenuItems:m,suppressScrollOnNewData:!0,onCellEditingStopped:h,columnMenu:"new",onGridReady:j,loadingOverlayComponent:Sm};return t.jsx(N,{sx:d.LinkedFieldTableContainer,children:t.jsx(N,{className:"ag-theme-salesPro",sx:{width:"100%",height:"100%"},children:t.jsx(Rh,{ref:s,...w,paginationPageSizeSelector:[10,25,50,100],getRowClass:C=>{var v;return(v=C.data)!=null&&v.id.startsWith("new_")?"ag-new-row":u(C)?"ag-highlight-row":""}})})})},rP=async n=>{try{const e=new se.Object("LinkedValueObject");return e.id=n,await e.destroy(),e.id}catch(e){throw await rn(e),e}},cP=async n=>{try{return await se.Cloud.run("fetchLinkedFieldsLeapCRMDestOptions",n)}catch(e){throw rn(e),e}},dP=async n=>{try{return await se.Cloud.run("getLinkedValueObjectsCloudFn",n)}catch(e){throw rn(e),e}},uP=async n=>await rP(n),pP=async n=>await cP(n),hP=async n=>await dP(n),mP=async n=>await om(n),gP=()=>{const{setSnackbar:n}=Ws(),e=Rs(),s=y.useRef(null),[o,a]=y.useState(!1),i=y.useRef(new Map),l=y.useRef(new Map),[r,d]=y.useState([]),c=(I,D="Error")=>{an({title:D,showVerbose:!0,error:I})},u=y.useCallback(async I=>{let D;const{startRow:F=0,endRow:M=25,filterModel:R,sortModel:P}=I,k={skip:F,limit:M-F,sortModel:P,filterModel:R};try{const T=await e.fetchQuery({queryKey:["fetchLinkedFieldObjects"],queryFn:async()=>await hP(k)}),B=new Set;if(T!=null&&T.length){const L=T==null?void 0:T.reduce((H,G)=>{var le,re,O;H.set(G.id,G);const ne=(O=(re=(le=G==null?void 0:G.destinationSettings)==null?void 0:le.jobProgressMeasureSheet)==null?void 0:re[0])==null?void 0:O.subAttributeId;return ne&&B.add(ne),H},new Map);d(Array.from(B)),l.current=new Map(Array.from(L.entries()).map(([H,G])=>[H,lt.cloneDeep(G)]))}D={success:!0,rows:T,lastRow:-1}}catch(T){c(T),D={success:!1,rows:[],lastRow:0}}return D},[e]),p=Vt({mutationKey:["syncLeapCrmLinkedFields"],mutationFn:async()=>{var D;return(D=s.current)==null||D.api.showLoadingOverlay(),await am()},onSuccess:async I=>{var D,F;(D=s.current)==null||D.api.paginationGoToFirstPage(),(F=s.current)==null||F.api.refreshServerSide(),n({children:I,severity:"success"})},onError:I=>c(I,"Error Syncing Linked Fields"),onSettled:()=>{var I;(I=s.current)==null||I.api.hideOverlay()}}),{data:h,isFetching:g}=He({queryKey:["fetchLinkedFieldsLeapCRMDestOptions",{subAttributeIds:r}],queryFn:async()=>{var M;const D=await pP({subAttributeIds:r,page:1,limit:100});return{...D,tradeOptionsMap:(M=D.tradeOptions)==null?void 0:M.reduce((R,P)=>{var k;return P!=null&&P.subAttributeId&&R.set((k=P==null?void 0:P.subAttributeId)==null?void 0:k.toString(),P),R},new Map)}},onSuccess:I=>{const{leapCrmErrorMsg:D=""}=I;D&&D!=="no-leapCrm-office"&&n({children:I.leapCrmErrorMsg,severity:"error"})},retry:!1,onError:I=>c(I,"Error Fetching Attribute/Trade Options")}),x=y.useCallback((I,D,F)=>{const M=l.current.get(I),R={id:I,[D]:F};i.current.set(I,R),(M==null?void 0:M[D])===F&&i.current.has(I)&&i.current.delete(I),a(i.current.size>0)},[]),m=y.useCallback(()=>{var D,F;const I={id:`new_${ss(10)}`,linkedField:"",linkedFieldType:[],destinationSettings:{},documents:[],isFinancial:!1,isMeasureSheet:!1,triggers:[]};i.current.set(I.id,I),(D=s.current)==null||D.api.applyServerSideTransaction({add:[I],addIndex:0}),(F=s.current)==null||F.api.paginationGoToFirstPage(),a(i.current.size>0)},[]),f=I=>new Promise(D=>{_o({title:"Delete Linked Field",msg:`Deleting this linked field will remove it from all associated documents. Are you sure you want to delete this linked field: ${I}?`,titleColor:"error",cancelText:"Cancel",confirmText:"Delete",confirmBtnColor:"error",onConfirm:()=>D(!0),onClose:()=>D(!1)})}),j=Vt({mutationFn:async({itemId:I,itemName:D})=>{var R;return await f(D)?((R=s.current)==null||R.api.showLoadingOverlay(),I.startsWith("new_")?I:await uP(I)):""},onError:I=>c(I,"Error Deleting Linked Field"),onSuccess:I=>{var F,M;n({severity:"success",children:"Linked Field deleted successfully"}),i.current.delete(I);const D=(F=s.current)==null?void 0:F.api.getRowNode(I);D!=null&&D.data&&((M=s.current)==null||M.api.applyServerSideTransaction({remove:[D.data]})),a(i.current.size>0)},onSettled:()=>{var I;
20(I=s.current)==null||I.api.hideOverlay()}}),S=(I=[])=>{let D=!0;return I.forEach(({linkedField:F,linkedField_invalid:M,id:R})=>{var P,k;if(!(F!=null&&F.trim())||M){const T=(P=s.current)==null?void 0:P.api.getRowNode(R);if(T!=null&&T.data){const B={...T.data,linkedField_invalid:!0};(k=s.current)==null||k.api.applyServerSideTransaction({update:[B]})}}(F==null?void 0:F.trim())===""&&!M&&(D=!1)}),D},w=(I,D)=>{I.forEach(F=>{var R,P;const M=(R=s.current)==null?void 0:R.api.getRowNode(F.id);if(M!=null&&M.data){const k={...M.data,linkedField_invalid:!!D.includes(F.linkedField)};(P=s.current)==null||P.api.applyServerSideTransaction({update:[k]})}})},C=async I=>{if(I.length===0)return[];const D=I.map(R=>(R==null?void 0:R.linkedField)||""),F=Array.from(new Set(D.filter((R,P)=>D.indexOf(R)!==P)));return F.length?F:await im(D)},v=Vt({mutationKey:["saveLinkedFieldObjects"],mutationFn:async()=>{var R;(R=s.current)==null||R.api.showLoadingOverlay();const I=Array.from(i.current.values());if(I.length===0)return"No changes to save";if(!S(I))throw new Error("Invalid linked field data. Please check the fields.");const F=await C(I);if(w(I,F),F.length>0)throw new Error(`Duplicate linked field names found: ${F.join(", ")}`);return await mP(I)},onError:I=>c(I,"Error Saving Linked Fields"),onSuccess:async()=>{var I;i.current.clear(),(I=s.current)==null||I.api.refreshServerSide({purge:!0}),a(i.current.size>0)},onSettled:()=>{var I;(I=s.current)==null||I.api.hideOverlay()}});return{onCellUpdate:x,gridRef:s,saveDisabled:!o,addNewField:m,deleteLinkedField:j.mutateAsync,destinationData:h,fetchingDestinationData:g,hasLeapCrmOffice:(h==null?void 0:h.leapCrmErrorMsg)!=="no-leapCrm-office",saveLinkedFieldObjects:v.mutateAsync,saving:v.isLoading,startFetchLinkedFieldObjects:u,syncLinkedFieldsFromLeapCRM:p.mutateAsync,syncing:p.isLoading}},xP=()=>{const n=zt(),e=n["linked-field-manager-crm"]===!0,{startFetchLinkedFieldObjects:s,onCellUpdate:o,addNewField:a,deleteLinkedField:i,destinationData:l,hasLeapCrmOffice:r,fetchingDestinationData:d,gridRef:c,saveDisabled:u,saveLinkedFieldObjects:p,saving:h,syncLinkedFieldsFromLeapCRM:g,syncing:x}=gP(),m=l==null?void 0:l.isAuthenticated,f=m?"Synced to Leap CRM":"Authentication failed. Please check your Leap CRM AuthToken.";return t.jsxs(Bo,{sx:{height:"100%"},children:[t.jsx(_h,{when:!1,message:"You have unsaved changes. Are you sure you want to leave without saving?"}),t.jsx(sP,{when:!1}),t.jsxs($o,{alignItems:"flex-end",mb:2,children:[t.jsxs(N,{children:[t.jsx(z,{variant:"subtitle1",children:"Linked Fields Manager"}),t.jsx(z,{variant:"body2",children:"Create and edit linked fields to pass information between documents and results."}),e&&r&&t.jsxs(t.Fragment,{children:[t.jsx(ie,{sx:{my:.5}}),t.jsxs(he,{direction:"row",alignItems:"center",gap:.5,children:[t.jsxs(z,{variant:"body2",sx:{fontWeight:"bold",mr:.5},children:[l==null?void 0:l.authenticatedOffice,":"]}),m?t.jsx(Bh,{sx:{fontSize:"14px",color:"success.main"}}):t.jsx(Wa,{sx:{fontSize:"14px",color:"warning.main"}}),t.jsx(z,{variant:"body2",color:m?"success.main":"warning.main",sx:{fontWeight:"bold"},children:d?"loading...":f})]})]})]}),t.jsxs(he,{direction:"row",alignItems:"center",gap:2,children:[e&&n["lfm-resync-button"]&&t.jsx(Q,{title:m?"Sync with Leap CRM":"Leap CRM not enabled",arrow:!0,children:t.jsx("span",{children:t.jsx(Os,{loading:x,variant:"outlined",color:"secondary","data-cy":"syncWithLeapCRM",disabled:!m,onClick:()=>g(),sx:{minHeight:"40px",minWidth:"auto",px:1},children:t.jsx($h,{})})})}),t.jsx(we,{variant:"contained",color:"secondary",onClick:a,"data-cy":"addNewCustomField",children:"+ New"}),t.jsx(Os,{size:"medium",sx:{minWidth:"110px"},loading:h,onClick:()=>p(),disabled:u,"data-cy":"saveChanges",children:"Save"})]})]}),t.jsx(lP,{startFetchLinkedFieldObjects:s,gridRef:c,onCellUpdate:o,deleteLinkedField:async(j,S)=>i({itemId:j,itemName:S}),hasLeapCrmOffice:r,tradeOptionsMap:(l==null?void 0:l.tradeOptionsMap)||new Map,fetchingDestinationData:d})]})},zP=()=>{const{path:n}=zh(),e=Sc(),s=zt(),{maxContractTemplateCount:o,maxProposalTemplateCount:a,maxCustomTemplateCount:i}=e||{};return t.jsxs(Wh,{children:[t.jsx(Hh,{exact:!0,path:`${n}/`,to:o!==0?`${n}/templates/contract`:a!==0?`${n}/templates/proposal`:i!==0?`${n}/custom`:"/"}),t.jsx(ds,{exact:!0,path:[`${n}/templates/:templateType/:libraryId`],component:Fm}),t.jsx(ds,{exact:!0,path:[`${n}/templates/:templateType`,`${n}/custom/templates/:templateType`],component:eg}),t.jsx(ds,{exact:!0,path:[`${n}/templates/:templateType/edit/:docId`,`${n}/custom/templates/:templateType/edit/:docId`],component:nP}),s["linked-field-manager-v2"]&&t.jsx(ds,{exact:!0,path:[`${n}/linked-field-manager`],component:xP}),i!==0&&t.jsx(ds,{exact:!0,path:[`${n}/custom`],component:rg})]})};export{zP as Documents,zP as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.