54 lines
1.8 KiB
TypeScript
54 lines
1.8 KiB
TypeScript
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";
|
|
import { GetCustomerByIdAdapter } from "../adapters";
|
|
import {
|
|
type UpdateCustomerByIdParams,
|
|
type UpdateCustomerByIdResult,
|
|
updateCustomerById,
|
|
} from "../api";
|
|
import type { Customer } from "../entities";
|
|
|
|
import { syncUpdatedCustomerCaches } from "./customer-cache-strategy";
|
|
import { CUSTOMER_UPDATE_KEY } from "./keys";
|
|
import { toValidationErrors } from "./to-validation-errors";
|
|
|
|
type UpdateCustomerContext = {};
|
|
|
|
export const useCustomerUpdateMutation = () => {
|
|
const queryClient = useQueryClient();
|
|
const dataSource = useDataSource();
|
|
const schema = UpdateCustomerByIdRequestSchema;
|
|
|
|
return useMutation<Customer, DefaultError, UpdateCustomerByIdParams, UpdateCustomerContext>({
|
|
mutationKey: CUSTOMER_UPDATE_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 actualizar 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: UpdateCustomerByIdResult = await updateCustomerById(dataSource, params);
|
|
return GetCustomerByIdAdapter.fromDTO(dto);
|
|
},
|
|
|
|
onSuccess: (updatedCustomer) => {
|
|
syncUpdatedCustomerCaches(queryClient, updatedCustomer);
|
|
},
|
|
});
|
|
};
|