Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[US15]: Realizar SAC #106

Merged
merged 5 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 83 additions & 30 deletions apps/backend/src/controllers/sac.controller.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,24 @@
import sacService from "../services/sac.service.js";
import nodemailerService from "../services/nodemailer.service.js";
import fs from "fs/promises";

import mongoose from "mongoose";

const createSac = async (req, res) => {
try {
const { nomeSobrenome, email, telefone, assunto, mensagem } = req.body;
const data = JSON.parse(req.body.data);
const { nomeSobrenome, email, telefone, assunto, mensagem } = data;

if (!nomeSobrenome || !email || !telefone || !assunto || !mensagem) {
return res.status(400).send({ message: "Preencha todos os campos!" });
}

const sac = await sacService.createService(req.body);
const sac = await sacService.createService(data);

if (!sac) {
return res.status(400).send({ message: 'Dados não salvo!' });
};

res.status(200).send({ message: 'Dados salvos com sucesso!', sac: sac });

} catch (err) {
res.status(500).send({ message: err.message })
}
}

const sendMail = async (req, res) => {
try {
const data = JSON.parse(req.body.data);
const { nomeSobrenome, email, telefone, assunto, mensagem } = data;

let emailSetor;

switch (assunto) {
Expand All @@ -52,27 +43,42 @@ const sendMail = async (req, res) => {

// Configura o corpo do e-mail
const emailBody = `
Nome: ${nomeSobrenome}
Email: ${email}
Telefone: ${telefone}
Assunto: ${assunto}
Mensagem: ${mensagem}
Nome: ${sac.nomeSobrenome}
Email: ${sac.email}
Telefone: ${sac.telefone}
Assunto: ${sac.assunto}
Mensagem: ${sac.mensagem}
Identificador: ${sac.identificador}
Status: Em aberto
`;

const assuntoEmail = `${sac.assunto} - ${sac.identificador}`;
// Configura os anexos se houver
const attachments = req.file
? [{ path: req.file.path }]
? [{
filename: req.file.originalname, // Nome original do arquivo
path: req.file.path // Caminho onde o arquivo foi salvo
}]
: [];

// Envia o e-mail
await nodemailerService.send(emailSetor, assunto, emailBody, attachments);
await nodemailerService.send(emailSetor, assuntoEmail, emailBody, attachments);

if (req.file) {
try {
await fs.unlink(req.file.path); // Deleta o arquivo
console.log(`Arquivo ${req.file.path} deletado com sucesso.`);
} catch (deleteError) {
console.error(`Erro ao deletar o arquivo ${req.file.path}:`, deleteError.message);
}
}

res.status(200).send({ message: 'Dados salvos com sucesso!', sac: sac });

res.status(200).send({ message: 'E-mail enviado com sucesso!' });
} catch (err) {
console.error('Erro ao enviar e-mail:', err);
res.status(500).send({ message: 'Erro ao enviar e-mail.' });
res.status(500).send({ message: err.message })
}
};
}


const findAllSac = async (req, res) => {
Expand All @@ -83,7 +89,7 @@ const findAllSac = async (req, res) => {
}

res.send(sacs);
}
};

const findAssuntoSac = async (req, res) => {
const assunto = req.params.assunto;
Expand All @@ -95,7 +101,7 @@ const findAssuntoSac = async (req, res) => {
}

res.send(sacs);
}
};


const deleteSacById = async (req, res) => {
Expand All @@ -109,21 +115,68 @@ const deleteSacById = async (req, res) => {
const result = await sacService.deleteById(id);

if (result.deletedCount > 0) {
return res.send({message: 'SAC deletado com sucesso.'});
return res.send({ message: 'SAC deletado com sucesso.' });
} else {
return res.send({message: 'Nenhum SAC encontrado para o id fornecido.'});
return res.send({ message: 'Nenhum SAC encontrado para o id fornecido.' });
}

} catch (error) {
console.error('Erro ao deletar SAC:', error);
return res.status(500).send({ message: "Erro interno ao tentar deletar o SAC." });
}
};

const findSacById = async (req, res) => {

const id = req.params.id;

//Conferir antes de tudo se o id é válido
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({ message: "Id invalido!" });
}

const sac = await sacService.findById(id);

if (!sac) {
return res.status(400).send({ message: "Usuario nao encontrado" });
}

res.send(sac);
};

const updateSacStatus = async (req, res) => {

const { status } = req.body;

if (status === undefined) {
return res.status(400).send({ message: "Preencha o campo de status!" });
}

const id = req.params.id;

//Conferir antes de tudo se o id é válido
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({ message: "Id invalido!" });
}

const sac = await sacService.findById(id);

if (!sac) {
return res.status(400).send({ message: "Sac nao encontrado" });
}

