75 lines
2.0 KiB
TypeScript
75 lines
2.0 KiB
TypeScript
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 { 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,
|
|
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 query = supabaseClient
|
|
.schema('medreport')
|
|
.from('ai_responses')
|
|
.select('*')
|
|
.eq('account_id', account.id)
|
|
.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);
|
|
return [];
|
|
}
|
|
|
|
if (data?.response) {
|
|
return JSON.parse(data.response as string).recommended;
|
|
} else {
|
|
if (isDoctorView) {
|
|
return await updateRecommendations({
|
|
account,
|
|
analyses,
|
|
analysisResponses,
|
|
aiResponseTimestamp,
|
|
});
|
|
}
|
|
return [];
|
|
}
|
|
}
|