Skip to content

Commit

Permalink
Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
swafit committed Oct 23, 2023
1 parent d1e61b7 commit 6039d58
Show file tree
Hide file tree
Showing 24 changed files with 519 additions and 85 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.petclinic.bffapigateway.BFFApiGatewayApplication;
import com.petclinic.bffapigateway.dtos.Visits.*;
import com.petclinic.bffapigateway.exceptions.BadRequestException;
import com.petclinic.bffapigateway.exceptions.DuplicateTimeException;
Expand All @@ -25,10 +24,8 @@
*/

@Component
@Slf4j
public class VisitsServiceClient {
private final WebClient webClient;

@Autowired
public VisitsServiceClient(
@Value("${app.visits-service-new.host}") String visitsServiceHost,
Expand Down Expand Up @@ -126,40 +123,12 @@ else if (httpStatus == HttpStatus.CONFLICT){
else {
return Mono.error(new BadRequestException(message));
}

} catch (IOException e) {
// Handle parsing error
return Mono.error(new BadRequestException("Bad Request"));
}
});
})
.onStatus(HttpStatusCode::is2xxSuccessful, response -> {
HttpStatusCode httpStatus = response.statusCode();
if (httpStatus == HttpStatus.CREATED) {

return null;
// return response.bodyToMono(VisitResponseDTO.class);
}
return null;

// return response.bodyToMono(String.class)
// .flatMap(errorMessage -> {
// try {
// ObjectMapper objectMapper = new ObjectMapper();
// JsonNode errorNode = objectMapper.readTree(errorMessage);
// String message = errorNode.get("message").asText();
//
// if (httpStatus == HttpStatus.NOT_FOUND) {
// return Mono.error(new NotFoundException(message));
// } else {
// return Mono.error(new BadRequestException(message));
// }
// } catch (IOException e) {
// // Handle parsing error
// return Mono.error(new BadRequestException("Bad Request"));
// }
// });
})
.bodyToMono(VisitResponseDTO.class);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,17 @@ public class VisitRequestDTO {
private LocalDateTime visitDate;
private String description;
private String petId;
private String ownerId;
private String jwtToken;//used to get the userDetails from the Auth-Service when sending visit emails
private String practitionerId;
private Status status;

public VisitRequestDTO(LocalDateTime now, String description, String petId, String practitionerId) {
public VisitRequestDTO(LocalDateTime now, String description, String petId, String ownerId, String jwtToken, String practitionerId) {
this.visitDate = now;
this.description = description;
this.petId = petId;
this.ownerId = ownerId;
this.jwtToken = jwtToken;
this.practitionerId = practitionerId;
this.status = Status.UPCOMING;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,8 @@ public Mono<VisitResponseDTO> getVisitByVisitId(@PathVariable String visitId){
}
@PostMapping(value = "visit/owners/{ownerId}/pets/{petId}/visits", consumes = "application/json", produces = "application/json")
Mono<ResponseEntity<VisitResponseDTO>> addVisit(@RequestBody VisitRequestDTO visit, @PathVariable String ownerId, @PathVariable String petId, @CookieValue("Bearer") String auth) {
// visit.setPetId(petId);
Mono<UserDetails> user = getUserById(auth, ownerId);
visit.setOwnerId(ownerId);
visit.setJwtToken(auth);
return visitsServiceClient.createVisitForPet(visit).map(ResponseEntity.status(HttpStatus.CREATED)::body)
.defaultIfEmpty(ResponseEntity.badRequest().build());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ void createVisitForPet_Valid() throws JsonProcessingException {
LocalDateTime.parse("2024-11-25 13:45", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
"Test Visit",
"1",
"f470653d-05c5-4c45-b7a0-7d70f003d2ac",
"testJwtToken",
"2"
);

Expand Down Expand Up @@ -178,6 +180,8 @@ void createVisitForPet_Valid() throws JsonProcessingException {

// Assert
StepVerifier.create(resultMono)
.expectNext()
.expectNext()
.expectNextMatches(visitResponse -> Objects.equals(visitResponse.getVisitId(), visitResponseDTO.getVisitId()))
.verifyComplete();

Expand All @@ -191,6 +195,8 @@ void createVisitForPet_DuplicateTime_ThrowsDuplicateTimeException() throws JsonP
LocalDateTime.parse("2024-11-25 13:45", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
"Test Visit",
"1",
"f470653d-05c5-4c45-b7a0-7d70f003d2ac",
"testJwtToken",
"2"
);

Expand Down Expand Up @@ -218,6 +224,8 @@ void createVisitForPet_NotFound_ThrowsNotFoundException() throws JsonProcessingE
LocalDateTime.parse("2024-11-25 13:45", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
"Test Visit",
"1",
"f470653d-05c5-4c45-b7a0-7d70f003d2ac",
"testJwtToken",
"2"
);

Expand Down Expand Up @@ -245,6 +253,8 @@ void createVisitForPet_BadRequest_ThrowsBadRequestException() throws JsonProcess
LocalDateTime.parse("2024-11-25 13:45", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
"Test Visit",
"1",
"f470653d-05c5-4c45-b7a0-7d70f003d2ac",
"testJwtToken",
"2"
);

Expand Down Expand Up @@ -272,6 +282,8 @@ void createVisitForPet_InvalidErrorResponse_ThrowsBadRequestException() throws J
LocalDateTime.parse("2024-11-25 13:45", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
"Test Visit",
"1",
"f470653d-05c5-4c45-b7a0-7d70f003d2ac",
"testJwtToken",
"2"
);

Expand Down Expand Up @@ -322,7 +334,7 @@ void getVisitById() throws Exception {
.visitDate(LocalDateTime.parse("2024-11-25 13:45", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")))
.description("this is a dummy description")
.petId("2")
.petName("YourPetNameHere")
.petName("YourPetNameHere")
.petBirthDate(new Date())
.practitionerId("2")
.vetFirstName("VetFirstNameHere")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ void setUp(){
.thenReturn(Calls.response(format("Message sent to %s", EMAIL_VALID.getTo())));

when(mockMailCall.sendMail(EMAIL_EMPTY_INVALID))
.thenReturn(Calls.response(Response.error(400, ResponseBody.create(JSON, "Bad request"))));
.thenReturn(Calls.response(Response.error(400, ResponseBody.create("Bad request", JSON))));
}

@Test
Expand Down
40 changes: 20 additions & 20 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,7 @@ services:
- SPRING_PROFILES_ACTIVE=docker
depends_on:
- mongo2

# visits:
# build: visits-service
# hostname: visits
# #mem_limit: 350m
# environment:
# - SPRING_PROFILES_ACTIVE=docker
# depends_on:
# mysql1:
# condition: service_healthy
- mailer-service

inventory-service:
build: inventory-service
Expand All @@ -47,16 +38,6 @@ services:
depends_on:
- mongo-customers

# customers:
# build: customers-service
# hostname: customers
# #mem_limit: 350m
# environment:
# - SPRING_PROFILES_ACTIVE=docker
# depends_on:
# mysql3:
# condition: service_healthy

api-gateway:
build: api-gateway
#mem_limit: 350m
Expand Down Expand Up @@ -101,6 +82,25 @@ services:
env_file:
- mailer.env

# visits:
# build: visits-service
# hostname: visits
# #mem_limit: 350m
# environment:
# - SPRING_PROFILES_ACTIVE=docker
# depends_on:
# mysql1:
# condition: service_healthy

# customers:
# build: customers-service
# hostname: customers
# #mem_limit: 350m
# environment:
# - SPRING_PROFILES_ACTIVE=docker
# depends_on:
# mysql3:
# condition: service_healthy

# mysql1:
# image: mysql:5.7
Expand Down
7 changes: 4 additions & 3 deletions visits-service-new/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ dependencies {
'org.springframework.boot:spring-boot-starter-webflux',
'org.yaml:snakeyaml:2.2',
"org.mapstruct:mapstruct:${mapstructVersion}",
'org.simplejavamail:simple-java-mail:8.3.1', 'net.markenwerk:utils-mail-dkim:2.0.1' //Simple Java Mail and DKIM a framework for DKIM signing and verification
'org.simplejavamail:simple-java-mail:8.3.1', 'net.markenwerk:utils-mail-dkim:2.0.1', //Simple Java Mail and DKIM a framework for DKIM signing and verification
'com.squareup.retrofit2:retrofit:2.9.0', 'com.squareup.retrofit2:converter-jackson:2.9.0'

compileOnly 'org.projectlombok:lombok',
"org.mapstruct:mapstruct-processor:${mapstructVersion}"
Expand All @@ -31,13 +32,13 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok',
"org.mapstruct:mapstruct-processor:${mapstructVersion}"

testImplementation 'com.squareup.okhttp3:mockwebserver:4.11.0',
testImplementation 'com.squareup.okhttp3:mockwebserver:4.11.0', 'com.squareup.okhttp3:okhttp:4.11.0',
'org.simplejavamail:simple-java-mail:8.3.1', 'net.markenwerk:utils-mail-dkim:2.0.1', //Simple Java Mail and DKIM a framework for DKIM signing and verification
'org.springframework.boot:spring-boot-starter-test',
'org.yaml:snakeyaml:2.2',
'de.flapdoodle.embed:de.flapdoodle.embed.mongo.spring30x:4.9.2',
'io.projectreactor:reactor-test',
'com.squareup.okhttp3:okhttp:4.11.0'
'com.squareup.retrofit2:retrofit-mock:2.9.0'
}

jacoco {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
import com.petclinic.visits.visitsservicenew.DataLayer.Status;
import com.petclinic.visits.visitsservicenew.DataLayer.VisitRepo;
import com.petclinic.visits.visitsservicenew.DomainClientLayer.*;
import com.petclinic.visits.visitsservicenew.DomainClientLayer.Auth.AuthServiceClient;
import com.petclinic.visits.visitsservicenew.DomainClientLayer.Auth.UserDetails;
import com.petclinic.visits.visitsservicenew.DomainClientLayer.Mailing.Mail;
import com.petclinic.visits.visitsservicenew.DomainClientLayer.Mailing.MailService;
import com.petclinic.visits.visitsservicenew.Exceptions.BadRequestException;
import com.petclinic.visits.visitsservicenew.Exceptions.DuplicateTimeException;
import com.petclinic.visits.visitsservicenew.Exceptions.NotFoundException;
Expand All @@ -15,6 +19,8 @@
import reactor.core.publisher.Mono;
import java.time.LocalDateTime;

import static java.lang.String.format;


@Service
@RequiredArgsConstructor
Expand All @@ -24,6 +30,8 @@ public class VisitServiceImpl implements VisitService {
private final PetsClient petsClient;
private final EntityDtoUtil entityDtoUtil;

private final AuthServiceClient authServiceClient;
private final MailService mailService;
@Override
public Flux<VisitResponseDTO> getAllVisits() {
return repo.findAll().flatMap(visit -> entityDtoUtil.toVisitResponseDTO(visit));
Expand Down Expand Up @@ -77,11 +85,20 @@ public Mono<VisitResponseDTO> addVisit(Mono<VisitRequestDTO> visitRequestDTOMono
.then(validatePetId(visitRequestDTO.getPetId()))
.then(validateVetId(visitRequestDTO.getPractitionerId()))
.then(Mono.just(visitRequestDTO))
.doOnNext(s->{

authServiceClient.getUserById(visitRequestDTO.getJwtToken(), visitRequestDTO.getOwnerId()).subscribe(user->mailService.sendMail(generateVisitRequestEmail(user, visitRequestDTO.getPetId(), visitRequestDTO.getVisitDate())));

// Mono<UserDetails> user = getUserById(auth, ownerId);
// try{
// simpleJavaMailClient.sendMail(emailBuilder("[email protected]"));
// }catch(Exception e){System.out.println("Email failed to send: "+e.getMessage());}
})
)
.doOnNext(v -> System.out.println("Request Date: " + v.getVisitDate())) // Debugging
// .doOnNext(v -> System.out.println("Request Date: " + v.getVisitDate())) // Debugging
.map(visitRequestDTO -> entityDtoUtil.toVisitEntity(visitRequestDTO))
.doOnNext(x -> x.setVisitId(entityDtoUtil.generateVisitIdString()))
.doOnNext(v -> System.out.println("Entity Date: " + v.getVisitDate())) // Debugging
// .doOnNext(x -> x.setVisitId(entityDtoUtil.generateVisitIdString()))
// .doOnNext(v -> System.out.println("Entity Date: " + v.getVisitDate())) // Debugging
.flatMap(visit ->
repo.findByVisitDateAndPractitionerId(visit.getVisitDate(), visit.getPractitionerId()) // FindVisits method in repository
.collectList()
Expand Down Expand Up @@ -210,4 +227,57 @@ else if (dto.getStatus() != Status.UPCOMING){
return Mono.just(dto);
}
}

private Mail generateVisitRequestEmail(UserDetails user, String petName, LocalDateTime visitDate) {
return Mail.builder()
.message(
format("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Verification</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
}
p {
color: #555;
}
a {
color: #007BFF;
}
</style>
</head>
<body>
<div class="container">
<h1>Dear %s,</h1>
<h3>We have received a request to schedule a visit for one of your pet: %s at the following date and time: %s.</h3>
\s
<p>If you do not wish to create an account, please disregard this email.</p>
\s
<p>Thank you for choosing Pet Clinic.</p>
</div>
</body>
</html>
""", user.getUsername(), petName, visitDate.toString()))
.subject("PetClinic Visit request")
.to(user.getEmail())
.build();
}
}
Loading

0 comments on commit 6039d58

Please sign in to comment.