FactuGES_ERP/modules/customer-invoices/src/web/hooks/use-create-customer-invoice-mutation.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

2025-09-29 08:42:46 +00:00
import { useDataSource } from "@erp/core/hooks";
import { UniqueID, ValidationErrorCollection } from "@repo/rdx-ddd";
2025-11-13 11:49:36 +00:00
import { type DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
import { CreateProformaRequestSchema } from "../../common";
2025-11-21 18:42:17 +00:00
import type { Proforma } from "../proformas/types/proforma.api.schema";
2025-11-13 11:49:36 +00:00
import type { InvoiceFormData } from "../schemas";
2025-09-29 08:42:46 +00:00
type CreateCustomerInvoicePayload = {
2025-10-12 10:43:06 +00:00
data: InvoiceFormData;
2025-09-29 08:42:46 +00:00
};
2025-06-24 18:38:57 +00:00
2025-11-13 11:49:36 +00:00
export const useCreateProforma = () => {
2025-06-24 18:38:57 +00:00
const queryClient = useQueryClient();
const dataSource = useDataSource();
2025-11-13 11:49:36 +00:00
const schema = CreateProformaRequestSchema;
2025-09-29 08:42:46 +00:00
2025-11-13 11:49:36 +00:00
return useMutation<Proforma, DefaultError, CreateCustomerInvoicePayload>({
2025-09-29 08:42:46 +00:00
mutationKey: ["customer-invoice:create"],
mutationFn: async (payload) => {
const { data } = payload;
const invoiceId = UniqueID.generateNewID();
const newInvoiceData = {
...data,
id: invoiceId.toString(),
};
const result = schema.safeParse(newInvoiceData);
if (!result.success) {
// Construye errores detallados
const validationErrors = result.error.issues.map((err) => ({
field: err.path.join("."),
message: err.message,
}));
throw new ValidationErrorCollection("Validation failed", validationErrors);
}
const created = await dataSource.createOne("customer-invoices", newInvoiceData);
2025-11-13 11:49:36 +00:00
return created;
2025-06-24 18:38:57 +00:00
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["customer-invoices"] });
},
});
};