fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
ea0481e09e
commit
cb74c2fcc1
2 files changed
+175
-104
No files matched your search
@@ -0,0 +1,75 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { Calendar } from '@fullcalendar/react';
|
||||||
|
import dayGridPlugin from '@fullcalendar/daygrid';
|
||||||
|
import timeGridPlugin from '@fullcalendar/timegrid';
|
||||||
|
import interactionPlugin from '@fullcalendar/interaction';
|
||||||
|
import ptBrLocale from '@fullcalendar/core/locales/pt-br';
|
||||||
|
import { startOfWeek, endOfWeek, format, parseISO } from 'date-fns';
|
||||||
|
import { api } from '../services/api';
|
||||||
|
import { toast } from 'react-toastify';
|
||||||
|
|
||||||
|
interface AgendamentoCalendarioProps {
|
||||||
|
onEventClick?: (event: any) => void;
|
||||||
|
onDateSelect?: (selectInfo: any) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AgendamentoCalendario: React.FC<AgendamentoCalendarioProps> = ({
|
||||||
|
onEventClick,
|
||||||
|
onDateSelect
|
||||||
|
}) => {
|
||||||
|
const [eventos, setEventos] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const loadAgendamentos = async (data: string) => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const response = await api.get('/atendimentos/agendamentos', {
|
||||||
|
params: { data }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.data.success) {
|
||||||
|
setEventos(response.data.data);
|
||||||
|
} else {
|
||||||
|
toast.error('Erro ao carregar agendamentos');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao carregar agendamentos:', error);
|
||||||
|
toast.error('Falha ao carregar agendamentos');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative h-full">
|
||||||
|
{loading && (
|
||||||
|
<div className="absolute inset-0 bg-white/50 flex items-center justify-center z-10">
|
||||||
|
<div className="loading-spinner">Carregando...</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Calendar
|
||||||
|
plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
|
||||||
|
initialView="dayGridMonth"
|
||||||
|
locale={ptBrLocale}
|
||||||
|
events={eventos}
|
||||||
|
editable={false}
|
||||||
|
selectable={true}
|
||||||
|
selectMirror={true}
|
||||||
|
dayMaxEvents={true}
|
||||||
|
weekends={true}
|
||||||
|
datesSet={({ start }) => {
|
||||||
|
const formattedDate = format(start, 'yyyy-MM-dd');
|
||||||
|
loadAgendamentos(formattedDate);
|
||||||
|
}}
|
||||||
|
eventClick={({ event }) => onEventClick?.(event)}
|
||||||
|
select={(selectInfo) => onDateSelect?.(selectInfo)}
|
||||||
|
headerToolbar={{
|
||||||
|
left: 'prev,next today',
|
||||||
|
center: 'title',
|
||||||
|
right: 'dayGridMonth,timeGridWeek,timeGridDay'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
+100
-104
@@ -12,81 +12,101 @@ const upload = multer({ storage: multer.memoryStorage() });
|
|||||||
|
|
||||||
router.use(authMiddleware);
|
router.use(authMiddleware);
|
||||||
|
|
||||||
|
// Middleware para logging com informações mais detalhadas
|
||||||
|
router.use((req, res, next) => {
|
||||||
|
const requestId = Math.random().toString(36).substring(7);
|
||||||
|
console.log(`[${new Date().toISOString()}][${requestId}] Request:`, {
|
||||||
|
method: req.method,
|
||||||
|
path: req.path,
|
||||||
|
originalUrl: req.originalUrl,
|
||||||
|
params: req.params,
|
||||||
|
query: req.query,
|
||||||
|
body: req.body
|
||||||
|
});
|
||||||
|
|
||||||
|
// Interceptar resposta para logging
|
||||||
|
const oldJson = res.json;
|
||||||
|
res.json = function(data) {
|
||||||
|
console.log(`[${new Date().toISOString()}][${requestId}] Response:`, {
|
||||||
|
statusCode: res.statusCode,
|
||||||
|
data: data
|
||||||
|
});
|
||||||
|
return oldJson.apply(res, arguments);
|
||||||
|
};
|
||||||
|
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
// Função auxiliar para validar se uma string é um UUID válido
|
// Função auxiliar para validar se uma string é um UUID válido
|
||||||
function isValidUUID(uuid: string): boolean {
|
function isValidUUID(uuid: string, isRoute: boolean = false): boolean {
|
||||||
|
// Lista de rotas que não precisam de validação UUID
|
||||||
|
const routeExceptions = ['agendamentos', 'upload'];
|
||||||
|
|
||||||
|
// Se for uma rota e estiver na lista de exceções, retorna true
|
||||||
|
if (isRoute && (routeExceptions.includes(uuid) || routeExceptions.some(route => uuid.startsWith(route)))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
if (!uuid) return false;
|
if (!uuid) return false;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Validação principal com regex para UUID padrão
|
|
||||||
const regexUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
const regexUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
return regexUUID.test(uuid);
|
||||||
// Se passar na validação principal, retorna verdadeiro
|
|
||||||
if (regexUUID.test(uuid)) return true;
|
|
||||||
|
|
||||||
// Caso contrário, verifica se é um ID válido de alguma outra forma
|
|
||||||
// (como um ID numérico ou string que possa ser convertida em UUID)
|
|
||||||
console.log(`ID recebido em formato não-UUID padrão: ${uuid}`);
|
|
||||||
|
|
||||||
// Se for "agendamentos", é uma rota especial que não precisa de validação UUID
|
|
||||||
if (uuid === "agendamentos") return true;
|
|
||||||
|
|
||||||
// Se chegou aqui e não é um UUID válido, retorna falso
|
|
||||||
return false;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao validar UUID:", error);
|
console.error("Erro ao validar UUID:", error);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Middleware para validação de UUID em rotas específicas
|
||||||
|
router.param('id', (req, res, next, id) => {
|
||||||
|
const path = req.path.split('/')[1]; // Pega o primeiro segmento da rota após a /
|
||||||
|
|
||||||
|
if (!isValidUUID(id, true)) {
|
||||||
|
console.error(`ID inválido: ${id} para rota ${path}`);
|
||||||
|
return res.status(400).json({
|
||||||
|
error: "ID inválido",
|
||||||
|
details: "O formato do ID fornecido não é válido para esta operação"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
// Rota para listar agendamentos
|
// Rota para listar agendamentos
|
||||||
router.get("/agendamentos", async (req: Request, res: Response) => {
|
router.get("/agendamentos", async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const { data } = req.query;
|
const { data, inicio, fim } = req.query;
|
||||||
console.log("Requisição de agendamentos recebida, data:", data);
|
console.log("[Agendamentos] Parâmetros recebidos:", { data, inicio, fim });
|
||||||
|
|
||||||
let dateFilter = {};
|
let whereClause = {};
|
||||||
|
|
||||||
if (data) {
|
if (data) {
|
||||||
try {
|
// Suporte ao formato antigo usando data
|
||||||
// Aceitar e validar o formato da data de forma mais flexível
|
const parsedDate = parseISO(data as string);
|
||||||
const parsedDate = new Date(data as string);
|
|
||||||
|
|
||||||
// Verificar se a data é válida
|
|
||||||
if (isNaN(parsedDate.getTime())) {
|
|
||||||
console.error("Data inválida recebida:", data);
|
|
||||||
// Em vez de retornar erro, continue sem filtro
|
|
||||||
console.log("Continuando sem filtro de data devido a data inválida");
|
|
||||||
} else {
|
|
||||||
console.log("Data parseada:", parsedDate);
|
|
||||||
|
|
||||||
const weekStart = startOfWeek(parsedDate, { locale: ptBR });
|
const weekStart = startOfWeek(parsedDate, { locale: ptBR });
|
||||||
const weekEnd = endOfWeek(parsedDate, { locale: ptBR });
|
const weekEnd = endOfWeek(parsedDate, { locale: ptBR });
|
||||||
|
|
||||||
console.log("Período de busca:", {
|
whereClause = {
|
||||||
weekStart: weekStart.toISOString(),
|
|
||||||
weekEnd: weekEnd.toISOString()
|
|
||||||
});
|
|
||||||
|
|
||||||
dateFilter = {
|
|
||||||
data: {
|
data: {
|
||||||
gte: weekStart,
|
gte: weekStart,
|
||||||
lte: weekEnd,
|
lte: weekEnd,
|
||||||
},
|
}
|
||||||
|
};
|
||||||
|
} else if (inicio && fim) {
|
||||||
|
// Novo formato usando início e fim
|
||||||
|
whereClause = {
|
||||||
|
data: {
|
||||||
|
gte: new Date(inicio as string),
|
||||||
|
lte: new Date(fim as string)
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (parseError) {
|
|
||||||
console.error("Erro ao analisar data:", parseError);
|
|
||||||
// Continuar sem filtro de data em caso de erro, em vez de falhar
|
|
||||||
console.log("Continuando sem filtro de data devido ao erro");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log("Filtro de data:", JSON.stringify(dateFilter));
|
console.log("[Agendamentos] Filtro:", whereClause);
|
||||||
|
|
||||||
// Usando o modelo correto e com tratamento de erro adequado
|
|
||||||
try {
|
|
||||||
const agendamentos = await prisma.agendamentoAtendimento.findMany({
|
const agendamentos = await prisma.agendamentoAtendimento.findMany({
|
||||||
where: dateFilter,
|
where: whereClause,
|
||||||
include: {
|
include: {
|
||||||
cliente: {
|
cliente: {
|
||||||
select: {
|
select: {
|
||||||
@@ -106,20 +126,26 @@ router.get("/agendamentos", async (req: Request, res: Response) => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`Encontrados ${agendamentos.length} agendamentos`);
|
return res.json({
|
||||||
|
success: true,
|
||||||
return res.json(agendamentos);
|
data: agendamentos.map(ag => ({
|
||||||
} catch (dbError) {
|
id: ag.id,
|
||||||
console.error("Erro na consulta do banco de dados:", dbError);
|
title: `${ag.cliente.nome}${ag.observacoes ? ` - ${ag.observacoes}` : ''}`,
|
||||||
return res.status(500).json({
|
start: ag.data.toISOString(),
|
||||||
error: "Erro ao buscar agendamentos no banco de dados",
|
end: ag.data.toISOString(),
|
||||||
details: dbError.message
|
clienteId: ag.clienteId,
|
||||||
|
observacoes: ag.observacoes,
|
||||||
|
status: ag.status,
|
||||||
|
usuario: ag.usuario,
|
||||||
|
cliente: ag.cliente
|
||||||
|
}))
|
||||||
});
|
});
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro geral ao listar agendamentos:", error);
|
console.error("[Agendamentos] Erro:", error);
|
||||||
return res.status(500).json({
|
return res.status(500).json({
|
||||||
error: "Erro ao listar agendamentos",
|
success: false,
|
||||||
|
error: "Erro ao buscar agendamentos",
|
||||||
details: error.message
|
details: error.message
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -128,11 +154,14 @@ router.get("/agendamentos", async (req: Request, res: Response) => {
|
|||||||
// Rota para criar um novo agendamento
|
// Rota para criar um novo agendamento
|
||||||
router.post("/agendamentos", async (req: Request, res: Response) => {
|
router.post("/agendamentos", async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const { clienteId, data, observacoes, tipo } = req.body;
|
const { clienteId, data, observacoes } = req.body; // Removido tipo temporariamente
|
||||||
console.log("Criando agendamento:", { clienteId, data, observacoes, tipo });
|
console.log("[Agendamentos] Criando agendamento:", { clienteId, data, observacoes });
|
||||||
|
|
||||||
if (!clienteId || !data) {
|
if (!clienteId || !data) {
|
||||||
return res.status(400).json({ error: "Cliente e data são obrigatórios" });
|
return res.status(400).json({
|
||||||
|
error: "Dados inválidos",
|
||||||
|
details: "Cliente e data são obrigatórios"
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verificar se o cliente existe
|
// Verificar se o cliente existe
|
||||||
@@ -144,15 +173,14 @@ router.post("/agendamentos", async (req: Request, res: Response) => {
|
|||||||
return res.status(404).json({ error: "Cliente não encontrado" });
|
return res.status(404).json({ error: "Cliente não encontrado" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Criar o agendamento - usando agendamentoAtendimento
|
// Criar o agendamento sem o campo tipo
|
||||||
const agendamento = await prisma.agendamentoAtendimento.create({
|
const agendamento = await prisma.agendamentoAtendimento.create({
|
||||||
data: {
|
data: {
|
||||||
clienteId,
|
clienteId,
|
||||||
data: new Date(data),
|
data: new Date(data),
|
||||||
observacoes,
|
observacoes,
|
||||||
tipo,
|
|
||||||
status: "AGENDADO",
|
status: "AGENDADO",
|
||||||
usuarioId: req.user?.id // Adicionando usuarioId do middleware auth
|
usuarioId: req.user?.id
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
cliente: {
|
cliente: {
|
||||||
@@ -164,16 +192,20 @@ router.post("/agendamentos", async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log("Agendamento criado:", {
|
console.log("[Agendamentos] Agendamento criado com sucesso:", {
|
||||||
id: agendamento.id,
|
id: agendamento.id,
|
||||||
data: agendamento.data,
|
data: agendamento.data,
|
||||||
clienteNome: agendamento.cliente.nome
|
clienteNome: agendamento.cliente.nome
|
||||||
});
|
});
|
||||||
|
|
||||||
res.status(201).json(agendamento);
|
return res.status(201).json(agendamento);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao criar agendamento:", error);
|
console.error("[Agendamentos] Erro ao criar agendamento:", error);
|
||||||
res.status(500).json({ error: "Erro ao criar agendamento", details: error.message });
|
return res.status(500).json({
|
||||||
|
error: "Erro ao criar agendamento",
|
||||||
|
details: error.message,
|
||||||
|
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -183,15 +215,6 @@ router.put("/agendamentos/:id", async (req: Request, res: Response) => {
|
|||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const { clienteId, data, observacoes, tipo } = req.body;
|
const { clienteId, data, observacoes, tipo } = req.body;
|
||||||
|
|
||||||
// Validação do UUID antes de consultar o banco de dados
|
|
||||||
if (!isValidUUID(id)) {
|
|
||||||
console.error(`ID de agendamento inválido: ${id}. Não é um UUID válido.`);
|
|
||||||
return res.status(400).json({
|
|
||||||
error: "ID de agendamento inválido",
|
|
||||||
details: "O formato do ID fornecido não é um UUID válido."
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log("Atualizando agendamento:", { id, clienteId, data, observacoes, tipo });
|
console.log("Atualizando agendamento:", { id, clienteId, data, observacoes, tipo });
|
||||||
|
|
||||||
// Verificar se o agendamento existe usando a tabela correta
|
// Verificar se o agendamento existe usando a tabela correta
|
||||||
@@ -241,15 +264,6 @@ router.delete("/agendamentos/:id", async (req: Request, res: Response) => {
|
|||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
console.log("Excluindo agendamento:", id);
|
console.log("Excluindo agendamento:", id);
|
||||||
|
|
||||||
// Validação do UUID antes de consultar o banco de dados
|
|
||||||
if (!isValidUUID(id)) {
|
|
||||||
console.error(`ID de agendamento inválido: ${id}. Não é um UUID válido.`);
|
|
||||||
return res.status(400).json({
|
|
||||||
error: "ID de agendamento inválido",
|
|
||||||
details: "O formato do ID fornecido não é um UUID válido."
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar se o agendamento existe usando a tabela correta
|
// Verificar se o agendamento existe usando a tabela correta
|
||||||
const agendamento = await prisma.agendamentoAtendimento.findUnique({
|
const agendamento = await prisma.agendamentoAtendimento.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
@@ -286,15 +300,6 @@ router.patch("/:id", async (req: Request, res: Response) => {
|
|||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const { anexos, ...data } = req.body;
|
const { anexos, ...data } = req.body;
|
||||||
|
|
||||||
// Validação do UUID antes de consultar o banco de dados
|
|
||||||
if (!isValidUUID(id)) {
|
|
||||||
console.error(`ID de atendimento inválido: ${id}. Não é um UUID válido.`);
|
|
||||||
return res.status(400).json({
|
|
||||||
error: "ID de atendimento inválido",
|
|
||||||
details: "O formato do ID fornecido não é um UUID válido."
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log("Atualizando atendimento:", id, { anexos, data }); // Debug log
|
console.log("Atualizando atendimento:", id, { anexos, data }); // Debug log
|
||||||
|
|
||||||
const atendimento = await prisma.atendimento.update({
|
const atendimento = await prisma.atendimento.update({
|
||||||
@@ -363,15 +368,6 @@ router.get("/:id", async (req: Request, res: Response) => {
|
|||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
|
|
||||||
// Validação do UUID antes de consultar o banco de dados
|
|
||||||
if (!isValidUUID(id)) {
|
|
||||||
console.error(`ID de atendimento inválido: ${id}. Não é um UUID válido.`);
|
|
||||||
return res.status(400).json({
|
|
||||||
error: "ID de atendimento inválido",
|
|
||||||
details: "O formato do ID fornecido não é um UUID válido."
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const atendimento = await prisma.atendimento.findUnique({
|
const atendimento = await prisma.atendimento.findUnique({
|
||||||
where: {
|
where: {
|
||||||
id: id,
|
id: id,
|
||||||
|
|||||||
Reference in new issue
Block a user