Merge pull request #140 from MR-medreport/MED-177
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
|
||||
|
||||
@@ -66,14 +66,16 @@ async function OrdersPage() {
|
||||
({ medusa_order_id }) => medusa_order_id === medusaOrder.id,
|
||||
);
|
||||
|
||||
const ttoReservation = ttoOrders.find(({ id }) => {
|
||||
const connectedOnlineReservationId =
|
||||
medusaOrder?.items &&
|
||||
medusaOrder.items.find(
|
||||
({ metadata }) => !!metadata?.connectedOnlineReservationId,
|
||||
)?.metadata?.connectedOnlineReservationId;
|
||||
return id === connectedOnlineReservationId;
|
||||
});
|
||||
const orderIds = new Set(
|
||||
(medusaOrder?.items ?? [])
|
||||
.map((i) => i?.metadata?.connectedOnlineReservationId)
|
||||
.filter(Boolean)
|
||||
.map(String),
|
||||
);
|
||||
|
||||
const ttoReservation = ttoOrders.find((o) =>
|
||||
orderIds.has(String(o.id)),
|
||||
);
|
||||
|
||||
const medusaOrderItems = medusaOrder.items || [];
|
||||
const medusaOrderItemsAnalysisPackages = medusaOrderItems.filter(
|
||||
@@ -105,7 +107,6 @@ async function OrdersPage() {
|
||||
medusaOrderId={medusaOrder.id}
|
||||
analysisOrder={analysisOrder}
|
||||
ttoReservation={ttoReservation}
|
||||
medusaOrderStatus={medusaOrder.status}
|
||||
itemsAnalysisPackage={medusaOrderItemsAnalysisPackages}
|
||||
itemsTtoService={medusaOrderItemsTtoServices}
|
||||
itemsOther={medusaOrderItemsOther}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Label } from '@medusajs/ui';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { RadioGroup, RadioGroupItem } from '@kit/ui/radio-group';
|
||||
import { Card } from '@kit/ui/shadcn/card';
|
||||
@@ -8,7 +7,6 @@ import { Trans } from '@kit/ui/trans';
|
||||
import { useBooking } from './booking.provider';
|
||||
|
||||
const LocationSelector = () => {
|
||||
const { t } = useTranslation();
|
||||
const { selectedLocationId, setSelectedLocationId, locations } = useBooking();
|
||||
|
||||
const onLocationSelect = (locationId: number | string | null) => {
|
||||
@@ -16,6 +14,15 @@ const LocationSelector = () => {
|
||||
setSelectedLocationId(Number(locationId));
|
||||
};
|
||||
|
||||
const uniqueLocations = locations?.filter((item, index, self) => {
|
||||
return (
|
||||
index ===
|
||||
self.findIndex(
|
||||
(loc) => loc.sync_id === item.sync_id && loc.name === item.name,
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="mb-4 p-4">
|
||||
<h5 className="text-semibold mb-2">
|
||||
@@ -26,20 +33,23 @@ const LocationSelector = () => {
|
||||
className="mb-2 flex flex-col"
|
||||
onValueChange={(val) => onLocationSelect(val)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* <div className="flex items-center gap-2">
|
||||
<RadioGroupItem
|
||||
value={'all'}
|
||||
id={'all'}
|
||||
value="all"
|
||||
id="all"
|
||||
checked={selectedLocationId === null}
|
||||
/>
|
||||
<Label htmlFor={'all'}>{t('booking:showAllLocations')}</Label>
|
||||
</div>
|
||||
{locations?.map((location) => (
|
||||
<Label htmlFor="all">{t('booking:showAllLocations')}</Label>
|
||||
</div> */}
|
||||
{uniqueLocations?.map((location, index) => (
|
||||
<div key={location.sync_id} className="flex items-center gap-2">
|
||||
<RadioGroupItem
|
||||
value={location.sync_id.toString()}
|
||||
id={location.sync_id.toString()}
|
||||
checked={selectedLocationId === location.sync_id}
|
||||
checked={
|
||||
selectedLocationId === location.sync_id ||
|
||||
(index === 0 && selectedLocationId === null)
|
||||
}
|
||||
/>
|
||||
<Label htmlFor={location.sync_id.toString()}>
|
||||
{location.name}
|
||||
|
||||
@@ -18,19 +18,19 @@ const MobileCartItems = ({
|
||||
productColumnLabelKey: string;
|
||||
}) => {
|
||||
const {
|
||||
i18n: { language },
|
||||
i18n: { language, t },
|
||||
} = useTranslation();
|
||||
|
||||
return (
|
||||
<Table className="border-separate rounded-lg border p-2">
|
||||
<TableBody>
|
||||
<MobileTableRow
|
||||
titleKey={productColumnLabelKey}
|
||||
title={t(productColumnLabelKey)}
|
||||
value={item.product_title}
|
||||
/>
|
||||
<MobileTableRow titleKey="cart:table.time" value={item.quantity} />
|
||||
<MobileTableRow title={t('cart:table.time')} value={item.quantity} />
|
||||
<MobileTableRow
|
||||
titleKey="cart:table.price"
|
||||
title={t('cart:table.price')}
|
||||
value={formatCurrency({
|
||||
value: item.unit_price,
|
||||
currencyCode,
|
||||
@@ -38,7 +38,7 @@ const MobileCartItems = ({
|
||||
})}
|
||||
/>
|
||||
<MobileTableRow
|
||||
titleKey="cart:table.total"
|
||||
title={t('cart:table.total')}
|
||||
value={
|
||||
item.total &&
|
||||
formatCurrency({
|
||||
|
||||
@@ -25,27 +25,30 @@ const MobileCartServiceItems = ({
|
||||
setEditingItem: (item: EnrichedCartItem | null) => void;
|
||||
}) => {
|
||||
const {
|
||||
i18n: { language },
|
||||
i18n: { language, t },
|
||||
} = useTranslation();
|
||||
|
||||
return (
|
||||
<Table className="border-separate rounded-lg border p-2">
|
||||
<TableBody>
|
||||
<MobileTableRow
|
||||
titleKey={productColumnLabelKey}
|
||||
title={t(productColumnLabelKey)}
|
||||
value={item.product_title}
|
||||
/>
|
||||
<MobileTableRow
|
||||
titleKey="cart:table.time"
|
||||
title={t('cart:table.time')}
|
||||
value={formatDateAndTime(item.reservation.startTime.toString())}
|
||||
/>
|
||||
<MobileTableRow
|
||||
titleKey="cart:table.location"
|
||||
title={t('cart:table.location')}
|
||||
value={item.reservation.location?.address ?? '-'}
|
||||
/>
|
||||
<MobileTableRow titleKey="cart:table.quantity" value={item.quantity} />
|
||||
<MobileTableRow
|
||||
titleKey="cart:table.price"
|
||||
title={t('cart:table.quantity')}
|
||||
value={item.quantity}
|
||||
/>
|
||||
<MobileTableRow
|
||||
title={t('cart:table.price')}
|
||||
value={formatCurrency({
|
||||
value: item.unit_price,
|
||||
currencyCode,
|
||||
@@ -53,7 +56,7 @@ const MobileCartServiceItems = ({
|
||||
})}
|
||||
/>
|
||||
<MobileTableRow
|
||||
titleKey="cart:table.total"
|
||||
title={t('cart:table.total')}
|
||||
value={
|
||||
item.total &&
|
||||
formatCurrency({
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import React from 'react';
|
||||
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { TableCell, TableHead, TableRow } from '@kit/ui/shadcn/table';
|
||||
|
||||
const MobleTableRow = ({
|
||||
titleKey,
|
||||
title,
|
||||
value,
|
||||
}: {
|
||||
titleKey?: string;
|
||||
title?: string;
|
||||
value?: string | number;
|
||||
}) => (
|
||||
<TableRow>
|
||||
<TableHead className="h-2 font-bold">
|
||||
<Trans i18nKey={titleKey} />
|
||||
</TableHead>
|
||||
<TableHead className="h-2 font-bold">{title}</TableHead>
|
||||
|
||||
<TableCell className="p-0 text-right">
|
||||
<p className="txt-medium-plus text-ui-fg-base">{value}</p>
|
||||
|
||||
@@ -13,7 +13,6 @@ export default function OrderBlock({
|
||||
analysisOrder,
|
||||
ttoLocation,
|
||||
ttoReservation,
|
||||
medusaOrderStatus,
|
||||
itemsAnalysisPackage,
|
||||
itemsTtoService,
|
||||
itemsOther,
|
||||
@@ -22,7 +21,6 @@ export default function OrderBlock({
|
||||
analysisOrder?: AnalysisOrder;
|
||||
ttoLocation?: { name: string };
|
||||
ttoReservation?: TTOOrder;
|
||||
medusaOrderStatus: string;
|
||||
itemsAnalysisPackage: StoreOrderLineItem[];
|
||||
itemsTtoService: StoreOrderLineItem[];
|
||||
itemsOther: StoreOrderLineItem[];
|
||||
@@ -70,11 +68,13 @@ 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,
|
||||
id: ttoReservation?.id,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import React, { 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';
|
||||
import { formatDate } from 'date-fns';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { Button } from '@kit/ui/button';
|
||||
@@ -41,8 +42,16 @@ export default function OrderItemsTable({
|
||||
type?: OrderItemType;
|
||||
isPackage?: boolean;
|
||||
}) {
|
||||
const {
|
||||
i18n: { t },
|
||||
} = useTranslation();
|
||||
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;
|
||||
@@ -56,7 +65,7 @@ export default function OrderItemsTable({
|
||||
await logAnalysisResultsNavigateAction(order.medusaOrderId);
|
||||
router.push(`${pathsConfig.app.analysisResults}/${order.id}`);
|
||||
} else {
|
||||
router.push(`${pathsConfig.app.myOrders}/${order.medusaOrderId}`);
|
||||
router.push(`${pathsConfig.app.myOrders}/${order.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -69,27 +78,31 @@ export default function OrderItemsTable({
|
||||
(a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
|
||||
)
|
||||
.map((orderItem) => (
|
||||
<div key={`${orderItem.id}-mobile`}>
|
||||
<React.Fragment key={`${orderItem.id}-mobile`}>
|
||||
<MobileTableRow
|
||||
titleKey={title}
|
||||
title={t(title)}
|
||||
value={orderItem.product_title || ''}
|
||||
/>
|
||||
<MobileTableRow
|
||||
titleKey="orders:table.createdAt"
|
||||
title={t('orders:table.createdAt')}
|
||||
value={formatDate(orderItem.created_at, 'dd.MM.yyyy HH:mm')}
|
||||
/>
|
||||
{order.location && (
|
||||
<MobileTableRow
|
||||
titleKey="orders:table.location"
|
||||
title={t('orders:table.location')}
|
||||
value={order.location}
|
||||
/>
|
||||
)}
|
||||
<MobileTableRow
|
||||
titleKey="orders:table.status"
|
||||
title={t('orders:table.status')}
|
||||
value={
|
||||
isPackage
|
||||
? `orders:status.analysisPackageOrder.${order?.status ?? 'CONFIRMED'}`
|
||||
: `orders:status.${type}.${order?.status ?? 'CONFIRMED'}`
|
||||
? t(
|
||||
`orders:status.analysisPackageOrder.${order?.status ?? 'CONFIRMED'}`,
|
||||
)
|
||||
: t(
|
||||
`orders:status.${type}.${order?.status ?? 'CONFIRMED'}`,
|
||||
)
|
||||
}
|
||||
/>
|
||||
<TableRow>
|
||||
@@ -109,7 +122,7 @@ export default function OrderItemsTable({
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</div>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
@@ -171,7 +184,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"
|
||||
@@ -185,12 +198,18 @@ export default function OrderItemsTable({
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{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"
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { cache } from 'react';
|
||||
|
||||
import { getProductCategories, listProducts } from '@lib/data';
|
||||
|
||||
import { isPaymentRequiredForService } from './actions';
|
||||
import { loadCountryCodes } from './load-analyses';
|
||||
|
||||
async function categoryLoader({ handle }: { handle: string }) {
|
||||
@@ -26,6 +27,24 @@ async function categoryLoader({ handle }: { handle: string }) {
|
||||
queryParams: { limit: 100, category_id: response.product_categories[0].id },
|
||||
});
|
||||
|
||||
const productsWithNoRequiredPayment = categoryProducts.filter(
|
||||
async (product) => {
|
||||
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 +55,7 @@ async function categoryLoader({ handle }: { handle: string }) {
|
||||
handle: category?.handle || '',
|
||||
name: category?.name || '',
|
||||
countryCode,
|
||||
products: categoryProducts,
|
||||
products: productsWithNoRequiredPayment,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import { RequestStatus } from '@/lib/types/audit';
|
||||
import {
|
||||
AvailableAppointmentsResponse,
|
||||
BookTimeResponse,
|
||||
ConfirmedLoadResponse,
|
||||
ConnectedOnlineMethodName,
|
||||
FailureReason,
|
||||
} from '@/lib/types/connected-online';
|
||||
@@ -99,7 +98,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 +152,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 +206,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 +220,7 @@ export async function bookAppointment(
|
||||
AddToBasket: false,
|
||||
Key: dbClinic.key,
|
||||
Lang: 'et',
|
||||
Location: dbReservation.location_sync_id,
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -275,16 +280,34 @@ export async function bookAppointment(
|
||||
'Booked time, updated reservation with id ' + updatedReservation?.id,
|
||||
);
|
||||
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.BookTime,
|
||||
RequestStatus.Success,
|
||||
JSON.stringify(connectedOnlineBookingResponseData),
|
||||
startTime.toString(),
|
||||
service.id,
|
||||
clinicId,
|
||||
);
|
||||
return { success: true };
|
||||
if (responseParts[1]) {
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.BookTime,
|
||||
RequestStatus.Success,
|
||||
JSON.stringify(connectedOnlineBookingResponseData),
|
||||
startTime.toString(),
|
||||
service.id,
|
||||
clinicId,
|
||||
);
|
||||
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 +319,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}`,
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
},
|
||||
param: JSON.stringify({ Value: `${reservationCode}|7T624nlu|et` }),
|
||||
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',
|
||||
},
|
||||
);
|
||||
|
||||
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,
|
||||
|
||||
@@ -443,9 +443,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) {
|
||||
|
||||
@@ -194,6 +194,7 @@ export async function getTtoLocation(syncId?: number | null) {
|
||||
.from('connected_online_locations')
|
||||
.select('name')
|
||||
.eq('sync_id', syncId)
|
||||
.limit(1)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -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, StoreCartPromotion } from '@medusajs/types';
|
||||
import type { HttpTypes, StoreCart, StoreCartPromotion } from '@medusajs/types';
|
||||
|
||||
import { getLogger } from '@kit/shared/logger';
|
||||
|
||||
|
||||
2033
pnpm-lock.yaml
generated
2033
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -25,7 +25,8 @@
|
||||
"FULL_ANALYSIS_RESPONSE": "Kõik tulemused käes",
|
||||
"COMPLETED": "Kinnitatud",
|
||||
"REJECTED": "Tagastatud",
|
||||
"CANCELLED": "Tühistatud"
|
||||
"CANCELLED": "Tühistatud",
|
||||
"CONFIRMED": "Kinnitatud"
|
||||
},
|
||||
"analysisPackageOrder": {
|
||||
"QUEUED": "Esitatud",
|
||||
|
||||
Reference in New Issue
Block a user