add doctor feedback
This commit is contained in:
27
app/doctor/_components/analysis-fallback.tsx
Normal file
27
app/doctor/_components/analysis-fallback.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
'use server';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { Spinner } from '@kit/ui/makerkit/spinner';
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Progress } from '@kit/ui/shadcn/progress';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
const AnalysisFallback = ({
|
||||
progress,
|
||||
progressTextKey,
|
||||
}: {
|
||||
progress: number;
|
||||
progressTextKey: string;
|
||||
}) => {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-10">
|
||||
<Trans i18nKey={progressTextKey} />
|
||||
<Spinner />
|
||||
<Progress value={progress} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default withI18n(AnalysisFallback);
|
||||
@@ -16,6 +16,7 @@ import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import { Spinner } from '@kit/ui/makerkit/spinner';
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import {
|
||||
@@ -32,12 +33,21 @@ const AnalysisFeedback = ({
|
||||
feedback,
|
||||
patient,
|
||||
order,
|
||||
aiDoctorFeedback,
|
||||
timestamp,
|
||||
recommendations,
|
||||
isRecommendationsEdited,
|
||||
}: {
|
||||
feedback?: DoctorFeedback;
|
||||
patient: Patient;
|
||||
order: Order;
|
||||
aiDoctorFeedback?: string;
|
||||
timestamp?: string;
|
||||
recommendations: string[];
|
||||
isRecommendationsEdited: boolean;
|
||||
}) => {
|
||||
const [isDraftSubmitting, setIsDraftSubmitting] = useState(false);
|
||||
const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false);
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
const { data: user } = useUser();
|
||||
const queryClient = useQueryClient();
|
||||
@@ -46,7 +56,7 @@ const AnalysisFeedback = ({
|
||||
resolver: zodResolver(doctorAnalysisFeedbackFormSchema),
|
||||
reValidateMode: 'onChange',
|
||||
defaultValues: {
|
||||
feedbackValue: feedback?.value ?? '',
|
||||
feedbackValue: feedback?.value ?? aiDoctorFeedback ?? '',
|
||||
userId: patient.userId,
|
||||
},
|
||||
});
|
||||
@@ -71,23 +81,30 @@ const AnalysisFeedback = ({
|
||||
data: DoctorAnalysisFeedbackForm,
|
||||
status: 'DRAFT' | 'COMPLETED',
|
||||
) => {
|
||||
setIsConfirmOpen(false);
|
||||
setIsSubmittingFeedback(true);
|
||||
|
||||
const result = await giveFeedbackAction({
|
||||
...data,
|
||||
analysisOrderId: order.analysisOrderId,
|
||||
status,
|
||||
patientId: patient.userId,
|
||||
timestamp,
|
||||
recommendations,
|
||||
isRecommendationsEdited,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
return toast.error(<Trans i18nKey="common:genericServerError" />);
|
||||
}
|
||||
|
||||
setIsSubmittingFeedback(false);
|
||||
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => query.queryKey.includes('doctor-jobs'),
|
||||
});
|
||||
|
||||
toast.success(<Trans i18nKey={'doctor:updateFeedbackSuccess'} />);
|
||||
|
||||
return setIsConfirmOpen(false);
|
||||
return toast.success(<Trans i18nKey={'doctor:updateFeedbackSuccess'} />);
|
||||
};
|
||||
|
||||
const confirmComplete = form.handleSubmit(async (data) => {
|
||||
@@ -96,10 +113,6 @@ const AnalysisFeedback = ({
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3>
|
||||
<Trans i18nKey="doctor:feedback" />
|
||||
</h3>
|
||||
<p>{feedback?.value ?? '-'}</p>
|
||||
{!isReadOnly && (
|
||||
<Form {...form}>
|
||||
<form className="space-y-4 lg:w-1/2">
|
||||
@@ -109,7 +122,11 @@ const AnalysisFeedback = ({
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<Textarea {...field} disabled={isReadOnly} />
|
||||
<Textarea
|
||||
className="min-h-[200px]"
|
||||
{...field}
|
||||
disabled={isDraftSubmitting || isSubmittingFeedback}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -136,7 +153,11 @@ const AnalysisFeedback = ({
|
||||
}
|
||||
className="xs:w-1/4 w-full"
|
||||
>
|
||||
{isDraftSubmitting || form.formState.isSubmitting ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Trans i18nKey="common:save" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { capitalize } from 'lodash';
|
||||
|
||||
@@ -23,20 +25,40 @@ import { bmiFromMetric } from '~/lib/utils';
|
||||
import AnalysisFeedback from './analysis-feedback';
|
||||
import DoctorAnalysisWrapper from './doctor-analysis-wrapper';
|
||||
import DoctorJobSelect from './doctor-job-select';
|
||||
import DoctorRecommendedAnalyses from './doctor-recommended-analyses';
|
||||
|
||||
export default function AnalysisView({
|
||||
patient,
|
||||
order,
|
||||
analyses,
|
||||
feedback,
|
||||
aiDoctorFeedback,
|
||||
recommendations,
|
||||
availableAnalyses,
|
||||
timestamp,
|
||||
}: {
|
||||
patient: Patient;
|
||||
order: Order;
|
||||
analyses: AnalysisResponse[];
|
||||
feedback?: DoctorFeedback;
|
||||
aiDoctorFeedback?: string;
|
||||
recommendations?: string[];
|
||||
availableAnalyses?: string[];
|
||||
timestamp?: string;
|
||||
}) {
|
||||
const { data: user } = useUser();
|
||||
const queryClient = useQueryClient();
|
||||
const [recommendedAnalyses, setRecommendedAnalyses] = useState<string[]>(
|
||||
recommendations ?? [],
|
||||
);
|
||||
const isRecommendationsEdited = useMemo(() => {
|
||||
if (recommendedAnalyses.length !== recommendations?.length) return true;
|
||||
const sa = new Set(recommendedAnalyses),
|
||||
sb = new Set(recommendations);
|
||||
if (sa.size !== sb.size) return true;
|
||||
for (const v of sa) if (!sb.has(v)) return true;
|
||||
return false;
|
||||
}, [recommendations, recommendedAnalyses]);
|
||||
|
||||
const languageNames = useCurrentLocaleLanguageNames();
|
||||
|
||||
@@ -154,7 +176,28 @@ export default function AnalysisView({
|
||||
})}
|
||||
</div>
|
||||
{order.isPackage && (
|
||||
<AnalysisFeedback order={order} patient={patient} feedback={feedback} />
|
||||
<>
|
||||
<h3>
|
||||
<Trans i18nKey="doctor:feedback" />
|
||||
</h3>
|
||||
<p>{feedback?.value ?? '-'}</p>
|
||||
<div className="flex flex-col gap-4 lg:flex-row">
|
||||
<AnalysisFeedback
|
||||
order={order}
|
||||
patient={patient}
|
||||
feedback={feedback}
|
||||
aiDoctorFeedback={aiDoctorFeedback}
|
||||
timestamp={timestamp}
|
||||
recommendations={recommendedAnalyses}
|
||||
isRecommendationsEdited={isRecommendationsEdited}
|
||||
/>
|
||||
<DoctorRecommendedAnalyses
|
||||
recommendedAnalyses={recommendedAnalyses}
|
||||
availableAnalyses={availableAnalyses}
|
||||
setRecommendedAnalyses={setRecommendedAnalyses}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
53
app/doctor/_components/doctor-recommended-analyses.tsx
Normal file
53
app/doctor/_components/doctor-recommended-analyses.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
'use client';
|
||||
|
||||
import React, { Dispatch, SetStateAction } from 'react';
|
||||
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
|
||||
const DoctorRecommendedAnalyses = ({
|
||||
recommendedAnalyses,
|
||||
availableAnalyses,
|
||||
setRecommendedAnalyses,
|
||||
}: {
|
||||
recommendedAnalyses?: string[];
|
||||
availableAnalyses?: string[];
|
||||
setRecommendedAnalyses: Dispatch<SetStateAction<string[]>>;
|
||||
}) => {
|
||||
if (availableAnalyses?.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h5>
|
||||
<Trans i18nKey="doctor:recommendedAnalyses" />
|
||||
</h5>
|
||||
<div className="mt-4 flex gap-2">
|
||||
{availableAnalyses?.map((analysis, index) => {
|
||||
return (
|
||||
<Button
|
||||
size="sm"
|
||||
key={`${index}-analysis-feedback-list`}
|
||||
variant={
|
||||
recommendedAnalyses?.includes(analysis) ? 'default' : 'outline'
|
||||
}
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setRecommendedAnalyses((prev: string[]) =>
|
||||
prev.includes(analysis)
|
||||
? prev.filter((x) => x !== analysis)
|
||||
: [...prev, analysis],
|
||||
)
|
||||
}
|
||||
>
|
||||
{analysis}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DoctorRecommendedAnalyses;
|
||||
@@ -0,0 +1,90 @@
|
||||
'use server';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { AnalysisResponses } from '@/app/home/(user)/_components/ai/types';
|
||||
import { OrderAnalysisCard } from '@/app/home/(user)/_components/order-analyses-cards';
|
||||
import { loadLifeStyle } from '@/app/home/(user)/_lib/server/load-life-style';
|
||||
import { loadRecommendations } from '@/app/home/(user)/_lib/server/load-recommendations';
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
import { AnalysisResultDetails } from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
import {
|
||||
loadDoctorFeedback,
|
||||
prepareFeedback,
|
||||
} from '../_lib/server/load-doctor-feedback';
|
||||
import AnalysisView from './analysis-view';
|
||||
|
||||
async function NewAnalysisRecommendationsLoader({
|
||||
analysisResultDetails,
|
||||
account,
|
||||
analysisResponses,
|
||||
currentAIResponseTimestamp,
|
||||
analyses,
|
||||
patient,
|
||||
}: {
|
||||
currentAIResponseTimestamp: string;
|
||||
account: AccountWithParams | null;
|
||||
analysisResponses: AnalysisResponses;
|
||||
analysisResultDetails: AnalysisResultDetails;
|
||||
analyses: OrderAnalysisCard[];
|
||||
patient: AccountWithParams | null;
|
||||
}) {
|
||||
if (!analysisResultDetails.order.isPackage) {
|
||||
return (
|
||||
<AnalysisView
|
||||
patient={analysisResultDetails.patient}
|
||||
order={analysisResultDetails.order}
|
||||
analyses={analysisResultDetails.analysisResponse}
|
||||
feedback={analysisResultDetails.doctorFeedback}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const [lifeStyle, recommendations, aiFeedback] = await Promise.all([
|
||||
loadLifeStyle({
|
||||
account: patient,
|
||||
analysisResponses,
|
||||
isDoctorView: true,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
}),
|
||||
loadRecommendations({
|
||||
account: patient,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
isDoctorView: true,
|
||||
analyses,
|
||||
}),
|
||||
loadDoctorFeedback(
|
||||
analysisResultDetails.patient,
|
||||
analysisResultDetails.analysisResponse,
|
||||
currentAIResponseTimestamp,
|
||||
),
|
||||
]);
|
||||
|
||||
const feedback = prepareFeedback({
|
||||
aiResponse: aiFeedback,
|
||||
recommendations,
|
||||
lifeStyleSummary: lifeStyle.response.summary,
|
||||
patientName: analysisResultDetails.patient.firstName,
|
||||
doctorName: `${account?.name} ${account?.last_name}`,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
});
|
||||
|
||||
return (
|
||||
<AnalysisView
|
||||
patient={analysisResultDetails.patient}
|
||||
order={analysisResultDetails.order}
|
||||
analyses={analysisResultDetails.analysisResponse}
|
||||
feedback={analysisResultDetails.doctorFeedback}
|
||||
aiDoctorFeedback={feedback}
|
||||
availableAnalyses={analyses.map((analysis) => analysis.title)}
|
||||
recommendations={recommendations}
|
||||
timestamp={currentAIResponseTimestamp}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(NewAnalysisRecommendationsLoader);
|
||||
55
app/doctor/_components/prepare-ai-parameters.tsx
Normal file
55
app/doctor/_components/prepare-ai-parameters.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use server';
|
||||
|
||||
import React, { Suspense } from 'react';
|
||||
|
||||
import { loadAnalyses } from '@/app/home/(user)/_lib/server/load-analyses';
|
||||
import {
|
||||
loadCurrentUserAccount,
|
||||
loadUserAccount,
|
||||
} from '@/app/home/(user)/_lib/server/load-user-account';
|
||||
import { AnalysisResultDetails } from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
|
||||
import { createUserAnalysesApi } from '@/packages/features/user-analyses/src/server/api';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { getLatestResponseTime } from '~/lib/utils';
|
||||
|
||||
import AnalysisFallback from './analysis-fallback';
|
||||
import NewAnalysisRecommendationsLoader from './new-analysis-recommendations-loader';
|
||||
|
||||
async function PrepareAIParameters({
|
||||
analysisResultDetails,
|
||||
}: {
|
||||
analysisResultDetails: AnalysisResultDetails;
|
||||
}) {
|
||||
const { analyses } = await loadAnalyses();
|
||||
const { account: doctorAccount } = await loadCurrentUserAccount();
|
||||
const patientAccount = await loadUserAccount(
|
||||
analysisResultDetails.patient.userId,
|
||||
);
|
||||
const client = getSupabaseServerClient();
|
||||
const userAnalysesApi = createUserAnalysesApi(client);
|
||||
const analysisResponses = await userAnalysesApi.getAllUserAnalysisResponses(
|
||||
patientAccount.id,
|
||||
);
|
||||
const currentAIResponseTimestamp = getLatestResponseTime(analysisResponses);
|
||||
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<AnalysisFallback progress={66} progressTextKey="doctor:loadFeedback" />
|
||||
}
|
||||
>
|
||||
<NewAnalysisRecommendationsLoader
|
||||
account={doctorAccount}
|
||||
currentAIResponseTimestamp={currentAIResponseTimestamp}
|
||||
analysisResponses={analysisResponses}
|
||||
analysisResultDetails={analysisResultDetails}
|
||||
analyses={analyses}
|
||||
patient={patientAccount}
|
||||
/>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(PrepareAIParameters);
|
||||
98
app/doctor/_lib/server/load-doctor-feedback.ts
Normal file
98
app/doctor/_lib/server/load-doctor-feedback.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { cache } from 'react';
|
||||
|
||||
import { PROMPT_NAME } from '@/app/home/(user)/_components/ai/types';
|
||||
import { generateDoctorFeedback } from '@/app/home/(user)/_lib/server/ai-actions';
|
||||
import {
|
||||
AnalysisResponse,
|
||||
Patient,
|
||||
} from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
|
||||
import { getLogger } from '@/packages/shared/src/logger';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
export const loadDoctorFeedback = cache(doctorFeedbackLoader);
|
||||
|
||||
const PLACEHOLDER = {
|
||||
ANALYSES: 'SOOVITATUD_ANALYYSID_PLACEHOLDER',
|
||||
LIFE_STYLE_SUMMARY: 'ELUSTIILI_KOKKUVOTTE_PLACEHOLDER',
|
||||
PATIENT_NAME: 'PATSIENDI_NIMI_PLACEHOLDER',
|
||||
DOCTOR_NAME: 'ARSTI_NIMI_PLACEHOLDER',
|
||||
ANALYSES_DATE: 'ANALYYSI_KUUPAEV_PLACEHOLDER',
|
||||
};
|
||||
|
||||
export const prepareFeedback = ({
|
||||
aiResponse,
|
||||
recommendations,
|
||||
lifeStyleSummary,
|
||||
patientName,
|
||||
doctorName,
|
||||
aiResponseTimestamp,
|
||||
}: {
|
||||
aiResponse: string;
|
||||
recommendations?: string[];
|
||||
lifeStyleSummary: string | null;
|
||||
patientName: string;
|
||||
doctorName: string;
|
||||
aiResponseTimestamp: string;
|
||||
}) => {
|
||||
const recommendationsList = recommendations
|
||||
? recommendations.map((analysis) => `${analysis}`).join('\n')
|
||||
: '';
|
||||
const feedback = aiResponse
|
||||
.replace(PLACEHOLDER.ANALYSES, recommendationsList)
|
||||
.replace(PLACEHOLDER.LIFE_STYLE_SUMMARY, lifeStyleSummary ?? '')
|
||||
.replace(PLACEHOLDER.PATIENT_NAME, patientName)
|
||||
.replace(PLACEHOLDER.DOCTOR_NAME, doctorName)
|
||||
.replace(
|
||||
PLACEHOLDER.ANALYSES_DATE,
|
||||
new Date(aiResponseTimestamp).toLocaleString(),
|
||||
);
|
||||
|
||||
return feedback;
|
||||
};
|
||||
|
||||
async function doctorFeedbackLoader(
|
||||
patient: Patient | null,
|
||||
analysisResponses: AnalysisResponse[],
|
||||
aiResponseTimestamp: string,
|
||||
): Promise<string> {
|
||||
const logger = await getLogger();
|
||||
if (!patient?.personalCode) {
|
||||
return '';
|
||||
}
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
|
||||
logger.info(
|
||||
{
|
||||
aiResponseTimestamp,
|
||||
patientId: patient.userId,
|
||||
},
|
||||
'Attempting to receive existing doctor feedback',
|
||||
);
|
||||
|
||||
const { data, error } = await supabaseClient
|
||||
.schema('medreport')
|
||||
.from('ai_responses')
|
||||
.select('*')
|
||||
.eq('account_id', patient.userId)
|
||||
.eq('prompt_name', PROMPT_NAME.FEEDBACK)
|
||||
.eq('latest_data_change', aiResponseTimestamp)
|
||||
.limit(1)
|
||||
.maybeSingle();
|
||||
|
||||
logger.info({ data: !!data }, 'Existing doctor feedback');
|
||||
|
||||
if (error) {
|
||||
console.error('Error fetching AI response from DB: ', error);
|
||||
return '';
|
||||
}
|
||||
|
||||
if (data?.response) {
|
||||
return data.response as string;
|
||||
} else {
|
||||
return await generateDoctorFeedback({
|
||||
patient,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
import { cache } from 'react';
|
||||
import { Suspense, cache } from 'react';
|
||||
|
||||
import { getAnalysisResultsForDoctor } from '@kit/doctor/services/doctor-analysis.service';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import {
|
||||
DoctorPageViewAction,
|
||||
createDoctorPageViewLog,
|
||||
} from '~/lib/services/audit/doctorPageView.service';
|
||||
|
||||
import AnalysisView from '../../_components/analysis-view';
|
||||
import AnalysisFallback from '../../_components/analysis-fallback';
|
||||
import { DoctorGuard } from '../../_components/doctor-guard';
|
||||
import PrepareAiParameters from '../../_components/prepare-ai-parameters';
|
||||
|
||||
async function AnalysisPage({
|
||||
params,
|
||||
@@ -37,16 +39,20 @@ async function AnalysisPage({
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody className="px-12">
|
||||
<AnalysisView
|
||||
patient={analysisResultDetails.patient}
|
||||
order={analysisResultDetails.order}
|
||||
analyses={analysisResultDetails.analysisResponse}
|
||||
feedback={analysisResultDetails.doctorFeedback}
|
||||
<Suspense
|
||||
fallback={
|
||||
<AnalysisFallback
|
||||
progress={33}
|
||||
progressTextKey="doctor:loadParameters"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PrepareAiParameters analysisResultDetails={analysisResultDetails} />
|
||||
</Suspense>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DoctorGuard(AnalysisPage);
|
||||
export default DoctorGuard(withI18n(AnalysisPage));
|
||||
const loadResult = cache(getAnalysisResultsForDoctor);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import React from 'react';
|
||||
|
||||
import { Circle } from 'lucide-react';
|
||||
import { createUserAnalysesApi } from '@/packages/features/user-analyses/src/server/api';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import { cn } from '@kit/ui/lib/utils';
|
||||
import { PageBody } from '@kit/ui/makerkit/page';
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Skeleton } from '@kit/ui/shadcn/skeleton';
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
PageViewAction,
|
||||
createPageViewLog,
|
||||
} from '~/lib/services/audit/pageView.service';
|
||||
import { getLatestResponseTime } from '~/lib/utils';
|
||||
|
||||
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
||||
import { loadLifeStyle } from '../../_lib/server/load-life-style';
|
||||
@@ -31,14 +32,22 @@ async function LifeStylePage() {
|
||||
if (!account) {
|
||||
return null;
|
||||
}
|
||||
const data = await loadLifeStyle(account);
|
||||
const client = getSupabaseServerClient();
|
||||
const userAnalysesApi = createUserAnalysesApi(client);
|
||||
const analysisResponses = await userAnalysesApi.getAllUserAnalysisResponses();
|
||||
const currentAIResponseTimestamp = getLatestResponseTime(analysisResponses);
|
||||
const { response } = await loadLifeStyle({
|
||||
account,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
});
|
||||
|
||||
await createPageViewLog({
|
||||
accountId: account.id,
|
||||
action: PageViewAction.VIEW_LIFE_STYLE,
|
||||
});
|
||||
|
||||
if (!data.lifestyle) {
|
||||
if (!response.lifestyle) {
|
||||
return <Skeleton className="mt-10 h-10 w-full" />;
|
||||
}
|
||||
|
||||
@@ -51,16 +60,10 @@ async function LifeStylePage() {
|
||||
|
||||
<PageBody>
|
||||
<div className="mt-8">
|
||||
{data.lifestyle.map(({ title, description, score }, index) => (
|
||||
{response.lifestyle.map(({ title, description }, index) => (
|
||||
<React.Fragment key={`${index}-${title}`}>
|
||||
<div className="flex items-center gap-2">
|
||||
<h3>{title}</h3>
|
||||
<Circle
|
||||
className={cn('text-success fill-success size-6', {
|
||||
'text-warning fill-warning': score === 1,
|
||||
'text-destructive fill-destructive': score === 2,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<p className="font-regular py-4">{description}</p>
|
||||
</React.Fragment>
|
||||
|
||||
@@ -41,7 +41,10 @@ const AIBlocks = async ({
|
||||
return (
|
||||
<Suspense fallback={<RecommendationsSkeleton />}>
|
||||
<LifeStyleCard account={account} analysisResponses={analysisResponses} />
|
||||
<Recommendations account={account} />
|
||||
<Recommendations
|
||||
account={account}
|
||||
analysisResponses={analysisResponses}
|
||||
/>
|
||||
</Suspense>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -12,6 +12,8 @@ import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import { Card, CardHeader } from '@kit/ui/shadcn/card';
|
||||
|
||||
import { getLatestResponseTime } from '~/lib/utils';
|
||||
|
||||
import { loadLifeStyle } from '../../_lib/server/load-life-style';
|
||||
import { AnalysisResponses } from './types';
|
||||
|
||||
@@ -22,21 +24,31 @@ const LifeStyleCard = async ({
|
||||
account: AccountWithParams;
|
||||
analysisResponses?: AnalysisResponses;
|
||||
}) => {
|
||||
const data = await loadLifeStyle(account, analysisResponses);
|
||||
const aiResponseTimestamp = getLatestResponseTime(analysisResponses);
|
||||
const { response, dateCreated } = await loadLifeStyle({
|
||||
account,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp,
|
||||
});
|
||||
|
||||
return (
|
||||
<Card variant="gradient-success" className="flex flex-col justify-between">
|
||||
<CardHeader className="flex-row justify-between">
|
||||
<h5>
|
||||
<div>
|
||||
<span className="text-xs">
|
||||
{new Date(dateCreated).toLocaleString()}
|
||||
</span>
|
||||
<h5 className="flex flex-col">
|
||||
<Trans i18nKey="dashboard:heroCard.lifeStyle.title" />
|
||||
</h5>
|
||||
</div>
|
||||
<Link href={pathsConfig.app.lifeStyle}>
|
||||
<Button size="icon" variant="outline" className="px-2 text-black">
|
||||
<ChevronRight className="size-4 stroke-2" />
|
||||
</Button>
|
||||
</Link>
|
||||
</CardHeader>
|
||||
<span className="text-primary p-4 text-sm">{data.summary}</span>
|
||||
<span className="text-primary p-4 text-sm">{response.summary}</span>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -4,18 +4,29 @@ import React from 'react';
|
||||
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
|
||||
import { getLatestResponseTime } from '~/lib/utils';
|
||||
|
||||
import { loadAnalyses } from '../../_lib/server/load-analyses';
|
||||
import { loadRecommendations } from '../../_lib/server/load-recommendations';
|
||||
import OrderAnalysesCards from '../order-analyses-cards';
|
||||
import { AnalysisResponses } from './types';
|
||||
|
||||
export default async function Recommendations({
|
||||
account,
|
||||
analysisResponses,
|
||||
}: {
|
||||
account: AccountWithParams;
|
||||
analysisResponses?: AnalysisResponses;
|
||||
}) {
|
||||
const { analyses, countryCode } = await loadAnalyses();
|
||||
|
||||
const analysisRecommendations = await loadRecommendations(account);
|
||||
const currentAIResponseTimestamp = getLatestResponseTime(analysisResponses);
|
||||
const analysisRecommendations = await loadRecommendations({
|
||||
account,
|
||||
analyses,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
});
|
||||
const orderAnalyses = analyses.filter((analysis) =>
|
||||
analysisRecommendations.includes(analysis.title),
|
||||
);
|
||||
|
||||
@@ -12,6 +12,7 @@ export interface ILifeStyleResponse {
|
||||
export enum PROMPT_NAME {
|
||||
LIFE_STYLE = 'Life Style',
|
||||
ANALYSIS_RECOMMENDATIONS = 'Analysis Recommendations',
|
||||
FEEDBACK = 'Doctor Feedback',
|
||||
}
|
||||
|
||||
export type AnalysisResponses =
|
||||
|
||||
@@ -82,8 +82,8 @@ export function HomeMobileNavigation(props: {
|
||||
const hasDoctorRole =
|
||||
personalAccountData?.application_role === ApplicationRoleEnum.Doctor;
|
||||
|
||||
return hasDoctorRole && hasTotpFactor;
|
||||
}, [user, personalAccountData, hasTotpFactor]);
|
||||
return hasDoctorRole;
|
||||
}, [personalAccountData]);
|
||||
|
||||
const cartQuantityTotal =
|
||||
props.cart?.items?.reduce((acc, item) => acc + item.quantity, 0) ?? 0;
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
'use server';
|
||||
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
import {
|
||||
AnalysisResponse,
|
||||
Patient,
|
||||
} from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
|
||||
import { getLogger } from '@/packages/shared/src/logger';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
import OpenAI from 'openai';
|
||||
|
||||
@@ -13,26 +18,16 @@ import {
|
||||
} from '../../_components/ai/types';
|
||||
import { OrderAnalysisCard } from '../../_components/order-analyses-cards';
|
||||
|
||||
async function getLatestResponseTime(items?: AnalysisResponses) {
|
||||
if (!items?.length) return null;
|
||||
|
||||
let latest = null;
|
||||
for (const it of items) {
|
||||
const d = new Date(it.response_time);
|
||||
const t = d.getTime();
|
||||
if (!Number.isNaN(t) && (latest === null || t > latest.getTime())) {
|
||||
latest = d;
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
export async function updateLifeStyle({
|
||||
account,
|
||||
analysisResponses,
|
||||
isDoctorView = false,
|
||||
aiResponseTimestamp,
|
||||
}: {
|
||||
account: AccountWithParams;
|
||||
analysisResponses?: AnalysisResponses;
|
||||
isDoctorView?: boolean;
|
||||
aiResponseTimestamp: string;
|
||||
}): Promise<ILifeStyleResponse> {
|
||||
const LIFE_STYLE_PROMPT_ID = process.env.PROMPT_ID_LIFE_STYLE;
|
||||
if (!LIFE_STYLE_PROMPT_ID || !account?.personal_code) {
|
||||
@@ -65,11 +60,6 @@ export async function updateLifeStyle({
|
||||
?.find((ar) => ar.analysis_name_lab === 'Vitamiin D (25-OH)')
|
||||
?.response_value.toString() || 'unknown';
|
||||
|
||||
const latestResponseTime = await getLatestResponseTime(analysisResponses);
|
||||
const latestISO = latestResponseTime
|
||||
? new Date(latestResponseTime).toISOString()
|
||||
: new Date('2025').toISOString();
|
||||
|
||||
try {
|
||||
const response = await openAIClient.responses.create({
|
||||
store: false,
|
||||
@@ -106,8 +96,9 @@ export async function updateLifeStyle({
|
||||
vitamind,
|
||||
is_smoker: isSmoker.toString(),
|
||||
}),
|
||||
latest_data_change: latestISO,
|
||||
latest_data_change: aiResponseTimestamp,
|
||||
response: response.output_text,
|
||||
is_visible_to_customer: !isDoctorView,
|
||||
});
|
||||
|
||||
const json = JSON.parse(response.output_text);
|
||||
@@ -126,10 +117,12 @@ export async function updateRecommendations({
|
||||
analyses,
|
||||
analysisResponses,
|
||||
account,
|
||||
aiResponseTimestamp,
|
||||
}: {
|
||||
analyses: OrderAnalysisCard[];
|
||||
analysisResponses?: AnalysisResponses;
|
||||
account: AccountWithParams;
|
||||
aiResponseTimestamp: string;
|
||||
}) {
|
||||
const RECOMMENDATIONS_PROMPT_IT =
|
||||
process.env.PROMPT_ID_ANALYSIS_RECOMMENDATIONS;
|
||||
@@ -164,10 +157,6 @@ export async function updateRecommendations({
|
||||
description,
|
||||
title,
|
||||
}));
|
||||
const latestResponseTime = await getLatestResponseTime(analysisResponses);
|
||||
const latestISO = latestResponseTime
|
||||
? new Date(latestResponseTime).toISOString()
|
||||
: new Date('2025').toISOString();
|
||||
|
||||
try {
|
||||
const response = await openAIClient.responses.create({
|
||||
@@ -198,8 +187,9 @@ export async function updateRecommendations({
|
||||
age,
|
||||
weight,
|
||||
}),
|
||||
latest_data_change: latestISO,
|
||||
latest_data_change: aiResponseTimestamp,
|
||||
response: response.output_text,
|
||||
is_visible_to_customer: false,
|
||||
});
|
||||
|
||||
const json = JSON.parse(response.output_text);
|
||||
@@ -210,3 +200,125 @@ export async function updateRecommendations({
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateDoctorFeedback({
|
||||
patient,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp,
|
||||
}: {
|
||||
patient: Patient;
|
||||
analysisResponses: AnalysisResponse[];
|
||||
aiResponseTimestamp: string;
|
||||
}): Promise<string> {
|
||||
const DOCTOR_FEEDBACK_PROMPT_ID = process.env.PROMPT_ID_DOCTOR_FEEDBACK;
|
||||
|
||||
if (!DOCTOR_FEEDBACK_PROMPT_ID) {
|
||||
console.error('No secrets for doctor feedback');
|
||||
return '';
|
||||
}
|
||||
|
||||
const openAIClient = new OpenAI();
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
|
||||
const formattedAnalysisResponses = analysisResponses?.map(
|
||||
({
|
||||
analysis_name,
|
||||
response_value,
|
||||
norm_upper,
|
||||
norm_lower,
|
||||
norm_status,
|
||||
}) => ({
|
||||
name: analysis_name,
|
||||
value: response_value,
|
||||
normUpper: norm_upper,
|
||||
normLower: norm_lower,
|
||||
normStatus: norm_status,
|
||||
}),
|
||||
);
|
||||
|
||||
try {
|
||||
const response = await openAIClient.responses.create({
|
||||
store: false,
|
||||
prompt: {
|
||||
id: DOCTOR_FEEDBACK_PROMPT_ID,
|
||||
variables: {
|
||||
analysesresults: JSON.stringify(formattedAnalysisResponses),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await supabaseClient
|
||||
.schema('medreport')
|
||||
.from('ai_responses')
|
||||
.insert({
|
||||
account_id: patient.userId,
|
||||
prompt_name: PROMPT_NAME.FEEDBACK,
|
||||
prompt_id: DOCTOR_FEEDBACK_PROMPT_ID,
|
||||
input: JSON.stringify({
|
||||
analysesresults: formattedAnalysisResponses,
|
||||
}),
|
||||
latest_data_change: aiResponseTimestamp,
|
||||
response: response.output_text,
|
||||
});
|
||||
|
||||
return response.output_text;
|
||||
} catch (error) {
|
||||
console.error('Error getting doctor feedback: ', error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmPatientAIResponses(
|
||||
patientId: string,
|
||||
aiResponseTimestamp: string,
|
||||
recommendations: string[],
|
||||
isRecommendationsEdited: boolean,
|
||||
) {
|
||||
const logger = await getLogger();
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
|
||||
const { error } = await supabaseClient
|
||||
.schema('medreport')
|
||||
.from('ai_responses')
|
||||
.update({
|
||||
is_visible_to_customer: true,
|
||||
})
|
||||
.eq('latest_data_change', aiResponseTimestamp)
|
||||
.eq('account_id', patientId)
|
||||
.eq('prompt_name', PROMPT_NAME.LIFE_STYLE);
|
||||
|
||||
if (error) {
|
||||
logger.error(
|
||||
{ error, patientId, aiResponseTimestamp },
|
||||
'Failed updating life style',
|
||||
);
|
||||
}
|
||||
|
||||
const { error: _error } = await supabaseClient
|
||||
.schema('medreport')
|
||||
.from('ai_responses')
|
||||
.update({
|
||||
is_visible_to_customer: true,
|
||||
...(isRecommendationsEdited && {
|
||||
response: JSON.stringify({
|
||||
why: 'This was edited by doctor',
|
||||
recommended: recommendations,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.eq('latest_data_change', aiResponseTimestamp)
|
||||
.eq('account_id', patientId)
|
||||
.eq('prompt_name', PROMPT_NAME.ANALYSIS_RECOMMENDATIONS);
|
||||
|
||||
if (_error) {
|
||||
logger.error(
|
||||
{
|
||||
error,
|
||||
aiResponseTimestamp,
|
||||
patientId,
|
||||
isRecommendationsEdited,
|
||||
},
|
||||
'Failed updating analysis recommendations',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { cache } from 'react';
|
||||
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
import { getLogger } from '@/packages/shared/src/logger';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import {
|
||||
@@ -11,28 +12,52 @@ import {
|
||||
import { updateLifeStyle } from './ai-actions';
|
||||
|
||||
const failedResponse = {
|
||||
response: {
|
||||
lifestyle: [],
|
||||
summary: null,
|
||||
},
|
||||
dateCreated: new Date().toISOString(),
|
||||
};
|
||||
|
||||
async function lifeStyleLoader(
|
||||
account: AccountWithParams,
|
||||
analysisResponses?: AnalysisResponses,
|
||||
): Promise<ILifeStyleResponse> {
|
||||
async function lifeStyleLoader({
|
||||
account,
|
||||
analysisResponses,
|
||||
isDoctorView = false,
|
||||
aiResponseTimestamp,
|
||||
}: {
|
||||
account: AccountWithParams | null;
|
||||
analysisResponses?: AnalysisResponses;
|
||||
isDoctorView?: boolean;
|
||||
aiResponseTimestamp: string;
|
||||
}): Promise<{ response: ILifeStyleResponse; dateCreated: string }> {
|
||||
const logger = await getLogger();
|
||||
if (!account?.personal_code) {
|
||||
return failedResponse;
|
||||
}
|
||||
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
const { data, error } = await supabaseClient
|
||||
const query = supabaseClient
|
||||
.schema('medreport')
|
||||
.from('ai_responses')
|
||||
.select('response')
|
||||
.select('response, latest_data_change')
|
||||
.eq('account_id', account.id)
|
||||
.eq('prompt_name', PROMPT_NAME.LIFE_STYLE)
|
||||
.order('latest_data_change', { ascending: false, nullsFirst: false })
|
||||
.limit(1)
|
||||
.maybeSingle();
|
||||
.eq('prompt_name', PROMPT_NAME.LIFE_STYLE);
|
||||
|
||||
if (isDoctorView) {
|
||||
logger.info(
|
||||
{ aiResponseTimestamp, accountId: account.id },
|
||||
'Attempting to receive life style row',
|
||||
);
|
||||
query.eq('latest_data_change', aiResponseTimestamp);
|
||||
} else {
|
||||
query
|
||||
.eq('is_visible_to_customer', true)
|
||||
.order('latest_data_change', { ascending: false, nullsFirst: false });
|
||||
}
|
||||
|
||||
const { data, error } = await query.limit(1).maybeSingle();
|
||||
|
||||
logger.info({ data: !!data }, 'Existing life style row');
|
||||
|
||||
if (error) {
|
||||
console.error('Error fetching AI response from DB: ', error);
|
||||
@@ -40,9 +65,19 @@ async function lifeStyleLoader(
|
||||
}
|
||||
|
||||
if (data?.response) {
|
||||
return JSON.parse(data.response as string);
|
||||
return {
|
||||
response: JSON.parse(data.response as string),
|
||||
dateCreated: data.latest_data_change,
|
||||
};
|
||||
} else {
|
||||
return await updateLifeStyle({ account, analysisResponses });
|
||||
const newLifeStyle = await updateLifeStyle({
|
||||
account,
|
||||
analysisResponses,
|
||||
isDoctorView,
|
||||
aiResponseTimestamp,
|
||||
});
|
||||
|
||||
return { response: newLifeStyle, dateCreated: aiResponseTimestamp };
|
||||
}
|
||||
}
|
||||
export const loadLifeStyle = cache(lifeStyleLoader);
|
||||
|
||||
@@ -1,29 +1,57 @@
|
||||
import { cache } from 'react';
|
||||
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
import { getLogger } from '@/packages/shared/src/logger';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import { PROMPT_NAME } from '../../_components/ai/types';
|
||||
import { AnalysisResponses, PROMPT_NAME } from '../../_components/ai/types';
|
||||
import { OrderAnalysisCard } from '../../_components/order-analyses-cards';
|
||||
import { updateRecommendations } from './ai-actions';
|
||||
|
||||
export const loadRecommendations = cache(recommendationsLoader);
|
||||
|
||||
async function recommendationsLoader(
|
||||
account: AccountWithParams | null,
|
||||
): Promise<string[]> {
|
||||
async function recommendationsLoader({
|
||||
account,
|
||||
isDoctorView = false,
|
||||
analyses,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp,
|
||||
}: {
|
||||
account: AccountWithParams | null;
|
||||
isDoctorView?: boolean;
|
||||
analyses: OrderAnalysisCard[];
|
||||
analysisResponses?: AnalysisResponses;
|
||||
aiResponseTimestamp: string;
|
||||
}): Promise<string[]> {
|
||||
const logger = await getLogger();
|
||||
if (!account?.personal_code) {
|
||||
return [];
|
||||
}
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
|
||||
const { data, error } = await supabaseClient
|
||||
const query = supabaseClient
|
||||
.schema('medreport')
|
||||
.from('ai_responses')
|
||||
.select('*')
|
||||
.eq('account_id', account.id)
|
||||
.eq('prompt_name', PROMPT_NAME.ANALYSIS_RECOMMENDATIONS)
|
||||
.order('latest_data_change', { ascending: false, nullsFirst: false })
|
||||
.limit(1)
|
||||
.maybeSingle();
|
||||
.eq('prompt_name', PROMPT_NAME.ANALYSIS_RECOMMENDATIONS);
|
||||
|
||||
logger.info(
|
||||
{ accountId: account.id, isDoctorView, aiResponseTimestamp },
|
||||
'Attempting to receive existing recommendations',
|
||||
);
|
||||
|
||||
if (isDoctorView) {
|
||||
query.eq('latest_data_change', aiResponseTimestamp);
|
||||
} else {
|
||||
query
|
||||
.eq('is_visible_to_customer', true)
|
||||
.order('latest_data_change', { ascending: false, nullsFirst: false });
|
||||
}
|
||||
|
||||
const { data, error } = await query.limit(1).maybeSingle();
|
||||
|
||||
logger.info({ data: data }, 'Existing recommendations');
|
||||
|
||||
if (error) {
|
||||
console.error('Error fetching AI response from DB: ', error);
|
||||
@@ -33,6 +61,14 @@ async function recommendationsLoader(
|
||||
if (data?.response) {
|
||||
return JSON.parse(data.response as string).recommended;
|
||||
} else {
|
||||
if (isDoctorView) {
|
||||
return await updateRecommendations({
|
||||
account,
|
||||
analyses,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp,
|
||||
});
|
||||
}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
15
lib/utils.ts
15
lib/utils.ts
@@ -1,3 +1,4 @@
|
||||
import { AnalysisResponses } from '@/app/home/(user)/_components/ai/types';
|
||||
import { type ClassValue, clsx } from 'clsx';
|
||||
import Isikukood, { Gender } from 'isikukood';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
@@ -148,3 +149,17 @@ export const findProductTypeIdByHandle = (
|
||||
) => {
|
||||
return productTypes.find(({ metadata }) => metadata?.handle === handle)?.id;
|
||||
};
|
||||
|
||||
export function getLatestResponseTime(items?: AnalysisResponses) {
|
||||
if (!items?.length) return new Date().toISOString();
|
||||
|
||||
let latest = null;
|
||||
for (const it of items) {
|
||||
const d = new Date(it.response_time);
|
||||
const t = d.getTime();
|
||||
if (!Number.isNaN(t) && (latest === null || t > latest.getTime())) {
|
||||
latest = d;
|
||||
}
|
||||
}
|
||||
return latest ? new Date(latest).toISOString() : new Date().toISOString();
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import { revalidatePath } from 'next/cache';
|
||||
|
||||
import { confirmPatientAIResponses } from '@/app/home/(user)/_lib/server/ai-actions';
|
||||
|
||||
import { enhanceAction } from '@kit/next/actions';
|
||||
import { getLogger } from '@kit/shared/logger';
|
||||
|
||||
@@ -104,11 +106,19 @@ export const giveFeedbackAction = doctorAction(
|
||||
userId,
|
||||
analysisOrderId,
|
||||
status,
|
||||
patientId,
|
||||
timestamp,
|
||||
recommendations,
|
||||
isRecommendationsEdited,
|
||||
}: {
|
||||
feedbackValue: string;
|
||||
userId: DoctorAnalysisFeedbackTable['user_id'];
|
||||
analysisOrderId: DoctorAnalysisFeedbackTable['analysis_order_id'];
|
||||
status: DoctorAnalysisFeedbackTable['status'];
|
||||
patientId: string;
|
||||
timestamp?: string;
|
||||
recommendations: string[];
|
||||
isRecommendationsEdited: boolean;
|
||||
}) => {
|
||||
const logger = await getLogger();
|
||||
const isCompleted = status === 'COMPLETED';
|
||||
@@ -122,6 +132,19 @@ export const giveFeedbackAction = doctorAction(
|
||||
await submitFeedback(analysisOrderId, userId, feedbackValue, status);
|
||||
logger.info({ analysisOrderId }, `Successfully submitted feedback`);
|
||||
|
||||
if (timestamp) {
|
||||
logger.info(
|
||||
{ timestamp, patientId },
|
||||
'Attempting to update patient ai responses',
|
||||
);
|
||||
await confirmPatientAIResponses(
|
||||
patientId,
|
||||
timestamp,
|
||||
recommendations,
|
||||
isRecommendationsEdited,
|
||||
);
|
||||
}
|
||||
|
||||
revalidateDoctorAnalysis();
|
||||
|
||||
if (isCompleted) {
|
||||
|
||||
@@ -41,7 +41,8 @@ export const PatientSchema = z.object({
|
||||
email: z.string().nullable(),
|
||||
height: z.number().optional().nullable(),
|
||||
weight: z.number().optional().nullable(),
|
||||
preferred_locale: z.string().nullable(),
|
||||
preferred_locale: z.enum(['en', 'et', 'ru']).nullable(),
|
||||
isSmoker: z.boolean().optional(),
|
||||
});
|
||||
export type Patient = z.infer<typeof PatientSchema>;
|
||||
|
||||
|
||||
@@ -26,6 +26,10 @@ export const doctorAnalysisFeedbackSchema = z.object({
|
||||
userId: z.string().uuid(),
|
||||
analysisOrderId: z.number(),
|
||||
status: FeedbackStatus,
|
||||
patientId: z.string(),
|
||||
timestamp: z.string().optional(),
|
||||
recommendations: z.array(z.string()),
|
||||
isRecommendationsEdited: z.boolean(),
|
||||
});
|
||||
|
||||
export type DoctorAnalysisFeedback = z.infer<
|
||||
|
||||
@@ -424,7 +424,7 @@ export async function getAnalysisResultsForDoctor(
|
||||
.from('accounts')
|
||||
.select(
|
||||
`primary_owner_user_id, id, name, last_name, personal_code, phone, email, preferred_locale,
|
||||
accountParams:account_params(height,weight)`,
|
||||
accountParams:account_params(height,weight,is_smoker)`,
|
||||
)
|
||||
.eq('is_personal_account', true)
|
||||
.eq('primary_owner_user_id', userId)
|
||||
@@ -529,6 +529,7 @@ export async function getAnalysisResultsForDoctor(
|
||||
email,
|
||||
height: accountParams?.height,
|
||||
weight: accountParams?.weight,
|
||||
isSmoker: accountParams?.is_smoker || false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -434,7 +434,9 @@ class UserAnalysesApi {
|
||||
return data;
|
||||
}
|
||||
|
||||
async getAllUserAnalysisResponses(): Promise<
|
||||
async getAllUserAnalysisResponses(
|
||||
userId?: string,
|
||||
): Promise<
|
||||
Database['medreport']['Functions']['get_latest_analysis_response_elements_for_current_user']['Returns']
|
||||
> {
|
||||
const {
|
||||
@@ -448,7 +450,7 @@ class UserAnalysesApi {
|
||||
const { data, error } = await this.client
|
||||
.schema('medreport')
|
||||
.rpc('get_latest_analysis_response_elements_for_current_user', {
|
||||
p_user_id: user.id,
|
||||
p_user_id: userId ?? user.id,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {
|
||||
Bike,
|
||||
Apple,
|
||||
FileLineChart,
|
||||
HeartPulse,
|
||||
LineChart,
|
||||
@@ -57,7 +57,7 @@ const routes = [
|
||||
{
|
||||
label: 'common:routes.lifeStyle',
|
||||
path: pathsConfig.app.lifeStyle,
|
||||
Icon: <Bike className={iconClasses} />,
|
||||
Icon: <Apple className={iconClasses} />,
|
||||
end: true,
|
||||
},
|
||||
],
|
||||
|
||||
@@ -623,6 +623,7 @@ export type Database = {
|
||||
created_at: string
|
||||
id: string
|
||||
input: Json
|
||||
is_visible_to_customer: boolean
|
||||
latest_data_change: string
|
||||
prompt_id: string
|
||||
prompt_name: string
|
||||
@@ -633,6 +634,7 @@ export type Database = {
|
||||
created_at?: string
|
||||
id?: string
|
||||
input: Json
|
||||
is_visible_to_customer?: boolean
|
||||
latest_data_change: string
|
||||
prompt_id: string
|
||||
prompt_name: string
|
||||
@@ -643,6 +645,7 @@ export type Database = {
|
||||
created_at?: string
|
||||
id?: string
|
||||
input?: Json
|
||||
is_visible_to_customer?: boolean
|
||||
latest_data_change?: string
|
||||
prompt_id?: string
|
||||
prompt_name?: string
|
||||
|
||||
@@ -142,6 +142,7 @@
|
||||
"doctor": "Arst",
|
||||
"save": "Salvesta",
|
||||
"saveAsDraft": "Salvesta mustandina",
|
||||
"generateText": "Genereeri tekst",
|
||||
"confirm": "Kinnita",
|
||||
"previous": "Eelmine",
|
||||
"next": "Järgmine",
|
||||
|
||||
@@ -47,5 +47,8 @@
|
||||
"updateFeedbackSuccess": "Kokkuvõte uuendatud",
|
||||
"updateFeedbackLoading": "Kokkuvõtet uuendatakse...",
|
||||
"updateFeedbackError": "Kokkuvõtte uuendamine ebaõnnestus",
|
||||
"feedbackLengthError": "Kokkuvõte peab olema vähemalt 10 tähemärki pikk"
|
||||
"feedbackLengthError": "Kokkuvõte peab olema vähemalt 10 tähemärki pikk",
|
||||
"loadParameters": "Valmistame patsiendi andmed ette. Palun oodake hetk...",
|
||||
"loadFeedback": "Valmistame patsiendi tagasiside teksti. Palun oodake hetk...",
|
||||
"recommendedAnalyses": "Soovita neid Medreporti üksik analüüse"
|
||||
}
|
||||
|
||||
66
supabase/migrations/20251024164100_improve_ai_responses.sql
Normal file
66
supabase/migrations/20251024164100_improve_ai_responses.sql
Normal file
@@ -0,0 +1,66 @@
|
||||
ALTER TABLE medreport.ai_responses
|
||||
ADD COLUMN IF NOT EXISTS is_visible_to_customer boolean NOT NULL DEFAULT false;
|
||||
|
||||
drop policy if exists "ai_responses_select" on medreport.ai_responses;
|
||||
drop policy if exists "ai_responses_insert" on medreport.ai_responses;
|
||||
|
||||
create policy "ai_responses_select"
|
||||
on medreport.ai_responses
|
||||
for select
|
||||
to authenticated
|
||||
using (account_id = auth.uid() OR medreport.is_doctor());
|
||||
|
||||
create policy "ai_responses_insert"
|
||||
on medreport.ai_responses
|
||||
for insert
|
||||
to authenticated
|
||||
with check (account_id = auth.uid() OR medreport.is_doctor());
|
||||
|
||||
drop function if exists medreport.get_latest_analysis_response_elements_for_current_user(uuid);
|
||||
|
||||
create or replace function medreport.get_latest_analysis_response_elements_for_current_user(p_user_id uuid)
|
||||
returns table (
|
||||
analysis_name medreport.analysis_response_elements.analysis_name%type,
|
||||
response_time medreport.analysis_response_elements.response_time%type,
|
||||
norm_upper medreport.analysis_response_elements.norm_upper%type,
|
||||
norm_lower medreport.analysis_response_elements.norm_lower%type,
|
||||
norm_status medreport.analysis_response_elements.norm_status%type,
|
||||
response_value medreport.analysis_response_elements.response_value%type,
|
||||
analysis_name_lab medreport.analysis_elements.analysis_name_lab%type
|
||||
)
|
||||
language sql
|
||||
as $$
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
are.analysis_name,
|
||||
are.response_time,
|
||||
are.norm_upper,
|
||||
are.norm_lower,
|
||||
are.norm_status,
|
||||
are.response_value,
|
||||
ae.analysis_name_lab,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY are.analysis_name
|
||||
ORDER BY are.response_time DESC, are.id DESC
|
||||
) AS rn
|
||||
FROM medreport.analysis_responses ar
|
||||
JOIN medreport.analysis_response_elements are
|
||||
ON are.analysis_response_id = ar.id
|
||||
JOIN medreport.analysis_elements ae
|
||||
ON are.analysis_element_original_id = ae.analysis_id_original
|
||||
WHERE ar.user_id = p_user_id
|
||||
AND ar.order_status IN ('COMPLETED', 'ON_HOLD')
|
||||
)
|
||||
SELECT analysis_name, response_time, norm_upper, norm_lower, norm_status, response_value, analysis_name_lab
|
||||
FROM ranked
|
||||
WHERE rn = 1
|
||||
ORDER BY analysis_name;
|
||||
$$;
|
||||
|
||||
grant execute on function medreport.get_latest_analysis_response_elements_for_current_user(uuid) to authenticated, service_role;
|
||||
|
||||
create policy "ai_responses_update_only_doctor"
|
||||
on medreport.ai_responses
|
||||
for update
|
||||
to authenticated
|
||||
using (medreport.is_doctor());
|
||||
Reference in New Issue
Block a user