2026-04-03 19:49:59 +00:00
|
|
|
import { useDataSource } from "@erp/core/hooks";
|
|
|
|
|
import { UniqueID, ValidationErrorCollection } from "@repo/rdx-ddd";
|
|
|
|
|
import { type DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
|
|
|
|
|
|
|
|
import { CreateCustomerRequestSchema } from "../../../common";
|
|
|
|
|
import { GetCustomerByIdAdapter } from "../adapters";
|
2026-04-04 16:58:32 +00:00
|
|
|
import { type CreateCustomerParams, type CreateCustomerResult, createCustomer } from "../api";
|
2026-04-03 19:49:59 +00:00
|
|
|
import type { Customer } from "../entities";
|
|
|
|
|
|
|
|
|
|
import {
|
|
|
|
|
invalidateCustomerListQueries,
|
|
|
|
|
syncCreatedCustomerCaches,
|
|
|
|
|
} from "./customer-cache-strategy";
|
|
|
|
|
import { CUSTOMER_CREATE_KEY } from "./keys";
|
|
|
|
|
import { toValidationErrors } from "./to-validation-errors";
|
|
|
|
|
|
|
|
|
|
type CreateCustomerContext = {};
|
|
|
|
|
|
|
|
|
|
export const useCustomerCreateMutation = () => {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const dataSource = useDataSource();
|
|
|
|
|
const schema = CreateCustomerRequestSchema;
|
|
|
|
|
|
2026-04-04 16:58:32 +00:00
|
|
|
return useMutation<Customer, DefaultError, CreateCustomerParams, CreateCustomerContext>({
|
2026-04-03 19:49:59 +00:00
|
|
|
mutationKey: CUSTOMER_CREATE_KEY,
|
|
|
|
|
|
|
|
|
|
mutationFn: async (payload) => {
|
|
|
|
|
const id = UniqueID.generateNewID().toString();
|
2026-04-04 16:58:32 +00:00
|
|
|
const payloadWithId: CreateCustomerParams = { ...payload, id };
|
2026-04-03 19:49:59 +00:00
|
|
|
|
2026-04-04 16:58:32 +00:00
|
|
|
const result = schema.safeParse(payloadWithId);
|
2026-04-03 19:49:59 +00:00
|
|
|
if (!result.success) {
|
|
|
|
|
throw new ValidationErrorCollection("Validation failed", toValidationErrors(result.error));
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-04 16:58:32 +00:00
|
|
|
const dto: CreateCustomerResult = await createCustomer(dataSource, payloadWithId);
|
2026-04-03 19:49:59 +00:00
|
|
|
return GetCustomerByIdAdapter.fromDTO(dto);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
onSuccess: (createdCustomer) => {
|
|
|
|
|
syncCreatedCustomerCaches(queryClient, createdCustomer);
|
|
|
|
|
},
|
|
|
|
|
onSettled: async () => {
|
|
|
|
|
await invalidateCustomerListQueries(queryClient);
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
};
|