/
whitetech
/
tts
Обзор
Документация
Войти
/
whitetech
/
tts
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
ClientServiceImpl.java
440 строк
21 KB
whitetech
upload files
06 дек 2024, 11:19
06 дек 2024, 11:19
2dc37a9
Код
Авторство
О чём код?
package com.timesheet.service.impl.client; import com.timesheet.client.nextCloud.NextCloudClient; import com.timesheet.entity.client.Client; import com.timesheet.entity.client.ClientExternalProjectNames; import com.timesheet.entity.client.ClientJournal; import com.timesheet.entity.directory.project.DefaultSystemWorkType; import com.timesheet.entity.employee.Employee; import com.timesheet.entity.interview.nps.NetPromoterScoreItem; import com.timesheet.entity.project.Project; import com.timesheet.exception.extended.client.EditClientException; import com.timesheet.exception.extended.client.ExternalProjectNameIsEmptyException; import com.timesheet.exception.extended.client.NotFoundClientException; import com.timesheet.exception.extended.common.NotFoundException; import com.timesheet.exception.extended.common.ValidationException; import com.timesheet.exception.extended.program.NotFoundProgramException; import com.timesheet.helper.journal.ClientJournalHelper; import com.timesheet.helper.journal.ProjectJournalHelper; import com.timesheet.mailing.project.OpenCloseProjectLetter; import com.timesheet.model.client.ClientJournalWithEmployeeNameDto; import com.timesheet.model.client.ClientWithProjectsCounterDto; import com.timesheet.model.client.DefaultSystemRoleDto; import com.timesheet.model.client.SaveClientDto; import com.timesheet.model.client.property.ClientCrossStaffingPropertyDto; import com.timesheet.model.employee.EmployeeShortDto; import com.timesheet.model.employee.EmployeeShortExtDto; import com.timesheet.model.filters.client.ClientFilter; import com.timesheet.model.filters.project.CloseAllProjectFilter; import com.timesheet.model.filters.report.ProjectByClientFilter; import com.timesheet.model.project.DefaultSystemRolesAndWorkTypeDto; import com.timesheet.repository.client.ClientExternalProjectNamesRepository; import com.timesheet.repository.client.ClientJournalRepository; import com.timesheet.repository.client.ClientRepository; import com.timesheet.repository.directory.project.DefaultFullSystemRoleRepository; import com.timesheet.repository.directory.project.DefaultSystemWorkTypeRepository; import com.timesheet.repository.employee.EmployeeRepository; import com.timesheet.repository.interview.nps.NetPromoterScoreItemRepository; import com.timesheet.repository.program.ProgramRepository; import com.timesheet.repository.project.ProjectRepository; import com.timesheet.service.face.client.ClientService; import com.timesheet.service.impl.client.property.ClientCrossStaffingService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static com.timesheet.client.nextCloud.NextCloudClient.*; import static com.timesheet.constant.DateConst.datePattern; import static com.timesheet.utils.jpa.JpaUtil.createPageableWithSort; import static com.timesheet.utils.project.ProjectUtil.getClientCloudRelativePath; @Slf4j @Service @RequiredArgsConstructor public class ClientServiceImpl implements ClientService { private final NextCloudClient nextCloudClient; private final ProjectJournalHelper projectJournalHelper; private final ClientJournalHelper clientJournalHelper; private final OpenCloseProjectLetter openCloseProjectLetter; private final ClientCrossStaffingService clientCrossStaffingService; private final ClientRepository clientRepository; private final ProjectRepository projectRepository; private final ProgramRepository programRepository; private final EmployeeRepository employeeRepository; private final ClientJournalRepository clientJournalRepository; private final NetPromoterScoreItemRepository netPromoterScoreItemRepository; private final DefaultSystemWorkTypeRepository defaultSystemWorkTypeRepository; private final DefaultFullSystemRoleRepository defaultFullSystemRoleRepository; private final ClientExternalProjectNamesRepository clientExternalProjectNamesRepository; @Override @Transactional public Client getClientById(Integer clientId) { return clientRepository.findById(clientId) .map(Client::new) .orElseThrow(NotFoundClientException::new); } @Override public List<Client> getAllSorted() { return clientRepository.findAllByIsDeletedFalse() .stream() .sorted(Comparator.comparing(Client::getCompanyName)) .collect(Collectors.toList()); } @Override @Transactional public void deleteClient(int id, Integer employeeId) { Client client = getClientById(id); client.setIsDeleted(true); clientRepository.save(client); clientJournalHelper.clientRecord(client, employeeId, true); } @Override public Page<Project> getClientProjects(ProjectByClientFilter filter) { if (filter.getOrderName() == null) filter.setOrderName("projectName"); if (filter.getOrderIndex() == null) filter.setOrderIndex("ASC"); String projectName = filter.getProjectName(); if (projectName == null) projectName = "%%"; else projectName = "%" + projectName + "%"; Pageable pageable = createPageableWithSort(filter); return projectRepository.findAllByClientAndProjectName(filter.getClientId(), projectName, pageable); } @Override public Client addClient(Client client, Integer employeeId) { String catalogName = client.getCatalogName(); String companyName = client.getCompanyName(); if (companyName == null || companyName.equals("")) throw new ValidationException("Название клиента не может быть пустым"); if (catalogName == null || catalogName.equals("")) client.setCatalogName(companyName); if (containSlash(catalogName)) { log.error("Error in addClient, contains incorrect symbol slash ( / ) , ( \\ ): " + catalogName); throw new ValidationException("Каталог содержит запрещенные символы '/', '\\'"); } String relativePath = SERVER_FILES_PATH + "/" + client.getCatalogName(); try { nextCloudClient.createNewCatalog(relativePath); client.setCatalogName(catalogName); } catch (Exception ex) { client.setCatalogName(""); String message = "Не удалось создать каталог клиента:" + relativePath + ". " + ex.getLocalizedMessage(); cloudLogger(message, "Создание каталога клиента", null); log.error("Клиент успешно создан.<br>При создании в облаке каталога клиента произошла ошибка: " + message); } clientRepository.save(client); clientJournalHelper.clientRecord(client, employeeId, false); return client; } @Override @Transactional public void editClientV2(SaveClientDto clientDto, Employee author) { editClient(clientDto.getClient(), author.getEmployeeId()); //Свойство "Ставки по УВР" ClientCrossStaffingPropertyDto crossStaffingDto = clientDto.getCrossStaffing(); if (crossStaffingDto != null) { clientCrossStaffingService.saveOrUpdateProperty(crossStaffingDto, author); } } @Override @Transactional public void editClient(Client client, Integer employeeId) { String clientCatalogName = client.getCatalogName(); if (containSlash(clientCatalogName)) { log.error("Error in addClient, contains incorrect symbol slash ( / ) , ( \\ ): " + clientCatalogName); throw new ValidationException("Каталог содержит запрещенные символы '/', '\\'"); } try { Client oldClient = getClientById(client.getClientId()); String oldCatalogName = oldClient.getCatalogName(); if (!oldCatalogName.equals(clientCatalogName)) { String newRelativePath = SERVER_FILES_PATH + "/" + clientCatalogName; String oldRelativePath = SERVER_FILES_PATH + "/" + oldCatalogName; if (!oldCatalogName.isEmpty()) { try { try { nextCloudClient.editCatalogName(oldRelativePath, newRelativePath); client.setCatalogName(clientCatalogName); } catch (Exception e) { String msg = "Не удалось редактировать каталог клиента:" + oldRelativePath + ". " + e.getLocalizedMessage(); cloudLogger(msg, "Редактирование каталога клиента", null); client.setCatalogName(oldCatalogName); log.error("Exception in editClient, can't edit folder for client: " + client.getCatalogName() + ". With message:" + msg); } } catch (Exception ex) { client.setCatalogName(oldCatalogName); String message = "Не удалось редактировать каталог клиента:" + newRelativePath + ". " + ex.getLocalizedMessage(); cloudLogger(message, "Редактирование каталога клиента", null); log.error(message); } } else { try { nextCloudClient.createNewCatalog(newRelativePath); client.setCatalogName(clientCatalogName); } catch (Exception ex) { client.setCatalogName(oldCatalogName); String message = "Не удалось редактировать каталог клиента:" + newRelativePath + ". " + ex.getLocalizedMessage(); cloudLogger(message, "Создание каталога клиента", null); log.error(message); } } } clientRepository.save(client); clientJournalHelper.editClientRecord(oldClient, client, employeeId); } catch (Exception ex) { throw new EditClientException(ex); } } @Override public ClientExternalProjectNames addClientExternalProjectName(ClientExternalProjectNames newExternalProjectName) { if (newExternalProjectName.getName() == null || newExternalProjectName.getClientId() == null) { throw new ValidationException("Необходимо заполнить поле \"Внешнее имя проекта\""); } newExternalProjectName.setProjectUUID(UUID.randomUUID().toString()); ClientExternalProjectNames saved = clientExternalProjectNamesRepository.save(newExternalProjectName); if (saved.getId() != null) { return saved; } else { throw new ExternalProjectNameIsEmptyException(); } } @Override public ClientExternalProjectNames editClientExternalProjectName(ClientExternalProjectNames newExternalProjectName) { if (newExternalProjectName.getId() == null) { throw new ExternalProjectNameIsEmptyException(); } if (newExternalProjectName.getProjectUUID() == null) newExternalProjectName.setProjectUUID(UUID.randomUUID().toString()); ClientExternalProjectNames saved = clientExternalProjectNamesRepository.save(newExternalProjectName); if (saved.getId() != null) { return saved; } else { throw new ExternalProjectNameIsEmptyException(); } } @Override public void deleteClientExternalProjectName(Integer externalProjectNameId) { if (externalProjectNameId == null) { throw new ExternalProjectNameIsEmptyException(); } ClientExternalProjectNames externalProjectNames = clientExternalProjectNamesRepository.findById(externalProjectNameId) .orElseThrow(() -> new NotFoundException("Не удалось получить внешнее имя клиента")); checkUsagesOfExternalNameByPrograms(externalProjectNameId, externalProjectNames); clientExternalProjectNamesRepository.delete(externalProjectNames); } private void checkUsagesOfExternalNameByPrograms(Integer externalProjectNameId, ClientExternalProjectNames externalProjectNames) { List<Integer> programIdsWithThisExternalName = programRepository.findAllByDefaultExternalProjectNameId(externalProjectNameId); if (!programIdsWithThisExternalName.isEmpty()) { throw new ValidationException("Невозможно удалить внешнее имя проекта \"" + externalProjectNames.getName() + "\". Данное имя используется в программах"); } } @Override @Transactional public void closeAllProjectsWithExpiredWarranty(CloseAllProjectFilter filters, Employee author) { Integer clientId = filters.getClientId(); if (clientId != null) { List<Project> projectList = projectRepository.findAllByClientId(clientId); if (projectList != null && !projectList.isEmpty()) { CompletableFuture.runAsync(() -> sendLetterAndAddProjectRecordsAboutChangeStatus(projectList, author.getEmployeeId())); for (Project project : projectList) { //Закрытие проекта project.setIsOpen(false); } projectRepository.saveAll(projectList); } } else { throw new ValidationException("Пожалуйста, укажите клиента"); } } private void sendLetterAndAddProjectRecordsAboutChangeStatus(List<Project> projectList, Integer authorId) { for (Project project : projectList) { Project projectNew = new Project(project); Project projectOld = new Project(project); try { //Закрытие проекта project.setIsOpen(false); openCloseProjectLetter.projectStatusMailing(project, "close/open", authorId); //Запись в журнал projectNew.setIsOpen(false); projectJournalHelper.updateProjectRecord(projectNew, projectOld, authorId); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); } } } @Override public List<EmployeeShortExtDto> getTeamLeadersOnClient(int clientId) { return employeeRepository.findTeamLeadersOnClient(clientId); } @Override public List<Client> getAllClientsWithGroup() { LocalDate twoMonthBefore = LocalDate.now().minusMonths(2); List<Client> activeClientsList = clientRepository.findActiveClients(twoMonthBefore); List<Client> passiveClientsList = clientRepository.findPassiveClients(twoMonthBefore); return createExtClientList(activeClientsList, passiveClientsList); } @Override public List<ClientWithProjectsCounterDto> getAllClientsWithProjectsCounter(ClientFilter filter) { List<ClientWithProjectsCounterDto> clientList = clientRepository.findClientsByFilter(filter); List<Integer> accountManagerIdList = clientList.stream() .map(ClientWithProjectsCounterDto::getAccountManagerId) .toList(); if (accountManagerIdList.isEmpty()) { return clientList; } List<EmployeeShortDto> accountManagerList = employeeRepository.findByEmployeeIdIn(accountManagerIdList) .stream() .map(EmployeeShortDto::new) .toList(); if (accountManagerList.isEmpty()) { return clientList; } clientList.forEach(client -> { if (client.getAccountManagerId() != null) { client.setAccountManager( accountManagerList.stream() .filter(accountManager -> accountManager.getEmployeeId().equals(client.getAccountManagerId())) .findFirst() .orElse(null) ); } }); return clientList; } @Override public List<Client> getEmployeeClients(int employeeId) { return clientRepository.findEmployeeClients(employeeId); } @Override public List<Client> getEmployeeRealClients(int employeeId) { return clientRepository.findEmployeeRealClients(employeeId); } @Override public ClientWithProjectsCounterDto getClientWithProjectsCounterById(int clientId) { ClientWithProjectsCounterDto client = clientRepository.findClientWithCounterById(clientId); client.setRelativePath(getClientCloudRelativePath(client)); return client; } @Override public List<ClientJournalWithEmployeeNameDto> getClientJournal(int clientId) { return clientJournalRepository.getClientJournal(clientId); } @Override public List<ClientJournalWithEmployeeNameDto> removeClientJournalRecord(ClientJournal clientJournal) { clientJournalRepository.save(clientJournal); return getClientJournal(clientJournal.getClientId()); } @Override public DefaultSystemRolesAndWorkTypeDto getDefaultSystemRolesAndWorkTypes() { DefaultSystemRolesAndWorkTypeDto defaultSystemRolesAndWorkTypes = new DefaultSystemRolesAndWorkTypeDto(); List<DefaultSystemRoleDto> defaultSystemRoles = defaultFullSystemRoleRepository.findAllByOrderByRoleNameAsc() .stream() .map(DefaultSystemRoleDto::new) .toList(); List<DefaultSystemWorkType> defaultSystemWorkTypes = defaultSystemWorkTypeRepository.findAllOrdered(); defaultSystemRolesAndWorkTypes.setRoleList(defaultSystemRoles); defaultSystemRolesAndWorkTypes.setWorkTypeList(defaultSystemWorkTypes); return defaultSystemRolesAndWorkTypes; } @Override public List<ClientJournalWithEmployeeNameDto> addNewClientJournalRecord(ClientJournal clientJournal) { clientJournalRepository.save(clientJournal); return getClientJournal(clientJournal.getClientId()); } @Override public List<NetPromoterScoreItem> getClientNpsList(Integer clientId) { List<NetPromoterScoreItem> netPromoterScoreItemList = netPromoterScoreItemRepository.findAllByClientId(clientId); if (!netPromoterScoreItemList.isEmpty()) { for (NetPromoterScoreItem nps : netPromoterScoreItemList) { Integer creatorId = nps.getCreatorId(); if (creatorId != null) { employeeRepository.findById(creatorId) .ifPresent(empTmp -> nps.setCreator(new EmployeeShortDto(empTmp))); } Integer programId = nps.getProgramId(); if (programId != null) { nps.setProgram(programRepository.findById(programId).orElseThrow(NotFoundProgramException::new)); } } } return netPromoterScoreItemList; } @Override public List<Client> getClientsByTeamLeaderId(int teamLeaderId) { String date = getDateTwoMonthsLast(); List<Client> activeClientsList = clientRepository.findActiveClientsByTeamLeaderId(date, teamLeaderId); List<Client> passiveClientsList = clientRepository.findPassiveClientsByTeamLeaderId(date, teamLeaderId); return createExtClientList(activeClientsList, passiveClientsList); } private List<Client> createExtClientList(List<Client> activeClientsList, List<Client> passiveClientsList) { List<Client> clientList = new ArrayList<>(activeClientsList); clientList.add(new Client(100500, "────────────────────", false, null, false, "Line")); clientList.addAll(passiveClientsList); return clientList; } private String getDateTwoMonthsLast() { return datePattern.format(LocalDate.now().minusMonths(2)); } @Override public List<ClientExternalProjectNames> getClientExternalProjectNames(int clientId) { return clientExternalProjectNamesRepository.getClientExternalProjectNames(clientId); } @Override public List<EmployeeShortExtDto> getAllAccountManagers() { return employeeRepository.findAllAccountManagers(); } }