|
|
|
|
@@ -1,8 +1,10 @@
|
|
|
|
|
import 'server-only';
|
|
|
|
|
|
|
|
|
|
import { listOrdersByIds, retrieveOrder } from '@lib/data/orders';
|
|
|
|
|
import { isBefore } from 'date-fns';
|
|
|
|
|
|
|
|
|
|
import { renderDoctorSummaryReceivedEmail } from '@kit/email-templates';
|
|
|
|
|
import { getLogger } from '@kit/shared/logger';
|
|
|
|
|
import { getFullName } from '@kit/shared/utils';
|
|
|
|
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
|
|
|
|
import { createUserAnalysesApi } from '@kit/user-analyses/api';
|
|
|
|
|
@@ -31,7 +33,7 @@ async function enrichAnalysisData(analysisResponses?: AnalysisResponseBase[]) {
|
|
|
|
|
|
|
|
|
|
const [
|
|
|
|
|
{ data: doctorFeedbackItems },
|
|
|
|
|
{ data: medusaOrderItems },
|
|
|
|
|
medusaOrders,
|
|
|
|
|
{ data: analysisResponseElements },
|
|
|
|
|
{ data: accounts },
|
|
|
|
|
] = await Promise.all([
|
|
|
|
|
@@ -43,11 +45,7 @@ async function enrichAnalysisData(analysisResponses?: AnalysisResponseBase[]) {
|
|
|
|
|
'analysis_order_id',
|
|
|
|
|
analysisResponses.map((r) => r.analysis_order_id.id),
|
|
|
|
|
),
|
|
|
|
|
supabase
|
|
|
|
|
.schema('public')
|
|
|
|
|
.from('order_item')
|
|
|
|
|
.select('order_id, item_id(product_title, product_type)')
|
|
|
|
|
.in('order_id', medusaOrderIds),
|
|
|
|
|
listOrdersByIds(medusaOrderIds),
|
|
|
|
|
supabase
|
|
|
|
|
.schema('medreport')
|
|
|
|
|
.from('analysis_response_elements')
|
|
|
|
|
@@ -56,7 +54,7 @@ async function enrichAnalysisData(analysisResponses?: AnalysisResponseBase[]) {
|
|
|
|
|
supabase
|
|
|
|
|
.schema('medreport')
|
|
|
|
|
.from('accounts')
|
|
|
|
|
.select('name, last_name, id, primary_owner_user_id, preferred_locale')
|
|
|
|
|
.select('name,last_name,id,primary_owner_user_id,preferred_locale,slug')
|
|
|
|
|
.in('primary_owner_user_id', userIds),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
@@ -69,7 +67,7 @@ async function enrichAnalysisData(analysisResponses?: AnalysisResponseBase[]) {
|
|
|
|
|
? await supabase
|
|
|
|
|
.schema('medreport')
|
|
|
|
|
.from('accounts')
|
|
|
|
|
.select('name, last_name, id, primary_owner_user_id, preferred_locale')
|
|
|
|
|
.select('name,last_name,id,primary_owner_user_id,preferred_locale,slug')
|
|
|
|
|
.in('primary_owner_user_id', doctorUserIds)
|
|
|
|
|
: { data: [] };
|
|
|
|
|
|
|
|
|
|
@@ -82,21 +80,26 @@ async function enrichAnalysisData(analysisResponses?: AnalysisResponseBase[]) {
|
|
|
|
|
) || [];
|
|
|
|
|
|
|
|
|
|
const firstSampleGivenAt = responseElements.length
|
|
|
|
|
? responseElements.reduce((earliest, current) =>
|
|
|
|
|
new Date(current.response_time) < new Date(earliest.response_time)
|
|
|
|
|
? current
|
|
|
|
|
: earliest,
|
|
|
|
|
)?.response_time
|
|
|
|
|
? responseElements.reduce((earliest, current) => {
|
|
|
|
|
if (current.response_time && earliest.response_time) {
|
|
|
|
|
if (
|
|
|
|
|
new Date(current.response_time) < new Date(earliest.response_time)
|
|
|
|
|
) {
|
|
|
|
|
return current;
|
|
|
|
|
}
|
|
|
|
|
return earliest;
|
|
|
|
|
}
|
|
|
|
|
return current;
|
|
|
|
|
}).response_time
|
|
|
|
|
: null;
|
|
|
|
|
|
|
|
|
|
const medusaOrder = medusaOrderItems?.find(
|
|
|
|
|
({ order_id }) =>
|
|
|
|
|
order_id === analysisResponse.analysis_order_id.medusa_order_id,
|
|
|
|
|
const medusaOrder = medusaOrders?.find(
|
|
|
|
|
({ id }) => id === analysisResponse.analysis_order_id.medusa_order_id,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const patientAccount = allAccounts?.find(
|
|
|
|
|
({ primary_owner_user_id }) =>
|
|
|
|
|
analysisResponse.user_id === primary_owner_user_id,
|
|
|
|
|
({ primary_owner_user_id, slug }) =>
|
|
|
|
|
analysisResponse.user_id === primary_owner_user_id && !slug,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const feedback = doctorFeedbackItems?.find(
|
|
|
|
|
@@ -110,9 +113,10 @@ async function enrichAnalysisData(analysisResponses?: AnalysisResponseBase[]) {
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const order = {
|
|
|
|
|
title: medusaOrder?.item_id.product_title,
|
|
|
|
|
title: medusaOrder?.items?.[0]?.product_title,
|
|
|
|
|
isPackage:
|
|
|
|
|
medusaOrder?.item_id.product_type?.toLowerCase() === 'analysis package',
|
|
|
|
|
medusaOrder?.items?.[0]?.product_type?.toLowerCase() ===
|
|
|
|
|
'analysis package',
|
|
|
|
|
analysisOrderId: analysisResponse.analysis_order_id.id,
|
|
|
|
|
status: analysisResponse.order_status,
|
|
|
|
|
};
|
|
|
|
|
@@ -177,6 +181,7 @@ export async function getUserInProgressResponses({
|
|
|
|
|
`,
|
|
|
|
|
{ count: 'exact' },
|
|
|
|
|
)
|
|
|
|
|
.neq('status', 'ON_HOLD')
|
|
|
|
|
.in('analysis_order_id', analysisOrderIds)
|
|
|
|
|
.range(offset, offset + pageSize - 1)
|
|
|
|
|
.order('created_at', { ascending: false });
|
|
|
|
|
@@ -280,6 +285,7 @@ export async function getOpenResponses({
|
|
|
|
|
`,
|
|
|
|
|
{ count: 'exact' },
|
|
|
|
|
)
|
|
|
|
|
.neq('order_status', 'ON_HOLD')
|
|
|
|
|
.order('created_at', { ascending: false });
|
|
|
|
|
|
|
|
|
|
if (assignedIds.length > 0) {
|
|
|
|
|
@@ -365,47 +371,50 @@ export async function getOtherResponses({
|
|
|
|
|
export async function getAnalysisResultsForDoctor(
|
|
|
|
|
analysisResponseId: number,
|
|
|
|
|
): Promise<AnalysisResultDetails> {
|
|
|
|
|
const logger = await getLogger();
|
|
|
|
|
const ctx = {
|
|
|
|
|
action: 'get-analysis-results-for-doctor',
|
|
|
|
|
analysisResponseId,
|
|
|
|
|
};
|
|
|
|
|
const supabase = getSupabaseServerClient();
|
|
|
|
|
|
|
|
|
|
const { data: analysisResponseElements, error } = await supabase
|
|
|
|
|
.schema('medreport')
|
|
|
|
|
.from(`analysis_response_elements`)
|
|
|
|
|
.select(
|
|
|
|
|
`*,
|
|
|
|
|
analysis_responses(user_id, analysis_order_id(id,medusa_order_id, analysis_element_ids))`,
|
|
|
|
|
)
|
|
|
|
|
.eq('analysis_response_id', analysisResponseId);
|
|
|
|
|
const { data: analysisResponsesData, error: analysisResponsesError } =
|
|
|
|
|
await supabase
|
|
|
|
|
.schema('medreport')
|
|
|
|
|
.from(`analysis_response_elements`)
|
|
|
|
|
.select(
|
|
|
|
|
`*,
|
|
|
|
|
analysis_responses(user_id, analysis_order:analysis_order_id(id,medusa_order_id, analysis_element_ids))`,
|
|
|
|
|
)
|
|
|
|
|
.eq('analysis_response_id', analysisResponseId);
|
|
|
|
|
|
|
|
|
|
if (error) {
|
|
|
|
|
throw new Error('Something went wrong.');
|
|
|
|
|
if (analysisResponsesError) {
|
|
|
|
|
logger.error(
|
|
|
|
|
{ ...ctx, analysisResponsesError },
|
|
|
|
|
'No order response for this analysis response id',
|
|
|
|
|
);
|
|
|
|
|
throw new Error('No order for this analysis id');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const firstAnalysisResponse = analysisResponseElements?.[0];
|
|
|
|
|
const firstAnalysisResponse = analysisResponsesData?.[0];
|
|
|
|
|
const userId = firstAnalysisResponse?.analysis_responses.user_id;
|
|
|
|
|
const medusaOrderId =
|
|
|
|
|
firstAnalysisResponse?.analysis_responses?.analysis_order_id
|
|
|
|
|
?.medusa_order_id;
|
|
|
|
|
firstAnalysisResponse?.analysis_responses?.analysis_order?.medusa_order_id;
|
|
|
|
|
|
|
|
|
|
if (!analysisResponseElements?.length || !userId || !medusaOrderId) {
|
|
|
|
|
if (!analysisResponsesData?.length || !userId || !medusaOrderId) {
|
|
|
|
|
throw new Error('Failed to retrieve full analysis data.');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const responseElementAnalysisElementOriginalIds =
|
|
|
|
|
analysisResponseElements.map(
|
|
|
|
|
({ analysis_element_original_id }) => analysis_element_original_id,
|
|
|
|
|
);
|
|
|
|
|
const responseElementAnalysisElementOriginalIds = analysisResponsesData.map(
|
|
|
|
|
({ analysis_element_original_id }) => analysis_element_original_id,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const [
|
|
|
|
|
{ data: medusaOrderItems, error: medusaOrderError },
|
|
|
|
|
medusaOrder,
|
|
|
|
|
{ data: accountWithParams, error: accountError },
|
|
|
|
|
{ data: doctorFeedback, error: feedbackError },
|
|
|
|
|
{ data: previousAnalyses, error: previousAnalysesError },
|
|
|
|
|
] = await Promise.all([
|
|
|
|
|
supabase
|
|
|
|
|
.schema('public')
|
|
|
|
|
.from('order_item')
|
|
|
|
|
.select(`order_id, item_id(product_title, product_type)`)
|
|
|
|
|
.eq('order_id', medusaOrderId),
|
|
|
|
|
retrieveOrder(medusaOrderId, true, '*items'),
|
|
|
|
|
supabase
|
|
|
|
|
.schema('medreport')
|
|
|
|
|
.from('accounts')
|
|
|
|
|
@@ -422,7 +431,7 @@ export async function getAnalysisResultsForDoctor(
|
|
|
|
|
.select(`*`)
|
|
|
|
|
.eq(
|
|
|
|
|
'analysis_order_id',
|
|
|
|
|
firstAnalysisResponse.analysis_responses.analysis_order_id.id,
|
|
|
|
|
firstAnalysisResponse.analysis_responses.analysis_order.id,
|
|
|
|
|
)
|
|
|
|
|
.limit(1),
|
|
|
|
|
supabase
|
|
|
|
|
@@ -452,12 +461,7 @@ export async function getAnalysisResultsForDoctor(
|
|
|
|
|
.order('response_time'),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
medusaOrderError ||
|
|
|
|
|
accountError ||
|
|
|
|
|
feedbackError ||
|
|
|
|
|
previousAnalysesError
|
|
|
|
|
) {
|
|
|
|
|
if (!medusaOrder || accountError || feedbackError || previousAnalysesError) {
|
|
|
|
|
throw new Error('Something went wrong.');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -478,15 +482,20 @@ export async function getAnalysisResultsForDoctor(
|
|
|
|
|
} = accountWithParams[0];
|
|
|
|
|
|
|
|
|
|
const analysisResponseElementsWithPreviousData = [];
|
|
|
|
|
for (const analysisResponseElement of analysisResponseElements) {
|
|
|
|
|
for (const analysisResponseElement of analysisResponsesData) {
|
|
|
|
|
const latestPreviousAnalysis = previousAnalyses.find(
|
|
|
|
|
({ analysis_element_original_id, response_time }) =>
|
|
|
|
|
analysis_element_original_id ===
|
|
|
|
|
analysisResponseElement.analysis_element_original_id &&
|
|
|
|
|
isBefore(
|
|
|
|
|
new Date(response_time),
|
|
|
|
|
new Date(analysisResponseElement.response_time),
|
|
|
|
|
),
|
|
|
|
|
({ analysis_element_original_id, response_time }) => {
|
|
|
|
|
if (response_time && analysisResponseElement.response_time) {
|
|
|
|
|
return (
|
|
|
|
|
analysis_element_original_id ===
|
|
|
|
|
analysisResponseElement.analysis_element_original_id &&
|
|
|
|
|
isBefore(
|
|
|
|
|
new Date(response_time),
|
|
|
|
|
new Date(analysisResponseElement.response_time),
|
|
|
|
|
)
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
analysisResponseElementsWithPreviousData.push({
|
|
|
|
|
...analysisResponseElement,
|
|
|
|
|
@@ -497,12 +506,12 @@ export async function getAnalysisResultsForDoctor(
|
|
|
|
|
return {
|
|
|
|
|
analysisResponse: analysisResponseElementsWithPreviousData,
|
|
|
|
|
order: {
|
|
|
|
|
title: medusaOrderItems?.[0]?.item_id.product_title ?? '-',
|
|
|
|
|
title: medusaOrder.items?.[0]?.product_title ?? '-',
|
|
|
|
|
isPackage:
|
|
|
|
|
medusaOrderItems?.[0]?.item_id.product_type?.toLowerCase() ===
|
|
|
|
|
medusaOrder.items?.[0]?.product_type?.toLowerCase() ===
|
|
|
|
|
'analysis package',
|
|
|
|
|
analysisOrderId:
|
|
|
|
|
firstAnalysisResponse.analysis_responses.analysis_order_id.id,
|
|
|
|
|
firstAnalysisResponse.analysis_responses.analysis_order.id,
|
|
|
|
|
},
|
|
|
|
|
doctorFeedback: doctorFeedback?.[0],
|
|
|
|
|
patient: {
|
|
|
|
|
@@ -525,8 +534,15 @@ export async function selectJob(analysisOrderId: number, userId: string) {
|
|
|
|
|
const {
|
|
|
|
|
data: { user },
|
|
|
|
|
} = await supabase.auth.getUser();
|
|
|
|
|
const logger = await getLogger();
|
|
|
|
|
const ctx = {
|
|
|
|
|
action: 'select-job',
|
|
|
|
|
patientUserId: userId,
|
|
|
|
|
currentUserId: user?.id,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (!user?.id) {
|
|
|
|
|
logger.error(ctx, 'No user logged in');
|
|
|
|
|
throw new Error('No user logged in.');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -541,6 +557,7 @@ export async function selectJob(analysisOrderId: number, userId: string) {
|
|
|
|
|
const jobAssignedToUserId = existingFeedback?.[0]?.doctor_user_id;
|
|
|
|
|
|
|
|
|
|
if (!!jobAssignedToUserId && jobAssignedToUserId !== user.id) {
|
|
|
|
|
logger.error(ctx, 'Job assigned to a different user');
|
|
|
|
|
throw new Error(ErrorReason.JOB_ASSIGNED);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -557,6 +574,10 @@ export async function selectJob(analysisOrderId: number, userId: string) {
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (error || existingFeedbackError) {
|
|
|
|
|
logger.error(
|
|
|
|
|
{ ...ctx, error, existingFeedbackError },
|
|
|
|
|
'Failed updating doctor feedback',
|
|
|
|
|
);
|
|
|
|
|
throw new Error('Something went wrong');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|