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

BugFix #8182 Refactored funtionality for receiving total number of orders for employees. #1616

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
Original file line number Diff line number Diff line change
Expand Up @@ -582,20 +582,22 @@ public ResponseEntity<List<OrderInfoDto>> getAllDataForOrder(
}

/**
* Endpoint for getting total amount of orders.
* Endpoint for getting total amount of orders by employee.
*
* @return {@link List OrderCountDto}.
* @return {@link OrderCountDto}.
* @author Chernenko Vitaliy
*/
@Operation(summary = "Returns the total number of orders.")
@Operation(summary = "Returns the total number of orders by employee.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = HttpStatuses.OK),
@ApiResponse(responseCode = "401", description = HttpStatuses.UNAUTHORIZED, content = @Content),
@ApiResponse(responseCode = "403", description = HttpStatuses.FORBIDDEN, content = @Content),
@ApiResponse(responseCode = "404", description = HttpStatuses.NOT_FOUND, content = @Content),
})
@GetMapping("/orders/count")
public ResponseEntity<OrderCountDto> getOrdersCount() {
return ResponseEntity.status(HttpStatus.OK).body(ubsManagementService.getTotalNumberOfOrders());
public ResponseEntity<OrderCountDto> getOrdersCount(Principal principal) {
return ResponseEntity.status(HttpStatus.OK)
.body(bigOrderTableService.getTotalNumberOfOrdersByEmployee(principal.getName()));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import greencity.service.ubs.CertificateService;
import greencity.service.ubs.CoordinateService;
import greencity.service.ubs.PaymentService;
import greencity.service.ubs.UBSClientService;
import greencity.service.ubs.UBSManagementService;
import greencity.service.ubs.ViolationService;
import greencity.service.ubs.manager.BigOrderTableServiceView;
Expand Down Expand Up @@ -77,9 +76,6 @@ class ManagementOrderControllerTest {
@Mock
CertificateService certificateService;

@Mock
UBSClientService ubsClientService;

@Mock
private Validator mockValidator;

Expand Down Expand Up @@ -218,7 +214,7 @@ void getOrdersTotalAmountTest() throws Exception {
.principal(principal))
.andExpect(status().isOk());

verify(ubsManagementService, times(1)).getTotalNumberOfOrders();
verify(bigOrderTableServiceView, times(1)).getTotalNumberOfOrdersByEmployee(principal.getName());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import java.util.List;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.assertTrue;

@Sql(scripts = "/sqlFiles/bigOrderTableRepository/insert.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sqlFiles/bigOrderTableRepository/delete.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@ExtendWith(SpringExtension.class)
Expand Down Expand Up @@ -340,7 +342,7 @@ void get_All_Orders_Sort_By_OrderStatus_UA_Localization_ASC() {
DEFAULT_ORDER_SEARCH_CRITERIA, TARIFFS_ID_LIST, USER_LANGUAGE_UA).getContent();
boolean isListCorrectlySorted =
Comparators.isInOrder(bigOrderTableViewsList, orderStatusTranslationComparator(false));
Assertions.assertTrue(isListCorrectlySorted);
assertTrue(isListCorrectlySorted);
}

@Test
Expand All @@ -351,7 +353,7 @@ void get_All_Orders_Sort_By_OrderStatus_UA_Localization_DESC() {
DEFAULT_ORDER_SEARCH_CRITERIA, TARIFFS_ID_LIST, USER_LANGUAGE_UA).getContent();
boolean isListCorrectlySorted =
Comparators.isInOrder(bigOrderTableViewsList, orderStatusTranslationComparator(true));
Assertions.assertTrue(isListCorrectlySorted);
assertTrue(isListCorrectlySorted);
}

@Test
Expand Down Expand Up @@ -455,7 +457,7 @@ void get_All_Orders_Sort_By_OrderPaymentStatus_UA_Localization_ASC() {
DEFAULT_ORDER_SEARCH_CRITERIA, TARIFFS_ID_LIST, USER_LANGUAGE_UA).getContent();
boolean isListCorrectlySorted =
Comparators.isInOrder(bigOrderTableViewsList, orderPaymentStatusTranslationComparator(false));
Assertions.assertTrue(isListCorrectlySorted);
assertTrue(isListCorrectlySorted);
}

@Test
Expand All @@ -466,7 +468,7 @@ void get_All_Orders_Sort_By_OrderPaymentStatus_UA_Localization_DESC() {
DEFAULT_ORDER_SEARCH_CRITERIA, TARIFFS_ID_LIST, USER_LANGUAGE_UA).getContent();
boolean isListCorrectlySorted =
Comparators.isInOrder(bigOrderTableViewsList, orderPaymentStatusTranslationComparator(true));
Assertions.assertTrue(isListCorrectlySorted);
assertTrue(isListCorrectlySorted);
}

