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

55 lines
1.7 KiB
TypeScript
Raw Normal View History

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";
2026-04-03 19:49:59 +00:00
import { GetCustomerByIdAdapter } from "../adapters";
import { type CustomerUpdateInput, updateCustomerById } from "../api";
import type { Customer } from "../entities";
2026-03-16 17:45:45 +00:00
2026-04-03 19:49:59 +00:00
import {
invalidateCustomerListQueries,
syncUpdatedCustomerCaches,
} from "./customer-cache-strategy";
import { CUSTOMER_UPDATE_KEY } from "./keys";
import { toValidationErrors } from "./to-validation-errors";
2026-03-16 17:45:45 +00:00
type UpdateCustomerContext = {};
type UpdateCustomerPayload = {
id: string;
2026-04-03 19:49:59 +00:00
data: CustomerUpdateInput;
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));
}
2026-04-03 19:49:59 +00:00
const dto = await updateCustomerById(dataSource, customerId, data);
return GetCustomerByIdAdapter.fromDTO(dto);
2026-03-16 17:45:45 +00:00
},
2026-04-03 19:49:59 +00:00
onSuccess: (updatedCustomer) => {
syncUpdatedCustomerCaches(queryClient, updatedCustomer);
2026-03-16 17:45:45 +00:00
},
2026-04-03 19:49:59 +00:00
onSettled: async () => {
await invalidateCustomerListQueries(queryClient);
2026-03-16 17:45:45 +00:00
},
});
};