FactuGES_ERP/modules/customers/src/web/shared/hooks/use-customer-create-mutation.ts

61 lines
2.0 KiB
TypeScript
Raw Normal View History

2026-04-03 19:49:59 +00:00
import { useDataSource } from "@erp/core/hooks";
2026-04-04 17:38:09 +00:00
import { ValidationErrorCollection } from "@repo/rdx-ddd";
2026-04-03 19:49:59 +00:00
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,
2026-04-05 12:01:52 +00:00
mutationFn: async (params) => {
2026-04-05 16:04:43 +00:00
const { id: customerId, data } = params;
if (!customerId) {
throw new Error("customerId is required");
}
const result = schema.safeParse(data);
2026-04-03 19:49:59 +00:00
if (!result.success) {
2026-06-28 18:04:46 +00:00
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;
2026-04-03 19:49:59 +00:00
}
2026-04-05 12:01:52 +00:00
const dto: CreateCustomerResult = await createCustomer(dataSource, params);
2026-04-03 19:49:59 +00:00
return GetCustomerByIdAdapter.fromDTO(dto);
},
onSuccess: (createdCustomer) => {
syncCreatedCustomerCaches(queryClient, createdCustomer);
},
onSettled: async () => {
await invalidateCustomerListQueries(queryClient);
},
});
};