70 lines
2.0 KiB
TypeScript
70 lines
2.0 KiB
TypeScript
/* eslint-disable canonical/id-match */
|
|
'use server';
|
|
// eslint-disable-next-line sonarjs/no-internal-api-use
|
|
import type * as ApolloTypes from '../../../packages/graphql/node_modules/@apollo/client/core';
|
|
import { getProfile } from './profile';
|
|
import { formatDate, formatTime, sumTime } from '@/utils/date';
|
|
import * as api from '@repo/graphql/api';
|
|
import { Enum_Customer_Role, Enum_Slot_State } from '@repo/graphql/types';
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
type FixTypescriptCringe = ApolloTypes.FetchResult;
|
|
|
|
export const getOrder = api.getOrder;
|
|
|
|
type OrderInput = {
|
|
clientId: string;
|
|
date: Date;
|
|
serviceId: string;
|
|
slotId: string;
|
|
time: string;
|
|
};
|
|
|
|
export async function createOrder(input: OrderInput) {
|
|
const customer = await getProfile();
|
|
|
|
if (!input.slotId) {
|
|
throw new Error('Missing slot');
|
|
}
|
|
|
|
const { data } = await api.getSlot({ documentId: input.slotId });
|
|
|
|
if (data.slot?.state === Enum_Slot_State.Closed) {
|
|
throw new Error('Slot is closed');
|
|
}
|
|
|
|
if (customer.role === Enum_Customer_Role.Client) {
|
|
if (customer.documentId !== input.clientId) {
|
|
throw new Error('Invalid client');
|
|
}
|
|
|
|
const masterId = data.slot?.master?.documentId;
|
|
|
|
const masters = await api.getCustomerMasters(customer);
|
|
|
|
if (!masters.data.customers.some((master) => master?.documentId === masterId)) {
|
|
throw new Error('Invalid master');
|
|
}
|
|
}
|
|
|
|
if (
|
|
customer.role === Enum_Customer_Role.Master &&
|
|
data.slot?.master?.documentId !== customer.documentId
|
|
) {
|
|
throw new Error('Invalid master');
|
|
}
|
|
|
|
const service = await api.getService({ documentId: input.serviceId });
|
|
|
|
const endTime = sumTime(input.time, service?.data?.service?.duration);
|
|
const payload = {
|
|
client: input.clientId,
|
|
date: formatDate(input.date).db(),
|
|
services: [input.serviceId],
|
|
slot: input.slotId,
|
|
time_end: formatTime(endTime).db(),
|
|
time_start: formatTime(input.time).db(),
|
|
};
|
|
return api.createOrder(payload);
|
|
}
|