2025-09-17 17:37:41 +00:00
|
|
|
import { useDataSource } from "@erp/core/hooks";
|
2025-09-23 11:48:19 +00:00
|
|
|
import { UniqueID, ValidationErrorCollection } from "@repo/rdx-ddd";
|
2025-08-11 17:49:52 +00:00
|
|
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
2025-09-23 11:48:19 +00:00
|
|
|
import { CreateCustomerRequestSchema, CustomerCreationResponseDTO } from "../../common";
|
2025-09-23 17:21:16 +00:00
|
|
|
import { CustomerFormData } from "../schemas";
|
2025-09-17 17:37:41 +00:00
|
|
|
import { CUSTOMERS_LIST_KEY } from "./use-update-customer-mutation";
|
2025-08-11 17:49:52 +00:00
|
|
|
|
2025-09-22 17:43:55 +00:00
|
|
|
type CreateCustomerPayload = {
|
2025-09-23 17:21:16 +00:00
|
|
|
data: CustomerFormData;
|
2025-09-22 17:43:55 +00:00
|
|
|
};
|
|
|
|
|
|
2025-09-17 17:37:41 +00:00
|
|
|
export function useCreateCustomerMutation() {
|
2025-08-11 17:49:52 +00:00
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const dataSource = useDataSource();
|
2025-09-23 11:48:19 +00:00
|
|
|
const schema = CreateCustomerRequestSchema;
|
2025-08-11 17:49:52 +00:00
|
|
|
|
2025-09-23 11:48:19 +00:00
|
|
|
return useMutation<CustomerCreationResponseDTO, Error, CreateCustomerPayload>({
|
2025-09-16 17:29:37 +00:00
|
|
|
mutationKey: ["customer:create"],
|
2025-09-22 17:43:55 +00:00
|
|
|
|
|
|
|
|
mutationFn: async (payload) => {
|
|
|
|
|
const { data } = payload;
|
|
|
|
|
const customerId = UniqueID.generateNewID();
|
|
|
|
|
|
2025-09-23 11:48:19 +00:00
|
|
|
const newCustomerData = {
|
2025-09-22 17:43:55 +00:00
|
|
|
...data,
|
|
|
|
|
id: customerId.toString(),
|
2025-09-23 11:48:19 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const result = schema.safeParse(newCustomerData);
|
|
|
|
|
if (!result.success) {
|
|
|
|
|
// Construye errores detallados
|
|
|
|
|
const validationErrors = result.error.issues.map((err) => ({
|
|
|
|
|
field: err.path.join("."),
|
|
|
|
|
message: err.message,
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
throw new ValidationErrorCollection("Validation failed", validationErrors);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const created = await dataSource.createOne("customers", newCustomerData);
|
|
|
|
|
return created as CustomerCreationResponseDTO;
|
2025-08-11 17:49:52 +00:00
|
|
|
},
|
2025-09-22 17:43:55 +00:00
|
|
|
|
2025-08-11 17:49:52 +00:00
|
|
|
onSuccess: () => {
|
2025-09-22 17:43:55 +00:00
|
|
|
// Invalida el listado para refrescar desde servidor
|
2025-09-17 17:37:41 +00:00
|
|
|
queryClient.invalidateQueries({ queryKey: CUSTOMERS_LIST_KEY });
|
2025-08-11 17:49:52 +00:00
|
|
|
},
|
|
|
|
|
});
|
2025-09-17 17:37:41 +00:00
|
|
|
}
|