Uecko_ERP/modules/customers/src/web/shared/hooks/use-customer-update-mutation.ts

54 lines
1.8 KiB
TypeScript
Raw Normal View History

2026-03-16 17:45:45 +00:00
import { useDataSource } from "@erp/core/hooks";
import { ValidationErrorCollection } from "@repo/rdx-ddd";
import { type DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
import { UpdateCustomerByIdRequestSchema } from "../../../common";
2026-04-03 19:49:59 +00:00
import { GetCustomerByIdAdapter } from "../adapters";
2026-04-04 16:58:32 +00:00
import {
type UpdateCustomerByIdParams,
type UpdateCustomerByIdResult,
updateCustomerById,
} from "../api";
2026-04-03 19:49:59 +00:00
import type { Customer } from "../entities";
2026-03-16 17:45:45 +00:00
2026-04-05 16:00:37 +00:00
import { syncUpdatedCustomerCaches } from "./customer-cache-strategy";
2026-04-03 19:49:59 +00:00
import { CUSTOMER_UPDATE_KEY } from "./keys";
import { toValidationErrors } from "./to-validation-errors";
2026-03-16 17:45:45 +00:00
type UpdateCustomerContext = {};
export const useCustomerUpdateMutation = () => {
const queryClient = useQueryClient();
const dataSource = useDataSource();
const schema = UpdateCustomerByIdRequestSchema;
2026-04-04 16:58:32 +00:00
return useMutation<Customer, DefaultError, UpdateCustomerByIdParams, UpdateCustomerContext>({
2026-03-16 17:45:45 +00:00
mutationKey: CUSTOMER_UPDATE_KEY,
2026-04-05 12:01:52 +00:00
mutationFn: async (params) => {
const { id: customerId, data } = params;
2026-03-16 17:45:45 +00:00
if (!customerId) {
throw new Error("customerId is required");
}
const result = schema.safeParse(data);
if (!result.success) {
2026-04-20 19:15:35 +00:00
console.log("Error de validación al actualizar cliente:", toValidationErrors(result.error));
const errorCollection = new ValidationErrorCollection(
"Validation failed",
toValidationErrors(result.error)
);
console.log("Errores de validación convertidos:", errorCollection);
throw errorCollection;
2026-03-16 17:45:45 +00:00
}
2026-04-05 16:00:37 +00:00
const dto: UpdateCustomerByIdResult = await updateCustomerById(dataSource, params);
2026-04-03 19:49:59 +00:00
return GetCustomerByIdAdapter.fromDTO(dto);
2026-03-16 17:45:45 +00:00
},
2026-04-03 19:49:59 +00:00
onSuccess: (updatedCustomer) => {
syncUpdatedCustomerCaches(queryClient, updatedCustomer);
2026-03-16 17:45:45 +00:00
},
});
};