|
|
|
|
@@ -11,7 +11,7 @@ import { AnalysisOrderStatus } from '@/packages/shared/src/types/medipost-analys
|
|
|
|
|
import type {
|
|
|
|
|
ResponseUuringuGrupp,
|
|
|
|
|
MedipostOrderResponse,
|
|
|
|
|
ResponseUuring,
|
|
|
|
|
UuringElement,
|
|
|
|
|
} from '@/packages/shared/src/types/medipost-analysis';
|
|
|
|
|
import { toArray } from '@/lib/utils';
|
|
|
|
|
import type { AnalysisOrder } from '~/lib/types/analysis-order';
|
|
|
|
|
@@ -29,7 +29,7 @@ import { composeOrderXML, OrderedAnalysisElement } from './medipostXML.service';
|
|
|
|
|
import { getAccountAdmin } from '../account.service';
|
|
|
|
|
import { logMedipostDispatch } from '../audit.service';
|
|
|
|
|
import { MedipostValidationError } from './MedipostValidationError';
|
|
|
|
|
import { getExistingAnalysisResponseElements, upsertAnalysisResponse } from '../analysis-order.service';
|
|
|
|
|
import { createAnalysisResponseElement, getExistingAnalysisResponseElements, upsertAnalysisResponse } from '../analysis-order.service';
|
|
|
|
|
|
|
|
|
|
const BASE_URL = process.env.MEDIPOST_URL!;
|
|
|
|
|
const USER = process.env.MEDIPOST_USER!;
|
|
|
|
|
@@ -55,7 +55,7 @@ export async function getLatestPrivateMessageListItem({
|
|
|
|
|
throw new Error('Failed to get private message list');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return getLatestMessage({ messages: data?.messages, excludedMessageIds });
|
|
|
|
|
return await getLatestMessage({ messages: data?.messages, excludedMessageIds });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const logger = (analysisOrder: AnalysisOrder, externalId: string, analysisResponseId: string) => (message: string, error?: PostgrestError | null) => {
|
|
|
|
|
@@ -67,7 +67,7 @@ const logger = (analysisOrder: AnalysisOrder, externalId: string, analysisRespon
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
function canCreateAnalysisResponseElement({
|
|
|
|
|
export async function canCreateAnalysisResponseElement({
|
|
|
|
|
existingElements,
|
|
|
|
|
groupUuring: {
|
|
|
|
|
UuringuElement: {
|
|
|
|
|
@@ -78,8 +78,8 @@ function canCreateAnalysisResponseElement({
|
|
|
|
|
responseValue,
|
|
|
|
|
log,
|
|
|
|
|
}: {
|
|
|
|
|
existingElements: AnalysisResponseElement[];
|
|
|
|
|
groupUuring: ResponseUuring;
|
|
|
|
|
existingElements: Pick<AnalysisResponseElement, 'analysis_element_original_id' | 'status' | 'response_value'>[];
|
|
|
|
|
groupUuring: { UuringuElement: Pick<UuringElement, 'UuringOlek' | 'UuringId'> };
|
|
|
|
|
responseValue: number | null;
|
|
|
|
|
log: ReturnType<typeof logger>;
|
|
|
|
|
}) {
|
|
|
|
|
@@ -102,21 +102,19 @@ function canCreateAnalysisResponseElement({
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async function getAnalysisResponseElementsForGroup({
|
|
|
|
|
analysisResponseId,
|
|
|
|
|
export async function getAnalysisResponseElementsForGroup({
|
|
|
|
|
analysisGroup,
|
|
|
|
|
existingElements,
|
|
|
|
|
log,
|
|
|
|
|
}: {
|
|
|
|
|
analysisResponseId: number;
|
|
|
|
|
analysisGroup: ResponseUuringuGrupp;
|
|
|
|
|
analysisGroup: Pick<ResponseUuringuGrupp, 'UuringuGruppNimi' | 'Uuring'>;
|
|
|
|
|
existingElements: Pick<AnalysisResponseElement, 'analysis_element_original_id' | 'status' | 'response_value'>[];
|
|
|
|
|
log: ReturnType<typeof logger>;
|
|
|
|
|
}) {
|
|
|
|
|
const groupUuringItems = toArray(analysisGroup.Uuring as ResponseUuringuGrupp['Uuring']);
|
|
|
|
|
log(`Order has results in group '${analysisGroup.UuringuGruppNimi}' for ${groupUuringItems.length} analysis elements`);
|
|
|
|
|
|
|
|
|
|
const existingElements = await getExistingAnalysisResponseElements({ analysisResponseId });
|
|
|
|
|
|
|
|
|
|
const results: Omit<AnalysisResponseElement, 'created_at' | 'updated_at' | 'id'>[] = [];
|
|
|
|
|
const results: Omit<AnalysisResponseElement, 'created_at' | 'updated_at' | 'id' | 'analysis_response_id'>[] = [];
|
|
|
|
|
|
|
|
|
|
for (const groupUuring of groupUuringItems) {
|
|
|
|
|
const groupUuringElement = groupUuring.UuringuElement;
|
|
|
|
|
@@ -127,21 +125,25 @@ async function getAnalysisResponseElementsForGroup({
|
|
|
|
|
|
|
|
|
|
for (const response of elementAnalysisResponses) {
|
|
|
|
|
const analysisElementOriginalId = groupUuringElement.UuringId;
|
|
|
|
|
const vastuseVaartus = response.VastuseVaartus;
|
|
|
|
|
const responseValue = (() => {
|
|
|
|
|
const valueAsNumber = Number(response.VastuseVaartus);
|
|
|
|
|
const valueAsNumber = Number(vastuseVaartus);
|
|
|
|
|
if (isNaN(valueAsNumber)) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
return valueAsNumber;
|
|
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
if (!canCreateAnalysisResponseElement({ existingElements, groupUuring, responseValue, log })) {
|
|
|
|
|
if (!await canCreateAnalysisResponseElement({ existingElements, groupUuring, responseValue, log })) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const responseValueIsNumeric = responseValue !== null;
|
|
|
|
|
const responseValueIsNegative = vastuseVaartus === 'Negatiivne';
|
|
|
|
|
const responseValueIsWithinNorm = vastuseVaartus === 'Normi piires';
|
|
|
|
|
|
|
|
|
|
results.push({
|
|
|
|
|
analysis_element_original_id: analysisElementOriginalId,
|
|
|
|
|
analysis_response_id: analysisResponseId,
|
|
|
|
|
norm_lower: response.NormAlum?.['#text'] ?? null,
|
|
|
|
|
norm_lower_included:
|
|
|
|
|
response.NormAlum?.['@_kaasaarvatud'].toLowerCase() === 'jah',
|
|
|
|
|
@@ -156,6 +158,8 @@ async function getAnalysisResponseElementsForGroup({
|
|
|
|
|
analysis_name: groupUuringElement.UuringNimi || groupUuringElement.KNimetus,
|
|
|
|
|
comment: groupUuringElement.UuringuKommentaar ?? null,
|
|
|
|
|
status: status.toString(),
|
|
|
|
|
response_value_is_within_norm: responseValueIsNumeric ? null : responseValueIsWithinNorm,
|
|
|
|
|
response_value_is_negative: responseValueIsNumeric ? null : responseValueIsNegative,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
@@ -163,18 +167,55 @@ async function getAnalysisResponseElementsForGroup({
|
|
|
|
|
return results;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function syncPrivateMessage({
|
|
|
|
|
messageResponse,
|
|
|
|
|
async function getNewAnalysisResponseElements({
|
|
|
|
|
analysisGroups,
|
|
|
|
|
existingElements,
|
|
|
|
|
log,
|
|
|
|
|
}: {
|
|
|
|
|
analysisGroups: ResponseUuringuGrupp[];
|
|
|
|
|
existingElements: AnalysisResponseElement[];
|
|
|
|
|
log: ReturnType<typeof logger>;
|
|
|
|
|
}) {
|
|
|
|
|
const newElements: Omit<AnalysisResponseElement, 'created_at' | 'updated_at' | 'id' | 'analysis_response_id'>[] = [];
|
|
|
|
|
for (const analysisGroup of analysisGroups) {
|
|
|
|
|
log(`[${analysisGroups.indexOf(analysisGroup) + 1}/${analysisGroups.length}] Syncing analysis group '${analysisGroup.UuringuGruppNimi}'`);
|
|
|
|
|
const elements = await getAnalysisResponseElementsForGroup({
|
|
|
|
|
analysisGroup,
|
|
|
|
|
existingElements,
|
|
|
|
|
log,
|
|
|
|
|
});
|
|
|
|
|
newElements.push(...elements);
|
|
|
|
|
}
|
|
|
|
|
return newElements;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function hasAllAnalysisResponseElements({
|
|
|
|
|
analysisResponseId,
|
|
|
|
|
order,
|
|
|
|
|
}: {
|
|
|
|
|
messageResponse: NonNullable<MedipostOrderResponse['Saadetis']['Vastus']>;
|
|
|
|
|
analysisResponseId: number;
|
|
|
|
|
order: Pick<AnalysisOrder, 'analysis_element_ids'>;
|
|
|
|
|
}) {
|
|
|
|
|
const allOrderResponseElements = await getExistingAnalysisResponseElements({ analysisResponseId });
|
|
|
|
|
const expectedOrderResponseElements = order.analysis_element_ids?.length ?? 0;
|
|
|
|
|
return allOrderResponseElements.length === expectedOrderResponseElements;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function syncPrivateMessage({
|
|
|
|
|
messageResponse: {
|
|
|
|
|
ValisTellimuseId: externalId,
|
|
|
|
|
TellimuseNumber: orderNumber,
|
|
|
|
|
TellimuseOlek,
|
|
|
|
|
UuringuGrupp,
|
|
|
|
|
},
|
|
|
|
|
order,
|
|
|
|
|
}: {
|
|
|
|
|
messageResponse: Pick<NonNullable<MedipostOrderResponse['Saadetis']['Vastus']>, 'ValisTellimuseId' | 'TellimuseNumber' | 'TellimuseOlek' | 'UuringuGrupp'>;
|
|
|
|
|
order: Tables<{ schema: 'medreport' }, 'analysis_orders'>;
|
|
|
|
|
}) {
|
|
|
|
|
const supabase = getSupabaseServerAdminClient();
|
|
|
|
|
|
|
|
|
|
const externalId = messageResponse.ValisTellimuseId;
|
|
|
|
|
const orderNumber = messageResponse.TellimuseNumber;
|
|
|
|
|
const orderStatus = AnalysisOrderStatus[messageResponse.TellimuseOlek];
|
|
|
|
|
const orderStatus = AnalysisOrderStatus[TellimuseOlek];
|
|
|
|
|
|
|
|
|
|
const log = logger(order, externalId, orderNumber);
|
|
|
|
|
|
|
|
|
|
@@ -193,37 +234,28 @@ export async function syncPrivateMessage({
|
|
|
|
|
userId: analysisOrder.user_id,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const analysisGroups = toArray(messageResponse.UuringuGrupp);
|
|
|
|
|
const existingElements = await getExistingAnalysisResponseElements({ analysisResponseId });
|
|
|
|
|
|
|
|
|
|
const analysisGroups = toArray(UuringuGrupp);
|
|
|
|
|
log(`Order has results for ${analysisGroups.length} analysis groups`);
|
|
|
|
|
const newElements = await getNewAnalysisResponseElements({ analysisGroups, existingElements, log });
|
|
|
|
|
|
|
|
|
|
for (const analysisGroup of analysisGroups) {
|
|
|
|
|
log(`[${analysisGroups.indexOf(analysisGroup) + 1}/${analysisGroups.length}] Syncing analysis group '${analysisGroup.UuringuGruppNimi}'`);
|
|
|
|
|
|
|
|
|
|
const elements = await getAnalysisResponseElementsForGroup({
|
|
|
|
|
analysisResponseId,
|
|
|
|
|
analysisGroup,
|
|
|
|
|
log,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
for (const element of elements) {
|
|
|
|
|
const { error } = await supabase
|
|
|
|
|
.schema('medreport')
|
|
|
|
|
.from('analysis_response_elements')
|
|
|
|
|
.insert(element);
|
|
|
|
|
if (error) {
|
|
|
|
|
log(`Failed to insert order response elements for response id ${analysisResponseId} (order id: ${analysisOrder.id})`, error);
|
|
|
|
|
}
|
|
|
|
|
for (const element of newElements) {
|
|
|
|
|
try {
|
|
|
|
|
await createAnalysisResponseElement({
|
|
|
|
|
element: {
|
|
|
|
|
...element,
|
|
|
|
|
analysis_response_id: analysisResponseId,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
} catch (e) {
|
|
|
|
|
log(`Failed to create order response element for response id ${analysisResponseId}, element id '${element.analysis_element_original_id}' (order id: ${order.id})`, e as PostgrestError);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const allOrderResponseElements = await getExistingAnalysisResponseElements({ analysisResponseId });
|
|
|
|
|
const expectedOrderResponseElements = order.analysis_element_ids?.length ?? 0;
|
|
|
|
|
if (allOrderResponseElements.length !== expectedOrderResponseElements) {
|
|
|
|
|
return { isPartial: true };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { isCompleted: orderStatus === 'COMPLETED' };
|
|
|
|
|
return await hasAllAnalysisResponseElements({ analysisResponseId, order })
|
|
|
|
|
? { isCompleted: orderStatus === 'COMPLETED' }
|
|
|
|
|
: { isPartial: true };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function readPrivateMessageResponse({
|
|
|
|
|
@@ -297,6 +329,9 @@ export async function readPrivateMessageResponse({
|
|
|
|
|
analysisOrder = await getAnalysisOrder({ analysisOrderId })
|
|
|
|
|
medusaOrderId = analysisOrder.medusa_order_id;
|
|
|
|
|
} catch (e) {
|
|
|
|
|
if (IS_ENABLED_DELETE_PRIVATE_MESSAGE) {
|
|
|
|
|
await deletePrivateMessage(privateMessageId);
|
|
|
|
|
}
|
|
|
|
|
throw new Error(`No analysis order found for Medipost message ValisTellimuseId=${medipostExternalOrderId}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -305,17 +340,7 @@ export async function readPrivateMessageResponse({
|
|
|
|
|
throw new Error(`Order person personal code does not match Medipost message Patsient.Isikukood=${patientPersonalCode}, orderPerson.personal_code=${orderPerson.personal_code}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let order: Tables<{ schema: 'medreport' }, 'analysis_orders'>;
|
|
|
|
|
try {
|
|
|
|
|
order = await getAnalysisOrder({ medusaOrderId });
|
|
|
|
|
} catch (e) {
|
|
|
|
|
if (IS_ENABLED_DELETE_PRIVATE_MESSAGE) {
|
|
|
|
|
await deletePrivateMessage(privateMessageId);
|
|
|
|
|
}
|
|
|
|
|
throw new Error(`Order not found by Medipost message ValisTellimuseId=${medusaOrderId}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const status = await syncPrivateMessage({ messageResponse, order });
|
|
|
|
|
const status = await syncPrivateMessage({ messageResponse, order: analysisOrder });
|
|
|
|
|
|
|
|
|
|
await createMedipostActionLog({
|
|
|
|
|
action: 'sync_analysis_results_from_medipost',
|
|
|
|
|
@@ -394,7 +419,7 @@ export async function getPrivateMessage(messageId: string) {
|
|
|
|
|
await validateMedipostResponse(data, { canHaveEmptyCode: true });
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
message: parseXML(data) as MedipostOrderResponse,
|
|
|
|
|
message: (await parseXML(data)) as MedipostOrderResponse,
|
|
|
|
|
xml: data as string,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|