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

53 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-09-16 17:29:37 +00:00
import { useDataSource } from "@erp/core/hooks";
2025-09-23 16:38:20 +00:00
import { ValidationErrorCollection } from "@repo/rdx-ddd";
2025-09-16 17:29:37 +00:00
import { useMutation, useQueryClient } from "@tanstack/react-query";
2025-10-20 18:40:28 +00:00
import { UpdateCustomerByIdRequestSchema } from "../../common";
import { Customer, CustomerFormData } from "../schemas";
import { toValidationErrors } from "./use-create-customer-mutation";
import { upsertCustomerIntoListCaches } from "./use-customer-list-query";
import { setCustomerDetailCache } from "./use-customer-query";
2025-09-16 17:29:37 +00:00
2025-10-20 18:40:28 +00:00
export const CUSTOMER_UPDATE_KEY = ["customers", "update"] as const;
2025-09-16 17:29:37 +00:00
2025-09-24 10:34:04 +00:00
type UpdateCustomerContext = {};
2025-09-17 17:37:41 +00:00
type UpdateCustomerPayload = {
id: string;
2025-09-24 10:34:04 +00:00
data: Partial<CustomerFormData>;
2025-09-17 17:37:41 +00:00
};
2025-09-16 17:29:37 +00:00
2025-09-24 17:30:35 +00:00
export function useUpdateCustomer() {
2025-09-16 17:29:37 +00:00
const queryClient = useQueryClient();
const dataSource = useDataSource();
2025-09-23 16:38:20 +00:00
const schema = UpdateCustomerByIdRequestSchema;
2025-09-16 17:29:37 +00:00
2025-10-20 18:40:28 +00:00
return useMutation<Customer, Error, UpdateCustomerPayload, UpdateCustomerContext>({
mutationKey: CUSTOMER_UPDATE_KEY,
2025-09-17 17:37:41 +00:00
mutationFn: async (payload) => {
const { id: customerId, data } = payload;
if (!customerId) {
throw new Error("customerId is required");
}
2025-09-23 16:38:20 +00:00
const result = schema.safeParse(data);
if (!result.success) {
2025-10-20 18:40:28 +00:00
throw new ValidationErrorCollection("Validation failed", toValidationErrors(result.error));
2025-09-23 16:38:20 +00:00
}
2025-09-17 17:37:41 +00:00
const updated = await dataSource.updateOne("customers", customerId, data);
2025-10-20 18:40:28 +00:00
return updated as Customer;
2025-09-16 17:29:37 +00:00
},
2025-09-17 17:37:41 +00:00
2025-10-20 18:40:28 +00:00
onSuccess: (updated: Customer, variables) => {
const { id: customerId } = variables;
2025-09-16 17:29:37 +00:00
2025-10-20 18:40:28 +00:00
// Actualiza detalle
setCustomerDetailCache(queryClient, customerId, updated);
2025-09-16 17:29:37 +00:00
2025-10-20 18:40:28 +00:00
// Actualiza todas las páginas donde aparezca
upsertCustomerIntoListCaches(queryClient, { ...updated });
2025-09-16 17:29:37 +00:00
},
});
}