1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MessageTemplatesDialog-B1HeT6bA.js","assets/react-vendor-CU6Sz31W.js","assets/MessageTemplatesManager-BesVHpQc.js","assets/index-DEXJEDAi.js","assets/firebase-w6DYUbFN.js","assets/payment-icons-Daq1K3F1.js","assets/index-ClGd-I0y.css","assets/table-CxPdvV_9.js","assets/text-highlight-BFqqfcjs.js","assets/calendar-RV2oTCrW.js","assets/addWeeks-1hrFjz19.js","assets/DataTableCard-BluwWKn_.js","assets/index-BSuGcRaZ.js","assets/arrow-up-D6DFVL4j.js","assets/arrow-down-BjUlbB4f.js","assets/pill-filter-CtZSNPVl.js","assets/date-picker-filter-Qp1kqu9t.js","assets/clear-filters-button-DmPemFGr.js","assets/ExportCsvAction-BJr9eiP6.js","assets/modal-option-cards-Dksohkou.js","assets/patient-name-link-BAfQKbEs.js","assets/useTemplateVariableInsertion-DRs-_PWy.js","assets/prescriptionMessageTemplateVariables-AMxKc8BX.js","assets/pencil-CpqYHolO.js"])))=>i.map(i=>d[i]); 2import{r as i,j as r}from"./react-vendor-CU6Sz31W.js";import{as as C,g9 as ke,u as at,jI as ea,bg as ta,E as Rt,gs as Ca,au as J,t as W,rV as Fa,al as aa,ax as Pa,c6 as ja,i as tt,cd as ra,d as Ea,aA as xe,I as Be,U as Na,ex as Ht,b as sa,S as ia,c5 as ka,be as Kt,ii as Oa,ak as La,gA as Ia,e6 as Aa,b2 as Ta,j as Ba,eq as na}from"./index-DEXJEDAi.js";import{F as oa}from"./FormularyMappingManager-Cp-K-vjw.js";import{C as la}from"./ClientFormularyMedicationsTable-DGS5GEg6.js";import{g as ca,d as Mt,f as Da,e as Dt,c as ua,j as Ua,s as Ra}from"./firebase-w6DYUbFN.js";import{c as da}from"./useFormularySendTiming-PW-jkqj4.js";import{e as ma}from"./formularySendSchedules-hEX-RQcj.js";import{t as Vt,B as Ha,k as fa,S as Ka,P as Va,D as $a,i as wt,O as _a,o as ut,y as Ct,T as $t,C as Ut,U as At,g as za,n as qa,s as _t,V as Qa,j as Wa,W as Ya,l as Ja,X as Ga,p as zt,m as Xa}from"./formularyMappings-C8mJfsp2.js";import{J as Za,K as er,g as A,M as qt,N as ya,B as tr,O as pa,H as ar,P as rr,a as bt,Q as Qt,b as sr,w as ir}from"./formularyVariants-BV7CaEYS.js";import{j as Tt,m as dt,l as ga,a as Ne,K as ha,L as nr,s as Bt,N as or,d as ue,O as Wt,k as lr,g as cr,P as ur}from"./formularyRules-DurNzATt.js";import{R as dr}from"./RoutePageHeader-9W0v4VlT.js";import{l as mr}from"./categoryCatalogApi-CVlN5SfH.js";import{l as fr}from"./formularySeed-CU64n7sL.js";import"./calendar-RV2oTCrW.js";import{F as yr}from"./DataTableCard-BluwWKn_.js";import"./ExportCsvAction-BJr9eiP6.js";import"./patient-name-link-BAfQKbEs.js";import"./text-highlight-BFqqfcjs.js";import{M as pr}from"./message-square-text-CBK4eOxL.js";import{A as gr}from"./AccessDenied-Ba4b0-Uz.js";import"./payment-icons-Daq1K3F1.js";import"./ellipsis-tooltip-CfKm8VFV.js";import"./providerOperations-ELdKx_YD.js";import"./networkLicensurePolicy-Ct3PZM4V.js";import"./searchMatchPosition-D039Jv6R.js";import"./catalogCategoryVisibility-PKrVnYt-.js";import"./ProductInlineEditPopovers-B7oRL8nE.js";import"./CatalogSelectionList-D9FsL1Nv.js";import"./useTableSort-KpNOL2n3.js";import"./useFormularyTypesenseSearch-b2YherGX.js";import"./collectExportPages-B1mgoF_8.js";import"./editor-D8UbQKN1.js";import"./use-unsaved-changes-B6nL5Xdd.js";import"./formularySearchSeed-DFztyQr8.js";import"./pencil-CpqYHolO.js";import"./RoutePageHeaderContent-FkxdZGox.js";import"./addWeeks-1hrFjz19.js";import"./index-BSuGcRaZ.js";import"./table-CxPdvV_9.js";import"./arrow-up-D6DFVL4j.js";import"./arrow-down-BjUlbB4f.js";import"./pill-filter-CtZSNPVl.js";import"./date-picker-filter-Qp1kqu9t.js";import"./clear-filters-button-DmPemFGr.js";import"./modal-option-cards-Dksohkou.js";import"./shield-alert-DjOj07_r.js";function xa(t,e){const[n,b]=i.useState({}),x=i.useCallback((g,L)=>{b(K=>({...K,[g]:L?t:null}))},[t]);return{exportReady:!!t&&e.every(g=>n[g]===t),setExportSourceReady:x}}function hr(t){const[e,n]=i.useState([]);return i.useEffect(()=>{let b=!1;const x=[],g=new Map;return n([]),t&&ca(Mt(C,"Clients",t)).then(L=>{if(b)return;const K=L.data()||{};[...new Set([K.primaryProviderNetworkId,K.providerNetworkId,...K.providerNetworkIds||[],...K.additionalProviderNetworkIds||[]].filter(Boolean))].forEach(_=>x.push(Da(Dt(C,"ProviderNetworks",_,"FormularyMedicationOverrides"),R=>{g.set(_,R.docs.map(P=>({...P.data(),ownerScope:"providerNetwork",ownerId:_}))),n([...g.values()].flat())},()=>{b||ke.error("Unable to load network directions. Reload the formulary to try again.")})))}).catch(()=>{b||(n([]),ke.error("Unable to load network directions. Reload the formulary to try again."))}),()=>{b=!0,x.forEach(L=>L())}},[t]),e}const Yt=100,St=new Map,ct=new Map;function Ue(t){return t==null?"":String(t).trim()}function va(t){return Ue(t)==="providerNetwork"?"providerNetwork":"client"}function ba(t,e){const n=Ue(e);return n?va(t)==="providerNetwork"?["ProviderNetworks",n,"FormularyVisibility"]:["Clients",n,"FormularyVisibility"]:null}function Sa(t,e){return`${va(t)}:${Ue(e)}`}async function Ma(t,{scope:e,scopeId:n}={},b={}){const x=ba(e,n);if(!x)return new Set;const g=Sa(e,n),L=b.useCache!==!1;if(L&&St.has(g))return St.get(g);if(L&&ct.has(g))return ct.get(g);const K=(async()=>{const U=await ua(Dt(t,...x)),_=new Set;
2return U.forEach(R=>{var H;const P=(H=R.data())==null?void 0:H.hiddenMedicationIds;Array.isArray(P)&&P.forEach(D=>{const Z=Ue(D);Z&&_.add(Z)})}),L&&St.set(g,_),_})().finally(()=>{ct.delete(g)});return L&&ct.set(g,K),K}function xr(t){const e=[];for(let n=0;n<t.length;n+=Yt)e.push(t.slice(n,n+Yt));return e}const Jt=new Map;async function vr(t,{segments:e,cacheKey:n,normalizedTargets:b,hidden:x,user:g}){const L=Dt(t,...e),K=await ua(L),U=new Set,_=[];K.forEach(S=>{var re;_.push(S.id);const I=(re=S.data())==null?void 0:re.hiddenMedicationIds;Array.isArray(I)&&I.forEach(Y=>{const be=Ue(Y);be&&U.add(be)})});const R=new Set(U);b.forEach(S=>{x?R.add(S):R.delete(S)});const P=Array.from(R).sort(),H=xr(P),D={updatedAt:Ra(),updatedBy:Ue(g==null?void 0:g.uid),updatedByEmail:Ue(g==null?void 0:g.email)},Z=Ua(t);return H.forEach((S,I)=>{Z.set(Mt(L,`chunk_${I}`),{hiddenMedicationIds:S,...D},{merge:!0})}),_.forEach(S=>{const I=/^chunk_(\d+)$/.exec(S),re=I?Number(I[1]):null;(re==null||re>=H.length)&&Z.delete(Mt(L,S))}),await Z.commit(),St.set(n,R),ct.delete(n),R}async function wa(t,{scope:e,scopeId:n,medicationIds:b=[],hidden:x,user:g}={}){const L=ba(e,n);if(!L)throw new Error("Formulary visibility scope and scopeId are required.");const K=Array.from(new Set((Array.isArray(b)?b:[b]).map(P=>Ue(P)).filter(Boolean)));if(K.length===0)return Ma(t,{scope:e,scopeId:n});const U=Sa(e,n),R=(Jt.get(U)||Promise.resolve()).catch(()=>{}).then(()=>vr(t,{segments:L,cacheKey:U,normalizedTargets:K,hidden:x,user:g}));return Jt.set(U,R.catch(()=>{})),R}function br(t={}){return ue(t.itemType==="package"?"package":t.type||"product").toLowerCase()==="product"}function Sr(t={}){const e=Number(t.errorStatus||t.statusCode||t.status),n=ue(t.error||t.message).toLowerCase();return e===403||n.includes("status code 403")||n.includes("status 403")}function Mr(t={}){if(!t||t.inactiveFormularyMappingOnly||t.active===!1||t.enabled===!1)return!1;const e=ue(t.status||t.integrationStatus||t.state).toLowerCase();return!["inactive","disabled","archived","deleted"].includes(e)}function It(t=[]){return(Array.isArray(t)?t:[]).filter(e=>Mr(e)&&!Sr(e))}function wr(t=[],e=[]){const n=new Map;for(const b of[...t,...e]){const x=A(b);!x||n.has(x)||n.set(x,b)}return Array.from(n.values())}async function Cr(t){const e=ue(t);if(!e)return null;try{const n=await ca(Mt(C,"Formulary",e));return n.exists()?{id:n.id,...n.data()}:null}catch(n){return console.error("Error loading root formulary medication:",n),null}}function Fr(t,e={}){const n={...t};for(const[b,x]of Object.entries(e||{}))x==null||x===""||(n[b]=x);return delete n.inactiveFormularyMappingOnly,n}function Pr({active:t,clientId:e,showSuperAdminPriceSync:n=!1}){const{userType:b}=at(),x=hr(e),[g,L]=i.useState(!1),[K,U]=i.useState(!1),[_,R]=i.useState(""),P=ea("client",t?e:""),{catalog:H,error:D,revision:Z}=P,[S,I]=i.useState(!0),[re,Y]=i.useState([]),[be,we]=i.useState(!1),[Oe,de]=i.useState(!1),[Re,He]=i.useState(!1),[Ke,ne]=i.useState([]),[d,h]=i.useState({}),[G,oe]=i.useState({}),[fe,ee]=i.useState(!1),[Ft,Ve]=i.useState(""),[Pt,Le]=i.useState(!1),[mt,Se]=i.useState(()=>new Set),[ft,qe]=i.useState(!1),[ye,le]=i.useState(!1),[Ce,Qe]=i.useState(""),[yt,We]=i.useState({}),[rt,$e]=i.useState(!1),[Fe,se]=i.useState([]),[st,Pe]=i.useState([]),[jt,pe]=i.useState(""),[Et,pt]=i.useState(""),_e=i.useRef(null),z=b==="Client Admin"||b==="Super Admin",Nt=ta(b,["Client Admin","Client Staff"]),{exportReady:it,setExportSourceReady:X}=xa(e||"",["catalog","mappings","prices","custom","hidden"]);i.useEffect(()=>{if(!t)return;let s=!1;if(R(D?"Unable to check pharmacy access. Try again to load your formulary.":""),X("catalog",!1),Vt(e,[]),Y([]),U(!1),L(!D),I(!0),!e||D){e||R("Missing client formulary scope."),L(!1),U(!0);return}if(!H)return;const c=It(H.pharmacies||[]).map(F=>({...F,pricingLoading:!0}));if(Y(c),U(!0),L(!1),H.complete===!1)return()=>{s=!0};let M=0,T=!1;const p=new Map,$=async()=>{for(;!s&&M<c.length;){const F=c[M++];try{const te=await Ca({clientId:e,pharmacyIds:[F.pharmacyId]});if(s)return;const B=It(te.pharmacies||[]).find(ge=>ge.pharmacyId===F.pharmacyId&&ge.integrationId===F.integrationId);B&&p.set(`${F.integrationId}:${F.pharmacyId}`,B),Y(ge=>ge.flatMap(y=>y.pharmacyId===F.pharmacyId&&y.integrationId===F.integrationId?B?[B]:[]:[y]))}catch{T=!0,s||Y(te=>te.map(B=>B.pharmacyId===F.pharmacyId&&B.integrationId===F.integrationId?{...B,pricingLoading:!1}:B))}}};return Promise.all(Array.from({length:Math.min(3,c.length)},$)).then(()=>{s||(I(!1),X("catalog",!T),Vt(e,[...p.values()]),T&&ke.error("Some pharmacy prices could not load. Reopen the formulary to retry."))}),()=>{s=!0}},[t,e,H,D,Z,X]),i.useEffect(()=>{if(!t||!e){oe({}),ee(!0);return}let s=!1;return X("prices",!1),ee(!1),(async()=>{try{const c=await Tt(C,e,{useCache:!1});if(s)return;oe(dt(c)),X("prices",!0)}catch(c){if(s)return;console.error("Error loading client formulary medication overrides:",c),oe({})}finally{s||ee(!0)}})(),()=>{s=!0}},[t,e,X]);async function gt(){if(e){X("prices",!1),ee(!1);try{const s=await Tt(C,e,{useCache:!1});oe(dt(s)),X("prices",!0)}catch(s){console.error("Error loading client formulary medication overrides:",s),oe({})}finally{ee(!0)}}}i.useEffect(()=>{const s=P.visibility;Se((s==null?void 0:s.ownHiddenIds)||new Set),X("hidden",!!s)},[P.visibility,X]),i.useEffect(()=>{if(!t||!e){Pe([]);return}let s=!1;return(async()=>{try{const c=await Za(C,e,{useCache:!1,includeInactive:!0});if(s)return;Pe(Object.values(er(c)))}catch(c){if(s)return;console.error("Error loading formulary medication variants:",c),Pe([])}})(),()=>{s=!0}},[t,e]);async function ht(s,c){if(!e||!z)return;const M=Array.isArray(s)?s:[s];if(M.length===0)return;let T;Se(p=>{T=p;const $=new Set(p);return M.forEach(F=>c?$.add(F):$.delete(F)),$});try{const p=await wa(C,{scope:"client",scopeId:e,medicationIds:M,hidden:c,user:J.currentUser});Se(new Set(p))}catch(p){console.error("Error updating formulary medication visibility:",p),T&&Se(T),W.error((p==null?void 0:p.message)||"Unable to update medication visibility.")}}
2async function xt(){if(!(!e||!n)){Le(!0);try{const c=(await Fa({clientId:e})).summary||{};await gt(),W.success(`Synced ${c.pricesWritten||0} prices for ${c.pharmaciesProcessed||0} pharmacies (${c.pricesSkippedExisting||0} kept, ${c.pricesSkippedMatchingBase||0} matched base)`)}catch(s){W.error((s==null?void 0:s.message)||"Unable to sync client formulary prices.")}finally{Le(!1)}}}i.useEffect(()=>{if(!t||!e){le(!1),Qe(""),se([]),$e(!1);return}let s=!1;return X("custom",!1),se([]),$e(!1),(async()=>{try{const{enabled:c,providerNetworkId:M}=await Ha(C,{clientId:e});if(s)return;if(le(c),Qe(M||""),c){const[T,p]=await Promise.all([M?fa(C,M):Promise.resolve([]),Ka(C,e)]);if(s)return;se(wr(T,p))}else se([])}catch(c){if(s)return;console.error("Error resolving prescribe-by-product settings:",c),le(!1),Qe(""),se([]),$e(!0)}finally{s||($e(!0),X("custom",!0))}})(),()=>{s=!0}},[t,e,X]),i.useEffect(()=>{if(!t||!Ce){We({});return}let s=!1;return(async()=>{try{const c=await ga(C,Ce,{useCache:!1});if(s)return;We(dt(c))}catch(c){if(s)return;console.error("Error loading provider network formulary medication overrides:",c),We({})}})(),()=>{s=!0}},[t,Ce]),i.useEffect(()=>{if(!t)return;if(!e){we(!1),de(!0),He(!0),ne([]),h({});return}let s=!1;return X("mappings",!1),de(!1),He(!1),we(!0),(async()=>{try{const c=(await Va(C,e,{useCache:!1,includeClientOwned:ye})).filter(br);if(s)return;ne(c),de(!0);const M=await $a(C,{clientId:e,products:c,useCache:!1});if(s)return;h(M),X("mappings",!0)}catch(c){if(s)return;console.error("Error loading formulary product mappings:",c),ne([]),h({}),de(!0)}finally{s||(He(!0),we(!1))}})(),()=>{s=!0}},[t,e,ye,X]);const O=!!P.visibility,Ie=i.useMemo(()=>{var s;return((s=P.visibility)==null?void 0:s.networkHiddenIds)||new Set},[P.visibility]),nt=i.useMemo(()=>!O||!ye?[]:Fe.filter(s=>!Ie.has(A(s))),[Fe,Ie,ye,O]),Ae=i.useMemo(()=>!O||!H||D?[]:It(re).map(s=>({...s,drugs:(s.drugs||[]).filter(c=>!Ie.has(A(c)))})),[H,D,Ie,re,O]),me=g||!K||!O||!H&&!D,Ye=!K||!Oe||!Re||be;async function ot({product:s,drug:c,pharmacy:M,nextChecked:T}){const p=A(c),$=wt(s);if(!(!e||!p||!$))try{const{mappingKey:F,payload:te}=await _a(C,{clientId:e,product:s,pharmacy:M,drug:c,nextChecked:T,mapping:d[$]||{},user:J.currentUser});h(B=>({...B,[$]:{...B[$]||{},[F]:{...te,source:"client",hasOverride:!0}}}))}catch(F){console.error("Error saving formulary mapping:",F),W.error((F==null?void 0:F.message)||"Unable to save formulary mapping.")}}async function Je({pharmacy:s,drug:c,value:M,defaultValue:T}){const p=A(c);if(!e||!p||!z)return;const $=Ne(s,p,e);Ve(`${$}:price`);try{const F=await ha(C,{clientId:e,pharmacy:s,medicationId:p,field:"price",value:M,defaultValue:T,user:J.currentUser});oe(te=>{const B={...te};return F?B[$]=F:delete B[$],B})}catch(F){console.error("Error saving client formulary price override:",F),W.error((F==null?void 0:F.message)||"Unable to save price override.")}finally{Ve("")}}async function kt({pharmacy:s,drug:c,fields:M,applyDirectionsToAllPharmacies:T}){var ge;const p=A(c);if(!e||!p||!z||(c==null?void 0:c.ownerScope)==="providerNetwork")return!1;if(c!=null&&c.isFormularyVariant||c!=null&&c.formularyVariantId)try{const y=await qt(C,{clientId:e,variantId:c.formularyVariantId,medicationId:p,pharmacyMappingKey:(s==null?void 0:s.pharmacyMappingKey)||ut(s,e),...M,user:J.currentUser});return Pe(q=>[...q.filter(ae=>ae.id!==y.id),y]),!0}catch(y){return console.error("Error saving formulary medication variant:",y),W.error((y==null?void 0:y.message)||"Unable to save medication variant."),!1}if(Ct(s)){if((c==null?void 0:c.ownerScope)==="providerNetwork")return W.error("This custom medication is owned by the provider network. Duplicate it to create an editable copy."),!1;try{const y=await $t(C,{clientId:e,medicationId:p,...M,provenance:c,user:J.currentUser});return se(q=>q.map(Q=>A(Q)===A(y)?y:Q)),!0}catch(y){return console.error("Error saving custom formulary medication:",y),W.error((y==null?void 0:y.message)||"Unable to save custom medication."),!1}}const $=[{pharmacy:s,drug:c}];if(T&&(M==null?void 0:M.directions)!==void 0)for(const y of Ae){if(!y||y.id===(s==null?void 0:s.id))continue;const q=(Array.isArray(y.drugs)?y.drugs:[]).find(Q=>A(Q)===p);q&&$.push({pharmacy:y,drug:q,directionsOnly:!0})}const F=await Promise.allSettled($.map(async y=>{const q=A(y.drug),Q=y.directionsOnly?{directions:M.directions}:M,ae=await nr(C,{clientId:e,pharmacy:y.pharmacy,medicationId:q,fields:Q,defaults:Bt(y.drug,y.pharmacy),user:J.currentUser});return{key:Ne(y.pharmacy,q,e),saved:ae}})),te=F.filter(y=>y.status==="fulfilled").map(y=>y.value);te.length>0&&oe(y=>{const q={...y};for(const{key:Q,saved:ae}of te)ae?q[Q]=ae:delete q[Q];return q});const B=F.filter(y=>y.status==="rejected");return B.length>0?(console.error("Error saving formulary medication defaults:",B[0].reason),W.error(((ge=B[0].reason)==null?void 0:ge.message)||"Unable to save medication defaults for some pharmacies."),!1):!0}async function Ge({pharmacy:s,drug:c,isCustomRow:M,targetIdentity:T}){try{await da({scope:"client",clientId:e,sourceIdentity:ma({drug:c,pharmacy:s,isCustomFormulary:M}),targetIdentity:T})}catch(p){console.error("Error copying pharmacy send timing to the duplicate:",p),ke.error(p!=null&&p.message?`The copy was created, but its pharmacy send timing was not: ${p.message}`:"The copy was created, but its pharmacy send timing was not. Set it on the new row.")}}async function Ot({pharmacy:s,drug:c,row:M}){const T=A(c);if(!(!e||!T||!z||!ye)){pt(T);try{const p=!!(M!=null&&M.isCustomFormulary||Ct(s)),$=!!(M!=null&&M.inactiveFormularyMappingOnly||s!=null&&s.inactiveFormularyMappingOnly),F=Ne(s,T,e),te=G[F]||null;if(!p&&!$){const Q=ya(tr(st,T).map(ze=>ze.label)),ae=pa({drug:c,pharmacy:s,override:te,label:Q}),je=await qt(C,{clientId:e,medicationId:T,pharmacyMappingKey:(s==null?void 0:s.pharmacyMappingKey)||ut(s,e),...ae,user:J.currentUser});Pe(ze=>ze.some(Xe=>Xe.id===je.id)?ze.map(Xe=>Xe.id===je.id?je:Xe):[...ze,je]),pe(je.id),W.success("Duplicated as an OnlyScripts variant."),await Ge({pharmacy:s,drug:c,isCustomRow:p,targetIdentity:{kind:"variant",formularyVariantId:je.id}});return}let B=c;if(!p&&$){const Q=await Cr(T);Q&&(B=Fr(Q,c))}const ge=or({drug:B,pharmacy:s,override:te,isCustomFormulary:p,scopeId:Ce||e}),y=await $t(C,{clientId:e,...ge,user:J.currentUser}),q=A(y);se(Q=>Q.some(ae=>A(ae)===q)?Q.map(ae=>A(ae)===q?y:ae):[...Q,y]),pe(q),W.success("Duplicated into an editable copy."),await Ge({pharmacy:s,drug:c,isCustomRow:p,targetIdentity:{kind:"custom",customFormularyId:q}})}catch(p){console.error("Error duplicating formulary medication:",p),W.error((p==null?void 0:p.message)||"Unable to duplicate medication.")}finally{pt("")}}}function V(s){s||pe("")}function Te(s,c){const M=wt(s);M&&h(T=>({...T,[M]:c||{}}))}function vt(s){!s||Object.keys(s).length===0||h(c=>({...c,...s}))}const Lt=rt?Ce||e:"",Me=ye?"":"Requires prescribe-by-product on the linked provider network";return t?r.jsx("div",{className:"space-y-8 max-lg:space-y-3","data-testid":"client-formulary-panel",children:_?r.jsx("div",{className:"rounded-xl border border-border bg-card",children:r.jsx(Rt,{reason:"error",title:"Formulary unavailable",description:_,action:{label:"Retry",onClick:()=>{var s;return(s=P.refresh)==null?void 0:s.call(P)}}})}):!me&&rt&&Ae.length===0&&nt.length===0?r.jsx("div",{className:"rounded-xl border border-border bg-card",children:r.jsx(Rt,{reason:"empty",title:"No pharmacies enabled",description:z?"Enable an available pharmacy in Integrations to view its formulary.":"Ask your Client Admin to enable a pharmacy in Integrations.",action:z?{label:"Open Integrations",href:"/integrations"}:null})}):r.jsxs(r.Fragment,{children:[r.jsx(la,{includeInactiveMappedPharmacies:!1,exportReady:it&&O&&!S,pharmacies:Ae,clientId:e,products:Ke,mappingsByProductKey:d,canEdit:z,onToggleProduct:ot,onMappingsChange:vt,priceOverridesByKey:G,medicationOverridesByKey:G,networkMedicationOverridesByKey:yt,networkOverrideScopeId:Ce,canEditPriceOverrides:z,onSavePriceOverride:Je,savingPriceOverrideKey:
2Ft,editableMedicationFields:!0,showDirectionsColumn:!0,packageHeader:"Package size",networkDirectionSources:x,showEditColumn:z,showMessageTemplates:!1,onSaveMedicationFields:z?kt:null,onDuplicateMedication:z?Ot:null,duplicatingMedicationId:Et,duplicateDisabledReason:Me,focusedMedicationId:jt,openEditorForFocusedMedication:z,onEditorOpenChange:z?V:null,loading:me,pairingsHydrating:!Oe||!Re||be,overridesHydrating:!fe,surfaceTitle:"Formulary",canExportCsv:Nt,showSuperAdminPriceSync:n,onSyncClientPrices:n?xt:null,syncingClientPrices:Pt,hiddenMedicationIds:mt,canHide:z,showHidden:ft,onToggleHidden:ht,onToggleShowHidden:()=>qe(s=>!s),customMedications:nt,formularyVariants:st,customFormularyScopeId:Lt,showSendTimingColumn:!0,stretchToMaxHeight:!0},`${e}:${Ae.map(s=>s.integrationId).join("|")}`),r.jsx("div",{ref:_e,children:r.jsx(oa,{clientId:e,pharmacies:Ae,products:Ke,mappingsByProductKey:d,customMedications:nt,formularyVariants:st,customFormularyScopeId:Ce||e,priceOverridesByKey:G,canEdit:z,title:"Formulary mapping",description:"Pick a catalog product on the left, toggle formulary meds on the right; changes save as you edit.",onMappingsChange:Te,showQuantity:!0,loading:Ye})})]})}):null}function Gt({readOnly:t=!1,embedded:e=!1,hideHeader:n=!1,credentialManagerUserType:b=null}){const{userDoc:x}=at();return r.jsxs("main",{className:e?"space-y-4 max-lg:space-y-2.5":"app-page-shell space-y-4 max-lg:space-y-3 sm:space-y-8","data-testid":t?"page-formulary-client-staff":"page-formulary-client-admin",children:[n?null:r.jsx(dr,{title:"Formulary",titleClassName:"max-lg:truncate",description:t?"Review medications from enabled pharmacies and how they pair with catalog products. Contact a client admin to change pairings.":"Manage catalog pairings with medications from enabled pharmacies."}),r.jsx(Pr,{active:!0,clientId:x==null?void 0:x.clientId,showSuperAdminPriceSync:b==="Super Admin"})]})}const Xt=Ut.reduce((t,e)=>(e.key==="allowClinicalDifferenceOverwrite"?t[e.key]=!1:t[e.key]=e.type==="boolean"?!0:"",t),{}),jr=Object.fromEntries(Ut.map(t=>[t.key,t])),Ee="mb-1 block text-xs max-[1024px]:mb-0.5 max-[1024px]:text-2xs",De="h-9 max-[1024px]:h-8";function ve(t){var e;return((e=jr[t])==null?void 0:e.label)||t}function Er(t,e){if(t.key==="allowClinicalDifferenceOverwrite")return e[t.key]===!0;if(t.type==="boolean")return e[t.key]!==!1;if(t.type==="positiveInteger"||t.type==="nonNegativeInteger"){const n=e[t.key];return n===0||n==="0"?"0":n==null||n===""?"":String(n)}return e[t.key]||""}const Zt="provider-network-custom-formulary-form";function Nr({open:t=!1,onOpenChange:e,providerNetworkId:n,medications:b=[],loading:x=!1,canEdit:g=!1,onMedicationsChange:L}){var Ke,ne;const{availableClients:K,providerNetwork:U,selectedClientId:_}=at(),{branding:R}=aa(),[P,H]=i.useState(!1),[D,Z]=i.useState(""),[S,I]=i.useState(Xt),re=i.useMemo(()=>(Array.isArray(b)?b:[]).filter(d=>d.active!==!1),[b]),Y=i.useMemo(()=>(K||[]).find(d=>d.id===_)||null,[K,_]),be=((Ke=[Y==null?void 0:Y.displayName,Y==null?void 0:Y.companyName,Y==null?void 0:Y.name].find(d=>typeof d=="string"&&d.trim()))==null?void 0:Ke.trim())||"",we=((ne=[U==null?void 0:U.displayName,U==null?void 0:U.companyName,U==null?void 0:U.name,R==null?void 0:R.name].find(d=>typeof d=="string"&&d.trim()))==null?void 0:ne.trim())||"",Oe=be?`e.g. ${be} compound`:we?`e.g. ${we} compound`:"e.g. compound";function de(){Z(""),I(Xt)}i.useEffect(()=>{t||de()},[t]);function Re(d){Z(d.id);const h={};for(const G of Ut)h[G.key]=Er(G,d);I(h)}async function He(d){if(d.preventDefault(),!g||!n)return;const h=String(S.medicationName||"").trim();if(!h){W.error("Medication name is required.");return}H(!0);try{const G=await At(C,{providerNetworkId:n,medicationId:D||void 0,medicationName:h,strength:S.strength,doseForm:S.doseForm,directions:S.directions,pharmacyName:S.pharmacyName,quantity:S.quantity,refills:S.refills,daysSupply:S.daysSupply,clinicalDifferenceStatement:S.clinicalDifferenceStatement,allowClinicalDifferenceOverwrite:S.allowClinicalDifferenceOverwrite===!0?!0:null,active:S.active!==!1,user:J.currentUser}),oe=D?b.map(fe=>fe.id===D?G:fe):[...b,G].sort((fe,ee)=>fe.medicationName.localeCompare(ee.medicationName));L==null||L(oe),W.success(D?"Custom medication updated":"Custom medication added"),e==null||e(!1)}catch(G){console.error("Error saving custom formulary medication:",G),W.error((G==null?void 0:G.message)||"Unable to save custom medication.")}finally{H(!1)}}return r.jsx(Pa,{open:t,onOpenChange:d=>{P||e==null||e(d)},title:"Custom formulary",description:"Add or edit non-OnlyScripts medications for save-only prescribing.",contentClassName:"max-w-2xl",contentTestId:"dialog-formulary-custom-formulary",closeLabel:"Close custom formulary",footerClassName:"bg-slate-100 dar
2k:bg-slate-900 max-[1024px]:gap-1.5 max-[1024px]:px-3 max-[1024px]:py-2.5",footer:g?r.jsxs(r.Fragment,{children:[r.jsx(tt,{type:"button",variant:"outline",className:"rounded-full",disabled:P,onClick:()=>e==null?void 0:e(!1),children:"Cancel"}),r.jsxs(tt,{type:"submit",form:Zt,className:"rounded-full text-white",style:{backgroundColor:(R==null?void 0:R.accentColor)||sa},disabled:P||!n,children:[P?r.jsx(ia,{size:"md",className:"mr-2"}):null,D?"Save changes":"Add medication"]})]}):null,children:r.jsx("form",{id:Zt,onSubmit:He,children:r.jsxs(ja,{className:"overflow-hidden bg-surface-raised p-0",children:[r.jsxs("div",{className:"px-4 py-3 max-[1024px]:px-2.5 max-[1024px]:py-2",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3 max-[1024px]:gap-1.5",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-content-primary max-[1024px]:text-xs",children:"Custom medications"}),r.jsx("p",{className:"mt-0.5 text-xs text-content-secondary max-[1024px]:text-2xs",children:"Pair these medications to protocols from the formulary table."})]}),g?r.jsxs(tt,{type:"button",size:"sm",variant:"outline",className:"h-8 rounded-full px-3 text-xs max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",onClick:de,disabled:P,children:[r.jsx(ra,{className:"mr-1 size-3.5 max-[1024px]:h-3 max-[1024px]:w-3","aria-hidden":!0}),"New medication"]}):null]}),x?r.jsxs("p",{className:"mt-3 inline-flex items-center gap-2 text-xs text-content-tertiary max-[1024px]:mt-2 max-[1024px]:gap-1.5 max-[1024px]:text-2xs",children:[r.jsx(Ea,{className:"size-3.5 animate-spin max-[1024px]:h-3 max-[1024px]:w-3","aria-hidden":!0}),"Loading custom medications..."]}):null,!x&&re.length>0?r.jsx("div",{className:"mt-3 divide-y divide-slate-200 dark:divide-slate-700 max-[1024px]:mt-2",children:re.map(d=>r.jsxs("div",{className:"flex items-center justify-between gap-3 py-2.5 max-[1024px]:gap-2 max-[1024px]:py-2",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"truncate text-sm font-medium text-content-primary max-[1024px]:text-xs",children:d.medicationName}),r.jsx("p",{className:"truncate text-xs text-content-secondary max-[1024px]:text-2xs",children:[d.strength,d.doseForm,d.directions,d.pharmacyName].filter(Boolean).join(" · ")||"No strength or directions yet"})]}),g?r.jsx(tt,{type:"button",size:"sm",variant:"ghost",className:"h-8 rounded-full px-3 text-xs max-[1024px]:h-7 max-[1024px]:min-h-7 max-[1024px]:px-2 max-[1024px]:text-2xs",onClick:()=>Re(d),children:"Edit"}):null]},d.id))}):null,!x&&re.length===0?r.jsx("p",{className:"mt-3 text-sm text-content-secondary max-[1024px]:mt-2 max-[1024px]:text-xs",children:"No custom medications yet."}):null]}),r.jsxs("div",{className:"grid gap-3 border-t border-subtle px-4 py-4 sm:grid-cols-2 max-[1024px]:gap-2 max-[1024px]:px-2.5 max-[1024px]:py-2.5",children:[r.jsxs("div",{className:"sm:col-span-2",children:[r.jsx(xe,{htmlFor:"custom-formulary-medication-name",className:Ee,children:ve("medicationName")}),r.jsx(Be,{id:"custom-formulary-medication-name",value:S.medicationName,onChange:d=>I(h=>({...h,medicationName:d.target.value})),className:De,placeholder:Oe,autoComplete:"off",required:!0})]}),r.jsxs("div",{children:[r.jsx(xe,{htmlFor:"custom-formulary-strength",optional:!0,className:Ee,children:ve("strength")}),r.jsx(Be,{id:"custom-formulary-strength",value:S.strength,onChange:d=>I(h=>({...h,strength:d.target.value})),className:De,placeholder:"e.g. 10 mg/mL"})]}),r.jsxs("div",{children:[r.jsx(xe,{htmlFor:"custom-formulary-dose-form",optional:!0,className:Ee,children:ve("doseForm")}),r.jsx(Be,{id:"custom-formulary-dose-form",value:S.doseForm,onChange:d=>I(h=>({...h,doseForm:d.target.value})),className:De,placeholder:"e.g. cream"})]}),r.jsxs("div",{className:"sm:col-span-2",children:[r.jsx(xe,{htmlFor:"custom-formulary-directions",optional:!0,className:Ee,children:ve("directions")}),r.jsx(Be,{id:"custom-formulary-directions",value:S.directions,onChange:d=>I(h=>({...h,directions:d.target.value})),className:De,placeholder:"Patient-facing sig"})]}),r.jsxs("div",{className:"sm:col-span-2",children:[r.jsx(xe,{htmlFor:"custom-formulary-pharmacy-name",optional:!0,className:Ee,children:ve("pharmacyName")}),r.jsx(Be,{id:"custom-formulary-pharmacy-name",value:S.pharmacyName,onChange:d=>I(h=>({...h,pharmacyName:d.target.value})),className:De,placeholder:"e.g. compounding pharmacy",autoComplete:"off"})]}),r.jsxs("div",{children:[r.jsx(xe,{htmlFor:"custom-formulary-quantity",optional:!0,className:Ee,children:ve("quantity")}),r.jsx(Be,{id:"custom-formulary-quantity",value:S.quantity,onChange:d=>I(h=>({...h,quantity:ar(d.target.value)})),className:De,inputMode:"decimal",placeholder:"e.g. 30"})]}),r.jsxs("div",{children:[r.jsx(xe,{htmlFor:"custom-formulary-refills",optional:!0,className:Ee,children:ve("refills")}),r.jsx(Be,{id:"custom-formulary-refills",value:S.refills,onChange:d=>I(h=>({...h,refills:d.target.value.replace(/[^0-9]/g,"")})),className:De,inputMode:"numeric",placeholder:"e.g. 0"})]}),r.jsxs("div",{children:[r.jsx(xe,{htmlFor:"custom-formulary-days-supply",optional:!0,className:Ee,children:ve("daysSupply")}),r.jsx(Be,{id:"custom-formulary-days-supply",value:S.daysSupply,onChange:d=>I(h=>({...h,daysSupply:d.target.value.replace(/[^0-9]/g,"")})),className:De,inputMode:"numeric",placeholder:"e.g. 30"})]}),r.jsxs("div",{className:"sm:col-span-2",children:[r.jsx(xe,{htmlFor:"custom-formulary-clinical-difference",optional:!0,className:Ee,children:ve("clinicalDifferenceStatement")}),r.jsx(Na,{id:"custom-formulary-clinical-difference",value:S.clinicalDifferenceStatement||"",onChange:d=>I(h=>({...h,clinicalDifferenceStatement:d.target.value})),maxLength:2e3,rows:3,placeholder:"Optional"})]}),r.jsxs("div",{className:"flex items-center gap-2 sm:col-span-2",children:[r.jsx(Ht,{id:"custom-formulary-allow-overwrite",checked:S.allowClinicalDifferenceOverwrite===!0,onCheckedChange:d=>I(h=>({...h,allowClinicalDifferenceOverwrite:d===!0})),disabled:!g||P,"data-testid":"switch-custom-formulary-allowClinicalDifferenceOverwrite"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx(xe,{htmlFor:"custom-formulary-allow-overwrite",optional:!0,className:"text-xs text-content-secondary max-[1024px]:text-2xs",children:ve("allowClinicalDifferenceOverwrite")}),r.jsx("p",{className:"text-xs text-muted-foreground",children:"Prescribers can edit this statement on each prescription line before it is sent. When off, the statement is sent as written."})]})]}
2),r.jsxs("div",{className:"flex items-center gap-2 self-end pb-1",children:[r.jsx(Ht,{id:"custom-formulary-active",checked:S.active!==!1,onCheckedChange:d=>I(h=>({...h,active:d===!0}))}),r.jsx(xe,{htmlFor:"custom-formulary-active",optional:!0,className:"text-xs text-content-secondary max-[1024px]:text-2xs",children:ve("active")})]})]})]})})})}const kr=i.lazy(()=>ka(()=>import("./MessageTemplatesDialog-B1HeT6bA.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23])).then(t=>({default:t.MessageTemplatesDialog})));function et(t={}){const e=ue(t.pharmacyId||t.externalPharmacyId);if(e)return e;const n=ue(t.id).split(":").filter(Boolean);return n.length>=3?n[n.length-1]:ue(t.id)}function Or(t={}){return ue(t.type||"product").toLowerCase()==="product"}function Lr(t={}){const e=Number(t.errorStatus||t.statusCode||t.status),n=ue(t.error||t.message).toLowerCase();return e===403||n.includes("status code 403")||n.includes("status 403")}function Ir(t={}){if(!t||t.inactiveFormularyMappingOnly||t.active===!1||t.enabled===!1)return!1;const e=ue(t.status||t.integrationStatus||t.state).toLowerCase();return!["inactive","disabled","archived","deleted"].includes(e)}function Ar(t=[],e=[]){return JSON.stringify(t)===JSON.stringify(e)}function Tr(t=[],e={}){const n=Array.isArray(t)?t:[],b=n.findIndex(g=>g.id===e.id);if(b===-1)return[...n,e];const x=n.slice();return x[b]=e,x}function Br({active:t,providerNetworkId:e,fixedProduct:n=null,showMedicationTable:b=!0,priceOverrideScope:x=null,showCustomMedicationNames:g=!1,renderExtraActions:L=null,canEdit:K=null,liveEligibility:U=!1}){const{userType:_,availableClients:R=[]}=at(),P=U&&Kt(_,"Provider Network Admin"),H=ea("providerNetwork",t&&P?e:""),D=H.readiness,Z=H.error,[S,I]=i.useState([]),[re,Y]=i.useState(""),[be,we]=i.useState("");i.useEffect(()=>{let a=!1;return I([]),t&&e&&rr(C,e,{includeInactive:!0}).then(o=>{a||I([...o.values()])}).catch(()=>{a||ke.error("Unable to load formulary options. Reload the page to retry.")}),()=>{a=!0}},[t,e]);const{branding:Oe}=aa(),de=(Oe==null?void 0:Oe.accentColor)||sa,{confirmAction:Re,confirmDialog:He}=Oa({accentColor:de}),[Ke,ne]=i.useState(!1),[d,h]=i.useState(!1),[G,oe]=i.useState(""),[fe,ee]=i.useState([]),[Ft,Ve]=i.useState(!1),[Pt,Le]=i.useState(!1),[mt,Se]=i.useState(!1),[ft,qe]=i.useState([]),[ye,le]=i.useState({}),[Ce,Qe]=i.useState([]),[yt,We]=i.useState(!1),[rt,$e]=i.useState("");i.useEffect(()=>{if(Qe([]),We(!1),$e(""),!t||!e)return;let a=!1;return mr({ownerType:"providerNetwork",scopeId:e,includeGlobal:!1}).then(o=>{a||(Qe(o.filter(l=>(l.status||"active")==="active").sort((l,v)=>(l.name||"").localeCompare(v.name||""))),We(!0))}).catch(()=>{a||$e("Categories could not load. Reload the page to try again.")}),()=>{a=!0}},[t,e]);const[Fe,se]=i.useState({}),[st,Pe]=i.useState(!1),[jt,pe]=i.useState(()=>new Set),[Et,pt]=i.useState(!1),[_e,z]=i.useState([]),[Nt,it]=i.useState(!1),[X,gt]=i.useState(!1),[ht,xt]=i.useState(!1),O=typeof K=="boolean"?K:Kt(_,"Provider Network Admin")||_==="Super Admin",Ie=ta(_,["Provider","Provider Network Admin","Provider Delegate"]),[nt,Ae]=i.useState(""),me=(x==null?void 0:x.type)==="client"?ue(x.id):"",Ye=!!me,[ot,Je]=i.useState({}),[kt,Ge]=i.useState(!0),{exportReady:Ot,setExportSourceReady:V}=xa(e?`${e}:${me}:${(n==null?void 0:n.id)||""}`:"",["catalog","mappings","overrides","prices","custom","hidden"]);i.useEffect(()=>{var f;if(!t)return;if(!e){ne(!1),h(!0),ee([]);return}if(P&&!D){ee([]),h(!!Z),ne(!Z),oe(Z?"Unable to check pharmacy access. Reload to retry.":""),V("catalog",!1);return}let a=!1;const o=typeof AbortController<"u"?new AbortController:null;V("catalog",!1),h(!1);const l=D?new Set(D.pharmacies.map(m=>et(m))):null,v=(f=za(e))==null?void 0:f.filter(m=>!l||l.has(et(m)));return v?(ee(v),h(!0),ne(!1)):ne(!0),oe(""),(async()=>{try{const m=D||await La({providerNetworkId:e});if(a)return;const ie=(Array.isArray(m.pharmacies)?m.pharmacies:[]).filter(k=>ue(k.source).toLowerCase()==="onlyscripts").map(k=>qa({...k,pharmacyId:et(k)},e));if(!v){let k=null;try{await fr({providerNetworkId:e,pharmacies:ie,signal:o==null?void 0:o.signal,onPage:u=>{a||u.some(N=>(N.drugs||[]).length>0)&&(k=u,ee(u),h(!0),ne(!1))}})}catch(u){console.error("Error seeding provider network formulary from search:",u)}if(k&&_t(e,k),a)return}const j=await Promise.all(ie.map(async k=>{const u=et(k);let N;try{const w=await Ia({providerNetworkId:e,integrationId:k.integrationId,integrationScopeType:k.integrationScopeType,integrationScopeId:k.integrationScopeId,p
2harmacyId:u,catalogOnly:P,useCache:!1});N={...k,drugs:Array.isArray(w.drugs)?w.drugs:[],error:null}}catch(w){N={...k,drugs:[],error:(w==null?void 0:w.message)||"Unable to load formulary.",errorStatus:(w==null?void 0:w.status)||(w==null?void 0:w.statusCode)}}return a||ee(w=>Tr(w,N)),N}));if(a)return;ee(k=>Ar(k,j)?k:j),_t(e,j),V("catalog",j.every(k=>!k.error))}catch(m){if(a)return;v?console.error("Error refreshing cached provider network formulary:",m):(oe((m==null?void 0:m.message)||"Unable to load formulary."),ee([]))}finally{a||(h(!0),ne(!1))}})(),()=>{a=!0,o==null||o.abort()}},[t,e,V,P,D,Z]),i.useEffect(()=>{if(!t)return;if(!e){Ve(!1),Le(!0),Se(!0),qe(n?[n]:[]),le({});return}let a=!1;const o=`providerNetwork:${e}`,l=n?[n]:Qa(e),v=l?Wa(o,l):null;return V("mappings",!1),Le(!1),Se(!1),l&&(qe(l),Le(!0)),v&&(le(v),Se(!0)),Ve(!l||!v),(async()=>{try{const f=n?[n]:(await Ya(C,e,{useCache:!1})).filter(Or);if(a)return;qe(f),Le(!0);const m=await Ja(C,{providerNetworkId:e,products:f,useCache:!1});if(a)return;le(m),V("mappings",!0),Se(!0)}catch(f){if(a)return;console.error("Error loading provider network formulary mappings:",f),l||(qe([]),Le(!0)),v||(le({}),Se(!0))}finally{a||Ve(!1)}})(),()=>{a=!0}},[t,n,e,V]),i.useEffect(()=>{if(!t||!e){se({}),Pe(!0);return}let a=!1;return V("overrides",!1),Pe(!1),(async()=>{try{const o=await ga(C,e,{useCache:!1});if(a)return;se(dt(o)),V("overrides",!0)}catch(o){if(a)return;console.error("Error loading formulary medication overrides:",o),se({})}finally{a||Pe(!0)}})(),()=>{a=!0}},[t,e,V]),i.useEffect(()=>{if(!t||!me){V("prices",!me),Je({}),Ge(!0);return}let a=!1;return V("prices",!1),Ge(!1),(async()=>{try{const o=await Tt(C,me,{useCache:!1});if(a)return;Je(dt(o)),V("prices",!0)}catch(o){if(a)return;console.error("Error loading formulary price overrides:",o),Je({})}finally{a||Ge(!0)}})(),()=>{a=!0}},[t,me,V]),i.useEffect(()=>{if(!t||!e){z([]),it(!0);return}let a=!1;return V("custom",!1),it(!1),(async()=>{try{const o=await fa(C,e,{includeInactive:!0});if(a)return;z(o),V("custom",!0)}catch(o){if(a)return;console.error("Error loading custom formulary medications:",o),z([])}finally{a||it(!0)}})(),()=>{a=!0}},[t,e,V]),i.useEffect(()=>{var o;if(!t||!e){pe(new Set);return}if(P){pe(((o=H.visibility)==null?void 0:o.ownHiddenIds)||new Set),V("hidden",!!H.visibility);return}let a=!1;return V("hidden",!1),(async()=>{try{const l=await Ma(C,{scope:"providerNetwork",scopeId:e},{useCache:!1});if(a)return;pe(new Set(l)),V("hidden",!0)}catch(l){if(a)return;console.error("Error loading formulary hidden medications:",l),pe(new Set)}})(),()=>{a=!0}},[t,e,V,P,H.visibility]);const Te=i.useMemo(()=>(R||[]).filter(a=>Aa(a)&&Ta(a).includes(e)).map(a=>({id:String(a.id||"").trim(),name:a.displayName||a.name||a.companyName||"Client"})).filter(a=>a.id).sort((a,o)=>a.name.localeCompare(o.name)),[R,e]),vt=i.useCallback(a=>{const o=fe.flatMap(l=>l.drugs||[]).find(l=>A(l)===a)||_e.find(l=>A(l)===a);return o?bt(o):"this medication"},[_e,fe]),Lt=i.useCallback(async(a,o)=>{if(!e||!O)return;const l=Array.isArray(a)?a:[a];if(l.length===0)return;if(o){const f=l.length===1?vt(l[0]):"";if(!await Re({title:l.length===1?"Hide medication?":`Hide ${l.length} medications?`,description:r.jsxs("span",{className:"block space-y-3",children:[r.jsx("span",{children:l.length===1?r.jsxs(r.Fragment,{children:["Hiding"," ",r.jsx("span",{className:"font-medium text-content-primary",children:f})," ","hides it from affiliate clients on this network. They will not see it on Formulary, product pairing, or prescribing."]}):r.jsx(r.Fragment,{children:"These medications will be hidden from affiliate clients on this network. They will not see them on Formulary, product pairing, or prescribing."})}),r.jsx("span",{className:"block text-sm text-content-secondary",children:"Review + Prescribe clients keep their own formulary and are not affected."}),r.jsxs("span",{className:"block",children:[r.jsx("span",{className:"font-medium text-content-primary",children:Te.length===0?"No affiliate clients are linked to this network right now":`${Te.length} affiliate client${Te.length===1?"":"s"} will no longer see ${l.length===1?"this medication":"these medications"}`}),Te.length>0?r.jsx("ul",{className:"mt-2 max-h-32 list-disc space-y-1 overflow-y-auto pl-5 text-sm text-content-secondary",children:Te.map(E=>r.jsx("li",{children:E.name},E.id))}):null]})]}),tone:"warning",confirmLabel:l.length===1?"Hide medication":"Hide medications",contentTestId:"dialog-formulary-hide-medication",confirmTestId:"button-formulary-hide-medication-confirm"}))return}let v;pe(f=>{v=f;const m=new Set(f);return l.forEach(E=>o?m.add(E):m.delete(E)),m});try{const f=await wa(C,{scope:"providerNetwork",scopeId:e,medicationIds:l,hidden:o,user:J.currentUser});pe(new Set(f))}catch(f){console.error("Error updating formulary medication visibility:",f),v&&pe(v),W.error((f==null?void 0:f.message)||"Unable to update medication visibility.")}},[Te,O,Re,e,vt]),Me=i.useMemo(()=>P&&(!D||!H.visibility)?[]:fe.filter(a=>Ir(a)&&!Lr(a)),[fe,P,D,H.visibility]),s=Ke||!d||P&&!Z&&(!D||!H.visibility),c=!d||!Pt,M=!mt||Ft,T=!mt,p=!st||Ye&&!kt;
2async function $({pharmacy:a,drug:o,isCustomRow:l,targetIdentity:v}){try{await da({scope:"providerNetwork",providerNetworkId:e,sourceIdentity:ma({drug:o,pharmacy:a,isCustomFormulary:l}),targetIdentity:v})}catch(f){console.error("Error copying pharmacy send timing to the duplicate:",f),ke.error(f!=null&&f.message?`The copy was created, but its pharmacy send timing was not: ${f.message}`:"The copy was created, but its pharmacy send timing was not. Set it on the new row.")}}async function F({pharmacy:a,drug:o}){if(!O||!e)return;const l=A(o);we(l);try{if(Ct(a)){const m=await At(C,{providerNetworkId:e,...o,medicationId:"",id:"",provenance:o,medicationName:`${bt(o)} (copy)`,user:J.currentUser});z(E=>[...E,m]),Y(m.id),await $({pharmacy:a,drug:o,isCustomRow:!0,targetIdentity:{kind:"custom",customFormularyId:m.id}});return}const v=o.isFormularyVariant?o:Fe[Ne(a,l,e)],f=await Qt(C,{providerNetworkId:e,medicationId:l,pharmacyId:et(a),pharmacyMappingKey:ut(a,e),...pa({drug:o,pharmacy:a,override:v,label:ya(S.filter(m=>m.medicationId===l).map(m=>m.label))}),user:J.currentUser});I(m=>[...m,f]),Y(f.id),ke.success("Formulary option duplicated."),await $({pharmacy:a,drug:o,isCustomRow:!1,targetIdentity:{kind:"variant",formularyVariantId:f.id}})}catch(v){ke.error(v.message||"Unable to duplicate this option. Try again.")}finally{we("")}}const te=i.useCallback(async({pharmacy:a,drug:o,fields:l,applyDirectionsToAllPharmacies:v})=>{var k;if(o!=null&&o.isFormularyVariant){if(!O)return!1;try{const u=await Qt(C,{providerNetworkId:e,variantId:o.formularyVariantId,medicationId:A(o),pharmacyId:et(a),pharmacyMappingKey:ut(a,e),...l,user:J.currentUser});return I(N=>N.map(w=>w.id===u.id?u:w)),!0}catch(u){return ke.error(u.message),!1}}const f=A(o);if(!e||!f||!O)return!1;if(Ct(a))try{const u=await At(C,{providerNetworkId:e,medicationId:f,...l,user:J.currentUser});return z(N=>N.map(w=>w.id===u.id?{...w,...u}:w)),!0}catch(u){return console.error("Error saving custom formulary medication:",u),W.error((u==null?void 0:u.message)||"Unable to save custom medication."),!1}const m=[{pharmacy:a,drug:o}];if(v&&(l==null?void 0:l.directions)!==void 0)for(const u of Me){if(!u||u.id===(a==null?void 0:a.id))continue;const N=(Array.isArray(u.drugs)?u.drugs:[]).find(w=>A(w)===f);N&&m.push({pharmacy:u,drug:N,directionsOnly:!0})}const E=await Promise.allSettled(m.map(async u=>{const N=A(u.drug),w=u.directionsOnly?{directions:l.directions}:l,he=await Wt(C,{providerNetworkId:e,pharmacy:u.pharmacy,medicationId:N,fields:w,defaults:Bt(u.drug,u.pharmacy),user:J.currentUser});return{key:Ne(u.pharmacy,N,e),saved:he}})),ie=E.filter(u=>u.status==="fulfilled").map(u=>u.value);ie.length>0&&se(u=>{const N={...u};for(const{key:w,saved:he}of ie)he?N[w]=he:delete N[w];return N});const j=E.filter(u=>u.status==="rejected");return j.length>0?(console.error("Error saving formulary medication defaults:",j[0].reason),W.error(((k=j[0].reason)==null?void 0:k.message)||"Unable to save medication defaults for some pharmacies."),!1):!0},[O,e,Me]),B=i.useCallback(async({pharmacy:a,drug:o,fields:l})=>{const v=A(o);if(!e||!v||!O)return!1;const f=Ne(a,v,e),m=E=>Object.prototype.hasOwnProperty.call(l||{},E);if(m("price")&&!me)return!1;try{if(m("customName")||m("categoryIds")){const E=await Wt(C,{providerNetworkId:e,pharmacy:a,medicationId:v,fields:{...m("customName")?{customName:l.customName}:{},...m("categoryIds")?{categoryIds:l.categoryIds}:{}},defaults:Bt(o,a),user:J.currentUser});se(ie=>{const j={...ie};return E?j[f]=E:delete j[f],j})}if(m("price")){const E=await ha(C,{clientId:me,pharmacy:a,medicationId:v,field:"price",value:l.price,defaultValue:lr(o),user:J.currentUser});Je(ie=>{const j={...ie};return E?j[f]=E:delete j[f],j})}return!0}catch(E){return console.error("Error saving medication override:",E),W.error((E==null?void 0:E.message)||"Unable to save medication changes. Try again."),!1}},[O,me,e]),ge=i.useCallback(async({pharmacy:a,drug:o,value:l})=>{const v=A(o),f=Ne(a,v,e);Ae(`${f}:price`);try{await B({pharmacy:a,drug:o,fields:{price:l}})}finally{Ae("")}},[B,e]),y=i.useCallback((a,o)=>{const l=bt(a);return!g||!e?l:cr({overridesByKey:Fe,pharmacy:o,medicationId:A(a),providerNetworkId:e})||l},[Fe,g,e]),q=typeof L=="function",Q=i.useMemo(()=>
2{if(!q)return[];const a=[];return Me.forEach(o=>{(Array.isArray(o.drugs)?o.drugs:[]).forEach(l=>{const v=A(l);if(!v)return;const f=Ne(o,v,e),m=Fe[f]||null,E=bt(l);a.push({key:f,pharmacy:o,drug:l,override:m,priceOverride:ot[f]||null,originalLabel:E,label:y(l,o)||E,pharmacyName:ue(o.name||o.pharmacyName||o.id)})})}),a.sort((o,l)=>o.label.localeCompare(l.label))},[y,q,Fe,ot,e,Me]),ae=i.useCallback(async({pharmacy:a,drug:o,messageTemplateIds:l,applyMessageTemplatesToAllPharmacies:v})=>{var k;const f=A(o);if(!e||!f||!O)return!1;const m=[{pharmacy:a,drug:o}];if(v)for(const u of Me){if(!u||u.id===(a==null?void 0:a.id))continue;const N=(Array.isArray(u.drugs)?u.drugs:[]).find(w=>A(w)===f);N&&m.push({pharmacy:u,drug:N})}const E=await Promise.allSettled(m.map(async u=>{const N=A(u.drug),w=await ur(C,{providerNetworkId:e,pharmacy:u.pharmacy,medicationId:N,messageTemplateIds:l,user:J.currentUser});return{key:Ne(u.pharmacy,N,e),saved:w}})),ie=E.filter(u=>u.status==="fulfilled").map(u=>u.value);ie.length>0&&se(u=>{const N={...u};for(const{key:w,saved:he}of ie)he?N[w]=he:delete N[w];return N});const j=E.filter(u=>u.status==="rejected");return j.length>0?(console.error("Error saving formulary message templates:",j[0].reason),W.error(((k=j[0].reason)==null?void 0:k.message)||"Unable to save message templates for some pharmacies."),!1):!0},[O,e,Me]);async function je({product:a,drug:o,pharmacy:l,nextChecked:v}){const f=A(o),m=wt(a);if(!e||!f||!m)return;const E=ye[m]||{},ie=sr(E,l,e),j=Xa(E,l,e),k=ir({currentIds:ie,currentVariantIdByMedicationId:(j==null?void 0:j.variantIdByMedicationId)||{},currentVariantIdsByMedicationId:(j==null?void 0:j.variantIdsByMedicationId)||{},medicationId:f,variantId:o.formularyVariantId||"",nextChecked:v}),u=k.medicationIds,N=ut(l,e),w=ye[m],he={};Object.entries((j==null?void 0:j.directionsByMedicationId)||{}).forEach(([ce,lt])=>{u.includes(ce)&&(he[ce]=lt)}),le(ce=>({...ce,[m]:{...ce[m]||{},[N]:{...j||{},pharmacyMappingKey:N,medicationIds:u,directionsByMedicationId:he,variantIdByMedicationId:k.variantIdByMedicationId,variantIdsByMedicationId:k.variantIdsByMedicationId,hasOverride:!0}}}));try{const{mappingKey:ce,payload:lt}=await zt(C,{providerNetworkId:e,product:a,pharmacy:l,medicationIds:u,variantIdsByMedicationId:k.variantIdsByMedicationId,variantIdByMedicationId:k.variantIdByMedicationId,medications:Array.isArray(l==null?void 0:l.drugs)?l.drugs:[o],directionsByMedicationId:(j==null?void 0:j.directionsByMedicationId)||{},user:J.currentUser});le(Ze=>({...Ze,[m]:{...Ze[m]||{},[ce]:{...lt,hasOverride:!0}}}))}catch(ce){le(lt=>{const Ze={...lt};return w===void 0?delete Ze[m]:Ze[m]=w,Ze}),console.error("Error saving provider network formulary mapping:",ce),W.error((ce==null?void 0:ce.message)||"Unable to save formulary mapping.")}}function ze(a,o){const l=wt(a);l&&le(v=>({...v,[l]:o||{}}))}function Xe(a){!a||Object.keys(a).length===0||le(o=>({...o,...a}))}return t?r.jsxs("div",{className:"space-y-8 max-lg:space-y-3","data-testid":"provider-network-formulary-panel",children:[rt?r.jsx("p",{role:"alert",className:"text-sm text-destructive",children:rt}):null,G?r.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 max-lg:text-xs",role:"alert",children:G}):null,r.jsxs(r.Fragment,{children:[b?r.jsxs(r.Fragment,{children:[r.jsx(la,{exportReady:Ot&&yt,canExportCsv:!0,pharmacies:Me,clientId:e,getMedicationDisplayLabel:g?y:null,priceOverridesByKey:Ye?ot:void 0,canEditPriceOverrides:Ye&&O,onSavePriceOverride:Ye&&O?ge:null,savingPriceOverrideKey:nt,products:ft,mappingsByProductKey:ye,canEdit:O,scope:"providerNetwork",onToggleProduct:je,onMappingsChange:Xe,surfaceId:"provider-network-formulary-medications",surfaceTitle:"Formulary",surfaceActions:O||Ie?r.jsxs("div",{className:"flex flex-wrap items-center gap-2 max-lg:flex-nowrap max-lg:gap-1 max-lg:[&>*]:shrink-0",children:[Ie?r.jsxs(tt,{type:"button",variant:"outline",size:"sm",className:"h-8 text-xs dark:border-slate-600 dark:hover:bg-slate-700 max-lg:h-6 max-lg:min-h-6 max-lg:px-2 max-lg:text-3xs",onClick:()=>xt(!0),"data-testid":Ba("button","formulary","message-templates"),children:[r.jsx(pr,{className:"mr-1.5 size-3.5 max-lg:mr-1 max-lg:size-3","aria-hidden":!0}),"Message Templates"]}):null,typeof L=="function"?L({canEdit:O,accentColor:de,medications:Q,saveMedicationOverrideFields:B}):null,O?r.jsxs(tt,{type:"button",size:"sm",className:"h-8 rounded-full px-3 text-xs text-white max-lg:h-6 max-lg:min-h-6 max-lg:px-2 max-lg:text-3xs",style:{backgroundColor:de},onClick:()=>gt(!0),"data-testid":"button-formulary-add-custom-formulary",children:[r.jsx(ra,{className:"mr-1.5 size-3.5 max-lg:mr-1 max-lg:size-3","aria-hidden":!0}),"Add custom formulary"]}):null]}):null,tableTestId:"table-provider-network-formulary-medications",loading:s,formularyVariants:S,onDuplicateMedication:O?F:null,duplicatingMedicationId:be,focusedMedicationId:re,openEditorForFocusedMedication:!0,onEditorOpenChange:a=>{a||Y("")},showEditColumn:O,showDirectionsColumn:!0,showClinicalDifferenceColumn:!0,showDirxMedicalNecessityColumn:!0,showQuantityColumn:!0,showDaysSupplyColumn:!0,pairedProductsHeader:"Protocols",pairedItemLabel:"protocol",packageHeader:"Package size",editableMedicationFields:O,showMessageTemplates:O,medicationCategories:Ce,medicationCategoriesLoading:!yt,onSaveMedicationCategories:B,medicationOverridesByKey:Fe,onSaveMedicationFields:te,onSaveMessageTemplates:ae,hiddenMedicationIds:jt,canHide:O,showHidden:Et,onToggleHidden:Lt,onToggleShowHidden:()=>pt(a=>!a),maxHeight:yr,stretchToMaxHeight:!0,pairingsHydrating:T,overridesHydrating:p,customMedications:_e.filter(a=>a.active!==!1),customFormularyScopeId:e,showSendTimingColumn:!0}),r.jsx(Nr,{open:X,onOpenChange:gt,providerNetworkId:e,medications:_e,loading:!Nt,canEdit:O,onMedicationsChange:z}),ht?r.jsx(i.Suspense,{fallback:null,children:r.jsx(kr,{open:ht,onOpenChange:xt,accentColor:de,canManage:Ie,testIdScope:"formulary"})}):null]}):null,He,r.jsx("div",{className:"min-w-0",children:r.jsx(oa,{clientId:e,scopeId:e,pharmacies:Me,products:ft,mappingsByProductKey:ye,customMedications:_e.filter(a=>a.active!==!1),customFormularyScopeId:e,canEdit:O,fixedProduct:n,title:n?"Formulary defaults":"Formulary mapping",description:n?"Pair OnlyScripts medications with this protocol.":"Select one or more protocols on the left, pair medications on the right, then save.",onMappingsChange:ze,saveMapping:zt,resetMapping:Ga,variant:"providerNetwork",showQuantity:!0,loading:c,overlayLoading:M})})]})]}):null}function Dr(){const{userDoc:t,providerNetwork:e}=at(),n=(t==null?void 0:t.providerNetworkId)||(e==null?void 0:e.id)||null;return r.jsxs("main",{className:"app-page-shell space-y-8 max-lg:space-y-3","data-testid":"page-formulary-provider-network-admin",children:[r.jsx(na,{headerId:"formulary-network",titleClassName:"max-lg:truncate",descriptionClassName:"max-lg:mt-0.5"}),r.jsx(Br,{active:!0,liveEligibility:!0,providerNetworkId:n})]})}function ks({embedded:t=!1,hideHeader:e=!1,credentialManagerUserType:n=null}){const{userType:b,loading:x}=at();if(x)return r.jsx("div",{className:t?"space-y-4":"app-page-shell space-y-6",children:r.jsx(ia,{label:"Loading formularyâ¦"})});let g;switch(b){case"Client Admin":g=r.jsx(Gt,{embedded:t,hideHeader:e,credentialManagerUserType:n});break;case"Client Staff":g=r.jsx(Gt,{readOnly:!0,embedded:t,hideHeader:e,credentialManagerUserType:n});break;case"Provider Network Admin":g=r.jsx(Dr,{});break;default:return r.jsxs("main",{className:"app-page-shell space-y-6",children:[r.jsx(na,{title:"Formulary"}),r.jsx(gr,{description:"This page is only available to formulary-enabled tenant administrators and staff."})]})}return g}export{ks as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.