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 type { Customer } from "../api"; import { toValidationErrors } from "./toValidationErrors"; export const CUSTOMER_UPDATE_KEY = ["customers", "update"] as const; type UpdateCustomerContext = {}; type UpdateCustomerPayload = { id: string; data: Partial; }; export const useCustomerUpdateMutation = () => { const queryClient = useQueryClient(); const dataSource = useDataSource(); const schema = UpdateCustomerByIdRequestSchema; return useMutation({ mutationKey: CUSTOMER_UPDATE_KEY, mutationFn: async (payload) => { const { id: customerId, data } = payload; if (!customerId) { throw new Error("customerId is required"); } const result = schema.safeParse(data); if (!result.success) { throw new ValidationErrorCollection("Validation failed", toValidationErrors(result.error)); } const updated = await dataSource.updateOne("customers", customerId, data); return updated as Customer; }, onSuccess: (updated: Customer, variables) => { const { id: customerId } = updated; // Invalida el listado para refrescar desde servidor //invalidateCustomerListCache(queryClient); // Actualiza detalle //setCustomerDetailCache(queryClient, customerId, updated); // Actualiza todas las páginas donde aparezca //upsertCustomerIntoListCaches(queryClient, { ...updated }); }, onSettled: () => { // Refresca todos los listados //invalidateCustomerListCache(queryClient); }, }); };