61 lines
2.0 KiB
TypeScript
61 lines
2.0 KiB
TypeScript
import { useDataSource } from "@erp/core/hooks";
|
|
import { ValidationErrorCollection } from "@repo/rdx-ddd";
|
|
import { type DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
|
|
import { CreateCustomerRequestSchema } from "../../../common";
|
|
import { GetCustomerByIdAdapter } from "../adapters";
|
|
import { type CreateCustomerParams, type CreateCustomerResult, createCustomer } from "../api";
|
|
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;
|
|
|
|
return useMutation<Customer, DefaultError, CreateCustomerParams, CreateCustomerContext>({
|
|
mutationKey: CUSTOMER_CREATE_KEY,
|
|
|
|
mutationFn: async (params) => {
|
|
const { id: customerId, data } = params;
|
|
|
|
if (!customerId) {
|
|
throw new Error("customerId is required");
|
|
}
|
|
|
|
const result = schema.safeParse(data);
|
|
if (!result.success) {
|
|
console.log(
|
|
"Error de validación al crear nuevo cliente:",
|
|
toValidationErrors(result.error)
|
|
);
|
|
|
|
const errorCollection = new ValidationErrorCollection(
|
|
"Validation failed",
|
|
toValidationErrors(result.error)
|
|
);
|
|
console.log("Errores de validación convertidos:", errorCollection);
|
|
throw errorCollection;
|
|
}
|
|
|
|
const dto: CreateCustomerResult = await createCustomer(dataSource, params);
|
|
return GetCustomerByIdAdapter.fromDTO(dto);
|
|
},
|
|
|
|
onSuccess: (createdCustomer) => {
|
|
syncCreatedCustomerCaches(queryClient, createdCustomer);
|
|
},
|
|
onSettled: async () => {
|
|
await invalidateCustomerListQueries(queryClient);
|
|
},
|
|
});
|
|
};
|