@openmrs/esm-cohort-builder-app 4.0.8-pre.1629 → 4.0.8-pre.1632

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/111.js CHANGED
@@ -1 +1 @@
1
- (globalThis.webpackChunk_openmrs_esm_cohort_builder_app=globalThis.webpackChunk_openmrs_esm_cohort_builder_app||[]).push([["111"],{4767(e,t,a){var r={"./en.json":["4300","117"]};function n(e){if(!a.o(r,e))return Promise.resolve().then(function(){var t=Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t});var t=r[e],n=t[0];return a.e(t[1]).then(function(){return a(n)})}n.keys=()=>Object.keys(r),n.id=4767,e.exports=n},5930(e,t,a){"use strict";a.r(t),a.d(t,{cohortBuilder:()=>ej,clearSearchHistoryModal:()=>eX,saveCohortModal:()=>eK,importTranslation:()=>eQ,deleteQueryModal:()=>eJ,cohortBuilderAdminPageCardLink:()=>eG,deleteCohortModal:()=>eZ,clearItemFromSearchHistoryModal:()=>eW,startupApp:()=>eV,saveQueryModal:()=>e0});var r=a(2388),n=a(4923),l=a.n(n),o=a(9536),s=a(202);let i="-esm-cohort-builder__modals__deleteButton___wIYdW";var c=a(2137),m=a(6942),d=a.n(m);let u=e=>{let t={type:"org.openmrs.module.reporting.dataset.definition.PatientDataSetDefinition",columns:[],rowFilters:[],customRowFilterCombination:""};t.columns=E();let a=0;for(let r in t.rowFilters=[],e){if(h(e[r])){delete e[r];continue}"all"!=e[r]&&""!=e&&(t.rowFilters[a]={},t.rowFilters[a].key=p(r,e[r])),Array.isArray(e[r])&&(t.rowFilters[a].parameterValues=b(e[r])),e[r].length>=1&&"alive"===e[r][0].livingStatus&&(t.rowFilters[a].livingStatus="alive"),t.rowFilters[a].type="org.openmrs.module.reporting.dataset.definition.PatientDataSetDefinition",a+=1}return t.customRowFilterCombination=g(t.rowFilters),{query:t}},h=e=>Array.isArray(e)&&e.length>=1?!e[0].value:"all"===e||!e,p=(e,t)=>{let a="reporting.library.cohortDefinition.builtIn";return"gender"===e?a+=`.${t}`:a+=`.${e}`,a},b=e=>{let t={};return e.forEach(e=>{t[e.name]=e.value}),t},g=e=>{let t="",a=e.length;for(let r=1;r<=a;r++)"alive"===e[r-1].livingStatus?(t+=`NOT ${r}`,delete e[r-1].livingStatus):t+=`${r}`,t+=r<a?" AND ":"";return t},E=()=>[{name:"firstname",key:"preferredName.givenName"},{name:"lastname",key:"preferredName.familyName"},{name:"gender",key:"gender"},{name:"age",key:"ageOnDate.fullYears"},{name:"patientId",key:"patientId"},{name:"identifier",key:"preferredIdentifier.identifier"}].map(e=>(e.type="org.openmrs.module.reporting.data.patient.definition.PatientDataDefinition",e.key=`reporting.library.patientDataDefinition.builtIn.${e.key}`,e)),_=(...e)=>e.filter(Boolean).join(" "),y=e=>{let t=new Date(e),a=t.getDate(),r=t.getMonth()+1,n=t.getFullYear();return`${a}/${r}/${n}`},v=async e=>await (0,r.openmrsFetch)(`${r.restBaseUrl}/reportingrest/adhocquery?v=full`,{method:"POST",headers:{"Content-Type":"application/json"},body:e.query}),S=()=>{let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/location`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,locations:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),locationsError:t}},w=async e=>(await (0,r.openmrsFetch)(`${r.restBaseUrl}/reportingrest/dataSet/${e}`,{method:"GET"})).data.rows.map(e=>(e.id=e.patientId?.toString()??"",e.name=_(e.firstname,e.lastname),e));class f extends Error{constructor(){super("None of the cohort's members could be loaded"),this.name="CohortMembersLoadError"}}let C=async e=>{let t=await T(e),a=new Date,r=t.filter(e=>(function({voided:e,startDate:t,endDate:a},r){return!e&&(!t||new Date(t)<=r)&&(!a||new Date(a)>=r)})(e,a)).map(e=>e.patientUuid),n=(await k(r,6,N)).filter(Boolean);if(r.length>0&&0===n.length)throw new f;return{patients:n,total:r.length}};async function T(e){let t=new Map;for(let a=0;a<1e3;a++){let{data:a}=await (0,r.openmrsFetch)(`${r.restBaseUrl}/cohort/${e}/membership?v=custom:(uuid,patientUuid,startDate,endDate,voided)&limit=100&startIndex=${t.size}`),n=t.size;if(a.results.forEach(e=>t.set(e.uuid,e)),!a.links?.some(e=>"next"===e.rel)||t.size===n)break}return[...t.values()]}async function N(e){try{let{data:{patientId:t,person:a,identifiers:n}}=await (0,r.openmrsFetch)(`${r.restBaseUrl}/patient/${e}?v=custom:(patientId,person:(gender,age,preferredName:(givenName,familyName)),identifiers:(identifier,preferred))`);if(!a?.preferredName)return null;let{givenName:l,familyName:o}=a.preferredName,s=n?.find(({preferred:e})=>e)?.identifier??"";return{id:t.toString(),patientId:t,identifier:s,name:_(l,o),firstname:l,lastname:o,age:a.age,gender:a.gender}}catch{return null}}async function k(e,t,a){let r=[],n=0,l=async()=>{for(;n<e.length;){let t=n++;r[t]=await a(e[t])}};return await Promise.all(Array.from({length:Math.min(t,e.length)},l)),r}let I=e=>e.replace(/([()])/g," $1 ").trim().split(/\s+/),D="-esm-cohort-builder__search-button-set__button___tg6-2",x=({isLoading:e,isSearchDisabled:t,onHandleSubmit:a,onHandleReset:r})=>{let{t:n}=(0,s.useTranslation)();return l().createElement(o.Column,{sm:2,md:{offset:4},className:"-esm-cohort-builder__search-button-set__container___jIXOL"},l().createElement(o.ButtonSet,{className:"-esm-cohort-builder__search-button-set__buttonSet___itc+A"},l().createElement(o.Button,{className:D,kind:"secondary",onClick:r,"data-testid":"reset-btn"},n("reset","Reset")),l().createElement(o.Button,{className:D,kind:"primary",disabled:e||t,onClick:a,"data-testid":"search-btn"},e?l().createElement(o.InlineLoading,{description:n("loading","Loading")}):n("search","Search"))))},O="-esm-cohort-builder__composition-style__text___YdbOd",A=({onSubmit:e})=>{let{t}=(0,s.useTranslation)(),[a,i]=(0,n.useState)(!1),[c,m]=(0,n.useState)(""),[d,u]=(0,n.useState)(""),h=async()=>{i(!0);try{if(I(c).every(e=>/^(and|or|not|union|intersection|\d+|[()])$/i.test(e))){let t,a=(t={type:"org.openmrs.module.reporting.dataset.definition.PatientDataSetDefinition",columns:E(),rowFilters:[],customRowFilterCombination:""},I(c).forEach(e=>{if(e.match(/\d/)){let a,r,n=JSON.parse(window.sessionStorage.getItem("openmrsHistory"))[parseInt(e)-1].parameters;a=n.customRowFilterCombination,r=t.rowFilters.length,n.customRowFilterCombination=a.replace(/\d+/g,e=>(parseInt(e)+r).toString()),t.customRowFilterCombination+=`(${n.customRowFilterCombination})`,t.rowFilters=t.rowFilters.concat(n.rowFilters)}else t.customRowFilterCombination+=` ${e} `}),{query:t});await e(a,d)}else(0,r.showSnackbar)({title:t("error","Error!"),kind:"error",isLowContrast:!0,subtitle:t("invalidComposition","Composition is not valid")});i(!1)}catch(e){i(!1),(0,r.showSnackbar)({title:t("error","Error!"),kind:"error",isLowContrast:!0,subtitle:t("invalidComposition","Composition is not valid")})}};return l().createElement(l().Fragment,null,l().createElement(o.TextInput,{labelText:t("composition","Composition"),"data-testid":"composition-query",id:"composition-query",onChange:e=>{var t;m(t=e.target.value),u("Composition of "+t)},value:c}),l().createElement("br",null),l().createElement(o.TextInput,{labelText:t("description","Description"),"data-testid":"composition-description",id:"composition-description",onChange:e=>u(e.target.value),value:d}),l().createElement("br",null),l().createElement("p",{className:O},t("compositionExplanationOne","A composition query combines together the results of multiple cohorts using the logical operators: AND, OR and NOT.")),l().createElement("br",null),l().createElement("p",{className:O},t("compositionExplanationTwo","To use this query you need to already have query results in your search history. Those existing query results can then be combined to yield the results of the composition query.")),l().createElement("br",null),l().createElement("p",{className:O},t("compositionExplanationThree","Example: if the search history #1 is a cohort of patients who are males, and if the search history #2 is a cohort of patients with ages between 23 and 35 years; then '1 AND 2' will result in a cohort of patients who are males with ages between 23 and 35 years.")),l().createElement("br",null),l().createElement(x,{onHandleReset:()=>{u(""),m("")},onHandleSubmit:h,isLoading:a}))};var L=a(2551),M=a.n(L);let $=`${r.restBaseUrl}/cohort?v=full`,F=async e=>await (0,r.openmrsFetch)(`${r.restBaseUrl}/cohort/${e}`,{method:"DELETE"}),q=e=>l().createElement(o.Layer,null,l().createElement(o.Tile,{className:"-esm-cohort-builder__empty-data-style__tile___kGzLZ"},l().createElement(r.EmptyCardIllustration,null),l().createElement("p",{className:"-esm-cohort-builder__empty-data-style__content___zUidZ"},"There are no ",e.displayText.toLowerCase()," to display"))),B="-esm-cohort-builder__saved-cohort-options__menuItem___rX2ia",P="view",R="delete",H=({cohort:e,onViewCohort:t,onDeleteCohort:a})=>{let{t:n}=(0,s.useTranslation)(),i=async()=>{try{await t(e.id)}catch(e){(0,r.showSnackbar)({title:n("cohortViewError","Error viewing the cohort"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},c=async t=>{switch(t){case P:i();break;case R:m(e.id)}},m=t=>{let a=(0,r.showModal)("delete-cohort-modal",{closeModal:()=>a(),cohortName:e.name,cohortId:t,onDeleteCohort:d,size:"sm"})},d=async()=>{await a(e.id)};return l().createElement(o.OverflowMenu,{"aria-label":n("savedCohortsOptions","Saved cohorts options"),flipped:!0,direction:"bottom","data-testid":"options"},l().createElement(o.OverflowMenuItem,{className:B,"data-testid":"view",itemText:n("view","View"),onClick:()=>c(P)}),l().createElement(o.OverflowMenuItem,{className:B,"data-testid":"delete",hasDivider:!0,isDelete:!0,itemText:n("delete","Delete"),onClick:()=>c(R)}))},U="-esm-cohort-builder__cohort-builder__heading___fKg4I",Y="-esm-cohort-builder__cohort-builder__tab___OIkeX",z="-esm-cohort-builder__cohort-builder__optionCell___0dfgH",Q="-esm-cohort-builder__cohort-builder__optionHeader___IBQGc",V="-esm-cohort-builder__cohort-builder__text___Dk0eN",j=({onViewCohort:e})=>{let{t}=(0,s.useTranslation)(),[a,i]=(0,n.useState)(10),{cohorts:c,error:m,isLoading:d,mutate:u}=function(){let{data:e,error:t,isLoading:a,isValidating:l,mutate:o}=M()($,r.openmrsFetch);return{cohorts:(0,n.useMemo)(()=>e?.data?.results?.map(e=>({id:e.uuid,name:e.name,description:e.description})),[e])??[],error:t,isLoading:a,isValidating:l,mutate:o}}(),{results:h,currentPage:p,goTo:b}=(0,r.usePagination)(c,a),g=[{key:"name",header:t("name","Name")},{key:"description",header:t("description","Description")}],E=async e=>{try{await F(e),(0,r.showSnackbar)({title:t("cohortDeleted","Cohort deleted"),kind:"success",isLowContrast:!0,subtitle:t("cohortDeleted","Cohort deleted")}),await u()}catch(e){(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:e?.message})}};return l().createElement("div",{className:"-esm-cohort-builder__saved-cohorts__container___RcI67"},l().createElement("p",{className:V},t("savedCohortDescription","You can only search for Cohort Definitions that you have saved using a Name.")),m&&l().createElement(o.InlineNotification,{kind:"error",lowContrast:!0,hideCloseButton:!0,title:t("errorLoadingCohorts","Error loading saved cohorts"),subtitle:m.message}),d?l().createElement(o.DataTableSkeleton,{headers:g,rowCount:3,showHeader:!1,showToolbar:!1}):!m||c.length>0?l().createElement(o.DataTable,{rows:h,headers:g,useZebraStyles:!0},({rows:t,headers:a,getTableProps:r,getHeaderProps:n,getRowProps:s})=>l().createElement(o.Table,r(),l().createElement(o.TableHead,null,l().createElement(o.TableRow,null,a.map(e=>l().createElement(o.TableHeader,n({header:e}),e.header)),l().createElement(o.TableHeader,{className:Q}))),l().createElement(o.TableBody,null,t.map((t,a)=>l().createElement(o.TableRow,{...s({row:t}),key:a},t.cells.map((e,t)=>l().createElement(o.TableCell,{key:t},e.value)),l().createElement(o.TableCell,{className:z},l().createElement(H,{cohort:h[a],onViewCohort:e,onDeleteCohort:E}))))))):null,c?.length>10&&l().createElement(o.Pagination,{backwardText:t("previousPage","Previous page"),forwardText:t("nextPage","Next page"),itemsPerPageText:t("itemsPerPage","Items per page:"),onChange:({page:e,pageSize:t})=>{b(e),i(t)},page:p,pageSize:a,pageSizes:[10,20,30,40,50],size:"md",totalItems:c.length}),!d&&!m&&!c?.length&&l().createElement(q,{displayText:t("cohorts","cohorts")}))},G=`${r.restBaseUrl}/reportingrest/dataSetDefinition?v=full`,W=async e=>await (0,r.openmrsFetch)(`${r.restBaseUrl}/reportingrest/adhocdataset/${e}?purge=true`,{method:"DELETE"}),X="-esm-cohort-builder__saved-queries-options__menuItem___Qs6Ro",Z="delete",J="view",K=({query:e,onViewQuery:t,deleteQuery:a})=>{let{t:n}=(0,s.useTranslation)(),i=async e=>{switch(e){case J:c();break;case Z:m()}},c=async()=>{try{await t(e.id)}catch(e){(0,r.showSnackbar)({title:n("QueryDeleteError","Something went wrong"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},m=()=>{let t=(0,r.showModal)("delete-query-modal",{closeModal:()=>t(),queryName:e.name,queryId:e.id,onDelete:d,size:"sm"})},d=async()=>{await a(e.id)};return l().createElement(o.OverflowMenu,{"aria-label":n("savedQueriesOptions","Saved queries options"),size:"md",flipped:!0,direction:"bottom"},l().createElement(o.OverflowMenuItem,{className:X,"data-testid":"view",itemText:n("view","View"),onClick:()=>i(J)}),l().createElement(o.OverflowMenuItem,{className:X,"data-testid":"delete",hasDivider:!0,isDelete:!0,itemText:n("delete","Delete"),onClick:()=>i(Z)}))},ee=({onViewQuery:e})=>{let{t}=(0,s.useTranslation)(),[a,i]=(0,n.useState)(10),{queries:c,error:m,isLoading:d,mutate:u}=function(){let{data:e,error:t,isLoading:a,mutate:l}=M()(G,r.openmrsFetch);return{queries:(0,n.useMemo)(()=>e?.data?.results?.map(e=>({id:e.uuid,name:e.name.replace("[AdHocDataExport]",""),description:e.description})),[e])??[],error:t,isLoading:a,mutate:l}}(),{results:h,currentPage:p,goTo:b}=(0,r.usePagination)(c,a),g=async e=>{try{await W(e),(0,r.showSnackbar)({title:t("success","Success"),kind:"success",isLowContrast:!0,subtitle:t("queryIsDeleted","the query is deleted")}),await u()}catch(e){(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:e?.message})}},E=[{key:"name",header:t("name","Name")},{key:"description",header:t("description","Description")}];return l().createElement("div",{className:"-esm-cohort-builder__saved-queries__container___apr+8"},l().createElement("p",{className:V},t("savedQueryDescription","You can only search for Query Definitions that you have saved using a Name.")),m&&l().createElement(o.InlineNotification,{kind:"error",lowContrast:!0,hideCloseButton:!0,title:t("errorLoadingQueries","Error loading saved queries"),subtitle:m.message}),d?l().createElement(o.DataTableSkeleton,{headers:E,rowCount:3,showHeader:!1,showToolbar:!1}):!m||c.length>0?l().createElement(o.DataTable,{rows:h,headers:E,useZebraStyles:!0},({rows:t,headers:a,getTableProps:r,getHeaderProps:n,getRowProps:s})=>l().createElement(o.Table,r(),l().createElement(o.TableHead,null,l().createElement(o.TableRow,null,a.map(e=>l().createElement(o.TableHeader,n({header:e}),e.header)),l().createElement(o.TableHeader,{className:Q}))),l().createElement(o.TableBody,null,t.map((t,a)=>l().createElement(o.TableRow,{...s({row:t}),key:a},t.cells.map((e,t)=>l().createElement(o.TableCell,{key:t},e.value)),l().createElement(o.TableCell,{className:z},l().createElement(K,{query:h[a],onViewQuery:e,deleteQuery:g}))))))):null,c.length>10&&l().createElement(o.Pagination,{backwardText:t("previousPage","Previous page"),forwardText:t("nextPage","Next page"),itemsPerPageText:t("itemsPerPage","Items per page:"),onChange:({page:e,pageSize:t})=>{b(e),i(t)},page:p,pageSize:a,pageSizes:[10,20,30,40,50],size:"md",totalItems:c.length}),!d&&!m&&!c.length&&l().createElement(q,{displayText:t("queries","queries")}))};var et=a(4353),ea=a.n(et),er=a(4861);async function en(e){let t=await (0,r.openmrsFetch)(`${r.restBaseUrl}/concept?v=full&q=${encodeURIComponent(e)}`,{method:"GET"}),a=[];return t.data.results.length>0&&(a=t.data.results.map(e=>{let t=e.descriptions.filter(e=>"en"==e.locale?e.description:"");return{uuid:e.uuid,units:e.units||"",answers:e.answers,hl7Abbrev:e.datatype.hl7Abbreviation,name:e.name.name,description:t.length>0?t[0].description:"no description available",datatype:e.datatype}})),a}let el={searchContainer:"-esm-cohort-builder__search-concept__searchContainer___dpJim",search:"-esm-cohort-builder__search-concept__search___9eq8D",loader:"-esm-cohort-builder__search-concept__loader___RvR4m",concept:"-esm-cohort-builder__search-concept__concept___WbcYA",conceptList:"-esm-cohort-builder__search-concept__conceptList___XqGdL",text:"-esm-cohort-builder__search-concept__text___Ow696",notification:"-esm-cohort-builder__search-concept__notification___x7E6s"},eo=({concept:e,searchText:t,setConcept:a,setSearchText:r})=>{let{t:i}=(0,s.useTranslation)(),[c,m]=(0,n.useState)([]),[d,u]=(0,n.useState)(""),[h,p]=(0,n.useState)(!1),[b,g]=(0,n.useState)(!1),E=async e=>{m([]),a(null),p(!0),g(!1);try{let t=await en(e);t.length?m(t):g(!0),p(!1)}catch(e){u(e.toString()),p(!1)}},_=(0,n.useRef)((0,er.A)(async e=>{e&&await E(e)},500)).current;return(0,n.useEffect)(()=>()=>{_.cancel()},[_]),l().createElement("div",null,l().createElement(o.Column,{className:el.column},l().createElement("div",{className:el.searchContainer},l().createElement(o.Search,{closeButtonLabelText:i("clearSearch","Clear search"),id:"concept-search",labelText:i("searchConcepts","Search Concepts"),onChange:e=>{r(e.target.value),_(e.target.value)},onClear:()=>{g(!1),m([])},placeholder:i("searchConcepts","Search Concepts"),value:t}),l().createElement("div",{className:el.search},h?l().createElement(o.InlineLoading,{className:el.loader,description:i("searching","Searching")+"..."}):l().createElement("ul",{className:el.conceptList},c?.map((e,t)=>l().createElement("li",{role:"menuitem",className:el.concept,key:t,onClick:()=>{a(e),m([]),g(!1)}},e.name))))),e&&l().createElement("span",{className:el.text},i("patientsWithObservationsWhoseAnswerIs","Patients with observations whose answer is"),l().createElement("strong",null,' "',e.name,'"'),"."),t&&b&&l().createElement(o.Tile,null,l().createElement("span",null,i("noMatchingConcepts","No concepts were found that match"),l().createElement("strong",null,' "',t,'"'),".")),d&&l().createElement("span",null,d)))};var es=a(445),ei=a.n(es);ea().extend(ei());let ec=e=>{let t=ea()(e.trim(),["DD-MM-YYYY","D-MM-YYYY","DD-M-YYYY","D-M-YYYY"],!0);return!!t.isValid()&&t.toDate()},em=({id:e,labelText:t,value:a,onChange:r})=>{let n=(e,t,{selectedDates:[a]})=>r(a?ea()(a).format():"");return l().createElement(o.DatePicker,{dateFormat:"d-m-Y",datePickerType:"single",parseDate:ec,onChange:n,onClose:n,value:a&&ea()(a).format("DD-MM-YYYY")},l().createElement(o.DatePickerInput,{id:e,labelText:t,placeholder:"DD-MM-YYYY",size:"md",onChange:e=>!e.target.value&&r(""),onKeyDownCapture:e=>{if("Tab"===e.key){let t=e.currentTarget;t._flatpickr?.setDate(ec(t.value)||"",!0)}}}))},ed="-esm-cohort-builder__search-by-concepts-style__column___fpjOs",eu="-esm-cohort-builder__search-by-concepts-style__dateRange___unfDl",eh="-esm-cohort-builder__search-by-concepts-style__multipleInputs___O7iAI",ep=[{id:0,label:"<",value:"LESS_THAN"},{id:1,label:"<=",value:"LESS_EQUAL"},{id:2,label:"=",value:"EQUAL"},{id:3,label:">=",value:"GREATER_EQUAL"},{id:4,label:">",value:"GREATER_THAN"}],eb={CWE:"codedObsSearchAdvanced",NM:"numericObsSearchAdvanced",DT:"dateObsSearchAdvanced",ST:"dateObsSearchAdvanced",TS:"textObsSearchAdvanced",ZZ:"codedObsSearchAdvanced",BIT:"codedObsSearchAdvanced"},eg=({onSubmit:e})=>{let{t}=(0,s.useTranslation)(),[a,r]=(0,n.useState)(null),[i,c]=(0,n.useState)(0),[m,d]=(0,n.useState)(0),[h,p]=(0,n.useState)(""),[b,g]=(0,n.useState)("LESS_THAN"),[E,_]=(0,n.useState)("ANY"),[v,S]=(0,n.useState)(""),[w,f]=(0,n.useState)(""),[C,T]=(0,n.useState)(""),[N,k]=(0,n.useState)(!1),I=[{id:"option-0",label:t("haveObservations","Patients who have these observations"),value:"ANY"},{id:"option-1",label:t("haveNoObservations","Patients who do not have these observations"),value:"NO"}],D=[{id:"option-0",label:t("any","Any"),value:"ANY"},{id:"option-1",label:t("none","None"),value:"NO"},{id:"option-2",label:t("earliest","Earliest"),value:"FIRST"},{id:"option-3",label:t("recent","Most Recent"),value:"LAST"},{id:"option-4",label:t("lowest","Lowest"),value:"MIN"},{id:"option-5",label:t("highest","Highest"),value:"MAX"},{id:"option-6",label:t("average","Average"),value:"AVG"}],O=a?.hl7Abbrev==="NM",A=O?D:I,L=A.find(({value:e})=>e===E)??A[0],M=async()=>{if(!a)return;k(!0);let t={modifier:"",operator1:O?b:"",value1:O&&""!==h?h.toString():"",question:a.uuid,onOrBefore:(()=>{if(i>0||m>0)return ea()().subtract(i,"days").subtract(m,"months").format()})()||w,onOrAfter:v,timeModifier:L.value},r=eb[a.hl7Abbrev],n={[r]:[]};Object.keys(t).forEach(e=>{""!==t[e]&&n[r].push({name:"modifier"===e?["CWE","TS"].includes(a.hl7Abbrev)?"values":"value1":e,value:"modifier"===e&&["CWE","TS"].includes(a.hl7Abbrev)?[t[e]]:t[e]})}),await e(u(n),((e,t)=>{let{timeModifier:a,onOrAfter:r,onOrBefore:n}=e,l=r?`since ${y(r)}`:"",o=n?`until ${y(n)}`:"";return`Patients with ${a} ${t} ${l} ${o}`.trim()})(t,a.name)),k(!1)};return l().createElement(l().Fragment,null,l().createElement("div",null,l().createElement(eo,{setConcept:r,concept:a,searchText:C,setSearchText:T}),O?l().createElement(l().Fragment,null,l().createElement(o.Column,{className:ed},l().createElement("div",{style:{display:"flex"}},l().createElement("div",{className:eh},l().createElement("p",{style:{paddingRight:20}},t("whatObservations","What observations")),l().createElement(o.Dropdown,{id:"timeModifier",onChange:e=>_(e.selectedItem.value),selectedItem:L,items:D,className:"-esm-cohort-builder__search-by-concepts-style__timeModifier___SeThC",label:"",titleText:""})))),l().createElement(o.Column,{className:ed},l().createElement("p",{className:"-esm-cohort-builder__search-by-concepts-style__value___FUIbI"},t("whatValues","What values")),l().createElement("div",{className:"-esm-cohort-builder__search-by-concepts-style__whatValuesInputs___5UXAP"},l().createElement("div",{className:"-esm-cohort-builder__search-by-concepts-style__operators___KUi3k"},l().createElement(o.ContentSwitcher,{selectedIndex:ep.findIndex(({value:e})=>e===b),className:"-esm-cohort-builder__search-by-concepts-style__contentSwitcher___LXxCi",size:"lg",onChange:({index:e})=>g(ep[e].value)},ep.map(e=>l().createElement(o.Switch,{key:e.id,name:e.value,text:e.label})))),l().createElement("div",{className:eh},l().createElement(o.NumberInput,{allowEmpty:!0,hideSteppers:!0,id:"operator-value",invalidText:t("numberIsNotValid","Number is not valid"),label:t("valueIn","Enter a value in ")+a.units,min:0,size:"sm",value:h,onChange:(e,{value:t})=>p(""===t?"":Number(t))}))))):l().createElement(o.Column,{className:ed},l().createElement(o.Dropdown,{id:"timeModifier","data-testid":"timeModifier",onChange:e=>_(e.selectedItem.value),selectedItem:L,items:I,label:"",titleText:""})),l().createElement(o.Column,{className:eu},l().createElement(o.Column,null,l().createElement(o.NumberInput,{hideSteppers:!0,id:"last-months","data-testid":"last-months",label:t("withinTheLast","Within the last months"),invalidText:t("numberIsNotValid","Number is not valid"),min:0,value:m,onChange:(e,{value:t})=>d(Number(t))})),l().createElement(o.Column,null,l().createElement(o.NumberInput,{hideSteppers:!0,label:t("lastDays","and / or days"),id:"last-days","data-testid":"last-days",invalidText:t("numberIsNotValid","Number is not valid"),min:0,value:i,onChange:(e,{value:t})=>c(Number(t))}))),l().createElement("div",{className:eu},l().createElement(o.Column,null,l().createElement(em,{id:"startDate",labelText:t("dateRange","Date range start date"),value:v,onChange:S})),l().createElement(o.Column,null,l().createElement(em,{id:"endDate",labelText:t("endDate","End date"),value:w,onChange:f})))),l().createElement(x,{isLoading:N,onHandleSubmit:M,onHandleReset:()=>{r(null),c(0),T(""),S(""),f(""),d(0),p(""),g("LESS_THAN"),_("ANY")}}))},eE="-esm-cohort-builder__search-by-demographics-style__contentSwitcher___L5GhV",e_="-esm-cohort-builder__search-by-demographics-style__column___agceq",ey="-esm-cohort-builder__search-by-demographics-style__switch___Q01uO",ev=({onSubmit:e})=>{let{t}=(0,s.useTranslation)(),[a,r]=(0,n.useState)("alive"),[i,c]=(0,n.useState)("all"),[m,h]=(0,n.useState)(""),[p,b]=(0,n.useState)(""),[g,E]=(0,n.useState)(0),[_,y]=(0,n.useState)(0),[v,S]=(0,n.useState)(!1),w=[{id:0,label:t("all","All"),value:"all"},{id:1,label:t("males","Male"),value:"males"},{id:3,label:t("females","Female"),value:"females"}],f=[{id:0,label:t("alive","Alive"),value:"alive"},{id:1,label:t("dead","Dead"),value:"dead"}],C=async()=>{S(!0);let t={gender:i,minAge:g,maxAge:_,birthDayStartDate:m,birthDayEndDate:p,livingStatus:a};await e((({gender:e,minAge:t,maxAge:a,birthDayStartDate:r,birthDayEndDate:n,livingStatus:l})=>{let o={gender:e};t&&a?o.ageRangeOnDate=[{name:"minAge",value:t},{name:"maxAge",value:a}]:t?o.atLeastAgeOnDate=[{name:"minAge",value:t}]:o.upToAgeOnDate=[{name:"maxAge",value:a}],r&&n&&(o.bornDuringPeriod=[{name:"startDate",dataType:"date",value:r},{name:"endDate",dataType:"date",value:n}]),o.diedDuringPeriod=[{name:"endDate",dataType:"date",value:ea()().format(),livingStatus:l}];let s=u(o);if("all"===o.gender){let e=["males","females","unknownGender"].map(e=>({type:"org.openmrs.module.reporting.dataset.definition.PatientDataSetDefinition",key:`reporting.library.cohortDefinition.builtIn.${e}`})),{query:{rowFilters:t,customRowFilterCombination:a}}=s,r=t=t.length>0?[...t,...e]:e,n=a;a=n?`(${r.length-2} OR ${r.length-1} OR ${r.length}) AND ${n}`:"(1 OR 2 OR 3)"}return s})(t),(({gender:e,minAge:t,maxAge:a,birthDayStartDate:r,birthDayEndDate:n,livingStatus:l})=>{let o="all"!=e?`${"males"===e?"Male":"Female"} Patients`:"All Patients";return(t||a)&&(t&&a?o+=` with ages between ${t} and ${a}`:o+=t?` with minimum age of ${t}`:` with maximum age of ${a}`,o+=" years"),(""!=r||""!=n)&&(r&&n?o+=` and birthdate between ${r} and ${n}`:o+=t?` and born before ${r}`:` and born before ${n}`),l&&(o+=` that are ${l}`),o})(t)),S(!1)};return l().createElement(l().Fragment,null,l().createElement(o.Column,null,l().createElement("p",{className:d()("-esm-cohort-builder__search-by-demographics-style__text___x8MO2","-esm-cohort-builder__search-by-demographics-style__genderTitle___06Nb4")},t("gender","Gender")),l().createElement("div",{className:"-esm-cohort-builder__search-by-demographics-style__genderContainer___VkE-3"},l().createElement("div",{className:ey},l().createElement(o.ContentSwitcher,{selectedIndex:w.findIndex(({value:e})=>e===i),className:eE,size:"lg",onChange:({index:e})=>c(w[e].value)},w.map(e=>l().createElement(o.Switch,{"data-testid":e.label,key:e.id,name:e.value,text:e.label})))),l().createElement("div",{className:ey},l().createElement(o.ContentSwitcher,{selectedIndex:f.findIndex(({value:e})=>e===a),className:eE,size:"lg",onChange:({index:e})=>r(f[e].value)},f.map(e=>l().createElement(o.Switch,{key:e.id,name:e.value,text:e.label})))))),l().createElement("div",{className:e_},l().createElement(o.Column,{className:"-esm-cohort-builder__search-by-demographics-style__age___DEuDD"},l().createElement(o.Column,null,l().createElement(o.NumberInput,{"data-testid":"minAge",hideSteppers:!0,id:"minAge",invalidText:t("minAgeIsNotValid","The age must be greater than 0"),label:t("ageBetween","Age between"),min:0,onChange:(e,{value:t})=>E(Number(t)),value:g})),l().createElement(o.Column,null,l().createElement(o.NumberInput,{"data-testid":"maxAge",hideSteppers:!0,id:"maxAge",invalidText:t("maxAgeIsNotValid","The age must be less than 200"),label:t("and","and"),max:200,min:0,onChange:(e,{value:t})=>y(Number(t)),value:_})))),l().createElement("div",{className:e_},l().createElement(o.Column,null,l().createElement(em,{id:"startDate",labelText:t("birthDate","Birth date between"),value:m,onChange:h})),l().createElement(o.Column,null,l().createElement(em,{id:"endDate",labelText:t("and","and"),value:p,onChange:b}))),l().createElement(x,{isLoading:v,onHandleSubmit:C,onHandleReset:()=>{c("all"),r("alive"),y(0),E(0),b(""),h("")}}))},eS="-esm-cohort-builder__search-by-drug-orders-style__column___nQLUC",ew=({onSubmit:e})=>{let{t}=(0,s.useTranslation)(),{drugs:a,drugsError:i}=function(){let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/drug`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return(0,n.useMemo)(()=>({isLoading:a,drugs:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),drugsError:t}),[e,t,a])}(),{careSettings:c,careSettingsError:m}=function(){let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/caresetting`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return(0,n.useMemo)(()=>({isLoading:a,careSettings:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),careSettingsError:t}),[e,t,a])}(),[d,h]=(0,n.useState)(""),[p,b]=(0,n.useState)(""),[g,E]=(0,n.useState)(""),[_,y]=(0,n.useState)(""),[v,S]=(0,n.useState)([]),[w,f]=(0,n.useState)(null),[C,T]=(0,n.useState)(!1),N=i?.message;(0,n.useEffect)(()=>{N&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:N})},[N,t]);let k=m?.message;(0,n.useEffect)(()=>{k&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:k})},[k,t]);let I=async()=>{T(!0);let t={selectedDrugs:v,selectedCareSetting:w,activeOnOrAfter:d,activeOnOrBefore:p,activatedOnOrAfter:g,activatedOnOrBefore:_};try{await e((({selectedDrugs:e,selectedCareSetting:t,activeOnOrBefore:a,activeOnOrAfter:r,activatedOnOrBefore:n,activatedOnOrAfter:l})=>{let o={drugOrderSearch:[]};return r&&o.drugOrderSearch.push({name:"activeOnOrAfter",value:r}),l&&o.drugOrderSearch.push({name:"activatedOnOrAfter",value:l}),n&&o.drugOrderSearch.push({name:"activatedOnOrBefore",value:n}),t&&o.drugOrderSearch.push({name:"careSetting",value:t.value}),e.length&&o.drugOrderSearch.push({name:"drugs",value:e.map(e=>e.value)}),a&&o.drugOrderSearch.push({name:"activeOnOrBefore",value:a}),u(o)})(t),(({selectedDrugs:e,selectedCareSetting:t,activeOnOrBefore:a,activeOnOrAfter:n,activatedOnOrBefore:l,activatedOnOrAfter:o})=>{let s="Patients who taking "+e.map(e=>e.label).join(", ").replace(/,(?=[^,]*$)/," and");if(t&&(s+=` from ${t.label}`),n){let e=(0,r.formatDate)(new Date(n),{mode:"standard"});a?s+=` from ${e}`:s+=` on or after ${e}`}if(a){let e=(0,r.formatDate)(new Date(a),{mode:"standard"});n?s+=` to ${e}`:s+=` on or before ${e}`}if(o){let e=(0,r.formatDate)(new Date(o),{mode:"standard"});l?s+=` from ${e}`:s+=` on or after ${e}`}if(l){let e=(0,r.formatDate)(new Date(l),{mode:"standard"});o?s+=` to ${e}`:s+=` on or before ${e}`}return s})(t))}finally{T(!1)}};return l().createElement(l().Fragment,null,l().createElement(o.Column,null,l().createElement("div",null,l().createElement(o.MultiSelect,{id:"drugs","data-testid":"drugs",onChange:e=>S(e.selectedItems),selectedItems:v,items:a,label:t("selectDrugs","Select drugs")}))),l().createElement("div",{className:eS},l().createElement(o.Column,null,l().createElement(o.Dropdown,{id:"careSettings","data-testid":"careSettings",onChange:e=>f(e.selectedItem),selectedItem:w,items:c,label:t("selectCareSettings","Select a care setting"),titleText:""}))),l().createElement("div",{className:eS},l().createElement(o.Column,null,l().createElement(em,{id:"activeOnOrAfter",labelText:t("using","Using between"),value:d,onChange:h})),l().createElement(o.Column,null,l().createElement(em,{id:"activeOnOrBefore",labelText:t("to","to"),value:p,onChange:b}))),l().createElement("div",{className:eS},l().createElement(o.Column,null,l().createElement(em,{id:"activatedOnOrAfter",labelText:t("used","Used between"),value:g,onChange:E})),l().createElement(o.Column,null,l().createElement(em,{id:"activatedOnOrBefore",labelText:t("and","and"),value:_,onChange:y}))),l().createElement(x,{onHandleReset:()=>{S([]),f(null),h(""),b(""),E(""),y("")},onHandleSubmit:I,isLoading:C}))},ef="-esm-cohort-builder__search-by-encounters-style__column___2KGkF",eC="-esm-cohort-builder__search-by-encounters-style__multipleInputs___AQXO8",eT=({onSubmit:e})=>{let{t}=(0,s.useTranslation)(),[a,i]=(0,n.useState)(0),[c,m]=(0,n.useState)(0),{encounterTypes:d,encounterTypesError:h}=(()=>{let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/encountertype`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,encounterTypes:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),encounterTypesError:t}})(),[p,b]=(0,n.useState)([]),[g,E]=(0,n.useState)([]),[_,y]=(0,n.useState)([]),{locations:v,locationsError:w}=S(),{forms:f,formsError:C}=(()=>{let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/form`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,forms:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),formsError:t}})(),[T,N]=(0,n.useState)(""),[k,I]=(0,n.useState)(""),[D,O]=(0,n.useState)(!1),A=w?.message;(0,n.useEffect)(()=>{A&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:A})},[A,t]);let L=C?.message;(0,n.useEffect)(()=>{L&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:L})},[L,t]);let M=h?.message;(0,n.useEffect)(()=>{M&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:M})},[M,t]);let $=async()=>{O(!0);let t={onOrAfter:k,atLeastCount:a,atMostCount:c,encounterForms:_,encounterLocations:g,onOrBefore:T,selectedEncounterTypes:p};try{await e((({onOrAfter:e,atLeastCount:t,atMostCount:a,encounterForms:r,encounterLocations:n,onOrBefore:l,selectedEncounterTypes:o})=>{let s={encounterSearchAdvanced:[]};return e&&s.encounterSearchAdvanced.push({name:"onOrAfter",value:e}),t&&s.encounterSearchAdvanced.push({name:"atLeastCount",value:t}),a&&s.encounterSearchAdvanced.push({name:"atMostCount",value:a}),r.length&&s.encounterSearchAdvanced.push({name:"formList",value:r.map(e=>e.value)}),n.length&&s.encounterSearchAdvanced.push({name:"locationList",value:n.map(e=>e.value)}),l&&s.encounterSearchAdvanced.push({name:"onOrBefore",value:l}),o.length>0&&s.encounterSearchAdvanced.push({name:"encounterTypeList",value:o.map(e=>e.value)}),u(s)})(t),(({selectedEncounterTypes:e,encounterLocations:t,encounterForms:a,atLeastCount:r,atMostCount:n,onOrAfter:l,onOrBefore:o})=>{let s="Patients with Encounter of",i=e.map(e=>e.label).join(", ").replace(/,(?=[^,]*$)/," and ");return s+=i?` Type${i.length>1?"s":""} ${i}`:" any Type",t.length&&(s+=` at ${t.map(e=>e.label).join(", ")}`),a.length&&(s+=` from ${a.map(e=>e.label).join(", ")}`),r&&(s+=` at least ${r} ${r>1?"times":"time"}`),n&&(s+=` ${r?" and":""} at most ${n} ${n>1?"times":"time"}`),l&&(o?s+=` from ${l}`:s+=` on or after ${l}`),o&&(l?s+=` to ${o}`:s+=` on or before ${o}`),s})(t))}finally{O(!1)}};return l().createElement(l().Fragment,null,l().createElement(o.Column,null,l().createElement("div",null,l().createElement(o.MultiSelect,{id:"encounters",onChange:e=>b(e.selectedItems),selectedItems:p,items:d,label:t("selectEncounterTypes","Select encounter types")}))),l().createElement(o.MultiSelect,{id:"forms","data-testid":"forms",onChange:e=>y(e.selectedItems),selectedItems:_,items:f,label:t("selectForms","Select forms")}),l().createElement(o.MultiSelect,{id:"locations",onChange:e=>E(e.selectedItems),selectedItems:g,items:v,label:t("selectLocations","Select locations")}),l().createElement("div",{className:ef},l().createElement(o.Column,{className:"-esm-cohort-builder__search-by-encounters-style__encounterRange___0Q8rh"},l().createElement("div",{className:eC},l().createElement(o.NumberInput,{hideSteppers:!0,id:"atLeastCount","data-testid":"atLeastCount",label:t("atLeast","at least"),min:0,size:"sm",value:a,onChange:(e,{value:t})=>i(Number(t))})),l().createElement("div",{className:eC},l().createElement(o.NumberInput,{hideSteppers:!0,id:"atMostCount","data-testid":"atMostCount",label:t("upto","upto this many"),min:0,size:"sm",value:c,onChange:(e,{value:t})=>m(Number(t))})))),l().createElement("div",{className:ef},l().createElement(o.Column,null,l().createElement(em,{id:"onOrAfter",labelText:t("from","From"),value:k,onChange:I})),l().createElement(o.Column,null,l().createElement(em,{id:"onOrBefore",labelText:t("to","to"),value:T,onChange:N}))),l().createElement(x,{isLoading:D,onHandleSubmit:$,onHandleReset:()=>{b([]),y([]),E([]),i(0),m(0),N(""),I("")}}))},eN="-esm-cohort-builder__search-by-enrollments-style__column___10FcT",ek=({onSubmit:e})=>{let{t}=(0,s.useTranslation)(),{programs:a,programsError:i}=function(){let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/program`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,programs:(e??[]).map((e,t)=>({id:t,label:e.name,value:e.uuid})),programsError:t}}(),{locations:c,locationsError:m}=S(),[d,h]=(0,n.useState)(""),[p,b]=(0,n.useState)(""),[g,E]=(0,n.useState)(""),[_,y]=(0,n.useState)(""),[v,w]=(0,n.useState)([]),[f,C]=(0,n.useState)([]),[T,N]=(0,n.useState)(!1),k=i?.message;(0,n.useEffect)(()=>{k&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:k})},[k,t]);let I=m?.message;(0,n.useEffect)(()=>{I&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:I})},[I,t]);let D=async()=>{N(!0);let t={enrolledOnOrAfter:d,enrolledOnOrBefore:p,completedOnOrAfter:g,completedOnOrBefore:_,selectedPrograms:f,selectedLocations:v};try{await e((({enrolledOnOrAfter:e,enrolledOnOrBefore:t,completedOnOrAfter:a,completedOnOrBefore:r,selectedPrograms:n,selectedLocations:l})=>u({patientsWithEnrollment:[{name:"programs",value:n?.map(e=>e.value)},e&&{name:"enrolledOnOrAfter",value:e},t&&{name:"enrolledOnOrBefore",value:t},a&&{name:"completedOnOrAfter",value:a},r&&{name:"completedOnOrBefore",value:r},{name:"locationList",value:l?.map(e=>e.value)}]}))(t),(({selectedPrograms:e,selectedLocations:t})=>{let a=`Patients enrolled in ${e?.map(e=>e.label).join(", ")}`;return t?.length&&(a+=` at ${t?.map(e=>e.label).join(", ")}`),a})(t))}finally{N(!1)}};return l().createElement(l().Fragment,null,l().createElement(o.Column,null,l().createElement("div",null,l().createElement(o.MultiSelect,{id:"programs","data-testid":"programs",onChange:e=>C(e.selectedItems),selectedItems:f,items:a,label:t("selectPrograms","Select programs")}))),l().createElement(o.Column,null,l().createElement("div",null,l().createElement(o.MultiSelect,{id:"locations","data-testid":"locations",onChange:e=>w(e.selectedItems),selectedItems:v,items:c,label:t("selectLocations","Select locations")}))),l().createElement("div",{className:eN},l().createElement(o.Column,null,l().createElement(em,{id:"enrolledOnOrAfter",labelText:t("enrolledBetween","Enrolled between"),value:d,onChange:h})),l().createElement(o.Column,null,l().createElement(em,{id:"enrolledOnOrBefore",labelText:t("and","and"),value:p,onChange:b}))),l().createElement("div",{className:eN},l().createElement(o.Column,null,l().createElement(em,{id:"completedOnOrAfter",labelText:t("completedBetween","Completed between"),value:g,onChange:E})),l().createElement(o.Column,null,l().createElement(em,{id:"completedOnOrBefore",labelText:t("and","and"),value:_,onChange:y}))),l().createElement(x,{onHandleReset:()=>{C([]),w([]),h(""),b(""),E(""),y("")},onHandleSubmit:D,isLoading:T}))},eI=({onSubmit:e})=>{let{t}=(0,s.useTranslation)(),a=(0,n.useMemo)(()=>[{id:0,label:t("anyEncounter","Any Encounter"),value:"ANY"},{id:1,label:t("mostRecentEncounter","Most Recent Encounter"),value:"LAST"},{id:2,label:t("earliestEncounter","Earliest Encounter"),value:"FIRST"}],[t]),{locations:i,locationsError:c}=S(),[m,d]=(0,n.useState)([]),[h,p]=(0,n.useState)(a[0]),[b,g]=(0,n.useState)(!1),E=c?.message;(0,n.useEffect)(()=>{E&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:E})},[E,t]);let _=async()=>{g(!0);try{var t;let a;await e((t=h.value,a=[],m?.map(e=>a.push(e.value)),u({encounterSearchAdvanced:[{name:"locationList",value:a},{name:"timeQualifier",value:t}]})),((e,t)=>{let a=t?.length?`Patients in ${t.map(e=>e.label).join(", ")}`:"Patients in any location";switch(e){case"FIRST":a+=" (by method EARLIEST_ENCOUNTER).";break;case"LAST":a+=" (by method LATEST_ENCOUNTER).";break;default:a+=" (by method ANY_ENCOUNTER)."}return a})(h.value,m))}finally{g(!1)}};return l().createElement(l().Fragment,null,l().createElement(o.Column,null,l().createElement("div",null,l().createElement(o.MultiSelect,{"aria-label":t("selectLocations","Select locations"),id:"locations","data-testid":"locations",onChange:e=>d(e.selectedItems),selectedItems:m,items:i,label:t("selectLocations","Select locations"),placeholder:t("searchForALocation","Search for a location")}))),l().createElement("div",{className:"-esm-cohort-builder__search-by-location-style__column___yC9N2"},l().createElement(o.Column,null,l().createElement(o.Dropdown,{id:"methods","data-testid":"methods",onChange:e=>p(e.selectedItem),selectedItem:h,items:a,label:t("selectMethod","Select a method"),titleText:""}))),l().createElement(x,{onHandleReset:()=>{d([]),p(a[0])},onHandleSubmit:_,isLoading:b}))},eD=({onSubmit:e})=>{let{t}=(0,s.useTranslation)(),{personAttributes:a,personAttributesError:i}=function(){let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/personattributetype`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,personAttributes:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),personAttributesError:t}}(),[c,m]=(0,n.useState)(""),[d,h]=(0,n.useState)(null),[p,b]=(0,n.useState)(!1),g=a.find(e=>e.value===d)??null,E=i?.message;(0,n.useEffect)(()=>{E&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:E})},[E,t]);let _=async()=>{b(!0);let t=c.split(",").map(e=>e.trim()).filter(Boolean);try{var a;let r,n;await e(u({personWithAttribute:[{name:"attributeType",value:d},{name:"values",value:t}]}),(a=g?.label,r="Patients",n=t.length>0?t.join(", ").replace(/,(?=[^,]*$)/," or"):"",r+=a?` with${n?"":" any"} ${a}`:a,r+=n?` equal to ${t.length>1?"either ":""}${n}`:""))}finally{b(!1)}};return l().createElement(l().Fragment,null,l().createElement(o.Column,null,l().createElement("div",null,l().createElement(o.Dropdown,{id:"personAttributes","data-testid":"personAttributes",onChange:e=>h(e.selectedItem?.value??null),selectedItem:g,items:a,label:t("selectAttribute","Select a person attribute"),titleText:""}))),l().createElement("div",{className:"-esm-cohort-builder__search-by-person-attributes-style__column___Tvomw"},l().createElement(o.Column,null,l().createElement(o.TextInput,{id:"selectedAttributeValues","data-testid":"selectedAttributeValues",disabled:!d,labelText:t("selectedAttributeValues","Enter Comma Delimited Values"),value:c,onChange:e=>m(e.target.value)}))),l().createElement(x,{onHandleReset:()=>{h(null),m("")},onHandleSubmit:_,isLoading:p,isSearchDisabled:!d}))};async function ex(e){return await (0,r.openmrsFetch)(`${r.restBaseUrl}/cohort`,{method:"POST",headers:{"Content-Type":"application/json"},body:e})}async function eO(e){return await (0,r.openmrsFetch)(`${r.restBaseUrl}/reportingrest/adhocdataset`,{method:"POST",headers:{"Content-Type":"application/json"},body:e})}let eA="-esm-cohort-builder__search-history-options__menuItem___iYtpR",eL="delete",eM="download",e$="saveCohort",eF="saveQuery",eq=async(e,t,a,n,l)=>{let o=[],{patients:s}=a;s.forEach(e=>o.push(parseInt(e.id)));try{await ex({display:e,memberIds:o,description:t,name:e}),(0,r.showSnackbar)({title:n("success","Success"),kind:"success",isLowContrast:!0,subtitle:n("cohortSaved","Cohort created successfully")}),l($)}catch(e){(0,r.showSnackbar)({title:n("errorCreatingCohort","Error creating the cohort"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},eB=({searchItem:e,updateSearchHistory:t})=>{let{t:a}=(0,s.useTranslation)(),{mutate:n}=(0,L.useSWRConfig)(),i=async t=>{let{patients:a,description:r}=e;switch(t){case e$:h();break;case eF:d();break;case eM:let n=new Blob(["patient_id, full_name, age, gender\n"+a.map(e=>Object.keys({patientId:e.patientId,name:e.name,age:e.age,gender:e.gender}).map(t=>`"${e[t]}"`).join(",")).join("\n")],{type:"text/csv;charset=utf-8;"}),l=URL.createObjectURL(n),o=document.createElement("a");o.href=l,o.setAttribute("download",r),o.click();break;case eL:u()}},c=async()=>{try{t(e),(0,r.showSnackbar)({title:a("success","Success"),kind:"success",isLowContrast:!0,subtitle:"the search item is deleted"})}catch(e){(0,r.showSnackbar)({title:a("searchItemDeleteError","Error deleting the cohort"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},m=async({queryName:t,queryDescription:l})=>{try{let{parameters:o}=e;o.name=t,o.description=l,await eO(o),(0,r.showSnackbar)({title:a("success","Success"),kind:"success",isLowContrast:!0,subtitle:"the query is saved"}),n(G)}catch(e){(0,r.showSnackbar)({title:a("queryDeleteError","Error saving the query"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},d=()=>{let e=(0,r.showModal)("save-query-modal",{closeModal:()=>e(),onSaveQuery:m,size:"sm"})},u=()=>{let t=(0,r.showModal)("clear-item-from-search-history-modal",{closeModal:()=>t(),onRemove:c,searchItemName:e?.description,size:"sm"})},h=()=>{let t=(0,r.showModal)("save-cohort-modal",{closeModal:()=>t(),onSave:(t,r)=>eq(t,r,e,a,n),size:"sm"})};return l().createElement(o.OverflowMenu,{"aria-label":a("searchHistoryOptions","Search history options"),size:"md",flipped:!0,direction:"top","data-testid":"options"},l().createElement(o.OverflowMenuItem,{className:eA,"data-testid":"save-cohort",itemText:a("saveCohort","Save cohort"),onClick:()=>i(e$)}),l().createElement(o.OverflowMenuItem,{className:eA,"data-testid":"save-query",itemText:a("saveQuery","Save query"),onClick:()=>i(eF)}),l().createElement(o.OverflowMenuItem,{className:eA,itemText:a("downloadResults","Download results"),onClick:()=>i(eM)}),l().createElement(o.OverflowMenuItem,{className:eA,"data-testid":"deleteFromHistory",hasDivider:!0,isDelete:!0,itemText:a("deleteFromHistory","Delete from history"),onClick:()=>i(eL)}))},eP=({isHistoryUpdated:e,setIsHistoryUpdated:t})=>{let{t:a}=(0,s.useTranslation)(),[i,c]=(0,n.useState)([]),[m,d]=(0,n.useState)(10),{results:u,currentPage:h,goTo:p}=(0,r.usePagination)(i,m);(0,n.useEffect)(()=>{if(e){let e,a;c((e=JSON.parse(window.sessionStorage.getItem("openmrsHistory")),a=[],e?.map((e,t)=>a.push({...e,id:(t+1).toString(),results:e.patients.length})),a)),t(!1)}},[e,t]);let b=[{key:"id",header:"#"},{key:"description",header:a("query","Query")},{key:"results",header:a("results","Results")}],g=()=>{window.sessionStorage.removeItem("openmrsHistory"),c([])},E=e=>{let t=[...i].filter((t,a)=>a!=i.indexOf(e));c(t),window.sessionStorage.setItem("openmrsHistory",JSON.stringify(t))};return l().createElement("div",{className:"-esm-cohort-builder__search-history-style__container___KJBMK"},l().createElement("div",{className:"-esm-cohort-builder__search-history-style__header___C-R7x"},l().createElement("p",{className:U},a("searchHistory","Search History")),i.length>0&&l().createElement(o.Button,{kind:"danger--tertiary",onClick:()=>{let e=(0,r.showModal)("clear-search-history-modal",{closeModal:()=>e(),onClearHistory:g,size:"sm"})}},a("clearSearchHistory","Clear search history"))),l().createElement(o.DataTable,{rows:u,headers:b,useZebraStyles:!0},({rows:e,headers:t,getTableProps:a,getHeaderProps:r,getRowProps:n})=>l().createElement(o.Table,a(),l().createElement(o.TableHead,null,l().createElement(o.TableRow,null,t.map(e=>l().createElement(o.TableHeader,r({header:e}),e.header)),l().createElement(o.TableHeader,{className:Q}))),l().createElement(o.TableBody,null,e.map((e,t)=>l().createElement(o.TableRow,n({row:e}),e.cells.map(e=>l().createElement(o.TableCell,{key:e.id},e.value)),l().createElement(o.TableCell,{className:z},l().createElement(eB,{searchItem:u[t],updateSearchHistory:E}))))))),i.length>10&&l().createElement(o.Pagination,{backwardText:a("previousPage","Previous page"),forwardText:a("nextPage","Next page"),itemsPerPageText:a("itemsPerPage","Items per page:"),onChange:({page:e,pageSize:t})=>{p(e),d(t)},page:h,pageSize:m,pageSizes:[10,20,30,40,50],size:"md",totalItems:i.length}),!i.length&&l().createElement(q,{displayText:a("data","data")}))},eR=({patients:e})=>{let[t,a]=(0,n.useState)(1),[r,i]=(0,n.useState)(10),[c,m]=(0,n.useState)(e),{t:d}=(0,s.useTranslation)();e!==c&&(m(e),a(1));let u=[{key:"identifier",header:d("openmrsId","OpenMRS ID")},{key:"name",header:d("name","Name")},{key:"age",header:d("age","Age")},{key:"gender",header:d("gender","Gender")}];return l().createElement("div",{className:"-esm-cohort-builder__search-results-table__container___y4+06"},l().createElement("p",{className:U},d("searchResults","Search Results")),l().createElement(o.DataTable,{rows:e,headers:u,useZebraStyles:!0},({rows:e,headers:a,getTableProps:n,getHeaderProps:s,getRowProps:i})=>l().createElement(o.Table,n(),l().createElement(o.TableHead,null,l().createElement(o.TableRow,null,a.map(e=>l().createElement(o.TableHeader,s({header:e}),e.header)))),l().createElement(o.TableBody,null,e.slice((t-1)*r).slice(0,r).map((e,t)=>l().createElement(o.TableRow,{...i({row:e}),key:t},e.cells.map((e,t)=>l().createElement(o.TableCell,{key:t},e.value))))))),e.length>10&&l().createElement(o.Pagination,{backwardText:d("previousPage","Previous page"),forwardText:d("nextPage","Next page"),itemsPerPageText:d("itemsPerPage","Items per page:"),onChange:({page:e,pageSize:t})=>{a(e),i(t)},page:t,pageSize:r,pageSizes:[10,20,30,40,50],size:"md",totalItems:e.length}),!e.length&&l().createElement(q,{displayText:d("data","data")}))};var eH=a(9785),eU=a(3285),eY=a(4476);let ez={featureName:"cohort-builder",moduleName:"@openmrs/esm-cohort-builder-app"},eQ=a(4767);function eV(){}let ej=(0,r.getSyncLifecycle)(()=>{let{t:e}=(0,s.useTranslation)(),[t,a]=(0,n.useState)([]),[i,c]=(0,n.useState)(!0),m="tablet"===(0,r.useLayoutType)(),u=(t,n)=>new Promise(l=>{a([]),v(t).then(({data:{rows:o}})=>{var s;let i,m;o.map(e=>{e.id=e.patientId.toString(),e.name=_(e.firstname,e.lastname)}),a(o),s=t.query,i=JSON.parse(window.sessionStorage.getItem("openmrsHistory")),m=[],m=i?[...i,{description:n,patients:o,parameters:s}]:[{description:n,patients:o,parameters:s}],window.sessionStorage.setItem("openmrsHistory",JSON.stringify(m)),(0,r.showSnackbar)({title:e("searchCompleted","Search completed"),kind:"success",isLowContrast:!0,subtitle:e("noOfResultsFound","{{count}} results found",{count:o.length})}),c(!0),l(!0)}).catch(t=>{(0,r.showSnackbar)({title:e("error","Error"),kind:"error",isLowContrast:!1,subtitle:t?.message}),l(!0)})}),h=async t=>{try{let n=await w(t);a(n),(0,r.showSnackbar)({title:e("searchCompleted","Search completed"),kind:"success",isLowContrast:!0,subtitle:e("noOfResultsFound","{{count}} results found",{count:n.length})})}catch(t){(0,r.showSnackbar)({title:e("error","Error"),kind:"error",isLowContrast:!1,subtitle:t?.message})}},p=async t=>{try{let{patients:n,total:l}=await C(t);a(n),n.length<l?(0,r.showSnackbar)({title:e("someCohortMembersNotShown","Some of the cohort's members could not be shown"),kind:"warning",isLowContrast:!0,subtitle:e("showingCohortMembers","Showing {{shown}} of {{count}} members",{shown:n.length,count:l})}):(0,r.showSnackbar)({title:e("searchCompleted","Search completed"),kind:"success",isLowContrast:!0,subtitle:e("noOfResultsFound","{{count}} results found",{count:n.length})})}catch(t){(0,r.showSnackbar)({title:e("error","Error"),kind:"error",isLowContrast:!1,subtitle:t instanceof f?e("cohortMembersLoadFailed","None of the cohort's members could be loaded"):t?.message})}},b=[{name:e("concepts","Concepts"),component:l().createElement(eg,{onSubmit:u})},{name:e("demographics","Demographics"),component:l().createElement(ev,{onSubmit:u})},{name:e("personAttributes","Person Attributes"),component:l().createElement(eD,{onSubmit:u})},{name:e("encounters","Encounters"),component:l().createElement(eT,{onSubmit:u})},{name:e("location","Location"),component:l().createElement(eI,{onSubmit:u})},{name:e("enrollments","Enrollments"),component:l().createElement(ek,{onSubmit:u})},{name:e("drugOrder","Drug Order"),component:l().createElement(ew,{onSubmit:u})},{name:e("composition","Composition"),component:l().createElement(A,{onSubmit:u})},{name:e("savedCohorts","Saved Cohorts"),component:l().createElement(j,{onViewCohort:p})},{name:e("savedQueries","Saved Queries"),component:l().createElement(ee,{onViewQuery:h})}];return l().createElement("div",null,l().createElement(r.PageHeader,{className:"-esm-cohort-builder__cohort-builder__header___VRsag"},l().createElement(r.PageHeaderContent,{illustration:l().createElement(r.CohortsPictogram,null),title:e("cohortBuilder","Cohort Builder")})),l().createElement("div",{className:d()("-esm-cohort-builder__cohort-builder__mainContainer___LXqCB","-esm-cohort-builder__cohort-builder__cohortBuilder___IqfBP")},l().createElement("div",{className:d()(m?"-esm-cohort-builder__cohort-builder__tabletContainer___7xD+u":"-esm-cohort-builder__cohort-builder__desktopContainer___I5sch")},l().createElement("div",{className:"-esm-cohort-builder__cohort-builder__tabContainer___u8YU-"},l().createElement("p",{className:U},e("searchCriteria","Search Criteria")),l().createElement("div",{className:Y},l().createElement(o.Tabs,null,l().createElement(o.TabList,{"aria-label":"navigation"},b.map((e,t)=>l().createElement(o.Tab,{className:Y,key:t},e.name))),l().createElement(o.TabPanels,null,b.map((e,t)=>l().createElement(o.TabPanel,{key:t},e.component)))))),l().createElement(eR,{patients:t}),l().createElement(eP,{isHistoryUpdated:i,setIsHistoryUpdated:c}))))},ez),eG=(0,r.getSyncLifecycle)(()=>{let{t:e}=(0,s.useTranslation)();return l().createElement(o.Layer,null,l().createElement(o.ClickableTile,{href:`${window.spaBase}/cohort-builder`},l().createElement("div",null,l().createElement("div",{className:"heading"},e("manageCohorts","Manage Cohorts")),l().createElement("div",{className:"content"},e("cohortBuilder","Cohort Builder"))),l().createElement("div",{className:"iconWrapper"},l().createElement(c.Qp,{size:16}))))},ez),eW=(0,r.getSyncLifecycle)(({closeModal:e,onRemove:t,searchItemName:a})=>{let{t:c}=(0,s.useTranslation)(),[m,d]=(0,n.useState)(!1);return l().createElement("div",null,l().createElement(o.ModalHeader,{closeModal:e,title:c("clearItemFromHistory","Clear item from search history")}),l().createElement(o.ModalBody,null,l().createElement("p",null,c("removeItemFromSearchHistory","Are you sure you want to remove this item from the search history?")),l().createElement("br",null),l().createElement("p",null,l().createElement("strong",null,'"',a,'"'))),l().createElement(o.ModalFooter,null,l().createElement(o.Button,{kind:"secondary",onClick:e},(0,r.getCoreTranslation)("cancel")),l().createElement(o.Button,{className:i,kind:"danger",onClick:()=>{d(!0),t(),d(!1),e()},disabled:m},m?l().createElement(o.InlineLoading,{description:c("removing","Removing")+"..."}):l().createElement("span",null,(0,r.getCoreTranslation)("delete")))))},ez),eX=(0,r.getSyncLifecycle)(({closeModal:e,onClearHistory:t,searchItemName:a})=>{let{t:c}=(0,s.useTranslation)(),[m,d]=(0,n.useState)(!1);return l().createElement("div",null,l().createElement(o.ModalHeader,{closeModal:e,title:c("clearSearchHistory","Clear search history")}),l().createElement(o.ModalBody,null,l().createElement("p",null,c("clearSearchHistoryModalText","Are you sure you want to clear the search history?"))),l().createElement(o.ModalFooter,null,l().createElement(o.Button,{kind:"secondary",onClick:e},(0,r.getCoreTranslation)("cancel")),l().createElement(o.Button,{className:i,disabled:m,kind:"danger",onClick:()=>{d(!0),t(),d(!1),e()}},m?l().createElement(o.InlineLoading,{description:c("clearing","Clearing")+"..."}):l().createElement("span",null,c("clearHistory","Clear history")))))},ez),eZ=(0,r.getSyncLifecycle)(({closeModal:e,cohortName:t,onDeleteCohort:a})=>{let{t:i}=(0,s.useTranslation)(),[c,m]=(0,n.useState)(!1);return l().createElement("div",null,l().createElement(o.ModalHeader,{closeModal:e,title:i("deleteCohort","Delete cohort")}),l().createElement(o.ModalBody,null,l().createElement("p",null,i("deleteCohortModalText","Are you sure you want to delete the cohort")," ",l().createElement("strong",null,'"',t,'"'),"?")),l().createElement(o.ModalFooter,null,l().createElement(o.Button,{kind:"secondary",onClick:e},(0,r.getCoreTranslation)("cancel")),l().createElement(o.Button,{className:"-esm-cohort-builder__delete-cohort__deleteButton___15Gkt",kind:"danger",onClick:()=>{m(!0),a(),m(!1),e()},disabled:c},c?l().createElement(o.InlineLoading,{description:i("deleting","Deleting")+"..."}):l().createElement("span",null,(0,r.getCoreTranslation)("delete")))))},ez),eJ=(0,r.getSyncLifecycle)(({closeModal:e,queryName:t,queryId:a,onDelete:i})=>{let{t:c}=(0,s.useTranslation)(),[m,d]=(0,n.useState)(!1),u=async()=>{d(!0),await i(a),d(!1),e()};return l().createElement("div",null,l().createElement(o.ModalHeader,{closeModal:e,title:c("deleteSavedQuery","Delete saved query")}),l().createElement(o.ModalBody,null,l().createElement("p",null,c("deleteSavedQueryConfirmation","Are you sure you want to delete this saved query?"))),l().createElement(o.ModalFooter,null,l().createElement(o.Button,{kind:"secondary",onClick:e},(0,r.getCoreTranslation)("cancel")),l().createElement(o.Button,{kind:"danger",onClick:u,disabled:m},m?l().createElement(o.InlineLoading,{description:c("deleting","Deleting")+"..."}):l().createElement("span",null,(0,r.getCoreTranslation)("delete")))))},ez),eK=(0,r.getSyncLifecycle)(({closeModal:e,onSave:t})=>{let{t:a}=(0,s.useTranslation)(),{control:n,handleSubmit:c,formState:{errors:m}}=(0,eH.mN)({resolver:(0,eU.u)(eY.z.object({name:eY.z.string({required_error:a("cohortNameRequired","Cohort name is required")}).trim().min(1,a("cohortNameRequired","Cohort name is required")),description:eY.z.string({required_error:a("cohortDescriptionRequired","Description is required")}).trim().min(1,a("cohortDescriptionRequired","Description is required"))})),mode:"onChange"}),d=a=>{t(a.name.trim(),a.description.trim()),e()};return l().createElement("div",null,l().createElement(o.ModalHeader,{closeModal:e,title:a("saveCohort","Save cohort")}),l().createElement(o.ModalBody,null,l().createElement("form",{onSubmit:c(d)},l().createElement(o.Stack,{gap:5},l().createElement(eH.xI,{name:"name",control:n,render:({field:e})=>l().createElement(o.TextInput,{"data-testid":"cohort-name",id:"cohort-name",labelText:a("enterCohortName","Enter a cohort name"),...e,invalid:!!m.name,invalidText:m.name?.message})}),l().createElement(eH.xI,{name:"description",control:n,render:({field:e})=>l().createElement(o.TextInput,{"data-testid":"cohort-description",id:"cohort-description",labelText:a("enterCohortDescription","Enter a cohort description"),...e,invalid:!!m.description,invalidText:m.description?.message})})))),l().createElement(o.ModalFooter,null,l().createElement(o.Button,{kind:"secondary",onClick:e},(0,r.getCoreTranslation)("cancel")),l().createElement(o.Button,{className:i,kind:"danger",onClick:c(d)},l().createElement("span",null,(0,r.getCoreTranslation)("save")))))},ez),e0=(0,r.getSyncLifecycle)(({closeModal:e,onSaveQuery:t})=>{let{t:a}=(0,s.useTranslation)(),{control:n,handleSubmit:c,formState:{errors:m,isSubmitting:d}}=(0,eH.mN)({resolver:(0,eU.u)(eY.z.object({queryName:eY.z.string({required_error:a("queryNameRequired","Name is required")}).min(1,a("queryNameRequired","Name is required")),queryDescription:eY.z.string({required_error:a("queryDescriptionRequired","Description is required")}).min(1,a("queryDescriptionRequired","Description is required"))})),defaultValues:{queryName:"",queryDescription:""}}),u=async a=>{await t(a),e()};return l().createElement("div",null,l().createElement(o.ModalHeader,{closeModal:e,title:a("saveQuery","Save query")}),l().createElement("form",{onSubmit:c(u)},l().createElement(o.ModalBody,null,l().createElement(o.Stack,{gap:5},l().createElement(eH.xI,{name:"queryName",control:n,render:({field:e})=>l().createElement(o.TextInput,{...e,labelText:a("enterQueryName","Enter a name for the query"),id:"query-name","data-testid":"query-name",invalid:!!m.queryName,invalidText:m.queryName?.message})}),l().createElement(eH.xI,{name:"queryDescription",control:n,render:({field:e})=>l().createElement(o.TextInput,{...e,labelText:a("enterQueryDescription","Enter a description of the query"),id:"query-description",invalid:!!m.queryDescription,invalidText:m.queryDescription?.message})}))),l().createElement(o.ModalFooter,null,l().createElement(o.Button,{kind:"secondary",onClick:e},(0,r.getCoreTranslation)("cancel")),l().createElement(o.Button,{className:i,disabled:d,kind:"primary",type:"submit"},d?l().createElement(o.InlineLoading,{description:a("saving","Saving")+"..."}):l().createElement("span",null,(0,r.getCoreTranslation)("save"))))))},ez)}}]);
1
+ (globalThis.webpackChunk_openmrs_esm_cohort_builder_app=globalThis.webpackChunk_openmrs_esm_cohort_builder_app||[]).push([["111"],{4767(e,t,a){var r={"./en.json":["4300","117"]};function s(e){if(!a.o(r,e))return Promise.resolve().then(function(){var t=Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t});var t=r[e],s=t[0];return a.e(t[1]).then(function(){return a(s)})}s.keys=()=>Object.keys(r),s.id=4767,e.exports=s},5930(e,t,a){"use strict";a.r(t),a.d(t,{cohortBuilder:()=>eV,clearSearchHistoryModal:()=>eX,saveCohortModal:()=>eK,importTranslation:()=>ez,deleteQueryModal:()=>eJ,cohortBuilderAdminPageCardLink:()=>eG,deleteCohortModal:()=>eZ,clearItemFromSearchHistoryModal:()=>eW,startupApp:()=>eQ,saveQueryModal:()=>e0});var r=a(2388),s=a(6390),n=a(4923),i=a(9536),o=a(202);let l="-esm-cohort-builder__modals__deleteButton___wIYdW";var d=a(2137),c=a(6942),u=a.n(c);let m=e=>{let t={type:"org.openmrs.module.reporting.dataset.definition.PatientDataSetDefinition",columns:[],rowFilters:[],customRowFilterCombination:""};t.columns=x();let a=0;for(let r in t.rowFilters=[],e){if(h(e[r])){delete e[r];continue}"all"!=e[r]&&""!=e&&(t.rowFilters[a]={},t.rowFilters[a].key=p(r,e[r])),Array.isArray(e[r])&&(t.rowFilters[a].parameterValues=b(e[r])),e[r].length>=1&&"alive"===e[r][0].livingStatus&&(t.rowFilters[a].livingStatus="alive"),t.rowFilters[a].type="org.openmrs.module.reporting.dataset.definition.PatientDataSetDefinition",a+=1}return t.customRowFilterCombination=g(t.rowFilters),{query:t}},h=e=>Array.isArray(e)&&e.length>=1?!e[0].value:"all"===e||!e,p=(e,t)=>{let a="reporting.library.cohortDefinition.builtIn";return"gender"===e?a+=`.${t}`:a+=`.${e}`,a},b=e=>{let t={};return e.forEach(e=>{t[e.name]=e.value}),t},g=e=>{let t="",a=e.length;for(let r=1;r<=a;r++)"alive"===e[r-1].livingStatus?(t+=`NOT ${r}`,delete e[r-1].livingStatus):t+=`${r}`,t+=r<a?" AND ":"";return t},x=()=>[{name:"firstname",key:"preferredName.givenName"},{name:"lastname",key:"preferredName.familyName"},{name:"gender",key:"gender"},{name:"age",key:"ageOnDate.fullYears"},{name:"patientId",key:"patientId"},{name:"identifier",key:"preferredIdentifier.identifier"}].map(e=>(e.type="org.openmrs.module.reporting.data.patient.definition.PatientDataDefinition",e.key=`reporting.library.patientDataDefinition.builtIn.${e.key}`,e)),_=(...e)=>e.filter(Boolean).join(" "),y=e=>{let t=new Date(e),a=t.getDate(),r=t.getMonth()+1,s=t.getFullYear();return`${a}/${r}/${s}`},v=async e=>await (0,r.openmrsFetch)(`${r.restBaseUrl}/reportingrest/adhocquery?v=full`,{method:"POST",headers:{"Content-Type":"application/json"},body:e.query}),j=()=>{let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/location`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,locations:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),locationsError:t}},S=async e=>(await (0,r.openmrsFetch)(`${r.restBaseUrl}/reportingrest/dataSet/${e}`,{method:"GET"})).data.rows.map(e=>(e.id=e.patientId?.toString()??"",e.name=_(e.firstname,e.lastname),e));class w extends Error{constructor(){super("None of the cohort's members could be loaded"),this.name="CohortMembersLoadError"}}let f=async e=>{let t=await C(e),a=new Date,r=t.filter(e=>(function({voided:e,startDate:t,endDate:a},r){return!e&&(!t||new Date(t)<=r)&&(!a||new Date(a)>=r)})(e,a)).map(e=>e.patientUuid),s=(await N(r,6,T)).filter(Boolean);if(r.length>0&&0===s.length)throw new w;return{patients:s,total:r.length}};async function C(e){let t=new Map;for(let a=0;a<1e3;a++){let{data:a}=await (0,r.openmrsFetch)(`${r.restBaseUrl}/cohort/${e}/membership?v=custom:(uuid,patientUuid,startDate,endDate,voided)&limit=100&startIndex=${t.size}`),s=t.size;if(a.results.forEach(e=>t.set(e.uuid,e)),!a.links?.some(e=>"next"===e.rel)||t.size===s)break}return[...t.values()]}async function T(e){try{let{data:{patientId:t,person:a,identifiers:s}}=await (0,r.openmrsFetch)(`${r.restBaseUrl}/patient/${e}?v=custom:(patientId,person:(gender,age,preferredName:(givenName,familyName)),identifiers:(identifier,preferred))`);if(!a?.preferredName)return null;let{givenName:n,familyName:i}=a.preferredName,o=s?.find(({preferred:e})=>e)?.identifier??"";return{id:t.toString(),patientId:t,identifier:o,name:_(n,i),firstname:n,lastname:i,age:a.age,gender:a.gender}}catch{return null}}async function N(e,t,a){let r=[],s=0,n=async()=>{for(;s<e.length;){let t=s++;r[t]=await a(e[t])}};return await Promise.all(Array.from({length:Math.min(t,e.length)},n)),r}let k=e=>e.replace(/([()])/g," $1 ").trim().split(/\s+/),I="-esm-cohort-builder__search-button-set__button___tg6-2",D=({isLoading:e,isSearchDisabled:t,onHandleSubmit:a,onHandleReset:r})=>{let{t:n}=(0,o.useTranslation)();return(0,s.jsx)(i.Column,{sm:2,md:{offset:4},className:"-esm-cohort-builder__search-button-set__container___jIXOL",children:(0,s.jsxs)(i.ButtonSet,{className:"-esm-cohort-builder__search-button-set__buttonSet___itc+A",children:[(0,s.jsx)(i.Button,{className:I,kind:"secondary",onClick:r,"data-testid":"reset-btn",children:n("reset","Reset")}),(0,s.jsx)(i.Button,{className:I,kind:"primary",disabled:e||t,onClick:a,"data-testid":"search-btn",children:e?(0,s.jsx)(i.InlineLoading,{description:n("loading","Loading")}):n("search","Search")})]})})},O="-esm-cohort-builder__composition-style__text___YdbOd",E=({onSubmit:e})=>{let{t}=(0,o.useTranslation)(),[a,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(""),[u,m]=(0,n.useState)(""),h=async()=>{l(!0);try{if(k(d).every(e=>/^(and|or|not|union|intersection|\d+|[()])$/i.test(e))){let t,a=(t={type:"org.openmrs.module.reporting.dataset.definition.PatientDataSetDefinition",columns:x(),rowFilters:[],customRowFilterCombination:""},k(d).forEach(e=>{if(e.match(/\d/)){let a,r,s=JSON.parse(window.sessionStorage.getItem("openmrsHistory"))[parseInt(e)-1].parameters;a=s.customRowFilterCombination,r=t.rowFilters.length,s.customRowFilterCombination=a.replace(/\d+/g,e=>(parseInt(e)+r).toString()),t.customRowFilterCombination+=`(${s.customRowFilterCombination})`,t.rowFilters=t.rowFilters.concat(s.rowFilters)}else t.customRowFilterCombination+=` ${e} `}),{query:t});await e(a,u)}else(0,r.showSnackbar)({title:t("error","Error!"),kind:"error",isLowContrast:!0,subtitle:t("invalidComposition","Composition is not valid")});l(!1)}catch(e){l(!1),(0,r.showSnackbar)({title:t("error","Error!"),kind:"error",isLowContrast:!0,subtitle:t("invalidComposition","Composition is not valid")})}};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(i.TextInput,{labelText:t("composition","Composition"),"data-testid":"composition-query",id:"composition-query",onChange:e=>{var t;c(t=e.target.value),m("Composition of "+t)},value:d}),(0,s.jsx)("br",{}),(0,s.jsx)(i.TextInput,{labelText:t("description","Description"),"data-testid":"composition-description",id:"composition-description",onChange:e=>m(e.target.value),value:u}),(0,s.jsx)("br",{}),(0,s.jsx)("p",{className:O,children:t("compositionExplanationOne","A composition query combines together the results of multiple cohorts using the logical operators: AND, OR and NOT.")}),(0,s.jsx)("br",{}),(0,s.jsx)("p",{className:O,children:t("compositionExplanationTwo","To use this query you need to already have query results in your search history. Those existing query results can then be combined to yield the results of the composition query.")}),(0,s.jsx)("br",{}),(0,s.jsx)("p",{className:O,children:t("compositionExplanationThree","Example: if the search history #1 is a cohort of patients who are males, and if the search history #2 is a cohort of patients with ages between 23 and 35 years; then '1 AND 2' will result in a cohort of patients who are males with ages between 23 and 35 years.")}),(0,s.jsx)("br",{}),(0,s.jsx)(D,{onHandleReset:()=>{m(""),c("")},onHandleSubmit:h,isLoading:a})]})};var A=a(2551),L=a.n(A);let M=`${r.restBaseUrl}/cohort?v=full`,$=async e=>await (0,r.openmrsFetch)(`${r.restBaseUrl}/cohort/${e}`,{method:"DELETE"}),F=e=>(0,s.jsx)(i.Layer,{children:(0,s.jsxs)(i.Tile,{className:"-esm-cohort-builder__empty-data-style__tile___kGzLZ",children:[(0,s.jsx)(r.EmptyCardIllustration,{}),(0,s.jsxs)("p",{className:"-esm-cohort-builder__empty-data-style__content___zUidZ",children:["There are no ",e.displayText.toLowerCase()," to display"]})]})}),q="-esm-cohort-builder__saved-cohort-options__menuItem___rX2ia",B="view",P="delete",R=({cohort:e,onViewCohort:t,onDeleteCohort:a})=>{let{t:n}=(0,o.useTranslation)(),l=async()=>{try{await t(e.id)}catch(e){(0,r.showSnackbar)({title:n("cohortViewError","Error viewing the cohort"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},d=async t=>{switch(t){case B:l();break;case P:c(e.id)}},c=t=>{let a=(0,r.showModal)("delete-cohort-modal",{closeModal:()=>a(),cohortName:e.name,cohortId:t,onDeleteCohort:u,size:"sm"})},u=async()=>{await a(e.id)};return(0,s.jsxs)(i.OverflowMenu,{"aria-label":n("savedCohortsOptions","Saved cohorts options"),flipped:!0,direction:"bottom","data-testid":"options",children:[(0,s.jsx)(i.OverflowMenuItem,{className:q,"data-testid":"view",itemText:n("view","View"),onClick:()=>d(B)}),(0,s.jsx)(i.OverflowMenuItem,{className:q,"data-testid":"delete",hasDivider:!0,isDelete:!0,itemText:n("delete","Delete"),onClick:()=>d(P)})]})},H="-esm-cohort-builder__cohort-builder__heading___fKg4I",U="-esm-cohort-builder__cohort-builder__tab___OIkeX",Y="-esm-cohort-builder__cohort-builder__optionCell___0dfgH",z="-esm-cohort-builder__cohort-builder__optionHeader___IBQGc",Q="-esm-cohort-builder__cohort-builder__text___Dk0eN",V=({onViewCohort:e})=>{let{t}=(0,o.useTranslation)(),[a,l]=(0,n.useState)(10),{cohorts:d,error:c,isLoading:u,mutate:m}=function(){let{data:e,error:t,isLoading:a,isValidating:s,mutate:i}=L()(M,r.openmrsFetch);return{cohorts:(0,n.useMemo)(()=>e?.data?.results?.map(e=>({id:e.uuid,name:e.name,description:e.description})),[e])??[],error:t,isLoading:a,isValidating:s,mutate:i}}(),{results:h,currentPage:p,goTo:b}=(0,r.usePagination)(d,a),g=[{key:"name",header:t("name","Name")},{key:"description",header:t("description","Description")}],x=async e=>{try{await $(e),(0,r.showSnackbar)({title:t("cohortDeleted","Cohort deleted"),kind:"success",isLowContrast:!0,subtitle:t("cohortDeleted","Cohort deleted")}),await m()}catch(e){(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:e?.message})}};return(0,s.jsxs)("div",{className:"-esm-cohort-builder__saved-cohorts__container___RcI67",children:[(0,s.jsx)("p",{className:Q,children:t("savedCohortDescription","You can only search for Cohort Definitions that you have saved using a Name.")}),c&&(0,s.jsx)(i.InlineNotification,{kind:"error",lowContrast:!0,hideCloseButton:!0,title:t("errorLoadingCohorts","Error loading saved cohorts"),subtitle:c.message}),u?(0,s.jsx)(i.DataTableSkeleton,{headers:g,rowCount:3,showHeader:!1,showToolbar:!1}):!c||d.length>0?(0,s.jsx)(i.DataTable,{rows:h,headers:g,useZebraStyles:!0,children:({rows:t,headers:a,getTableProps:r,getHeaderProps:o,getRowProps:l})=>(0,s.jsxs)(i.Table,{...r(),children:[(0,s.jsx)(i.TableHead,{children:(0,s.jsxs)(i.TableRow,{children:[a.map(e=>(0,s.jsx)(i.TableHeader,{...o({header:e}),children:e.header})),(0,s.jsx)(i.TableHeader,{className:z})]})}),(0,s.jsx)(i.TableBody,{children:t.map((t,a)=>(0,n.createElement)(i.TableRow,{...l({row:t}),key:a,children:[t.cells.map((e,t)=>(0,s.jsx)(i.TableCell,{children:e.value},t)),(0,s.jsx)(i.TableCell,{className:Y,children:(0,s.jsx)(R,{cohort:h[a],onViewCohort:e,onDeleteCohort:x})})]}))})]})}):null,d?.length>10&&(0,s.jsx)(i.Pagination,{backwardText:t("previousPage","Previous page"),forwardText:t("nextPage","Next page"),itemsPerPageText:t("itemsPerPage","Items per page:"),onChange:({page:e,pageSize:t})=>{b(e),l(t)},page:p,pageSize:a,pageSizes:[10,20,30,40,50],size:"md",totalItems:d.length}),!u&&!c&&!d?.length&&(0,s.jsx)(F,{displayText:t("cohorts","cohorts")})]})},G=`${r.restBaseUrl}/reportingrest/dataSetDefinition?v=full`,W=async e=>await (0,r.openmrsFetch)(`${r.restBaseUrl}/reportingrest/adhocdataset/${e}?purge=true`,{method:"DELETE"}),X="-esm-cohort-builder__saved-queries-options__menuItem___Qs6Ro",Z="delete",J="view",K=({query:e,onViewQuery:t,deleteQuery:a})=>{let{t:n}=(0,o.useTranslation)(),l=async e=>{switch(e){case J:d();break;case Z:c()}},d=async()=>{try{await t(e.id)}catch(e){(0,r.showSnackbar)({title:n("QueryDeleteError","Something went wrong"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},c=()=>{let t=(0,r.showModal)("delete-query-modal",{closeModal:()=>t(),queryName:e.name,queryId:e.id,onDelete:u,size:"sm"})},u=async()=>{await a(e.id)};return(0,s.jsxs)(i.OverflowMenu,{"aria-label":n("savedQueriesOptions","Saved queries options"),size:"md",flipped:!0,direction:"bottom",children:[(0,s.jsx)(i.OverflowMenuItem,{className:X,"data-testid":"view",itemText:n("view","View"),onClick:()=>l(J)}),(0,s.jsx)(i.OverflowMenuItem,{className:X,"data-testid":"delete",hasDivider:!0,isDelete:!0,itemText:n("delete","Delete"),onClick:()=>l(Z)})]})},ee=({onViewQuery:e})=>{let{t}=(0,o.useTranslation)(),[a,l]=(0,n.useState)(10),{queries:d,error:c,isLoading:u,mutate:m}=function(){let{data:e,error:t,isLoading:a,mutate:s}=L()(G,r.openmrsFetch);return{queries:(0,n.useMemo)(()=>e?.data?.results?.map(e=>({id:e.uuid,name:e.name.replace("[AdHocDataExport]",""),description:e.description})),[e])??[],error:t,isLoading:a,mutate:s}}(),{results:h,currentPage:p,goTo:b}=(0,r.usePagination)(d,a),g=async e=>{try{await W(e),(0,r.showSnackbar)({title:t("success","Success"),kind:"success",isLowContrast:!0,subtitle:t("queryIsDeleted","the query is deleted")}),await m()}catch(e){(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:e?.message})}},x=[{key:"name",header:t("name","Name")},{key:"description",header:t("description","Description")}];return(0,s.jsxs)("div",{className:"-esm-cohort-builder__saved-queries__container___apr+8",children:[(0,s.jsx)("p",{className:Q,children:t("savedQueryDescription","You can only search for Query Definitions that you have saved using a Name.")}),c&&(0,s.jsx)(i.InlineNotification,{kind:"error",lowContrast:!0,hideCloseButton:!0,title:t("errorLoadingQueries","Error loading saved queries"),subtitle:c.message}),u?(0,s.jsx)(i.DataTableSkeleton,{headers:x,rowCount:3,showHeader:!1,showToolbar:!1}):!c||d.length>0?(0,s.jsx)(i.DataTable,{rows:h,headers:x,useZebraStyles:!0,children:({rows:t,headers:a,getTableProps:r,getHeaderProps:o,getRowProps:l})=>(0,s.jsxs)(i.Table,{...r(),children:[(0,s.jsx)(i.TableHead,{children:(0,s.jsxs)(i.TableRow,{children:[a.map(e=>(0,s.jsx)(i.TableHeader,{...o({header:e}),children:e.header})),(0,s.jsx)(i.TableHeader,{className:z})]})}),(0,s.jsx)(i.TableBody,{children:t.map((t,a)=>(0,n.createElement)(i.TableRow,{...l({row:t}),key:a,children:[t.cells.map((e,t)=>(0,s.jsx)(i.TableCell,{children:e.value},t)),(0,s.jsx)(i.TableCell,{className:Y,children:(0,s.jsx)(K,{query:h[a],onViewQuery:e,deleteQuery:g})})]}))})]})}):null,d.length>10&&(0,s.jsx)(i.Pagination,{backwardText:t("previousPage","Previous page"),forwardText:t("nextPage","Next page"),itemsPerPageText:t("itemsPerPage","Items per page:"),onChange:({page:e,pageSize:t})=>{b(e),l(t)},page:p,pageSize:a,pageSizes:[10,20,30,40,50],size:"md",totalItems:d.length}),!u&&!c&&!d.length&&(0,s.jsx)(F,{displayText:t("queries","queries")})]})};var et=a(4353),ea=a.n(et),er=a(4861);async function es(e){let t=await (0,r.openmrsFetch)(`${r.restBaseUrl}/concept?v=full&q=${encodeURIComponent(e)}`,{method:"GET"}),a=[];return t.data.results.length>0&&(a=t.data.results.map(e=>{let t=e.descriptions.filter(e=>"en"==e.locale?e.description:"");return{uuid:e.uuid,units:e.units||"",answers:e.answers,hl7Abbrev:e.datatype.hl7Abbreviation,name:e.name.name,description:t.length>0?t[0].description:"no description available",datatype:e.datatype}})),a}let en={searchContainer:"-esm-cohort-builder__search-concept__searchContainer___dpJim",search:"-esm-cohort-builder__search-concept__search___9eq8D",loader:"-esm-cohort-builder__search-concept__loader___RvR4m",concept:"-esm-cohort-builder__search-concept__concept___WbcYA",conceptList:"-esm-cohort-builder__search-concept__conceptList___XqGdL",text:"-esm-cohort-builder__search-concept__text___Ow696",notification:"-esm-cohort-builder__search-concept__notification___x7E6s"},ei=({concept:e,searchText:t,setConcept:a,setSearchText:r})=>{let{t:l}=(0,o.useTranslation)(),[d,c]=(0,n.useState)([]),[u,m]=(0,n.useState)(""),[h,p]=(0,n.useState)(!1),[b,g]=(0,n.useState)(!1),x=async e=>{c([]),a(null),p(!0),g(!1);try{let t=await es(e);t.length?c(t):g(!0),p(!1)}catch(e){m(e.toString()),p(!1)}},_=(0,n.useRef)((0,er.A)(async e=>{e&&await x(e)},500)).current;return(0,n.useEffect)(()=>()=>{_.cancel()},[_]),(0,s.jsx)("div",{children:(0,s.jsxs)(i.Column,{className:en.column,children:[(0,s.jsxs)("div",{className:en.searchContainer,children:[(0,s.jsx)(i.Search,{closeButtonLabelText:l("clearSearch","Clear search"),id:"concept-search",labelText:l("searchConcepts","Search Concepts"),onChange:e=>{r(e.target.value),_(e.target.value)},onClear:()=>{g(!1),c([])},placeholder:l("searchConcepts","Search Concepts"),value:t}),(0,s.jsx)("div",{className:en.search,children:h?(0,s.jsx)(i.InlineLoading,{className:en.loader,description:l("searching","Searching")+"..."}):(0,s.jsx)("ul",{className:en.conceptList,children:d?.map((e,t)=>(0,s.jsx)("li",{role:"menuitem",className:en.concept,onClick:()=>{a(e),c([]),g(!1)},children:e.name},t))})})]}),e&&(0,s.jsxs)("span",{className:en.text,children:[l("patientsWithObservationsWhoseAnswerIs","Patients with observations whose answer is"),(0,s.jsxs)("strong",{children:[' "',e.name,'"']}),"."]}),t&&b&&(0,s.jsx)(i.Tile,{children:(0,s.jsxs)("span",{children:[l("noMatchingConcepts","No concepts were found that match"),(0,s.jsxs)("strong",{children:[' "',t,'"']}),"."]})}),u&&(0,s.jsx)("span",{children:u})]})})};var eo=a(445),el=a.n(eo);ea().extend(el());let ed=e=>{let t=ea()(e.trim(),["DD-MM-YYYY","D-MM-YYYY","DD-M-YYYY","D-M-YYYY"],!0);return!!t.isValid()&&t.toDate()},ec=({id:e,labelText:t,value:a,onChange:r})=>{let n=(e,t,{selectedDates:[a]})=>r(a?ea()(a).format():"");return(0,s.jsx)(i.DatePicker,{dateFormat:"d-m-Y",datePickerType:"single",parseDate:ed,onChange:n,onClose:n,value:a&&ea()(a).format("DD-MM-YYYY"),children:(0,s.jsx)(i.DatePickerInput,{id:e,labelText:t,placeholder:"DD-MM-YYYY",size:"md",onChange:e=>!e.target.value&&r(""),onKeyDownCapture:e=>{if("Tab"===e.key){let t=e.currentTarget;t._flatpickr?.setDate(ed(t.value)||"",!0)}}})})},eu="-esm-cohort-builder__search-by-concepts-style__column___fpjOs",em="-esm-cohort-builder__search-by-concepts-style__dateRange___unfDl",eh="-esm-cohort-builder__search-by-concepts-style__multipleInputs___O7iAI",ep=[{id:0,label:"<",value:"LESS_THAN"},{id:1,label:"<=",value:"LESS_EQUAL"},{id:2,label:"=",value:"EQUAL"},{id:3,label:">=",value:"GREATER_EQUAL"},{id:4,label:">",value:"GREATER_THAN"}],eb={CWE:"codedObsSearchAdvanced",NM:"numericObsSearchAdvanced",DT:"dateObsSearchAdvanced",ST:"dateObsSearchAdvanced",TS:"textObsSearchAdvanced",ZZ:"codedObsSearchAdvanced",BIT:"codedObsSearchAdvanced"},eg=({onSubmit:e})=>{let{t}=(0,o.useTranslation)(),[a,r]=(0,n.useState)(null),[l,d]=(0,n.useState)(0),[c,u]=(0,n.useState)(0),[h,p]=(0,n.useState)(""),[b,g]=(0,n.useState)("LESS_THAN"),[x,_]=(0,n.useState)("ANY"),[v,j]=(0,n.useState)(""),[S,w]=(0,n.useState)(""),[f,C]=(0,n.useState)(""),[T,N]=(0,n.useState)(!1),k=[{id:"option-0",label:t("haveObservations","Patients who have these observations"),value:"ANY"},{id:"option-1",label:t("haveNoObservations","Patients who do not have these observations"),value:"NO"}],I=[{id:"option-0",label:t("any","Any"),value:"ANY"},{id:"option-1",label:t("none","None"),value:"NO"},{id:"option-2",label:t("earliest","Earliest"),value:"FIRST"},{id:"option-3",label:t("recent","Most Recent"),value:"LAST"},{id:"option-4",label:t("lowest","Lowest"),value:"MIN"},{id:"option-5",label:t("highest","Highest"),value:"MAX"},{id:"option-6",label:t("average","Average"),value:"AVG"}],O=a?.hl7Abbrev==="NM",E=O?I:k,A=E.find(({value:e})=>e===x)??E[0],L=async()=>{if(!a)return;N(!0);let t={modifier:"",operator1:O?b:"",value1:O&&""!==h?h.toString():"",question:a.uuid,onOrBefore:(()=>{if(l>0||c>0)return ea()().subtract(l,"days").subtract(c,"months").format()})()||S,onOrAfter:v,timeModifier:A.value},r=eb[a.hl7Abbrev],s={[r]:[]};Object.keys(t).forEach(e=>{""!==t[e]&&s[r].push({name:"modifier"===e?["CWE","TS"].includes(a.hl7Abbrev)?"values":"value1":e,value:"modifier"===e&&["CWE","TS"].includes(a.hl7Abbrev)?[t[e]]:t[e]})}),await e(m(s),((e,t)=>{let{timeModifier:a,onOrAfter:r,onOrBefore:s}=e,n=r?`since ${y(r)}`:"",i=s?`until ${y(s)}`:"";return`Patients with ${a} ${t} ${n} ${i}`.trim()})(t,a.name)),N(!1)};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(ei,{setConcept:r,concept:a,searchText:f,setSearchText:C}),O?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(i.Column,{className:eu,children:(0,s.jsx)("div",{style:{display:"flex"},children:(0,s.jsxs)("div",{className:eh,children:[(0,s.jsx)("p",{style:{paddingRight:20},children:t("whatObservations","What observations")}),(0,s.jsx)(i.Dropdown,{id:"timeModifier",onChange:e=>_(e.selectedItem.value),selectedItem:A,items:I,className:"-esm-cohort-builder__search-by-concepts-style__timeModifier___SeThC",label:"",titleText:""})]})})}),(0,s.jsxs)(i.Column,{className:eu,children:[(0,s.jsx)("p",{className:"-esm-cohort-builder__search-by-concepts-style__value___FUIbI",children:t("whatValues","What values")}),(0,s.jsxs)("div",{className:"-esm-cohort-builder__search-by-concepts-style__whatValuesInputs___5UXAP",children:[(0,s.jsx)("div",{className:"-esm-cohort-builder__search-by-concepts-style__operators___KUi3k",children:(0,s.jsx)(i.ContentSwitcher,{selectedIndex:ep.findIndex(({value:e})=>e===b),className:"-esm-cohort-builder__search-by-concepts-style__contentSwitcher___LXxCi",size:"lg",onChange:({index:e})=>g(ep[e].value),children:ep.map(e=>(0,s.jsx)(i.Switch,{name:e.value,text:e.label},e.id))})}),(0,s.jsx)("div",{className:eh,children:(0,s.jsx)(i.NumberInput,{allowEmpty:!0,hideSteppers:!0,id:"operator-value",invalidText:t("numberIsNotValid","Number is not valid"),label:t("valueIn","Enter a value in ")+a.units,min:0,size:"sm",value:h,onChange:(e,{value:t})=>p(""===t?"":Number(t))})})]})]})]}):(0,s.jsx)(i.Column,{className:eu,children:(0,s.jsx)(i.Dropdown,{id:"timeModifier","data-testid":"timeModifier",onChange:e=>_(e.selectedItem.value),selectedItem:A,items:k,label:"",titleText:""})}),(0,s.jsxs)(i.Column,{className:em,children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)(i.NumberInput,{hideSteppers:!0,id:"last-months","data-testid":"last-months",label:t("withinTheLast","Within the last months"),invalidText:t("numberIsNotValid","Number is not valid"),min:0,value:c,onChange:(e,{value:t})=>u(Number(t))})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)(i.NumberInput,{hideSteppers:!0,label:t("lastDays","and / or days"),id:"last-days","data-testid":"last-days",invalidText:t("numberIsNotValid","Number is not valid"),min:0,value:l,onChange:(e,{value:t})=>d(Number(t))})})]}),(0,s.jsxs)("div",{className:em,children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"startDate",labelText:t("dateRange","Date range start date"),value:v,onChange:j})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"endDate",labelText:t("endDate","End date"),value:S,onChange:w})})]})]}),(0,s.jsx)(D,{isLoading:T,onHandleSubmit:L,onHandleReset:()=>{r(null),d(0),C(""),j(""),w(""),u(0),p(""),g("LESS_THAN"),_("ANY")}})]})},ex="-esm-cohort-builder__search-by-demographics-style__contentSwitcher___L5GhV",e_="-esm-cohort-builder__search-by-demographics-style__column___agceq",ey="-esm-cohort-builder__search-by-demographics-style__switch___Q01uO",ev=({onSubmit:e})=>{let{t}=(0,o.useTranslation)(),[a,r]=(0,n.useState)("alive"),[l,d]=(0,n.useState)("all"),[c,h]=(0,n.useState)(""),[p,b]=(0,n.useState)(""),[g,x]=(0,n.useState)(0),[_,y]=(0,n.useState)(0),[v,j]=(0,n.useState)(!1),S=[{id:0,label:t("all","All"),value:"all"},{id:1,label:t("males","Male"),value:"males"},{id:3,label:t("females","Female"),value:"females"}],w=[{id:0,label:t("alive","Alive"),value:"alive"},{id:1,label:t("dead","Dead"),value:"dead"}],f=async()=>{j(!0);let t={gender:l,minAge:g,maxAge:_,birthDayStartDate:c,birthDayEndDate:p,livingStatus:a};await e((({gender:e,minAge:t,maxAge:a,birthDayStartDate:r,birthDayEndDate:s,livingStatus:n})=>{let i={gender:e};t&&a?i.ageRangeOnDate=[{name:"minAge",value:t},{name:"maxAge",value:a}]:t?i.atLeastAgeOnDate=[{name:"minAge",value:t}]:i.upToAgeOnDate=[{name:"maxAge",value:a}],r&&s&&(i.bornDuringPeriod=[{name:"startDate",dataType:"date",value:r},{name:"endDate",dataType:"date",value:s}]),i.diedDuringPeriod=[{name:"endDate",dataType:"date",value:ea()().format(),livingStatus:n}];let o=m(i);if("all"===i.gender){let e=["males","females","unknownGender"].map(e=>({type:"org.openmrs.module.reporting.dataset.definition.PatientDataSetDefinition",key:`reporting.library.cohortDefinition.builtIn.${e}`})),{query:{rowFilters:t,customRowFilterCombination:a}}=o,r=t=t.length>0?[...t,...e]:e,s=a;a=s?`(${r.length-2} OR ${r.length-1} OR ${r.length}) AND ${s}`:"(1 OR 2 OR 3)"}return o})(t),(({gender:e,minAge:t,maxAge:a,birthDayStartDate:r,birthDayEndDate:s,livingStatus:n})=>{let i="all"!=e?`${"males"===e?"Male":"Female"} Patients`:"All Patients";return(t||a)&&(t&&a?i+=` with ages between ${t} and ${a}`:i+=t?` with minimum age of ${t}`:` with maximum age of ${a}`,i+=" years"),(""!=r||""!=s)&&(r&&s?i+=` and birthdate between ${r} and ${s}`:i+=t?` and born before ${r}`:` and born before ${s}`),n&&(i+=` that are ${n}`),i})(t)),j(!1)};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)(i.Column,{children:[(0,s.jsx)("p",{className:u()("-esm-cohort-builder__search-by-demographics-style__text___x8MO2","-esm-cohort-builder__search-by-demographics-style__genderTitle___06Nb4"),children:t("gender","Gender")}),(0,s.jsxs)("div",{className:"-esm-cohort-builder__search-by-demographics-style__genderContainer___VkE-3",children:[(0,s.jsx)("div",{className:ey,children:(0,s.jsx)(i.ContentSwitcher,{selectedIndex:S.findIndex(({value:e})=>e===l),className:ex,size:"lg",onChange:({index:e})=>d(S[e].value),children:S.map(e=>(0,s.jsx)(i.Switch,{"data-testid":e.label,name:e.value,text:e.label},e.id))})}),(0,s.jsx)("div",{className:ey,children:(0,s.jsx)(i.ContentSwitcher,{selectedIndex:w.findIndex(({value:e})=>e===a),className:ex,size:"lg",onChange:({index:e})=>r(w[e].value),children:w.map(e=>(0,s.jsx)(i.Switch,{name:e.value,text:e.label},e.id))})})]})]}),(0,s.jsx)("div",{className:e_,children:(0,s.jsxs)(i.Column,{className:"-esm-cohort-builder__search-by-demographics-style__age___DEuDD",children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)(i.NumberInput,{"data-testid":"minAge",hideSteppers:!0,id:"minAge",invalidText:t("minAgeIsNotValid","The age must be greater than 0"),label:t("ageBetween","Age between"),min:0,onChange:(e,{value:t})=>x(Number(t)),value:g})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)(i.NumberInput,{"data-testid":"maxAge",hideSteppers:!0,id:"maxAge",invalidText:t("maxAgeIsNotValid","The age must be less than 200"),label:t("and","and"),max:200,min:0,onChange:(e,{value:t})=>y(Number(t)),value:_})})]})}),(0,s.jsxs)("div",{className:e_,children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"startDate",labelText:t("birthDate","Birth date between"),value:c,onChange:h})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"endDate",labelText:t("and","and"),value:p,onChange:b})})]}),(0,s.jsx)(D,{isLoading:v,onHandleSubmit:f,onHandleReset:()=>{d("all"),r("alive"),y(0),x(0),b(""),h("")}})]})},ej="-esm-cohort-builder__search-by-drug-orders-style__column___nQLUC",eS=({onSubmit:e})=>{let{t}=(0,o.useTranslation)(),{drugs:a,drugsError:l}=function(){let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/drug`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return(0,n.useMemo)(()=>({isLoading:a,drugs:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),drugsError:t}),[e,t,a])}(),{careSettings:d,careSettingsError:c}=function(){let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/caresetting`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return(0,n.useMemo)(()=>({isLoading:a,careSettings:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),careSettingsError:t}),[e,t,a])}(),[u,h]=(0,n.useState)(""),[p,b]=(0,n.useState)(""),[g,x]=(0,n.useState)(""),[_,y]=(0,n.useState)(""),[v,j]=(0,n.useState)([]),[S,w]=(0,n.useState)(null),[f,C]=(0,n.useState)(!1),T=l?.message;(0,n.useEffect)(()=>{T&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:T})},[T,t]);let N=c?.message;(0,n.useEffect)(()=>{N&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:N})},[N,t]);let k=async()=>{C(!0);let t={selectedDrugs:v,selectedCareSetting:S,activeOnOrAfter:u,activeOnOrBefore:p,activatedOnOrAfter:g,activatedOnOrBefore:_};try{await e((({selectedDrugs:e,selectedCareSetting:t,activeOnOrBefore:a,activeOnOrAfter:r,activatedOnOrBefore:s,activatedOnOrAfter:n})=>{let i={drugOrderSearch:[]};return r&&i.drugOrderSearch.push({name:"activeOnOrAfter",value:r}),n&&i.drugOrderSearch.push({name:"activatedOnOrAfter",value:n}),s&&i.drugOrderSearch.push({name:"activatedOnOrBefore",value:s}),t&&i.drugOrderSearch.push({name:"careSetting",value:t.value}),e.length&&i.drugOrderSearch.push({name:"drugs",value:e.map(e=>e.value)}),a&&i.drugOrderSearch.push({name:"activeOnOrBefore",value:a}),m(i)})(t),(({selectedDrugs:e,selectedCareSetting:t,activeOnOrBefore:a,activeOnOrAfter:s,activatedOnOrBefore:n,activatedOnOrAfter:i})=>{let o="Patients who taking "+e.map(e=>e.label).join(", ").replace(/,(?=[^,]*$)/," and");if(t&&(o+=` from ${t.label}`),s){let e=(0,r.formatDate)(new Date(s),{mode:"standard"});a?o+=` from ${e}`:o+=` on or after ${e}`}if(a){let e=(0,r.formatDate)(new Date(a),{mode:"standard"});s?o+=` to ${e}`:o+=` on or before ${e}`}if(i){let e=(0,r.formatDate)(new Date(i),{mode:"standard"});n?o+=` from ${e}`:o+=` on or after ${e}`}if(n){let e=(0,r.formatDate)(new Date(n),{mode:"standard"});i?o+=` to ${e}`:o+=` on or before ${e}`}return o})(t))}finally{C(!1)}};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)("div",{children:(0,s.jsx)(i.MultiSelect,{id:"drugs","data-testid":"drugs",onChange:e=>j(e.selectedItems),selectedItems:v,items:a,label:t("selectDrugs","Select drugs")})})}),(0,s.jsx)("div",{className:ej,children:(0,s.jsx)(i.Column,{children:(0,s.jsx)(i.Dropdown,{id:"careSettings","data-testid":"careSettings",onChange:e=>w(e.selectedItem),selectedItem:S,items:d,label:t("selectCareSettings","Select a care setting"),titleText:""})})}),(0,s.jsxs)("div",{className:ej,children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"activeOnOrAfter",labelText:t("using","Using between"),value:u,onChange:h})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"activeOnOrBefore",labelText:t("to","to"),value:p,onChange:b})})]}),(0,s.jsxs)("div",{className:ej,children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"activatedOnOrAfter",labelText:t("used","Used between"),value:g,onChange:x})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"activatedOnOrBefore",labelText:t("and","and"),value:_,onChange:y})})]}),(0,s.jsx)(D,{onHandleReset:()=>{j([]),w(null),h(""),b(""),x(""),y("")},onHandleSubmit:k,isLoading:f})]})},ew="-esm-cohort-builder__search-by-encounters-style__column___2KGkF",ef="-esm-cohort-builder__search-by-encounters-style__multipleInputs___AQXO8",eC=({onSubmit:e})=>{let{t}=(0,o.useTranslation)(),[a,l]=(0,n.useState)(0),[d,c]=(0,n.useState)(0),{encounterTypes:u,encounterTypesError:h}=(()=>{let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/encountertype`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,encounterTypes:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),encounterTypesError:t}})(),[p,b]=(0,n.useState)([]),[g,x]=(0,n.useState)([]),[_,y]=(0,n.useState)([]),{locations:v,locationsError:S}=j(),{forms:w,formsError:f}=(()=>{let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/form`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,forms:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),formsError:t}})(),[C,T]=(0,n.useState)(""),[N,k]=(0,n.useState)(""),[I,O]=(0,n.useState)(!1),E=S?.message;(0,n.useEffect)(()=>{E&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:E})},[E,t]);let A=f?.message;(0,n.useEffect)(()=>{A&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:A})},[A,t]);let L=h?.message;(0,n.useEffect)(()=>{L&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:L})},[L,t]);let M=async()=>{O(!0);let t={onOrAfter:N,atLeastCount:a,atMostCount:d,encounterForms:_,encounterLocations:g,onOrBefore:C,selectedEncounterTypes:p};try{await e((({onOrAfter:e,atLeastCount:t,atMostCount:a,encounterForms:r,encounterLocations:s,onOrBefore:n,selectedEncounterTypes:i})=>{let o={encounterSearchAdvanced:[]};return e&&o.encounterSearchAdvanced.push({name:"onOrAfter",value:e}),t&&o.encounterSearchAdvanced.push({name:"atLeastCount",value:t}),a&&o.encounterSearchAdvanced.push({name:"atMostCount",value:a}),r.length&&o.encounterSearchAdvanced.push({name:"formList",value:r.map(e=>e.value)}),s.length&&o.encounterSearchAdvanced.push({name:"locationList",value:s.map(e=>e.value)}),n&&o.encounterSearchAdvanced.push({name:"onOrBefore",value:n}),i.length>0&&o.encounterSearchAdvanced.push({name:"encounterTypeList",value:i.map(e=>e.value)}),m(o)})(t),(({selectedEncounterTypes:e,encounterLocations:t,encounterForms:a,atLeastCount:r,atMostCount:s,onOrAfter:n,onOrBefore:i})=>{let o="Patients with Encounter of",l=e.map(e=>e.label).join(", ").replace(/,(?=[^,]*$)/," and ");return o+=l?` Type${l.length>1?"s":""} ${l}`:" any Type",t.length&&(o+=` at ${t.map(e=>e.label).join(", ")}`),a.length&&(o+=` from ${a.map(e=>e.label).join(", ")}`),r&&(o+=` at least ${r} ${r>1?"times":"time"}`),s&&(o+=` ${r?" and":""} at most ${s} ${s>1?"times":"time"}`),n&&(i?o+=` from ${n}`:o+=` on or after ${n}`),i&&(n?o+=` to ${i}`:o+=` on or before ${i}`),o})(t))}finally{O(!1)}};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)("div",{children:(0,s.jsx)(i.MultiSelect,{id:"encounters",onChange:e=>b(e.selectedItems),selectedItems:p,items:u,label:t("selectEncounterTypes","Select encounter types")})})}),(0,s.jsx)(i.MultiSelect,{id:"forms","data-testid":"forms",onChange:e=>y(e.selectedItems),selectedItems:_,items:w,label:t("selectForms","Select forms")}),(0,s.jsx)(i.MultiSelect,{id:"locations",onChange:e=>x(e.selectedItems),selectedItems:g,items:v,label:t("selectLocations","Select locations")}),(0,s.jsx)("div",{className:ew,children:(0,s.jsxs)(i.Column,{className:"-esm-cohort-builder__search-by-encounters-style__encounterRange___0Q8rh",children:[(0,s.jsx)("div",{className:ef,children:(0,s.jsx)(i.NumberInput,{hideSteppers:!0,id:"atLeastCount","data-testid":"atLeastCount",label:t("atLeast","at least"),min:0,size:"sm",value:a,onChange:(e,{value:t})=>l(Number(t))})}),(0,s.jsx)("div",{className:ef,children:(0,s.jsx)(i.NumberInput,{hideSteppers:!0,id:"atMostCount","data-testid":"atMostCount",label:t("upto","upto this many"),min:0,size:"sm",value:d,onChange:(e,{value:t})=>c(Number(t))})})]})}),(0,s.jsxs)("div",{className:ew,children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"onOrAfter",labelText:t("from","From"),value:N,onChange:k})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"onOrBefore",labelText:t("to","to"),value:C,onChange:T})})]}),(0,s.jsx)(D,{isLoading:I,onHandleSubmit:M,onHandleReset:()=>{b([]),y([]),x([]),l(0),c(0),T(""),k("")}})]})},eT="-esm-cohort-builder__search-by-enrollments-style__column___10FcT",eN=({onSubmit:e})=>{let{t}=(0,o.useTranslation)(),{programs:a,programsError:l}=function(){let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/program`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,programs:(e??[]).map((e,t)=>({id:t,label:e.name,value:e.uuid})),programsError:t}}(),{locations:d,locationsError:c}=j(),[u,h]=(0,n.useState)(""),[p,b]=(0,n.useState)(""),[g,x]=(0,n.useState)(""),[_,y]=(0,n.useState)(""),[v,S]=(0,n.useState)([]),[w,f]=(0,n.useState)([]),[C,T]=(0,n.useState)(!1),N=l?.message;(0,n.useEffect)(()=>{N&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:N})},[N,t]);let k=c?.message;(0,n.useEffect)(()=>{k&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:k})},[k,t]);let I=async()=>{T(!0);let t={enrolledOnOrAfter:u,enrolledOnOrBefore:p,completedOnOrAfter:g,completedOnOrBefore:_,selectedPrograms:w,selectedLocations:v};try{await e((({enrolledOnOrAfter:e,enrolledOnOrBefore:t,completedOnOrAfter:a,completedOnOrBefore:r,selectedPrograms:s,selectedLocations:n})=>m({patientsWithEnrollment:[{name:"programs",value:s?.map(e=>e.value)},e&&{name:"enrolledOnOrAfter",value:e},t&&{name:"enrolledOnOrBefore",value:t},a&&{name:"completedOnOrAfter",value:a},r&&{name:"completedOnOrBefore",value:r},{name:"locationList",value:n?.map(e=>e.value)}]}))(t),(({selectedPrograms:e,selectedLocations:t})=>{let a=`Patients enrolled in ${e?.map(e=>e.label).join(", ")}`;return t?.length&&(a+=` at ${t?.map(e=>e.label).join(", ")}`),a})(t))}finally{T(!1)}};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)("div",{children:(0,s.jsx)(i.MultiSelect,{id:"programs","data-testid":"programs",onChange:e=>f(e.selectedItems),selectedItems:w,items:a,label:t("selectPrograms","Select programs")})})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)("div",{children:(0,s.jsx)(i.MultiSelect,{id:"locations","data-testid":"locations",onChange:e=>S(e.selectedItems),selectedItems:v,items:d,label:t("selectLocations","Select locations")})})}),(0,s.jsxs)("div",{className:eT,children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"enrolledOnOrAfter",labelText:t("enrolledBetween","Enrolled between"),value:u,onChange:h})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"enrolledOnOrBefore",labelText:t("and","and"),value:p,onChange:b})})]}),(0,s.jsxs)("div",{className:eT,children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"completedOnOrAfter",labelText:t("completedBetween","Completed between"),value:g,onChange:x})}),(0,s.jsx)(i.Column,{children:(0,s.jsx)(ec,{id:"completedOnOrBefore",labelText:t("and","and"),value:_,onChange:y})})]}),(0,s.jsx)(D,{onHandleReset:()=>{f([]),S([]),h(""),b(""),x(""),y("")},onHandleSubmit:I,isLoading:C})]})},ek=({onSubmit:e})=>{let{t}=(0,o.useTranslation)(),a=(0,n.useMemo)(()=>[{id:0,label:t("anyEncounter","Any Encounter"),value:"ANY"},{id:1,label:t("mostRecentEncounter","Most Recent Encounter"),value:"LAST"},{id:2,label:t("earliestEncounter","Earliest Encounter"),value:"FIRST"}],[t]),{locations:l,locationsError:d}=j(),[c,u]=(0,n.useState)([]),[h,p]=(0,n.useState)(a[0]),[b,g]=(0,n.useState)(!1),x=d?.message;(0,n.useEffect)(()=>{x&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:x})},[x,t]);let _=async()=>{g(!0);try{var t;let a;await e((t=h.value,a=[],c?.map(e=>a.push(e.value)),m({encounterSearchAdvanced:[{name:"locationList",value:a},{name:"timeQualifier",value:t}]})),((e,t)=>{let a=t?.length?`Patients in ${t.map(e=>e.label).join(", ")}`:"Patients in any location";switch(e){case"FIRST":a+=" (by method EARLIEST_ENCOUNTER).";break;case"LAST":a+=" (by method LATEST_ENCOUNTER).";break;default:a+=" (by method ANY_ENCOUNTER)."}return a})(h.value,c))}finally{g(!1)}};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)("div",{children:(0,s.jsx)(i.MultiSelect,{"aria-label":t("selectLocations","Select locations"),id:"locations","data-testid":"locations",onChange:e=>u(e.selectedItems),selectedItems:c,items:l,label:t("selectLocations","Select locations"),placeholder:t("searchForALocation","Search for a location")})})}),(0,s.jsx)("div",{className:"-esm-cohort-builder__search-by-location-style__column___yC9N2",children:(0,s.jsx)(i.Column,{children:(0,s.jsx)(i.Dropdown,{id:"methods","data-testid":"methods",onChange:e=>p(e.selectedItem),selectedItem:h,items:a,label:t("selectMethod","Select a method"),titleText:""})})}),(0,s.jsx)(D,{onHandleReset:()=>{u([]),p(a[0])},onHandleSubmit:_,isLoading:b})]})},eI=({onSubmit:e})=>{let{t}=(0,o.useTranslation)(),{personAttributes:a,personAttributesError:l}=function(){let{data:e,error:t,isLoading:a}=(0,r.useOpenmrsFetchAll)(`${r.restBaseUrl}/personattributetype`,{immutable:!0,swrInfiniteConfig:{revalidateFirstPage:!1}});return{isLoading:a,personAttributes:(e??[]).map((e,t)=>({id:t,label:e.display,value:e.uuid})),personAttributesError:t}}(),[d,c]=(0,n.useState)(""),[u,h]=(0,n.useState)(null),[p,b]=(0,n.useState)(!1),g=a.find(e=>e.value===u)??null,x=l?.message;(0,n.useEffect)(()=>{x&&(0,r.showSnackbar)({title:t("error","Error"),kind:"error",isLowContrast:!1,subtitle:x})},[x,t]);let _=async()=>{b(!0);let t=d.split(",").map(e=>e.trim()).filter(Boolean);try{var a;let r,s;await e(m({personWithAttribute:[{name:"attributeType",value:u},{name:"values",value:t}]}),(a=g?.label,r="Patients",s=t.length>0?t.join(", ").replace(/,(?=[^,]*$)/," or"):"",r+=a?` with${s?"":" any"} ${a}`:a,r+=s?` equal to ${t.length>1?"either ":""}${s}`:""))}finally{b(!1)}};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(i.Column,{children:(0,s.jsx)("div",{children:(0,s.jsx)(i.Dropdown,{id:"personAttributes","data-testid":"personAttributes",onChange:e=>h(e.selectedItem?.value??null),selectedItem:g,items:a,label:t("selectAttribute","Select a person attribute"),titleText:""})})}),(0,s.jsx)("div",{className:"-esm-cohort-builder__search-by-person-attributes-style__column___Tvomw",children:(0,s.jsx)(i.Column,{children:(0,s.jsx)(i.TextInput,{id:"selectedAttributeValues","data-testid":"selectedAttributeValues",disabled:!u,labelText:t("selectedAttributeValues","Enter Comma Delimited Values"),value:d,onChange:e=>c(e.target.value)})})}),(0,s.jsx)(D,{onHandleReset:()=>{h(null),c("")},onHandleSubmit:_,isLoading:p,isSearchDisabled:!u})]})};async function eD(e){return await (0,r.openmrsFetch)(`${r.restBaseUrl}/cohort`,{method:"POST",headers:{"Content-Type":"application/json"},body:e})}async function eO(e){return await (0,r.openmrsFetch)(`${r.restBaseUrl}/reportingrest/adhocdataset`,{method:"POST",headers:{"Content-Type":"application/json"},body:e})}let eE="-esm-cohort-builder__search-history-options__menuItem___iYtpR",eA="delete",eL="download",eM="saveCohort",e$="saveQuery",eF=async(e,t,a,s,n)=>{let i=[],{patients:o}=a;o.forEach(e=>i.push(parseInt(e.id)));try{await eD({display:e,memberIds:i,description:t,name:e}),(0,r.showSnackbar)({title:s("success","Success"),kind:"success",isLowContrast:!0,subtitle:s("cohortSaved","Cohort created successfully")}),n(M)}catch(e){(0,r.showSnackbar)({title:s("errorCreatingCohort","Error creating the cohort"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},eq=({searchItem:e,updateSearchHistory:t})=>{let{t:a}=(0,o.useTranslation)(),{mutate:n}=(0,A.useSWRConfig)(),l=async t=>{let{patients:a,description:r}=e;switch(t){case eM:h();break;case e$:u();break;case eL:let s=new Blob(["patient_id, full_name, age, gender\n"+a.map(e=>Object.keys({patientId:e.patientId,name:e.name,age:e.age,gender:e.gender}).map(t=>`"${e[t]}"`).join(",")).join("\n")],{type:"text/csv;charset=utf-8;"}),n=URL.createObjectURL(s),i=document.createElement("a");i.href=n,i.setAttribute("download",r),i.click();break;case eA:m()}},d=async()=>{try{t(e),(0,r.showSnackbar)({title:a("success","Success"),kind:"success",isLowContrast:!0,subtitle:"the search item is deleted"})}catch(e){(0,r.showSnackbar)({title:a("searchItemDeleteError","Error deleting the cohort"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},c=async({queryName:t,queryDescription:s})=>{try{let{parameters:i}=e;i.name=t,i.description=s,await eO(i),(0,r.showSnackbar)({title:a("success","Success"),kind:"success",isLowContrast:!0,subtitle:"the query is saved"}),n(G)}catch(e){(0,r.showSnackbar)({title:a("queryDeleteError","Error saving the query"),kind:"error",isLowContrast:!0,subtitle:e?.message})}},u=()=>{let e=(0,r.showModal)("save-query-modal",{closeModal:()=>e(),onSaveQuery:c,size:"sm"})},m=()=>{let t=(0,r.showModal)("clear-item-from-search-history-modal",{closeModal:()=>t(),onRemove:d,searchItemName:e?.description,size:"sm"})},h=()=>{let t=(0,r.showModal)("save-cohort-modal",{closeModal:()=>t(),onSave:(t,r)=>eF(t,r,e,a,n),size:"sm"})};return(0,s.jsxs)(i.OverflowMenu,{"aria-label":a("searchHistoryOptions","Search history options"),size:"md",flipped:!0,direction:"top","data-testid":"options",children:[(0,s.jsx)(i.OverflowMenuItem,{className:eE,"data-testid":"save-cohort",itemText:a("saveCohort","Save cohort"),onClick:()=>l(eM)}),(0,s.jsx)(i.OverflowMenuItem,{className:eE,"data-testid":"save-query",itemText:a("saveQuery","Save query"),onClick:()=>l(e$)}),(0,s.jsx)(i.OverflowMenuItem,{className:eE,itemText:a("downloadResults","Download results"),onClick:()=>l(eL)}),(0,s.jsx)(i.OverflowMenuItem,{className:eE,"data-testid":"deleteFromHistory",hasDivider:!0,isDelete:!0,itemText:a("deleteFromHistory","Delete from history"),onClick:()=>l(eA)})]})},eB=({isHistoryUpdated:e,setIsHistoryUpdated:t})=>{let{t:a}=(0,o.useTranslation)(),[l,d]=(0,n.useState)([]),[c,u]=(0,n.useState)(10),{results:m,currentPage:h,goTo:p}=(0,r.usePagination)(l,c);(0,n.useEffect)(()=>{if(e){let e,a;d((e=JSON.parse(window.sessionStorage.getItem("openmrsHistory")),a=[],e?.map((e,t)=>a.push({...e,id:(t+1).toString(),results:e.patients.length})),a)),t(!1)}},[e,t]);let b=[{key:"id",header:"#"},{key:"description",header:a("query","Query")},{key:"results",header:a("results","Results")}],g=()=>{window.sessionStorage.removeItem("openmrsHistory"),d([])},x=e=>{let t=[...l].filter((t,a)=>a!=l.indexOf(e));d(t),window.sessionStorage.setItem("openmrsHistory",JSON.stringify(t))};return(0,s.jsxs)("div",{className:"-esm-cohort-builder__search-history-style__container___KJBMK",children:[(0,s.jsxs)("div",{className:"-esm-cohort-builder__search-history-style__header___C-R7x",children:[(0,s.jsx)("p",{className:H,children:a("searchHistory","Search History")}),l.length>0&&(0,s.jsx)(i.Button,{kind:"danger--tertiary",onClick:()=>{let e=(0,r.showModal)("clear-search-history-modal",{closeModal:()=>e(),onClearHistory:g,size:"sm"})},children:a("clearSearchHistory","Clear search history")})]}),(0,s.jsx)(i.DataTable,{rows:m,headers:b,useZebraStyles:!0,children:({rows:e,headers:t,getTableProps:a,getHeaderProps:r,getRowProps:n})=>(0,s.jsxs)(i.Table,{...a(),children:[(0,s.jsx)(i.TableHead,{children:(0,s.jsxs)(i.TableRow,{children:[t.map(e=>(0,s.jsx)(i.TableHeader,{...r({header:e}),children:e.header})),(0,s.jsx)(i.TableHeader,{className:z})]})}),(0,s.jsx)(i.TableBody,{children:e.map((e,t)=>(0,s.jsxs)(i.TableRow,{...n({row:e}),children:[e.cells.map(e=>(0,s.jsx)(i.TableCell,{children:e.value},e.id)),(0,s.jsx)(i.TableCell,{className:Y,children:(0,s.jsx)(eq,{searchItem:m[t],updateSearchHistory:x})})]}))})]})}),l.length>10&&(0,s.jsx)(i.Pagination,{backwardText:a("previousPage","Previous page"),forwardText:a("nextPage","Next page"),itemsPerPageText:a("itemsPerPage","Items per page:"),onChange:({page:e,pageSize:t})=>{p(e),u(t)},page:h,pageSize:c,pageSizes:[10,20,30,40,50],size:"md",totalItems:l.length}),!l.length&&(0,s.jsx)(F,{displayText:a("data","data")})]})},eP=({patients:e})=>{let[t,a]=(0,n.useState)(1),[r,l]=(0,n.useState)(10),[d,c]=(0,n.useState)(e),{t:u}=(0,o.useTranslation)();e!==d&&(c(e),a(1));let m=[{key:"identifier",header:u("openmrsId","OpenMRS ID")},{key:"name",header:u("name","Name")},{key:"age",header:u("age","Age")},{key:"gender",header:u("gender","Gender")}];return(0,s.jsxs)("div",{className:"-esm-cohort-builder__search-results-table__container___y4+06",children:[(0,s.jsx)("p",{className:H,children:u("searchResults","Search Results")}),(0,s.jsx)(i.DataTable,{rows:e,headers:m,useZebraStyles:!0,children:({rows:e,headers:a,getTableProps:o,getHeaderProps:l,getRowProps:d})=>(0,s.jsxs)(i.Table,{...o(),children:[(0,s.jsx)(i.TableHead,{children:(0,s.jsx)(i.TableRow,{children:a.map(e=>(0,s.jsx)(i.TableHeader,{...l({header:e}),children:e.header}))})}),(0,s.jsx)(i.TableBody,{children:e.slice((t-1)*r).slice(0,r).map((e,t)=>(0,n.createElement)(i.TableRow,{...d({row:e}),key:t},e.cells.map((e,t)=>(0,s.jsx)(i.TableCell,{children:e.value},t))))})]})}),e.length>10&&(0,s.jsx)(i.Pagination,{backwardText:u("previousPage","Previous page"),forwardText:u("nextPage","Next page"),itemsPerPageText:u("itemsPerPage","Items per page:"),onChange:({page:e,pageSize:t})=>{a(e),l(t)},page:t,pageSize:r,pageSizes:[10,20,30,40,50],size:"md",totalItems:e.length}),!e.length&&(0,s.jsx)(F,{displayText:u("data","data")})]})};var eR=a(9785),eH=a(3285),eU=a(4476);let eY={featureName:"cohort-builder",moduleName:"@openmrs/esm-cohort-builder-app"},ez=a(4767);function eQ(){}let eV=(0,r.getSyncLifecycle)(()=>{let{t:e}=(0,o.useTranslation)(),[t,a]=(0,n.useState)([]),[l,d]=(0,n.useState)(!0),c="tablet"===(0,r.useLayoutType)(),m=(t,s)=>new Promise(n=>{a([]),v(t).then(({data:{rows:i}})=>{var o;let l,c;i.map(e=>{e.id=e.patientId.toString(),e.name=_(e.firstname,e.lastname)}),a(i),o=t.query,l=JSON.parse(window.sessionStorage.getItem("openmrsHistory")),c=[],c=l?[...l,{description:s,patients:i,parameters:o}]:[{description:s,patients:i,parameters:o}],window.sessionStorage.setItem("openmrsHistory",JSON.stringify(c)),(0,r.showSnackbar)({title:e("searchCompleted","Search completed"),kind:"success",isLowContrast:!0,subtitle:e("noOfResultsFound","{{count}} results found",{count:i.length})}),d(!0),n(!0)}).catch(t=>{(0,r.showSnackbar)({title:e("error","Error"),kind:"error",isLowContrast:!1,subtitle:t?.message}),n(!0)})}),h=async t=>{try{let s=await S(t);a(s),(0,r.showSnackbar)({title:e("searchCompleted","Search completed"),kind:"success",isLowContrast:!0,subtitle:e("noOfResultsFound","{{count}} results found",{count:s.length})})}catch(t){(0,r.showSnackbar)({title:e("error","Error"),kind:"error",isLowContrast:!1,subtitle:t?.message})}},p=async t=>{try{let{patients:s,total:n}=await f(t);a(s),s.length<n?(0,r.showSnackbar)({title:e("someCohortMembersNotShown","Some of the cohort's members could not be shown"),kind:"warning",isLowContrast:!0,subtitle:e("showingCohortMembers","Showing {{shown}} of {{count}} members",{shown:s.length,count:n})}):(0,r.showSnackbar)({title:e("searchCompleted","Search completed"),kind:"success",isLowContrast:!0,subtitle:e("noOfResultsFound","{{count}} results found",{count:s.length})})}catch(t){(0,r.showSnackbar)({title:e("error","Error"),kind:"error",isLowContrast:!1,subtitle:t instanceof w?e("cohortMembersLoadFailed","None of the cohort's members could be loaded"):t?.message})}},b=[{name:e("concepts","Concepts"),component:(0,s.jsx)(eg,{onSubmit:m})},{name:e("demographics","Demographics"),component:(0,s.jsx)(ev,{onSubmit:m})},{name:e("personAttributes","Person Attributes"),component:(0,s.jsx)(eI,{onSubmit:m})},{name:e("encounters","Encounters"),component:(0,s.jsx)(eC,{onSubmit:m})},{name:e("location","Location"),component:(0,s.jsx)(ek,{onSubmit:m})},{name:e("enrollments","Enrollments"),component:(0,s.jsx)(eN,{onSubmit:m})},{name:e("drugOrder","Drug Order"),component:(0,s.jsx)(eS,{onSubmit:m})},{name:e("composition","Composition"),component:(0,s.jsx)(E,{onSubmit:m})},{name:e("savedCohorts","Saved Cohorts"),component:(0,s.jsx)(V,{onViewCohort:p})},{name:e("savedQueries","Saved Queries"),component:(0,s.jsx)(ee,{onViewQuery:h})}];return(0,s.jsxs)("div",{children:[(0,s.jsx)(r.PageHeader,{className:"-esm-cohort-builder__cohort-builder__header___VRsag",children:(0,s.jsx)(r.PageHeaderContent,{illustration:(0,s.jsx)(r.CohortsPictogram,{}),title:e("cohortBuilder","Cohort Builder")})}),(0,s.jsx)("div",{className:u()("-esm-cohort-builder__cohort-builder__mainContainer___LXqCB","-esm-cohort-builder__cohort-builder__cohortBuilder___IqfBP"),children:(0,s.jsxs)("div",{className:u()(c?"-esm-cohort-builder__cohort-builder__tabletContainer___7xD+u":"-esm-cohort-builder__cohort-builder__desktopContainer___I5sch"),children:[(0,s.jsxs)("div",{className:"-esm-cohort-builder__cohort-builder__tabContainer___u8YU-",children:[(0,s.jsx)("p",{className:H,children:e("searchCriteria","Search Criteria")}),(0,s.jsx)("div",{className:U,children:(0,s.jsxs)(i.Tabs,{children:[(0,s.jsx)(i.TabList,{"aria-label":"navigation",children:b.map((e,t)=>(0,s.jsx)(i.Tab,{className:U,children:e.name},t))}),(0,s.jsx)(i.TabPanels,{children:b.map((e,t)=>(0,s.jsx)(i.TabPanel,{children:e.component},t))})]})})]}),(0,s.jsx)(eP,{patients:t}),(0,s.jsx)(eB,{isHistoryUpdated:l,setIsHistoryUpdated:d})]})})]})},eY),eG=(0,r.getSyncLifecycle)(()=>{let{t:e}=(0,o.useTranslation)();return(0,s.jsx)(i.Layer,{children:(0,s.jsxs)(i.ClickableTile,{href:`${window.spaBase}/cohort-builder`,children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"heading",children:e("manageCohorts","Manage Cohorts")}),(0,s.jsx)("div",{className:"content",children:e("cohortBuilder","Cohort Builder")})]}),(0,s.jsx)("div",{className:"iconWrapper",children:(0,s.jsx)(d.Qp,{size:16})})]})})},eY),eW=(0,r.getSyncLifecycle)(({closeModal:e,onRemove:t,searchItemName:a})=>{let{t:d}=(0,o.useTranslation)(),[c,u]=(0,n.useState)(!1);return(0,s.jsxs)("div",{children:[(0,s.jsx)(i.ModalHeader,{closeModal:e,title:d("clearItemFromHistory","Clear item from search history")}),(0,s.jsxs)(i.ModalBody,{children:[(0,s.jsx)("p",{children:d("removeItemFromSearchHistory","Are you sure you want to remove this item from the search history?")}),(0,s.jsx)("br",{}),(0,s.jsx)("p",{children:(0,s.jsxs)("strong",{children:['"',a,'"']})})]}),(0,s.jsxs)(i.ModalFooter,{children:[(0,s.jsx)(i.Button,{kind:"secondary",onClick:e,children:(0,r.getCoreTranslation)("cancel")}),(0,s.jsx)(i.Button,{className:l,kind:"danger",onClick:()=>{u(!0),t(),u(!1),e()},disabled:c,children:c?(0,s.jsx)(i.InlineLoading,{description:d("removing","Removing")+"..."}):(0,s.jsx)("span",{children:(0,r.getCoreTranslation)("delete")})})]})]})},eY),eX=(0,r.getSyncLifecycle)(({closeModal:e,onClearHistory:t,searchItemName:a})=>{let{t:d}=(0,o.useTranslation)(),[c,u]=(0,n.useState)(!1);return(0,s.jsxs)("div",{children:[(0,s.jsx)(i.ModalHeader,{closeModal:e,title:d("clearSearchHistory","Clear search history")}),(0,s.jsx)(i.ModalBody,{children:(0,s.jsx)("p",{children:d("clearSearchHistoryModalText","Are you sure you want to clear the search history?")})}),(0,s.jsxs)(i.ModalFooter,{children:[(0,s.jsx)(i.Button,{kind:"secondary",onClick:e,children:(0,r.getCoreTranslation)("cancel")}),(0,s.jsx)(i.Button,{className:l,disabled:c,kind:"danger",onClick:()=>{u(!0),t(),u(!1),e()},children:c?(0,s.jsx)(i.InlineLoading,{description:d("clearing","Clearing")+"..."}):(0,s.jsx)("span",{children:d("clearHistory","Clear history")})})]})]})},eY),eZ=(0,r.getSyncLifecycle)(({closeModal:e,cohortName:t,onDeleteCohort:a})=>{let{t:l}=(0,o.useTranslation)(),[d,c]=(0,n.useState)(!1);return(0,s.jsxs)("div",{children:[(0,s.jsx)(i.ModalHeader,{closeModal:e,title:l("deleteCohort","Delete cohort")}),(0,s.jsx)(i.ModalBody,{children:(0,s.jsxs)("p",{children:[l("deleteCohortModalText","Are you sure you want to delete the cohort")," ",(0,s.jsxs)("strong",{children:['"',t,'"']}),"?"]})}),(0,s.jsxs)(i.ModalFooter,{children:[(0,s.jsx)(i.Button,{kind:"secondary",onClick:e,children:(0,r.getCoreTranslation)("cancel")}),(0,s.jsx)(i.Button,{className:"-esm-cohort-builder__delete-cohort__deleteButton___15Gkt",kind:"danger",onClick:()=>{c(!0),a(),c(!1),e()},disabled:d,children:d?(0,s.jsx)(i.InlineLoading,{description:l("deleting","Deleting")+"..."}):(0,s.jsx)("span",{children:(0,r.getCoreTranslation)("delete")})})]})]})},eY),eJ=(0,r.getSyncLifecycle)(({closeModal:e,queryName:t,queryId:a,onDelete:l})=>{let{t:d}=(0,o.useTranslation)(),[c,u]=(0,n.useState)(!1),m=async()=>{u(!0),await l(a),u(!1),e()};return(0,s.jsxs)("div",{children:[(0,s.jsx)(i.ModalHeader,{closeModal:e,title:d("deleteSavedQuery","Delete saved query")}),(0,s.jsx)(i.ModalBody,{children:(0,s.jsx)("p",{children:d("deleteSavedQueryConfirmation","Are you sure you want to delete this saved query?")})}),(0,s.jsxs)(i.ModalFooter,{children:[(0,s.jsx)(i.Button,{kind:"secondary",onClick:e,children:(0,r.getCoreTranslation)("cancel")}),(0,s.jsx)(i.Button,{kind:"danger",onClick:m,disabled:c,children:c?(0,s.jsx)(i.InlineLoading,{description:d("deleting","Deleting")+"..."}):(0,s.jsx)("span",{children:(0,r.getCoreTranslation)("delete")})})]})]})},eY),eK=(0,r.getSyncLifecycle)(({closeModal:e,onSave:t})=>{let{t:a}=(0,o.useTranslation)(),{control:n,handleSubmit:d,formState:{errors:c}}=(0,eR.mN)({resolver:(0,eH.u)(eU.z.object({name:eU.z.string({required_error:a("cohortNameRequired","Cohort name is required")}).trim().min(1,a("cohortNameRequired","Cohort name is required")),description:eU.z.string({required_error:a("cohortDescriptionRequired","Description is required")}).trim().min(1,a("cohortDescriptionRequired","Description is required"))})),mode:"onChange"}),u=a=>{t(a.name.trim(),a.description.trim()),e()};return(0,s.jsxs)("div",{children:[(0,s.jsx)(i.ModalHeader,{closeModal:e,title:a("saveCohort","Save cohort")}),(0,s.jsx)(i.ModalBody,{children:(0,s.jsx)("form",{onSubmit:d(u),children:(0,s.jsxs)(i.Stack,{gap:5,children:[(0,s.jsx)(eR.xI,{name:"name",control:n,render:({field:e})=>(0,s.jsx)(i.TextInput,{"data-testid":"cohort-name",id:"cohort-name",labelText:a("enterCohortName","Enter a cohort name"),...e,invalid:!!c.name,invalidText:c.name?.message})}),(0,s.jsx)(eR.xI,{name:"description",control:n,render:({field:e})=>(0,s.jsx)(i.TextInput,{"data-testid":"cohort-description",id:"cohort-description",labelText:a("enterCohortDescription","Enter a cohort description"),...e,invalid:!!c.description,invalidText:c.description?.message})})]})})}),(0,s.jsxs)(i.ModalFooter,{children:[(0,s.jsx)(i.Button,{kind:"secondary",onClick:e,children:(0,r.getCoreTranslation)("cancel")}),(0,s.jsx)(i.Button,{className:l,kind:"danger",onClick:d(u),children:(0,s.jsx)("span",{children:(0,r.getCoreTranslation)("save")})})]})]})},eY),e0=(0,r.getSyncLifecycle)(({closeModal:e,onSaveQuery:t})=>{let{t:a}=(0,o.useTranslation)(),{control:n,handleSubmit:d,formState:{errors:c,isSubmitting:u}}=(0,eR.mN)({resolver:(0,eH.u)(eU.z.object({queryName:eU.z.string({required_error:a("queryNameRequired","Name is required")}).min(1,a("queryNameRequired","Name is required")),queryDescription:eU.z.string({required_error:a("queryDescriptionRequired","Description is required")}).min(1,a("queryDescriptionRequired","Description is required"))})),defaultValues:{queryName:"",queryDescription:""}}),m=async a=>{await t(a),e()};return(0,s.jsxs)("div",{children:[(0,s.jsx)(i.ModalHeader,{closeModal:e,title:a("saveQuery","Save query")}),(0,s.jsxs)("form",{onSubmit:d(m),children:[(0,s.jsx)(i.ModalBody,{children:(0,s.jsxs)(i.Stack,{gap:5,children:[(0,s.jsx)(eR.xI,{name:"queryName",control:n,render:({field:e})=>(0,s.jsx)(i.TextInput,{...e,labelText:a("enterQueryName","Enter a name for the query"),id:"query-name","data-testid":"query-name",invalid:!!c.queryName,invalidText:c.queryName?.message})}),(0,s.jsx)(eR.xI,{name:"queryDescription",control:n,render:({field:e})=>(0,s.jsx)(i.TextInput,{...e,labelText:a("enterQueryDescription","Enter a description of the query"),id:"query-description",invalid:!!c.queryDescription,invalidText:c.queryDescription?.message})})]})}),(0,s.jsxs)(i.ModalFooter,{children:[(0,s.jsx)(i.Button,{kind:"secondary",onClick:e,children:(0,r.getCoreTranslation)("cancel")}),(0,s.jsx)(i.Button,{className:l,disabled:u,kind:"primary",type:"submit",children:u?(0,s.jsx)(i.InlineLoading,{description:a("saving","Saving")+"..."}):(0,s.jsx)("span",{children:(0,r.getCoreTranslation)("save")})})]})]})]})},eY)}}]);