Merge branch 'develop' into MED-213

This commit is contained in:
Danel Kungla
2025-10-22 16:57:13 +03:00
20 changed files with 359 additions and 2114 deletions

View File

@@ -1,11 +1,15 @@
'use server';
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
import { updateLineItem } from '@lib/data/cart';
import { StoreProductVariant } from '@medusajs/types';
import logRequestResult from '~/lib/services/audit.service';
import { handleAddToCart } from '~/lib/services/medusaCart.service';
import { createInitialReservation } from '~/lib/services/reservation.service';
import {
cancelReservation,
createInitialReservation,
} from '~/lib/services/reservation.service';
import { RequestStatus } from '~/lib/types/audit';
import { ConnectedOnlineMethodName } from '~/lib/types/connected-online';
import { ExternalApi } from '~/lib/types/external';
@@ -46,11 +50,16 @@ export async function createInitialReservationAction(
}
}
export async function cancelTtoBooking(bookingCode: string, clinicId: number) {
export async function cancelTtoBooking(
bookingCode: string,
clinicId: number,
medusaLineItemId: string,
) {
try {
await fetch(
`${process.env.CONNECTED_ONLINE_URL}/${ConnectedOnlineMethodName.ConfirmedCancel}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
@@ -60,7 +69,14 @@ export async function cancelTtoBooking(bookingCode: string, clinicId: number) {
},
);
return null;
await cancelReservation(medusaLineItemId);
await logRequestResult(
ExternalApi.ConnectedOnline,
ConnectedOnlineMethodName.ConfirmedCancel,
RequestStatus.Success,
medusaLineItemId,
);
} catch (error) {
await logRequestResult(
ExternalApi.ConnectedOnline,
@@ -74,3 +90,22 @@ export async function cancelTtoBooking(bookingCode: string, clinicId: number) {
console.error('Error cancelling booking: ', error);
}
}
export async function isPaymentRequiredForService(serviceId: number) {
const supabaseClient = getSupabaseServerClient();
try {
const { data } = await supabaseClient
.schema('medreport')
.from('connected_online_services')
.select('requires_payment')
.eq('id', serviceId)
.is('requires_payment', true)
.maybeSingle();
return !!data;
} catch (error) {
console.error('Error checking payment requirement: ', error);
return false;
}
}

View File

@@ -7,6 +7,8 @@ import type { StoreCart, StoreOrder } from '@medusajs/types';
import jwt from 'jsonwebtoken';
import { z } from 'zod';
import { getLogger } from '@kit/shared/logger';
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { bookAppointment } from '~/lib/services/connected-online.service';
import { sendOrderToMedipost } from '~/lib/services/medipost/medipostPrivateMessage.service';
@@ -139,6 +141,7 @@ export const initiatePayment = async ({
};
export async function handlePlaceOrder({ cart }: { cart: StoreCart }) {
const logger = await getLogger();
const { account } = await loadCurrentUserAccount();
if (!account) {
throw new Error('Account not found in context');
@@ -158,7 +161,7 @@ export async function handlePlaceOrder({ cart }: { cart: StoreCart }) {
const existingAnalysisOrder = await getAnalysisOrder({
medusaOrderId: medusaOrder.id,
});
console.info(
logger.info(
`Analysis order already exists for medusaOrderId=${medusaOrder.id}, orderId=${existingAnalysisOrder.id}`,
);
return { success: true, orderId: existingAnalysisOrder.id };
@@ -183,7 +186,8 @@ export async function handlePlaceOrder({ cart }: { cart: StoreCart }) {
let bookServiceResults: {
success: boolean;
reason?: FailureReason;
serviceId?: number;
bookingCode: string | null;
clinicKey: string | null;
}[] = [];
if (orderedTtoServices?.length) {
const bookingPromises = orderedTtoServices.map((service) =>
@@ -197,7 +201,6 @@ export async function handlePlaceOrder({ cart }: { cart: StoreCart }) {
);
bookServiceResults = await Promise.all(bookingPromises);
}
// TODO: SEND EMAIL
if (email) {
if (analysisPackageOrder) {
@@ -207,22 +210,35 @@ export async function handlePlaceOrder({ cart }: { cart: StoreCart }) {
analysisPackageOrder,
});
} else {
console.info(`Order has no analysis package, skipping email.`);
logger.info(`Order has no analysis package, skipping email.`);
}
if (analysisItemsOrder) {
// @TODO send email for separate analyses
console.warn(
logger.warn(
`Order has analysis items, but no email template exists yet`,
);
} else {
console.info(`Order has no analysis items, skipping email.`);
logger.info(`Order has no analysis items, skipping email.`);
}
} else {
console.error('Missing email to send order result email', orderResult);
logger.error('Missing email to send order result email', orderResult);
}
if (env().isEnabledDispatchOnMontonioCallback) {
// if (bookServiceResults?.length) {
// bookServiceResults.forEach(async ({ bookingCode, clinicKey }) => {
// if (!bookingCode || !clinicKey) {
// logger.info('A booking is missing either bookingCode or clinicKey', {
// bookingCode,
// clinicKey,
// });
// return;
// }
// await getConfirmedService(bookingCode, clinicKey);
// });
// }
if (env().isEnabledDispatchOnMontonioCallback && orderContainsSynlabItems) {
await sendOrderToMedipost({ medusaOrderId, orderedAnalysisElements });
}

View File

@@ -1,19 +1,31 @@
import { cache } from 'react';
import { getProductCategories, listProducts } from '@lib/data';
import {
getProductCategories,
listProductTypes,
listProducts,
} from '@lib/data';
import { findProductTypeIdByHandle } from '~/lib/utils';
import { isPaymentRequiredForService } from './actions';
import { loadCountryCodes } from './load-analyses';
async function categoryLoader({ handle }: { handle: string }) {
const [response, countryCodes] = await Promise.all([
const [response, countryCodes, { productTypes }] = await Promise.all([
getProductCategories({
handle,
limit: 1,
}),
loadCountryCodes(),
listProductTypes(),
]);
const category = response.product_categories[0];
const countryCode = countryCodes[0]!;
const ttoServiceTypeId = findProductTypeIdByHandle(
productTypes,
'tto-service',
);
if (!response.product_categories?.[0]?.id) {
return { category: null };
@@ -26,6 +38,27 @@ async function categoryLoader({ handle }: { handle: string }) {
queryParams: { limit: 100, category_id: response.product_categories[0].id },
});
const productsWithNoRequiredPayment = categoryProducts.filter(
async (product) => {
if (product.type_id !== ttoServiceTypeId) {
return false;
}
if (product.metadata?.serviceIds) {
const serviceIds: number[] = JSON.parse(
product.metadata.serviceIds as string,
);
for (const serviceId of serviceIds) {
const requiresPayment = await isPaymentRequiredForService(serviceId);
if (requiresPayment) {
return false;
}
}
return true;
}
return false;
},
);
return {
category: {
color:
@@ -36,7 +69,7 @@ async function categoryLoader({ handle }: { handle: string }) {
handle: category?.handle || '',
name: category?.name || '',
countryCode,
products: categoryProducts,
products: productsWithNoRequiredPayment,
},
};
}