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";
|
|
|
|
|
import type { Customer } from "../api";
|
2026-03-18 16:38:40 +00:00
|
|
|
import type { CustomerData } from "../types";
|
2026-03-16 17:45:45 +00:00
|
|
|
|
|
|
|
|
import { toValidationErrors } from "./toValidationErrors";
|
|
|
|
|
|
|
|
|
|
export const CUSTOMER_UPDATE_KEY = ["customers", "update"] as const;
|
|
|
|
|
|
|
|
|
|
type UpdateCustomerContext = {};
|
|
|
|
|
|
|
|
|
|
type UpdateCustomerPayload = {
|
|
|
|
|
id: string;
|
2026-03-18 16:38:40 +00:00
|
|
|
data: Partial<CustomerData>;
|
2026-03-16 17:45:45 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const useCustomerUpdateMutation = () => {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const dataSource = useDataSource();
|
|
|
|
|
const schema = UpdateCustomerByIdRequestSchema;
|
|
|
|
|
|
|
|
|
|
return useMutation<Customer, DefaultError, UpdateCustomerPayload, UpdateCustomerContext>({
|
|
|
|
|
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);
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
};
|