49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import { useDataSource } from "@erp/core/hooks";
|
|
import { UniqueID, ValidationErrorCollection } from "@repo/rdx-ddd";
|
|
import { type DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
|
|
import { CreateProformaRequestSchema } from "../../common";
|
|
import type { Proforma } from "../proformas/types/proforma.api.schema";
|
|
import type { InvoiceFormData } from "../schemas";
|
|
|
|
type CreateCustomerInvoicePayload = {
|
|
data: InvoiceFormData;
|
|
};
|
|
|
|
export const useCreateProforma = () => {
|
|
const queryClient = useQueryClient();
|
|
const dataSource = useDataSource();
|
|
const schema = CreateProformaRequestSchema;
|
|
|
|
return useMutation<Proforma, DefaultError, CreateCustomerInvoicePayload>({
|
|
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);
|
|
return created;
|
|
},
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ["customer-invoices"] });
|
|
},
|
|
});
|
|
};
|