84 lines
2.2 KiB
TypeScript
84 lines
2.2 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,
|
|
ILifeStyleResponse,
|
|
PROMPT_NAME,
|
|
} from '../../_components/ai/types';
|
|
import { updateLifeStyle } from './ai-actions';
|
|
|
|
const failedResponse = {
|
|
response: {
|
|
lifestyle: [],
|
|
summary: null,
|
|
},
|
|
dateCreated: new Date().toISOString(),
|
|
};
|
|
|
|
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 query = supabaseClient
|
|
.schema('medreport')
|
|
.from('ai_responses')
|
|
.select('response, latest_data_change')
|
|
.eq('account_id', account.id)
|
|
.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);
|
|
return failedResponse;
|
|
}
|
|
|
|
if (data?.response) {
|
|
return {
|
|
response: JSON.parse(data.response as string),
|
|
dateCreated: data.latest_data_change,
|
|
};
|
|
} else {
|
|
const newLifeStyle = await updateLifeStyle({
|
|
account,
|
|
analysisResponses,
|
|
isDoctorView,
|
|
aiResponseTimestamp,
|
|
});
|
|
|
|
return { response: newLifeStyle, dateCreated: aiResponseTimestamp };
|
|
}
|
|
}
|
|
export const loadLifeStyle = cache(lifeStyleLoader);
|