211 lines
No EOL
6 KiB
TypeScript
211 lines
No EOL
6 KiB
TypeScript
import { useState, useCallback } from 'react';
|
|
import { laboratorioApiService, LaboratorioBff, LaboratoriosBffParams } from '@/services/laboratorioApiService';
|
|
|
|
export interface LaboratorioFormData {
|
|
nome: string;
|
|
}
|
|
|
|
export interface UseLaboratoriosReturn {
|
|
laboratorios: LaboratorioBff[];
|
|
loading: boolean;
|
|
isCreating: boolean;
|
|
error: string | null;
|
|
totalLaboratorios: number;
|
|
currentPage: number;
|
|
totalPages: number;
|
|
isChangingPage: boolean;
|
|
listarLaboratorios: (page?: number, search?: string) => Promise<void>;
|
|
buscarLaboratorios: (nome: string, page?: number) => Promise<void>;
|
|
cadastrarLaboratorio: (data: LaboratorioFormData) => Promise<boolean>;
|
|
atualizarLaboratorio: (id: string, data: LaboratorioFormData) => Promise<boolean>;
|
|
deletarLaboratorio: (id: string) => Promise<boolean>;
|
|
setCurrentPage: (page: number) => void;
|
|
limparErro: () => void;
|
|
}
|
|
|
|
const PAGE_SIZE = 10;
|
|
|
|
export const useLaboratorios = (): UseLaboratoriosReturn => {
|
|
const [laboratorios, setLaboratorios] = useState<LaboratorioBff[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [totalLaboratorios, setTotalLaboratorios] = useState(0);
|
|
const [currentPage, setCurrentPage] = useState(1);
|
|
const [totalPages, setTotalPages] = useState(0);
|
|
const [isChangingPage, setIsChangingPage] = useState(false);
|
|
const [isCreating, setIsCreating] = useState(false);
|
|
|
|
const listarLaboratorios = useCallback(async (page = 1, search = '') => {
|
|
setIsChangingPage(true);
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const params: LaboratoriosBffParams = {
|
|
page,
|
|
limit: PAGE_SIZE,
|
|
search: search.trim() || undefined,
|
|
};
|
|
|
|
const response = await laboratorioApiService.listar(params);
|
|
|
|
setLaboratorios(response.items);
|
|
setTotalLaboratorios(response.total);
|
|
setCurrentPage(response.page);
|
|
setTotalPages(Math.ceil(response.total / response.limit));
|
|
|
|
|
|
|
|
} catch (err) {
|
|
const errorMessage = err instanceof Error ? err.message : 'Erro desconhecido ao carregar laboratórios';
|
|
setError(errorMessage);
|
|
console.error('❌ Erro no hook useLaboratorios:', err);
|
|
|
|
// Limpar dados em caso de erro
|
|
setLaboratorios([]);
|
|
setTotalLaboratorios(0);
|
|
setTotalPages(0);
|
|
} finally {
|
|
setLoading(false);
|
|
setIsChangingPage(false);
|
|
}
|
|
}, []);
|
|
|
|
const buscarLaboratorios = useCallback(async (nome: string, page = 1) => {
|
|
setIsChangingPage(true);
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const params: LaboratoriosBffParams = {
|
|
page,
|
|
limit: PAGE_SIZE,
|
|
search: nome.trim(),
|
|
};
|
|
|
|
const response = await laboratorioApiService.listar(params);
|
|
|
|
setLaboratorios(response.items);
|
|
setTotalLaboratorios(response.total);
|
|
setCurrentPage(response.page);
|
|
setTotalPages(Math.ceil(response.total / response.limit));
|
|
|
|
|
|
|
|
} catch (err) {
|
|
const errorMessage = err instanceof Error ? err.message : 'Erro desconhecido ao buscar laboratórios';
|
|
setError(errorMessage);
|
|
console.error('❌ Erro ao buscar laboratórios:', err);
|
|
|
|
// Limpar dados em caso de erro
|
|
setLaboratorios([]);
|
|
setTotalLaboratorios(0);
|
|
setTotalPages(0);
|
|
} finally {
|
|
setLoading(false);
|
|
setIsChangingPage(false);
|
|
}
|
|
}, []);
|
|
|
|
const cadastrarLaboratorio = useCallback(async (formData: LaboratorioFormData): Promise<boolean> => {
|
|
setIsCreating(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const laboratorioCriado = await laboratorioApiService.criar(formData);
|
|
|
|
return true;
|
|
|
|
} catch (err) {
|
|
const errorMessage = err instanceof Error ? err.message : 'Erro desconhecido ao cadastrar laboratório';
|
|
setError(errorMessage);
|
|
console.error('❌ Erro ao cadastrar laboratório:', err);
|
|
return false;
|
|
} finally {
|
|
setIsCreating(false);
|
|
}
|
|
}, []);
|
|
|
|
const atualizarLaboratorio = useCallback(async (id: string, formData: LaboratorioFormData): Promise<boolean> => {
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const laboratorioAtualizado = await laboratorioApiService.atualizar(id, formData);
|
|
|
|
// Atualizar o laboratório na lista local
|
|
setLaboratorios(prevLaboratorios =>
|
|
prevLaboratorios.map(lab =>
|
|
lab.id === id ? laboratorioAtualizado : lab
|
|
)
|
|
);
|
|
|
|
return true;
|
|
|
|
} catch (err) {
|
|
const errorMessage = err instanceof Error ? err.message : 'Erro desconhecido ao atualizar laboratório';
|
|
setError(errorMessage);
|
|
console.error('❌ Erro ao atualizar laboratório:', err);
|
|
return false;
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
const deletarLaboratorio = useCallback(async (id: string): Promise<boolean> => {
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const sucesso = await laboratorioApiService.deletar(id);
|
|
|
|
if (sucesso) {
|
|
// Remover o laboratório da lista local
|
|
setLaboratorios(prevLaboratorios =>
|
|
prevLaboratorios.filter(lab => lab.id !== id)
|
|
);
|
|
|
|
// Decrementar o total
|
|
setTotalLaboratorios(prev => prev - 1);
|
|
setTotalPages(prev => Math.ceil((totalLaboratorios - 1) / PAGE_SIZE));
|
|
|
|
}
|
|
|
|
return sucesso;
|
|
|
|
} catch (err) {
|
|
const errorMessage = err instanceof Error ? err.message : 'Erro desconhecido ao deletar laboratório';
|
|
setError(errorMessage);
|
|
console.error('❌ Erro ao deletar laboratório:', err);
|
|
return false;
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [totalLaboratorios]);
|
|
|
|
const handleSetCurrentPage = useCallback((page: number) => {
|
|
setCurrentPage(page);
|
|
}, []);
|
|
|
|
const limparErro = useCallback(() => {
|
|
setError(null);
|
|
}, []);
|
|
|
|
return {
|
|
laboratorios,
|
|
loading,
|
|
isCreating,
|
|
error,
|
|
totalLaboratorios,
|
|
currentPage,
|
|
totalPages,
|
|
isChangingPage,
|
|
listarLaboratorios,
|
|
buscarLaboratorios,
|
|
cadastrarLaboratorio,
|
|
atualizarLaboratorio,
|
|
deletarLaboratorio,
|
|
setCurrentPage: handleSetCurrentPage,
|
|
limparErro,
|
|
};
|
|
}; |