Ejemplo n.º 1
0
 /**
  * Определяет является ли отпуск учитываемым в трудозатратах
  *
  * @param vacation
  * @return
  */
 public Boolean isConsiderVacation(Vacation vacation) {
   if (vacation == null) {
     return false;
   }
   return VacationTypesEnum.getConsiderVacationTypes()
       .contains(VacationTypesEnum.getById(vacation.getType().getId()));
 }
Ejemplo n.º 2
0
  @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);
  }
Ejemplo n.º 3
0
 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;
 }
Ejemplo n.º 4
0
 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;
 }
Ejemplo n.º 5
0
 // возвращает количество дней в списке отпусков (в зависимости от того какой список был передан)
 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;
 }
Ejemplo n.º 6
0
  // возвращает список отпусков за год определенного типа с указанием количества календарных или
  // рабочих дней
  // в зависимости от того, какой список был передан
  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;
  }
Ejemplo n.º 7
0
 /* функция возвращает можно ли удалить планируемый отпуск в таблице заявлений на отпуск */
 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;
 }
Ejemplo n.º 8
0
  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);
  }