Skip to content

Commit 4cd4f7a

Browse files
committed
Add feature to allow responses to notifications
1 parent 7ff59ac commit 4cd4f7a

File tree

7 files changed

+67
-8
lines changed

7 files changed

+67
-8
lines changed

BackEnd/No-Country-simulation/src/main/java/com/school/persistence/entities/Notification.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,5 +58,11 @@ public class Notification {
5858
private LocalDateTime sentAt;
5959

6060
// Lista de respuestas a la notificación, si se han agregado
61-
private List<String> responses;
61+
//private List<String> responses;
62+
63+
private String subject;
64+
65+
private LocalDateTime responseTime;
66+
67+
private String responseText;
6268
}

BackEnd/No-Country-simulation/src/main/java/com/school/rest/controller/NotificationController.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,4 +194,14 @@ public ResponseEntity<List<NotificationDTO>> getNotificationsForParent(@PathVari
194194

195195
return ResponseEntity.ok(notificationDTOs);
196196
}
197+
198+
@Secured({"ROLE_STUDENT", "ROLE_PARENT"})
199+
@PostMapping("/{id}/responses")
200+
public ResponseEntity<String> respondToNotification(@PathVariable Long id, @RequestParam String responseText) {
201+
202+
notificationService.addResponse(id, responseText);
203+
204+
return ResponseEntity.ok("Respuesta añadida a la notificación.");
205+
}
206+
197207
}

BackEnd/No-Country-simulation/src/main/java/com/school/security/config/SecurityConfig.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws
6767
http.requestMatchers(HttpMethod.POST, "/admin/**").hasRole("ADMIN");
6868
http.requestMatchers(HttpMethod.POST, "/evaluations/load").hasRole("TEACHER");
6969
http.requestMatchers(HttpMethod.POST, "/evaluations/student").hasAnyRole("STUDENT", "PARENT");
70+
http.requestMatchers(HttpMethod.POST, "/notifications/{id}/responses").hasAnyRole("STUDENT", "PARENT");
7071

7172
// Permisos para notificaciones
7273
http.requestMatchers(HttpMethod.POST, "/notifications/send/all").hasRole("TEACHER");
@@ -76,6 +77,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws
7677
http.requestMatchers(HttpMethod.GET, "/notifications/student/{dni}").hasRole("STUDENT");
7778
http.requestMatchers(HttpMethod.GET, "/notifications/parent/{dni}").hasRole("PARENT");
7879

80+
7981
// Denegar todas las demás solicitudes
8082
http.anyRequest().denyAll();
8183
})

BackEnd/No-Country-simulation/src/main/java/com/school/service/dto/NotificationDTO.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import jakarta.validation.constraints.NotBlank;
44
import jakarta.validation.constraints.Pattern;
55

