@Transactional public String deleteVacation(Integer vacationId) { final JsonArrayNodeBuilder builder = anArrayBuilder(); String message = null; final Vacation vacation = tryFindVacation(vacationId); if (vacation == null) { // если вдруг удалил автор, а не сотрудник throw new DeleteVacationException("Запись не найдена"); } final Employee employee = securityService.getSecurityPrincipal().getEmployee(); if (isVacationDeletePermission(vacation, employee)) { /* для планируемых отпусков другая удалялка */ if (vacation.getType().getId() == VacationTypesEnum.PLANNED.getId()) { sendMailService.performPlannedVacationDeletedMailing(vacation); } else { sendMailService.performVacationDeletedMailing( vacation); // todo переделать, чтобы рассылка все-таки была после удаления? } delete(vacation); } else { message = "Нельзя удалить заявление на отпуск. Для удаления данного заявления необходимо написать на [email protected]"; } builder.withElement( anObjectBuilder() .withField("status", aNumberBuilder(message == null ? "0" : "-1")) .withField("message", aStringBuilder(message == null ? "" : message))); return JsonUtil.format(builder); }
@Transactional public String approveVacation(Integer vacationId) { Vacation vacation = findVacation(vacationId); Set<VacationApproval> vacationApprovals = vacation.getVacationApprovals(); Date responseDate = new Date(); vacation.setStatus(dictionaryItemService.find(VacationStatusEnum.APPROVED.getId())); store(vacation); vacationApprovalProcessService.sendBackDateVacationApproved(vacation); if (!vacationApprovals.isEmpty()) { for (VacationApproval vacationApproval : vacationApprovals) { vacationApproval.setResult(true); vacationApproval.setResponseDate(responseDate); StringBuilder comment = new StringBuilder("Согласовано "); if (isVacationApprovePermission(vacation)) { comment.append("РЦК"); } else if (request.isUserInRole(ROLE_ADMIN)) { comment.append("Администратором"); } vacationApproval.setComment(comment.toString()); vacationApprovalService.store(vacationApproval); } } return JsonUtil.format( anObjectBuilder().withField("isApproved", JsonNodeBuilders.aTrueBuilder())); }
public Map<Vacation, Integer> getCalDays(List<Vacation> vacations) { Map<Vacation, Integer> calDays = new HashMap<Vacation, Integer>(vacations.size()); for (Vacation vacation : vacations) { Integer diffInDays = DateTimeUtil.getDiffInDays(vacation.getBeginDate(), vacation.getEndDate()); calDays.put(vacation, diffInDays); } return calDays; }
// возвращает количество дней в списке отпусков (в зависимости от того какой список был передан) private int getSummaryDaysCount(Map<Vacation, Integer> days) { int summaryDays = 0; for (Map.Entry<Vacation, Integer> entry : days.entrySet()) { Vacation vacation = entry.getKey(); Integer daysInVacation = entry.getValue(); if (VacationStatusEnum.APPROVED.getId() == vacation.getStatus().getId() || VacationTypesEnum.PLANNED.getId() == vacation.getType().getId()) { summaryDays += daysInVacation; } } return summaryDays; }
// возвращает список отпусков за год определенного типа с указанием количества календарных или // рабочих дней // в зависимости от того, какой список был передан private Map<Vacation, Integer> getDaysForYearByType( Map<Vacation, Integer> days, int year, DictionaryItem type) { Map<Vacation, Integer> daysForYearByType = new HashMap<Vacation, Integer>(); for (Map.Entry<Vacation, Integer> entry : days.entrySet()) { Vacation vacation = entry.getKey(); Integer calDaysInVacation = entry.getValue(); if (vacationStatusInThisYear(vacation, year) && type.getId().equals(vacation.getType().getId())) { daysForYearByType.put(vacation, calDaysInVacation); } } return daysForYearByType; }
/** * Определяет является ли отпуск учитываемым в трудозатратах * * @param vacation * @return */ public Boolean isConsiderVacation(Vacation vacation) { if (vacation == null) { return false; } return VacationTypesEnum.getConsiderVacationTypes() .contains(VacationTypesEnum.getById(vacation.getType().getId())); }
public Map<Vacation, Integer> getWorkDays( Map<Vacation, Integer> calDays, List<Holiday> holidays) { Map<Vacation, Integer> workDays = new HashMap<Vacation, Integer>(calDays.size()); for (Map.Entry<Vacation, Integer> entry : calDays.entrySet()) { Vacation vacation = entry.getKey(); Integer calDaysInVacation = entry.getValue(); Region emplRegion = vacation.getEmployee().getRegion(); final int holidaysCount = getHolidaysCount(holidays, emplRegion, vacation.getBeginDate(), vacation.getEndDate()); final int workDaysCount = calDaysInVacation - holidaysCount; workDays.put(vacation, workDaysCount); } return workDays; }
/* ============================================================================= * main * ============================================================================= */ public static void main(String argv[]) throws Exception { System.gc(); Thread.sleep(1000); Manager managerPtr; Client clients[]; long start; long stop; /* Initialization */ Vacation vac = new Vacation(); vac.parseArgs(argv); managerPtr = vac.initializeManager(); clients = vac.initializeClients(managerPtr); int numThread = vac.CLIENTS; /* Run transactions */ System.out.println("Running clients... "); Barrier.setBarrier(numThread + 1); for (int i = 0; i < numThread; i++) { clients[i].start(); } Barrier.enterBarrier(); start = System.currentTimeMillis(); Barrier.enterBarrier(); stop = System.currentTimeMillis(); Barrier.assertIsClear(); System.out.print("done."); long diff = stop - start; System.out.println("TIME=" + diff); vac.checkTables(managerPtr); /* Clean up */ System.out.println("Deallocating memory... "); /* * TODO: The contents of the manager's table need to be deallocated. */ System.out.println("done."); }
public List<DictionaryItem> getVacationTypes(List<Vacation> vacations) { List<DictionaryItem> result = new ArrayList<DictionaryItem>(); for (Vacation vacation : vacations) { if (!result.contains(vacation.getType())) { result.add(vacation.getType()); } } // отсортируем Collections.sort( result, new Comparator() { @Override public int compare(Object type1, Object type2) { Integer typeId1 = ((DictionaryItem) type1).getId(); Integer typeId2 = ((DictionaryItem) type2).getId(); return typeId1.compareTo(typeId2); } }); return result; }
public String getVacationListByRegionJSON( Date dateFrom, Date dateTo, List<Vacation> vacationList) { List<Region> regionList = regionService.getRegions(); List<Employee> employeeList = new ArrayList<Employee>(); for (Vacation vacation : vacationList) { Employee employee = vacation.getEmployee(); if (!(employeeList.contains(employee))) { employeeList.add(employee); } } final JsonArrayNodeBuilder result = anArrayBuilder(); // для каждого проекта смотрим сотрудников у которых есть отпуск for (Region region : regionList) { JsonArrayNodeBuilder employeeNode = anArrayBuilder(); boolean hasEmployees = false; for (Employee employee : employeeList) { if (employee.getRegion().getId().equals(region.getId())) { JsonArrayNodeBuilder vacationNode = createVacationsNode(employee, vacationList); hasEmployees = true; employeeNode.withElement( anObjectBuilder() .withField("employee", aStringBuilder(employee.getName())) .withField("vacations", vacationNode)); } } if (hasEmployees) { result.withElement( anObjectBuilder() .withField("region_id", aStringBuilder(region.getId().toString())) .withField("region_name", aStringBuilder(region.getName())) .withField("employeeList", employeeNode) .withField("holidays", getHolidayInRegion(dateFrom, dateTo, region))); } } return JsonUtil.format(result); }
public JsonArrayNodeBuilder createVacationsNode(Employee employee, List<Vacation> vacationList) { JsonArrayNodeBuilder vacationNode = anArrayBuilder(); for (Vacation vacation : vacationList) { if (vacation.getEmployee().equals(employee)) { vacationNode.withElement( anObjectBuilder() .withField( "beginDate", aStringBuilder(dateToString(vacation.getBeginDate(), VIEW_DATE_PATTERN))) .withField( "endDate", aStringBuilder(dateToString(vacation.getEndDate(), VIEW_DATE_PATTERN))) .withField("status", aStringBuilder(vacation.getStatus().getValue())) .withField("type", aStringBuilder(vacation.getType().getId().toString())) .withField("typeName", aStringBuilder(vacation.getType().getValue()))); } } return vacationNode; }
/* функция возвращает можно ли удалить планируемый отпуск в таблице заявлений на отпуск */ public Boolean isVacationDeletePermission(Vacation vacation, Employee employee) { if (employee != null && vacation != null) { /* проверим Админ ли текущий пользователь */ if (employeeService.isEmployeeAdmin(employee.getId())) { return Boolean.TRUE; } else { /* для запланированных отпусков проверяем что это либо создатель отпуска либо сам отпускник * либо является лин. рук. отпускника */ if (vacation.getType().getId() == VacationTypesEnum.PLANNED.getId() && (vacation.getEmployee().equals(employee) || vacation.getAuthor().equals(employee) || employeeService.getLinearEmployees(vacation.getEmployee()).contains(employee))) { return Boolean.TRUE; } /* пользователь создатель или отпускник и статус не отклонено и не утверждено */ if ((vacation.getEmployee().equals(employee) || vacation.getAuthor().equals(employee)) && vacation.getStatus().getId() != VacationStatusEnum.REJECTED.getId() && vacation.getStatus().getId() != VacationStatusEnum.APPROVED.getId()) { return Boolean.TRUE; } } } return Boolean.FALSE; }
public Boolean isVacationNotApproved(Vacation vacation) { return !vacation .getStatus() .getId() .equals(dictionaryItemService.find(VacationStatusEnum.APPROVED.getId()).getId()); }
/* определяет по дате началу отпуска принадлежность году */ private Boolean vacationStatusInThisYear(Vacation vacation, int year) { Calendar cal = Calendar.getInstance(); cal.setTime(vacation.getBeginDate()); return cal.get(Calendar.YEAR) == year; }
public void createAndMailVacation( CreateVacationForm createVacationForm, Employee employee, Employee curEmployee, boolean isApprovedVacation) throws VacationApprovalServiceException { final Vacation vacation = new Vacation(); vacation.setCreationDate(new Date()); vacation.setBeginDate(DateTimeUtil.stringToTimestamp(createVacationForm.getCalFromDate())); vacation.setEndDate(DateTimeUtil.stringToTimestamp(createVacationForm.getCalToDate())); vacation.setComment(createVacationForm.getComment().trim()); vacation.setType(dictionaryItemService.find(createVacationForm.getVacationType())); vacation.setAuthor(curEmployee); vacation.setEmployee(employee); vacation.setRemind(false); vacation.setStatus( dictionaryItemService.find( isApprovedVacation ? VacationStatusEnum.APPROVED.getId() : VacationStatusEnum.APPROVEMENT_WITH_PM.getId())); TransactionStatus transactionStatus = null; try { transactionStatus = getNewTransaction(); store(vacation); boolean isPlannedVacation = vacation.getType().getId().equals(VacationTypesEnum.PLANNED.getId()); if (isPlannedVacation) { vacationApprovalProcessService.sendNoticeForPlannedVacaton(vacation); } else { List<Vacation> plannedVacations = vacationDAO.getPlannedVacationsByBeginAndEndDates( employee, vacation.getBeginDate(), vacation.getEndDate()); for (Vacation plannedVacation : plannedVacations) { delete(plannedVacation); } if (needsToBeApproved(vacation)) { vacationApprovalProcessService.sendVacationApproveRequestMessages( vacation); // рассылаем письма о согласовании отпуска } else { vacationApprovalProcessService.sendBackDateVacationApproved(vacation); } } commit(transactionStatus); } catch (VacationApprovalServiceException e) { if (transactionStatus != null) { rollback(transactionStatus); logger.error("Transaction rollbacked. Error saving vacation: {} ", e); } else { logger.error("TransactionStatus is null."); } } sendMailService.performVacationCreateMailing(vacation); }
private boolean needsToBeApproved(Vacation vacation) { return !vacation.getStatus().getId().equals(VacationStatusEnum.APPROVED.getId()); }
/** * Проверка на РЦК * * @param vacation * @return */ public Boolean isVacationApprovePermission(Vacation vacation) { TimeSheetUser securityUser = securityService.getSecurityPrincipal(); Employee manager = vacation.getEmployee().getDivision().getLeaderId(); return securityUser.getEmployee().getId().equals(manager.getId()); }