@Test
Expand All @@ -485,6 +487,15 @@ void get_All_Orders_Filter_By_RegionId_And_CityId_And_DistrictId() {
Assertions.assertEquals(expectedValue, actualValue);
}

@Test
void getOrdersCountByTariffsTest() {
List<Long> tariffsInfoIds = List.of(1L, 2L, 3L);

long result = bigOrderTableRepository.getOrdersCountByTariffs(tariffsInfoIds);

assertTrue(result > 0);
}

private Comparator<BigOrderTableViews> orderStatusTranslationComparator(boolean descending) {
Comparator<BigOrderTableViews> comparator = Comparator.comparingInt(
view -> OrderStatusSortingTranslation.valueOf(view.getOrderStatus()).getSortOrder());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,23 @@ public BigOrderTableViews findSingleOrderById(Long orderId) {
.orElse(null);
}

/**
* Method returns total number of orders by list of tariffs.
*
* @param tariffsInfoIds {@link List} list of tariff ids.
* @return the total number of orders, represented as a {@code long}.
*/
public long getOrdersCountByTariffs(List<Long> tariffsInfoIds) {
var countQuery = criteriaBuilder.createQuery(Long.class);
var countOrderRoot = countQuery.from(BigOrderTableViews.class);
var predicates = new ArrayList<Predicate>();

getPredicateByTariffsInfoId(predicates, tariffsInfoIds, countOrderRoot);
var countPredicate = criteriaBuilder.and(predicates.toArray(Predicate[]::new));
countQuery.select(criteriaBuilder.count(countOrderRoot)).where(countPredicate);
return entityManager.createQuery(countQuery).getSingleResult();
}

private Predicate getPredicate(OrderSearchCriteria sc, Root<BigOrderTableViews> orderRoot,
List<Long> tariffsInfoIds) {
var predicates = new ArrayList<Predicate>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import greencity.dto.order.AdminCommentDto;
import greencity.dto.order.BigOrderTableDTO;
import greencity.dto.order.CounterOrderDetailsDto;
import greencity.dto.order.OrderCountDto;
import greencity.dto.order.DetailsOrderInfoDto;
import greencity.dto.order.EcoNumberDto;
import greencity.dto.order.ExportDetailsDto;
Expand Down Expand Up @@ -133,15 +132,6 @@ void setOrderDetail(Order order,
*/
OrderDetailStatusDto getOrderDetailStatus(Long id);

/**
* Method that returns total number of orders.
*
* @return {@link Long}.
*
* @author Chernenko Vitaliy
*/
OrderCountDto getTotalNumberOfOrders();

/**
* Method that update order and payment status by id.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package greencity.service.ubs.manager;

import greencity.dto.order.BigOrderTableDTO;
import greencity.dto.order.OrderCountDto;
import greencity.dto.table.CustomTableViewDto;
import greencity.entity.table.TableColumnWidthForEmployee;
import greencity.filters.OrderPage;
Expand Down Expand Up @@ -40,4 +41,14 @@ public interface BigOrderTableServiceView {
* @author Hrenevych Ivan
*/
TableColumnWidthForEmployee changeIsFreezeStatus(String uuid, Boolean value);

/**
* Method returns total number of orders by employee email.
*
* @param email employee email.
* @return {@link OrderCountDto} object for representing count of orders.
*
* @author Chernenko Vitaliy.
*/
OrderCountDto getTotalNumberOfOrdersByEmployee(String email);
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import greencity.dto.order.OrderAddressDtoResponse;
import greencity.dto.order.OrderAddressExportDetailsDtoUpdate;
import greencity.dto.order.OrderCancellationReasonDto;
import greencity.dto.order.OrderCountDto;
import greencity.dto.order.OrderDetailDto;
import greencity.dto.order.OrderDetailInfoDto;
import greencity.dto.order.OrderDetailStatusDto;
Expand Down Expand Up @@ -821,14 +820,6 @@ public OrderDetailStatusDto getOrderDetailStatus(Long id) {
return buildStatuses(order, payment.getFirst());
}

/**
* {@inheritDoc}
*/
@Override
public OrderCountDto getTotalNumberOfOrders() {
return new OrderCountDto(orderRepository.count());
}

/**
* {@inheritDoc}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.List;
import greencity.client.UserRemoteClient;
import greencity.constant.ErrorMessage;
import greencity.dto.order.OrderCountDto;
import greencity.dto.user.UserVO;
import greencity.entity.table.TableColumnWidthForEmployee;
import greencity.entity.user.employee.Employee;
Expand Down Expand Up @@ -104,6 +105,15 @@ public TableColumnWidthForEmployee changeIsFreezeStatus(String uuid, Boolean val
throw new EntityNotFoundException(EMPLOYEE_WITH_UUID_NOT_FOUND);
}

@Override
public OrderCountDto getTotalNumberOfOrdersByEmployee(String email) {
Long employeeId = employeeRepository.findByEmail(email)
.orElseThrow(() -> new EntityNotFoundException(EMPLOYEE_NOT_FOUND)).getId();
List<Long> tariffsInfoIds = employeeRepository.findTariffsInfoForEmployee(employeeId);

return new OrderCountDto(bigOrderTableRepository.getOrdersCountByTariffs(tariffsInfoIds));
}

private CustomTableViewDto castTableViewToDto(String titles) {
return CustomTableViewDto.builder()
.titles(titles)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import greencity.dto.employee.EmployeePositionDtoRequest;
import greencity.dto.order.AdminCommentDto;
import greencity.dto.order.CounterOrderDetailsDto;
import greencity.dto.order.OrderCountDto;
import greencity.dto.order.DetailsOrderInfoDto;
import greencity.dto.order.EcoNumberDto;
import greencity.dto.order.ExportDetailsDto;
Expand Down Expand Up @@ -666,18 +665,6 @@ void testGetOrderDetailStatusThrowsPaymentNotFoundException() {
() -> ubsManagementService.getOrderDetailStatus(1L));
}

@Test
void getTotalNumberOfOrdersTest() {
final long expectedTotalNumberOfOrders = 10L;
when(orderRepository.count()).thenReturn(expectedTotalNumberOfOrders);

OrderCountDto result = ubsManagementService.getTotalNumberOfOrders();

assertEquals(expectedTotalNumberOfOrders, result.getOrderCount());

verify(orderRepository, times(1)).count();
}

@Test
void testGetOrderDetails() {
when(orderRepository.getOrderDetails(1L)).thenReturn(Optional.of(TEST_ORDER));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,19 @@
import static greencity.ModelUtils.getEmployee;
import static greencity.ModelUtils.getTestTableColumnWidth;
import static greencity.ModelUtils.getTestTableColumnWidthWithIsTableFreezeTrue;
import static greencity.constant.ErrorMessage.EMPLOYEE_NOT_FOUND;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;

@ExtendWith(MockitoExtension.class)
class BigOrderTableServiceImplTest {
class BigOrderTableViewServiceImplTest {
private static final String USER_EMAIL = "test@gmail.com";
private static final String NOT_EXISTS_USER_EMAIL = "not_exists_email@some.com";
@InjectMocks
private BigOrderTableViewServiceImpl bigOrderTableService;
@Mock
Expand All @@ -54,13 +61,13 @@ void getOrders() {
var orderSearchCriteria = getOrderSearchCriteria();
Optional<Employee> employee = Optional.of(getEmployee());
List<Long> tariffsInfoIds = new ArrayList<>();
when(employeeRepository.findByEmail("test@gmail.com")).thenReturn(employee);
when(employeeRepository.findByEmail(USER_EMAIL)).thenReturn(employee);
UserVO userVO = new UserVO().setLanguageVO(new LanguageVO(null, "eng"));
when(userRemoteClient.findNotDeactivatedByEmail("test@gmail.com")).thenReturn(Optional.of(userVO));
when(userRemoteClient.findNotDeactivatedByEmail(USER_EMAIL)).thenReturn(Optional.of(userVO));
when(bigOrderTableRepository.findAll(orderPage, orderSearchCriteria, tariffsInfoIds, "eng"))
.thenReturn(Page.empty());

bigOrderTableService.getOrders(orderPage, orderSearchCriteria, "test@gmail.com");
bigOrderTableService.getOrders(orderPage, orderSearchCriteria, USER_EMAIL);

verify(bigOrderTableRepository).findAll(orderPage, orderSearchCriteria, tariffsInfoIds, "eng");
}
Expand Down Expand Up @@ -97,7 +104,7 @@ void changeOrderTableViewForEmployeeTableWhenIsTableFreezeTrue() {
when(tableColumnWidthForEmployeeRepository.findByEmployeeId(getEmployee().getId()))
.thenReturn(Optional.ofNullable(getTestTableColumnWidthWithIsTableFreezeTrue()));

Assertions.assertThrows(BadRequestException.class,
assertThrows(BadRequestException.class,
() -> bigOrderTableService.changeOrderTableView(uuid, "titles1,titles2"),
"should throw BadRequestException");

Expand Down Expand Up @@ -163,7 +170,7 @@ void changeIsFreezeStatusForNon_ExistUuidTest() {
String nonExistUuid = "Non_Exist";
when(employeeRepository.findByUuid(nonExistUuid)).thenReturn(Optional.empty());

Assertions.assertThrows(
assertThrows(
EntityNotFoundException.class,
() -> bigOrderTableService.changeIsFreezeStatus(nonExistUuid, true),
"Should throw EntityNotFoundException");
Expand All @@ -181,7 +188,7 @@ void changeIsFreezeStatusForNon_ExistEmployeeTableTest() {
when(tableColumnWidthForEmployeeRepository.findByEmployeeId(getEmployee().getId()))
.thenReturn(Optional.empty());

Assertions.assertThrows(
assertThrows(
EntityNotFoundException.class,
() -> bigOrderTableService.changeIsFreezeStatus(uuid, true),
"Should throw EntityNotFoundException");
Expand All @@ -191,6 +198,34 @@ void changeIsFreezeStatusForNon_ExistEmployeeTableTest() {

}

@Test
void getTotalNumberOfOrdersByEmployeeWithValidEmailTest() {
Employee employee = ModelUtils.getEmployee();
List<Long> tariffsInfoIds = List.of(1L, 2L, 3L);
when(employeeRepository.findByEmail(USER_EMAIL)).thenReturn(Optional.of(employee));
when(employeeRepository.findTariffsInfoForEmployee(employee.getId())).thenReturn(tariffsInfoIds);
when(bigOrderTableRepository.getOrdersCountByTariffs(tariffsInfoIds)).thenReturn(10L);

bigOrderTableService.getTotalNumberOfOrdersByEmployee(USER_EMAIL);

verify(employeeRepository, times(1)).findByEmail(USER_EMAIL);
verify(employeeRepository, times(1)).findTariffsInfoForEmployee(employee.getId());
verify(bigOrderTableRepository, times(1)).getOrdersCountByTariffs(tariffsInfoIds);
}

@Test
void getTotalNumberOfOrdersByEmployeeWithNotValidEmailTest() {
when(employeeRepository.findByEmail(NOT_EXISTS_USER_EMAIL))
.thenThrow(new EntityNotFoundException(EMPLOYEE_NOT_FOUND));

assertThrows(EntityNotFoundException.class,
() -> bigOrderTableService.getTotalNumberOfOrdersByEmployee(NOT_EXISTS_USER_EMAIL));

verify(employeeRepository, times(1)).findByEmail(anyString());
verify(employeeRepository, times(0)).findTariffsInfoForEmployee(anyLong());
verify(bigOrderTableRepository, times(0)).getOrdersCountByTariffs(anyList());
}

private OrderPage getOrderPage() {
return new OrderPage().setPageNumber(1);
}
Expand Down
Loading