6+
import java.time.LocalDateTime;
7+
68
/**
79
* NotificationDTO es un registro que encapsula los datos necesarios para enviar una notificación
810
* a un estudiante, padre o grupo de curso. Este DTO es utilizado para recibir las solicitudes
@@ -28,5 +30,13 @@ public record NotificationDTO(
2830
// El DNI del estudiante para identificarlo en la base de datos (obligatorio y debe ser un número de 8 dígitos).
2931
@NotBlank(message = "El DNI no puede estar vacío")
3032
@Pattern(regexp = "\\d{8}", message = "El DNI debe ser un número de 8 dígitos")
31-
String dni ) {
33+
String dni,
34+
35+
LocalDateTime sentAt,
36+
37+
String subject,
38+
39+
String responseText,
40+
41+
LocalDateTime responseTime) {
3242
}

BackEnd/No-Country-simulation/src/main/java/com/school/service/implementation/NotificationServiceImpl.java

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,12 @@
1111
import jakarta.persistence.EntityNotFoundException;
1212
import org.springframework.beans.factory.annotation.Autowired;
1313
import org.springframework.stereotype.Service;
14+
import org.springframework.transaction.annotation.Transactional;
1415

16+
import java.time.LocalDateTime;
17+
import java.time.format.DateTimeFormatter;
18+
import java.util.ArrayList;
19+
import java.util.List;
1520
import java.util.Set;
1621

1722
@Service
@@ -27,7 +32,7 @@ public class NotificationServiceImpl implements INotificationService {
2732

2833
/**
2934
* Envía una notificación a todos los estudiantes y padres de un curso.
30-
*
35+
* <p>
3136
* Convierte el objeto {@code NotificationDTO} en una entidad {@code Notification}.
3237
* Verifica que el año y el turno estén presentes y establece el grupo objetivo
3338
* como "course". Finalmente, guarda la notificación en la base de datos.
@@ -51,13 +56,13 @@ public void sendNotificationToAll(NotificationDTO notificationDTO) {
5156

5257
/**
5358
* Envía una notificación a un estudiante específico y su padre.
54-
*
59+
* <p>
5560
* Verifica el DNI del estudiante, busca al estudiante y su padre en la base de datos,
5661
* y asigna estos a la notificación. Finalmente, guarda la notificación en la base de datos.
5762
*
5863
* @param notification La notificación que se va a enviar.
5964
* @throws IllegalArgumentException Si el DNI del estudiante es inválido.
60-
* @throws EntityNotFoundException Si el estudiante o el padre no son encontrados.
65+
* @throws EntityNotFoundException Si el estudiante o el padre no son encontrados.
6166
*/
6267
@Override
6368
public void sendNotificationToStudent(Notification notification) {
@@ -78,22 +83,23 @@ public void sendNotificationToStudent(Notification notification) {
7883
notification.setStudent(student);
7984
notification.setParent(parent);
8085
notification.setTargetGroup("student");
86+
notification.setSentAt(LocalDateTime.now());
8187

8288
// Guarda la notificación
8389
notificationRepository.save(notification);
8490
}
8591

8692
/**
8793
* Envía una notificación a un padre específico basado en el DNI del estudiante.
88-
*
94+
* <p>
8995
* Convierte el objeto {@code NotificationDTO} en una entidad {@code Notification}.
9096
* Verifica que el DNI, el año y el turno estén presentes. Luego, busca al estudiante
9197
* y al padre en la base de datos, asigna el padre a la notificación y establece el grupo
9298
* objetivo como "parent". Finalmente, guarda la notificación en la base de datos.
9399
*
94100
* @param notificationDTO El DTO que contiene los detalles de la notificación.
95101
* @throws IllegalArgumentException Si el DNI, el año o el turno están vacíos.
96-
* @throws EntityNotFoundException Si el estudiante o el padre no son encontrados.
102+
* @throws EntityNotFoundException Si el estudiante o el padre no son encontrados.
97103
*/
98104
@Override
99105
public void sendNotificationToParent(NotificationDTO notificationDTO) {
@@ -116,6 +122,7 @@ public void sendNotificationToParent(NotificationDTO notificationDTO) {
116122
Parent parent = parents.iterator().next(); // Accede al primer padre
117123
notification.setParent(parent);
118124
notification.setTargetGroup("parent");
125+
notification.setSentAt(LocalDateTime.now());
119126

120127
// Guarda la notificación
121128
notificationRepository.save(notification);
@@ -163,4 +170,19 @@ private void validateNotificationData(String dni, String year, String session, S
163170
}
164171
}
165172
}
173+
174+
@Transactional
175+
@Override
176+
public void addResponse(Long notificationId, String responseText) {
177+
// Busca la notificación por ID
178+
Notification notification = notificationRepository.findById(notificationId)
179+
.orElseThrow(() -> new EntityNotFoundException("Notificación no encontrada con ID: " + notificationId));
180+
181+
// Asigna los valores de la respuesta
182+
notification.setResponseTime(LocalDateTime.now());
183+
notification.setResponseText(responseText);
184+
185+
// Guarda la notificación actualizada en la base de datos
186+
notificationRepository.save(notification);
187+
}
166188
}

BackEnd/No-Country-simulation/src/main/java/com/school/service/interfaces/INotificationService.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,6 @@ public interface INotificationService {
3030
* @param notificationDTO El objeto DTO que contiene los detalles de la notificación.
3131
*/
3232
void sendNotificationToParent(NotificationDTO notificationDTO);
33+
34+
void addResponse(Long notificationId, String responseText);
3335
}

BackEnd/No-Country-simulation/src/main/java/com/school/utility/NotificationMapper.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@ public NotificationDTO notificationToDto(Notification notification) {
2929
notification.getSession(),
3030
notification.getMessage(),
3131
notification.getTargetGroup(),
32-
notification.getDni());
32+
notification.getDni(),
33+
notification.getSentAt(),
34+
notification.getSubject(),
35+
notification.getResponseText(),
36+
notification.getResponseTime());
3337
}
3438

3539
/**
@@ -56,6 +60,9 @@ public Notification dtoToNotification(NotificationDTO notificationDTO) {
5660
notification.setMessage(notificationDTO.message());
5761
notification.setTargetGroup(notificationDTO.targetGroup());
5862
notification.setDni(notificationDTO.dni());
63+
notification.setSubject(notificationDTO.subject());
64+
notification.setResponseText(notificationDTO.responseText());
65+
notification.setResponseTime(notificationDTO.responseTime());
5966
return notification;
6067
}
6168
}

0 commit comments

Comments
 (0)