shoc-frontend-new/src/app/(protected)/vendors/_components/use-vendor-roster-resolver.ts
2026-08-20 20:43:52 -03:00

43 lines
1.7 KiB
TypeScript

import { useMemo } from "react";
import { type Resolver } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
vendorCompanyRosterSchema,
type VendorCompanyRosterFormValues,
} from "@/domain/vendors/schemas/vendor-roster-schema";
import { getSingleStatusOnlyChange } from "@/domain/vendors/use-cases/use-save-vendor-company-roster";
import type { VendorCompanyRoster } from "@/domain/vendors/types/vendor";
function withoutTechnicianStubs(
values: VendorCompanyRosterFormValues,
): VendorCompanyRosterFormValues {
return {
...values,
technicians: values.technicians.filter((technician) => {
if (technician === null || typeof technician !== "object" || Array.isArray(technician)) {
return true;
}
const candidate = technician as unknown as Record<string, unknown>;
const keys = Object.keys(candidate);
const isGeneratedStatusStub =
keys.length === 1 && keys[0] === "isActive" && typeof candidate.isActive === "boolean";
return !isGeneratedStatusStub;
}),
};
}
export function useVendorRosterResolver(
routeRoster: VendorCompanyRoster | undefined,
): Resolver<VendorCompanyRosterFormValues> {
const strictResolver = useMemo(() => zodResolver(vendorCompanyRosterSchema), []);
return useMemo<Resolver<VendorCompanyRosterFormValues>>(
() => async (values, context, options) => {
const normalizedValues = withoutTechnicianStubs(values);
if (routeRoster && getSingleStatusOnlyChange(routeRoster, normalizedValues)) {
return { values: normalizedValues, errors: {} };
}
return strictResolver(normalizedValues, context, options);
},
[routeRoster, strictResolver],
);
}