MED-177: add booking confirmation
This commit is contained in:
@@ -10,6 +10,7 @@ MEDIPOST_PASSWORD=your-medipost-password
|
||||
MEDIPOST_RECIPIENT=your-medipost-recipient
|
||||
|
||||
CONNECTED_ONLINE_URL=your-connected-online-url
|
||||
CONNECTED_ONLINE_CONFIRMED_URL=your-connected-confirmed-url
|
||||
|
||||
EMAIL_SENDER=
|
||||
EMAIL_USER= # refer to your email provider's documentation
|
||||
|
||||
@@ -69,11 +69,12 @@ export default function OrderBlock({
|
||||
title="orders:table.ttoService"
|
||||
type="ttoService"
|
||||
order={{
|
||||
status: medusaOrderStatus.toUpperCase(),
|
||||
status: ttoReservation?.status,
|
||||
medusaOrderId,
|
||||
location: ttoLocation?.name,
|
||||
bookingCode: ttoReservation?.booking_code,
|
||||
clinicId: ttoReservation?.clinic_id,
|
||||
medusaLineItemId: ttoReservation?.medusa_cart_line_item_id,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { redirect, useRouter } from 'next/navigation';
|
||||
|
||||
import ConfirmationModal from '@/packages/shared/src/components/confirmation-modal';
|
||||
import { StoreOrderLineItem } from '@medusajs/types';
|
||||
@@ -40,6 +40,11 @@ export default function OrderItemsTable({
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
const isCancelOrderAllowed =
|
||||
order?.bookingCode &&
|
||||
order?.clinicId &&
|
||||
order?.medusaLineItemId &&
|
||||
order?.status === 'CONFIRMED';
|
||||
|
||||
if (!items || items.length === 0) {
|
||||
return null;
|
||||
@@ -109,7 +114,7 @@ export default function OrderItemsTable({
|
||||
<Button size="sm" onClick={openDetailedView}>
|
||||
<Trans i18nKey="analysis-results:view" />
|
||||
</Button>
|
||||
{isTtoservice && order.bookingCode && (
|
||||
{isCancelOrderAllowed && (
|
||||
<Button
|
||||
size="sm"
|
||||
className="bg-warning/90 hover:bg-warning mt-2 w-full"
|
||||
@@ -122,12 +127,18 @@ export default function OrderItemsTable({
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
{order?.bookingCode && order?.clinicId && (
|
||||
{isCancelOrderAllowed && (
|
||||
<ConfirmationModal
|
||||
isOpen={isConfirmOpen}
|
||||
onClose={() => setIsConfirmOpen(false)}
|
||||
onConfirm={async () => {
|
||||
await cancelTtoBooking(order.bookingCode!, order.clinicId!);
|
||||
cancelTtoBooking(
|
||||
order.bookingCode!,
|
||||
order.clinicId!,
|
||||
order.medusaLineItemId!,
|
||||
).then(() => {
|
||||
redirect(pathsConfig.app.myOrders);
|
||||
});
|
||||
}}
|
||||
titleKey="orders:confirmBookingCancel.title"
|
||||
descriptionKey="orders:confirmBookingCancel.description"
|
||||
|
||||
@@ -5,7 +5,10 @@ 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 +49,16 @@ export async function createInitialReservationAction(
|
||||
}
|
||||
}
|
||||
|
||||
export async function cancelTtoBooking(bookingCode: string, clinicId: number) {
|
||||
export async function cancelTtoBooking(
|
||||
bookingCode: string,
|
||||
clinicId: number,
|
||||
medusaLineItemId: string,
|
||||
) {
|
||||
try {
|
||||
const response = await fetch(
|
||||
await fetch(
|
||||
`${process.env.CONNECTED_ONLINE_URL}/${ConnectedOnlineMethodName.ConfirmedCancel}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
},
|
||||
@@ -60,7 +68,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,
|
||||
|
||||
@@ -9,8 +9,13 @@ 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 {
|
||||
bookAppointment,
|
||||
getConfirmedService,
|
||||
} from '~/lib/services/connected-online.service';
|
||||
import { sendOrderToMedipost } from '~/lib/services/medipost/medipostPrivateMessage.service';
|
||||
import { handleNavigateToPayment } from '~/lib/services/medusaCart.service';
|
||||
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';
|
||||
@@ -141,6 +146,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');
|
||||
@@ -160,7 +166,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 };
|
||||
@@ -185,7 +191,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) =>
|
||||
@@ -199,7 +206,6 @@ export async function handlePlaceOrder({ cart }: { cart: StoreCart }) {
|
||||
);
|
||||
bookServiceResults = await Promise.all(bookingPromises);
|
||||
}
|
||||
// TODO: SEND EMAIL
|
||||
|
||||
if (email) {
|
||||
if (analysisPackageOrder) {
|
||||
@@ -209,22 +215,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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -65,8 +65,7 @@ async function loadAccountMembers(
|
||||
|
||||
const members = data ?? [];
|
||||
|
||||
return members
|
||||
.sort((prev, next) => {
|
||||
return members.sort((prev, next) => {
|
||||
if (prev.primary_owner_user_id === prev.user_id) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -99,7 +99,12 @@ export async function bookAppointment(
|
||||
syncUserID: number,
|
||||
startTime: string,
|
||||
comments = '',
|
||||
) {
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
reason?: FailureReason;
|
||||
bookingCode: string | null;
|
||||
clinicKey: string | null;
|
||||
}> {
|
||||
const logger = await getLogger();
|
||||
const supabase = getSupabaseServerClient();
|
||||
|
||||
@@ -148,7 +153,7 @@ export async function bookAppointment(
|
||||
supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.select('id')
|
||||
.select('id,location_sync_id')
|
||||
.eq('clinic_id', clinicId)
|
||||
.eq('service_id', serviceId)
|
||||
.eq('start_time', formattedStartTime)
|
||||
@@ -202,8 +207,8 @@ export async function bookAppointment(
|
||||
},
|
||||
param: JSON.stringify({
|
||||
ClinicID: clinic.id,
|
||||
ServiceID: service.sync_id,
|
||||
ClinicServiceID: service.id,
|
||||
ServiceID: service.id,
|
||||
ClinicServiceID: service.sync_id,
|
||||
UserID: appointmentUserId,
|
||||
SyncUserID: syncUserID,
|
||||
StartTime: startTime,
|
||||
@@ -216,6 +221,7 @@ export async function bookAppointment(
|
||||
AddToBasket: false,
|
||||
Key: dbClinic.key,
|
||||
Lang: 'et',
|
||||
Location: dbReservation.location_sync_id,
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -275,6 +281,7 @@ export async function bookAppointment(
|
||||
'Booked time, updated reservation with id ' + updatedReservation?.id,
|
||||
);
|
||||
|
||||
if (responseParts[1]) {
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.BookTime,
|
||||
@@ -284,7 +291,24 @@ export async function bookAppointment(
|
||||
service.id,
|
||||
clinicId,
|
||||
);
|
||||
return { success: true };
|
||||
return {
|
||||
success: true,
|
||||
bookingCode: responseParts[1],
|
||||
clinicKey: dbClinic.key,
|
||||
};
|
||||
} else {
|
||||
logger.error(`Missing booking code: ${responseParts}`);
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.BookTime,
|
||||
RequestStatus.Fail,
|
||||
JSON.stringify(error),
|
||||
startTime.toString(),
|
||||
serviceId,
|
||||
clinicId,
|
||||
);
|
||||
return { success: false, bookingCode: null, clinicKey: null };
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Failed to book time, error: ${JSON.stringify(error)}`);
|
||||
await logRequestResult(
|
||||
@@ -296,41 +320,33 @@ export async function bookAppointment(
|
||||
serviceId,
|
||||
clinicId,
|
||||
);
|
||||
return { success: false, reason };
|
||||
return { success: false, reason, bookingCode: null, clinicKey: null };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getConfirmedService(reservationCode: string) {
|
||||
export async function getConfirmedService(
|
||||
reservationCode: string,
|
||||
clinicKey: string,
|
||||
) {
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${process.env.CONNECTED_ONLINE_URL!}/${ConnectedOnlineMethodName.ConfirmedLoad}`,
|
||||
{
|
||||
const url = new URL(process.env.CONNECTED_ONLINE_CONFIRMED_URL!);
|
||||
url.searchParams.set('code1', reservationCode);
|
||||
url.searchParams.set('key', clinicKey);
|
||||
url.searchParams.set('lang', 'et');
|
||||
await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
},
|
||||
param: JSON.stringify({ Value: `${reservationCode}|7T624nlu|et` }),
|
||||
},
|
||||
);
|
||||
|
||||
const responseData: ConfirmedLoadResponse = JSON.parse(response.data.d);
|
||||
|
||||
if (responseData?.ErrorCode !== 0) {
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.ConfirmedLoad,
|
||||
RequestStatus.Fail,
|
||||
JSON.stringify(responseData),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.ConfirmedLoad,
|
||||
RequestStatus.Success,
|
||||
JSON.stringify(responseData),
|
||||
'ok',
|
||||
);
|
||||
return responseData.Data;
|
||||
return;
|
||||
} catch (error) {
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
|
||||
@@ -438,9 +438,6 @@ export async function readPrivateMessageResponse({
|
||||
medusaOrderId,
|
||||
orderStatus: 'PARTIAL_ANALYSIS_RESPONSE',
|
||||
});
|
||||
if (IS_ENABLED_DELETE_PRIVATE_MESSAGE) {
|
||||
await deletePrivateMessage(privateMessageId);
|
||||
}
|
||||
hasAnalysisResponse = true;
|
||||
hasPartialAnalysisResponse = true;
|
||||
} else if (status.isCompleted) {
|
||||
|
||||
@@ -12,4 +12,5 @@ export type Order = {
|
||||
location?: string;
|
||||
bookingCode?: string | null;
|
||||
clinicId?: number;
|
||||
medusaLineItemId?: string | null;
|
||||
};
|
||||
|
||||
@@ -16,8 +16,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@headlessui/react": "^2.2.0",
|
||||
"@medusajs/js-sdk": "latest",
|
||||
"@medusajs/ui": "latest",
|
||||
"@radix-ui/react-accordion": "^1.2.1",
|
||||
"@stripe/react-stripe-js": "^1.7.2",
|
||||
"@stripe/stripe-js": "^1.29.0",
|
||||
@@ -34,8 +32,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.17.5",
|
||||
"@medusajs/types": "latest",
|
||||
"@medusajs/ui-preset": "latest",
|
||||
"@types/lodash": "^4.14.195",
|
||||
"@types/node": "17.0.21",
|
||||
"@types/pg": "^8.11.0",
|
||||
|
||||
@@ -5,7 +5,7 @@ import { redirect } from 'next/navigation';
|
||||
|
||||
import { sdk } from '@lib/config';
|
||||
import medusaError from '@lib/util/medusa-error';
|
||||
import { HttpTypes, StoreCart } from '@medusajs/types';
|
||||
import type { HttpTypes, StoreCart } from '@medusajs/types';
|
||||
|
||||
import {
|
||||
getAuthHeaders,
|
||||
|
||||
@@ -84,9 +84,9 @@ export function AccountMembersTable({
|
||||
});
|
||||
|
||||
const searchString = search.toLowerCase();
|
||||
const filteredMembers = searchString.length > 0
|
||||
? members
|
||||
.filter((member) => {
|
||||
const filteredMembers =
|
||||
searchString.length > 0
|
||||
? members.filter((member) => {
|
||||
const displayName = (
|
||||
member.name ??
|
||||
member.email.split('@')[0] ??
|
||||
|
||||
2033
pnpm-lock.yaml
generated
2033
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user