Skip to content
This repository has been archived by the owner on Dec 10, 2024. It is now read-only.

Commit

Permalink
Merge pull request #87 from mauro8778/mauro2
Browse files Browse the repository at this point in the history
asdasdad
  • Loading branch information
Davpad authored Dec 6, 2024
2 parents 83ec89f + f8ae9b5 commit 0ab2d7b
Show file tree
Hide file tree
Showing 4 changed files with 161 additions and 2 deletions.
43 changes: 43 additions & 0 deletions src/controllers/volunteersController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import jwt from 'jsonwebtoken';
import * as volunteerService from '../services/volunteersServices';
import mongoose from 'mongoose';
import Refugee from '../models/refugeeModel';
import Volunteer from '../models/volunteersModel';

const handleResponse = (res: Response, data: any, success: boolean, message: string, statusCode: number) => {
res.status(statusCode).json({
Expand Down Expand Up @@ -111,3 +112,45 @@ export const updateVolunteerOpportunity = async (req: Request, res: Response): P
handleError(res, error, "Error al actualizar la oportunidad de voluntariado");
}
};

export const registerVolunteerController = async (req: Request, res: Response) => {
try {
const userId = req.user?.id;
if (!userId) {
return res.status(400).json({ error: 'User ID is missing' });
}

const refugioId = req.params.refugioId;
const { oportunidadId, mensaje, fecha, horasDisponibles, formData } = req.body;

const result = await volunteerService.registerVolunteer(
{ refugioId, oportunidadId, mensaje, fecha, horasDisponibles, formData },
userId
);

res.status(200).json(result);
} catch (error: any) {
res.status(400).json({ error: error.message });
}
};


export const getVolunteerOpportunitiesController = async (req: Request, res: Response) => {
try {
const refugioId = req.params.refugioId;

const refugio = await Refugee.findById(refugioId).populate('opportunities');
if (!refugio) {
return res.status(404).json({ error: 'Refugio no encontrado' });
}

const oportunidades = await Volunteer.find({ _id: { $in: refugio.opportunities } });

res.status(200).json({
refugio: refugio.name_refugee,
oportunidades
});
} catch (error: any) {
res.status(400).json({ error: error.message });
}
};
3 changes: 3 additions & 0 deletions src/dtos/volunteeerDto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface volunterDto{

}
4 changes: 3 additions & 1 deletion src/routes/volunteerRouts.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import express from 'express';
import { createVolunteerController, getVolunteerOpportunities, getVolunteerOpportunitiesByRefugeeId, deleteVolunteerOpportunity, updateVolunteerOpportunity } from '../controllers/volunteersController';
import { createVolunteerController, getVolunteerOpportunities, getVolunteerOpportunitiesByRefugeeId, deleteVolunteerOpportunity, updateVolunteerOpportunity, registerVolunteerController } from '../controllers/volunteersController';
import { checkRole } from '../middlewares/roleMiddleware';

const volunteerRoutes = express.Router();
Expand All @@ -9,6 +9,8 @@ volunteerRoutes.get('/:refugeeId', getVolunteerOpportunitiesByRefugeeId);
volunteerRoutes.post('/:id', checkRole('refugee'), createVolunteerController);
volunteerRoutes.delete('/:id', checkRole('refugee'), deleteVolunteerOpportunity);
volunteerRoutes.put('/:opportunityId', updateVolunteerOpportunity);
volunteerRoutes.post('/:refugioId/oportunidades', registerVolunteerController);



export default volunteerRoutes;
113 changes: 112 additions & 1 deletion src/services/volunteersServices.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import mongoose from 'mongoose';
import VolunteersModel from '../models/volunteersModel';
import Refugee, { IRefugee } from '../models/refugeeModel';
import Usuario from '../models/userModel';
import Volunteer from '../models/volunteersModel';
import mailService from './mailService';

export const getVolunteerOpportunities = async () => {
return VolunteersModel.find().populate('refugee_id', 'name');
Expand All @@ -8,7 +12,7 @@ export const getVolunteerOpportunities = async () => {
export const getOpportunitiesByRefugeeId = async (refugee_id: string) => {

const objectIdRefugeeId = new mongoose.Types.ObjectId(refugee_id)
return VolunteersModel.find({ refugee_id: objectIdRefugeeId}).populate('refugee_id', 'name');
return VolunteersModel.find({ refugee_id: objectIdRefugeeId }).populate('refugee_id', 'name');
};

export const createVolunteerOpportunity = async ({
Expand Down Expand Up @@ -69,4 +73,111 @@ export const updateVolunteerOpportunity = async (
}

return updatedOpportunity;
};



interface VolunteerRegistrationInput {
refugioId: string;
oportunidadId: string;
mensaje: string;
fecha: string;
horasDisponibles: number;
formData: any;
}

export const registerVolunteer = async (input: VolunteerRegistrationInput, userId: string) => {
const { refugioId, oportunidadId, mensaje, fecha, horasDisponibles, formData } = input;

const refugio: IRefugee | null = await Refugee.findById(refugioId).populate('opportunities');
if (!refugio) {
throw new Error('Refugio no encontrado');
}

const oportunidad = refugio.opportunities.find(op => op.toString() === oportunidadId);
if (!oportunidad) {
throw new Error('Oportunidad no encontrada en este refugio');
}

const detalleOportunidad = await Volunteer.findById(oportunidad);
if (!detalleOportunidad) {
throw new Error('Detalles de la oportunidad no encontrados');
}

const usuario: any | null = await Usuario.findById(userId);
if (!usuario) {
throw new Error('Usuario no encontrado');
}

const {
personalData,
availability,
experienceAndSkills,
motivation,
rolePreferences,
healthConditions,
additionalObservations,
selectedVolunteering
} = formData;

const mailContent = `
Hola ${usuario.name} ${usuario.last_name},
Gracias por inscribirte a la oportunidad de voluntariado "${detalleOportunidad.description}" en el refugio "${refugio.name_refugee}". Aquí están los detalles de tu inscripción:
**Información Personal:**
- Nombre completo: ${personalData.fullName || `${usuario.name} ${usuario.last_name}`}
- Fecha de nacimiento: ${personalData.birth || "No especificada"}
- Género: ${personalData.gender || "No especificado"}
- Dirección: ${personalData.address || "No especificada"}
- Teléfono de contacto: ${personalData.contactTel || "No especificado"}
- Email: ${personalData.email || usuario.email}
**Disponibilidad:**
- Días disponibles: ${availability.availableDays || "No especificados"}
- Horas disponibles: ${availability.availableHours || horasDisponibles}
- Frecuencia: ${availability.frecuency || "No especificada"}
**Experiencia y habilidades:**
- Experiencia: ${experienceAndSkills.experience || "No especificada"}
- Área de preferencia: ${experienceAndSkills.preferenceArea || "No especificada"}
- Conocimientos adicionales: ${experienceAndSkills.knowledge || "No especificados"}
**Motivación:**
- Razón para ser voluntario: ${motivation.volunteer || "No especificada"}
- Aprendizajes esperados: ${motivation.learn || "No especificado"}
**Preferencias de rol:**
- Rol deseado: ${rolePreferences.role || "No especificado"}
- Trabajo: ${rolePreferences.individualTeam || "No especificado"}
**Condiciones médicas:**
- Condiciones médicas: ${healthConditions.medicalConditions || "No especificadas"}
- Alergias: ${healthConditions.alergics || "No especificadas"}
**Información adicional:**
- ${additionalObservations.adicionalInfo || "No especificada"}
**Detalles del voluntariado seleccionado:**
- Nombre: ${selectedVolunteering.volunteeringName || detalleOportunidad.description}
- Descripción: ${selectedVolunteering.volunteeringDescription || "No especificada"}
**Mensaje adicional:**
"${mensaje || "Sin mensaje adicional"}"
¡Gracias por tu interés en ayudar!
`;

await mailService.sendEmail({
to: usuario.email,
subject: `Confirmación de inscripción: ${detalleOportunidad.description}`,
text: mailContent
});

return {
message: 'Inscripción exitosa. Se ha enviado un correo de confirmación.',
refugio: refugio.name_refugee,
oportunidad: detalleOportunidad.description,
detallesEnviados: mailContent
};
};

0 comments on commit 0ab2d7b

Please sign in to comment.