MED-103: add booking functionality
This commit is contained in:
@@ -1,14 +1,14 @@
|
||||
'use server'
|
||||
|
||||
import { RequestStatus } from '@/lib/types/audit';
|
||||
'use server';
|
||||
|
||||
import { RequestStatus, SyncStatus } from '@/lib/types/audit';
|
||||
import { ConnectedOnlineMethodName } from '@/lib/types/connected-online';
|
||||
import { ExternalApi } from '@/lib/types/external';
|
||||
import { MedipostAction } from '@/lib/types/medipost';
|
||||
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
|
||||
export default async function logRequestResult(
|
||||
/* personalCode: string, */ requestApi: keyof typeof ExternalApi,
|
||||
requestApi: keyof typeof ExternalApi,
|
||||
requestApiMethod: `${ConnectedOnlineMethodName}` | `${MedipostAction}`,
|
||||
status: RequestStatus,
|
||||
comment?: string,
|
||||
@@ -16,11 +16,10 @@ export default async function logRequestResult(
|
||||
serviceId?: number,
|
||||
serviceProviderId?: number,
|
||||
) {
|
||||
const { error } = await getSupabaseServerClient()
|
||||
const { error } = await getSupabaseServerAdminClient()
|
||||
.schema('audit')
|
||||
.from('request_entries')
|
||||
.insert({
|
||||
/* personal_code: personalCode, */
|
||||
request_api: requestApi,
|
||||
request_api_method: requestApiMethod,
|
||||
requested_start_date: startTime,
|
||||
@@ -69,3 +68,29 @@ export async function getMedipostDispatchTries(medusaOrderId: string) {
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function logSyncResult({
|
||||
operation,
|
||||
comment,
|
||||
status,
|
||||
changed_by_role,
|
||||
}: {
|
||||
operation: string;
|
||||
comment?: string;
|
||||
status: SyncStatus;
|
||||
changed_by_role: string;
|
||||
}) {
|
||||
const { error } = await getSupabaseServerAdminClient()
|
||||
.schema('audit')
|
||||
.from('sync_entries')
|
||||
.insert({
|
||||
operation,
|
||||
comment,
|
||||
status,
|
||||
changed_by_role,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw new Error('Failed to insert log entry, error: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,19 +7,30 @@ import {
|
||||
BookTimeResponse,
|
||||
ConfirmedLoadResponse,
|
||||
ConnectedOnlineMethodName,
|
||||
FailureReason,
|
||||
} from '@/lib/types/connected-online';
|
||||
import { ExternalApi } from '@/lib/types/external';
|
||||
import { Tables } from '@/packages/supabase/src/database.types';
|
||||
import { createClient } from '@/utils/supabase/server';
|
||||
import { StoreOrder } from '@medusajs/types';
|
||||
import axios from 'axios';
|
||||
import { uniq, uniqBy } from 'lodash';
|
||||
|
||||
import { renderBookTimeFailedEmail } from '@kit/email-templates';
|
||||
import { getLogger } from '@kit/shared/logger';
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
|
||||
import { TimeSlotResponse } from '../../app/home/(user)/_components/booking/booking.context';
|
||||
import { sendEmailFromTemplate } from './mailer.service';
|
||||
import { handleDeleteCartItem } from './medusaCart.service';
|
||||
|
||||
export async function getAvailableAppointmentsForService(
|
||||
serviceId: number,
|
||||
key: string,
|
||||
locationId: number | null,
|
||||
startTime?: Date,
|
||||
) {
|
||||
try {
|
||||
const showTimesFrom = startTime ? { StartTime: startTime } : {};
|
||||
|
||||
const start = startTime ? { StartTime: startTime } : {};
|
||||
const response = await axios.post(
|
||||
`${process.env.CONNECTED_ONLINE_URL!}/${ConnectedOnlineMethodName.GetAvailabilities}`,
|
||||
{
|
||||
@@ -28,9 +39,11 @@ export async function getAvailableAppointmentsForService(
|
||||
},
|
||||
param: JSON.stringify({
|
||||
ServiceID: serviceId,
|
||||
Key: '7T624nlu',
|
||||
Key: key,
|
||||
Lang: 'et',
|
||||
...showTimesFrom,
|
||||
MaxDays: 120,
|
||||
LocationId: locationId ?? -1,
|
||||
...start,
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -51,12 +64,12 @@ export async function getAvailableAppointmentsForService(
|
||||
: `No booking times present in appointment availability response, service id: ${serviceId}, start time: ${startTime}`;
|
||||
}
|
||||
|
||||
// await logRequestResult(
|
||||
// ExternalApi.ConnectedOnline,
|
||||
// ConnectedOnlineMethodName.GetAvailabilities,
|
||||
// RequestStatus.Fail,
|
||||
// comment,
|
||||
// );
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.GetAvailabilities,
|
||||
RequestStatus.Fail,
|
||||
comment,
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -80,157 +93,210 @@ export async function getAvailableAppointmentsForService(
|
||||
}
|
||||
|
||||
export async function bookAppointment(
|
||||
serviceSyncId: number,
|
||||
serviceId: number,
|
||||
clinicId: number,
|
||||
appointmentUserId: number,
|
||||
syncUserID: number,
|
||||
startTime: string,
|
||||
locationId = 0,
|
||||
comments = '',
|
||||
isEarlierTimeRequested = false,
|
||||
earlierTimeRequestComment = '',
|
||||
) {
|
||||
const supabase = await createClient();
|
||||
const logger = await getLogger();
|
||||
const supabase = getSupabaseServerClient();
|
||||
|
||||
let reason = FailureReason.BOOKING_FAILED;
|
||||
try {
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
logger.info(
|
||||
`Booking time slot ${JSON.stringify({ serviceId, clinicId, startTime, userId: user?.id })}`,
|
||||
);
|
||||
|
||||
if (!user?.id) {
|
||||
throw new Error('User not authenticated');
|
||||
}
|
||||
|
||||
const formattedStartTime = startTime.replace('T', ' ');
|
||||
|
||||
const [
|
||||
{ data: dbClinic, error: clinicError },
|
||||
{ data: dbService, error: serviceError },
|
||||
{ data: account, error: accountError },
|
||||
{ data: dbReservation, error: dbReservationError },
|
||||
] = await Promise.all([
|
||||
supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_providers')
|
||||
.select('*')
|
||||
.eq('id', clinicId)
|
||||
.limit(1),
|
||||
.single(),
|
||||
supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_services')
|
||||
.select('*')
|
||||
.eq('sync_id', serviceSyncId)
|
||||
.eq('id', serviceId)
|
||||
.eq('clinic_id', clinicId)
|
||||
.limit(1),
|
||||
.single(),
|
||||
supabase
|
||||
.schema('medreport')
|
||||
.from('accounts')
|
||||
.select('name, last_name, personal_code, phone, email')
|
||||
.eq('is_personal_account', true)
|
||||
.eq('primary_owner_user_id', user.id)
|
||||
.single(),
|
||||
supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.select('id')
|
||||
.eq('clinic_id', clinicId)
|
||||
.eq('service_id', serviceId)
|
||||
.eq('start_time', formattedStartTime)
|
||||
.eq('user_id', user.id)
|
||||
.eq('status', 'PENDING')
|
||||
.single(),
|
||||
]);
|
||||
|
||||
if (!dbClinic?.length || !dbService?.length) {
|
||||
return logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.BookTime,
|
||||
RequestStatus.Fail,
|
||||
dbClinic?.length
|
||||
? `Could not find clinic with id ${clinicId}, error: ${JSON.stringify(clinicError)}`
|
||||
: `Could not find service with sync id ${serviceSyncId} and clinic id ${clinicId}, error: ${JSON.stringify(serviceError)}`,
|
||||
startTime,
|
||||
serviceSyncId,
|
||||
clinicId,
|
||||
);
|
||||
if (!dbClinic || !dbService) {
|
||||
const errorMessage = dbClinic
|
||||
? `Could not find clinic with id ${clinicId}, error: ${JSON.stringify(clinicError)}`
|
||||
: `Could not find service with sync id ${serviceId} and clinic id ${clinicId}, error: ${JSON.stringify(serviceError)}`;
|
||||
logger.error(errorMessage);
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
if (clinicError || serviceError || accountError) {
|
||||
const stringifiedErrors = JSON.stringify({
|
||||
clinicError,
|
||||
serviceError,
|
||||
accountError,
|
||||
});
|
||||
const errorMessage = `Failed to book time, error: ${stringifiedErrors}`;
|
||||
logger.error(errorMessage);
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
if (!dbReservation) {
|
||||
const errorMessage = `No reservation found in db with data ${JSON.stringify({ clinicId, serviceId, startTime, userId: user.id })}, got error ${JSON.stringify(dbReservationError)}`;
|
||||
logger.error(errorMessage);
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const clinic: Tables<
|
||||
{ schema: 'medreport' },
|
||||
'connected_online_providers'
|
||||
> = dbClinic![0];
|
||||
> = dbClinic;
|
||||
const service: Tables<
|
||||
{ schema: 'medreport' },
|
||||
'connected_online_services'
|
||||
> = dbService![0];
|
||||
> = dbService;
|
||||
|
||||
// TODO the dummy data needs to be replaced with real values once they're present on the user/account
|
||||
const response = await axios.post(
|
||||
const connectedOnlineBookingResponse = await axios.post(
|
||||
`${process.env.CONNECTED_ONLINE_URL!}/${ConnectedOnlineMethodName.BookTime}`,
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
},
|
||||
param: JSON.stringify({
|
||||
EarlierTime: isEarlierTimeRequested, // once we have the e-shop functionality we can let the user select if she would like to be offered earlier time slots if they become available
|
||||
EarlierTimeComment: earlierTimeRequestComment,
|
||||
ClinicID: clinic.id,
|
||||
ServiceID: service.id,
|
||||
ClinicServiceID: service.sync_id,
|
||||
UserID: appointmentUserId,
|
||||
SyncUserID: syncUserID,
|
||||
StartTime: startTime,
|
||||
FirstName: 'Test',
|
||||
LastName: 'User',
|
||||
PersonalCode: '4',
|
||||
Email: user.email,
|
||||
Phone: 'phone',
|
||||
FirstName: account.name,
|
||||
LastName: account.last_name,
|
||||
PersonalCode: account.personal_code,
|
||||
Email: account.email ?? user.email,
|
||||
Phone: account.phone,
|
||||
Comments: comments,
|
||||
Location: locationId,
|
||||
FreeCode: '',
|
||||
AddToBasket: false,
|
||||
Key: '7T624nlu',
|
||||
Lang: 'et', // update when integrated into app, if needed
|
||||
Key: dbClinic.key,
|
||||
Lang: 'et',
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const responseData: BookTimeResponse = JSON.parse(response.data.d);
|
||||
const connectedOnlineBookingResponseData: BookTimeResponse = JSON.parse(
|
||||
connectedOnlineBookingResponse.data.d,
|
||||
);
|
||||
|
||||
if (responseData?.ErrorCode !== 0 || !responseData.Value) {
|
||||
return logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.BookTime,
|
||||
RequestStatus.Fail,
|
||||
JSON.stringify(responseData),
|
||||
startTime,
|
||||
service.id,
|
||||
clinicId,
|
||||
const errorCode = connectedOnlineBookingResponseData?.ErrorCode;
|
||||
if (errorCode !== 0 || !connectedOnlineBookingResponseData.Value) {
|
||||
const errorMessage = `Received invalid result from external api, error: ${JSON.stringify(connectedOnlineBookingResponseData)}`;
|
||||
logger.error(errorMessage);
|
||||
if (process.env.SUPPORT_EMAIL) {
|
||||
await sendEmailFromTemplate(
|
||||
renderBookTimeFailedEmail,
|
||||
{ reservationId: dbReservation.id, error: errorMessage },
|
||||
process.env.SUPPORT_EMAIL,
|
||||
);
|
||||
}
|
||||
await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.update({
|
||||
status: 'REJECTED',
|
||||
})
|
||||
.eq('id', dbReservation.id)
|
||||
.throwOnError();
|
||||
|
||||
if (errorCode === 1) {
|
||||
reason = FailureReason.TIME_SLOT_UNAVAILABLE;
|
||||
}
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const responseParts = connectedOnlineBookingResponseData.Value.split(',');
|
||||
|
||||
const { data: updatedReservation, error } = await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.update({
|
||||
booking_code: responseParts[1],
|
||||
requires_payment: !!responseParts[0],
|
||||
status: 'CONFIRMED',
|
||||
})
|
||||
.eq('id', dbReservation.id)
|
||||
.select('id')
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
throw new Error(
|
||||
JSON.stringify({ connectedOnlineBookingResponseData, error }),
|
||||
);
|
||||
}
|
||||
|
||||
const responseParts = responseData.Value.split(',');
|
||||
|
||||
const { error } = await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.insert({
|
||||
booking_code: responseParts[1],
|
||||
clinic_id: clinic.id,
|
||||
comments,
|
||||
lang: 'et', // change later, if needed
|
||||
service_id: service.id,
|
||||
service_user_id: appointmentUserId,
|
||||
start_time: startTime,
|
||||
sync_user_id: syncUserID,
|
||||
requires_payment: !!responseParts[0],
|
||||
user_id: user.id,
|
||||
});
|
||||
logger.info(
|
||||
'Booked time, updated reservation with id ' + updatedReservation?.id,
|
||||
);
|
||||
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.BookTime,
|
||||
RequestStatus.Success,
|
||||
JSON.stringify(responseData),
|
||||
startTime,
|
||||
JSON.stringify(connectedOnlineBookingResponseData),
|
||||
startTime.toString(),
|
||||
service.id,
|
||||
clinicId,
|
||||
);
|
||||
|
||||
if (error) {
|
||||
throw new Error(error.message);
|
||||
}
|
||||
|
||||
return responseData.Value;
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return logRequestResult(
|
||||
logger.error(`Failed to book time, error: ${JSON.stringify(error)}`);
|
||||
await logRequestResult(
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.BookTime,
|
||||
RequestStatus.Fail,
|
||||
JSON.stringify(error),
|
||||
startTime,
|
||||
serviceSyncId,
|
||||
startTime.toString(),
|
||||
serviceId,
|
||||
clinicId,
|
||||
);
|
||||
return { success: false, reason };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,8 +336,182 @@ export async function getConfirmedService(reservationCode: string) {
|
||||
ExternalApi.ConnectedOnline,
|
||||
ConnectedOnlineMethodName.ConfirmedLoad,
|
||||
RequestStatus.Fail,
|
||||
JSON.stringify(error),
|
||||
error?.toString(),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAvailableTimeSlotsForDisplay(
|
||||
serviceIds: number[],
|
||||
locationId: number | null,
|
||||
date?: Date,
|
||||
): Promise<TimeSlotResponse> {
|
||||
const supabase = getSupabaseServerClient();
|
||||
|
||||
const { data: syncedServices } = await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_services')
|
||||
.select(
|
||||
'*, providerClinic:clinic_id(*,locations:connected_online_locations(*))',
|
||||
)
|
||||
.in('id', serviceIds)
|
||||
.throwOnError();
|
||||
|
||||
const timeSlotPromises = [];
|
||||
for (const syncedService of syncedServices) {
|
||||
const timeSlotsPromise = getAvailableAppointmentsForService(
|
||||
syncedService.id,
|
||||
syncedService.providerClinic.key,
|
||||
locationId,
|
||||
date,
|
||||
);
|
||||
timeSlotPromises.push(timeSlotsPromise);
|
||||
}
|
||||
|
||||
const timeSlots = await Promise.all(timeSlotPromises);
|
||||
|
||||
const mappedTimeSlots = [];
|
||||
for (const timeSlotGroup of timeSlots) {
|
||||
const { data: serviceProviders } = await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_service_providers')
|
||||
.select(
|
||||
'name, id, jobTitleEn: job_title_en, jobTitleEt: job_title_et, jobTitleRu: job_title_ru, clinicId: clinic_id',
|
||||
)
|
||||
.in(
|
||||
'clinic_id',
|
||||
uniq(timeSlotGroup?.T_Booking.map(({ ClinicID }) => ClinicID)),
|
||||
)
|
||||
.throwOnError();
|
||||
|
||||
const timeSlots =
|
||||
timeSlotGroup?.T_Booking?.map((item) => {
|
||||
return {
|
||||
...item,
|
||||
serviceProvider: serviceProviders.find(
|
||||
({ id }) => id === item.UserID,
|
||||
),
|
||||
syncedService: syncedServices.find(
|
||||
(syncedService) => syncedService.sync_id === item.ServiceID,
|
||||
),
|
||||
location: syncedServices
|
||||
.find(
|
||||
({ providerClinic }) =>
|
||||
providerClinic.id === Number(item.ClinicID),
|
||||
)
|
||||
?.providerClinic?.locations?.find(
|
||||
(location) => location.sync_id === item.LocationID,
|
||||
),
|
||||
};
|
||||
}) ?? [];
|
||||
mappedTimeSlots.push(...timeSlots);
|
||||
}
|
||||
|
||||
return {
|
||||
timeSlots: mappedTimeSlots,
|
||||
locations: uniqBy(
|
||||
syncedServices.flatMap(({ providerClinic }) => providerClinic.locations),
|
||||
'id',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createInitialReservation(
|
||||
serviceId: number,
|
||||
clinicId: number,
|
||||
appointmentUserId: number,
|
||||
syncUserID: number,
|
||||
startTime: Date,
|
||||
medusaLineItemId: string,
|
||||
locationId?: number | null,
|
||||
comments = '',
|
||||
) {
|
||||
const logger = await getLogger();
|
||||
const supabase = getSupabaseServerClient();
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
const userId = user?.id;
|
||||
|
||||
if (!userId) {
|
||||
throw new Error('User not authenticated');
|
||||
}
|
||||
|
||||
logger.info(
|
||||
'Creating reservation' +
|
||||
JSON.stringify({ serviceId, clinicId, startTime, userId }),
|
||||
);
|
||||
|
||||
try {
|
||||
const { data: createdReservation } = await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.insert({
|
||||
clinic_id: clinicId,
|
||||
comments,
|
||||
lang: 'et',
|
||||
service_id: serviceId,
|
||||
service_user_id: appointmentUserId,
|
||||
start_time: startTime.toString(),
|
||||
sync_user_id: syncUserID,
|
||||
user_id: userId,
|
||||
status: 'PENDING',
|
||||
medusa_cart_line_item_id: medusaLineItemId,
|
||||
location_sync_id: locationId,
|
||||
})
|
||||
.select('id')
|
||||
.single()
|
||||
.throwOnError();
|
||||
|
||||
logger.info(
|
||||
`Created reservation ${JSON.stringify({ createdReservation, userId })}`,
|
||||
);
|
||||
|
||||
return createdReservation;
|
||||
} catch (e) {
|
||||
logger.error(
|
||||
`Failed to create initial reservation ${JSON.stringify({ serviceId, clinicId, startTime })} ${e}`,
|
||||
);
|
||||
await handleDeleteCartItem({ lineId: medusaLineItemId });
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export async function cancelReservation(medusaLineItemId: string) {
|
||||
const supabase = getSupabaseServerClient();
|
||||
|
||||
return supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.update({
|
||||
status: 'CANCELLED',
|
||||
})
|
||||
.eq('medusa_cart_line_item_id', medusaLineItemId)
|
||||
.throwOnError();
|
||||
}
|
||||
|
||||
export async function getOrderedTtoServices({
|
||||
medusaOrder,
|
||||
}: {
|
||||
medusaOrder: StoreOrder;
|
||||
}) {
|
||||
const supabase = getSupabaseServerClient();
|
||||
|
||||
const ttoReservationIds: number[] =
|
||||
medusaOrder.items
|
||||
?.filter(({ metadata }) => !!metadata?.connectedOnlineReservationId)
|
||||
.map(({ metadata }) => Number(metadata!.connectedOnlineReservationId)) ??
|
||||
[];
|
||||
|
||||
const { data: orderedTtoServices } = await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.select('*')
|
||||
.in('id', ttoReservationIds)
|
||||
.throwOnError();
|
||||
|
||||
return orderedTtoServices;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { z } from 'zod';
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
|
||||
import { requireUserInServerComponent } from '../server/require-user-in-server-component';
|
||||
import { cancelReservation } from './connected-online.service';
|
||||
|
||||
const env = () =>
|
||||
z
|
||||
@@ -26,8 +27,10 @@ const env = () =>
|
||||
.min(1),
|
||||
})
|
||||
.parse({
|
||||
medusaBackendPublicUrl: process.env.MEDUSA_BACKEND_PUBLIC_URL!,
|
||||
siteUrl: process.env.NEXT_PUBLIC_SITE_URL!,
|
||||
medusaBackendPublicUrl:
|
||||
'http://weebhook.site:3000' /* process.env.MEDUSA_BACKEND_PUBLIC_URL! */,
|
||||
siteUrl:
|
||||
'http://weebhook.site:3000' /* process.env.NEXT_PUBLIC_SITE_URL! */,
|
||||
});
|
||||
|
||||
export async function handleAddToCart({
|
||||
@@ -44,7 +47,7 @@ export async function handleAddToCart({
|
||||
}
|
||||
|
||||
const quantity = 1;
|
||||
const cart = await addToCart({
|
||||
const { newCart, addedItem } = await addToCart({
|
||||
variantId: selectedVariant.id,
|
||||
quantity,
|
||||
countryCode,
|
||||
@@ -54,18 +57,19 @@ export async function handleAddToCart({
|
||||
variant_id: selectedVariant.id,
|
||||
operation: 'ADD_TO_CART',
|
||||
account_id: account.id,
|
||||
cart_id: cart.id,
|
||||
cart_id: newCart.id,
|
||||
changed_by: user.id,
|
||||
});
|
||||
if (error) {
|
||||
throw new Error('Error logging cart entry: ' + error.message);
|
||||
}
|
||||
|
||||
return cart;
|
||||
return { cart: newCart, addedItem };
|
||||
}
|
||||
|
||||
export async function handleDeleteCartItem({ lineId }: { lineId: string }) {
|
||||
await deleteLineItem(lineId);
|
||||
await cancelReservation(lineId);
|
||||
|
||||
const supabase = getSupabaseServerClient();
|
||||
const cartId = await getCartId();
|
||||
|
||||
@@ -152,3 +152,29 @@ export async function getAnalysisOrdersAdmin({
|
||||
const orders = await query.order('created_at', { ascending: false }).throwOnError();
|
||||
return orders.data;
|
||||
}
|
||||
|
||||
export async function getTtoOrders({
|
||||
orderStatus,
|
||||
}: {
|
||||
orderStatus?: Tables<{ schema: 'medreport' }, 'connected_online_reservation'>['status'];
|
||||
} = {}) {
|
||||
const client = getSupabaseServerClient();
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await client.auth.getUser();
|
||||
if (!user) {
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
const query = client
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.select('*')
|
||||
.eq("user_id", user.id)
|
||||
if (orderStatus) {
|
||||
query.eq('status', orderStatus);
|
||||
}
|
||||
const orders = await query.order('created_at', { ascending: false }).throwOnError();
|
||||
return orders.data;
|
||||
}
|
||||
@@ -10,13 +10,15 @@ export type BookTimeResponse = z.infer<typeof BookTimeResponseSchema>;
|
||||
|
||||
export enum ConnectedOnlineMethodName {
|
||||
SearchLoad = 'Search_Load',
|
||||
DefaultLoad = 'Default_Load',
|
||||
ConfirmedCancel = 'Confirmed_Cancel',
|
||||
GetAvailabilities = 'GetAvailabilities',
|
||||
BookTime = 'BookTime',
|
||||
ConfirmedLoad = 'Confirmed_Load',
|
||||
}
|
||||
|
||||
export const AvailableAppointmentTBookingSchema = z.object({
|
||||
ClinicID: z.string(),
|
||||
ClinicID: z.number(),
|
||||
LocationID: z.number(),
|
||||
UserID: z.number(),
|
||||
SyncUserID: z.number(),
|
||||
@@ -225,6 +227,18 @@ export const ConfirmedLoadResponseSchema = z.object({
|
||||
});
|
||||
export type ConfirmedLoadResponse = z.infer<typeof ConfirmedLoadResponseSchema>;
|
||||
|
||||
export type P_JobTitleTranslation = {
|
||||
ID: number;
|
||||
SyncID: number;
|
||||
TextEN: string;
|
||||
TextET: string;
|
||||
TextFI: string;
|
||||
TextRU: string;
|
||||
TextLT: string;
|
||||
ClinicID: number;
|
||||
Deleted: number;
|
||||
};
|
||||
|
||||
export interface ISearchLoadResponse {
|
||||
Value: string;
|
||||
Data: {
|
||||
@@ -232,9 +246,11 @@ export interface ISearchLoadResponse {
|
||||
ID: number;
|
||||
Name: string;
|
||||
OnlineCanSelectWorker: boolean;
|
||||
Address: string;
|
||||
Email: string | null;
|
||||
PersonalCodeRequired: boolean;
|
||||
Phone: string | null;
|
||||
Key: string;
|
||||
}[];
|
||||
T_Service: {
|
||||
ID: number;
|
||||
@@ -253,7 +269,14 @@ export interface ISearchLoadResponse {
|
||||
RequiresPayment: boolean;
|
||||
SyncID: string;
|
||||
}[];
|
||||
T_Doctor: TDoctor[];
|
||||
P_JobTitleTranslations: P_JobTitleTranslation[];
|
||||
};
|
||||
ErrorCode: number;
|
||||
ErrorMessage: string;
|
||||
}
|
||||
|
||||
export enum FailureReason {
|
||||
BOOKING_FAILED = 'BOOKING_FAILED',
|
||||
TIME_SLOT_UNAVAILABLE = 'TIME_SLOT_UNAVAILABLE',
|
||||
}
|
||||
|
||||
11
lib/utils.ts
11
lib/utils.ts
@@ -20,7 +20,7 @@ export function toTitleCase(str?: string) {
|
||||
?.toLowerCase()
|
||||
.replace(/[^-'’\s]+/g, (match) =>
|
||||
match.replace(/^./, (first) => first.toUpperCase()),
|
||||
) ?? ""
|
||||
) ?? ''
|
||||
);
|
||||
}
|
||||
|
||||
@@ -145,6 +145,13 @@ export default class PersonalCode {
|
||||
gender,
|
||||
dob: parsed.getBirthday(),
|
||||
age: parsed.getAge(),
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const findProductTypeIdByHandle = (
|
||||
productTypes: { metadata?: Record<string, unknown> | null; id: string }[],
|
||||
handle: string,
|
||||
) => {
|
||||
return productTypes.find(({ metadata }) => metadata?.handle === handle)?.id;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user