1import{i as e}from"./rolldown-runtime-jxEyR9vv.js";import{v as t}from"./charts-BqcS3ABW.js";import{d as a,l as s,t as i,u as n}from"./react-aNZyGp20.js";import{t as r}from"./axios-DPlPz_4c.js";import{At as o,Ht as l,St as c,i as d,it as u}from"./icons-B3484nFG.js";import{c as p,i as m,l as g,n as f,r as h,s as x}from"./index-CpvLNjQu.js";import{t as b}from"./alert-C8dtXGVU.js";import{t as y}from"./dateFormat-DhRYI9Jx.js";import{f as v,o as j,r as w,v as N}from"./patient.api-DzwQL3yj.js";import{O as S}from"./labtest.api-DGONyV9V.js";import{t as _}from"./user.api-CdycYLjt.js";import{r as C}from"./patientPackages.api-DkKnNJAS.js";import{a as A,i as R}from"./packageFormat-3PqkKha8.js";import{t as I}from"./CatalogSearchInput-BiVqonGL.js";import{t as E}from"./PastVisitsModal-yXFb22pH.js";import{t as D}from"./ViewReportsModal-CfbRiQoa.js";var k=e(t(),1),T=i();function M({visit:e,patient:t,vitals:a,onDoctorResolved:s}){const i=t?.full_name||t?.patient_name||e?.patient_name||t?.name||"",n=t?.patientid??t?.patient_id??t?.patient_number??t?.id??e?.patient,r=e?.visit_id??e?.visitid??e?.id??"",o=e?.referred_to??"",l=(0,k.useMemo)(()=>e?.specialty||e?.speciality||e?.department||"",[e]),[c,d]=(0,k.useState)("");(0,k.useEffect)(()=>{let a=!1;return(async()=>{if(l)return void d(String(l));if(!o)return void d("");const i=String(e?.hospital||t?.hospital||localStorage.getItem("hospitalId")||"");if(i)try{const e=await _({hospitalId:i});if(a)return;const t=B(o),n=(e||[]).find(e=>B(e?.staff_name)===t),r=n||(e||[]).find(e=>{const a=B(e?.staff_name);return a&&t&&(a.includes(t)||t.includes(a))}),l=r?.specialization||r?.department_name||"";d(l?String(l):""),"function"==typeof s&&s({doctorId:r?.id??null,specialty:l?String(l):""})}catch{if(a)return;d(""),"function"==typeof s&&s({doctorId:null,specialty:""})}else d("")})(),()=>{a=!0}},[o,s,t?.hospital,l,e?.hospital]);const u=c,p=function(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):`${y(t)} | ${t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!0}).toLowerCase()}`}(e?.visit_date??e?.visit_datetime??e?.created_at??e?.date??e?.visitDate),m=function(e){if(!e)return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const a=new Date;let s=a.getFullYear()-t.getFullYear();const i=a.getMonth()-t.getMonth();
1(i<0||0===i&&a.getDate()<t.getDate())&&(s-=1);return s<0?"":`${s} years`}(t?.date_of_birth??t?.dob),g=t?.gender??"",f=a?.height??"",h=a?.weight??"",x=a?.blood_pressure??a?.bp??"",b=a?.pulse_rate??a?.pulseRate??a?.pulse??"",v=a?.spo2??"";return(0,T.jsxs)("div",{className:"border-b pb-4 border-gray-200",children:[(0,T.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[(0,T.jsxs)("div",{children:[(0,T.jsxs)("div",{className:"flex items-baseline gap-3",children:[(0,T.jsx)("h2",{className:"text-base font-semibold text-gray-900",children:i||"-"}),n?(0,T.jsxs)("span",{className:"text-xs text-gray-400",children:["ID: ",n]}):null]}),(0,T.jsxs)("div",{className:"mt-3 space-y-2 text-sm",children:[(0,T.jsx)(V,{label:"Visit ID",value:r||"-"}),(0,T.jsx)(V,{label:"Visit No.",value:null!=e?.visit_number&&""!==e?.visit_number?String(e.visit_number):"â"}),(0,T.jsx)(V,{label:"Age",value:m||"-"}),(0,T.jsx)(V,{label:"Gender",value:g||"-"})]})]}),(0,T.jsx)("div",{className:"md:border-l md:border-gray-200 md:pl-6",children:(0,T.jsxs)("div",{className:"mt-1 space-y-2 text-sm",children:[(0,T.jsx)(V,{label:"Doctor Name",value:o||"-"}),(0,T.jsx)(V,{label:"Specialty",value:u||"-"})]})}),(0,T.jsx)("div",{className:"md:border-l md:border-gray-200 md:pl-6",children:(0,T.jsx)("div",{className:"mt-1 space-y-2 text-sm",children:(0,T.jsx)(V,{label:"Date",value:p||"-"})})})]}),(0,T.jsxs)("div",{className:"mt-5 grid grid-cols-1 md:grid-cols-3 gap-6 text-sm",children:[(0,T.jsxs)("div",{className:"space-y-2",children:[(0,T.jsx)(V,{label:"Height",value:L(f,"cm")||"-"}),(0,T.jsx)(V,{label:"Weight",value:L(h,"kg")||"-"})]}),(0,T.jsxs)("div",{className:"md:border-l md:border-gray-200 md:pl-6 space-y-2",children:[(0,T.jsx)(V,{label:"Blood Pressure",value:H(x)||"-"}),(0,T.jsx)(V,{label:"Pulse Rate",value:L(b,"bpm")||"-"})]}),(0,T.jsx)("div",{className:"md:border-l md:border-gray-200 md:pl-6 space-y-2",children:(0,T.jsx)(V,{label:"SpOâ",value:L(v,"%")||"-"})})]}),(0,T.jsxs)("div",{className:"mt-5 text-sm flex flex-col gap-2 md:flex-row md:gap-12",children:[(0,T.jsx)(V,{label:"Visit Reason",value:e?.visit_reason??e?.visitReason??"-"}),e?.referred_by?(0,T.jsx)(V,{label:"Referred By",value:e.referred_by}):null]})]})}function V({label:e,value:t}){return(0,T.jsxs)("div",{className:"flex gap-2",children:[(0,T.jsxs)("p",{className:"w-32 text-gray-400",children:[e,":"]}),(0,T.jsx)("p",{className:"font-medium text-gray-900",children:t})]})}function L(e,t){if(null==e)return"";const a=String(e).trim();return a?t&&a.toLowerCase().includes(t.toLowerCase())?a:t?`${a} ${t}`:a:""}function H(e){if(null==e)return"";const t=String(e).trim();return t?t.toLowerCase().includes("mmhg")?t:`${t} mm/Hg`:""}function B(e){return String(e||"").toLowerCase().replace(/\([^)]*\)/g," ").replace(/\bdr\.?\b/g," ").replace(/[^a-z\s]/g," ").replace(/\s+/g," ").trim()}var F=(0,k.forwardRef)(function({onAudioCaptured:e,disabled:t=!1,onRecordingChange:a},s){const i=(0,k.useRef)(null),n=(0,k.useRef)(null),r=(0,k.useRef)([]),o=(0,k.useRef)(null),c=(0,k.useRef)(null),d=(0,k.useRef)(null),u=(0,k.useRef)(null),p=(0,k.useRef)(0),m=(0,k.useRef)(!1),[g,f]=(0,k.useState)(!1);(0,k.useEffect)(()=>{a?.(g)},[g,a]);const h=()=>{try{n.current?.getTracks?.()?.forEach(e=>e.stop())}catch{}n.current=null},x=()=>{try{d.current&&cancelAnimationFrame(d.current)}catch{}d.current=null,u.current=null,c.current=null,m.current=!1;try{o.current&&"function"==typeof o.current.close&&o.current.close()}catch{}o.current=null},y=async()=>{if(!t&&!g)if(navigator.mediaDevices&&window.MediaRecorder)try{const t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});n.current=t,r.current=[],p.current=Date.now(),m.current=!1;const a=new window.MediaRecorder(t);i.current=a,a.ondataavailable=e=>{e.data&&e.data.size>0&&r.current.push(e.data)},a.onstop=async()=>{const t=new Blob(r.current,{type:r.current?.[0]?.type||"audio/webm"});r.current=[],x(),h(),f(!1),e?.(t)},a.start(),f(!0),(e=>{const t=window.AudioContext||window.webkitAudioContext;if(t)try{const a=new t,s=a.createMediaStreamSource(e),n=a.createAnalyser();n.fftSize=2048,s.connect(n),o.current=a,c.current=n,u.current=null,m.current=!1;
1const r=new Uint8Array(n.fftSize),l=.02,g=.012,f=2200,h=3500,b=()=>{try{const e=i.current;if(!e||"recording"!==e.state)return void x();n.getByteTimeDomainData(r);let t=0;for(let i=0;i<r.length;i+=1){const e=(r[i]-128)/128;t+=e*e}const a=Math.sqrt(t/r.length);a>l&&(m.current=!0);const s=Date.now(),o=s-(p.current||s),c=a<g;if(m.current&&o>=h&&c){if(u.current||(u.current=s),s-u.current>=f)return v(),void x()}else c||(u.current=null)}catch{}d.current=requestAnimationFrame(b)};d.current=requestAnimationFrame(b)}catch{x()}})(t)}catch{x(),h(),b("Could not access microphone")}else b("Recording not supported in this browser")},v=()=>{try{const e=i.current;e&&"recording"===e.state&&(e.stop(),f(!1))}catch{}};return(0,k.useImperativeHandle)(s,()=>({startRecording:y,stopRecording:v,getState:()=>({recording:g})}),[g]),(0,T.jsxs)("div",{className:"flex justify-between items-start border-b border-gray-100 pb-4",children:[(0,T.jsxs)("div",{className:"text-sm text-gray-600 max-w-3xl",children:["Say ",(0,T.jsx)("span",{className:"font-bold text-red-600 ",children:'"start recording"'})," to begin, then"," ",(0,T.jsx)("span",{className:"font-bold text-red-600",children:'"stop recording"'})," to finish. After fields are filled, say"," ",(0,T.jsx)("span",{className:"font-bold text-red-600",children:'"proceed with data"'}),"."]}),(0,T.jsxs)("button",{className:"btn-primary flex gap-2"+(g?" opacity-60":""),type:"button",onClick:async()=>{t||g||await y()},disabled:t||g,children:[(0,T.jsx)(l,{size:16})," ",g?"Recording...":"Zonov.ai Agent"]}),g&&(0,T.jsx)("button",{className:"btn-secondary ml-2",type:"button",onClick:()=>{v()},children:"Stop Recording"})]})});function P({value:e,onChange:t,disabled:a=!1}){return(0,T.jsx)("textarea",{name:"conversation",value:e,onChange:t,disabled:a,readOnly:a,placeholder:"Start recording to see transcript here...",className:"w-full border border-gray-100 rounded-lg p-3 text-sm min-h-[120px]"})}function $({title:e,name:t,value:a="",onChange:s,disabled:i=!1,onAudioCaptured:n,uploading:r=!1,debounceMs:o=500}){const c=(0,k.useMemo)(()=>"undefined"!=typeof window&&"undefined"!=typeof navigator&&!!navigator.mediaDevices?.getUserMedia&&"function"==typeof window.MediaRecorder,[]),d=(0,k.useRef)(null),u=(0,k.useRef)(null),p=(0,k.useRef)([]),[m,g]=(0,k.useState)(!1),[f,h]=(0,k.useState)(""),[x,y]=(0,k.useState)(a??"");(0,k.useEffect)(()=>{y(a??"")},[a]),(0,k.useEffect)(()=>{if(i)return;const e=x??"",a=setTimeout(()=>{s?.({target:{name:t,value:e}})},Math.max(0,Number(o)||0));return()=>clearTimeout(a)},[x,t,s,o,i]);return(0,k.useEffect)(()=>()=>{try{d.current?.stop()}catch{}try{u.current?.getTracks?.().forEach(e=>e.stop())}catch{}u.current=null,d.current=null},[]),(0,T.jsxs)("div",{children:[(0,T.jsxs)("div",{className:"flex justify-between items-center mb-1",children:[(0,T.jsx)("h3",{className:"text-[#347BD7] text-sm",children:e}),(0,T.jsxs)("div",{className:"flex items-center gap-2",children:[(0,T.jsx)("button",{className:"text-red-500 text-xs disabled:opacity-50",type:"button",disabled:i||r||m,onClick:()=>s({target:{name:t,value:""}}),children:"Clear"}),(0,T.jsx)("button",{className:"p-1 rounded bg-blue-100 disabled:opacity-50",type:"button",disabled:i||r||!c||m,onClick:()=>{i||(c?(h(""),(async()=>{try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});u.current=e,p.current=[];const a=new MediaRecorder(e);d.current=a,a.ondataavailable=e=>{e?.data&&e.data.size>0&&p.current.push(e.data)},a.onerror=e=>{h(e?.error?.name?String(e.error.name):"recorder_error"),g(!1)},a.onstop=async()=>{try{const e=a.mimeType||"audio/webm",s=new Blob(p.current,{type:e});"function"==typeof n&&s.size>0&&await n({field:t,audioBlob:s})}catch{}finally{p.current=[];try{u.current?.getTracks?.().forEach(e=>e.stop())}catch{}u.current=null,d.current=null,g(!1)}},a.start(),g(!0)}catch(e){h(e?.name?String(e.name):"mic_permission_denied"),g(!1)}})()):b("Audio recording is not supported in this browser."))},title:c?"Start recording":"Not supported",children:(0,T.jsx)(l,{size:12})}),m&&(0,T.jsx)("button",{type:"button",onClick:()=>{try{d.current?.stop()}finally{g(!1)}},className:"px-2 py-1 rounded bg-red-600 text-white text-xs",disabled:i,title:"Stop recording",children:"Stop"})]})]}),!i&&m&&(0,T.jsx)("div",{className:"mb-2 text-xs text-gray-600",children:"Recording⦠speak now."}),!i&&!m&&r&&(0,T.jsx)("div",{className:"mb-2 text-xs text-gray-600",children:"Uploading audioâ¦"}),!i&&!m&&f&&(0,T.jsxs)("div",{className:"mb-2 text-xs text-red-600",children:["Mic error: ",f]}),(0,T.jsx)("textarea",{name:t,value:x,onChange:e=>y(e.target.value),disabled:i,readOnly:i,placeholder:`${e} - Voice + Manual Entry`,className:"w-full border border-[#f0f0f0] rounded-lg p-3 text-sm min-h-[100px]"})]})}function U({onSelect:e,fetchItems:t,disabled:a=!1,debounceMs:s=350}){const[i,n]=(0,k.useState)(""),[r,o]=(0,k.useState)(""),[l,c]=(0,k.useState)(""),[d,p]=(0,k.useState)([]),[m,g]=(0,k.useState)(!1),[f,h]=(0,k.useState)(!1),x=(0,k.useRef)(null),b=(0,k.useRef)(null),y=i.trim()||r.trim()||l.trim(),v=(0,k.useCallback)(async(e,a,s)=>{b.current?.abort();const i=new AbortController;b.current=i,g(!0);try{const n=await t(e.trim(),a.trim(),s.trim());i.signal.aborted||(p(Array.isArray(n)?n:[]),h(!0))}catch{b.current?.signal.aborted||p([])}finally{b.current?.signal.aborted||g(!1)}},[t]);(0,k.useEffect)(()=>
1{if(!y)return p([]),void h(!1);const e=setTimeout(()=>v(i,r,l),s);return()=>clearTimeout(e)},[i,r,l,y,s,v]),(0,k.useEffect)(()=>{const e=e=>{x.current&&!x.current.contains(e.target)&&h(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);const j="w-full pl-8 pr-3 py-2 text-sm border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-200 disabled:opacity-50";return(0,T.jsxs)("div",{ref:x,className:"relative mb-2",children:[(0,T.jsxs)("div",{className:"flex gap-2",children:[(0,T.jsxs)("div",{className:"relative flex-1",children:[(0,T.jsx)(u,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),(0,T.jsx)("input",{type:"text",value:i,onChange:e=>n(e.target.value),onFocus:()=>d.length>0&&h(!0),disabled:a,placeholder:"Medicine Nameâ¦",className:j})]}),(0,T.jsxs)("div",{className:"relative flex-1",children:[(0,T.jsx)(u,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),(0,T.jsx)("input",{type:"text",value:r,onChange:e=>o(e.target.value),onFocus:()=>d.length>0&&h(!0),disabled:a,placeholder:"Salt Contentâ¦",className:j})]}),(0,T.jsxs)("div",{className:"relative flex-1",children:[(0,T.jsx)(u,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),(0,T.jsx)("input",{type:"text",value:l,onChange:e=>c(e.target.value),onFocus:()=>d.length>0&&h(!0),disabled:a,placeholder:"Brand Nameâ¦",className:j}),m&&(0,T.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-gray-400",children:"â¦"})]})]}),f&&d.length>0&&(0,T.jsx)("ul",{className:"absolute z-50 left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-48 overflow-y-auto",children:d.map(t=>(0,T.jsx)("li",{children:(0,T.jsxs)("button",{type:"button",onMouseDown:a=>{a.preventDefault(),(t=>{e?.(t.name),n(""),o(""),c(""),p([]),h(!1)})(t)},className:"w-full text-left px-3 py-2 text-sm hover:bg-blue-50 text-gray-700",children:[t.name,t.brand_name&&(0,T.jsxs)("span",{className:"ml-2 text-xs text-gray-400",children:["(",t.brand_name,")"]})]})},t.id??t.name))}),f&&!m&&0===d.length&&y&&(0,T.jsx)("div",{className:"absolute z-50 left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg px-3 py-2 text-sm text-gray-400",children:"No results found"})]})}function O({title:e,items:t,onAdd:a,disabled:s=!1}){const i=Array.isArray(t)?t:[];return 0===i.length?null:(0,T.jsxs)("div",{className:"mb-3 rounded-xl border border-purple-200 bg-purple-50/50 p-3",children:[(0,T.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,T.jsx)(o,{size:15,className:"text-purple-600"}),(0,T.jsx)("span",{className:"text-xs font-semibold text-purple-800 uppercase tracking-wide",children:e})]}),(0,T.jsx)("div",{className:"flex flex-wrap gap-2",children:i.map(e=>{const t=e.remaining??Math.max(0,(e.total_count||0)-(e.consumed_count||0)),i=t<=0;return(0,T.jsxs)("div",{className:"flex items-center gap-2 bg-white border border-gray-200 rounded-lg pl-2.5 pr-1.5 py-1",children:[(0,T.jsx)("span",{className:"text-sm text-gray-800",children:e.name}),(0,T.jsx)("span",{className:`px-1.5 py-0.5 rounded-full text-[9px] font-medium ${R(e.category)}`,children:A(e.category)}),(0,T.jsxs)("span",{className:"text-[11px] text-gray-500",children:[e.consumed_count??0,"/",e.total_count??0," · ",t," left"]}),i?(0,T.jsx)("span",{className:"text-[10px] font-medium text-red-500 px-1.5",children:"Exhausted"}):(0,T.jsx)("button",{type:"button",disabled:s,onClick:()=>a?.(e.name),title:`Add ${e.name}`,className:"inline-flex items-center justify-center h-6 w-6 rounded-md bg-[#347BD7] text-white hover:bg-blue-700 disabled:opacity-50",children:(0,T.jsx)(c,{size:14})})]},`${e.category}-${e.name}`)})})]})}function z({onClose:e,onCloseVisit:t,onSaveVisit:a,onSubmit:s,onProceed:i,onDownloadReport:n,onOpenVisitAgain:r,openVisitAgainEnabled:o=!1,disabled:l=!1}){return(0,T.jsxs)("div",{className:"flex justify-between gap-3 p-4 border-t border-gray-200",children:[(0,T.jsx)("div",{className:"flex gap-3",children:(0,T.jsx)("button",{type:"button",onClick:r,className:"btn-outline disabled:opacity-60",disabled:"function"!=typeof r||l&&!o,children:"Open this visit again"})}),(0,T.jsxs)("div",{className:"flex gap-3",children:[(0,T.jsx)("button",{type:"button",onClick:e,className:"btn-outline",children:"Cancel"}),(0,T.jsx)("button",{type:"button",onClick:a,className:"btn-secondary disabled:opacity-60",disabled:l||"function"!=typeof a,children:"Save Visit"}),(0,T.jsx)("button",{type:"button",onClick:i,className:"btn-primary disabled:opacity-60",disabled:l||"function"!=typeof i,children:"Proceed"})]})]})}function G({onClose:e,onCreate:t,onProceed:i,visit:o,variant:l="modal"}){const c=a(),u=s(),y=n(),A=o||u.state?.visit,[R,V]=(0,k.useState)(null),L=(()=>{const e=c?.id;if(!e)return null;const t=Number.parseInt(String(e),10);return Number.isFinite(t)?t:null})();(0,k.useEffect)(()=>{let e=!1;return(async()=>
1{if(L)if(A?.id&&Number(A.id)===L)V(A);else try{const t=await j(L);e||V(t||null)}catch{e||V(null)}else V(A||null)})(),()=>{e=!0}},[L,A]);const H=R||A,B="done"===(G=H?.status,String(G??"").trim().toLowerCase());var G;const{form:Y,update:J,setFormData:K,submit:W}=function(e){const[t,a]=(0,k.useState)({});return{form:t,update:(0,k.useCallback)(e=>{const{name:t,value:s}=e.target;a(e=>({...e,[t]:s}))},[]),setFormData:(0,k.useCallback)(e=>{a(t=>({...t,...e||{}}))},[]),clearSection:(0,k.useCallback)(e=>{a(t=>({...t,[e]:""}))},[]),submit:(0,k.useCallback)(()=>{const a=Boolean(t.id),s={...t,id:a?t.id:Date.now(),date:t.date||(new Date).toLocaleString(),status:t.status||"Active"};e?.(s),b(a?"Visit Updated Successfully":"Visit Created Successfully")},[t,e])}}(t),[Z,Q]=(0,k.useState)(!1),[X,ee]=(0,k.useState)(!1);(0,k.useRef)(null);const[te,ae]=(0,k.useState)(!1),se=(0,k.useRef)(!1),ie=(0,k.useRef)(!1),ne=(0,k.useRef)(!1),[re,oe]=(0,k.useState)(null),[le,ce]=(0,k.useState)(null),[de,ue]=(0,k.useState)([]),[pe,me]=(0,k.useState)(null),ge=(0,k.useCallback)(({doctorId:e})=>me(e),[]),[fe,he]=(0,k.useState)(!1),[xe,be]=(0,k.useState)({}),[ye,ve]=(0,k.useState)(null),[je,we]=(0,k.useState)(!1),[Ne,Se]=(0,k.useState)(!1),[_e,Ce]=(0,k.useState)(null),Ae=(0,k.useRef)(null),Re=(0,k.useRef)(null),Ie=(0,k.useRef)(!1),Ee=(0,k.useRef)(0),De=(0,k.useRef)(!1),ke=(0,k.useRef)(null);(0,k.useEffect)(()=>{const e=e=>{"VISIT_REPORT_MARK_DONE_SUCCESS"===e?.data?.type&&(Ce(null),y("/visits/PatientVisit"))};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)},[y]),(0,k.useEffect)(()=>{se.current=!!te},[te]),(0,k.useEffect)(()=>{ie.current=!!Z},[Z]),(0,k.useEffect)(()=>{ne.current=!!X},[X]),(0,k.useEffect)(()=>{ae(!1),ve(null),K({allergy:"",complaint:"",history:"",pastHistory:"",examination:"",diagnosis:"",investigation:"",advice:"",medications:"",followup:"",conversation:""})},[c?.id,K]),(0,k.useEffect)(()=>{let e=!1;return(async()=>{if(!H)return oe(null),void ce(null);try{const[t,a]=await Promise.all([H?.patient?w(H.patient):Promise.resolve(null),H?.id?v(H.id):Promise.resolve([])]);if(e)return;oe(t),ce([...Array.isArray(a)?a:Array.isArray(a?.vitals)?a.vitals:a?.results||[]].sort((e,t)=>{const a=new Date(e?.updated_at||e?.created_at||0).getTime();return new Date(t?.updated_at||t?.created_at||0).getTime()-a}).at(0)||null)}catch{if(e)return;oe(null),ce(null)}})(),()=>{e=!0}},[H]);const Te=(0,k.useCallback)(async()=>{const e=H?.patient??re?.id??null,t=H?.hospital?.id??H?.hospital??localStorage.getItem("hospitalId")??"";if(e)try{const a=await C({hospitalId:t,patientId:e});ue((Array.isArray(a)?a:[]).filter(e=>e.is_active).flatMap(e=>(e.items||[]).map(t=>({...t,package_name:e.package_name}))))}catch{ue([])}else ue([])},[H?.patient,H?.hospital,re?.id]);(0,k.useEffect)(()=>{Te()},[Te]);const Me=(0,k.useMemo)(()=>de.filter(e=>"laboratory"===e.category||"radiology"===e.category),[de]),Ve=(0,k.useMemo)(()=>de.filter(e=>"other"===e.category),[de]);(0,k.useEffect)(()=>{let e=!1;return(async()=>{const t=c?.id,a=H?.id??(t?Number.parseInt(String(t),10):null);if(a){he(!0);try{let t=null;try{t=await m(a,{hospitalId:H?.hospital?.id??H?.hospital,branchId:H?.branch?.id??H?.branch})}catch(s){t=null}if(e||!t)return;ve(t?.id??t?.drslip_id??t?.doctor_slip_id??t?.doctorSlipId??null),K(function(e){return{allergy:e?.allergy??"",complaint:e?.chief_complaint??e?.complaints??"",history:e?.history_of_present_illness??e?.medical_history??"",pastHistory:e?.past_medical_surgical_history??e?.past_history??"",examination:e?.clinical_examination??"",diagnosis:e?.diagnosis??"",investigation:e?.investigation??e?.lab_tests_advised??"",advice:e?.advice??"",medications:e?.medicines_suggested??"",followup:e?.follow_up??""}}(t))}catch(s){const e=s?.response?.status;401!==e&&403!==e||b("Session expired. Please login again.")}finally{e||he(!1)}}})(),()=>{e=!0}},[c?.id,K,H?.id,H?.hospital,H?.branch]);const Le=e=>Z?"Loading...":Y[e]||"",He=localStorage.getItem("hospitalId")||"",[Be,Fe]=(0,k.useState)(""),[Pe,$e]=(0,k.useState)([]),[Ue,Oe]=(0,k.useState)(A?.panel_category||"");(0,k.useEffect)(()=>{const e=H?.panel_category;e&&Oe(e)},[H?.panel_category]);const ze=(0,k.useMemo)(()=>({panelCategory:Ue,subType:Be}),[Ue,Be]),Ge=(0,k.useCallback)(async(e,t={})=>{try{return await S({search:e,hospitalId:He,panelCategory:t.panelCategory||"",subType:t.subType||""})}catch{return[]}},[He]),qe=(0,k.useCallback)(async(e,t,a)=>{try{const s={page_size:20};e&&(s.medicine_name=e),t&&(s.salt_content=t),a&&(s.brand_name=a);const i=(await r.get("/pharmacy/medicine/",{params:s}))?.data;return Array.isArray(i)?i:Array.isArray(i?.results)?i.results:[]}catch{return[]}},[]),Ye=(0,k.useCallback)((e,t)=>{const a=(Y[e]||"").trim();J({target:{name:e,value:a?`${a}\n${t}`:t}})},[Y,J]),Je=async({field:e,audioBlob:t})=>{if(B)b("This visit is closed (Done). You can't edit it.");else if(e&&t){be(t=>({...t,[e]:!0}));try{const a=(await g({audioBlobOrFile:t,field:e}))?.corrected_text??"";K({[e]:a})}catch(a){const e=a?.response?.data?.error,t=a?.response?.data?.details;b(e||t?`${e||"Request failed"}${t?`\n\n${t}`:""}`:"Failed to process audio")}finally{be(t=>({...t,[e]:!1}))}}},Ke=async({navigateAfterSave:a=!0}={})=>
1{if(B)return void b("This visit is closed (Done). You can't save changes.");if(!H)return void b("Visit data missing");const s=localStorage.getItem("user");let i=null;try{i=s?JSON.parse(s):null}catch{i=null}const n=String(H.hospital||re?.hospital||localStorage.getItem("hospitalId")||""),r=n?localStorage.getItem(`selectedBranchId:${n}`):null,o=String(H.branch||r||localStorage.getItem("branchId")||""),l=H?.id??null,c=H?.patient??re?.id??null,d=String(H?.referred_to||"");let u=pe;if(!u&&d&&n)try{const e=await _({hospitalId:n}),t=q(d),a=(e||[]).find(e=>q(e?.staff_name)===t);u=(a||(e||[]).find(e=>{const a=q(e?.staff_name);return a&&t&&(a.includes(t)||t.includes(a))}))?.id??null}catch{u=null}const p={visit:l,patient:c,hospital:n?Number(n):null,branch:o?Number(o):null,doctor:u?Number(u):null,slip_created_on:(new Date).toISOString(),patient_type:"opd",doctor_name:d||i?.full_name||"",doctor_id:u?Number(u):null,visit_id:l,patient_id:c,hospital_id:n,branch_id:o,allergy:Y.allergy||"",chief_complaint:Y.complaint||"",complaints:Y.complaint||"",history_of_present_illness:Y.history||"",medical_history:Y.history||"",past_medical_surgical_history:Y.pastHistory||"",past_history:Y.pastHistory||"",clinical_examination:Y.examination||"",diagnosis:Y.diagnosis||"",advice:Y.advice||"",follow_up:Y.followup||"",investigation:Y.investigation||"",lab_tests_advised:Y.investigation||"",lab_test_type_ids:Pe,medicines_suggested:Y.medications||"",complaint:Y.complaint||"",history:Y.history||"",pastHistory:Y.pastHistory||"",examination:Y.examination||"",medications:Y.medications||"",followup:Y.followup||""};if(p.hospital&&p.branch&&p.patient&&p.visit){ee(!0);try{const s=null!=ye?await x(ye,p):await f(p),i=s?.id??s?.drslip_id??s?.doctor_slip_id??s?.doctorSlipId??ye??null;null!=i&&ve(i),t?.(s),$e([]),Te(),b("Report saved successfully"),a&&(y("/visits/PatientVisit",{replace:!0}),e?.())}catch(m){b(m?.response?.data?.error||m?.response?.data?.detail||(m?.response?.data?.errors?JSON.stringify(m.response.data.errors):null)||m?.message||"Failed to save report")}finally{ee(!1)}}else b("Missing required ids (hospital/branch/patient/visit)")},We="function"==typeof e?e:"page"===l?()=>y(-1):void 0,Ze="function"==typeof i?i:async()=>{const e=H?.id??L??c?.id;e?(await Ke({navigateAfterSave:!1}),Ce(e)):b("Visit id is missing for this report.")};(0,k.useEffect)(()=>{ke.current=Ze},[Ze]);const Qe=()=>{try{const e=Re.current;if(e){e.onresult=null,e.onerror=null,e.onend=null;try{"function"==typeof e.abort&&e.abort()}catch{}try{"function"==typeof e.stop&&e.stop()}catch{}}}finally{Re.current=null}},Xe=()=>{if(Ie.current)return;if(Re.current)return;const e=window.SpeechRecognition||window.webkitSpeechRecognition;if(e)try{const t=new e;t.lang="en-IN",t.interimResults=!1,t.continuous=!0,t.onresult=e=>{const t=Array.from(e.results).slice(e.resultIndex).map(e=>e[0].transcript).join(" ").trim().toLowerCase();if(!t)return;const a=Date.now();if(a-Ee.current<900)return;const s=/\bstart\s+recording\b/.test(t),i=/\bstop\s+recording\b/.test(t),n=/\bproceed\s+with\s+data\b/.test(t);return!s||De.current||ie.current||ne.current||B?i&&De.current?(Ee.current=a,void Ae.current?.stopRecording?.()):void(n&&se.current&&!ie.current&&!ne.current&&(Ee.current=a,ke.current?.())):(Ee.current=a,ae(!1),void Ae.current?.startRecording?.())},t.onerror=e=>{const t=e?.error;"not-allowed"!==t&&"service-not-allowed"!==t||(Ie.current=!0),Qe()},t.onend=()=>{Re.current=null,Ie.current||setTimeout(()=>Xe(),500)},Re.current=t,t.start()}catch{Qe()}};return(0,k.useEffect)(()=>(Xe(),()=>Qe()),[]),(0,T.jsx)("div",{className:"modal"===l?"fixed inset-0 bg-black/40 z-50 overflow-auto":"w-full",children:(0,T.jsxs)("div",{className:"modal"===l?"bg-white max-w-7xl mx-auto my-6 rounded-xl shadow":"bg-white rounded-xl shadow",children:[(0,T.jsxs)("div",{className:"p-6 space-y-6",children:[(0,T.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,T.jsxs)("button",{type:"button",onClick:()=>y("/visits/PatientVisit"),className:"inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-gray-100 text-gray-700 hover:bg-gray-200",children:[(0,T.jsx)("span",{className:"text-lg leading-none",children:"â"}),(0,T.jsx)("span",{children:"Back"})]}),(0,T.jsxs)("div",{className:"flex items-center gap-2",children:[(0,T.jsx)("button",{type:"button",onClick:()=>Se(!0),className:"bg-[#347BD7] text-white px-6 py-2 rounded-lg flex items-center gap-2 cursor-pointer",children:"Reports"}),(0,T.jsx)("button",{type:"button",onClick:()=>we(!0),className:"bg-[#347BD7] text-white px-6 py-2 rounded-lg flex items-center gap-2 cursor-pointer",children:"Past Visits"})]})]}),(0,T.jsx)(M,{visit:H,patient:re,vitals:le,onDoctorResolved:ge}),(0,T.jsx)(F,{ref:Ae,onAudioCaptured:async e=>{if(B)b("This visit is closed (Done). You can't edit it.");else{ae(!1),Q(!0);try{K({allergy:"",complaint:"",history:"",pastHistory:"",examination:"",diagnosis:"",investigation:"",advice:"",medications:"",followup:"",conversation:""});const t=await p(e),a=t&&"object"==typeof t&&t.data&&"object"==typeof t.data?t.data:t,s={cheif_complaint:"complaint",chief_complaint:"complaint",history_of_present_illness:"history",past_medical_surgical_history:"pastHistory",clinical_examination:"examination",follow_up:"followup",allergys:"allergy",allergies:"allergy"},i={};
1a&&"object"==typeof a&&Object.entries(a).forEach(([e,t])=>{const a=s[e]||e;let n=t;Array.isArray(n)&&(n=n.join(", ")),null==n&&(n=""),i[a]=n}),K(i),ae(!0)}catch(t){const e=t?.response?.data?.error,a=t?.response?.data?.details;b(e||a?`${e||"Request failed"}${a?`\n\n${a}`:""}`:"Failed to fetch medical data")}finally{Q(!1)}}},disabled:Z||B,onRecordingChange:e=>{De.current=!!e}}),(0,T.jsx)(P,{value:Le("conversation"),onChange:J,disabled:Z||B}),fe?(0,T.jsx)("div",{className:"text-xs text-gray-500",children:"Loading saved reportâ¦"}):null,(0,T.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[(0,T.jsx)($,{title:"Allergy",name:"allergy",value:Le("allergy"),onChange:J,disabled:Z||B,uploading:!!xe?.allergy,onAudioCaptured:Je}),(0,T.jsx)($,{title:"Chief Complaint",name:"complaint",value:Le("complaint"),onChange:J,disabled:Z||B,uploading:!!xe?.complaint,onAudioCaptured:Je}),(0,T.jsx)($,{title:"History of Presenting Illness",name:"history",value:Le("history"),onChange:J,disabled:Z||B,uploading:!!xe?.history,onAudioCaptured:Je}),(0,T.jsx)($,{title:"Past Medical/Surgical History",name:"pastHistory",value:Le("pastHistory"),onChange:J,disabled:Z||B,uploading:!!xe?.pastHistory,onAudioCaptured:Je}),(0,T.jsx)($,{title:"Clinical Examination",name:"examination",value:Le("examination"),onChange:J,disabled:Z||B,uploading:!!xe?.examination,onAudioCaptured:Je}),(0,T.jsx)($,{title:"Diagnosis",name:"diagnosis",value:Le("diagnosis"),onChange:J,disabled:Z||B,uploading:!!xe?.diagnosis,onAudioCaptured:Je}),(0,T.jsxs)("div",{children:[(0,T.jsx)(O,{title:"Package â Investigations included",items:Me,onAdd:e=>Ye("investigation",e),disabled:Z||B}),(0,T.jsxs)("div",{className:"flex gap-2 mb-2 items-center",children:[(0,T.jsxs)("select",{value:Be,onChange:e=>Fe(e.target.value),disabled:Z||B,className:"text-sm border border-gray-200 rounded-lg px-2 py-2 bg-white focus:outline-none focus:ring-2 focus:ring-blue-200 disabled:opacity-50",children:[(0,T.jsx)("option",{value:"",children:"All Types"}),(0,T.jsx)("option",{value:"radiology",children:"Radiology"}),(0,T.jsx)("option",{value:"pathology",children:"Pathology"})]}),(0,T.jsxs)("select",{value:Ue,onChange:e=>Oe(e.target.value),disabled:Z||B,className:"text-sm border border-gray-200 rounded-lg px-2 py-2 bg-white focus:outline-none focus:ring-2 focus:ring-blue-200 disabled:opacity-50",children:[(0,T.jsx)("option",{value:"",children:"All Categories"}),(0,T.jsx)("option",{value:"GENERAL",children:"GENERAL"}),(0,T.jsx)("option",{value:"ADITYA BIRLA",children:"ADITYA BIRLA"}),(0,T.jsx)("option",{value:"BAJAJ FINSERV",children:"BAJAJ FINSERV"}),(0,T.jsx)("option",{value:"FHPL TPA",children:"FHPL TPA"}),(0,T.jsx)("option",{value:"ICICI LOMBARD",children:"ICICI LOMBARD"}),(0,T.jsx)("option",{value:"RGHS NON NABH",children:"RGHS NON NABH"}),(0,T.jsx)("option",{value:"SBI GENERAL INSURANCE",children:"SBI GENERAL INSURANCE"}),(0,T.jsx)("option",{value:"SHAKTI SHINE GROUP",children:"SHAKTI SHINE GROUP"}),(0,T.jsx)("option",{value:"STAR HEALTH INSURANCE",children:"STAR HEALTH INSURANCE"}),(0,T.jsx)("option",{value:"TATA AIG INSURANCE",children:"TATA AIG INSURANCE"}),(0,T.jsx)("option",{value:"VGU",children:"VGU"})]}),(0,T.jsx)("div",{className:"flex-1",children:(0,T.jsx)(I,{placeholder:"Search available tests to addâ¦",fetchItems:Ge,onSelect:(e,t)=>{Ye("investigation",e);const a=Number(t?.id);Number.isFinite(a)&&a>0&&$e(e=>e.includes(a)?e:[...e,a])},disabled:Z||B,filters:ze})})]}),(0,T.jsx)($,{title:"Investigations",name:"investigation",value:Le("investigation"),onChange:J,disabled:Z||B,uploading:!!xe?.investigation,onAudioCaptured:Je})]}
1),(0,T.jsx)($,{title:"Advice",name:"advice",value:Le("advice"),onChange:J,disabled:Z||B,uploading:!!xe?.advice,onAudioCaptured:Je}),(0,T.jsxs)("div",{children:[(0,T.jsx)(O,{title:"Package â Medicines included",items:Ve,onAdd:e=>Ye("medications",e),disabled:Z||B}),(0,T.jsx)(U,{fetchItems:qe,onSelect:e=>Ye("medications",e),disabled:Z||B}),(0,T.jsx)($,{title:"Medications",name:"medications",value:Le("medications"),onChange:J,disabled:Z||B,uploading:!!xe?.medications,onAudioCaptured:Je})]}),(0,T.jsx)($,{title:"Follow-up",name:"followup",value:Le("followup"),onChange:J,disabled:Z||B,uploading:!!xe?.followup,onAudioCaptured:Je})]})]}),(0,T.jsx)(z,{onClose:We,onCloseVisit:async()=>{if(!H)return void b("Visit data missing");if(B)return void b("This visit is already closed (Done).");if(!window.confirm("Close this visit? This will lock the medical form."))return;const e=String(H.hospital||re?.hospital||localStorage.getItem("hospitalId")||""),t=e?localStorage.getItem(`selectedBranchId:${e}`):null,a=String(H.branch||t||localStorage.getItem("branchId")||""),s=String(H?.visit_id??H?.visitid??H?.visitId??H?.visit);if(e&&a&&s)try{const t=await N({hospital_id:e,branch_id:a,visit_id:s,status:"done"}),i=t?.visit??t;V(i&&"object"==typeof i?e=>({...e||H||{},...i}):e=>({...e||H||{},status:"done"})),b("Visit closed successfully")}catch(i){b(i?.response?.data?.error||i?.response?.data?.detail||i?.message||"Failed to close visit")}else b("Missing required ids (hospital/branch/visit_id)")},onSaveVisit:async()=>{await Ke({navigateAfterSave:!1})},onSubmit:X?void 0:Ke,onProceed:Ze,onDownloadReport:async()=>{const e=String(H?.hospital||re?.hospital||localStorage.getItem("hospitalId")||"").trim(),t=null!=ye?String(ye).trim():"";if(e&&t)try{const a=await h({hospitalId:e,drslipId:t}),s=a?.headers?.["content-type"]||"application/pdf",i=/filename\*?=(?:UTF-8''|"?)([^";]+)"?/i.exec(a?.headers?.["content-disposition"]||""),n=i?.[1]?decodeURIComponent(i[1]):"",r=n&&n.toLowerCase().endsWith(".pdf")?n:n?`${n}.pdf`:`doctor-slip-${t}.pdf`,o=new Blob([a.data],{type:s}),l=window.URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=r,document.body.appendChild(c),c.click(),c.remove(),window.URL.revokeObjectURL(l)}catch(a){b(a?.response?.data?.detail||a?.response?.data?.error||a?.message||"Failed to download report")}else b("Please save the report first.")},onOpenVisitAgain:B?async()=>{if(!H)return void b("Visit data missing");if(!B)return void b("This visit is already open.");const e=String(H.hospital||re?.hospital||localStorage.getItem("hospitalId")||""),t=e?localStorage.getItem(`selectedBranchId:${e}`):null,a=String(H.branch||t||localStorage.getItem("branchId")||""),s=String(H?.visit_id??H?.visitid??H?.visitId??H?.visit);if(e&&a&&s)try{const t=await N({hospital_id:e,branch_id:a,visit_id:s,status:"in_progress"}),i=t?.visit??t;V(i&&"object"==typeof i?e=>({...e||H||{},...i}):e=>({...e||H||{},status:"in_progress"})),b("Visit reopened for editing.")}catch(i){b(i?.response?.data?.error||i?.response?.data?.detail||i?.message||"Failed to reopen visit")}else b("Missing required ids (hospital/branch/visit_id)")}:void 0,openVisitAgainEnabled:B,disabled:X||Z||B}),(0,T.jsx)(E,{open:je,visitId:H?.id??c?.id,onClose:()=>we(!1)}),(0,T.jsx)(D,{open:Ne,visit:H,onClose:()=>Se(!1)}),_e?(0,T.jsx)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4",onMouseDown:e=>{e.target===e.currentTarget&&Ce(null)},children:(0,T.jsxs)("div",{className:"w-full max-w-7xl h-[90vh] bg-white rounded-2xl border border-gray-200 shadow-xl overflow-hidden flex flex-col",children:[(0,T.jsxs)("div",{className:"flex items-center justify-between px-6 py-3 border-b border-gray-200 bg-gray-50 flex-none",children:[(0,T.jsx)("span",{className:"text-[#347BD7] font-semibold",children:"Visit Medical Report"}),(0,T.jsx)("button",{type:"button",onClick:()=>Ce(null),className:"h-9 w-9 inline-flex items-center justify-center rounded-xl hover:bg-gray-200 text-gray-600","aria-label":"Close report",children:(0,T.jsx)(d,{size:18})})]}),(0,T.jsx)("iframe",{src:`${"undefined"!=typeof window?window.location.origin:""}/visits/medical-report/${_e}?embed=1`,title:"Visit Medical Report",className:"flex-1 w-full min-h-0 border-0 rounded-b-2xl"})]})}):null]})})}function q(e){return String(e||"").toLowerCase().replace(/\([^)]*\)/g," ").replace(/\bdr\.?\b/g," ").replace(/[^a-z\s]/g," ").replace(/\s+/g," ").trim()}
1export{G 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.