2025-09-16 17:29:37 +00:00
|
|
|
import { useDataSource } from "@erp/core/hooks";
|
|
|
|
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
2025-09-17 17:37:41 +00:00
|
|
|
import { CustomerData, CustomerUpdateData } from "../schemas";
|
2025-09-16 17:29:37 +00:00
|
|
|
import { CUSTOMER_QUERY_KEY } from "./use-customer-query";
|
|
|
|
|
|
|
|
|
|
export const CUSTOMERS_LIST_KEY = ["customers"] as const;
|
|
|
|
|
|
2025-09-17 17:37:41 +00:00
|
|
|
type UpdateCustomerPayload = {
|
|
|
|
|
id: string;
|
|
|
|
|
data: CustomerUpdateData;
|
|
|
|
|
};
|
2025-09-16 17:29:37 +00:00
|
|
|
|
2025-09-17 17:37:41 +00:00
|
|
|
export function useUpdateCustomerMutation() {
|
2025-09-16 17:29:37 +00:00
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const dataSource = useDataSource();
|
|
|
|
|
|
2025-09-17 17:37:41 +00:00
|
|
|
return useMutation<CustomerData, Error, UpdateCustomerPayload>({
|
|
|
|
|
mutationKey: ["customer:update"], //, customerId],
|
|
|
|
|
|
|
|
|
|
mutationFn: async (payload) => {
|
|
|
|
|
const { id: customerId, data } = payload;
|
|
|
|
|
if (!customerId) {
|
|
|
|
|
throw new Error("customerId is required");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const updated = await dataSource.updateOne("customers", customerId, data);
|
|
|
|
|
return updated as CustomerData;
|
2025-09-16 17:29:37 +00:00
|
|
|
},
|
2025-09-17 17:37:41 +00:00
|
|
|
onSuccess: (updated, variables) => {
|
|
|
|
|
const { id: customerId } = variables;
|
|
|
|
|
|
2025-09-16 17:29:37 +00:00
|
|
|
// Refresca inmediatamente el detalle
|
2025-09-17 17:37:41 +00:00
|
|
|
queryClient.setQueryData<CustomerData>(CUSTOMER_QUERY_KEY(customerId), updated);
|
2025-09-16 17:29:37 +00:00
|
|
|
|
|
|
|
|
// Otra opción es invalidar el detalle para forzar refetch:
|
|
|
|
|
// queryClient.invalidateQueries({ queryKey: CUSTOMER_QUERY_KEY(customerId) });
|
|
|
|
|
|
|
|
|
|
// Invalida el listado para refrescar desde servidor
|
|
|
|
|
queryClient.invalidateQueries({ queryKey: CUSTOMERS_LIST_KEY });
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|