179 lines
4.7 KiB
TypeScript
179 lines
4.7 KiB
TypeScript
import { Router, Request, Response } from "express";
|
|
import multer from "multer";
|
|
import { authMiddleware } from "../../middleware/auth";
|
|
import { NextCloudService } from "../../services/nextcloud";
|
|
import { prisma } from "../prismaClient";
|
|
import { agendamentosRouter } from './agendamentos';
|
|
|
|
const router = Router();
|
|
const upload = multer({ storage: multer.memoryStorage() });
|
|
|
|
router.use(authMiddleware);
|
|
|
|
// Rotas de agendamentos em subrouter separado
|
|
router.use('/agendamentos', agendamentosRouter);
|
|
|
|
// 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
|
|
function isValidUUID(uuid: string): boolean {
|
|
if (!uuid) return false;
|
|
|
|
try {
|
|
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);
|
|
} catch (error) {
|
|
console.error("Erro ao validar UUID:", error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Desabilitar validação UUID para rotas específicas
|
|
const SKIP_UUID_VALIDATION = ['/agendamentos', '/upload'];
|
|
|
|
router.use((req, res, next) => {
|
|
// Pula validação para rotas específicas
|
|
if (SKIP_UUID_VALIDATION.some(path => req.path.startsWith(path))) {
|
|
return next();
|
|
}
|
|
|
|
// Se tiver ID nos parâmetros, valida
|
|
const { id } = req.params;
|
|
if (id && !isValidUUID(id)) {
|
|
return res.status(400).json({
|
|
error: "ID inválido",
|
|
details: "Formato de ID inválido para esta operação"
|
|
});
|
|
}
|
|
|
|
next();
|
|
});
|
|
|
|
// Rota para atualizar atendimento com anexos
|
|
router.patch("/:id", async (req: Request, res: Response) => {
|
|
try {
|
|
const { id } = req.params;
|
|
const { anexos, ...data } = req.body;
|
|
|
|
console.log("Atualizando atendimento:", id, { anexos, data }); // Debug log
|
|
|
|
const atendimento = await prisma.atendimento.update({
|
|
where: { id },
|
|
data: {
|
|
...data,
|
|
...(anexos && {
|
|
anexos: {
|
|
createMany: {
|
|
data: anexos.map((anexo: any) => ({
|
|
nome: anexo.nome,
|
|
url: anexo.url,
|
|
tipo: anexo.tipo,
|
|
tamanho: anexo.tamanho,
|
|
})),
|
|
},
|
|
},
|
|
}),
|
|
},
|
|
include: {
|
|
anexos: true,
|
|
cliente: true,
|
|
},
|
|
});
|
|
|
|
console.log("Atendimento atualizado:", atendimento); // Debug log
|
|
res.json(atendimento);
|
|
} catch (error) {
|
|
console.error("Erro ao atualizar atendimento:", error);
|
|
res.status(500).json({ error: "Erro ao atualizar atendimento" });
|
|
}
|
|
});
|
|
|
|
// Nova rota para upload de arquivo via proxy
|
|
router.post("/upload", upload.single("file"), async (req: Request, res: Response) => {
|
|
try {
|
|
if (!req.file || !req.body.clienteNome) {
|
|
return res
|
|
.status(400)
|
|
.json({ error: "Arquivo e nome do cliente são obrigatórios" });
|
|
}
|
|
|
|
// Enviar para o NextCloud usando a estrutura de pastas correta
|
|
const buffer = req.file.buffer;
|
|
Object.defineProperty(buffer, "name", {
|
|
value: req.file.originalname,
|
|
writable: true,
|
|
enumerable: true,
|
|
});
|
|
|
|
const filePath = await NextCloudService.uploadFile(
|
|
buffer,
|
|
req.body.clienteNome,
|
|
"atendimento",
|
|
req.body.protocolo,
|
|
);
|
|
|
|
res.json({ url: filePath });
|
|
} catch (error) {
|
|
console.error("Erro no upload:", error);
|
|
res.status(500).json({ error: "Erro no upload do arquivo" });
|
|
}
|
|
});
|
|
|
|
router.get("/:id", async (req: Request, res: Response) => {
|
|
try {
|
|
const { id } = req.params;
|
|
|
|
const atendimento = await prisma.atendimento.findUnique({
|
|
where: {
|
|
id: id,
|
|
},
|
|
include: {
|
|
cliente: true,
|
|
processo: true,
|
|
usuario: {
|
|
select: {
|
|
id: true,
|
|
nome: true,
|
|
oab: true,
|
|
oabUF: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!atendimento) {
|
|
return res.status(404).json({ error: "Atendimento não encontrado" });
|
|
}
|
|
|
|
res.json(atendimento);
|
|
} catch (error) {
|
|
console.error("Erro ao buscar atendimento:", error);
|
|
res.status(500).json({ error: "Erro ao buscar atendimento" });
|
|
}
|
|
});
|
|
|
|
export default router;
|