await sacService.updateSacStatus(
id,
status
);

res.send({ message: "Sac foi atualizado com sucesso" });
}

export default {
createSac,
findAllSac,
findAssuntoSac,
deleteSacById,
sendMail
updateSacStatus
};
15 changes: 13 additions & 2 deletions apps/backend/src/middlewares/sac.middleware.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
import multer from "multer";
import path from "path";

// Configurando o armazenamento do arquivo
const storage = multer.diskStorage({
destination: "uploads/", // Pasta onde os arquivos serão armazenados
filename: (req, file, cb) => {
const ext = path.extname(file.originalname); // Pega a extensão original do arquivo
const name = path.basename(file.originalname, ext); // Pega o nome do arquivo sem a extensão
cb(null, `${name}-${Date.now()}${ext}`); // Gera um nome único para evitar sobrescrita
}
});

const upload = multer({
dest: "uploads/",
storage: storage,
limits: {
fileSize: 15 * 1024 * 1024 // 15MB em bytes
}
});

export default upload;
export default upload;
29 changes: 22 additions & 7 deletions apps/backend/src/models/Sac.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,42 @@
import mongoose from "mongoose";
import crypto from "crypto";

const generateUniqueIdentifier = () => {
return crypto.randomBytes(8).toString("hex");
};

const SacSchema = new mongoose.Schema({
identificador: {
type: String,
required: true,
default: generateUniqueIdentifier,
},
nomeSobrenome: {
type: String,
require: true,
required: true,
},
email: {
type: String,
require: true,
required: true,
},
telefone: {
type: String,
require: true,
required: true,
},
assunto: {
type: String,
require: true,
required: true,
},
mensagem: {
type: String,
require: true,
}
required: true,
},
status: {
type: Boolean,
required: true,
default: false,
},
});

const Sac = mongoose.model('Sac', SacSchema);
export default Sac;
export default Sac;
11 changes: 3 additions & 8 deletions apps/backend/src/routes/sac.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ const sacRouter = express.Router();

import sacController from '../controllers/sac.controller.js';

sacRouter.post('/createSac', sacController.createSac);
sacRouter.post(
'/sendMail',
upload.single("arquivo"),
sacRouter.post('/createSac', upload.single("arquivo"),
(req, res, next) => {
try {
if (req.file && req.file.size > 15 * 1024 * 1024) {
Expand All @@ -20,13 +17,11 @@ sacRouter.post(
}
next(err);
}
},
sacController.sendMail
);
}, sacController.createSac);


sacRouter.get('/', sacController.findAllSac);
sacRouter.get('/:assunto', sacController.findAssuntoSac);
sacRouter.delete('/:id', sacController.deleteSacById);
sacRouter.patch('/:id', sacController.updateSacStatus)

export default sacRouter;
44 changes: 27 additions & 17 deletions apps/backend/src/services/nodemailer.service.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
import nodemailer from "nodemailer";

const send = (to, subject, body, attachments = []) => {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS
}
});

transporter.sendMail({
from: process.env.MAIL_USER, //esse é o email de quem está enviando
to, //esse é o email para quem vai receber a mensagem
subject, //aqui vai o assunto
text: body, //aqui é o corpo do email
attachments // anexos
});
const send = async (to, subject, body, attachments = []) => {
try {
const transporter = nodemailer.createTransport({
service: 'gmail', // Verifique se você está usando o Gmail ou outro provedor
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS // Certifique-se de usar uma senha de app
}
});

// Configuração do e-mail
const mailOptions = {
from: process.env.MAIL_USER, // E-mail do remetente
to, // E-mail do destinatário
subject, // Assunto
text: body, // Corpo do e-mail em texto
attachments // Anexos
};

// Enviando o e-mail
const info = await transporter.sendMail(mailOptions);
console.log("E-mail enviado com sucesso:", info.messageId);
} catch (error) {
console.error("Erro ao enviar e-mail:", error);
throw error; // Repassa o erro para o controller tratar
}
};

export default {
send,
}
};
15 changes: 14 additions & 1 deletion apps/backend/src/services/sac.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,28 @@ import mongoose from 'mongoose';
const createService = (body) => Sac.create(body);
const findAllService = () => Sac.find();
const findByAssunto = (assunto) => Sac.find({assunto});
const findById = (id) => Sac.findById(id);

const deleteById = (id) => {
const objectId = new mongoose.Types.ObjectId(id);
return Sac.deleteOne({ _id: objectId });
};

const updateSacStatus = (
id,
status,
) =>
Sac.findOneAndUpdate(
{ _id: id },
{ status }
);


export default {
createService,
findAllService,
findByAssunto,
deleteById
deleteById,
findById,
updateSacStatus
};
Loading