Skip to content

Commit

Permalink
feat/(CUST-CPC-1068): Show all customers (#634)
Browse files Browse the repository at this point in the history
JIRA: https://champlainsaintlambert.atlassian.net/browse/CPC-1068
## Context:
This ticket is about being able, as an Admin, to view every customers
(owners) and their personal informations in a page
## Changes
* Created a new endpoint to get all owners in the OwnerController
* Created the api call method to the new endpoint (getAllOwners.ts)
* Created a page where you are able to see all the customers
* Adding the routing for getting all the customers in "router.tsx"
* Made a test for the get all to verify the users are Admin
## Before and After UI (Required for UI-impacting PRs)

![getallcustomers](https://github.com/user-attachments/assets/415440df-b810-4256-aa27-077a04c3198c)
  • Loading branch information
AndrewBadIdea authored Sep 15, 2024
1 parent 9e4c59f commit 306a47e
Show file tree
Hide file tree
Showing 9 changed files with 268 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.petclinic.bffapigateway.domainclientlayer.CustomersServiceClient;
import com.petclinic.bffapigateway.dtos.CustomerDTOs.OwnerRequestDTO;
import com.petclinic.bffapigateway.dtos.CustomerDTOs.OwnerResponseDTO;
import com.petclinic.bffapigateway.dtos.Products.ProductResponseDTO;
import com.petclinic.bffapigateway.exceptions.InvalidInputException;
import com.petclinic.bffapigateway.utils.Security.Annotations.IsUserSpecific;
import com.petclinic.bffapigateway.utils.Security.Annotations.SecuredEndpoint;
Expand All @@ -14,6 +15,7 @@
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
Expand Down Expand Up @@ -49,5 +51,11 @@ public Mono<ResponseEntity<OwnerResponseDTO>> updateOwner(
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.badRequest().build());
}
@SecuredEndpoint(allowedRoles = {Roles.ADMIN, Roles.VET})
@GetMapping(value = "", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<OwnerResponseDTO> getAllOwners() {
return customersServiceClient.getAllOwners();
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

Expand All @@ -36,10 +37,12 @@ public void startMockServer() {
mockServerConfigCustomersService = new MockServerConfigCustomersService();
mockServerConfigCustomersService.registerUpdateOwnerEndpoint();
mockServerConfigCustomersService.registerAddOwnerEndpoint();
mockServerConfigCustomersService.registerGetAllOwnersEndpoint();

mockServerConfigAuthService = new MockServerConfigAuthService();
mockServerConfigAuthService.registerValidateTokenForOwnerEndpoint();
mockServerConfigAuthService.registerValidateTokenForAdminEndpoint();
mockServerConfigAuthService.registerValidateTokenForVetEndpoint();

}

Expand Down Expand Up @@ -125,6 +128,7 @@ void whenUpdateOwner_asCustomer_withInvalidOwnerId_thenReturnInvalidInputExcepti
.verifyComplete();
}


@Test
void whenAddOwner_asAdmin_thenReturnCreatedOwnerResponseDTO() {
OwnerRequestDTO newOwnerRequestDTO = OwnerRequestDTO.builder()
Expand Down Expand Up @@ -186,4 +190,43 @@ void whenAddOwner_asCustomer_thenReturnForbidden() {
.expectStatus().isForbidden();
}

@Test
void whenGetAllOwners_asAdmin_thenReturnAllOwners() {
Flux<OwnerResponseDTO> result = webTestClient.get()
.uri("/api/v2/gateway/owners")
.cookie("Bearer", jwtTokenForValidAdmin) // Token for an admin user
.accept(MediaType.valueOf(MediaType.TEXT_EVENT_STREAM_VALUE))
.exchange()
.expectStatus().isOk()
.expectHeader().contentType("text/event-stream;charset=UTF-8")
.returnResult(OwnerResponseDTO.class)
.getResponseBody();

StepVerifier
.create(result)
.expectNextCount(3)
.verifyComplete();


}

@Test
void whenGetAllOwners_asVet_thenReturnAllOwners() {
Flux<OwnerResponseDTO> result = webTestClient.get()
.uri("/api/v2/gateway/owners")
.cookie("Bearer", jwtTokenForValidVet) // Token for a vet user
.accept(MediaType.valueOf(MediaType.TEXT_EVENT_STREAM_VALUE))
.exchange()
.expectStatus().isOk()
.expectHeader().contentType("text/event-stream;charset=UTF-8")
.returnResult(OwnerResponseDTO.class)
.getResponseBody();

StepVerifier
.create(result)
.expectNextCount(3)
.verifyComplete();
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,28 @@ public class MockServerConfigAuthService {

public static final String jwtTokenForValidAdmin = "valid-test-token-for-valid-admin";

public static final String jwtTokenForValidVet = "valid-test-token-for-valid-vet";


public MockServerConfigAuthService() {
this.clientAndServer = ClientAndServer.startClientAndServer(AUTH_SERVICE_SERVER_PORT);
}

public void registerValidateTokenForVetEndpoint(){
mockServerClient_AuthService
.when(
request()
.withMethod("POST")
.withPath("/users/validate-token")
.withCookie("Bearer", jwtTokenForValidVet)
)
.respond(
response()
.withStatusCode(200)
.withBody(json("{\"token\":\"valid-test-token\",\"userId\":\"cb6701ef-22cf-465c-be59-b1ef71cd4f2e\",\"roles\":[\"VET\"]}"))
);
}

public void registerValidateTokenForOwnerEndpoint() {
mockServerClient_AuthService
.when(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,26 @@ public void registerAddOwnerEndpoint() {
);
}

public void registerGetAllOwnersEndpoint() {
String responseBody = "["
+ "{\"ownerId\":\"owner1\",\"firstName\":\"John\",\"lastName\":\"Does\",\"address\":\"123 Main St\",\"city\":\"Springfield\",\"province\":\"Chicago\",\"telephone\":\"1234567890\"},"
+ "{\"ownerId\":\"owner2\",\"firstName\":\"Jane\",\"lastName\":\"Doew\",\"address\":\"456 Maple St\",\"city\":\"Shelbyville\",\"province\":\"Illinois\",\"telephone\":\"0987654321\"},"
+ "{\"ownerId\":\"owner3\",\"firstName\":\"Jim\",\"lastName\":\"Doee\",\"address\":\"789 Oak St\",\"city\":\"Capital City\",\"province\":\"Longueuil\",\"telephone\":\"1122334455\"}"
+ "]";

mockServerClient_CustomersService
.when(
request()
.withMethod("GET")
.withPath("/owners")
)
.respond(
response()
.withStatusCode(200)
.withBody(json(responseBody))
);
}

public void stopMockServer() {
if(clientAndServer != null)
this.clientAndServer.stop();
Expand Down
15 changes: 15 additions & 0 deletions petclinic-frontend/src/features/customers/api/getAllOwners.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*import { AxiosResponse } from 'axios';
import axiosInstance from '@/shared/api/axiosInstance';
import { OwnerResponseModel } from '../models/OwnerResponseModel';
export const getAllOwners = async (): Promise<
AxiosResponse<OwnerResponseModel[]>
> => {
return await axiosInstance.get<OwnerResponseModel[]>(
`http://localhost:8080/api/v2/gateway/owners`,
);
};
*/
85 changes: 85 additions & 0 deletions petclinic-frontend/src/pages/Customer/AllOwners.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/* General layout for the table */
.owners-container {
max-width: 900px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
background-color: #ffffff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.owners-container h1 {
text-align: center;
margin-bottom: 20px;
color: #333;
font-family: 'Arial', sans-serif;
}

/* Table styling */
.owners-container table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-family: 'Arial', sans-serif;
}

.owners-container th,
.owners-container td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #ddd;
font-size: 16px;
}

.owners-container th {
background-color: #f4f4f4;
color: #555;
}

.owners-container tr:hover {
background-color: #f9f9f9;
}

/* Alternate row background for better readability */
.owners-container tbody tr:nth-child(even) {
background-color: #f2f2f2;
}

/* Responsive table on smaller screens */
@media screen and (max-width: 768px) {
.owners-container table {
width: 100%;
font-size: 14px;
}

.owners-container th,
.owners-container td {
padding: 10px;
}
}

/* Buttons and hover effects */
.owners-container button {
padding: 10px 20px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-family: 'Arial', sans-serif;
font-size: 14px;
transition: background-color 0.3s ease;
}

.owners-container button:hover {
background-color: #218838;
}

/* Error styling */
.error {
color: red;
font-size: 0.8em;
margin-top: 5px;
font-family: 'Arial', sans-serif;
}
71 changes: 71 additions & 0 deletions petclinic-frontend/src/pages/Customer/AllOwners.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import * as React from 'react';
import { useEffect, useState } from 'react';
import { OwnerResponseModel } from '@/features/customers/models/OwnerResponseModel';
import './AllOwners.css';

const AllOwners: React.FC = (): JSX.Element => {
const [owners, setOwners] = useState<OwnerResponseModel[]>([]);

useEffect(() => {
// Now handle real-time updates with EventSource
// Listen for updates in the event stream

const eventSource = new EventSource(
'http://localhost:8080/api/v2/gateway/owners',

{
withCredentials: true,
}
);
eventSource.onmessage = event => {
try {
const parsedData: OwnerResponseModel = JSON.parse(event.data);
setOwners(prevOwners => [...prevOwners, parsedData]); // Add new owner to state
} catch (error) {
console.error('Error parsing event data:', error);
}
};

eventSource.onerror = error => {
console.error('EventSource error:', error);
eventSource.close(); // Close the connection on error
};

// Clean up when the component unmounts
return () => {
eventSource.close();
};
}, []);

return (
<div className="owners-container">
<h1>Owners</h1>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>Province</th>
<th>Telephone</th>
</tr>
</thead>
<tbody>
{owners.map(owner => (
<tr key={owner.ownerId}>
<td>{owner.firstName}</td>
<td>{owner.lastName}</td>
<td>{owner.address}</td>
<td>{owner.city}</td>
<td>{owner.province}</td>
<td>{owner.telephone}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

export default AllOwners;
9 changes: 9 additions & 0 deletions petclinic-frontend/src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Home from '@/pages/Home/Home.tsx';
import ProfileEdit from '@/pages/Customer/ProfileEdit.tsx';
import AddingCustomer from '@/pages/Customer/AddingCustomer.tsx';
import CustomerBillingPage from '@/pages/Bills/CostumerBills.tsx';
import AllOwners from '@/pages/Customer/AllOwners.tsx';

const router = createBrowserRouter([
{
Expand Down Expand Up @@ -61,6 +62,14 @@ const router = createBrowserRouter([
</ProtectedRoute>
),
},
{
path: AppRoutePaths.AllCustomers,
element: (
<ProtectedRoute>
<AllOwners />
</ProtectedRoute>
),
},
// {
// path: AppRoutePaths.PageNotFound,
// element: /* PageNotFoundComponent */
Expand Down
1 change: 1 addition & 0 deletions petclinic-frontend/src/shared/models/path.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ export enum AppRoutePaths {
login = '/users/login',
CustomerProfileEdit = '/customer/profile/edit',
AddingCustomer = '/customer/add',
AllCustomers = '/customers',
Home = '/home',
}

0 comments on commit 306a47e

Please sign in to comment.