FactuGES_ERP/modules/customers/src/web/shared/hooks/use-customer-create-mutation.ts

47 lines
1.6 KiB
TypeScript
Raw Normal View History

2026-04-03 19:49:59 +00:00
import { useDataSource } from "@erp/core/hooks";
import { UniqueID, ValidationErrorCollection } from "@repo/rdx-ddd";
import { type DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
import { CreateCustomerRequestSchema } from "../../../common";
import { GetCustomerByIdAdapter } from "../adapters";
import { type CustomerCreateInput, createCustomer } from "../api";
import type { Customer } from "../entities";
import {
invalidateCustomerListQueries,
syncCreatedCustomerCaches,
} from "./customer-cache-strategy";
import { CUSTOMER_CREATE_KEY } from "./keys";
import { toValidationErrors } from "./to-validation-errors";
type CreateCustomerContext = {};
export const useCustomerCreateMutation = () => {
const queryClient = useQueryClient();
const dataSource = useDataSource();
const schema = CreateCustomerRequestSchema;
2026-04-04 10:44:26 +00:00
return useMutation<Customer, DefaultError, CustomerCreateInput, CreateCustomerContext>({
2026-04-03 19:49:59 +00:00
mutationKey: CUSTOMER_CREATE_KEY,
mutationFn: async (payload) => {
const id = UniqueID.generateNewID().toString();
2026-04-04 10:44:26 +00:00
const result = schema.safeParse(payload);
2026-04-03 19:49:59 +00:00
if (!result.success) {
throw new ValidationErrorCollection("Validation failed", toValidationErrors(result.error));
}
2026-04-04 10:44:26 +00:00
const dto = await createCustomer(dataSource, id, payload);
2026-04-03 19:49:59 +00:00
return GetCustomerByIdAdapter.fromDTO(dto);
},
onSuccess: (createdCustomer) => {
syncCreatedCustomerCaches(queryClient, createdCustomer);
},
onSettled: async () => {
await invalidateCustomerListQueries(queryClient);
},
});
};