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

57 lines
1.8 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";
2026-04-04 16:58:32 +00:00
import {
type UpdateCustomerByIdParams,
type UpdateCustomerByIdResult,
updateCustomerById,
} from "../api";
2026-04-03 19:49:59 +00:00
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 = {};
export const useCustomerUpdateMutation = () => {
const queryClient = useQueryClient();
const dataSource = useDataSource();
const schema = UpdateCustomerByIdRequestSchema;
2026-04-04 16:58:32 +00:00
return useMutation<Customer, DefaultError, UpdateCustomerByIdParams, UpdateCustomerContext>({
2026-03-16 17:45:45 +00:00
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-04 16:58:32 +00:00
const dto: UpdateCustomerByIdResult = await updateCustomerById(
dataSource,
payload as UpdateCustomerByIdParams
);
2026-04-03 19:49:59 +00:00
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
},
});
};