1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[49561,86985],{446:(e,t,n)=>{n.d(t,{XI:()=>i,b0:()=>s,hO:()=>a});let i={desktopMode:"split",recorderSide:"left",recorderShare:47.5,sessionsWidth:380,sessionsSide:"right",sidebarWidth:252,sidebarVisible:!0,mobilePane:"record",calculator:"manual",timer:"manual"};function s(e){let t=e&&"object"==typeof e?e:{},n=(e,n,s)=>"number"==typeof t[e]&&Number.isFinite(t[e])?Math.min(s,Math.max(n,t[e])):i[e],s=e=>"scribe"===t[e]||"always"===t[e]?t[e]:"manual";return{desktopMode:"stacked"===t.desktopMode||"focused"===t.desktopMode?t.desktopMode:"split",recorderSide:"right"===t.recorderSide?"right":"left",recorderShare:n("recorderShare",35,65),sessionsWidth:n("sessionsWidth",300,520),sessionsSide:"left"===t.sessionsSide?"left":"right",sidebarWidth:n("sidebarWidth",220,360),sidebarVisible:"boolean"!=typeof t.sidebarVisible||t.sidebarVisible,mobilePane:"chat"===t.mobilePane?"chat":"record",calculator:s("calculator"),timer:s("timer")}}function a(e,t){return"always"===e||"scribe"===e&&"main"===t}},4482:(e,t,n)=>{function i(e){let t=e.saved_clinic_profiles??[];return 0===t.length?null:e.active_clinic_profile_id&&t.some(t=>t.id===e.active_clinic_profile_id)?e.active_clinic_profile_id:t.find(t=>!!e.hospital_name&&t.hospital_name===e.hospital_name&&(!e.hospital_address||t.hospital_address===e.hospital_address)&&(!e.hospital_phone||t.hospital_phone===e.hospital_phone))?.id??t[0]?.id??null}function s(e){let t=[...e.referral_directory??[]],n=i(e);return n?t.filter(e=>!e.clinic_profile_id||e.clinic_profile_id===n):t}function a(e){let t=[...e.referral_directory??[]],n=i(e);return n?t.map(e=>e.clinic_profile_id?e:{...e,clinic_profile_id:n}):t}n.d(t,{X2:()=>a,m9:()=>i,pt:()=>s})},5142:(e,t,n)=>{n.r(t),n.d(t,{__flushQuerySessionForTests:()=>x,__resetQuerySessionForTests:()=>P,defineSessionQuery:()=>R,getActiveScope:()=>I,getPublishedScope:()=>k,getScopeFor:()=>C,isScopeCurrent:()=>D,onScopeTransition:()=>O,subscribeScope:()=>T,useQueryScope:()=>E});var i=n(12115),s=n(5858),a=n(29753),r=n(17052),o=n(34471),l=n(18233),d=n(19939),c=n(8582),_=n(4389);let u=globalThis;function p(){return u.__vetSoapQuerySession||(u.__vetSoapQuerySession={bound:!1,fence:null,liveScope:null,publishedScope:null,reconcileQueued:!1,transitionListeners:new Set,scopeSubscribers:new Set,sessionQueries:new Map,unbind:[]}),u.__vetSoapQuerySession}function m(e){var t;let n=l.useAuthStore.getState().user?.id??null;if(e.fence){if(n===e.fence.userId)return null;e.fence=null}if(!n)return null;let i=(0,o.NI)();if(i.userId!==n)return null;if(e.liveScope&&(t=e.liveScope,t.userId===i.userId&&(t.clinicId??null)===(i.clinicId??null)&&t.generation===i.generation&&t.clinicMoves===i.clinicMoves))return e.liveScope;let s=Object.freeze({userId:n,clinicId:i.clinicId??null,generation:i.generation,clinicMoves:i.clinicMoves});return e.liveScope=s,s}function g(e,t){for(let n of[...e.transitionListeners])try{n(t)}catch(e){console.error("[query] Scope transition listener failed:",e)}}function h(e){for(let t of[...e.scopeSubscribers])t()}function f(e){e.unsubscribe?.(),e.observer?.destroy(),e.unsubscribe=void 0,e.observer=void 0,e.keyHash=void 0}function y(e,t){let n;try{n=e.factory(t)}catch(e){console.error("[query] Session query factory failed:",e),n=null}if(!n)return void f(e);let i=(0,s.EN)(n.queryKey);if(e.observer&&e.keyHash===i)return void e.observer.setOptions(n);f(e);let r=new a.$((0,_.getQueryClient)(),n);e.observer=r,e.keyHash=i,e.unsubscribe=r.subscribe(()=>void 0)}function v(e,t){let n=e.publishedScope;for(let t of(e.publishedScope=null,e.liveScope=null,e.sessionQueries.values()))f(t);(0,_.peekQueryClient)()?.clear(),g(e,{type:"retired",previous:n,reason:t}),h(e)}function b(e){e.reconcileQueued=!1;let t=m(e),n=e.publishedScope;if(t===n)return;n&&(!t||t.userId!==n.userId||t.generation!==n.generation)&&v(e,"identity_changed");let i=e.publishedScope;if(e.publishedScope=t,t){var s;let n=!i||i.clinicId!==t.clinicId||i.clinicMoves!==t.clinicMoves;for(let n of(t.clinicId&&i?.clinicId!==t.clinicId&&(s=t.clinicId,(0,_.peekQueryClient)()?.removeQueries({predicate:e=>e.queryKey[0]===c.Yc&&e.queryKey[1]!==s}
1)),e.sessionQueries.values()))y(n,t);g(e,{type:"changed",previous:i,next:t,clinicChanged:n})}h(e)}function w(e){e.reconcileQueued||(e.reconcileQueued=!0,queueMicrotask(()=>{p()===e&&e.reconcileQueued&&b(e)}))}function S(){let e=p();return e.bound||(e.bound=!0,e.unbind.push((0,r.G)(t=>{if("session_cleared"!==t.type)return;let n=l.useAuthStore.getState().user?.id??null;e.fence={userId:t.previousUserId??n},v(e,t.reason),w(e)})),"function"==typeof l.useAuthStore.subscribe&&e.unbind.push(l.useAuthStore.subscribe(t=>{let n=t.user?.id??null;e.fence&&n!==e.fence.userId&&(e.fence=null),w(e)})),"function"==typeof d.useClinicStore.subscribe&&e.unbind.push(d.useClinicStore.subscribe(()=>w(e))),e.publishedScope=m(e)),e}function I(){return m(S())}function C(e){let t=I();return(0,c.om)(t,e)?t:null}function k(){return S().publishedScope}function T(e){let t=S();return t.scopeSubscribers.add(e),()=>{t.scopeSubscribers.delete(e)}}function A(){return null}function E(){return(0,i.useSyncExternalStore)(T,k,A)}function D(e,t){if(!(0,c.om)(e,t))return!1;let n=S();return(!n.fence||n.fence.userId!==e.userId)&&("clinic"===t?(0,o.Ue)(e):(0,o.e1)(e))}function O(e){let t=S();return t.transitionListeners.add(e),()=>{t.transitionListeners.delete(e)}}function R(e,t){let n=S(),i=n.sessionQueries.get(e);i&&f(i);let s={factory:t};return n.sessionQueries.set(e,s),n.publishedScope&&y(s,n.publishedScope),()=>{n.sessionQueries.get(e)===s&&(f(s),n.sessionQueries.delete(e))}}function x(){let e=p();e.reconcileQueued&&b(e)}function P(){let e=u.__vetSoapQuerySession;if(e){for(let t of e.unbind)t();for(let t of e.sessionQueries.values())f(t);u.__vetSoapQuerySession=void 0}}},8582:(e,t,n)=>{n.d(t,{Ip:()=>r,VJ:()=>s,Xh:()=>l,Yc:()=>i,gv:()=>o,om:()=>a,vm:()=>d});let i="clinic",s="user";function a(e,t){return!!e?.userId&&("user"===t||!!e.clinicId)}function r(e,t,n,...o){if("string"!=typeof n||0===n.length)throw Error("Query keys need a non-empty domain name.");return a(e,t)?"clinic"===t?[i,e.clinicId,n,...o]:[s,e.userId,n,...o]:["scope-unavailable",t,n,...o]}function o(e,t,...n){return r(e,"clinic",t,...n)}function l(e,t,...n){return r(e,"user",t,...n)}function d(e,t,n){let a=function(e){let[t,n]=e;return"string"!=typeof n||0===n.length?null:t===i?{kind:"clinic",id:n}:t===s?{kind:"user",id:n}:null}(e);return!!a&&a.kind===n&&("clinic"===n?a.id===t.clinicId:a.id===t.userId)}},8610:(e,t,n)=>{n.d(t,{f:()=>i});function i(e,t,n,i){return s=>{let a=s.findIndex(n=>n[e]===t),r=a>=0?s[a]:null;if(null===n)return null===r||r!==i?s:s.filter(n=>n[e]!==t);if(null===r||r!==i)return s;let o=s.slice();return o[a]=n,o}}},15780:(e,t,n)=>{n.d(t,{B9:()=>w,D0:()=>E,GG:()=>h,GI:()=>A,IM:()=>C,L4:()=>p,L7:()=>I,Lt:()=>c,MX:()=>m,PU:()=>g,QX:()=>y,Tj:()=>T,Ul:()=>f,e0:()=>S,fj:()=>r.f,qp:()=>b,sJ:()=>k,sc:()=>o.sc,vS:()=>o.vS,xd:()=>_});var i=n(4389),s=n(8582),a=n(5142),r=n(8610),o=n(44197);let l=globalThis;function d(){if(!l.__vetSoapQueryOps){let e={serial:0,claims:new Map,tombstones:new Map};l.__vetSoapQueryOps=e,e.unbind=(0,a.onScopeTransition)(t=>{"retired"===t.type&&(e.claims.clear(),e.tombstones.clear())})}return l.__vetSoapQueryOps}function c(e,t){return{scope:e,kind:t,isCurrent:()=>(0,a.isScopeCurrent)(e,t)}}function _(e){let t=(0,a.getScopeFor)(e);if(!t)return null;let n=d();return n.serial+=1,{id:`op-${n.serial}`,scope:t,kind:e,isCurrent:()=>(0,a.isScopeCurrent)(t,e)}}function u(e,t){return e.isCurrent()&&(0,s.vm)(t,e.scope,e.kind)}function p(e,t,n){if(!u(e,t))return!1;let s=(0,i.getQueryClient)(),a=s.getQueryData(t);if(void 0===a)return!1;let r=n(a);return r!==a&&void 0!==r&&(s.setQueryData(t,r),!0)}function m(e,t){if(!u(e,t))return 0;let n=(0,i.getQueryClient)(),s=n.getQueryCache().findAll({queryKey:t,fetchStatus:"fetching"});return 0===s.length?0:(n.cancelQueries({queryKey:t,fetchStatus:"fetching"}),s.length)}function g(e,t,n){if(!u(e,t))return 0;let s=(0,i.getQueryClient)(),a=0;for(let[e,i]of s.getQueriesData({queryKey:t})){if(void 0===i)continue;let t=n(i,e);t!==i&&void 0!==t&&(s.setQueryData(e,t),a+=1)}return a}function h(e,t,n){if(!u(e,t))return!1;let s=(0,i.getQueryClient)();return void 0===s.getQueryData(t)&&(s.setQueryData(t,n),s.invalidateQueries({queryKey:t,exact:!0,refetchType:"none"}),!0)}function f(e,t,n){if(!u(e,t))return!1;let s=(0,i.getQueryClient)(),a=s.getQueryCache().find({queryKey:t,exact:!0});if("function"==typeof a?.options.queryFn)return!1;let r=a?.state.data,o=n(r);return o!==r&&void 0!==o&&(s.setQueryData(t,o),!0)}function y(e,t,n={}){return u(e,t)?(0,i.getQueryClient)().invalidateQueries({queryKey:t},n):Promise.resolve()}function v(e){return e.id}function b(e,t,n={}){let i=n.idOf??v,s=i(t),a=e.findIndex(e=>i(e)===s);if(a>=0){let i=e[a];if(!function(e,t,n=function(e){if(!e||"object"!=typeof e)return NaN;let{version:t,updated_at:n}=e;return"number"==typeof t&&Number.isFinite(t)?t:"string"==typeof n?Date.parse(n):NaN}){if(null==e)return!0;let i=n(e),s=n(t);return!!(Number.isNaN(i)||Number.isNaN(s))||s>=i}(i,t,n.versionOf))return e;let s=(n.merge??function(e,t){return{...e,...t}})(i,t);if(s===i)return e;let r=e.slice();return r[a]=s,r}let r=n.insert??"start";return"function"==typeof r?r(e,t):"end"===r?[...e,t]:[t,...e]}function w(e,t,n=v){return 0>e.findIndex(e=>n(e)===t)?e:e.filter(e=>n(e)!==t)}function S(e,t){return`${e}:${t}`}function I(e,t){d().claims.set(t,e.id)}function C(e,t){let{claims:n}=d();n.get(t)===e.id&&n.delete(t)}function k(e){return d().claims.has(e)}function T(e,t=6e4){d().tombstones.set(e,Date.now()+t)}function A(e){let{tombstones:t}=d(),n=t.get(e);return void 0!==n&&(Date.now()<n||(t.delete(e),!1))}function E(e){d().tombstones.delete(e)}}
1,19939:(e,t,n)=>{n.d(t,{NG:()=>y,NP:()=>f,Ug:()=>w,cv:()=>v,eQ:()=>g,sN:()=>h,useClinicStore:()=>m,vC:()=>b});var i=n(1934),s=n(16385),a=n(18233),r=n(17052),o=n(64024),l=n(25424);function d(e){let t="number"==typeof e?e:Number(e??0);return Number.isFinite(t)?t:0}let c={clinicId:null,role:null,membershipId:null,linkedStaffId:null,staffRole:null,isAdmin:!1,ownerEntitlement:null,isEntitlementResolved:!1,entitlementError:null};async function _(e,t){try{let n=await fetch("/api/clinic/entitlement",{headers:{Authorization:`Bearer ${e}`},cache:"no-store"}),i=await n.json().catch(()=>({}));if(t!==u)return;if(!n.ok){(401===n.status||403===n.status)&&l.IS.getState().clear(),m.setState({ownerEntitlement:null,isEntitlementResolved:!1,entitlementError:"Subscription verification failed. Please retry."});return}let s=function(e){if("clinic_owner"!==e.source||!e.settings)return null;let t="string"==typeof e.settings.subscription_tier?e.settings.subscription_tier:null;return t?{subscriptionTier:t,monthlyCostUsed:d(e.settings.monthly_cost_used),trialStatus:"string"==typeof e.settings.trial_status?e.settings.trial_status:null,trialEndDate:"string"==typeof e.settings.trial_end_date?e.settings.trial_end_date:null,extraVetSeats:d(e.settings.extra_vet_seats),subscriptionPeriodEnd:"string"==typeof e.settings.subscription_period_end?e.settings.subscription_period_end:null,usageResetDate:"string"==typeof e.settings.usage_reset_date?e.settings.usage_reset_date:null,costBudget:d(e.settings.cost_budget)}:null}(i);m.setState({ownerEntitlement:s,isEntitlementResolved:!0,entitlementError:null}),s||l.IS.getState().clear()}catch{if(t!==u)return;m.setState({ownerEntitlement:null,isEntitlementResolved:!1,entitlementError:"Subscription verification failed. Please retry."})}}let u=0;function p(e){return"owner"===e||"admin"===e}let m=(0,i.v)()((e,t)=>({...c,isLoading:!1,hasFetchedFromServer:!1,error:null,contextRevision:0,requestedClinicId:null,fetchClinicContext:async(n=!1,i)=>{let r=++u,o=i?.trim()||null;if(void 0!==i&&l.IS.getState().clear(),void 0!==i&&!o)return void e(e=>({...c,isLoading:!1,hasFetchedFromServer:!0,error:"Clinic selection is invalid.",requestedClinicId:null,contextRevision:e.contextRevision+1}));if(!(0,s.isSupabaseConfigured)()||!s.supabase)return void e(e=>({...c,isLoading:!1,hasFetchedFromServer:!0,error:"Clinic services are not configured.",requestedClinicId:null,contextRevision:e.contextRevision+1}));if(!a.useAuthStore.getState().user)return void e(e=>({...c,isLoading:!1,hasFetchedFromServer:!1,error:null,requestedClinicId:null,contextRevision:e.contextRevision+1}));let d=t(),g=null===o||o===d.clinicId;if(!d.hasFetchedFromServer||n||!g){e({...c,isLoading:!0,hasFetchedFromServer:!1,error:null,requestedClinicId:o});try{let t;if(o){let e=a.useAuthStore.getState().session?.access_token;if(!e)throw Error("Authentication session is unavailable.");let n=await fetch(`/api/clinic/context?clinic_id=${encodeURIComponent(o)}`,{headers:{Authorization:`Bearer ${e}`},cache:"no-store"}),i=await n.json();if(!n.ok)throw Error(i.error??"Failed to load clinic membership.");t=[i]}else{let{data:e,error:n}=await s.supabase.rpc("get_user_clinic_context");if(n)throw n;t=e??[]}if(r!==u)return;let n=t[0]??null,i=l.IS.getState().snapshot;if(i&&(!n||i.clinicId!==n.clinic_id||i.member!==("owner"!==n.role))&&l.IS.getState().clear(),n){var h;let t=(h=n.role,"owner"===h||"admin"===h||"staff"===h||"vet"===h||"tech"===h?h:null);if(!n.clinic_id||!n.membership_id||!t)throw Error("Clinic membership response is incomplete.");if(e(e=>{var i;return{clinicId:n.clinic_id??null,role:t,membershipId:n.membership_id??null,linkedStaffId:n.linked_staff_id??null,staffRole:(i=n.staff_role,"veterinarian"===i||"technician"===i?i:null),isAdmin:p(t),isLoading:!1,hasFetchedFromServer:!0,error:null,requestedClinicId:null,contextRevision:e.contextRevision+1}}),"owner"!==t){let e=a.useAuthStore.getState().session?.access_token;e&&_(e,r)}else m.setState({ownerEntitlement:null,isEntitlementResolved:!0})}else e(e=>({...c,isLoading:!1,hasFetchedFromServer:!0,error:null,requestedClinicId:null,contextRevision:e.contextRevision+1}))}catch(t){if(r!==u)return;console.error("[ClinicStore] Failed to resolve clinic context:",t),e(e=>({...c,isLoading:!1,hasFetchedFromServer:!0,error:"Failed to load clinic membership.",requestedClinicId:null,contextRevision:e.contextRevision+1}))}}},switchClinicContext:async e=>{await t().fetchClinicContext(!0,e)},resetClinic:()=>{l.IS.getState().clear(),u++,e(e=>({...c,isLoading:!1,hasFetchedFromServer:!1,error:null,requestedClinicId:null,contextRevision:e.contextRevision+1}))}}));function g(){let e=m(e=>e.clinicId),t=m(e=>e.role),n=m(e=>e.membershipId),i=m(e=>e.linkedStaffId),s=m(e=>e.staffRole),a=m(e=>e.isAdmin),r=m(e=>e.isLoading),o=m(e=>e.hasFetchedFromServer),l=m(e=>e.error),d=m(e=>e.contextRevision),c=m(e=>e.requestedClinicId);return{clinicId:e,role:t,membershipId:n,linkedStaffId:i,staffRole:s,isAdmin:a,isLoading:r,hasFetchedFromServer:o,error:l,contextRevision:d,requestedClinicId:c,fetchClinicContext:m(e=>e.fetchClinicContext),switchClinicContext:m(e=>e.switchClinicContext)}}function h(e){return e.isLoading||!e.hasFetchedFromServer?{status:"loading",clinicId:null,role:null,canViewSetup:!1,canManageSetup:!1,error:null}:e.error?{status:"error",clinicId:null,role:null,canViewSetup:!1,canManageSetup:!1,error:e.error}:e.clinicId&&e.role?{status:"ready",clinicId:e.clinicId,role:e.role,canViewSetup:!0,canManageSetup:p(e.role),error:null}:{status:"no_clinic",clinicId:null,role:null,canViewSetup:!1,canManageSetup:!1,error:null}}function f(){let e=m(e=>e.clinicId),t=m(e=>e.role),n=m(e=>e.isLoading);return h({clinicId:e,role:t,isLoading:n,hasFetchedFromServer:m(e=>e.hasFetchedFromServer),error:m(e=>e.error)})}(0,r.G)(e=>{"session_cleared"===e.type&&m.getState().resetClinic()});let y=()=>m(e=>e.clinicId),v=()=>m(e=>e.role),b=()=>m(e=>{let{viewingAsRegularUser:t}
1=o._H.getState();return!t&&e.isAdmin}),w=()=>m(e=>{let{viewingAsRegularUser:t}=o._H.getState();return e.hasFetchedFromServer&&!e.isLoading&&!e.error&&!t&&p(e.role)})},25424:(e,t,n)=>{n.d(t,{$b:()=>l,IS:()=>d,ob:()=>c});var i=n(1934),s=n(31692),a=n(17052),r=n(38455);let o=["subscription_tier","monthly_cost_used","trial_status","trial_end_date","extra_vet_seats","subscription_period_end","usage_reset_date","subscription_cancel_at_period_end","scheduled_downgrade_tier","scheduled_downgrade_date","purchase_source"];function l(e){return Object.fromEntries(o.map(t=>[t,e[t]]))}let d=(0,i.v)()((0,s.Zr)((e,t)=>({snapshot:null,remember:n=>{let i=t().snapshot;i&&Date.now()-i.observedAt<6e4&&JSON.stringify({...i,observedAt:void 0})===JSON.stringify(n)||e({snapshot:{...n,observedAt:Date.now()}})},clear:()=>e({snapshot:null})}),{name:"vet-soap-subscription-snapshot",storage:r.jo,partialize:e=>({snapshot:e.snapshot})}));function c(e,t){if(!e||!t||e.userId!==t||!e.settings||"boolean"!=typeof e.member||!Number.isFinite(e.observedAt))return!1;let n=Date.now()-e.observedAt;if(n<0||n>864e5)return!1;let i=e.member?e.entitlement?.trialStatus:e.settings.trial_status,s=e.member?e.entitlement?.trialEndDate:e.settings.trial_end_date;return"active"!==i||!!s&&new Date(s).getTime()>Date.now()}(0,r.Ui)(d),(0,a.G)(()=>d.getState().clear())},27158:(e,t,n)=>{n.d(t,{Hb:()=>d,PR:()=>l,XZ:()=>a,gd:()=>c,i8:()=>r,pJ:()=>s});var i=n(48884);let s=6;function a(e){let t="number"==typeof e?e:"string"==typeof e?Number(e):0;return Number.isFinite(t)?Math.max(0,Math.floor(t)):0}function r(e){return s+a(e)}function o(e){return"string"==typeof e.id&&e.id.length>0&&"veterinarian"===e.role&&null==e.deleted_at}function l(e,t=[],n={},i=[]){return function(e,t=[],n={},i=[]){let s=new Set(e.filter(e=>e.id!==n.excludeStaffId).filter(o).map(e=>e.id)),a=new Set(t.filter(e=>"active"===e.status&&("veterinarian"===e.staff_role||null==e.staff_role)).map(e=>e.linked_staff_id).filter(e=>"string"==typeof e&&s.has(e))),r=Date.now(),l=i.filter(e=>{if("veterinarian"!==e.staff_role||null!=e.accepted_at||null!=e.accepted_by||null!=e.revoked_at||"string"!=typeof e.expires_at)return!1;let t=new Date(e.expires_at).getTime();return Number.isFinite(t)&&t>r}).length;return{linkedMemberSeats:a.size,pendingInviteSeats:l,unclaimedProfileSeats:0,totalSeats:a.size+l}}(e,t,n,i).totalSeats}function d(e){return 3e3*a(e)}function c(e,t){if("string"!=typeof e)return 0;let n=Object.hasOwn(i.bt,e)?i.bt[e]:0;return n<=0?0:n+d(t)}},29442:(e,t,n)=>{n.d(t,{CR:()=>w,Vs:()=>f,bF:()=>y,k0:()=>h,qc:()=>v,rX:()=>p,z6:()=>g});var i=n(49561),s=n(15780);n(70805);var a=n(43265),r=n(4389),o=n(5142),l=n(76840);let d=[],c=new WeakSet,_=new WeakMap;function u(){let e=_.get((0,r.getQueryClient)());return e?.owner.isCurrent()?e:void 0}function p(e,t){let n=(0,r.getQueryClient)(),i=u()??{owner:e,pending:0,protectedIds:new Set,interrupted:!1};return _.set(n,i),i.pending++,t.forEach(e=>i.protectedIds.add(e)),()=>{i.pending--,!i.pending&&e.isCurrent()&&_.get(n)===i&&m(i)}}async function m(e){let t=(0,r.getQueryClient)(),n=(0,l.M2)(e.owner.scope).queryKey;if(e.interrupted=(0,s.MX)(e.owner,n)>0||e.interrupted,await t.cancelQueries({queryKey:n,exact:!0}),!e.owner.isCurrent()||e.pending||_.get(t)!==e||(_.delete(t),await t.invalidateQueries({queryKey:n,exact:!0,refetchType:"none"}),!e.owner.isCurrent()||u()?.pending))return;let i=t.getQueryCache().find({queryKey:n,exact:!0})?.isActive();(e.interrupted||i)&&await t.fetchQuery((0,l.M2)(e.owner.scope)).catch(()=>void 0)}function g(e){let t=u();if(!t)return e;let n=h(),i=new Map(n.map(e=>[e.id,e])),s=e.flatMap(e=>t.protectedIds.has(e.id)?i.has(e.id)?[i.get(e.id)]:[]:[e]),a=new Set(s.map(e=>e.id));return[...s,...n.filter(e=>t.protectedIds.has(e.id)&&!a.has(e.id))]}function h(e=(0,o.getScopeFor)("user")){return e?(0,r.getQueryClient)().getQueryData((0,l.M2)(e).queryKey)??d:d}function f(e=(0,o.getScopeFor)("user")){return!!e&&void 0!==(0,r.getQueryClient)().getQueryData((0,l.M2)(e).queryKey)}function y(e,t,n=!0){if(!e.isCurrent())return;let i=(0,l.M2)(e.scope).queryKey,a=n&&(0,s.MX)(e,i)>0,o=u();o&&(o.interrupted||=a),void 0===(0,r.getQueryClient)().getQueryData(i)?(0,s.GG)(e,i,t([])):(0,s.L4)(e,i,t)}function v(e){let t=(0,o.getScopeFor)("user");t&&y((0,s.Lt)(t,"user"),()=>e)}function b(e){return e.map(e=>({id:e.id,user_id:e.user_id,record_id:e.record_id,pet_name:e.pet_name,signalment:e.signalment,reason_summary:e.reason_summary,plan_snippet:e.plan_snippet,recheck_due:e.recheck_due,priority:e.priority,status:e.status,resolved_at:e.resolved_at,patient_id:e.patient_id,created_at:e.created_at,updated_at:e.updated_at}))}function w(){let e=(0,r.getQueryClient)();c.has(e)||(c.add(e),(0,a.JC)({id:"cases.list",version:1,kind:"user",queryKey:e=>(0,l.M2)(e).queryKey,project:b,restore:e=>e}),(0,o.onScopeTransition)(e=>{"retired"===e.type&&(0,i.Bs)()}))}},30969:(e,t,n)=>{n.d(t,{D1:()=>y,De:()=>u,I4:()=>p,Jn:()=>_,KZ:()=>a,OQ:()=>g,PH:()=>l,We:()=>h,_E:()=>o,a$:()=>b,dy:()=>r,eL:()=>v,lv:()=>c,nq:()=>s,pX:()=>d,uY:()=>f});var i=n(92276);let s={id:"default-soap",name:"Default SOAP",preamble:"(Generate a veterinary SOAP note using the supplied clinical information.) Follow this EXACT format:",history_template:`Patient Signalment and presenting complaint: 2Past medical concerns: 3C/S/V/D: 4Energy and appetite: 5Current medications: 6Diet: 7 8(If nothing is mentioned about C/S/V/D, put normal. If nothing is mentioned about Diet put not mentioned. If energy and appetite not mentioned assume it is normal. If no medications mentioned, put no medications reported. Don't leave anything in the history blank) 9(DO NOT PUT EXAM FINDINGS IN THE HISTORY. DO NOT PUT TREATMENT PLANS OR MEDICATIONS BEING PRESCRIBED DURING THE VISIT IN THE HISTORY.)`,exam_template:`Bodyweight: 10Temperature: 11Heart rate: 12Respiratory rate: 13CRT/MM: 1-2s, pink/moist 14BCS: 5/9 15Dental Score: 1/4 16FAS: 1/5 17Pain Score: 0 18(For CRT/MM, BCS, Dental Score, and Pain Score: default to the values listed above if nothing is mentioned. For FAS: use the dictated score; otherwise estimate from current fear/anxiety/stress behavior and label it estimated. Use FAS 1/5 only when neither a score nor behavior is described. For Bodyweight, Temperature, Heart rate, and Respiratory rate: leave blank if not supplied â do NOT invent or assume values.) 19(For body systems: If abnormality mentioned, replace "normal" and write ONLY the abnormality in medical terminology. If nothing is mentioned about the body system assume it is normal) 20 21 22GENERAL APPEARANCE/MENTATION/HYDRATION: BARH 23ORAL CAVITY: normal 24EYES: normal 25EARS: normal 26NOSE: normal
27THROAT: normal 28CARDIOVASCULAR/RESPIRATORY: normal 29ABDOMINAL PALPATION: normal 30UROGENITARY: normal 31LYMPH NODES: normal 32INTEGUMENT: normal 33NEURO: normal 34MUSCULOSKELETAL: normal 35RECTAL: normal 36 37DO NOT OMIT ANY SECTIONS EVEN IF NOTHING SAID ABOUT THEM. 38DO NOT put history or diagnostic findings in the physical exam. 39DO NOT put diagnostic results in the exam. 40Physical exam abnormalities should ALWAYS be medical terminology, NO lay terms.`,assessment_template:`Create a problem list. Do NOT add differentialsâleave that for the doctor to add manually. 41When listing items, use new lines only (no dashes, numbers, or bullet points).`,plan_template:`Diagnostics: 42(List if performed, otherwise leave blank) 43 44Treatments: 45(List if performed, otherwise leave blank) 46 47RX: 48(List medications sent home, otherwise leave blank) 49 50Client discussion: 51(Include key discussion points. If no client discussion dictated, leave blank. All points need to be separated with a line break)`,discharge_content:`Generate professional, client-friendly discharge instructions. Write for a worried pet owner, NOT for a medical chart. 52 53**SUMMARY OF YOUR VISIT** 542-3 sentences thanking them and stating why they came in and what the outcome was. 55 56**WHAT WE FOUND TODAY** 57Consolidate all findings into a flowing explanation that tells the story of what's going on. Explain what we discovered, what it means, and connect the dots for the client. Use plain language with medical terms in parentheses only when helpful. 58 59**WHAT WE DID TODAY** 60Consolidate all findings into a flowing explanation that tells the story of what happened. Explain what we found, what we did, any notable findings, and the expected outcome. Use plain language with medical terms in parentheses only when helpful. 61 62**HOME CARE INSTRUCTIONS** 63If pet was transferred or hospitalized, state that clearly and that the other facility will provide instructions. 64 65If going home, include: 66 671. Medications 68For each medication: 69**Medication Name (strength):** 70What it's for: [simple explanation] 71Dose: [how many, how often, with food?, for how long] 72Important: [any warnings] 73 742. Activity 75[Restrictions or recommendations] 76 773. Diet 78[If applicable] 79 80**REFERRAL/TRANSFER INFORMATION** 81[If transferred, explain why and what to expect. If not applicable, omit.] 82 83**WHAT TO WATCH FOR** 84Specific warning signs for THIS patient that should prompt a call. 85 86**FOLLOW-UP** 87When to return or what comes next. 88 89End with 1-2 warm, supportive sentences.`},a={id:"default-procedures",name:"Procedures",preamble:"(Generate a veterinary SOAP note using the supplied clinical information.) Follow this EXACT format:",history_template:`Patient Signalment and presenting complaint: 90Past medical concerns: 91C/S/V/D: 92Energy and appetite: 93Current medications: 94Diet: 95 96(If nothing is mentioned about C/S/V/D, put normal. If nothing is mentioned about Diet put not mentioned. If energy and appetite not mentioned assume it is normal. If no medications mentioned, put no medications reported. Don't leave anything in the history blank) 97(DO NOT PUT EXAM FINDINGS IN THE HISTORY. DO NOT PUT TREATMENT PLANS OR MEDICATIONS BEING PRESCRIBED DURING THE VISIT IN THE HISTORY.)`,exam_template:`Bodyweight: 98Temperature: 99Heart rate: 100Respiratory rate: 101CRT/MM: 1-2s, pink/moist 102BCS: 5/9 103Dental Score: 1/4 104FAS: 1/5 105Pain Score: 0 106(For CRT/MM, BCS, Dental Score, and Pain Score: default to the values listed above if nothing is mentioned. For FAS: use the dictated score; otherwise estimate from current fear/anxiety/stress behavior and label it estimated. Use FAS 1/5 only when neither a score nor behavior is described. For Bodyweight, Temperature, Heart rate, and Respiratory rate: leave blank if not supplied â do NOT invent or assume values.) 107(For body systems: If abnormality mentioned, replace "normal" and write ONLY the abnormality in medical terminology. If nothing is mentioned about the body system assume it is normal) 108 109 110GENERAL APPEARANCE/MENTATION/HYDRATION: BARH 111ORAL CAVITY: normal 112EYES: normal 113EARS: normal 114NOSE: normal 115THROAT: normal 116CARDIOVASCULAR/RESPIRATORY: normal 117ABDOMINAL PALPATION: normal 118UROGENITARY: normal 119LYMPH NODES: normal 120INTEGUMENT: normal 121NEURO: normal 122MUSCULOSKELETAL: normal 123RECTAL: normal 124 125DO NOT OMIT ANY SECTIONS EVEN IF NOTHING SAID ABOUT THEM. 126DO NOT put history or diagnostic findings in the physical exam. 127DO NOT put diagnostic results in the exam. 128Physical exam abnormalities should ALWAYS be medical terminology, NO lay terms.`,assessment_template:`Create a problem list. Do NOT add differentialsâleave that for the doctor to add manually. 129When listing items, use new lines only (no dashes, numbers, or bullet points).`,plan_template:`Diagnostics: 130(List if performed, otherwise leave blank) 131 132Treatments: 133(List if performed, otherwise leave blank) 134 135Procedure Report: 136 137RX: 138(List medications sent home, otherwise leave blank) 139 140Client discussion: 141(Include key discussion points. If no client discussion dictated, leave blank. All points need to be separated with a line break)`,discharge_content:`Generate professional, client-friendly post-procedure discharge instructions. Write for a worried pet owner, NOT for a medical chart. Adapt the content based on what procedure was actually performed (dental, surgery, or both). 142 143**SUMMARY OF TODAY'S PROCEDURE** 1442-3 sentences thanking them for trusting us with their pet's care, stating what procedure(s) were performed, and confirming how their pet did (e.g., "procedure went smoothly," "recovered well from anesthesia"). 145 146**WHAT WE DID TODAY** 147Consolidate all findings into a flowing explanation that tells the story of what happened. Explain what we found, what we did, any notable findings, and the expected outcome. Use plain language with medical terms in parentheses only when helpful. 148 149For dental procedures: Include what we found in the mouth, tartar/gum disease, any extractions and why.
150For surgical procedures: Include what we found, what we did, how we closed, any tissue sent for biopsy. 151 152**RECOVERY EXPECTATIONS** 153What's NORMAL in the first 24-48 hours after the procedure(s) performed: 154- Grogginess or sleepiness from anesthesia 155- Reduced appetite tonight 156- For dental: mild bleeding or pink-tinged saliva, drooling, reluctance to eat hard food 157- For surgery: mild swelling or bruising at incision site, some discomfort 158 159Your pet should be progressively getting more and more back to normal as time goes on. Some pets are extra sensitive to anesthesia and may take a bit longer to fully recoverâif your pet isn't showing improvement by 48 hours, please call us to let us know. 160 161**HOME CARE INSTRUCTIONS** 162 163Include ONLY the sections relevant to the procedure(s) performed: 164 1651. Incision Care (for surgical procedures) 166- How to monitor the incision (what normal healing looks like) 167- Keep dry (no baths, no swimming) for [X days] 168- E-collar requirements and why it's critical 169- What NOT to do (no licking, no picking at sutures) 170 1712. Mouth Care (for dental procedures) 172- NO brushing for [X days/weeks] to let extraction sites heal 173- No hard chews, bones, or tug toys for [X days/weeks] 174- When to resume dental home care 175 1763. Medications 177For each medication: 178**Medication Name (strength):** 179What it's for: [simple explanation] 180Dose: [how many, how often, with food?, for how long] 181Important: [any warnings] 182 1834. Activity 184[Specific restrictions based on procedure - strict rest vs. leash walks only vs. normal activity, and for how long] 185 1865. Diet 187- For dental: Soft food only for [X days], then gradually return to regular food 188- For surgery: [Specific feeding instructions based on procedure] 189- When to offer food tonight 190 191**WHAT TO WATCH FOR - CALL US IF YOU SEE:** 192Include warnings specific to the procedure(s) performed: 193- For dental: bleeding that doesn't stop, facial swelling, pawing at mouth, refusal to eat 194- For surgery: incision concerns (swelling, discharge, opening), signs of pain, lethargy 195- General: vomiting, not eating after 24-48 hours, anything that doesn't seem right 196 197**FOLLOW-UP** 198- Suture removal (if applicable): [When and for which site - incision, oral, or both] 199- Recheck appointment: [If needed, when] 200- Any pending results (biopsy, lab work): [Timeline] 201- Resume dental care: [When, if applicable] 202 203End with 2-3 warm, reassuring sentences. Remind them they made a good decision for their pet's health and encourage them to call with ANY concerns.`},r={id:"default-euthanasia",name:"Euthanasia",preamble:"Generate a euthanasia documentation note using the supplied clinical information. Follow this EXACT format:",history_template:`Reason for euthanasia: 204(Brief summary of condition, diagnosis, or quality of life concerns leading to this decision) 205 206Relevant history: 207(Recent decline, progression of disease, prior treatments attempted - if mentioned. If not mentioned, leave blank)`,exam_template:'(Brief terminal assessment if mentioned - general condition, mentation, any specific observations. If not mentioned, write "Terminal examination - patient in declining condition appropriate for humane euthanasia")',assessment_template:`Owner communication: 208Decision made by: 209Owner present: (Yes / No - if no, note if phone consent obtained) 210Quality of life discussion: (Brief summary if dictated, otherwise write "discussed with owner") 211Consent obtained: Yes`,plan_template:`Veterinarian: 212Staff present: 213Date: {{todayDate}} 214 215Sedation/Pre-euthanasia: 216(Drug, dose, route - if used. If none, write "none") 217 218Euthanasia solution: 219(Drug, dose, route) 220 221Method of confirmation: (Auscultation / No heartbeat and respiratory arrest) 222 223Complications: (If any, otherwise write "none") 224 225Aftercare: 226Remains: (Private cremation / Communal cremation / Home burial / Owner taking / Other) 227Paw print/fur clipping: (Yes / No) 228 229Additional notes: 230(Any additional notes, owner requests, or anything else relevant. If none, leave blank)`,discharge_content:`Generate a compassionate aftercare letter for a client who has just said goodbye to their pet. This is NOT a medical documentâwrite from the heart. Be warm, gentle, and supportive. 231 232In loving memory of the patient. 233 234**OPENING** 2352-3 sentences expressing sincere condolences. Acknowledge the weight of this loss and thank them for allowing us to be part of their pet's care and final moments. 236 237**YOU MADE THE RIGHT DECISION** 238Write a personalized paragraph reassuring them about their choice. Reference the specific situation if context is provided (the diagnosis, the decline, the quality of life concerns). Emphasize: 239- This was an act of love, not giving up 240- They prevented suffering 241- Knowing when to let go is the hardest and most selfless gift we can give 242- Their pet felt safe and loved at the end 243 244If no specific context provided, write a general but heartfelt reassurance that choosing to end suffering is the final act of love a pet owner can give. 245 246**WHAT YOU MAY BE FEELING** 247Gently normalize grief: 248- There's no right or wrong way to grieve 249- The loss of a pet is real and profoundâdon't let anyone minimize it 250- You may feel sadness, guilt, relief, emptiness, or all of these at onceâthat's completely normal 251- Grief comes in waves; some days will be harder than others 252- Take the time you needâthere's no timeline for healing 253 254**IF YOU HAVE OTHER PETS** 255(Include only if other pets are mentioned) 256Your other pets may also sense the loss. They might search for their companion, seem quieter than usual, or have changes in appetite or behavior. Give them extra love and maintain their normal routine as much as possible. Most pets adjust within a few weeks. 257 258**GRIEF SUPPORT RESOURCES**
259You don't have to go through this alone. These resources are staffed by trained counselors who understand pet loss: 260 261Pet Loss Support Hotlines: 262- Tufts University Pet Loss Hotline: (508) 839-7966 263 MondayâThursday, 6â9pm EST (voicemail available 24/7) 264- Cornell University Pet Loss Hotline: (607) 218-7457 265 Monday & Wednesday, 6â9pm EST 266- ASPCA Pet Loss Support: (877) 474-3310 267 Email: [email protected] 268 269Online Support: 270- Association for Pet Loss and Bereavement: www.aplb.org 271 Free chat rooms, video support groups, and resources 272- Lap of Love Pet Loss Support: www.lapoflove.com/pet-loss-support 273 Zoom support groups for pet loss, anticipatory grief, and more 274 275If you are experiencing a mental health crisis, please call or text 988 (Suicide and Crisis Lifeline). 276 277**HONORING THEIR MEMORY** 278When you're ready, there are many ways to honor the bond you shared: 279- Look through photos and share stories with those who knew your pet 280- Write a letter to your petâputting feelings into words can be healing 281- Create a small memorial: a photo display, a planted tree or flower, a special spot in your home 282- Make a donation to an animal charity in their name 283 284There's no rush. These are things to consider whenâand only whenâit feels right. 285 286**RECOMMENDED READING** 287These books have helped many pet owners navigate grief: 288- "The Loss of a Pet" by Wallace Sife, Ph.D. 289- "Grieving the Death of a Pet" by Betty Carmack 290- "Saying Goodbye to the Pet You Love" by Lorri A. Greene, Ph.D. 291 292**WE'RE HERE FOR YOU** 293Please know that our doors are always open. If you need to talk, have questions, or just want to share a memory, don't hesitate to reach out. We considered it a privilege to care for your pet, and we are here for you during this difficult time. 294 295**CLOSING** 296End with 2-3 warm, personal sentences that honor the bond they shared with their pet and offer gentle hope for the days ahead. 297 298With deepest sympathy, 299The entire veterinary team`},o={id:"default-communication",name:"Default Comm",content:'From this transcript, write a client communication summary I can email directly. Start with "Communication Summary for [Patient Name]" then write in natural paragraphs covering what was discussed - the current situation, any medication or diet changes, and next steps. Only include what\'s relevant to the conversation. Use bold text for emphasis where it helps clarity (medication names, important warnings, etc). Keep it conversational and avoid unexplained medical jargon. End with a friendly line inviting them to reach out with questions.'},l={id:"default-lab-callback",name:"Lab Callback",content:"Generate a client-ready lab results and communication summary from this transcript. This should be polished and ready to send directly to the pet owner. Start with the labwork results and analysis, then summarize the client communication."},d={id:"default-meeting",name:"Meeting Notes",content:`Generate professional meeting notes from this transcript. Include: 300 301**MEETING SUMMARY** 302- Date and participants (if mentioned) 303- Main purpose/topic of the meeting 304 305**KEY DISCUSSION POINTS** 306Summarize the main topics discussed in clear paragraphs. 307 308**DECISIONS MADE** 309List any decisions that were reached. 310 311**ACTION ITEMS** 312List specific tasks with owners (if mentioned): 313- [Task] - [Person responsible] - [Deadline if mentioned] 314 315**NEXT STEPS** 316Any follow-up meetings, deadlines, or pending items. 317 318Keep it concise and actionable. Focus on what matters for follow-up.`},c={id:"default-notes",name:"General Notes",content:"Generate a clear, organized summary from this transcript. Structure it logically based on the content - use headers and paragraphs as appropriate. Focus on capturing the key information in a way that's easy to reference later. Keep it concise but complete."},_={id:"default-general",name:"General Assistant",content:"You are a helpful documentation assistant. Generate clear, professional documents based on the provided content. Follow the template structure provided and maintain a professional tone throughout."},u=[{id:"default-general",name:"General Assistant",description:"General-purpose AI assistant for notes and documentation.",systemPrompt:"",isDefault:!0}],p=[{key:"history",label:"History",aliases:["Subjective","SUBJECTIVE","HISTORY"]}
318,{key:"exam",label:"Physical Exam",aliases:["Physical\\s*Exam(?:ination)?","PHYSICAL\\s*EXAM(?:INATION)?","Exam(?:ination)?","EXAM(?:INATION)?","Objective","OBJECTIVE"]},{key:"assessment",label:"Assessment",aliases:["ASSESSMENT"]},{key:"plan",label:"Plan",aliases:["Treatment\\s*Plan","TREATMENT\\s*PLAN","PLAN"]}],m={history_template:"history",exam_template:"exam",assessment_template:"assessment",plan_template:"plan"};function g(e){return Array.isArray(e.sections)?e.sections:p.map(t=>{let n=Object.entries(m).find(([,e])=>e===t.key)?.[0],i=n&&e[n]||"";return{...t,template:i}})}function h(e){let t=g(e).map(e=>`**${e.label.toUpperCase()}** 319${e.template}`).join("\n\n");return`${e.preamble} 320 321${t}`}function f(e){return Array.isArray(e.sections)&&0!==e.sections.length?e.sections.map((e,t)=>{let n=e.label.trim()||`Section ${t+1}`;return`**${n.toUpperCase()}** 322${e.template}`}).join("\n\n"):e.content}let y=i.b.map(e=>({id:`default-consent-${e.form_type}`,name:e.name,form_type:e.form_type,title:e.title,template_content:e.template_content})),v=1,b={generation_model:"gemini-3.8-flash",discharge_generation_model:"gemini-3.8-flash",admin_chat_model:"gemini-3.8-flash",admin_transcription_provider:void 0,admin_streaming_provider:void 0,model_overrides:{},vet_name:"",hospital_name:"",hospital_address:"",hospital_phone:"",auto_generate_discharge:!1,auto_extract_tasks:!0,auto_extract_memory:!0,memory_auto_apply:!0,auto_extract_cases:!1,auto_clinical_insights:!0,rag_generation_mode:"off",discharge_chat_enabled:!1,discharge_chat_full_context:!1,saved_clinic_profiles:[],active_clinic_profile_id:null,gmail_address:"",has_gmail_app_password:!1,gmail_app_password:"",saved_email_profiles:[],system_prompt_templates:[_],selected_system_prompt_id:"default-general",chat_persona_templates:u,selected_chat_persona_id:"default-general",patient_template_sets:[s,a,r],selected_patient_template_set_id:"default-soap",selected_recording_patient_template_set_id:"default-soap",communication_templates:[o,l],selected_communication_template_id:"default-communication",general_templates:[c,d],selected_general_template_id:"default-notes",consent_templates:y,selected_consent_template_id:"default-consent-general",style_preferences:`Tone: Warm, professional, reassuring 323Explain medical terms in plain language (parentheses for lay terms) 324Use "we" language 325Be specific with medication instructions - never "as directed" 326Keep documents scannable - clients should find info quickly 327No fluff or filler sentences 328If something wasn't discussed, don't make it up - omit or leave blank 329When listing items, use new lines only (no dashes, numbers, or bullets) unless specifically part of a template structure 330Physical exam abnormalities: medical terminology only, no lay terms 331Bold every physical abnormality in the SOAP 332Bold key pieces of information for emphasis, like medication instructions 333Do not add titles or headers not in the template 334With discharge instructions, be thorough, yet concise.`,style_preferences_general:"",ai_memory_patient:"",ai_memory_soap:"",ai_memory_discharge:"",ai_memory_communication:"",ai_memory_general:"",pending_memory_reviews:[],pending_case_reviews:[],pending_task_reviews:[],referral_directory:[],custom_links:[],hidden_default_link_ids:[],example_discharges:[],accent_color:"purple",translator_speaking_rate:1.15,translator_default_language:"Spanish",translator_default_voice_gender:"male",translator_default_clinician_language:"English",tts_provider:"soniox",tts_overrides:{},chat_tts_voice:"b089032e45db460fb1934ece75a8c51d",chat_tts_speed:1.2,chat_thinking_mode:!0,chat_show_response_mode_toggle:!1,generation_thinking_mode:!1,reasoning_effort:"high",reasoning_effort_overrides:{},vet_calc_stock_concentrations:{},hidden_drug_ids:[],tasks_last_seen_at:null,cases_last_seen_at:null,records_last_seen_at:null,subscription_tier:"free",free_recordings_used:0,monthly_cost_used:0,usage_reset_date:new Date().toISOString(),extra_vet_seats:0,stripe_customer_id:void 0,stripe_subscription_id:void 0,has_payment_method:!1,trial_status:null,trial_start_date:null,trial_end_date:null,ezyvet_client_id:void 0,ezyvet_client_secret:void 0,ezyvet_site_prefix:void 0,ezyvet_connected:!1,ezyvet_last_sync_at:void 0,ezyvet_auto_sync:!1,ezyvet_resource_id:void 0,ezyvet_default_email_detail_type_id:void 0,ezyvet_default_phone_detail_type_id:void 0,telnyx_virtual_number:void 0,telnyx_messaging_profile_id:void 0,default_input_mode:"voice",recording_show_context_button:!0,recording_show_patient_picker:!0,recording_show_media_tools:!0,recording_show_typed_notes:!0,recording_show_hospital_link:!0,recording_show_system_prompt:!0,interpretation_enabled:!0,toolbar_show_referrals:!0,toolbar_show_quick_links:!0}},34471:(e,t,n)=>{let i;n.d(t,{NI:()=>d,Ue:()=>c,e1:()=>_});var s=n(18233),a=n(19939),r=n(17052);let o=0,l=0;function d(){let e=a.useClinicStore.getState();return{userId:s.useAuthStore.getState().user?.id??null,clinicId:e.clinicId??null,generation:o,clinicMoves:l}}function c(e){return o===e.generation&&(s.useAuthStore.getState().user?.id??null)===e.userId&&l===e.clinicMoves&&(a.useClinicStore.getState().clinicId??null)===(e.clinicId??null)}function _(e){return o===e.generation&&(s.useAuthStore.getState().user?.id??null)===e.userId}(0,r.G)(()=>{o+=1}),a.useClinicStore.subscribe(()=>{!function(){let e=a.useClinicStore.getState().clinicId??null;if(void 0===i){i=e;return}e!==i&&(l+=1,i=e)}()})},39109:(e,t,n)=>{n.d(t,{Hc:()=>s,NT:()=>i,f1:()=>o,hG:()=>d,jQ:()=>c,jR:()=>a,n2:()=>r,yL:()=>l});let i={id:"__human_doctor__",name:"Human Doctor",description:"Human medicine AI assistant backed by 25K+ medical concepts, 191K FDA drug labels, and clinical evidence.",systemPrompt:"",isDefault:!1};function s(e,t,n,i){let s=e.generateId(),a={id:s,name:t,description:n,systemPrompt:i};return e.set(e=>({settings:{...e.settings,chat_persona_templates:[...e.settings.chat_persona_templates,a]}})),e.get().saveToSupabase(),s}
334function a(e,t,n){e.markSettingsDirty(),e.set(e=>({settings:{...e.settings,chat_persona_templates:e.settings.chat_persona_templates.map(e=>e.id===t?{...e,...n}:e)}})),e.scheduleDebouncedSave()}async function r(e,t){let n=e.get().settings.chat_persona_templates,i=n.find(e=>e.id===t);if(!i||i.isDefault||"__human_doctor__"===t||n.length<=1)return!1;let s=n.filter(e=>e.id!==t),a=e.get().settings.selected_chat_persona_id,r=a===t?s[0].id:a;return e.set(e=>({settings:{...e.settings,chat_persona_templates:s,selected_chat_persona_id:r}})),await e.get().saveToSupabase(),!0}function o(e,t){let n=e.get().settings.chat_persona_templates.find(e=>e.id===t);if(!n)return null;let i=e.generateId(),s={id:i,name:`${n.name} (Copy)`,description:n.description,systemPrompt:n.systemPrompt};return e.set(e=>({settings:{...e.settings,chat_persona_templates:[...e.settings.chat_persona_templates,s]}})),e.get().saveToSupabase(),i}function l(e,t){e.get().updateSettings({selected_chat_persona_id:t})}function d(e){let t=e.get().settings.chat_persona_templates,n=e.get().settings.selected_chat_persona_id;return t.find(e=>e.id===n)||t[0]||null}function c(e,t=!0){let n=e.get().settings.chat_persona_templates;if(!t)return n;let s=new Set(n.map(e=>e.id));return[...n,...[i].filter(e=>!s.has(e.id))]}},39700:(e,t,n)=>{n.d(t,{Fk:()=>h,VP:()=>g,jj:()=>m,sU:()=>u});var i=n(16385),s=n(99321),a=n(15780),r=n(29442),o=n(49561);let l=0,d=new Map,c=[];function _(e,t,n){let i={petName:e.pet_name,caseId:e.id,recordId:e.record_id,reason:t,timestamp:new Date().toISOString(),recordsLoadedCount:n};for(c.push(i);c.length>50;)c.shift();console.warn(`[CasesStore] REMOVING case "${e.pet_name}" (${e.id}): ${t} | records loaded: ${n}`)}function u(){let e=Date.now();return!(e-l<6e4)&&(l=e,!0)}function p(e,t){return t.has(e.record_id)?(0,o.xx)(e)?"vaccine_recheck":"visible":"orphan"}function m(e){let t=new Set((0,s.readRecordList)().map(e=>e.id));if(0===t.size)return{visibleCases:e,orphanedIds:[],vaccineRecheckIds:[],recordsLoaded:!1};let n=e.filter(e=>"orphan"===p(e,t)).map(e=>e.id),i=e.filter(e=>"vaccine_recheck"===p(e,t)).map(e=>e.id),a=new Set([...n,...i]);return{visibleCases:e.filter(e=>!a.has(e.id)),orphanedIds:n,vaccineRecheckIds:i,recordsLoaded:!0}}async function g(){let e=(0,a.xd)("user");if(!e)return;let t=(0,r.k0)(e.scope);if(!t||0===t.length)return;let n=new Set((0,s.readRecordList)().map(e=>e.id));if(0===n.size)return;let l=t.filter(e=>!n.has(e.record_id)),c=[];for(let e of l){let t=(d.get(e.id)||0)+1;if(d.set(e.id,t),t>=2){if((0,i.isSupabaseConfigured)()&&i.supabase){let{data:t}=await i.supabase.from("records").select("id").eq("id",e.record_id).single();if(t){d.delete(e.id);continue}}c.push(e)}}t.forEach(e=>{n.has(e.record_id)&&d.delete(e.id)});let u=t.filter(e=>n.has(e.record_id)&&(0,o.xx)(e));if(0===c.length&&0===u.length||!e.isCurrent())return;c.forEach(e=>_(e,"orphan",n.size)),u.forEach(e=>_(e,"vaccine_recheck",n.size));let p=c.map(e=>e.id),m=new Set([...p,...u.map(e=>e.id)]);(0,r.bF)(e,e=>e.filter(e=>!m.has(e.id)),!1),c.forEach(e=>d.delete(e.id)),u.length,p.length}function h(e){_(e,"realtime_delete",(0,s.readRecordList)().length)}window.getCaseRemovalLog=function(){return[...c]}},41167:(e,t,n)=>{n.d(t,{AW:()=>_,Ck:()=>o,HK:()=>l,MT:()=>r,_7:()=>d,c3:()=>a,ps:()=>c,zF:()=>s});let i=null;function s(e){i=e}function a(){if(!i)throw Error("recordsStore has not been registered yet â import order bug: localCache helpers ran before the store module initialized");return i}let r=new Map,o=e=>({id:e.id,user_id:e.user_id,pet_name:e.pet_name,signalment:e.signalment??null,tags:e.tags??null,visit_date:e.visit_date,document_type:e.document_type,transcript:null,audio_duration_seconds:e.audio_duration_seconds??null,soap_note:null,record_addenda:null,discharge_instructions:null,discharge_instructions_translated:e.discharge_instructions_translated??null,translated_language:e.translated_language??null,previous_pet_name:e.previous_pet_name??null,previous_signalment:e.previous_signalment??null,previous_soap_note:e.previous_soap_note??null,previous_discharge_instructions:e.previous_discharge_instructions??null,previous_discharge_instructions_translated:e.previous_discharge_instructions_translated??null,previous_translated_language:e.previous_translated_language??null,previous_updated_at:e.previous_updated_at??null,template_name:e.template_name??null,context_record_id:e.context_record_id??null,context_chain_ids:e.context_chain_ids??null,hospital_name:e.hospital_name??null,hospital_phone:e.hospital_phone??null,hospital_address:e.hospital_address??null,vet_name:e.vet_name??null,vet_id:e.vet_id??null,lesion_photos:e.lesion_photos,attachments:e.attachments,is_archived:e.is_archived,is_favorite:e.is_favorite,follow_up_date:e.follow_up_date??null,follow_up_notes:e.follow_up_notes??null,follow_up_completed:e.follow_up_completed,follow_up_completed_at:e.follow_up_completed_at??null,created_at:e.created_at,updated_at:e.updated_at,viewed_at:e.viewed_at??null,hospital
334ization_id:e.hospitalization_id??null,had_hospitalization:e.had_hospitalization??!1,help_requested_at:e.help_requested_at??null,help_message:e.help_message??null,discharge_chat_active:e.discharge_chat_active??null,patient_id:e.patient_id??null,pims_consult_id:e.pims_consult_id??null,pims_transferred_at:e.pims_transferred_at??null,pims_transfer_adapter:e.pims_transfer_adapter??null,consent_to_be_recorded:e.consent_to_be_recorded??null,vitals_snapshot:e.vitals_snapshot??null,clinical_insights:e.clinical_insights??null,ai_summary_card:e.ai_summary_card??null,ai_summary_card_history:null}),l=(e,t)=>{t&&r.set(e,t)},d=e=>r.get(e)??null,c=e=>{r.delete(e)},_=()=>{r.clear()}},43265:(e,t,n)=>{n.d(t,{JC:()=>h,cO:()=>y});var i=n(5858),s=n(38455),a=n(8582),r=n(4389),o=n(5142);let l=globalThis;function d(e){return`vet-soap-query:${e}`}function c(e){e.timer&&clearTimeout(e.timer),e.timer=void 0,e.pendingScope=void 0}function _(e,t){s.jo?.setItem(e,{state:t,version:1})}function u(e){s.jo?.removeItem(e)}function p(e,t,n){let i,{definition:l}=t;if(!(0,a.om)(n,l.kind)||!(0,o.isScopeCurrent)(n,l.kind)||(0,s.om)()!==n.userId)return;let c=l.queryKey(n),p=(0,r.getQueryClient)();if(void 0!==p.getQueryData(c))return;let m=d(l.id),g=function(e){let t=s.jo?.getItem(e);if(!t||t instanceof Promise)return null;let n=t.state;return n&&1===n.format&&"string"==typeof n.userId?n:null}(m);if(!g&&l.legacy){let e=s.jo?.getItem(l.legacy.name);if(e&&!(e instanceof Promise))try{let t=l.legacy.restore(e.state,n);void 0!==t&&(g={format:1,version:l.version,userId:n.userId,clinicId:"clinic"===l.kind?n.clinicId:null,updatedAt:0,data:l.project(t)},_(m,g))}catch{}}if(!g)return;let h=g.version===l.version&&g.userId===n.userId&&("user"===l.kind||g.clinicId===n.clinicId),f=void 0===l.maxAgeMs||Date.now()-g.updatedAt<=l.maxAgeMs;if(!h||!f)return void u(m);try{i=l.restore(g.data)}catch(e){console.warn(`[query] Discarding unreadable persisted query "${l.id}".`,e),u(m);return}if(void 0!==i){e.hydrating=!0;try{p.setQueryData(c,i,{updatedAt:g.updatedAt})}finally{e.hydrating=!1}p.invalidateQueries({queryKey:c,exact:!0,refetchType:"none"})}}function m(e,t){let n,{definition:i}=e;if(!(0,o.isScopeCurrent)(t,i.kind)||(0,s.om)()!==t.userId)return;let a=(0,r.getQueryClient)().getQueryCache().find({queryKey:i.queryKey(t),exact:!0}),l=a?.state.data;if(a&&void 0!==l){try{n=i.project(l)}catch(e){console.warn(`[query] Could not project persisted query "${i.id}".`,e);return}_(d(i.id),{format:1,version:i.version,userId:t.userId,clinicId:"clinic"===i.kind?t.clinicId:null,updatedAt:a.state.dataUpdatedAt,data:n})}}function g(){if(l.__vetSoapQueryPersistence)return l.__vetSoapQueryPersistence;let e={registrations:new Map,hydrating:!1,unbind:[],retired:new Set};if(l.__vetSoapQueryPersistence=e,"u">typeof document){let t=()=>(function(e){for(let t of e.registrations.values()){let e=t.pendingScope;e&&(c(t),m(t,e))}})(e),n=()=>{"hidden"===document.visibilityState&&t()};window.addEventListener("pagehide",t),document.addEventListener("visibilitychange",n),e.unbind.push(()=>{window.removeEventListener("pagehide",t),document.removeEventListener("visibilitychange",n)})}return e.unbind.push((0,o.onScopeTransition)(t=>{for(let n of e.registrations.values()){let e=n.pendingScope;("retired"===t.type||e&&!(0,o.isScopeCurrent)(e,n.definition.kind))&&c(n)}if("retired"!==t.type)for(let n of(f(e),e.registrations.values()))p(e,n,t.next)})),e.unbind.push((0,r.getQueryClient)().getQueryCache().subscribe(t=>{if(e.hydrating||"updated"!==t.type||"success"!==t.action.type)return;let n=(0,o.getPublishedScope)();if(n)for(let s of e.registrations.values()){let{definition:e}=s;(0,a.om)(n,e.kind)&&(0,i.EN)(e.queryKey(n))===t.query.queryHash&&function(e,t){(c(e),"u">typeof document&&"hidden"===document.visibilityState)?m(e,t):(e.pendingScope=t,e.timer=setTimeout(()=>{e.timer=void 0,e.pendingScope=void 0,m(e,t)},e.definition.writeDelayMs??1e3))}(s,n)}})),e}function h(e){let t=g(),n=t.registrations.get(e.id);n&&c(n);let i={definition:e};t.registrations.set(e.id,i);let s=(0,o.getPublishedScope)();return s&&p(t,i,s),()=>{t.registrations.get(e.id)===i&&(c(i),t.registrations.delete(e.id))}}function f(e){let t=(0,o.getPublishedScope)();if(t?.userId&&(0,s.om)()===t.userId)for(let t of e.retired)s.jo?.removeItem(t)}function y(e){let t=g();t.retired.add(e),f(t)}},44197:(e,t,n)=>{n.d(t,{lZ:()=>l,sc:()=>o,vS:()=>r});let i=new Set,s=new Map,a=2e3,r=(e,t=a)=>{let n=s.get(e);n&&clearTimeout(n),i.add(e);let r=setTimeout(()=>{i.delete(e),s.delete(e)},t);s.set(e,r)},o=e=>i.has(e),l=()=>
334{s.forEach(e=>clearTimeout(e)),s.clear(),i.clear()}},49561:(e,t,n)=>{n.d(t,{BJ:()=>T,Bs:()=>v,EV:()=>I,Gk:()=>C,MW:()=>y,T:()=>c,XH:()=>m,_N:()=>h,i1:()=>k,in:()=>_,t0:()=>f,uC:()=>g,wE:()=>d,xx:()=>S,yE:()=>p});var i=n(53423),s=n(94240),a=n(99321);let r=["vaccine","vaccination","vaccines","vax","booster"],o=["recheck","follow-up","follow up","followup"],l=["vaccine recheck","vaccination recheck","vaccine follow-up","vaccine follow up","vaccination follow-up","vaccination follow up"];function d(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function c(e,t){console.error(`Failed to ${e}:`,t instanceof Error?t.message:"Unknown error"),s.j.getState().addToast("error",`Failed to ${e}. Changes may not sync.`)}let _={latestFetchGen:0,pendingDeletes:new Map},u=1;function p(e,t){let n=_.pendingDeletes.get(e);if(n){n.lease&&(n.lease.invalidated=!0),n.inFlight+=1,!n.baseline&&t&&(n.baseline=t);let i={id:e,invalidated:!1,settled:!1,lifetime:n.lifetime};return n.lease=i,i}let i={id:e,invalidated:!1,settled:!1,lifetime:u++};return _.pendingDeletes.set(e,{status:"pending",gen:0,confirmedAt:0,inFlight:1,lifetime:i.lifetime,baseline:t,lease:i}),i}function m(e,t){let n=_.pendingDeletes.get(e.id);!n||e.settled||(e.settled=!0,n.lifetime===e.lifetime&&(n.inFlight=Math.max(0,n.inFlight-1),n.status="confirmed",n.gen=Math.max(n.gen,t),n.confirmedAt=Math.max(n.confirmedAt,Date.now())))}function g(e,t){let n=_.pendingDeletes.get(e);if(n){n.lease&&(n.lease.invalidated=!0),"pending"===n.status&&(n.status="confirmed"),t>n.gen&&(n.gen=t),n.confirmedAt=Math.max(n.confirmedAt,Date.now());return}_.pendingDeletes.set(e,{status:"confirmed",gen:t,confirmedAt:Date.now(),inFlight:0,lifetime:u++,baseline:null})}function h(e){let t=_.pendingDeletes.get(e.id);return!t||e.settled||(e.settled=!0,t.lifetime!==e.lifetime)?null:(t.inFlight=Math.max(0,t.inFlight-1),0===t.inFlight&&"pending"===t.status)?(_.pendingDeletes.delete(e.id),t.baseline):null}function f(e){return _.pendingDeletes.has(e)}function y(e){let t=Date.now();for(let[n,i]of _.pendingDeletes)"confirmed"===i.status&&0===i.inFlight&&i.gen<e&&t-i.confirmedAt>=6e4&&_.pendingDeletes.delete(n)}function v(){_.pendingDeletes.clear()}function b(e){return(e??"").toLowerCase()}function w(e,t){return t.some(t=>e.includes(t))}function S(e){let t=b(e.reason_summary),n=b(e.plan_snippet),i=`${t} ${n}`.trim();if(!i)return!1;if(l.some(e=>i.includes(e)))return!0;let s=w(i,r),a=w(i,o);return s&&a}function I(e){return(0,a.readRecordList)().find(t=>t.id===e)?.hospital_name??null}function C(e,t){return[...e].sort((e,n)=>{switch(t){case"priority":{let t={urgent:0,high:1,normal:2},i=t[e.priority??"normal"]-t[n.priority??"normal"];return 0!==i?i:(n.created_at??"").localeCompare(e.created_at??"")}case"recheck_date":if(e.recheck_due&&n.recheck_due)return e.recheck_due.localeCompare(n.recheck_due);if(e.recheck_due)return -1;if(n.recheck_due)return 1;return(n.created_at??"").localeCompare(e.created_at??"");case"pet_name":return(e.pet_name??"").localeCompare(n.pet_name??"",void 0,{sensitivity:"base"});case"newest":return(n.created_at??"").localeCompare(e.created_at??"");default:return(e.created_at??"").localeCompare(n.created_at??"")}})}function k(e){return[...e].sort((e,t)=>e.resolved_at&&t.resolved_at?t.resolved_at.localeCompare(e.resolved_at):(t.updated_at??t.created_at??"").localeCompare(e.updated_at??e.created_at??""))}function T(){return(0,i.l5)()}},50649:(e,t,n)=>{function i(e){let t=e.join("|");return[RegExp(`^##?\\s*(${t})\\s*$`,"im"),RegExp(`^\\*\\*(${t})\\*\\*\\s*$`,"im"),RegExp(`^(${t}):\\s*$`,"im"),RegExp(`^<strong>(${t})<\\/strong>\\s*$`,"im"),RegExp(`<p>\\s*<strong>(${t})<\\/strong>\\s*<\\/p>`,"i"),RegExp(`<h[1-3]>(${t})<\\/h[1-3]>`,"i"),RegExp(`^(${t})\\s*$`,"m"),RegExp(`<p[^>]*>\\s*<b>(${t})<\\/b>\\s*<\\/p>`,"i"),RegExp(`<p[^>]*>\\s*<strong>(${t})<\\/strong>\\s*<\\/p>`,"i")]}n.d(t,{$u:()=>g,X6:()=>h,b4:()=>f,oq:()=>v,su:()=>y});let s=["History","HISTORY","Subjective","SUBJECTIVE"],a=["Physical\\s*Exam(?:ination)?","PHYSICAL\\s*EXAM(?:INATION)?","Exam(?:ination)?","EXAM(?:INATION)?","Objective","OBJECTIVE"],r=["Assessment","ASSESSMENT"],o=["Treatment\\s*Plan","TREATMENT\\s*PLAN","Plan","PLAN"],l=/^(Patient|Name|Pet|Animal)\s*:\s*.+$/im,d=i(s),c=i(a),_=i(r),u=i(o);function p(e,t){for(let n of t){n.lastIndex=0;let t=n.exec(e);if(t)return{start:t.index,end:t.index+t[0].length}}return null}function m(e){let t=[];for(let{type:n,patterns:i}of[{type:"history",patterns:d}
334,{type:"exam",patterns:c},{type:"assessment",patterns:_},{type:"plan",patterns:u}]){let s=p(e,i);s&&t.push({type:n,start:s.start,headerEnd:s.end})}return t.sort((e,t)=>e.start-t.start),t}function g(e){let t={history:null,exam:null,assessment:null,plan:null,unparsed:null};if(!e||!e.trim())return t;let n=m(e);if(0===n.length)return t.unparsed=e.trim(),t;let i=n[0],s=null;if(i.start>0){let n=e.slice(0,i.start).trim();n&&(l.test(n)?s=n:t.unparsed=n)}for(let i=0;i<n.length;i++){let a=n[i],r=n[i+1],o=a.headerEnd,l=r?r.start:e.length,d=e.slice(o,l).trim();"history"===a.type&&s&&(d=s+"\n"+d),d&&(t[a.type]=d)}return s&&!t.history&&(t.unparsed=s),t}function h(e){return!!e&&!!e.trim()&&m(e).length>0}function f(e){switch(e){case"history":return"History";case"exam":return"Physical Exam";case"assessment":return"Assessment";case"plan":return"Plan";default:return e}}function y(e,t){let n={sections:{},unparsed:null};for(let e of t)n.sections[e.key]=null;if(!e||!e.trim())return n;let s=function(e,t){let n=[];for(let s of t){let t=p(e,function(e){let t=[e.label];e.aliases&&t.push(...e.aliases);let n=t.map(e=>e.includes("\\")?e:e.replace(/[.*+?^${}()|[\]]/g,"\\$&")),s=i(n);return s.push(RegExp(`^(${n.join("|")})\\s*$`,"im")),s}(s));t&&n.push({key:s.key,start:t.start,headerEnd:t.end})}return n.sort((e,t)=>e.start-t.start),n}(e,t);if(0===s.length)return n.unparsed=e.trim(),n;let a=s[0],r=null;if(a.start>0){let t=e.slice(0,a.start).trim();t&&(l.test(t)?r=t:n.unparsed=t)}for(let t=0;t<s.length;t++){let i=s[t],a=s[t+1],o=i.headerEnd,l=a?a.start:e.length,d=e.slice(o,l).trim();0===t&&r&&(d=r+"\n"+d),d&&(n.sections[i.key]=d)}return r&&s.length>0&&!n.sections[s[0].key]&&(n.unparsed=r),n}function v(e,t,n){let i=[];for(let s of(n&&i.push(n),t)){let t=e[s.key];t&&i.push(`<h2>${s.label}</h2> 335${t}`)}return i.join("\n\n")}[...s,...a,...r,...o]},53423:(e,t,n)=>{function i(e=new Date){let t=60*e.getTimezoneOffset()*1e3;return new Date(e.getTime()-t).toISOString().split("T")[0]}function s(e){let t=new Date;return t.setDate(t.getDate()+e),i(t)}function a(e,t){let n=new Date(e),i=n.getMonth()+t;return n.setMonth(i),n.getMonth()!==(i%12+12)%12&&n.setDate(0),n}n.d(t,{Sb:()=>a,e6:()=>s,l5:()=>i})},55342:(e,t,n)=>{n.d(t,{Bm:()=>u,Gq:()=>h,Hn:()=>d,L$:()=>o,T:()=>g,WZ:()=>_,aW:()=>p,hx:()=>c,j7:()=>a,q4:()=>l,qG:()=>f,wE:()=>m});var i=n(53423),s=n(94240);let a={unsubscribeBroadcast:null,hasFetchedThisSession:!1,wasDisconnected:!1,pendingDeletes:new Map,latestFetchGen:0},r=1;function o(e,t){let n=a.pendingDeletes.get(e);if(n){n.lease&&(n.lease.invalidated=!0),n.inFlight+=1,!n.baseline&&t&&(n.baseline=t);let i={id:e,invalidated:!1,settled:!1,lifetime:n.lifetime};return n.lease=i,i}let i={id:e,invalidated:!1,settled:!1,lifetime:r++};return a.pendingDeletes.set(e,{status:"pending",gen:0,confirmedAt:0,inFlight:1,lifetime:i.lifetime,baseline:t,lease:i}),i}function l(e,t){let n=a.pendingDeletes.get(e.id);!n||e.settled||(e.settled=!0,n.lifetime===e.lifetime&&(n.inFlight=Math.max(0,n.inFlight-1),n.status="confirmed",n.gen=Math.max(n.gen,t),n.confirmedAt=Math.max(n.confirmedAt,Date.now())))}function d(e,t){let n=a.pendingDeletes.get(e);if(n){n.lease&&(n.lease.invalidated=!0),"pending"===n.status&&(n.status="confirmed"),t>n.gen&&(n.gen=t),n.confirmedAt=Math.max(n.confirmedAt,Date.now());return}a.pendingDeletes.set(e,{status:"confirmed",gen:t,confirmedAt:Date.now(),inFlight:0,lifetime:r++,baseline:null})}function c(e){let t=a.pendingDeletes.get(e.id);return!t||e.settled||(e.settled=!0,t.lifetime!==e.lifetime)?null:(t.inFlight=Math.max(0,t.inFlight-1),0===t.inFlight&&"pending"===t.status)?(a.pendingDeletes.delete(e.id),t.baseline):null}function _(e){return a.pendingDeletes.has(e)}function u(e){let t=Date.now();for(let[n,i]of a.pendingDeletes)"confirmed"===i.status&&0===i.inFlight&&i.gen<e&&t-i.confirmedAt>=6e4&&a.pendingDeletes.delete(n)}function p(){a.pendingDeletes.clear()}let m=e=>{if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t};function g(e,t){console.error(`Failed to ${e}:`,t instanceof Error?t.message:"Unknown error"),s.j.getState().addToast("error",`Failed to ${e}. Changes may not sync.`)}let h=()=>(0,i.l5)(),f=e=>(0,i.e6)(e)},57858:(e,t,n)=>{n.d(t,{g:()=>l});var i=n(16385),s=n(15780),a=n(4389),r=n(65169);let o=new Map;function l(e,t,n){let l=e.scope.userId;if("user"!==e.kind||!l||!e.isCurrent())return Promise.resolve(null);let d=o.get(l),c=(async()=>
335{if(d&&await d.catch(()=>null),!e.isCurrent()||!i.supabase)return null;let{data:{user:o}}=await i.supabase.auth.getUser();if(!e.isCurrent()||o?.id!==l)return null;let c=async t=>{if(!e.isCurrent()||!i.supabase)return null;let{data:s,error:a}=await i.supabase.from("settings").update(n).eq("id",t).eq("user_id",l).select("*").maybeSingle();if(a)throw a;return s},_=t?await c(t):null;if(!e.isCurrent())return null;if(!_){let{data:t,error:s}=await i.supabase.from("settings").select("id").eq("user_id",l).maybeSingle();if(s)throw s;if(!e.isCurrent()||(t?.id&&(_=await c(t.id)),!e.isCurrent()))return null;if(!_){let{data:e,error:t}=await i.supabase.from("settings").insert({...n,user_id:l}).select("*").single();if(t)throw t;_=e}}if(!e.isCurrent()||!_)return null;_=(0,r.OY)(_);let u=(0,r.WK)(e.scope);return(await (0,a.getQueryClient)().cancelQueries({queryKey:u,exact:!0}),e.isCurrent())?((0,s.L4)(e,u,()=>_)||(0,s.GG)(e,u,_),_):null})();return o.set(l,c),c.finally(()=>{o.get(l)===c&&o.delete(l)}).catch(()=>void 0),c}},58645:(e,t,n)=>{n.d(t,{$Y:()=>_,j:()=>u,ny:()=>c});var i=n(9846),s=n(16385),a=n(55342),r=n(70805),o=n(4389),l=n(5142),d=n(83974);function c(e){return(0,r.AP)(e,{domain:"tasks",key:["list"],refetchOnWindowFocus:!1,refetchOnReconnect:!1,fetch:async({signal:e,scope:t})=>{if(!s.supabase)throw Error("Database unavailable");let n=++a.j7.latestFetchGen,i=[];for(let r=0;;r+=1e3){let{data:o,error:d}=await s.supabase.from("tasks").select("*").order("due_date",{ascending:!0,nullsFirst:!1}).order("id",{ascending:!0}).range(r,r+1e3-1).abortSignal(e);if(d)throw d;if(e.aborted)throw Error("Task read cancelled");let c=o??[];if(i.push(...c),c.length<1e3){let e=i.filter(e=>!(0,a.WZ)(e.id));return(0,l.isScopeCurrent)(t,"user")&&(0,a.Bm)(n),e}}}})}function _(e,t=!1){(0,d.lf)();let n=c(e),i=(0,o.getQueryClient)();return t&&i.cancelQueries({queryKey:n.queryKey,exact:!0}),i.fetchQuery(n)}async function u(e){if(!(0,s.isSupabaseConfigured)())return;let t=(0,l.getScopeFor)("user");if(!t)return;let n="boolean"==typeof e?e:e?.force,a=c(t).queryKey;if(n||void 0===(0,r.QX)(a))try{await _(t,!!n)}catch(e){!(0,i.wm)(e)&&(0,l.isScopeCurrent)(t,"user")&&console.error("Failed to fetch tasks:",e)}}},63769:(e,t,n)=>{n.d(t,{Tr:()=>m,VB:()=>h});var i=n(16385);let s=null,a=0,r=!1;async function o(e){if(i.supabase)return void 0===e&&Date.now()-a<3e3?s??void 0:s||(s=(async()=>{try{await i.supabase.realtime.setAuth(e),a=Date.now()}catch(e){console.debug("[realtime] setAuth failed:",e)}finally{s=null}})())}let l=new Set,d=new Set,c=null;function _(){c=null,l.size>0&&(console.debug(`[realtime] ${l.size} channel(s) disconnected: ${[...l].join(", ")}`),l.clear()),d.size>0&&(console.debug(`[realtime] ${d.size} channel(s) reconnected: ${[...d].join(", ")}`),d.clear())}function u(e,t){"disconnected"===t?(l.add(e),d.delete(e)):(d.add(e),l.delete(e)),c||(c=setTimeout(_,1e3))}let p=new Map;async function m(e,t,n,s){if(!(0,i.isSupabaseConfigured)()||!i.supabase)return()=>{};let a=`${e}:${t}`,r=!1,o={receive:e=>n(e),status:e=>{r=!0,s?.(e)}},l=p.get(a);if(!l){l={listeners:new Set,ready:Promise.resolve()},p.set(a,l);let n=l,i=e=>{if(p.get(a)===n){for(let t of[...n.listeners])if(n.listeners.has(t))try{e(t)}catch{console.error("[realtime] Consumer callback failed")}}};l.ready=g(e,t,e=>i(t=>t.receive(e)),e=>{n.status=e,i(t=>t.status(e))}).then(e=>{p.get(a)!==n?e():n.cleanup=e}).catch(e=>{throw p.get(a)===n&&p.delete(a),n.listeners.clear(),e})}let d=l;if(d.listeners.add(o),await d.ready,!r&&d.status&&p.get(a)===d)try{o.status(d.status)}catch{console.error("[realtime] Consumer callback failed")}let c=!1;return()=>{c||(c=!0,d.listeners.delete(o),0===d.listeners.size&&p.get(a)===d&&(p.delete(a),d.cleanup?.()))}}async function g(e,t,n,s){if(!(0,i.isSupabaseConfigured)()||!i.supabase)return()=>{};let a=i.supabase,l=`${e}:${t}`,d=!1,c=!1,_=null,p=null,m=0,g=null,h=null,f=()=>{h&&(clearTimeout(h),h=null)};function y(t){c||_!==t||g||(g=setTimeout(()=>{g=null,c||_!==t||(m+=1,o().then(()=>{if(!c&&_===t)try{v()}catch(n){_!==t&&(_=t,p="CLOSED"),console.error(`[${e}] Broadcast recovery error:`,n),y(t)}}))},Math.min(1e3*2**m,3e4)))}function v(){var t;let i=(t=a.channel(l,{config:{private:!0}}),t.on("broadcast",{event:"INSERT"},e=>{let t=e.payload?.record;t&&0!==Object.keys(t).length&&n({eventType:"INSERT",new:t,old:null})}).on("broadcast",{event:"UPDATE"},e=>{let t=e.payload?.record,i=e.payload?.old_record;t&&0!==Object.keys(t).length&&n({eventType:"UPDATE",new:t,old:i&&Object.keys(i).length>0?i:null})}).on("broadcast",{event:"DELETE"},e=>{let t=e.payload?.old_record;n({eventType:"DELETE",new:null,old:t&&Object.keys(t).length>0?t:null})}));return _=i,p=null,i.subscribe(t=>{c||_!==i||(p=t,"SUBSCRIBED"===t?(d&&(u(e,"reconnected"),d=!1),m>0&&(f(),h=setTimeout(()=>{h=null,c||_!==i||"SUBSCRIBED"!==p||(m=0)},3e4))):("TIMED_OUT"===t||"CLOSED"===t||"CHANNEL_ERROR"===t)&&(f(),d||(u(e,"disconnected"),d=!0)),"CLOSED"===t&&y(i),s?.(t))}),i}!r&&i.supabase&&(r=!0,i.supabase.auth.onAuthStateChange((e,t)=>{if("TOKEN_REFRESHED"===e||"SIGNED_IN"===e){let e=t?.access_token;e&&o(e)}})),await o();try{v()}catch(t){return console.error(`[${e}] Broadcast subscribe error:`,t),()=>{}}let b=()=>{"visible"===document.visibilityState&&!c&&_&&"joined"!==_.state&&o().then(()=>{!c&&_&&"CLOSED"===p&&y(_)})},w="u">typeof document;return w&&document.addEventListener("visibilitychange",b),()=>{!c&&(c=!0,g&&(clearTimeout(g),g=null),f(),w&&document.removeEventListener("visibilitychange",b),_&&"CLOSED"!==p&&a.removeChannel(_))}}class h{constructor(e){this.cleanups=new Map,this.destroyed=!1,this.channelKe
335y=e}async subscribe(e,t,n){if(!(0,i.isSupabaseConfigured)()||!i.supabase||this.destroyed)return;this.unsubscribe(e);let s=await m(e,this.channelKey,t,n);this.destroyed?s():this.cleanups.set(e,s)}unsubscribe(e){let t=this.cleanups.get(e);t&&(t(),this.cleanups.delete(e))}unsubscribeAll(){for(let[,e]of(this.destroyed=!0,this.cleanups))e();this.cleanups.clear()}get activeCount(){return this.cleanups.size}}},64024:(e,t,n)=>{n.d(t,{_H:()=>r});var i=n(1934),s=n(31692),a=n(38455);let r=(0,i.v)()((0,s.Zr)(e=>({viewingAsRegularUser:!1,enableViewAsRegularUser:()=>e({viewingAsRegularUser:!0}),disableViewAsRegularUser:()=>e({viewingAsRegularUser:!1}),toggleViewAsRegularUser:()=>e(e=>({viewingAsRegularUser:!e.viewingAsRegularUser}))}),{name:"vet-soap-view-as",version:1,migrate:()=>({viewingAsRegularUser:!1}),storage:a.jo,partialize:()=>({viewingAsRegularUser:!1})}));(0,a.Ui)(r)},65169:(e,t,n)=>{n.d(t,{BR:()=>_,OY:()=>d,WK:()=>c,pV:()=>u});var i=n(9846),s=n(16385),a=n(70805),r=n(8582),o=n(4389),l=n(5142);function d(e){let t={...e};return delete t.gmail_app_password,Array.isArray(t.saved_email_profiles)&&(t.saved_email_profiles=t.saved_email_profiles.map(e=>({id:e.id,name:e.name,gmail_address:e.gmail_address,has_password:"boolean"==typeof e.has_password?e.has_password:!!e.gmail_app_password}))),t}let c=e=>(0,r.Xh)(e,"settings-document");function _(e){let t=(0,l.getScopeFor)("user");t?.userId===e&&(0,o.getQueryClient)().cancelQueries({queryKey:c(t),exact:!0})}function u(e){let t=(0,l.getScopeFor)("user");return t&&t.userId===e?(0,o.getQueryClient)().fetchQuery((0,a.AP)(t,{domain:"settings-document",fetch:async({scope:e,signal:t})=>{if(!s.supabase)throw Error("Settings unavailable.");let{data:n,error:i}=await s.supabase.from("settings").select("*").order("updated_at",{ascending:!1}).limit(1).abortSignal(t).single();if(i&&"PGRST116"!==i.code)throw i;let a=n?d(n):null,r=(0,o.getQueryClient)().getQueryData(c(e)),l="string"==typeof a?.updated_at?Date.parse(a.updated_at):NaN,_="string"==typeof r?.updated_at?Date.parse(r.updated_at):NaN;return r&&a&&r.id===a.id&&_>l?r:a}})):Promise.reject(new i.cc)}},70805:(e,t,n)=>{n.d(t,{AP:()=>f,O6:()=>v,QX:()=>b,Vn:()=>y,lN:()=>h});var i=n(9846),s=n(30143),a=n(5858),r=n(87795),o=n(4389),l=n(8582),d=n(5142);let c=globalThis;function _(){return c.__vetSoapQueryReceipts??=new WeakMap,c.__vetSoapQueryReceipts}function u(e){e?.cancel({revert:!0})}async function p(e,t,n,s,a,r){let l=n.getQueryCache().find({queryKey:s,exact:!0});(0,d.isScopeCurrent)(t,e)||function(e,t){throw u(t),t&&void 0===t.state.data&&0===t.getObserversCount()&&e.getQueryCache().remove(t),new i.cc({revert:!0})}(n,l);let{owners:_}=function(){if(!c.__vetSoapQueryFetchFence){let e=new WeakMap,t=(0,d.onScopeTransition)(t=>{"changed"===t.type&&function(e){let t=(0,o.peekQueryClient)();if(t)for(let n of t.getQueryCache().getAll()){if("idle"===n.state.fetchStatus)continue;let t=e.get(n);t&&!(0,d.isScopeCurrent)(t.scope,t.kind)&&n.cancel({revert:!0})}}(e)});c.__vetSoapQueryFetchFence={owners:e,unbind:t}}return c.__vetSoapQueryFetchFence}(),p={scope:t,kind:e};l&&_.set(l,p);try{let n=await r();return a.aborted||(0,d.isScopeCurrent)(t,e)||u(l),n}finally{l&&_.get(l)===p&&_.delete(l)}}function m(e,t,n){let{domain:i,key:r=[],fetch:o,...d}=n,c=(0,l.Ip)(t,e,i,...r),_=(0,l.om)(t,e)?t:null;return(0,s.j)({...d,queryKey:c,queryFn:_?({signal:t,queryKey:n,client:i})=>p(e,_,i,n,t,()=>o({scope:_,signal:t,queryKey:n})):a.hT})}function g(e,t,n){let{domain:i,key:s=[],fetchPage:o,...d}=n,c=(0,l.Ip)(t,e,i,...s),_=(0,l.om)(t,e)?t:null;return(0,r.L)({...d,queryKey:c,queryFn:_?({signal:t,queryKey:n,client:i,pageParam:s})=>p(e,_,i,n,t,()=>o({scope:_,signal:t,queryKey:n,pageParam:s})):a.hT})}function h(e,t){return m("clinic",e,t)}function f(e,t){return m("user",e,t)}function y(e,t){return g("clinic",e,t)}function v(e,t){return g("user",e,t)}function b(e){let t=(0,o.getQueryClient)().getQueryCache().find({queryKey:e,exact:!0});return t?_().get(t):void 0}c.__vetSoapQueryReceiptListener||(c.__vetSoapQueryReceiptListener=!0,(0,o.subscribeQueryCache)(e=>{"updated"!==e.type||"success"!==e.action.type||e.action.manual||_().set(e.query,e.query.state.dataUpdatedAt)}))},76840:(e,t,n)=>{n.d(t,{M2:()=>_,U1:()=>p,yk:()=>u});var i=n(9846),s=n(16385),a=n(70805),r=n(4389),o=n(5142),l=n(49561),d=n(39700),c=n(29442);function _(e){return(0,a.AP)(e,{domain:"cases",key:["list"],refetchOnWindowFocus:!1,refetchOnReconnect:!1,fetch:async({signal:e,scope:t})=>{if(!(0,s.isSupabaseConfigured)()||!s.supabase)throw Error("Cases unavailable");let n=++l.in.latestFetchGen,a=[];for(let r=0;;r+=1e3){let{data:_,error:u}=await s.supabase.from("active_cases").select("*").order("recheck_due",{ascending:!0,nullsFirst:!1}).order("id",{ascending:!0}).abortSignal(e).range(r,r+1e3-1);if(e.aborted)throw new i.cc;if(u)throw u;let p=_??[];if(a.push(...p),p.length<1e3){let e=(0,d.jj)(a).visibleCases.filter(e=>!(0,l.t0)(e.id));return(0,o.isScopeCurrent)(t,"user")&&(0,l.MW)(n),(0,c.z6)(e)}}}})}async function u(e,t=!1){(0,c.CR)();let n=(0,r.getQueryClient)(),i=_(e);return t&&await n.cancelQueries({queryKey:i.queryKey,exact:!0}),n.fetchQuery(i)}async function p(e=!1){if(!(0,s.isSupabaseConfigured)())return;let t=(0,o.getScopeFor)("user");if(t&&(e||void 0===(0,a.QX)(_(t).queryKey)))try{await u(t,e)}catch(e){!(0,i.wm)(e)&&(0,o.isScopeCurrent)(t,"user")&&console.error("Failed to fetch cases:",e)}}}
335,83974:(e,t,n)=>{n.d(t,{j9:()=>_,lD:()=>m,lf:()=>h,uI:()=>u,yt:()=>p});var i=n(55342),s=n(15780);n(70805);var a=n(43265),r=n(4389),o=n(5142),l=n(58645);let d=[],c=new WeakSet;function _(e=(0,o.getScopeFor)("user")){return e?(0,r.getQueryClient)().getQueryData((0,l.ny)(e).queryKey)??d:d}function u(e=(0,o.getScopeFor)("user")){return!!e&&void 0!==(0,r.getQueryClient)().getQueryData((0,l.ny)(e).queryKey)}function p(e,t){let n=(0,l.ny)(e.scope).queryKey;e.isCurrent()&&((0,s.MX)(e,n),void 0===(0,r.getQueryClient)().getQueryData(n)?(0,s.GG)(e,n,t([])):(0,s.L4)(e,n,t))}function m(e){let t=(0,o.getScopeFor)("user");t&&p((0,s.Lt)(t,"user"),()=>e)}function g(e){return e.map(e=>({id:e.id,title:e.title,created_at:e.created_at,due_date:e.due_date,priority:e.priority,category:e.category,completed:e.completed,record_id:e.record_id,source:e.source,assigned_vet_id:e.assigned_vet_id}))}function h(){let e=(0,r.getQueryClient)();c.has(e)||(c.add(e),(0,a.JC)({id:"tasks.list",version:1,kind:"user",queryKey:e=>(0,l.ny)(e).queryKey,project:g,restore:e=>e}),(0,o.onScopeTransition)(e=>{"retired"===e.type&&((0,i.aW)(),i.j7.hasFetchedThisSession=!1)}))}},86985:(e,t,n)=>{n.r(t),n.d(t,{flushTelemetryOutbox:()=>b,getClientTelemetryContext:()=>h,reportClientEvent:()=>y,reportClientWorkflowOutcome:()=>w});let i="voxxo.telemetry-outbox.v1";function s(){try{return globalThis.localStorage??null}catch{return null}}function a(e){return"number"==typeof e&&Number.isFinite(e)}function r(e){return"object"!=typeof e||null===e?null:"string"==typeof e.body&&0!==e.body.length&&a(e.queuedAt)&&a(e.attempt)&&"string"==typeof e.sourceTime&&0!==e.sourceTime.length?{body:e.body,eventId:"string"==typeof e.eventId?e.eventId:null,sourceTime:e.sourceTime,queuedAt:e.queuedAt,attempt:e.attempt}:null}function o(){let e=s();if(!e)return[];try{let t=e.getItem(i);if(!t)return[];let n=JSON.parse(t);if(!Array.isArray(n))return[];return n.map(r).filter(e=>null!==e).slice(0,64)}catch{return[]}}function l(e){let t=s();if(t)try{t.setItem(i,JSON.stringify(e.slice(0,40)))}catch{}}function d(e){return o().filter(t=>e-t.queuedAt<864e5)}function c(e){try{let t=o().filter(t=>t.eventId!==e);l(t)}catch{}}var _=n(16385);let u=null,p=[];function m(){try{return globalThis.crypto?.randomUUID?.()??null}catch{return null}}function g(e){let t=p.indexOf(e);t>=0&&p.splice(t,1),p.push(e),p.length>20&&p.splice(0,p.length-20)}function h(){return{correlationId:u??=m(),recentEventIds:[...p]}}async function f(e){let t;try{let n=JSON.parse(e),i="workflow_outcome"===n.event&&!!n.properties.supabaseFailure,s=i?null:await (0,_.getFreshAccessToken)(),a=i?new AbortController:null;a&&(t=setTimeout(()=>a.abort(),5e3));let r=await fetch("/api/telemetry",{body:e,cache:"no-store",credentials:"same-origin",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},keepalive:!0,method:"POST",...a?{signal:a.signal}:{}});if(202===r.status)return{outcome:"delivered",stored:"1"===r.headers.get("X-Voxxo-Telemetry-Stored")};if(429===r.status||408===r.status||r.status>=500)return{outcome:"retry",stored:!1};return{outcome:"dropped",stored:!1}}catch{return{outcome:"retry",stored:!1}}finally{clearTimeout(t)}}async function y(e,t){try{let n=m(),i=u??=m(),s=t?.sourceTime??new Date().toISOString(),a=JSON.stringify({...e,...n?{eventId:n}:{},sourceTime:s,...i?{correlationId:i}:{}}),{outcome:r,stored:o}=await f(a);if("delivered"===r){n&&o&&g(n);return}"retry"===r&&function(e){try{let t=Date.now(),n=d(t),i=n.find(t=>t.eventId===e.eventId);if(i&&null!==e.eventId){i.attempt+=1,i.queuedAt=t,i.body=e.body,i.sourceTime=e.sourceTime,l(n);return}for(n.push({body:e.body,eventId:e.eventId,sourceTime:e.sourceTime,queuedAt:t,attempt:1});n.length>40;)n.shift();l(n)}catch{}}({body:a,eventId:n,sourceTime:s})}catch{}}let v=null;function b(){return v||(v=(async()=>{for(let e of function(){try{return d(Date.now())}catch{return[]}}()){if(!function(e){try{let t=JSON.parse(e.body);if("object"!=typeof t||null===t||"string"!=typeof t.event||"object"!=typeof t.properties)return null;return{event:t,eventId:"string"==typeof e.eventId?e.eventId:null,sourceTime:e.sourceTime}}catch{return null}}(e)){e.eventId&&c(e.eventId);continue}let{outcome:t,stored:n}=await f(e.body);"delivered"===t?e.eventId&&(c(e.eventId),n&&g(e.eventId)):"dropped"===t&&e.eventId&&c(e.eventId)}})().finally(()=>{v=null}))}try{b(),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&b()})}catch{}function w(e){y({event:"workflow_outcome",properties:e})}},92276:(e,t,n)=>{n.d(t,{b:()=>i});let i=[{name:"General Treatment Consent",form_type:"general",title:"Treatment Consent & Authorization",template_content:`## {{clinic_name}} 336 337{{clinic_address}} 338{{clinic_phone}} 339 340--- 341 342## Treatment Consent & Authorization 343 344Date: {{current_date}} 345Attending Veterinarian: {{vet_name}} 346 347### Patient Information 348 349Patient Name: {{patient_name}} 350Species: {{species}} 351Breed: {{breed}} 352Age: {{age}} 353Weight: {{weight}} 354 355### Owner / Authorized Agent 356 357Name: {{owner_name}} 358 359### Recommended Treatment 360 361{{procedure_name}} 362 363### Estimated Cost 364 365{{estimated_cost}} 366 367--- 368 369I, **{{owner_name}}**, hereby authorize **Dr. {{vet_name}}** and the veterinary staff of **{{clinic_name}}** to perform the recommended treatment(s) on my pet, **{{patient_name}}**. 370 371I understand that: 372 373- The nature and purpose of the recommended treatment has been explained to me 374- Potential risks, side effects, and complications have been discussed 375- Alternative treatment options, including the option of no treatment, have been presented 376- No guarantee of outcome has been made 377- I am financially responsible for all services rendered 378 379### Emergency Contact Authorization 380 381In case I cannot be reached during treatment, I authorize the veterinarian to: 382 383[ ] Perform any life-saving emergency procedures as deemed necessary 384[ ] Stabilize only and await my authorization for further treatment 385 386--- 387 388Owner / Authorized Agent Signature: _______________ 389Date: _______________`}
389,{name:"Surgical Consent",form_type:"surgery",title:"Surgical Consent & Authorization",template_content:`## {{clinic_name}} 390 391{{clinic_address}} 392{{clinic_phone}} 393 394--- 395 396## Surgical Consent & Authorization 397 398Date: {{current_date}} 399Attending Veterinarian: {{vet_name}} 400 401### Patient Information 402 403Patient Name: {{patient_name}} 404Species: {{species}} 405Breed: {{breed}} 406Age: {{age}} 407Weight: {{weight}} 408 409### Owner / Authorized Agent 410 411Name: {{owner_name}} 412 413### Planned Procedure(s) 414 415{{procedure_name}} 416 417### Estimated Cost 418 419{{estimated_cost}} 420 421--- 422 423I, **{{owner_name}}**, hereby authorize **Dr. {{vet_name}}** and the veterinary staff of **{{clinic_name}}** to perform the above procedure(s) on my pet, **{{patient_name}}**. 424 425### Anesthesia & Sedation 426 427I understand that all surgical and anesthetic procedures involve inherent risks, including but not limited to adverse drug reactions, bleeding, infection, pain, organ dysfunction, and in rare cases, death. I authorize the use of appropriate anesthesia, sedation, and pain management medications as deemed necessary by the attending veterinarian. 428 429### Pre-Anesthetic Bloodwork 430 431[ ] I authorize pre-anesthetic bloodwork (recommended) 432[ ] I decline pre-anesthetic bloodwork (against medical advice) 433 434### Additional Procedures 435 436If during the procedure an unforeseen condition is discovered that requires additional treatment: 437 438[ ] Contact me before proceeding with additional procedures 439[ ] Authorize the veterinarian to perform any additional procedures deemed medically necessary 440 441### Acknowledgments 442 443[ ] I understand the risks associated with anesthesia and surgery as explained by the veterinarian 444[ ] I understand that no guarantee of outcome has been made 445[ ] I agree to follow all post-operative care instructions 446[ ] I understand I am financially responsible for all services rendered 447[ ] I have provided accurate information about my pet's medical history, including current medications, allergies, and recent food/water intake 448 449--- 450 451Owner / Authorized Agent Signature: _______________ 452Date: _______________ 453 454Witness Signature: _______________ 455Date: _______________`},{name:"Anesthesia Consent",form_type:"anesthesia",title:"Anesthesia Consent & Authorization",template_content:`## {{clinic_name}} 456 457{{clinic_address}} 458{{clinic_phone}} 459 460--- 461 462## Anesthesia Consent & Authorization 463 464Date: {{current_date}} 465Attending Veterinarian: {{vet_name}} 466 467### Patient Information 468 469Patient Name: {{patient_name}} 470Species: {{species}} 471Breed: {{breed}} 472Age: {{age}} 473Weight: {{weight}} 474 475### Owner / Authorized Agent 476 477Name: {{owner_name}} 478 479### Reason for Anesthesia 480 481{{procedure_name}} 482 483--- 484 485I, **{{owner_name}}**, hereby authorize the use of general anesthesia and/or sedation on my pet, **{{patient_name}}**, for the purpose of the procedure(s) described above. 486 487### Risks of Anesthesia 488 489I understand that anesthesia involves inherent risks, including but not limited to: 490 491- Adverse reactions to anesthetic agents 492- Changes in heart rate, blood pressure, or breathing 493- Aspiration pneumonia 494- Organ dysfunction (liver, kidney, cardiac) 495- In rare cases, death 496 497These risks exist even in apparently healthy animals, and may be higher in animals that are elderly, very young, obese, brachycephalic (short-nosed breeds), or have pre-existing medical conditions. 498 499### Pre-Anesthetic Bloodwork 500 501[ ] I authorize pre-anesthetic bloodwork to screen for underlying conditions (recommended) 502[ ] I decline pre-anesthetic bloodwork (against medical advice) 503 504### IV Catheter & Fluids 505 506[ ] I authorize IV catheter placement and fluid therapy during anesthesia (recommended) 507[ ] I decline IV fluids (against medical advice) 508 509### Monitoring 510 511My pet will be monitored throughout the procedure using appropriate equipment including pulse oximetry, ECG, blood pressure, temperature, and capnography where available. A trained technician will be dedicated to anesthesia monitoring. 512 513### Acknowledgments 514 515[ ] I have disclosed all known medical conditions, medications, allergies, and recent food/water intake 516[ ] I understand the risks of anesthesia as explained to me 517[ ] I understand that no guarantee of outcome has been made 518[ ] I am financially responsible for all services rendered 519 520--- 521 522Owner / Authorized Agent Signature: _______________ 523Date: _______________ 524 525Witness Signature: _______________ 526Date: _______________`},{name:"Dental Procedure Consent",form_type:"dental",title:"Dental Procedure Consent & Authorization",template_content:`## {{clinic_name}} 527 528{{clinic_address}} 529{{clinic_phone}} 530 531--- 532 533## Dental Procedure Consent & Authorization 534 535Date: {{current_date}} 536Attending Veterinarian: {{vet_name}} 537 538### Patient Information 539 540Patient Name: {{patient_name}} 541Species: {{species}} 542Breed: {{breed}} 543Age: {{age}} 544Weight: {{weight}} 545 546### Owner / Authorized Agent 547 548Name: {{owner_name}} 549 550### Planned Dental Procedure(s) 551 552{{procedure_name}} 553 554### Estimated Cost 555 556{{estimated_cost}} 557 558--- 559 560I, **{{owner_name}}**, hereby authorize **Dr. {{vet_name}}** and the veterinary staff of **{{clinic_name}}** to perform a dental procedure on my pet, **{{patient_name}}**, under general anesthesia. 561 562### Scope of Dental Work 563 564I understand that the full extent of dental disease may not be apparent until my pet is under anesthesia and a thorough oral examination with dental radiographs
564is performed. Additional treatments discovered during the procedure may include: 565 566- Tooth extractions (simple or surgical) 567- Periodontal treatment 568- Oral mass biopsy or removal 569- Jaw fracture repair 570 571### Extraction Authorization 572 573If extractions are deemed medically necessary: 574 575[ ] Authorize the veterinarian to extract any teeth deemed medically necessary 576[ ] Contact me before performing any extractions 577[ ] Contact me only if more than ___ teeth need extraction 578 579### Anesthesia 580 581This procedure requires general anesthesia. I understand and accept the risks of anesthesia as described in the anesthesia consent section. Pre-anesthetic bloodwork is recommended. 582 583[ ] I authorize pre-anesthetic bloodwork (recommended) 584[ ] I decline pre-anesthetic bloodwork (against medical advice) 585 586### Acknowledgments 587 588[ ] I understand that dental radiographs are necessary for a complete dental assessment 589[ ] I understand that additional procedures may be needed based on findings under anesthesia 590[ ] I agree to follow all post-operative care instructions including soft food diet and oral medications 591[ ] I understand I am financially responsible for all services rendered 592 593--- 594 595Owner / Authorized Agent Signature: _______________ 596Date: _______________ 597 598Witness Signature: _______________ 599Date: _______________`},{name:"Euthanasia Authorization",form_type:"euthanasia",title:"Euthanasia Authorization & Consent",template_content:`## {{clinic_name}} 600 601{{clinic_address}} 602{{clinic_phone}} 603 604--- 605 606## Euthanasia Authorization & Consent 607 608Date: {{current_date}} 609Attending Veterinarian: {{vet_name}} 610 611### Patient Information 612 613Patient Name: {{patient_name}} 614Species: {{species}} 615Breed: {{breed}} 616Age: {{age}} 617Weight: {{weight}} 618 619### Owner / Authorized Agent 620 621Name: {{owner_name}} 622 623--- 624 625I, **{{owner_name}}**, hereby certify that I am the owner or duly authorized agent for the owner of the above-described animal. I hereby authorize **Dr. {{vet_name}}** and the staff of **{{clinic_name}}** to humanely euthanize my pet, **{{patient_name}}**. 626 627I understand that euthanasia will be performed by intravenous injection of an approved euthanasia solution, and that the procedure is irreversible. The veterinarian has explained the procedure, including sedation prior to the injection if appropriate, and I have had the opportunity to ask questions. 628 629### Rabies Disclosure 630 631I certify that **{{patient_name}}** has **not** bitten any person or animal within the past 15 days, and to my knowledge has not been exposed to rabies. 632 633[ ] Confirmed 634 635### Remains Disposition 636 637Please select one: 638 639[ ] Private cremation â ashes returned to owner 640[ ] Communal cremation â no ashes returned 641[ ] Owner will take remains home for private burial 642[ ] Other: _______________ 643 644### Acknowledgments 645 646[ ] I understand that this procedure is permanent and irreversible 647[ ] I have had the opportunity to spend time with my pet before the procedure 648[ ] I have discussed any questions or concerns with the veterinarian 649[ ] I understand I am financially responsible for all services rendered 650 651--- 652 653We at **{{clinic_name}}** understand that this is an incredibly difficult decision. Please know that our team is here to support you during this time, and we are committed to ensuring **{{patient_name}}**'s comfort and dignity throughout this process. 654 655--- 656 657Owner / Authorized Agent Signature: _______________ 658Date: _______________ 659 660Witness Signature: _______________ 661Date: _______________`},{name:"Do Not Resuscitate (DNR)",form_type:"dnr",title:"Do Not Resuscitate Order",template_content:`## {{clinic_name}} 662 663{{clinic_address}} 664{{clinic_phone}} 665 666--- 667 668## Do Not Resuscitate Order 669 670Date: {{current_date}} 671Attending Veterinarian: {{vet_name}} 672 673### Patient Information 674 675Patient Name: {{patient_name}} 676Species: {{species}} 677Breed: {{breed}} 678Age: {{age}} 679Weight: {{weight}} 680 681### Owner / Authorized Agent 682 683Name: {{owner_name}} 684 685--- 686 687I, **{{owner_name}}**, hereby request that in the event **{{patient_name}}** experiences cardiac or respiratory arrest while under the care of **{{clinic_name}}**, **no** cardiopulmonary resuscitation (CPR) or advanced life-saving measures be performed. 688 689I understand that: 690 691- This order means the veterinary team will **not** attempt chest compressions, artificial ventilation, emergency medications, or defibr
691illation in the event of cardiac or respiratory arrest 692- Comfort care and pain management will continue to be provided 693- This decision has been made after discussion with **Dr. {{vet_name}}** regarding my pet's current condition and prognosis 694- I may revoke this order at any time by notifying the veterinary staff verbally or in writing 695 696### Acknowledgments 697 698[ ] I have discussed my pet's condition and prognosis with the veterinarian 699[ ] I understand what CPR involves and its likelihood of success in my pet's case 700[ ] I make this decision voluntarily and with full understanding of the consequences 701[ ] I understand I may revoke this order at any time 702 703--- 704 705Owner / Authorized Agent Signature: _______________ 706Date: _______________ 707 708Witness Signature: _______________ 709Date: _______________`},{name:"Boarding Agreement",form_type:"boarding",title:"Boarding Agreement & Consent",template_content:`## {{clinic_name}} 710 711{{clinic_address}} 712{{clinic_phone}} 713 714--- 715 716## Boarding Agreement & Consent 717 718Date: {{current_date}} 719 720### Patient Information 721 722Patient Name: {{patient_name}} 723Species: {{species}} 724Breed: {{breed}} 725Age: {{age}} 726Weight: {{weight}} 727 728### Owner / Authorized Agent 729 730Name: {{owner_name}} 731 732### Boarding Details 733 734Check-In Date: {{admission_date}} 735Expected Pick-Up Date: _______________ 736 737Emergency Contact Name: _______________ 738Emergency Contact Phone: _______________ 739 740--- 741 742I, **{{owner_name}}**, hereby authorize **{{clinic_name}}** to board my pet, **{{patient_name}}**, for the period indicated above. 743 744### Medical Authorization 745 746In the event that my pet becomes ill or injured while boarding: 747 748[ ] Authorize emergency treatment up to $_____ without prior contact 749[ ] Contact me before any medical treatment is performed 750[ ] Authorize all necessary medical treatment regardless of cost 751 752### Feeding Instructions 753 754[ ] Feed clinic-provided food (standard diet) 755[ ] Owner-provided food (attached/described): _______________ 756 757Feeding Schedule: _______________ 758Allergies / Dietary Restrictions: _______________ 759 760### Medications 761 762[ ] No medications required 763[ ] Medications to be administered (details attached): _______________ 764 765### Vaccination Requirements 766 767I certify that **{{patient_name}}** is current on the following vaccinations: 768 769[ ] Rabies 770[ ] DHPP / FVRCP (Distemper combo) 771[ ] Bordetella (kennel cough) 772[ ] Canine Influenza (if required) 773 774### Acknowledgments 775 776[ ] I understand that boarding involves inherent risks including stress, exposure to illness, and minor injuries from normal activity 777[ ] I understand that {{clinic_name}} will take reasonable precautions to ensure my pet's safety and comfort 778[ ] I agree to pick up my pet by the expected date or notify the clinic of any changes 779[ ] I understand I am financially responsible for all boarding and any medical services rendered 780[ ] I have disclosed all known behavioral issues (aggression, anxiety, escape behavior) 781 782--- 783 784Owner / Authorized Agent Signature: _______________ 785Date: _______________ 786 787Clinic Staff Signature: _______________ 788Date: _______________`}]},94240:(e,t,n)=>{n.d(t,{j:()=>S});var i=n(1934),s=n(446),a=n(31692),r=n(38455),o=n(17052),l=n(16385);async function d(){if(!l.supabase)return null;let{data:{user:e}}=await l.supabase.auth.getUser();return e?.id??null}async function c(e){if(!l.supabase)return;let t=await d();t&&await l.supabase.from("records").update({viewed_at:new Date().toISOString()}).eq("id",e).eq("user_id",t)}async function _(e){if(!l.supabase)return;let t=await d();t&&await l.supabase.from("records").update({viewed_at:null}).eq("id",e).eq("user_id",t)}async function u(){if(!l.supabase)return[];let e=await d();if(!e)return[];let{data:t,error:n}=await l.supabase.from("records").select("id").eq("user_id",e).is("viewed_at",null).or("soap_note.neq.,discharge_instructions.neq.,discharge_instructions_translated.neq.");return n||!t?[]:t.map(e=>e.id)}async function p(){if(!l.supabase)return;let e=await d();e&&await l.supabase.from("records").update({viewed_at:new Date().toISOString()}).eq("user_id",e).is("viewed_at",null).or("soap_note.neq.,discharge_instructions.neq.,discharge_instructions_translated.neq.")}var m=n(97286),g=n(86985);async function h(e){try{let t=e.replace(/\s+/g," ").trim().toLowerCase().replace(/\d+/g,"N");if(!t)return null;
788let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`voxxo.error-toast.v1:${t}`)),i=(function(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t})(new Uint8Array(n)).slice(0,16).toUpperCase();return`VXT-${i}`}catch{return null}}let f={practice:["module","view","patientId","recordId","invoiceId","tab","clientId","section"],tutorials:["chapter","autostart"]},y=new Map,v="light",b="purple",w="list",S=(0,i.v)()((0,a.Zr)((e,t)=>({isSidebarOpen:!1,isSettingsOpen:!1,settingsTab:null,settingsSubtab:null,isChatOpen:!1,isVetCalcOpen:!1,isTimerOpen:!1,isQuickLinksOpen:!1,isReferralDirectoryOpen:!1,isDrugLibraryOpen:!1,isActiveCasesOpen:!1,isCalendarOpen:!1,isPlanMyWeekOpen:!1,planMyWeekInitialDraft:null,isWelcomeOpen:!1,isFeedbackOpen:!1,recordModeRequestNonce:0,uiHighlight:null,theme:v,showHelpButtons:!0,showInputHelpText:!0,showRecordingSyncDebug:!1,accentColor:b,customAccentHex:null,recorderLayout:w,workspaceLayout:{...s.XI},toasts:[],unviewedRecordIds:new Set,activeAppView:"main",artifactsReturnView:null,isChatInputVisible:!1,setActiveAppView:n=>{let i=t();!function(e,t,n){if("/"!==window.location.pathname)return;let i="artifacts"===e?n:e;if(!i||i===t||"artifacts"===t)return;let s=f[i];if(!s)return;let a=new URL(window.location.href);if(s.some(e=>a.searchParams.has(e))){for(let e of s)a.searchParams.delete(e);window.history.replaceState(window.history.state,"",`${a.pathname}${a.search}${a.hash}`)}}(i.activeAppView,n,i.artifactsReturnView),e({activeAppView:n})},openArtifactsView:()=>e(e=>({artifactsReturnView:"artifacts"===e.activeAppView?e.artifactsReturnView:e.activeAppView,activeAppView:"artifacts"})),closeArtifactsView:()=>e(e=>({activeAppView:e.artifactsReturnView??"main",artifactsReturnView:null})),setChatInputVisible:t=>e({isChatInputVisible:t}),toggleSidebar:()=>e(e=>({isSidebarOpen:!e.isSidebarOpen})),setSidebarOpen:t=>e({isSidebarOpen:t}),toggleSettings:()=>e(e=>({isSettingsOpen:!e.isSettingsOpen})),setSettingsOpen:t=>e({isSettingsOpen:t,settingsTab:null,settingsSubtab:null}),openSettingsTab:(t,n)=>{e({isSettingsOpen:!0,settingsTab:t,settingsSubtab:n??null})},toggleChat:()=>e(e=>({isChatOpen:!e.isChatOpen})),setChatOpen:t=>e({isChatOpen:t}),toggleVetCalc:()=>e(e=>({isVetCalcOpen:!e.isVetCalcOpen})),setVetCalcOpen:t=>e({isVetCalcOpen:t}),toggleTimer:()=>e(e=>({isTimerOpen:!e.isTimerOpen})),setTimerOpen:t=>e({isTimerOpen:t}),setQuickLinksOpen:t=>e({isQuickLinksOpen:t}),setReferralDirectoryOpen:t=>e({isReferralDirectoryOpen:t}),setDrugLibraryOpen:t=>e({isDrugLibraryOpen:t}),setActiveCasesOpen:t=>e({isActiveCasesOpen:t}),setCalendarOpen:t=>e({isCalendarOpen:t}),setPlanMyWeekOpen:t=>e(e=>({isPlanMyWeekOpen:t,planMyWeekInitialDraft:t?e.planMyWeekInitialDraft:null})),openPlanMyWeek:(t=null)=>e({isPlanMyWeekOpen:!0,planMyWeekInitialDraft:t}),setWelcomeOpen:t=>e({isWelcomeOpen:t}),setFeedbackOpen:t=>e({isFeedbackOpen:t}),requestRecordMode:()=>e(e=>({recordModeRequestNonce:e.recordModeRequestNonce+1})),requestUiHighlight:t=>e(e=>({uiHighlight:{...Array.isArray(t)?{testIds:t}:t,nonce:(e.uiHighlight?.nonce??0)+1}})),setTheme:t=>e({theme:t}),toggleTheme:()=>e(e=>({theme:"dark"===e.theme?"light":"dark"})),setShowHelpButtons:t=>e({showHelpButtons:t}),setShowInputHelpText:t=>e({showInputHelpText:t}),setShowRecordingSyncDebug:t=>e({showRecordingSyncDebug:t}),setAccentColor:t=>e({accentColor:t}),setCustomAccentHex:t=>e({customAccentHex:t}),setRecorderLayout:t=>e({recorderLayout:t}),updateWorkspaceLayout:t=>e(e=>({workspaceLayout:(0,s.b0)({...e.workspaceLayout,...t})})),resetWorkspaceLayout:()=>e({workspaceLayout:{...s.XI}}),addToast:(n,i,s)=>{if("string"!=typeof i){let e=i;if(e instanceof Error&&"string"==typeof e.message)i=e.message;else if(e&&"object"==typeof e){let t=e.message;if("string"==typeof t&&t)i=t;else try{i=JSON.stringify(e)}catch{i=String(e)}}else i=String(e??"")}if("error"===n&&"u">typeof navigator&&!navigator.onLine&&["Failed to fetch","NetworkError","Network request failed","net::ERR","Load failed"].some(e=>i.toLowerCase().includes(e.toLowerCase())))return;"error"===n&&function(e,t){try{(async()=>{let n=await h(e);n&&await (0,g.reportClientEvent)({event:"error_toast_shown",properties:{fingerprint:n,offline:t}})})()}catch{}}(i,"u">typeof navigator&&!navigator.onLine);let a=s?.scope,r=t().toasts.find(e=>e.type===n&&e.message===i&&e.scope===a),o=r?.id??crypto.randomUUID();r?e(e=>({toasts:[...e.toasts.filter(e=>e.id!==o),r]})):e(e=>({toasts:[...e.toasts,{id:o,type:n,message:i,scope:a}]}));let l=y.get(o);l&&clearTimeout(l);let d=setTimeout(()=>{e(e=>({toasts:e.toasts.filter(e=>e.id!==o)})),y.delete(o)},5e3);y.set(o,d)},removeToast:t=>{let n=y.get(t);n&&(clearTimeout(n),y.delete(t)),e(e=>({toasts:e.toasts.filter(e=>e.id!==t)}))},setUnviewedRecordIds:t=>e({unviewedRecordIds:t}),markRecordViewed:async t=>{e(e=>{let n=new Set(e.unviewedRecordIds);return n.delete(t),{unviewedRecordIds:n}});let n=new Date().toISOString();m.useSettingsStore.getState().updateSettingsImmediate({records_last_seen_at:n}),c(t)},markRecordUnviewed:async t=>{e(e=>{let n=new Set(e.unviewedRecordIds);return n.add(t),{unviewedRecordIds:n}}),_(t)}
788,markAllRecordsViewed:async()=>{e({unviewedRecordIds:new Set});let t=new Date().toISOString();m.useSettingsStore.getState().updateSettingsImmediate({records_last_seen_at:t}),p()},refreshUnviewedRecords:async()=>{e({unviewedRecordIds:new Set(await u())})},resetForSessionClear:n=>{y.forEach(e=>clearTimeout(e)),y.clear();let i="session_expired"===n,a=i?t().activeAppView:"main",r=i&&"artifacts"===a?t().artifactsReturnView:null;e({isSidebarOpen:!1,isSettingsOpen:!1,settingsTab:null,settingsSubtab:null,isChatOpen:!1,isVetCalcOpen:!1,isTimerOpen:!1,isQuickLinksOpen:!1,isReferralDirectoryOpen:!1,isDrugLibraryOpen:!1,isActiveCasesOpen:!1,isCalendarOpen:!1,isPlanMyWeekOpen:!1,planMyWeekInitialDraft:null,isWelcomeOpen:!1,isFeedbackOpen:!1,recordModeRequestNonce:0,uiHighlight:null,theme:v,showHelpButtons:!0,showInputHelpText:!0,showRecordingSyncDebug:!1,accentColor:b,customAccentHex:null,recorderLayout:w,workspaceLayout:{...s.XI},toasts:[],unviewedRecordIds:new Set,activeAppView:a,artifactsReturnView:r,isChatInputVisible:!1})}}),{name:"vet-soap-ui",storage:r.jo,merge:(e,t)=>({...t,...e,workspaceLayout:(0,s.b0)(e?.workspaceLayout)}),partialize:e=>({theme:e.theme,showHelpButtons:e.showHelpButtons,showInputHelpText:e.showInputHelpText,showRecordingSyncDebug:e.showRecordingSyncDebug,accentColor:e.accentColor,customAccentHex:e.customAccentHex,recorderLayout:e.recorderLayout,workspaceLayout:e.workspaceLayout,activeAppView:e.activeAppView})}));(0,r.Ui)(S),(0,o.G)(e=>{"session_cleared"===e.type&&S.getState().resetForSessionClear(e.reason)})},95037:(e,t,n)=>{n.d(t,{J:()=>x,useCurrentVetStore:()=>O});var i=n(16385),s=n(99605),a=n(70805),r=n(8582),o=n(4389),l=n(5142);function d(...e){return{...s.bc,...e.reduce((e,t)=>({...e,...function(e){if(!e)return{};let t={};for(let n of s.u_){let i=e[n];null!=i&&(t[n]=i)}let n=e.selected_system_prompt_template_id;return"string"==typeof n&&void 0===t.selected_system_prompt_id&&(t.selected_system_prompt_id=n),t}(t)}),{})}}async function c(e,t,n,s){if(!i.supabase)return{kind:"staff"};let{data:{user:a},error:r}=await i.supabase.auth.getUser();if(r||!a||a.id!==n.userId||s.aborted||!(0,l.isScopeCurrent)(n,"user"))return null;let{data:o,error:d}=await i.supabase.from("clinic_memberships").select("user_id").eq("linked_staff_id",e).eq("status","active").abortSignal(s).maybeSingle();if(d)return null;let c=o?.user_id;if(c)return c===a.id?{kind:"settings",userId:a.id}:{kind:"staff"};if(t.user_id!==a.id)return{kind:"staff"};let{data:_,error:u}=await i.supabase.from("hospital_staff").select("id").eq("clinic_id",t.clinic_id).eq("user_id",t.user_id).eq("role","veterinarian").eq("is_active",!0).is("deleted_at",null).abortSignal(s);return u?null:1===(_??[]).length?{kind:"settings",userId:a.id}:{kind:"staff"}}async function _(e,t,n){if(!i.supabase)return null;try{let{data:a,error:r}=await i.supabase.from("hospital_staff").select("id, clinic_id, user_id, preferences").eq("id",e).abortSignal(n).single();if(r||!a)return console.error("Failed to load vet preferences:",r??`no staff profile ${e}`),null;let o=await c(e,a,t,n);if(!o)return console.error("Failed to resolve where vet preferences are stored:",e),null;if("staff"===o.kind)return{preferences:d(a.preferences),source:o};let{data:l,error:_}=await i.supabase.from("settings").select(s.u_.join(", ")).eq("user_id",o.userId).abortSignal(n).maybeSingle();if(_)return console.error("Failed to load member vet preferences:",_),null;return{preferences:d(a.preferences,l),source:o}}catch(e){return console.error("Error loading vet preferences:",e),null}}let u=(e,t)=>(0,r.Xh)(e,"vet-preferences",t);async function p(e){let t=(0,l.getScopeFor)("user");if(!t)return null;let n=(0,o.getQueryClient)();n.cancelQueries({queryKey:u(t,e),exact:!0});try{return await n.fetchQuery((0,a.AP)(t,{domain:"vet-preferences",key:[e],gcTime:3e5,fetch:async({scope:t,signal:n})=>{let i=await _(e,t,n);if(!i)throw Error("Vet preferences unavailable.");return i}}))}catch{return null}}var m=n(15780),g=n(57858);let h=new Map;var f=n(1934),y=n(31692),v=n(38455),b=n(17052);let w=null;function S(e){return e&&"all"!==e?e:null}let I=null,C=0,k=0,T=null;function A(e){let t=I;return t&&t.vetId===e?null!==t.settledAt&&Date.now()-t.settledAt>=5e3?(I=null,null):t.values:null}function E(){k+=1,T=null,I=null}function D(e){T?.vetId!==e&&O.getState().loadVetPreferences(e)}let O=(0,f.v)()((0,y.Zr)((e,t)=>({currentVetId:null,currentVetName:null,currentStaffId:null,currentStaffName:null,currentVetPreferences:{...s.bc},currentVetPreferenceSource:null,isLoadingPreferences:!1,linkedVetId:null,linkedVetName:null,isVetIdentityLocked:!1,setCurrentStaff:(t,n)=>{e({currentStaffId:t,currentStaffName:n})},clearCurrentStaff:()=>{e({currentStaffId:null,currentStaffName:null})},setCurrentVet:(n,i)=>{let{currentVetId:a,linkedVetId:r,linkedVetName:o,saveVetPreferencesToServer:l,loadVetPreferences:d}=t(),c=S(n),_=r??c,u=r?o:_?i:null;if(_&&_===a){e({currentVetName:u}),D(_);return}a&&a!==_&&(w&&(clearTimeout(w),w=null),l()),E(),e({currentVetId:_,currentVetName:u,currentVetPreferences:{...s.bc},currentVetPreferenceSource:null,isLoadingPreferences:!1}),_&&d(_)},setLinkedVeterinarian:(n,i)=>{let s=S(n);e({linkedVetId:s,linkedVetName:s?i:null,isVetIdentityLocked:!!s}),s&&t().setCurrentVet(s,i)},loadVetPreferences:async n=>{if(!(0,i.isSupabaseConfigured)()||!i.supabase)return;let s=++k,a=p(n);T={vetId:n,promise:a},e({isLoadingPreferences:!0});try{if(!await a||s!==k||t().currentVetId!==n)return;R()}finally{s===k&&(T=null,e({isLoadingPreferences:!1}))}},updateVetPreferences:n=>{let{currentVetId:i,currentVetPreferences:s}=t();i&&(I={vetId:i,values:{...A(i),...n},version:++C,settledAt:null}),e({currentVetPreferences:{...s,...n}}),w&&clearTimeout(w),w=setTimeout(()=>{w=null,t().saveVetPreferencesToServer()},500)},setCurrentVetPreferencesFromRemote:e=>{let{currentVetId:n,currentVetPreferenceSource:i}=t();if(!n)return;if(i?.kind!=="staff")return void D(n);let a=e.selected_system_prompt_template_id,r=(0,m.xd)("user");if(!r)return;let o={source:i,preferences:{...s.bc,...e,selected_system_prompt_id:e.selected_system_prompt_id??a}},l=u(r.scope,n);(0,m.MX)(r,l),(0,m.L4)(r,l,()=>o)||(0,m.GG)(r,l,o)},saveVetPreferencesToServer:async()=>{let{currentVetId:e,currentVetPreferences:n,currentVetPreferenceSource:a}=t();if(!(0,i.isSupabaseConfigured)()||!i.supabase||!e)return;let r=(0,m.xd)("user");if(!r)return;let o=I?.vetId===e?I:null,l=o?.version??null,d={...o?.values},c=a,_=n,f=null;if(!c){if(!o)return;f=T?.vetId===e?T.promise:p(e)}try{let t;if(f){let e=await f;if(!e||!r.isCurrent())return void console.error("Skipped saving vet preferences: the profile could not be loaded");c=e.source,_={...e.preferences,...d}}if(!c||!r.isCurrent())return;await function(e,t,n){if("user"!==e.kind||!e.isCurrent())return Promise.resolve(null);let a="settings"===n.source.kind?`settings:${n.source.userId}`:`staff:${t}`,r=h.get(a),o=(async()=>
788{if(r&&await r.catch(()=>null),!e.isCurrent()||!i.supabase)return null;let{data:{user:a},error:o}=await i.supabase.auth.getUser();if(!e.isCurrent()||a?.id!==e.scope.userId)return null;if(o)throw o;let l=n;if("settings"===n.source.kind){if(n.source.userId!==e.scope.userId)return null;let t={updated_at:new Date().toISOString()};for(let e of s.u_)void 0!==n.preferences[e]&&(t[e]=n.preferences[e]);if(!await (0,g.g)(e,null,t))return null}else{let{data:s,error:a}=await i.supabase.from("hospital_staff").update({preferences:n.preferences}).eq("id",t).select("preferences").maybeSingle();if(!e.isCurrent())return null;if(a)throw a;if(!s)return null;l={...n,preferences:s.preferences??n.preferences}}if(!e.isCurrent())return null;let d=u(e.scope,t);return(0,m.MX)(e,d),(0,m.L4)(e,d,()=>l)||(0,m.GG)(e,d,l),l})();return h.set(a,o),o.finally(()=>{h.get(a)===o&&h.delete(a)}).catch(()=>void 0),o}(r,e,{source:c,preferences:_})&&r.isCurrent()&&(t=I,null!==l&&t&&t.vetId===e&&t.version===l&&(t.settledAt=Date.now()))}catch(e){console.error("Error saving vet preferences:",e)}},clearCurrentVet:()=>{w&&(clearTimeout(w),w=null);let{linkedVetId:n,linkedVetName:i}=t();E(),e({currentVetId:n,currentVetName:n?i:null,currentVetPreferences:{...s.bc},currentVetPreferenceSource:null,isLoadingPreferences:!1}),n&&t().loadVetPreferences(n)}}),{name:"vet-soap-current-vet",storage:v.jo,partialize:e=>({currentVetId:e.currentVetId,currentVetName:e.currentVetName,currentStaffId:e.currentStaffId,currentStaffName:e.currentStaffName})}));function R(){var e,t;let n,i=(0,l.getScopeFor)("user"),s=O.getState();if(!i||!s.currentVetId)return;let a=(0,o.getQueryClient)().getQueryData(u(i,s.currentVetId));if(!a)return;let r=(e=s.currentVetId,t=a.preferences,(n=A(e))?{...t,...n}:t);s.currentVetPreferenceSource===a.source&&Object.keys(r).every(e=>r[e]===s.currentVetPreferences[e])||O.setState({currentVetPreferences:r,currentVetPreferenceSource:a.source})}function x(){let e=S(O.getState().currentVetId);if(e)return e;if("u"<typeof localStorage)return null;let t=(0,v.om)();for(let e of t?[`vet-soap-current-vet:${t}`,"vet-soap-current-vet"]:["vet-soap-current-vet"])try{let t=localStorage.getItem(e);if(!t)continue;let n=JSON.parse(t),i=S(n?.state?.currentVetId);if(i)return i}catch{}return null}(0,o.subscribeQueryCache)(e=>{"vet-preferences"===e.query.queryKey[2]&&R()}),(0,v.Ui)(O),(0,b.G)(e=>{"session_cleared"===e.type&&(O.setState({linkedVetId:null,linkedVetName:null,isVetIdentityLocked:!1}),O.getState().clearCurrentVet(),O.getState().clearCurrentStaff())});{let{currentVetId:e,loadVetPreferences:t,clearCurrentVet:n}=O.getState(),i=S(e);e!==i?n():i&&t(i)}},97286:(e,t,n)=>{let i,s;n.d(t,{useSettingsStore:()=>eY});var a=n(1934),r=n(86938),o=n(16385),l=n(17052),d=n(30969);let c=e=>{if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t};function _(){return crypto.randomUUID()}var u=n(48884),p=n(15780),m=n(57858),g=n(50649),h=n(99605),f=n(95037),y=n(98906);async function v(e,t="[settings]"){if(e&&0!==e.length)try{let{addDrug:t,deleteDrug:i,readDrugsList:s,userDrugs:a}=await Promise.all([n.e(68902),n.e(91901)]).then(n.bind(n,68902)),r=a(s().drugs);for(let t of r)e.some(e=>e.id===t.id)||await i(t.id);for(let n of e)r.some(e=>e.id===n.id)||await t({name:n.name,category:n.category,concentration:n.concentration,concentration_unit:n.concentration_unit,dose_per_kg:n.dose_per_kg,dose_unit:n.dose_unit,notes:n.notes,species_notes:n.species_notes,is_cri:n.is_cri,dose_ranges:n.dose_ranges})}catch(e){console.error(`${t} Failed to restore custom drugs:`,e)}}async function b(e,t="[settings]"){if(e&&0!==e.length)try{let{useHospitalBoardStore:i}=await Promise.all([n.e(57093),n.e(26339),n.e(44788),n.e(36360)]).then(n.bind(n,78584)),s=i.getState(),a=s.staff,r=[];for(let t of e)a.find(e=>e.id===t.id)?await s.updateStaff(t.id,{name:t.name,role:t.role,color:t.color,initials:t.initials,is_active:t.is_active,preferences:t.preferences}):"veterinarian"===t.role?r.push(t.name??t.id):await s.addStaff({name:t.name,role:t.role,color:t.color,initials:t.initials,is_active:t.is_active,preferences:t.preferences});r.length>0&&console.warn(`${t} Skipped ${r.length} veterinarian profile(s) that no longer exist in this clinic;
788 invite them from Members instead of restoring: ${r.join(", ")}`)}catch(e){console.error(`${t} Failed to restore staff profiles:`,e)}}function w(e){if("string"==typeof e.history_template)return{...e,preamble:e.preamble??d.nq.preamble,history_template:e.history_template,exam_template:e.exam_template??d.nq.exam_template,assessment_template:e.assessment_template??d.nq.assessment_template,plan_template:e.plan_template??d.nq.plan_template,discharge_content:e.discharge_content??d.nq.discharge_content};if(!e.soap_content)return{...e,preamble:d.nq.preamble,history_template:d.nq.history_template,exam_template:d.nq.exam_template,assessment_template:d.nq.assessment_template,plan_template:d.nq.plan_template,discharge_content:e.discharge_content??d.nq.discharge_content};let t=(0,g.$u)(e.soap_content),n=t.unparsed?.trim()||d.nq.preamble;return{id:e.id,name:e.name,preamble:n,history_template:t.history??d.nq.history_template,exam_template:t.exam??d.nq.exam_template,assessment_template:t.assessment??d.nq.assessment_template,plan_template:t.plan??d.nq.plan_template,discharge_content:e.discharge_content??d.nq.discharge_content,...Array.isArray(e.sections)?{sections:e.sections}:{},soap_content:e.soap_content}}async function S(e){let t=e.get().settings,{currentVetId:n,currentVetPreferences:i,updateVetPreferences:s,saveVetPreferencesToServer:a}=f.useCurrentVetStore.getState();if(n){let e={saved_at:new Date().toISOString(),patient_template_forks:(0,y.Wp)(t.patient_template_sets,n,"patient",y.Sx),communication_template_forks:(0,y.Wp)(t.communication_templates,n,"communication",y.p6),general_template_forks:(0,y.Wp)(t.general_templates,n,"general",y.rT),consent_templates:t.consent_templates??[],ai_memory_soap:i.ai_memory_soap??h.bc.ai_memory_soap??"",ai_memory_discharge:i.ai_memory_discharge??h.bc.ai_memory_discharge??"",ai_memory_communication:i.ai_memory_communication??h.bc.ai_memory_communication??"",ai_memory_general:i.ai_memory_general??h.bc.ai_memory_general??"",style_preferences:i.style_preferences??h.bc.style_preferences??"",style_preferences_general:i.style_preferences_general??h.bc.style_preferences_general??"",selected_patient_template_set_id:i.selected_patient_template_set_id??h.bc.selected_patient_template_set_id??"",selected_recording_patient_template_set_id:i.selected_recording_patient_template_set_id??h.bc.selected_recording_patient_template_set_id??"",selected_communication_template_id:i.selected_communication_template_id??h.bc.selected_communication_template_id??"",selected_general_template_id:i.selected_general_template_id??h.bc.selected_general_template_id??"",selected_system_prompt_id:i.selected_system_prompt_id??h.bc.selected_system_prompt_id??"",selected_consent_template_id:t.selected_consent_template_id??"default-consent-general"};s({saved_settings_snapshot:{saved_at:e.saved_at,snapshot:e}}),await a()}await e.get().saveGlobalSettingsSnapshot()}async function I(e){if(!(0,o.isSupabaseConfigured)()||!o.supabase)return;let t=(0,p.xd)("user");if(!t)return;let i=e.get().settingsId;if(!i)return;let s=e.get().settings,{currentVetPreferences:a}=f.useCurrentVetStore.getState(),r={saved_at:new Date().toISOString(),hospital_name:s.hospital_name,hospital_address:s.hospital_address,hospital_phone:s.hospital_phone,saved_clinic_profiles:s.saved_clinic_profiles,active_clinic_profile_id:s.active_clinic_profile_id,vet_name:s.vet_name,gmail_address:s.gmail_address,patient_template_sets:s.patient_template_sets,communication_templates:s.communication_templates,general_templates:s.general_templates,system_prompt_templates:s.system_prompt_templates,consent_templates:s.consent_templates??[],chat_persona_templates:s.chat_persona_templates,style_preferences:s.style_preferences,style_preferences_general:s.style_preferences_general,ai_memory_patient:s.ai_memory_patient,ai_memory_soap:a.ai_memory_soap??"",ai_memory_discharge:a.ai_memory_discharge??"",ai_memory_communication:a.ai_memory_communication??"",ai_memory_general:a.ai_memory_general??"",selected_patient_template_set_id:a.selected_patient_template_set_id??h.bc.selected_patient_template_set_id,selected_recording_patient_template_set_id:a.selected_recording_patient_template_set_id??h.bc.selected_recording_patient_template_set_id,selected_communication_template_id:a.selected_communication_template_id??h.bc.selected_communication_template_id,selected_general_template_id:a.selected_general_template_id??h.bc.selected_general_template_id,selected_system_prompt_id:a.selected_system_prompt_id??h.bc.selected_system_prompt_id,selected_chat_persona_id:s.selected_chat_persona_id,accent_color:s.accent_color,referral_directory:s.referral_directory,custom_links:s.custom_links,hidden_default_link_ids:s.hidden_default_link_ids??[],chat_thinking_mode:s.chat_thinking_mode??!0,chat_show_response_mode_toggle:s.chat_show_response_mode_toggle??!1,generation_thinking_mode:s.generation_thinking_mode??!1,default_input_mode:s.default_input_mode??"voice",chat_tts_voice:s.chat_tts_voice??"b089032e45db460fb1934ece75a8c51d",chat_tts_speed:s.chat_tts_speed??1.2,recording_show_context_button:s.recording_show_context_button??!0,recording_show_patient_picker:s.recording_show_patient_picker??!0,recording_show_media_tools:s.recording_show_media_tools??!0,recording_show_typed_notes:s.recording_show_typed_notes??!0,recording_show_hospital_link:s.recording_show_hospital_link??!0,recording_show_system_prompt:s.recording_show_system_prompt??!0,interpretation_enabled:s.interpretation_enabled??!0,toolbar_show_referrals:s.toolbar_show_referrals??!0,toolbar_show_quick_links:s.toolbar_show_quick_links??!0,custom_drugs:await (async()=>{let{readDrugsList:e,userDrugs:t}=await Promise.all([n.e(68902),n.e(91901)]).then(n.bind(n,68902));return t(e().drugs)})(),staff_profiles:await (async()=>{let{useHospitalBoardStore:e}=await Promise.all([n.e(57093),n.e(26339),n.e(44788),n.e(36360)]).then(n.bind(n,78584)),t=f.useCurrentVetStore.getState().currentVetId;return e.getState().staff.map(e=>
788({id:e.id,name:e.name,role:e.role,color:e.color,initials:e.initials,is_active:e.is_active,preferences:e.id===t?{...e.preferences,...a}:e.preferences}))})()};!t.isCurrent()||await (0,m.g)(t,i,{saved_settings_snapshot:r,updated_at:new Date().toISOString()})&&t.isCurrent()&&e.set(e=>({settings:{...e.settings,saved_settings_snapshot:r}}))}async function C(e){let{currentVetId:t,currentVetPreferences:n,updateVetPreferences:i,saveVetPreferencesToServer:s}=f.useCurrentVetStore.getState(),a=!1;if(t){var r;let o=(r=n.saved_settings_snapshot?.snapshot)&&"object"==typeof r?{saved_at:"string"==typeof r.saved_at?r.saved_at:new Date().toISOString(),patient_template_forks:Array.isArray(r.patient_template_forks)?r.patient_template_forks.filter(e=>!!(e&&"string"==typeof e.id)).map(w):[],communication_template_forks:Array.isArray(r.communication_template_forks)?r.communication_template_forks.filter(e=>!!(e&&"string"==typeof e.id)):[],general_template_forks:Array.isArray(r.general_template_forks)?r.general_template_forks.filter(e=>!!(e&&"string"==typeof e.id)):[],consent_templates:Array.isArray(r.consent_templates)?r.consent_templates.filter(e=>!!(e&&"string"==typeof e.id)):[],ai_memory_soap:r.ai_memory_soap??h.bc.ai_memory_soap??"",ai_memory_discharge:r.ai_memory_discharge??h.bc.ai_memory_discharge??"",ai_memory_communication:r.ai_memory_communication??h.bc.ai_memory_communication??"",ai_memory_general:r.ai_memory_general??h.bc.ai_memory_general??"",style_preferences:r.style_preferences??h.bc.style_preferences??"",style_preferences_general:r.style_preferences_general??h.bc.style_preferences_general??"",selected_patient_template_set_id:r.selected_patient_template_set_id??h.bc.selected_patient_template_set_id??"",selected_recording_patient_template_set_id:r.selected_recording_patient_template_set_id??h.bc.selected_recording_patient_template_set_id??"",selected_communication_template_id:r.selected_communication_template_id??h.bc.selected_communication_template_id??"",selected_general_template_id:r.selected_general_template_id??h.bc.selected_general_template_id??"",selected_system_prompt_id:r.selected_system_prompt_id??h.bc.selected_system_prompt_id??"",selected_consent_template_id:r.selected_consent_template_id??"default-consent-general"}:null;if(o){a=!0,e.setSettingsDirty(!0),e.setRecentlySavedUntil(Date.now()+5e3);let n=(0,y.Wp)(o.patient_template_forks,t,"patient",y.Sx),r=(0,y.Wp)(o.communication_template_forks,t,"communication",y.p6),l=(0,y.Wp)(o.general_template_forks,t,"general",y.rT);e.set(e=>({settings:{...e.settings,patient_template_sets:[...(0,y.uK)(e.settings.patient_template_sets,t,"patient",y.Sx),...n],communication_templates:[...(0,y.uK)(e.settings.communication_templates,t,"communication",y.p6),...r],general_templates:[...(0,y.uK)(e.settings.general_templates,t,"general",y.rT),...l],consent_templates:o.consent_templates?.length?o.consent_templates:e.settings.consent_templates,selected_consent_template_id:o.selected_consent_template_id}})),i({ai_memory_soap:o.ai_memory_soap,ai_memory_discharge:o.ai_memory_discharge,ai_memory_communication:o.ai_memory_communication,ai_memory_general:o.ai_memory_general,style_preferences:o.style_preferences,style_preferences_general:o.style_preferences_general,selected_patient_template_set_id:o.selected_patient_template_set_id,selected_recording_patient_template_set_id:o.selected_recording_patient_template_set_id,selected_communication_template_id:o.selected_communication_template_id,selected_general_template_id:o.selected_general_template_id,selected_system_prompt_id:o.selected_system_prompt_id}),await Promise.all([e.get().saveToSupabase(),s()])}}let o=e.get().settings.saved_settings_snapshot;if(!o)return console.warn("[settings] restoreSettingsSnapshot: No snapshot found"),a;e.setSettingsDirty(!0),e.setRecentlySavedUntil(Date.now()+5e3);let l=(o.patient_template_sets||[]).map(w);return e.set(t=>{let n={...t.settings,hospital_name:o.hospital_name??t.settings.hospital_name,hospital_address:o.hospital_address??t.settings.hospital_address,hospital_phone:o.hospital_phone??t.settings.hospital_phone,saved_clinic_profiles:o.saved_clinic_profiles??t.settings.saved_clinic_profiles,active_clinic_profile_id:o.active_clinic_profile_id??t.settings.active_clinic_profile_id,vet_name:o.vet_name??t.settings.vet_name,gmail_address:o.gmail_address??t.settings.gmail_address,patient_template_sets:l.length>0?l:t.settings.patient_template_sets,communication_templates:o.communication_templates??t.settings.communication_templates,general_templates:o.general_templates??t.settings.general_templates,consent_templates:o.consent_templates??t.settings.consent_templates,system_prompt_templates:o.system_prompt_templates??t.settings.system_prompt_templates,chat_persona_templates:o.chat_persona_templates??t.settings.chat_persona_templates,selected_chat_persona_id:o.selected_chat_persona_id??t.settings.selected_chat_persona_id,style_preferences:o.style_preferences??t.settings.style_preferences,style_preferences_general:o.style_preferences_general??t.settings.style_preferences_general,ai_memory_patient:o.ai_memory_patient??t.settings.ai_memory_patient,ai_memory_soap:o.ai_memory_soap??t.settings.ai_memory_soap,ai_memory_discharge:o.ai_memory_discharge??t.settings.ai_memory_discharge,ai_memory_communication:o.ai_memory_communication??t.settings.ai_memory_communication,ai_memory_general:o.ai_memory_general??t.settings.ai_memory_general,accent_color:o.accent_color??t.settings.accent_color,referral_directory:o.referral_directory??t.settings.referral_directory,custom_links:o.custom_links??t.settings.custom_links,hidden_default_link_ids:o.hidden_default_link_ids??t.settings.hidden_default_link_ids,chat_thinking_mode:o.chat_thinking_mode??t.settings.chat_thinking_mode,chat_show_response_mode_toggle:o.chat_show_response_mode_toggle??t.settings.chat_show_response_mode_toggle,generation_thinking_mode:o.generation_thinking_mode??t.settings.generation_thinking_mode,default_input_mode:o.default_input_mode??t.settings.default_input_mode,chat_tts_voice:o.chat_tts_voice??t.settings.chat_tts_voice,chat_tts_speed:o.chat_tts_speed??t.settings.chat_tts_speed,recording_show_context_button:o.recording_show_context_button??t.settings.recording_show_context_button,recording_show_patient_picker:o.recording_show_patient_picker??t.settings.recording_show_patient_picker,recording_show_media_tools:o.recording_show_media_tools??t.settings.recording_show_media_tools,recording_show_typed_notes:o.recording_show_typed_notes??t.settings.recording_show_typed_notes,recording_show_hospital_link:o.recording_show_hospital_link??t.settings.recording_show_hospital_link,recording_show_system_prompt:o.recording_show_system_prompt??t.settings.recording_show_system_prompt,interpretation_enabled:o.interpretation_enabled??t.settings.interpretation_enabled,toolbar_show_referrals:o.toolbar_show_referrals??t.settings.toolbar_show_referrals,toolbar_show_quick_links:o.toolbar_show_quick_links??t.settings.toolbar_show_quick_links};return{settings:e.migrateSettings(n)}}),o.gmail_address&&await e.get().saveEmailSettings(),await e.get().saveToSupabase(),("ai_memory_soap"in o||"ai_memory_discharge"in o||"ai_memory_communication"in o||"ai_memory_general"in o||"selected_patient_template_set_id"in o||"selected_recording_patient_template_set_id"in o||"selected_communication_template_id"in o||"selected_general_template_id"in o||"selected_system_prompt_id"in o)&&t&&(i({ai_memory_soap:o.ai_memory_soap??h.bc.ai_memory_soap,ai_memory_discharge:o.ai_memory_discharge??h.bc.ai_memory_discharge,ai_memory_communication:o.ai_memory_communication??h.bc.ai_memory_communication,ai_memory_general:o.ai_memory_general??h.bc.ai_memory_general,style_preferences:o.style_preferences??h.bc.style_preferences,style_preferences_general:o.style_preferences_general??h.bc.style_preferences_general,selected_patient_template_set_id:o.selected_patient_template_set_id??h.bc.selected_patient_template_set_id,selected_recording_patient_template_set_id:o.selected_recording_patient_template_set_id??h.bc.selected_recording_patient_template_set_id,selected_communication_template_id:o.selected_communication_template_id??h.bc.selected_communication_template_id,selected_general_template_id:o.selected_general_template_id??h.bc.selected_general_template_id,selected_system_prompt_id:o.selected_system_prompt_id??h.bc.selected_system_prompt_id}),await s()),await v(o.custom_drugs,"[settings] restoreSettingsSnapshot:"),await b(o.staff_profiles,"[settings] restoreSettingsSnapshot:"),!0}async function k(e){let{currentVetId:t,updateVetPreferences:n,saveVetPreferencesToServer:i}=f.useCurrentVetStore.getState(),s=e.get().settings.saved_settings_snapshot;if(!s)return console.warn("[settings] restoreGlobalSettingsSnapshot: No snapshot found"),!1;
788e.setSettingsDirty(!0),e.setRecentlySavedUntil(Date.now()+5e3);let a=(s.patient_template_sets||[]).map(w);return e.set(t=>{let n={...t.settings,hospital_name:s.hospital_name??t.settings.hospital_name,hospital_address:s.hospital_address??t.settings.hospital_address,hospital_phone:s.hospital_phone??t.settings.hospital_phone,saved_clinic_profiles:s.saved_clinic_profiles??t.settings.saved_clinic_profiles,active_clinic_profile_id:s.active_clinic_profile_id??t.settings.active_clinic_profile_id,vet_name:s.vet_name??t.settings.vet_name,gmail_address:s.gmail_address??t.settings.gmail_address,patient_template_sets:a.length>0?a:t.settings.patient_template_sets,communication_templates:s.communication_templates??t.settings.communication_templates,general_templates:s.general_templates??t.settings.general_templates,consent_templates:s.consent_templates??t.settings.consent_templates,system_prompt_templates:s.system_prompt_templates??t.settings.system_prompt_templates,chat_persona_templates:s.chat_persona_templates??t.settings.chat_persona_templates,selected_chat_persona_id:s.selected_chat_persona_id??t.settings.selected_chat_persona_id,style_preferences:s.style_preferences??t.settings.style_preferences,style_preferences_general:s.style_preferences_general??t.settings.style_preferences_general,ai_memory_patient:s.ai_memory_patient??t.settings.ai_memory_patient,ai_memory_soap:s.ai_memory_soap??t.settings.ai_memory_soap,ai_memory_discharge:s.ai_memory_discharge??t.settings.ai_memory_discharge,ai_memory_communication:s.ai_memory_communication??t.settings.ai_memory_communication,ai_memory_general:s.ai_memory_general??t.settings.ai_memory_general,accent_color:s.accent_color??t.settings.accent_color,referral_directory:s.referral_directory??t.settings.referral_directory,custom_links:s.custom_links??t.settings.custom_links,hidden_default_link_ids:s.hidden_default_link_ids??t.settings.hidden_default_link_ids};return{settings:e.migrateSettings(n)}}),s.gmail_address&&await e.get().saveEmailSettings(),await e.get().saveToSupabase(),("ai_memory_soap"in s||"ai_memory_discharge"in s||"ai_memory_communication"in s||"ai_memory_general"in s||"selected_patient_template_set_id"in s||"selected_recording_patient_template_set_id"in s||"selected_communication_template_id"in s||"selected_general_template_id"in s||"selected_system_prompt_id"in s)&&t&&(n({ai_memory_soap:s.ai_memory_soap??h.bc.ai_memory_soap,ai_memory_discharge:s.ai_memory_discharge??h.bc.ai_memory_discharge,ai_memory_communication:s.ai_memory_communication??h.bc.ai_memory_communication,ai_memory_general:s.ai_memory_general??h.bc.ai_memory_general,style_preferences:s.style_preferences??h.bc.style_preferences,style_preferences_general:s.style_preferences_general??h.bc.style_preferences_general,selected_patient_template_set_id:s.selected_patient_template_set_id??h.bc.selected_patient_template_set_id,selected_recording_patient_template_set_id:s.selected_recording_patient_template_set_id??h.bc.selected_recording_patient_template_set_id,selected_communication_template_id:s.selected_communication_template_id??h.bc.selected_communication_template_id,selected_general_template_id:s.selected_general_template_id??h.bc.selected_general_template_id,selected_system_prompt_id:s.selected_system_prompt_id??h.bc.selected_system_prompt_id}),await i()),await v(s.custom_drugs,"[settings] restoreGlobalSettingsSnapshot:"),await b(s.staff_profiles,"[settings] restoreGlobalSettingsSnapshot:"),!0}var T=n(39109),A=n(27158),E=n(4482);let D=new Set([T.NT.id]);function O(e,t){return(u.rA||"agentic"!==e)&&("off"===e||"passive"===e||"active"===e||"agentic"===e)?e:t}function R(e,t){let{communication_rag_generation_mode:n,...i}=e,s={...t,...i,rag_generation_mode:O(i.rag_generation_mode,t.rag_generation_mode),extra_vet_seats:(0,A.XZ)(i.extra_vet_seats??t.extra_vet_seats)};s.active_clinic_profile_id=(0,E.m9)(s);let a=s.active_clinic_profile_id?s.saved_clinic_profiles.find(e=>e.id===s.active_clinic_profile_id):void 0;a&&(s.hospital_name=a.hospital_name,s.hospital_address=a.hospital_address,s.hospital_phone=a.hospital_phone),s.referral_directory=(0,E.X2)(s);let r=e.soap_templates&&e.soap_templates.length>0,o=e.discharge_templates&&e.discharge_templates.length>0,l=e.patient_template_sets&&e.patient_template_sets.length>0;if((r||o)&&!l){let t=e.soap_templates||[],n=e.discharge_templates||[],i=Math.max(t.length,n.length,1),a=[];for(let e=0;e<i;e++){let i=t[e],s=n[e];a.push({id:i?.id||s?.id||_(),name:i?.name||s?.name||`Template ${e+1}`,soap_content:i?.content||(0,d.We)(d.nq),discharge_content:s?.content||d.nq.discharge_content,preamble:"",history_template:"",exam_template:"",assessment_template:"",plan_template:""})}s.patient_template_sets=a,s.selected_patient_template_set_id=a[0]?.id||"default-patient"}return e.soap_template&&(!s.patient_template_sets||0===s.patient_template_sets.length)&&(s.patient_template_sets=[{id:"migrated-patient",name:"My Template",soap_content:e.soap_template,discharge_content:e.discharge_template||d.nq.discharge_content,preamble:"",history_template:"",exam_template:"",assessment_template:"",plan_template:""}],s.selected_patient_template_set_id="migrated-patient"),e.communication_template&&(!e.communication_templates||0===e.communication_templates.length)&&(s.communication_templates=[{id:"migrated-communication",name:"My Communication Template",content:e.communication_template}],s.selected_communication_template_id="migrated-communication"),s.patient_template_sets?.length||(s.patient_template_sets=[d.nq,d.KZ,d.dy]),s.communication_templates?.length||(s.communication_templates=[d._E,d.PH]
788),s.general_templates?.length||(s.general_templates=[d.lv,d.pX]),s.consent_templates?.length||(s.consent_templates=d.D1),s.system_prompt_templates?.length?(s.system_prompt_templates=s.system_prompt_templates.filter(e=>"default-veterinary"!==e.id),s.system_prompt_templates.find(e=>"default-general"===e.id)||s.system_prompt_templates.push(d.Jn)):s.system_prompt_templates=[d.Jn],"default-veterinary"===s.selected_system_prompt_id&&(s.selected_system_prompt_id="default-general"),s.patient_template_sets=s.patient_template_sets.map(w),s.patient_template_sets.find(e=>e.id===s.selected_patient_template_set_id)||(s.selected_patient_template_set_id=s.patient_template_sets[0].id),s.selected_recording_patient_template_set_id||(s.selected_recording_patient_template_set_id=s.selected_patient_template_set_id),s.patient_template_sets.find(e=>e.id===s.selected_recording_patient_template_set_id)||(s.selected_recording_patient_template_set_id=s.selected_patient_template_set_id),s.communication_templates.find(e=>e.id===s.selected_communication_template_id)||(s.selected_communication_template_id=s.communication_templates[0].id),s.general_templates.find(e=>e.id===s.selected_general_template_id)||(s.selected_general_template_id=s.general_templates[0].id),s.selected_consent_template_id&&s.consent_templates?.find(e=>e.id===s.selected_consent_template_id)||(s.selected_consent_template_id=s.consent_templates?.[0]?.id??"default-consent-general"),s.system_prompt_templates.find(e=>e.id===s.selected_system_prompt_id)||(s.selected_system_prompt_id=s.system_prompt_templates[0].id),s.chat_persona_templates?.length?(s.chat_persona_templates=s.chat_persona_templates.filter(e=>"default-veterinary"!==e.id),s.chat_persona_templates.length||(s.chat_persona_templates=d.De)):s.chat_persona_templates=d.De,"default-veterinary"===s.selected_chat_persona_id&&(s.selected_chat_persona_id="default-general"),s.chat_persona_templates.find(e=>e.id===s.selected_chat_persona_id)||D.has(s.selected_chat_persona_id)||(s.selected_chat_persona_id=s.chat_persona_templates[0].id),s}var x=n(44197),P=n(9846),N=n(70805),F=n(8582),L=n(4389),V=n(5142);let M=e=>(0,F.Xh)(e,"settings-email");function q(e){return{gmail_address:e.gmail_address||"",has_password:e.has_gmail_app_password??!!e.gmail_app_password,saved_email_profiles:e.saved_email_profiles}}async function Q(e,t,n,i){let s=Date.now();if(s-t<=n)return{emailSettings:e,nextLastEmailFetchTime:t};try{return{emailSettings:await function(e){let t=(0,V.getScopeFor)("user");return t&&t.userId===e?(0,L.getQueryClient)().fetchQuery((0,N.AP)(t,{domain:"settings-email",fetch:async({scope:e,signal:t})=>{if(!o.supabase)throw Error("Email settings unavailable.");let{data:{session:n},error:i}=await o.supabase.auth.getSession();if(i||!n?.access_token||n.user.id!==e.userId||t.aborted||!(0,V.isScopeCurrent)(e,"user"))throw Error("Email settings session unavailable.");let s=await fetch("/api/settings/email",{headers:{Authorization:`Bearer ${n.access_token}`},cache:"no-store",signal:t});if(!s.ok)throw Error("Email settings unavailable.");let a=await s.json();return{gmail_address:a.gmail_address,has_password:a.has_password,saved_email_profiles:a.saved_email_profiles?.map(e=>({id:e.id,name:e.name,gmail_address:e.gmail_address,has_password:e.has_password}))}}})):Promise.reject(new P.cc)}(i),nextLastEmailFetchTime:s}}catch{return{emailSettings:e,nextLastEmailFetchTime:t}}}function U(e,t){let n=e.filter(e=>!!e&&"string"==typeof e.id&&e.id.length>0),i=t.filter(e=>!!e&&"string"==typeof e.id&&e.id.length>0),s=n.filter(e=>!(0,x.sc)(`pending-task-${e.id}`)),a=i.filter(e=>(0,x.sc)(`pending-task-${e.id}`)),r=[],o=new Set;for(let e of[...s,...a])o.has(e.id)||(o.add(e.id),r.push(e));return r}var $=n(43265),W=n(65169);let H=["hospital_name","hospital_address","hospital_phone","vet_name","saved_clinic_profiles","active_clinic_profile_id","subscription_tier","monthly_cost_used","trial_status","trial_end_date","extra_vet_seats","usage_reset_date","purchase_source","subscription_period_end","subscription_cancel_at_period_end","scheduled_downgrade_tier","scheduled_downgrade_date","generation_model","discharge_generation_model","model_overrides","patient_template_sets","selected_patient_template_set_id","selected_recording_patient_template_set_id","communication_templates","selected_communication_template_id","general_templates","selected_general_template_id","system_prompt_templates","selected_system_prompt_id","accent_color","translator_speaking_rate","translator_default_language","translator_default_voice_gender","translator_default_clinician_language","tts_provider","tts_overrides","chat_tts_voice","chat_tts_speed","tasks_last_seen_at","cases_last_seen_at","records_last_seen_at","interpretation_enabled","toolbar_show_referrals","toolbar_show_quick_links","referral_directory","custom_links","vet_calc_stock_concentrations","hidden_drug_ids"],G={},z=null,j=[],K=new Set,B=()=>
788K.forEach(e=>e());function Y(e){for(let t of Object.keys(e))Object.prototype.hasOwnProperty.call(G,t)&&G[t]===e[t]&&delete G[t];B()}function X(){let e=(0,V.getScopeFor)("user"),t=e?(0,L.getQueryClient)().getQueryData((0,W.WK)(e)):void 0,n=t?.__restoredSettings,s=e?(0,L.getQueryClient)().getQueryData(M(e)):void 0,a=i&&i.row===t&&i.email===s?i.settings:void 0;if(!a){var r,o;if(a=null==t?d.a$:n?R(n.settings,d.a$):R((r=s??q(d.a$),o=d.a$,{generation_model:t.generation_model??u.UB,discharge_generation_model:t.discharge_generation_model??t.generation_model??u.UB,admin_chat_model:t.admin_chat_model??u.pI,admin_transcription_provider:t.admin_transcription_provider||void 0,admin_streaming_provider:t.admin_streaming_provider||void 0,model_overrides:t.model_overrides||{},transcription_overrides:t.transcription_overrides||{},tts_overrides:t.tts_overrides||{},vet_name:t.vet_name||"",hospital_name:t.hospital_name||"",hospital_address:t.hospital_address||"",hospital_phone:t.hospital_phone||"",saved_clinic_profiles:t.saved_clinic_profiles||[],active_clinic_profile_id:t.active_clinic_profile_id??null,gmail_address:r.gmail_address||"",has_gmail_app_password:r.has_password,gmail_app_password:"",saved_email_profiles:r.saved_email_profiles||[],system_prompt_templates:t.system_prompt_templates,selected_system_prompt_id:t.selected_system_prompt_id,chat_persona_templates:t.chat_persona_templates,selected_chat_persona_id:t.selected_chat_persona_id,patient_template_sets:t.patient_template_sets,selected_patient_template_set_id:t.selected_patient_template_set_id,selected_recording_patient_template_set_id:t.selected_recording_patient_template_set_id??t.selected_patient_template_set_id,communication_templates:t.communication_templates,selected_communication_template_id:t.selected_communication_template_id,general_templates:t.general_templates,selected_general_template_id:t.selected_general_template_id,consent_templates:t.consent_templates??[],selected_consent_template_id:t.selected_consent_template_id??"",soap_templates:t.soap_templates,discharge_templates:t.discharge_templates,selected_soap_template_id:t.selected_soap_template_id,selected_discharge_template_id:t.selected_discharge_template_id,soap_template:t.soap_template,discharge_template:t.discharge_template,communication_template:t.communication_template,style_preferences:t.style_preferences||"",ai_memory_patient:t.ai_memory_patient||"",ai_memory_soap:t.ai_memory_soap||"",ai_memory_discharge:t.ai_memory_discharge||"",ai_memory_communication:t.ai_memory_communication||"",ai_memory_general:t.ai_memory_general||"",pending_memory_reviews:(t.pending_memory_reviews||[]).filter(e=>!(0,x.sc)(`pending-memory-${e.text.slice(0,50)}`)),pending_case_reviews:(t.pending_case_reviews||[]).filter(e=>!(0,x.sc)(`pending-case-${e.record_id}`)),pending_task_reviews:U(t.pending_task_reviews??[],o.pending_task_reviews),referral_directory:t.referral_directory??[],custom_links:t.custom_links??[],example_discharges:t.example_discharges||[],accent_color:t.accent_color||"purple",vet_calc_stock_concentrations:t.vet_calc_stock_concentrations??{},hidden_drug_ids:t.hidden_drug_ids??[],auto_generate_discharge:t.auto_generate_discharge??!1,auto_extract_tasks:t.auto_extract_tasks??!0,auto_extract_memory:t.auto_extract_memory??!0,memory_auto_apply:t.memory_auto_apply??!0,auto_extract_cases:t.auto_extract_cases??!1,auto_clinical_insights:t.auto_clinical_insights??!0,rag_generation_mode:O(t.rag_generation_mode,"off"),discharge_chat_enabled:t.discharge_chat_enabled??!1,discharge_chat_full_context:t.discharge_chat_full_context??!1,tasks_last_seen_at:t.tasks_last_seen_at??null,cases_last_seen_at:t.cases_last_seen_at??null,records_last_seen_at:t.records_last_seen_at??null,subscription_tier:t.subscription_tier||(t.subscribed?"pro":"free"),free_recordings_used:t.free_recordings_used??0,monthly_cost_used:t.monthly_cost_used??0,extra_vet_seats:(0,A.XZ)(t.extra_vet_seats),usage_reset_date:t.usage_reset_date||new Date().toISOString(),stripe_customer_id:t.stripe_customer_id||void 0,stripe_subscription_id:t.stripe_subscription_id||void 0,has_payment_method:t.has_payment_method??!1,trial_status:t.trial_status??null,trial_start_date:t.trial_start_date??null,trial_end_date:t.trial_end_date??null,purchase_source:t.purchase_source??void 0,apple_transaction_id:t.apple_transaction_id||void 0,subscription_cancel_at_period_end:t.subscription_cancel_at_period_end??!1,subscription_period_end:t.subscription_period_end||void 0,scheduled_downgrade_tier:t.scheduled_downgrade_tier||void 0,scheduled_downgrade_date:t.scheduled_downgrade_date||void 0,stripe_schedule_id:t.stripe_schedule_id||void 0,saved_settings_snapshot:t.saved_settings_snapshot,chat_thinking_mode:t.chat_thinking_mode??!0,chat_show_response_mode_toggle:t.chat_show_response_mode_toggle??!1,generation_thinking_mode:t.generation_thinking_mode??!1,default_input_mode:t.default_input_mode??"voice",hidden_default_link_ids:t.hidden_default_link_ids??[],recording_show_context_button:t.recording_show_context_button??!0,recording_show_patient_picker:t.re
788cording_show_patient_picker??!0,recording_show_media_tools:t.recording_show_media_tools??!0,recording_show_typed_notes:t.recording_show_typed_notes??!0,recording_show_hospital_link:t.recording_show_hospital_link??!0,recording_show_system_prompt:t.recording_show_system_prompt??!0,interpretation_enabled:t.interpretation_enabled??!0,toolbar_show_referrals:t.toolbar_show_referrals??!0,toolbar_show_quick_links:t.toolbar_show_quick_links??!0,reasoning_effort:t.reasoning_effort??"low",reasoning_effort_overrides:t.reasoning_effort_overrides??{},translator_speaking_rate:t.translator_speaking_rate??1.15,translator_default_language:t.translator_default_language??"Spanish",translator_default_voice_gender:t.translator_default_voice_gender??"male",translator_default_clinician_language:t.translator_default_clinician_language??"English",tts_provider:t.tts_provider??"soniox",chat_tts_voice:t.chat_tts_voice??"b089032e45db460fb1934ece75a8c51d",chat_tts_speed:t.chat_tts_speed??1.2,ezyvet_connected:t.ezyvet_connected??!1,active_pims_adapter:t.active_pims_adapter??null}),d.a$),t&&(!n||n.templateListCacheVersion>=d.eL)){let e=n?.settings??t;for(let t of["patient_template_sets","communication_templates","general_templates","system_prompt_templates"])Array.isArray(e[t])&&0===e[t].length&&(a[t]=[])}i={row:t,email:s,settings:a}}return{settings:{...a,...G},settingsId:t&&!n&&t.id||null,templateListCacheVersion:void 0===t?0:n?.templateListCacheVersion??d.eL,hasVerifiedToolbarVisibility:void 0!==t&&(n?.hasVerifiedToolbarVisibility??!0),lastFetchedUserId:void 0===t?null:e?.userId??null}}function J(e){let t={};for(let n of H)Object.prototype.hasOwnProperty.call(e,n)&&Object.assign(t,{[n]:e[n]});return t}function Z(){let e=(0,L.getQueryClient)();if(z!==e){for(let e of j)e();z=e,j=[],(0,$.JC)({id:"settings-document",version:1,kind:"user",queryKey:W.WK,project:e=>{let t=e?.__restoredSettings;return{settings:J(t?.settings??e??d.a$),templateListCacheVersion:t?.templateListCacheVersion??d.eL,hasVerifiedToolbarVisibility:t?.hasVerifiedToolbarVisibility??!0,sourceUpdatedAt:t?.sourceUpdatedAt??("string"==typeof e?.updated_at?e.updated_at:null)}},restore:e=>{let t=J(e.settings);return{id:"",...t,__restoredSettings:{...e,settings:t}}},legacy:{name:"vet-soap-settings",restore:(e,t)=>{if(!e||e.lastFetchedUserId!==t.userId||!e.settings)return;let n={settings:J(e.settings),templateListCacheVersion:e.templateListCacheVersion??0,hasVerifiedToolbarVisibility:e.hasVerifiedToolbarVisibility??!1,sourceUpdatedAt:null};return{id:"",...n.settings,__restoredSettings:n}}}}),j.push((0,L.subscribeQueryCache)(e=>{("settings-document"===e.query.queryKey[2]||"settings-email"===e.query.queryKey[2])&&B()})),j.push((0,V.onScopeTransition)(e=>{"retired"===e.type&&(G={}),B()}))}}async function ee(e,t){let n=e.get().settings.system_prompt_templates;if(n.length<=1)return!1;let i=n.filter(e=>e.id!==t),s=e.get().settings.selected_system_prompt_id,a=s===t?i[0].id:s;return e.set(e=>({settings:{...e.settings,system_prompt_templates:i,selected_system_prompt_id:a}})),await e.get().saveToSupabase(),!0}async function et(e,t){let n=e.get().settings.patient_template_sets;if(n.length<=1)return!1;let i=n.filter(e=>e.id!==t),s=e.get().settings.selected_patient_template_set_id,a=s===t?i[0].id:s;return e.set(e=>({settings:{...e.settings,patient_template_sets:i,selected_patient_template_set_id:a}})),await e.get().saveToSupabase(),!0}function en(e,t,n,i){let s=e.generateId(),a={id:s,name:n,content:i};return e.set(e=>({settings:{...e.settings,[t]:[...e.settings[t],a]}})),e.get().saveToSupabase(),s}function ei(e,t,n,i){let s=e.get().settings[t];if(s.length<=1)return Promise.resolve(!1);let a=s.filter(e=>e.id!==i),r=e.get().settings[n],o=r===i?a[0].id:r;return e.set(e=>({settings:{...e.settings,[t]:a,[n]:o}})),e.get().saveToSupabase().then(()=>!0)}
788function es(e,t,n){let i=e.get().settings[t].find(e=>e.id===n);if(!i)return null;let s=e.generateId(),a={id:s,name:`${i.name} (Copy)`,content:i.content,sections:i.sections?.map(e=>({...e,aliases:[...e.aliases]}))};return e.set(e=>({settings:{...e.settings,[t]:[...e.settings[t],a]}})),e.get().saveToSupabase(),s}function ea(e,t,n,i,s,a,r){let{currentVetId:o}=f.useCurrentVetStore.getState();if(!o||!a.has(n))return!1;let l=(0,y.rf)(o,s,n);return e.markSettingsDirty(),e.set(e=>{if(e.settings[t].find(e=>e.id===l))return{settings:{...e.settings,[t]:e.settings[t].map(e=>e.id===l?{...e,...i}:e)}};let s=e.settings[t].find(e=>e.id===n);return s?{settings:{...e.settings,[t]:[...e.settings[t],{...s,...i,id:l}]}}:e}),r(l),e.scheduleDebouncedSave(),!0}async function er(e,t){return ei(e,"communication_templates","selected_communication_template_id",t)}async function eo(e,t){return ei(e,"general_templates","selected_general_template_id",t)}async function el(e,t){let n=e.get().settings.saved_clinic_profiles.find(e=>e.id===t);n&&(e.set(e=>({settings:{...e.settings,hospital_name:n.hospital_name,hospital_address:n.hospital_address,hospital_phone:n.hospital_phone,active_clinic_profile_id:n.id}})),e.saveToSupabase())}var ed=n(34471),ec=n(53423),e_=n(58645);async function eu(e,t,n,i){let s=()=>{if(!(0,V.isScopeCurrent)(e,"user"))throw Error("Account changed. Reopen the tasks list.")};if(s(),!o.supabase)throw Error("Tasks unavailable.");let{data:{user:a},error:r}=await o.supabase.auth.getUser();if(s(),r)throw r;if(!a||a.id!==e.userId)throw Error("Sign in to accept tasks.");let l=[...new Set(t.map(e=>e.record_id).filter(Boolean))],d=new Set;if(l.length){let{data:e,error:t}=await o.supabase.from("records").select("id").in("id",l);if(s(),t)throw t;(e??[]).forEach(e=>d.add(e.id))}let c=new Date().toISOString(),_=t.map(e=>({id:e.id,user_id:a.id,title:e.title,notes:e.notes,due_date:e.due_date??i,priority:"normal",category:e.category,record_id:e.record_id&&d.has(e.record_id)?e.record_id:null,source:"general"===e.category?"ai_soap":"ai_transcript",ai_extracted_text:e.ai_extracted_text,completed:!1,assigned_vet_id:n,created_at:c,updated_at:c}));s();let{error:u}=await o.supabase.from("tasks").upsert(_,{onConflict:"id",ignoreDuplicates:!0});if(s(),u)throw u;await (0,e_.$Y)(e,!0).catch(()=>void 0),s()}var ep=n(76840);async function em(e,t){if(!o.supabase)throw Error("This case is no longer available.");let n=()=>{if(!(0,V.isScopeCurrent)(e,"user"))throw Error("Account changed. Reopen the cases list.")};n();let{data:{user:i}}=await o.supabase.auth.getUser();if(n(),!i||i.id!==e.userId)throw Error("Sign in to accept this case.");let{data:s,error:a}=await o.supabase.from("records").select("id").eq("id",t.record_id).maybeSingle();if(n(),a)throw Error("Could not check the source record. Try again.");if(!s)return"missing";let{error:r}=await o.supabase.from("active_cases").insert({user_id:i.id,record_id:t.record_id,pet_name:t.pet_name,signalment:t.signalment,reason_summary:t.reason_summary,plan_snippet:t.plan_snippet,recheck_due:t.recheck_due,priority:t.priority??"normal",status:"active"});if(n(),r)throw Error("Could not accept this case. Try again.");return await (0,ep.yk)(e,!0).catch(()=>void 0),n(),"created"}let eg=new Set,eh=!1,ef=new Map;async function ey(e,t){let n=e.get().settings.pending_case_reviews[t];if(!n||!o.supabase)throw Error("This case is no longer available.");let i=(0,V.getScopeFor)("user");if(!i)throw Error("Sign in to accept this case.");let s=(0,ed.NI)(),a=()=>{(0,x.vS)(`pending-case-${n.record_id}`,5e3),e.set(e=>({settings:{...e.settings,pending_case_reviews:e.settings.pending_case_reviews.filter(e=>e.record_id!==n.record_id)}}))},r=await em(i,n);if(!(0,ed.e1)(s))throw Error("Account changed. Reopen the cases list.");if("missing"===r)throw a(),await e.get().saveToSupabase(),Error("Source record was deleted. Case dismissed.");a(),e.get().saveToSupabase().catch(()=>{})}async function ev(e,t){if(eh||eg.has(t))return;let i=e.get().settings.pending_task_reviews.find(e=>e.id===t);if(i&&o.supabase){eg.add(t),(0,x.vS)(`pending-task-${i.id}`,5e3);try{let s=(0,V.getScopeFor)("user");if(!s)return;let{useCurrentVetStore:a}=await Promise.resolve().then(n.bind(n,95037));if(!(0,V.isScopeCurrent)(s,"user")||(await eu(s,[i],a.getState().currentVetId??null,(0,ec.l5)()),!(0,V.isScopeCurrent)(s,"user")))return;e.set(e=>({settings:{...e.settings,pending_task_reviews:e.settings.pending_task_reviews.filter(e=>e.id!==t)}})),await e.get().saveToSupabase()}catch(e){console.error("Failed to approve pending task:",e)}finally{eg.delete(t)}}}async function eb(e){if(eh)return;let t=e.get().settings.pending_task_reviews;
788if(0!==t.length&&o.supabase){eh=!0,t.forEach(e=>{(0,x.vS)(`pending-task-${e.id}`,5e3),eg.add(e.id)});try{let i=(0,V.getScopeFor)("user");if(!i)return;let{useCurrentVetStore:s}=await Promise.resolve().then(n.bind(n,95037));if(!(0,V.isScopeCurrent)(i,"user")||(await eu(i,t,s.getState().currentVetId??null,(0,ec.l5)()),!(0,V.isScopeCurrent)(i,"user")))return;e.set(e=>({settings:{...e.settings,pending_task_reviews:[]}})),await e.get().saveToSupabase()}catch(e){console.error("Failed to approve all pending tasks:",e)}finally{eh=!1,t.forEach(e=>eg.delete(e.id))}}}var ew=n(63769),eS=n(18233);let eI=new Map;async function eC(e,t,n,i){if(!(0,o.isSupabaseConfigured)()||!o.supabase)return;let s=(0,p.xd)("user");if(s){if(!e().hasFetchedFromServer)return void console.warn("saveEmailSettings: Settings not yet fetched, skipping");n.lastLocalSettingsSavedAt=Date.now(),n.recentlySavedUntil=Date.now()+n.RECENTLY_SAVED_GRACE_MS;try{let n=e().settings.gmail_app_password??"",a=await function(e,t,n={}){if("user"!==e.kind||!e.isCurrent())return Promise.resolve(null);let i=e.scope.userId,s=JSON.stringify({gmail_address:t.gmail_address,...t.gmail_app_password?{gmail_app_password:t.gmail_app_password}:{},clear_password:!1===t.has_gmail_app_password&&!t.gmail_app_password,...n.activeEmailProfileId?{active_email_profile_id:n.activeEmailProfileId}:{},saved_email_profiles:t.saved_email_profiles}),a=eI.get(i),r=(async()=>{if(a&&await a.catch(()=>null),!e.isCurrent()||!o.supabase)return null;let{data:{session:t},error:n}=await o.supabase.auth.getSession();if(n||!e.isCurrent()||t?.user.id!==i||!t.access_token)return null;let r=await fetch("/api/settings/email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:s});if(!e.isCurrent()||!r.ok)return null;let l=await r.json();if(!e.isCurrent())return null;if("boolean"!=typeof l.has_password)throw Error("Email settings response omitted credential-presence metadata");return l.has_password})();return eI.set(i,r),r.finally(()=>{eI.get(i)===r&&eI.delete(i)}).catch(()=>void 0),r}(s,e().settings,i);if(!s.isCurrent()||null===a)return;t(e=>(e.settings.gmail_app_password??"")!==n?{}:{settings:{...e.settings,gmail_app_password:"",has_gmail_app_password:a}})}catch(e){s.isCurrent()&&console.error("Failed to save email settings:",e)}}}let ek=0;async function eT(e,t,n,i,s){let a;Z();let r=eS.useAuthStore.getState().user?.id??null;if(e&&(i.fetchSettingsGeneration+=1,r)){let e;(0,W.BR)(r),e=(0,V.getScopeFor)("user"),e?.userId===r&&(0,L.getQueryClient)().cancelQueries({queryKey:M(e),exact:!0})}let l=i.fetchSettingsGeneration,d=()=>i.fetchSettingsGeneration===l&&(eS.useAuthStore.getState().user?.id??null)===r,_=i.fetchSettingsPromise;if(!e&&_&&i.fetchSettingsUserId===r&&(await _,!d()||!e||t().hasFetchedFromServer&&t().lastFetchedUserId===r))return;let u=Date.now(),p=u-i.lastFetchSettingsTime<i.FETCH_SETTINGS_COOLDOWN_MS;if(!e&&p&&t().hasFetchedFromServer&&t().lastFetchedUserId===r||!d())return;i.lastFetchSettingsTime=u;let m=e=>{r&&d()&&n({hasFetchedFromServer:!0,settingsFetchError:{userId:r,reason:e}})};if(!(0,o.isSupabaseConfigured)()||!o.supabase){d()&&(n({hasFetchedFromServer:!0,hasVerifiedToolbarVisibility:!0,lastFetchedUserId:r}),m("unavailable"));return}if(!r)return;let g=async()=>{try{let{data:{user:e}}=await o.supabase.auth.getUser();if(!d())return;if(!e||e.id!==r)return void m("auth");let s=await (0,W.pV)(r);if(!d())return;if(s){let e=q(t().settings),{nextLastEmailFetchTime:n}=await Q(e,i.lastEmailFetchTime,i.EMAIL_FETCH_COOLDOWN_MS,r);if(!d())return;i.lastEmailFetchTime=n}if(n({...X(),hasFetchedFromServer:!0,settingsFetchError:null,hasVerifiedToolbarVisibility:!0,lastFetchedUserId:e.id}),i.hasCompletedServerFetch=!0,i.lastRemoteSettingsUpdatedAt=c(s?.updated_at),i.settingsDirty&&(i.pendingSettingsRefresh=!0),!d())return;t().subscribeToSettings()}catch{m("unavailable")}},h=(async()=>{try{await Promise.race([g(),new Promise(e=>{a=setTimeout(()=>{m("unavailable"),e()},i.SETTINGS_FETCH_TIMEOUT_MS)})]),d()&&!t().hasFetchedFromServer&&i.fetchSettingsGeneration===l&&(console.warn("[settings] fetchSettings bailed without setting readiness; unblocking UI"),m("unavailable"))}finally{void 0!==a&&clearTimeout(a)}})();i.fetchSettingsPromise=h,i.fetchSettingsUserId=r;try{await h}finally{i.fetchSettingsPromise===h&&(i.fetchSettingsPromise=null,i.fetchSettingsUserId=null)}}async function eA(e,t,n){if(!(0,o.isSupabaseConfigured)()||!o.supabase)return;if(!e().hasFetchedFromServer)return void console.warn("saveToSupabase: Settings not yet fetched from server, skipping save to prevent data loss");if(!n.hasCompletedServerFetch)return void console.warn("saveToSupabase: Server fetch not completed this session, skipping save to prevent data loss from stale localStorage defaults");let i=(0,p.xd)("user");
788if(!i||e().lastFetchedUserId!==i.scope.userId)return;let{settings:s,settingsId:a}=e(),r=++n.settingsEditRevision,l=new Date().toISOString();n.settingsDirty=!0,n.lastLocalSettingsSavedAt=c(l),n.recentlySavedUntil=Date.now()+n.RECENTLY_SAVED_GRACE_MS;let d=function(e,t,n={}){let i={generation_model:e.generation_model,discharge_generation_model:e.discharge_generation_model,admin_chat_model:e.admin_chat_model,admin_transcription_provider:e.admin_transcription_provider??null,admin_streaming_provider:e.admin_streaming_provider??null,model_overrides:e.model_overrides??{},transcription_overrides:e.transcription_overrides??{},tts_overrides:e.tts_overrides??{},vet_name:e.vet_name,hospital_name:e.hospital_name,hospital_address:e.hospital_address,hospital_phone:e.hospital_phone,saved_clinic_profiles:e.saved_clinic_profiles,active_clinic_profile_id:e.active_clinic_profile_id,system_prompt_templates:e.system_prompt_templates,selected_system_prompt_id:e.selected_system_prompt_id,chat_persona_templates:e.chat_persona_templates,selected_chat_persona_id:e.selected_chat_persona_id,patient_template_sets:e.patient_template_sets,selected_patient_template_set_id:e.selected_patient_template_set_id,selected_recording_patient_template_set_id:e.selected_recording_patient_template_set_id??e.selected_patient_template_set_id,communication_templates:e.communication_templates,selected_communication_template_id:e.selected_communication_template_id,general_templates:e.general_templates,selected_general_template_id:e.selected_general_template_id,consent_templates:e.consent_templates??[],selected_consent_template_id:e.selected_consent_template_id??"",style_preferences:e.style_preferences,ai_memory_patient:e.ai_memory_patient,ai_memory_soap:e.ai_memory_soap,ai_memory_discharge:e.ai_memory_discharge,ai_memory_communication:e.ai_memory_communication,ai_memory_general:e.ai_memory_general,pending_memory_reviews:e.pending_memory_reviews,pending_case_reviews:e.pending_case_reviews,pending_task_reviews:e.pending_task_reviews,referral_directory:e.referral_directory,custom_links:e.custom_links,example_discharges:e.example_discharges,accent_color:e.accent_color,vet_calc_stock_concentrations:e.vet_calc_stock_concentrations,hidden_drug_ids:e.hidden_drug_ids,auto_generate_discharge:e.auto_generate_discharge??!1,auto_extract_tasks:e.auto_extract_tasks??!0,auto_extract_memory:e.auto_extract_memory??!0,memory_auto_apply:e.memory_auto_apply??!0,auto_extract_cases:e.auto_extract_cases??!1,auto_clinical_insights:e.auto_clinical_insights??!0,rag_generation_mode:e.rag_generation_mode??"off",discharge_chat_enabled:e.discharge_chat_enabled??!1,discharge_chat_full_context:e.discharge_chat_full_context??!1,tasks_last_seen_at:e.tasks_last_seen_at??null,cases_last_seen_at:e.cases_last_seen_at??null,records_last_seen_at:e.records_last_seen_at??null,translator_speaking_rate:e.translator_speaking_rate,translator_default_language:e.translator_default_language,translator_default_voice_gender:e.translator_default_voice_gender,translator_default_clinician_language:e.translator_default_clinician_language,tts_provider:e.tts_provider,chat_tts_voice:e.chat_tts_voice,chat_tts_speed:e.chat_tts_speed,chat_thinking_mode:e.chat_thinking_mode??!0,chat_show_response_mode_toggle:e.chat_show_response_mode_toggle??!1,generation_thinking_mode:e.generation_thinking_mode??!1,default_input_mode:e.default_input_mode??"voice",hidden_default_link_ids:e.hidden_default_link_ids??[],recording_show_context_button:e.recording_show_context_button??!0,recording_show_patient_picker:e.recording_show_patient_picker??!0,recording_show_media_tools:e.recording_show_media_tools??!0,recording_show_typed_notes:e.recording_show_typed_notes??!0,recording_show_hospital_link:e.recording_show_hospital_link??!0,recording_show_system_prompt:e.recording_show_system_prompt??!0,interpretation_enabled:e.interpretation_enabled??!0,toolbar_show_referrals:e.toolbar_show_referrals??!0,toolbar_show_quick_links:e.toolbar_show_quick_links??!0,reasoning_effort:e.reasoning_effort??"low",reasoning_effort_overrides:e.reasoning_effort_overrides??{},updated_at:t};if(n.omitVetPreferenceFields)for(let e of h.u_)delete i[e];return i}(s,l,{omitVetPreferenceFields:!!f.useCurrentVetStore.getState().currentVetId});try{let s=await (0,m.g)(i,a,d);if(!s||!i.isCurrent()||(Y(d),t({settingsId:s.id}),n.lastRemoteSettingsUpdatedAt=c(l),n.settingsEditRevision!==r))return;
788n.settingsDirty=!1,n.hasLocalUserEdit=!1,n.pendingSettingsRefresh&&(n.pendingSettingsRefresh=!1,e().fetchSettings(!0))}catch(e){i.isCurrent()&&console.error("Failed to save settings to Supabase:",e)}}let eE=null,eD=null,eO=null,eR=!1,ex=0,eP=!1,eN=!1,eF=!1,eL=0,eV=0,eM=0,eq=null,eQ=null,eU=0,e$=0,eW=0,eH=d.a$;function eG(){ex+=1,eR=!0,eF=!0}function ez(e){return e.templateListCacheVersion>=d.eL}let ej=(Object.defineProperties(s={},{settingsUnsubscribe:{get:()=>eE,set:e=>{eE=e},enumerable:!0},subscribedUserId:{get:()=>eD,set:e=>{eD=e},enumerable:!0},saveDebounceTimer:{get:()=>eO,set:e=>{eO=e},enumerable:!0},settingsDirty:{get:()=>eR,set:e=>{eR=e},enumerable:!0},settingsEditRevision:{get:()=>ex,set:e=>{ex=e},enumerable:!0},pendingSettingsRefresh:{get:()=>eP,set:e=>{eP=e},enumerable:!0},hasCompletedServerFetch:{get:()=>eN,set:e=>{eN=e},enumerable:!0},hasLocalUserEdit:{get:()=>eF,set:e=>{eF=e},enumerable:!0},lastLocalSettingsSavedAt:{get:()=>eL,set:e=>{eL=e},enumerable:!0},lastRemoteSettingsUpdatedAt:{get:()=>eV,set:e=>{eV=e},enumerable:!0},recentlySavedUntil:{get:()=>eM,set:e=>{eM=e},enumerable:!0},fetchSettingsPromise:{get:()=>eq,set:e=>{eq=e},enumerable:!0},fetchSettingsUserId:{get:()=>eQ,set:e=>{eQ=e},enumerable:!0},fetchSettingsGeneration:{get:()=>eU,set:e=>{eU=e},enumerable:!0},lastFetchSettingsTime:{get:()=>e$,set:e=>{e$=e},enumerable:!0},lastEmailFetchTime:{get:()=>eW,set:e=>{eW=e},enumerable:!0},RECENTLY_SAVED_GRACE_MS:{value:2e3,writable:!1,enumerable:!0},FETCH_SETTINGS_COOLDOWN_MS:{value:3e4,writable:!1,enumerable:!0},SETTINGS_FETCH_TIMEOUT_MS:{value:2e4,writable:!1,enumerable:!0},EMAIL_FETCH_COOLDOWN_MS:{value:6e4,writable:!1,enumerable:!0}}),s),eK={migrateSettings:eB,mergePendingTaskReviews:U,defaultSettings:eH};function eB(e){return R(e,eH)}let eY=(0,a.v)()((e,t)=>{let n=n=>{let i=t(),s="function"==typeof n?n(i):n;s.settings&&function(e,t){for(let n of Object.keys(t))e[n]!==t[n]&&Object.assign(G,{[n]:t[n]})}(i.settings,s.settings),e(s)},i={get:()=>({settings:t().settings,saveToSupabase:()=>t().saveToSupabase(),updateSettings:e=>t().updateSettings(e)}),set:n,generateId:_,markSettingsDirty:eG,scheduleDebouncedSave:()=>{eO&&clearTimeout(eO);let e=(0,p.xd)("user");eO=setTimeout(()=>{eO=null,e?.isCurrent()&&t().saveToSupabase()},500)}},s={get:()=>({settings:t().settings,saveToSupabase:()=>t().saveToSupabase()}),set:n},a={get:()=>({settings:t().settings}),set:n,saveToSupabase:()=>{t().saveToSupabase()},saveEmailSettings:e=>{t().saveEmailSettings(e)},generateId:_},r={get:()=>({settings:t().settings,settingsId:t().settingsId,saveToSupabase:()=>t().saveToSupabase(),saveEmailSettings:()=>t().saveEmailSettings(),saveGlobalSettingsSnapshot:()=>t().saveGlobalSettingsSnapshot()}),set:n,setSettingsDirty:e=>{e?eG():eR=!1},setRecentlySavedUntil:e=>{eM=e},migrateSettings:eB};return{settings:eH,isLoaded:!1,hasFetchedFromServer:!1,settingsFetchError:null,hasVerifiedToolbarVisibility:!1,settingsId:null,lastFetchedUserId:null,templateListCacheVersion:0,updateSettings:e=>{let{vetUpdates:i,sharedUpdates:s}=(0,h.fb)(e),{currentVetId:a,updateVetPreferences:r}=f.useCurrentVetStore.getState(),o=a?s:{...s,...i};if(Object.keys(o).length>0&&(eG(),eM=Date.now()+2e3),Object.keys(i).length>0&&a&&r(i),n(t=>({settings:{...t.settings,...e}})),0===Object.keys(o).length)return;let l="gmail_address"in o||"gmail_app_password"in o||"has_gmail_app_password"in o;eO&&clearTimeout(eO);let d=(0,p.xd)("user");eO=setTimeout(async()=>{eO=null,!d?.isCurrent()||(l&&await t().saveEmailSettings(),d.isCurrent()&&t().saveToSupabase())},500)},updateSettingsImmediate:async i=>{let s=(0,p.xd)("user");if(n(e=>({settings:{...e.settings,...i}})),(0,o.isSupabaseConfigured)()&&o.supabase&&s)try{let{settingsId:n}=t(),a=new Date().toISOString(),r={...i,updated_at:a},o=await (0,m.g)(s,n,r);o&&s.isCurrent()&&(Y(i),e({settingsId:o.id}))}catch(e){s.isCurrent()&&console.error("updateSettingsImmediate: Exception:",e)}},resetSettings:()=>{ek+=1,eE&&(eE(),eE=null),eD=null,eO&&(clearTimeout(eO),eO=null),G={},eU+=1,eq=null,eQ=null,e$=0,eR=!1,eP=!1,eN=!1,eF=!1,eL=0,eV=0,eM=0,eW=0,e({settings:eH,settingsId:null,hasFetchedFromServer:!1,settingsFetchError:null,hasVerifiedToolbarVisibility:!1,lastFetchedUserId:null,templateListCacheVersion:0})},addSystemPromptTemplate:(e,t)=>
788{let n,s;return s={id:n=i.generateId(),name:e,content:t},i.set(e=>({settings:{...e.settings,system_prompt_templates:[...e.settings.system_prompt_templates,s]}})),i.get().saveToSupabase(),n},updateSystemPromptTemplate:(e,t)=>{i.markSettingsDirty(),i.set(n=>({settings:{...n.settings,system_prompt_templates:n.settings.system_prompt_templates.map(n=>n.id===e?{...n,...t}:n)}})),i.scheduleDebouncedSave()},deleteSystemPromptTemplate:e=>ee(i,e),duplicateSystemPromptTemplate:e=>(function(e,t){let n=e.get().settings.system_prompt_templates.find(e=>e.id===t);if(!n)return null;let i=e.generateId(),s={id:i,name:`${n.name} (Copy)`,content:n.content};return e.set(e=>({settings:{...e.settings,system_prompt_templates:[...e.settings.system_prompt_templates,s]}})),e.get().saveToSupabase(),i})(i,e),selectSystemPromptTemplate:e=>{i.get().updateSettings({selected_system_prompt_id:e})},getSelectedSystemPromptTemplate:()=>(function(e){let t=e.get().settings.system_prompt_templates,{currentVetId:n,currentVetPreferences:i}=f.useCurrentVetStore.getState(),s=n?i.selected_system_prompt_id??e.get().settings.selected_system_prompt_id:e.get().settings.selected_system_prompt_id;return t.find(e=>e.id===s)||t[0]||null})(i),getSystemPromptTemplates:()=>ez(t())?i.get().settings.system_prompt_templates:[],addChatPersonaTemplate:(e,t,n)=>(0,T.Hc)(i,e,t,n),updateChatPersonaTemplate:(e,t)=>
788(0,T.jR)(i,e,t),deleteChatPersonaTemplate:e=>(0,T.n2)(i,e),duplicateChatPersonaTemplate:e=>(0,T.f1)(i,e),selectChatPersonaTemplate:e=>(0,T.yL)(i,e),getSelectedChatPersonaTemplate:()=>(0,T.hG)(i),getChatPersonaTemplates:()=>(0,T.jQ)(i),addPatientTemplateSet:(e,t,n)=>{let s,a,r,o;return s=i.generateId(),r=(a=t.trim())?(0,g.$u)(a):null,o={id:s,name:e,preamble:r?.unparsed?.trim()??"",history_template:r?.history??"",exam_template:r?.exam??"",assessment_template:r?.assessment??"",plan_template:r?.plan??"",discharge_content:n,soap_content:a||void 0,sections:a?void 0:[{key:"section_1",label:"Section 1",aliases:[],template:""}]},i.set(e=>({settings:{...e.settings,patient_template_sets:[...e.settings.patient_template_sets,o]}})),i.get().saveToSupabase(),s},updatePatientTemplateSet:(e,t)=>(function(e,t,n){let{currentVetId:i,currentVetPreferences:s,updateVetPreferences:a}=f.useCurrentVetStore.getState();if(i&&y.Sx.has(t)){let r=(0,y.rf)(i,"patient",t);e.markSettingsDirty(),e.set(e=>{if(e.settings.patient_template_sets.find(e=>e.id===r))return{settings:{...e.settings,patient_template_sets:e.settings.patient_template_sets.map(e=>e.id===r?{...e,...n}:e)}};let i=e.settings.patient_template_sets.find(e=>e.id===t);return i?{settings:{...e.settings,patient_template_sets:[...e.settings.patient_template_sets,{...i,...n,id:r}]}}:e});let o={selected_patient_template_set_id:r};s.selected_recording_patient_template_set_id===t&&(o.selected_recording_patient_template_set_id=r),a(o),e.scheduleDebouncedSave();return}e.markSettingsDirty(),e.set(e=>({settings:{...e.settings,patient_template_sets:e.settings.patient_template_sets.map(e=>e.id===t?{...e,...n}:e)}})),e.scheduleDebouncedSave()})(i,e,t),deletePatientTemplateSet:e=>et(i,e),duplicatePatientTemplateSet:e=>(function(e,t){let n=e.get().settings.patient_template_sets.find(e=>e.id===t);if(!n)return null;let i=e.generateId(),s={...n,id:i,name:`${n.name} (Copy)`};return e.set(e=>({settings:{...e.settings,patient_template_sets:[...e.settings.patient_template_sets,s]}})),e.get().saveToSupabase(),i})(i,e),selectPatientTemplateSet:e=>{i.get().updateSettings({selected_patient_template_set_id:e})},getSelectedPatientTemplateSet:()=>(function(e){let t=e.get().settings.patient_template_sets,{currentVetId:n,currentVetPreferences:i}=f.useCurrentVetStore.getState(),s=n?i.selected_patient_template_set_id??e.get().settings.selected_patient_template_set_id:e.get().settings.selected_patient_template_set_id,a=(0,y.yA)(t,n,"patient",s,y.Sx);return t.find(e=>e.id===a)||t[0]||null})(i),getPatientTemplateSets:()=>ez(t())?function(e){let t=e.get().settings.patient_template_sets,{currentVetId:n}=f.useCurrentVetStore.getState();return(0,y.K6)(t,n,"patient",y.Sx)}(i):[],restoreDefaultTemplates:()=>(function(e){let{currentVetId:t,updateVetPreferences:n,saveVetPreferencesToServer:i}=f.useCurrentVetStore.getState(),s=e.get().settings;if(t){e.markSettingsDirty(),e.set(e=>({settings:{...e.settings,patient_template_sets:(0,y.uK)(e.settings.patient_template_sets,t,"patient",y.Sx),communication_templates:(0,y.uK)(e.settings.communication_templates,t,"communication",y.p6),general_templates:(0,y.uK)(e.settings.general_templates,t,"general",y.rT),consent_templates:d.D1,selected_consent_template_id:"default-consent-general"}})),n({ai_memory_soap:h.bc.ai_memory_soap,ai_memory_discharge:h.bc.ai_memory_discharge,ai_memory_communication:h.bc.ai_memory_communication,ai_memory_general:h.bc.ai_memory_general,style_preferences:h.bc.style_preferences,style_preferences_general:h.bc.style_preferences_general,selected_patient_template_set_id:h.bc.selected_patient_template_set_id,selected_recording_patient_template_set_id:h.bc.selected_recording_patient_template_set_id,selected_communication_template_id:h.bc.selected_communication_template_id,selected_general_template_id:h.bc.selected_general_template_id,selected_system_prompt_id:h.bc.selected_system_prompt_id}),i(),e.get().saveToSupabase();return}e.set(e=>({settings:{...e.settings,system_prompt_templates:[d.Jn],selected_system_prompt_id:"default-general",chat_persona_templates:d.De,selected_chat_persona_id:"default-general",patient_template_sets:[d.nq,d.KZ,d.dy],selected_patient_template_set_id:"default-soap",communication_templates:[d._E,d.PH],selected_communication_template_id:"default-communication",general_templates:[d.lv,d.pX],selected_general_template_id:"default-notes",consent_templates:d.D1,selected_consent_template_id:"default-consent-general",style_preferences:s.style_preferences,style_preferences_general:s.style_preferences_general}})),e.get().saveToSupabase()})(i),addCommunicationTemplate:(e,t)=>
788en(i,"communication_templates",e,t),updateCommunicationTemplate:(e,t)=>(function(e,t,n){let{updateVetPreferences:i}=f.useCurrentVetStore.getState();ea(e,"communication_templates",t,n,"communication",y.p6,e=>i({selected_communication_template_id:e}))||(e.markSettingsDirty(),e.set(e=>({settings:{...e.settings,communication_templates:e.settings.communication_templates.map(e=>e.id===t?{...e,...n}:e)}})),e.scheduleDebouncedSave())})(i,e,t),deleteCommunicationTemplate:e=>er(i,e),duplicateCommunicationTemplate:e=>es(i,"communication_templates",e),selectCommunicationTemplate:e=>{i.get().updateSettings({selected_communication_template_id:e})},getSelectedCommunicationTemplate:()=>(function(e){let t=e.get().settings.communication_templates,{currentVetId:n,currentVetPreferences:i}=f.useCurrentVetStore.getState(),s=n?i.selected_communication_template_id??e.get().settings.selected_communication_template_id:e.get().settings.selected_communication_template_id,a=(0,y.yA)(t,n,"communication",s,y.p6);return t.find(e=>e.id===a)||t[0]||null})(i),getCommunicationTemplates:()=>ez(t())?function(e){let t=e.get().settings.communication_templates,{currentVetId:n}=f.useCurrentVetStore.getState();return(0,y.K6)(t,n,"communication",y.p6)}(i):[],addGeneralTemplate:(e,t)=>
788en(i,"general_templates",e,t),updateGeneralTemplate:(e,t)=>(function(e,t,n){let{updateVetPreferences:i}=f.useCurrentVetStore.getState();ea(e,"general_templates",t,n,"general",y.rT,e=>i({selected_general_template_id:e}))||(e.markSettingsDirty(),e.set(e=>({settings:{...e.settings,general_templates:e.settings.general_templates.map(e=>e.id===t?{...e,...n}:e)}})),e.scheduleDebouncedSave())})(i,e,t),deleteGeneralTemplate:e=>eo(i,e),duplicateGeneralTemplate:e=>es(i,"general_templates",e),selectGeneralTemplate:e=>{i.get().updateSettings({selected_general_template_id:e})},getSelectedGeneralTemplate:()=>(function(e){let t=e.get().settings.general_templates,{currentVetId:n,currentVetPreferences:i}=f.useCurrentVetStore.getState(),s=n?i.selected_general_template_id??e.get().settings.selected_general_template_id:e.get().settings.selected_general_template_id,a=(0,y.yA)(t,n,"general",s,y.rT);return t.find(e=>e.id===a)||t[0]||null})(i),getGeneralTemplates:()=>ez(t())?function(e){let t=e.get().settings.general_templates,{currentVetId:n}=f.useCurrentVetStore.getState();return(0,y.K6)(t,n,"general",y.rT)}(i):[],addConsentTemplate:(e,t,n,s)=>{let a,r;return r={id:a=i.generateId(),name:e,form_type:t,title:n,template_content:s},i.set(e=>({settings:{...e.settings,consent_templates:[...e.settings.consent_templates??[],r]}})),i.get().saveToSupabase(),a},updateConsentTemplate:(e,t)=>
788{i.markSettingsDirty(),i.set(n=>({settings:{...n.settings,consent_templates:(n.settings.consent_templates??[]).map(n=>n.id===e?{...n,...t}:n)}})),i.scheduleDebouncedSave()},deleteConsentTemplate:e=>(function(e,t){let n=e.get().settings.consent_templates??[];if(n.length<=1)return Promise.resolve(!1);let i=n.filter(e=>e.id!==t),s=e.get().settings.selected_consent_template_id,a=s===t?i[0]?.id??"":s;return e.set(e=>({settings:{...e.settings,consent_templates:i,selected_consent_template_id:a}})),e.get().saveToSupabase().then(()=>!0)})(i,e),duplicateConsentTemplate:e=>(function(e,t){let n=(e.get().settings.consent_templates??[]).find(e=>e.id===t);if(!n)return null;let i=e.generateId(),s={id:i,name:`${n.name} (Copy)`,form_type:n.form_type,title:n.title,template_content:n.template_content};return e.set(e=>({settings:{...e.settings,consent_templates:[...e.settings.consent_templates??[],s]}})),e.get().saveToSupabase(),i})(i,e),selectConsentTemplate:e=>{i.get().updateSettings({selected_consent_template_id:e})},getSelectedConsentTemplate:()=>{let e,t;return e=i.get().settings.consent_templates??[],t=i.get().settings.selected_consent_template_id,e.find(e=>e.id===t)??e[0]??null},getConsentTemplates:()=>i.get().settings.consent_templates??[],saveClinicProfile:(e,t)=>(function(e,t,n){let i=e.generateId(),{hospital_name:s,hospital_address:a,hospital_phone:r}=e.get().settings,o={id:i,name:t,hospital_name:s,hospital_address:a,...n?{hospital_address_details:n}:{},hospital_phone:r,created_at:new Date().toISOString()};return e.set(e=>{let t;return{settings:(t=[...e.settings.saved_clinic_profiles,o],{...e.settings,saved_clinic_profiles:t,active_clinic_profile_id:o.id,hospital_name:o.hospital_name,hospital_address:o.hospital_address,hospital_phone:o.hospital_phone})}}),e.saveToSupabase(),i})(a,e,t),loadClinicProfile:e=>el(a,e),updateClinicProfile:(e,t)=>{a.set(n=>{if(!n.settings.saved_clinic_profiles.some(t=>t.id===e))return{settings:n.settings};let i=(0,E.m9)(n.settings),s=n.settings.saved_clinic_profiles.map(n=>n.id===e?{...n,...t}:n),a=i===e?s.find(t=>t.id===e):void 0;return{settings:{...n.settings,saved_clinic_profiles:s,...a?{active_clinic_profile_id:a.id,hospital_name:a.hospital_name,hospital_address:a.hospital_address,hospital_phone:a.hospital_phone}:{}}}}),a.saveToSupabase()},deleteClinicProfile:e=>{a.set(t=>{let n=(0,E.m9)(t.settings),i=n===e,s=t.settings.saved_clinic_profiles.filter(t=>t.id!==e),a=(0,E.m9)({...t.settings,active_clinic_profile_id:i?null:n,saved_clinic_profiles:s}),r=i&&a?s.find(e=>e.id===a):void 0,o=t.settings.referral_directory.map(t=>{if(t.clinic_profile_id!==e)return t;if(a)return{...t,clinic_profile_id:a};let{clinic_profile_id:n,...i}=t;return i});return{settings:{...t.settings,saved_clinic_profiles:s,active_clinic_profile_id:a,referral_directory:o,...r?{hospital_name:r.hospital_name,hospital_address:r.hospital_address,hospital_phone:r.hospital_phone}:{}}}}),a.saveToSupabase()},getClinicProfiles:()=>a.get().settings.saved_clinic_profiles,saveEmailProfile:e=>(function(e,t){let{gmail_address:n,gmail_app_password:i,has_gmail_app_password:s}=e.get().settings;if(!n)return;let a={id:e.generateId(),name:t,gmail_address:n,has_password:!!i||!!s};e.set(e=>({settings:{...e.settings,saved_email_profiles:[...e.settings.saved_email_profiles,a]}})),e.saveEmailSettings()})(a,e),loadEmailProfile:e=>{let t;(t=a.get().settings.saved_email_profiles.find(t=>t.id===e))&&(a.set(e=>({settings:{...e.settings,gmail_address:t.gmail_address,has_gmail_app_password:!!t.has_password,gmail_app_password:""}})),a.saveEmailSettings({activeEmailProfileId:e}))},deleteEmailProfile:e=>{a.set(t=>({settings:{...t.settings,saved_email_profiles:t.settings.saved_email_profiles.filter(t=>t.id!==e)}})),a.saveEmailSettings()},exportSettings:()=>JSON.stringify(t().settings,null,2),importSettings:e=>{try{let i=JSON.parse(e),s=eB({...t().settings,...i});return n({settings:s}),t().saveToSupabase(),!0}catch{return!1}},addPendingMemoryReviews:e=>{s.set(t=>({settings:{...t.settings,pending_memory_reviews:[...t.settings.pending_memory_reviews,...e]}})),s.get().saveToSupabase()},removePendingMemoryReview:e=>{let t;
788(t=s.get().settings.pending_memory_reviews[e])&&(0,x.vS)(`pending-memory-${t.text.slice(0,50)}`,5e3),s.set(t=>({settings:{...t.settings,pending_memory_reviews:t.settings.pending_memory_reviews.filter((t,n)=>n!==e)}})),s.get().saveToSupabase()},updatePendingMemoryReview:(e,t)=>{s.set(n=>({settings:{...n.settings,pending_memory_reviews:n.settings.pending_memory_reviews.map((n,i)=>i===e?{...n,text:t}:n)}})),s.get().saveToSupabase()},clearPendingMemoryReviews:()=>{s.get().settings.pending_memory_reviews.forEach(e=>(0,x.vS)(`pending-memory-${e.text.slice(0,50)}`,5e3)),s.set(e=>({settings:{...e.settings,pending_memory_reviews:[]}})),s.get().saveToSupabase()},addPendingCaseReview:e=>{!s.get().settings.pending_case_reviews.some(t=>t.record_id===e.record_id)&&(s.set(t=>({settings:{...t.settings,pending_case_reviews:[...t.settings.pending_case_reviews,e]}})),s.get().saveToSupabase())},removePendingCaseReview:e=>{let t;(t=s.get().settings.pending_case_reviews[e])&&(0,x.vS)(`pending-case-${t.record_id}`,5e3),s.set(t=>({settings:{...t.settings,pending_case_reviews:t.settings.pending_case_reviews.filter((t,
788n)=>n!==e)}})),s.get().saveToSupabase()},updatePendingCaseReview:(e,t)=>{let n;(n=s.get().settings.pending_case_reviews[e])&&(0,x.vS)(`pending-case-${n.record_id}`,5e3),s.set(n=>({settings:{...n.settings,pending_case_reviews:n.settings.pending_case_reviews.map((n,i)=>i===e?{...n,...t}:n)}})),s.get().saveToSupabase()},approvePendingCaseReview:e=>(function(e,t){let n=e.get().settings.pending_case_reviews[t];if(!n)return Promise.reject(Error("This case is no longer available."));let i=(0,ed.NI)(),s=`${i.generation}:${i.userId}:${n.record_id}`,a=ef.get(s);if(a)return a;let r=ey(e,t).finally(()=>{ef.get(s)===r&&ef.delete(s)});return ef.set(s,r),r})(s,e),addPendingTaskReview:e=>{!s.get().settings.pending_task_reviews.some(t=>t.record_id===e.record_id)&&((0,x.vS)(`pending-task-${e.id}`,5e3),s.set(t=>({settings:{...t.settings,pending_task_reviews:[...t.settings.pending_task_reviews,e]}})),s.get().saveToSupabase())},removePendingTaskReview:e=>{let t;(t=s.get().settings.pending_task_reviews.find(t=>t.id===e))&&(0,x.vS)(`pending-task-${t.id}`,5e3),s.set(t=>({settings:{...t.settings,pending_task_reviews:t.settings.pending_task_reviews.filter(t=>t.id!==e)}})),s.get().saveToSupabase()},updatePendingTaskReview:(e,t)=>{let n;(n=s.get().settings.pending_task_reviews.find(t=>t.id===e))&&(0,x.vS)(`pending-task-${n.id}`,5e3),s.set(n=>({settings:{...n.settings,pending_task_reviews:n.settings.pending_task_reviews.map(n=>n.id===e?{...n,...t}:n)}})),s.get().saveToSupabase()},approvePendingTaskReview:e=>ev(s,e),approveAllPendingTasks:()=>eb(s),rejectAllPendingTasks:()=>{s.get().settings.pending_task_reviews.forEach(e=>(0,x.vS)(`pending-task-${e.id}`,5e3)),s.set(e=>({settings:{...e.settings,pending_task_reviews:[]}})),s.get().saveToSupabase()},addReferral:e=>{let t,n,i,s;return t=a.generateId(),n=new Date().toISOString(),i=(0,E.m9)(a.get().settings),s={...e,id:t,...i?{clinic_profile_id:i}:{},created_at:n,updated_at:n},a.set(e=>({settings:{...e.settings,referral_directory:[...e.settings.referral_directory,s]}})),a.saveToSupabase(),t},updateReferral:(e,t)=>{a.set(n=>({settings:{...n.settings,referral_directory:n.settings.referral_directory.map(n=>n.id===e?{...n,...t,updated_at:new Date().toISOString()}:n)}})),a.saveToSupabase()},deleteReferral:e=>{a.set(t=>({settings:{...t.settings,referral_directory:t.settings.referral_directory.filter(t=>t.id!==e)}})),a.saveToSupabase()},getReferrals:()=>(0,E.pt)(a.get().settings),getReferralsBySpecialty:e=>(0,E.pt)(a.get().settings).filter(t=>t.specialty.toLowerCase()===e.toLowerCase()),addCustomLink:e=>{let t,n;return t=a.generateId(),n={...e,id:t},a.set(e=>({settings:{...e.settings,custom_links:[...e.settings.custom_links,n]}})),a.saveToSupabase(),t},updateCustomLink:(e,t)=>{a.set(n=>({settings:{...n.settings,custom_links:n.settings.custom_links.map(n=>n.id===e?{...n,...t}:n)}})),a.saveToSupabase()},deleteCustomLink:e=>{a.set(t=>({settings:{...t.settings,custom_links:t.settings.custom_links.filter(t=>t.id!==e)}})),a.saveToSupabase()},hideDefaultLink:e=>{a.set(t=>{let n=t.settings.hidden_default_link_ids??[];return n.includes(e)?{settings:t.settings}:{settings:{...t.settings,hidden_default_link_ids:[...n,e]}}}),a.saveToSupabase()},restoreDefaultLinks:()=>{a.set(e=>({settings:{...e.settings,hidden_default_link_ids:[]}})),a.saveToSupabase()},fetchSettings:(n=!1)=>eT(n,t,e,ej,eK),saveToSupabase:()=>eA(t,e,ej),saveEmailSettings:e=>eC(t,n,ej,e),subscribeToSettings:()=>(function(e,t,n){if(!(0,o.isSupabaseConfigured)()||!o.supabase)return;let i=eS.useAuthStore.getState().user?.id;if(!i||n.settingsUnsubscribe&&n.subscribedUserId===i)return;let s=++ek;n.settingsUnsubscribe&&(n.settingsUnsubscribe(),n.settingsUnsubscribe=null,n.subscribedUserId=null),(0,ew.Tr)("settings",i,a=>{if("UPDATE"!==a.eventType||!a.new||Date.now()<n.recentlySavedUntil)return;let r=a.new,o=e().settingsId;if(o&&r.id&&r.id!==o)return;let l=c(r.updated_at);l&&(l<=n.lastLocalSettingsSavedAt||l<=n.lastRemoteSettingsUpdatedAt)||s===ek&&n.subscribedUserId===i&&eS.useAuthStore.getState().user?.id===i&&(!function(e){let t=(0,p.xd)("user");if(!t)return;let n=(0,W.WK)(t.scope);(0,p.L4)(t,n,t=>{if(!t)return t;let n=(0,W.OY)({...t,...e});return t.__restoredSettings&&(n.__restoredSettings={...t.__restoredSettings,settings:J({...t.__restoredSettings.settings,...e}),sourceUpdatedAt:"string"==typeof e.updated_at?e.updated_at:t.__restoredSettings.sourceUpdatedAt}),n})}(r),t(X()),n.lastRemoteSettingsUpdatedAt=l||n.lastRemoteSettingsUpdatedAt)}).then(e=>{s!==ek||n.subscribedUserId!==i?e():n.settingsUnsubscribe=e}),n.subscribedUserId=i})(t,e,ej),saveSettingsSnapshot:()=>S(r),saveGlobalSettingsSnapshot:()=>I(r),restoreSettingsSnapshot:()=>C(r),restoreGlobalSettingsSnapshot:()=>
788k(r),getSettingsSnapshotDate:()=>(function(e){let{currentVetId:t,currentVetPreferences:n}=f.useCurrentVetStore.getState();if(t)return n.saved_settings_snapshot?.saved_at??null;let i=e().settings.saved_settings_snapshot;return i?.saved_at??null})(t),getVetSettingsSnapshotDate:()=>(function(){let{currentVetId:e,currentVetPreferences:t}=f.useCurrentVetStore.getState();return e?t.saved_settings_snapshot?.saved_at??null:null})(),getGlobalSettingsSnapshotDate:()=>{let e;return e=t().settings.saved_settings_snapshot,e?.saved_at??null}}});K.add(()=>{let e=X(),t=eY.getState();(0,r.x)(t.settings,e.settings)&&(e.settings=t.settings),Object.keys(e).every(n=>Object.is(t[n],e[n]))||eY.setState(e)}),Z(),eY.setState({...X(),isLoaded:!0}),(0,l.G)(e=>{"session_cleared"===e.type&&eY.getState().resetSettings()})},98906:(e,t,n)=>{n.d(t,{K6:()=>c,Sx:()=>s,Wp:()=>p,p6:()=>a,qM:()=>l,rT:()=>r,rf:()=>o,uK:()=>u,yA:()=>d});var i=n(30969);let s=new Set([i.nq.id,i.KZ.id,i.dy.id]),a=new Set([i._E.id,i.PH.id]),r=new Set([i.lv.id,i.pX.id]);function o(e,t,n){return`vet-${e}-${t}-${n}`}function l(e,t){if(!e.startsWith("vet-"))return null;let n=`-${t}-`,i=e.indexOf(n,4);if(-1===i)return null;let s=e.slice(4,i),a=e.slice(i+n.length);return s&&a?{vetId:s,baseTemplateId:a}:null}function d(e,t,n,i,s){if(!i||!t||!s.has(i))return i;let a=o(t,n,i);return e.some(e=>e.id===a)?a:i}function c(e,t,n,i){if(!t)return e;let s=new Map(e.map(e=>[e.id,e])),a=new Set(e.filter(e=>i.has(e.id)).map(e=>e.id)),r=new Set,d=[];for(let c of e){let e=l(c.id,n);if(e){if(e.vetId!==t||i.has(e.baseTemplateId)&&a.has(e.baseTemplateId))continue;r.has(c.id)||(d.push(c),r.add(c.id));continue}if(i.has(c.id)){let e=o(t,n,c.id),i=s.get(e);if(i){d.push(i),r.add(e);continue}}d.push(c)}return d}function _(e,t,n,i){let s=l(e,n);return null!==s&&s.vetId===t&&i.has(s.baseTemplateId)}function u(e,t,n,i){return e.filter(e=>!_(e.id,t,n,i))}function p(e,t,n,i){return e.filter(e=>_(e.id,t,n,i))}i.D1.map(e=>e.id)},99321:(e,t,n)=>{n.r(t),n.d(t,{beginRecordWrite:()=>m,cacheCreatedRecord:()=>C,hasCachedRecordList:()=>y,isRecordWriteProtected:()=>g,mapCachedRecords:()=>I,patchCachedRecord:()=>S,projectRecordList:()=>D,publishLeanRecord:()=>k,readRecordDetail:()=>v,readRecordDetails:()=>b,readRecordList:()=>f,recordCacheFence:()=>R,removeRecordDetail:()=>E,settleRecordWrite:()=>A,startRecordsCache:()=>O,writeRecordDetail:()=>T,writeRecordList:()=>w});var i=n(41167),s=n(15780),a=n(4389),r=n(5142),o=n(8582),l=n(43265);let d=[],c=new WeakSet,_=new WeakMap,u=new WeakMap;function p(){let e=u.get((0,a.getQueryClient)());return e?.fence.isCurrent()?e:void 0}function m(e){let t=(0,a.getQueryClient)(),n=p()??{fence:e,pending:0,rows:new Set};return u.set(t,n),n.pending++,async()=>{n.pending--,!n.pending&&e.isCurrent()&&u.get(t)===n&&await A(e)}}function g(e){return p()?.rows.has(e)??!1}function h(e,t){if(!e.isCurrent())return;let n=(0,a.getQueryClient)(),i=_.get(n);for(let s of(i||(i=new Map,_.set(n,i)),n.getQueryCache().findAll({queryKey:t,fetchStatus:"fetching"})))i.set(s.queryHash,e);(0,s.MX)(e,t)}function f(e=(0,r.getScopeFor)("user")){return e?(0,a.getQueryClient)().getQueryData((0,o.Xh)(e,"records","list"))??d:d}function y(e=(0,r.getScopeFor)("user")){return!!e&&void 0!==(0,a.getQueryClient)().getQueryData((0,o.Xh)(e,"records","list"))}function v(e,t=(0,r.getScopeFor)("user")){if(t)return(0,a.getQueryClient)().getQueryData((0,o.Xh)(t,"records","detail",e))??void 0}function b(e=(0,r.getScopeFor)("user")){return e?Object.fromEntries((0,a.getQueryClient)().getQueriesData({queryKey:(0,o.Xh)(e,"records","detail")}).flatMap(([e,t])=>t&&"string"==typeof e[4]?[[e[4],t]]:[])):{}}function w(e,t,n=!0){if(!e.isCurrent())return;let i=(0,o.Xh)(e.scope,"records","list");if(n){let n=p(),i=new Map(f(e.scope).map(e=>[e.id,e])),s=new Map(t.map(e=>[e.id,e]));for(let e of new Set([...i.keys(),...s.keys()]))i.get(e)!==s.get(e)&&n?.rows.add(e)}n&&h(e,i),void 0===(0,a.getQueryClient)().getQueryData(i)?(0,s.GG)(e,i,t):(0,s.L4)(e,i,()=>t)}function S(e,t,n=!0){let i=R();if(!i?.isCurrent())return;y(i.scope)&&w(i,f(i.scope).map(n=>n.id===e?{...n,...t}:n),n);let s=v(e,i.scope);s&&T(i,{...s,...t},n)}function I(e,t=!0){let n=R();if(n?.isCurrent())for(let i of(y(n.scope)&&w(n,f(n.scope).map(e),t),Object.values(b(n.scope)))){let s=e(i);s!==i&&T(n,s,t)}}function C(e,t){let n=R();if(!n?.isCurrent())return;let i=y(n.scope)?f(n.scope):[];w(n,i.some(t=>t.id===e.id)?i:[e,...i]),v(e.id,n.scope)||T(n,t)}function k(e){let t=R();if(!t?.isCurrent())return;let n=(0,i.Ck)({...e,is_archived:e.is_archived??!1,is_favorite:e.is_favorite??!1}),s=y(t.scope)?f(t.scope):[];
788w(t,s.some(e=>e.id===n.id)?s:[n,...s],!1)}function T(e,t,n=!0){if(!e.isCurrent())return;let i=(0,a.getQueryClient)(),r={queryKey:(0,o.Xh)(e.scope,"records","detail",t.id),gcTime:1/0};n&&p()?.rows.add(t.id),i.getQueryCache().build(i,{queryKey:r.queryKey,gcTime:r.gcTime}),n&&h(e,r.queryKey),void 0===i.getQueryData(r.queryKey)?(0,s.GG)(e,r.queryKey,t):(0,s.L4)(e,r.queryKey,()=>t)}async function A(e){if(!e.isCurrent())return;let t=(0,a.getQueryClient)(),n=p();if(n?.pending)return;let i=(0,o.Xh)(e.scope,"records","list");h(e,i);let s=_.get(t),r=new Set;for(let[t,n]of s??[]){if(!n.isCurrent()){s?.delete(t);continue}n.scope.userId===e.scope.userId&&r.add(t)}let l=t.getQueryCache().findAll({predicate:e=>r.has(e.queryHash)||e.queryKey.length===i.length&&e.queryKey.every((e,t)=>e===i[t])});await Promise.all(l.map(e=>t.cancelQueries({queryKey:e.queryKey,exact:!0}))),!e.isCurrent()||p()?.pending||(n&&u.get(t)===n&&u.delete(t),await Promise.all(l.map(async n=>{await t.invalidateQueries({queryKey:n.queryKey,exact:!0,refetchType:"none"}),!(!e.isCurrent()||p()?.pending)&&(r.has(n.queryHash)||n.isActive())&&(s?.delete(n.queryHash),await t.fetchQuery({...n.options,queryKey:n.queryKey,staleTime:0}).catch(()=>void 0))})))}function E(e,t){e.isCurrent()&&(0,s.L4)(e,(0,o.Xh)(e.scope,"records","detail",t),()=>null)}function D(e){return e.map(e=>({id:e.id,user_id:e.user_id,pet_name:e.pet_name,visit_date:e.visit_date,document_type:e.document_type,is_favorite:e.is_favorite,is_archived:e.is_archived,hospital_name:e.hospital_name,vet_name:e.vet_name,vet_id:e.vet_id,signalment:e.signalment,context_record_id:e.context_record_id,context_chain_ids:e.context_chain_ids,created_at:e.created_at,updated_at:e.updated_at,attachments:e.attachments?.map(e=>({type:e.type,attachmentType:e.attachmentType})),lesion_photos:e.lesion_photos?.length?[{}]:void 0,audio_duration_seconds:e.audio_duration_seconds??null,help_requested_at:e.help_requested_at??null,discharge_chat_active:e.discharge_chat_active??null,hospitalization_id:e.hospitalization_id??null,had_hospitalization:e.had_hospitalization??null,viewed_at:e.viewed_at??null,tags:e.tags??null,patient_id:e.patient_id??null,pims_consult_id:e.pims_consult_id??null}))}function O(){let e=(0,a.getQueryClient)();c.has(e)||(c.add(e),(0,l.JC)({id:"records.list",version:1,kind:"user",queryKey:e=>(0,o.Xh)(e,"records","list"),project:D,restore:e=>e.map(e=>(0,i.Ck)(e))}))}function R(){let e=(0,r.getScopeFor)("user");return e?(0,s.Lt)(e,"user"):null}},99605:(e,t,n)=>{n.d(t,{bc:()=>r,fb:()=>a,u_:()=>s});var i=n(30969);let s=["ai_memory_soap","ai_memory_discharge","ai_memory_communication","ai_memory_general","style_preferences","style_preferences_general","translator_speaking_rate","translator_default_language","translator_default_voice_gender","translator_default_clinician_language","tts_provider","selected_patient_template_set_id","selected_communication_template_id","selected_general_template_id","selected_system_prompt_id","selected_recording_patient_template_set_id"];function a(e){let t={},n={};for(let[i,a]of Object.entries(e))s.includes(i)?t[i]=a:n[i]=a;return{vetUpdates:t,sharedUpdates:n}}let r={ai_memory_soap:"",ai_memory_discharge:"",ai_memory_communication:"",ai_memory_general:"",style_preferences:i.a$.style_preferences,style_preferences_general:i.a$.style_preferences_general,translator_speaking_rate:1.15,translator_default_language:"Spanish",translator_default_voice_gender:"male",translator_default_clinician_language:"English",tts_provider:"soniox",selected_patient_template_set_id:"default-soap",selected_recording_patient_template_set_id:"default-soap",selected_communication_template_id:"default-communication",selected_general_template_id:"default-notes",selected_system_prompt_id:"default-general"}}}]);
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.