Example #1
0
  private Integer getVacationDaysCountForPeriod(
      String beginDateString, Integer employeeId, Integer vacationTypeId) {
    Employee employee = employeeService.find(employeeId);
    final Timestamp beginDate =
        DateTimeUtil.stringToTimestamp(beginDateString, CreateVacationForm.DATE_FORMAT);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(employee.getStartDate());
    Integer beginDay = calendar.get(Calendar.DAY_OF_MONTH);

    calendar.setTime(beginDate);
    Integer vacDay = calendar.get(Calendar.DAY_OF_MONTH);
    Integer month = calendar.get(Calendar.MONTH);
    Integer year = calendar.get(Calendar.YEAR);
    //  Если день начала отпуска меньше даты устройства на работу
    //  то оставляем месяц без изменений т.к. calendar.get(Calendar.MONTH) дает -1 один месяц
    if (vacDay > beginDay) {
      ++month;
    }
    Integer count = null;
    if (vacationTypeId.equals(VacationTypesEnum.WITH_PAY.getId())) {
      count = getFactVacationDaysCount(employee, year, month);
    } else {
      count = getPlanVacationDaysCount(employee, year, month);
    }
    return count;
  }
  @Transactional
  public String deleteVacationApprovalByIdAndCheckIsApproved(Integer approvalId) {
    final JsonArrayNodeBuilder builder = anArrayBuilder();
    VacationApproval vacationApproval = find(approvalId);
    final Employee employee = securityService.getSecurityPrincipal().getEmployee();
    final boolean isAdmin = employeeService.isEmployeeAdmin(employee.getId());
    String message = null;
    if (isAdmin) {
      if (vacationApproval != null) {
        deleteVacationApproval(vacationApproval);
      } else {
        message = "Ошибка при удалении, данные отсутствуют";
      }
    } else {
      message = "Ошибка доступа";
    }

    Vacation vacation = vacationApproval.getVacation();
    if (vacation == null) {
      message = "Ошибка при удалении, данные отсутствуют";
    }

    try {
      vacationApprovalProcessService.checkVacationIsApproved(vacation);
    } catch (VacationApprovalServiceException e) {
      message = e.getLocalizedMessage();
    }

    builder.withElement(
        anObjectBuilder()
            .withField("status", aNumberBuilder(message == null ? "0" : "-1"))
            .withField("message", aStringBuilder(message == null ? "" : message)));

    return JsonUtil.format(builder);
  }
  /**
   * рекурсивно поднимаемся по руководителям (employee.manager.manager...) пока не найдем
   * последнего, кому отправлялся запрос согласования. (продолаем рекурсивно подниматься)
   */
  protected VacationApproval getTopLineManagerApprovalRecursive(VacationApproval vacationApproval)
      throws VacationApprovalServiceException {

    int lineManagerDaysToApprove = getControlTimeForLineManager(vacationApproval.getVacation());

    if (vacationApproval.getResult() != null) { // линейный вынес решение об отпуске
      return vacationApproval;
    }

    if (lineManagerHasTimeToApproveVacation(
        lineManagerDaysToApprove, vacationApproval)) { // у линейного еще есть время подумать
      return vacationApproval;
    }

    Employee manager = vacationApproval.getManager();

    if (!managerExists(manager)) { // у линейного нет руководителя или он сам себе руководитель
      return vacationApproval;
    }

    Vacation vacation = vacationApproval.getVacation();
    VacationApproval managerOfManagerApproval =
        tryGetManagerApproval(vacation, manager.getManager());
    if (managerOfManagerApproval
        == null) { // письмо линейному руководителю этого линейного еще не посылалось
      return vacationApproval;
    }

    return getTopLineManagerApprovalRecursive(
        managerOfManagerApproval); // проверяем следующего по иерархии линейного руководителя
  }
 private void setDivision(Project project, String hcLdap) {
   Employee employee = this.employeeDAO.findByLdapName(hcLdap.split("/")[0]);
   if (employee != null) {
     Set<Division> divisions = new TreeSet<Division>();
     divisions.add(employee.getDivision());
     project.setDivisions(divisions);
   }
 }
Example #5
0
  public String checkVacationCountDaysJSON(
      String beginDateString, String endDateString, Integer employeeId, Integer vacationTypeId) {
    Employee employee = employeeService.find(employeeId);

    final Timestamp beginDate =
        DateTimeUtil.stringToTimestamp(beginDateString, CreateVacationForm.DATE_FORMAT);
    final Timestamp endDate =
        DateTimeUtil.stringToTimestamp(endDateString, CreateVacationForm.DATE_FORMAT);

    Integer factCount =
        getVacationDaysCountForPeriod(
            beginDateString, employeeId, VacationTypesEnum.WITH_PAY.getId());
    Integer planCount =
        getVacationDaysCountForPeriod(
            beginDateString, employeeId, VacationTypesEnum.PLANNED.getId());

    // Получаем кол-во дней в отпуске за исключением неучитываемых праздников
    Integer vacationDayCountExCons =
        calendarService.getCountDaysForPeriodForRegionExConsiderHolidays(
            beginDate, endDate, employee.getRegion());

    boolean factError =
        factCount - vacationDayCountExCons < 0
            && vacationTypeId.equals(VacationTypesEnum.WITH_PAY.getId());
    boolean planError = planCount - vacationDayCountExCons < 0;

    JsonObjectNodeBuilder builder =
        anObjectBuilder()
            .withField(
                "error",
                factError
                    ? JsonUtil.aNumberBuilder(-1)
                    : planError ? JsonUtil.aNumberBuilder(1) : JsonUtil.aNumberBuilder(0))
            .withField(
                "message",
                aStringBuilder(
                    factError
                        ? String.format(
                            "Внимание! Вы не можете запланировать отпуск на количество дней, больше %s дней",
                            factCount.toString())
                        : planError
                            ? "Внимание! Создаваемый отпуск превышает допустимое количество дней. Продолжить?"
                            : ""));

    return JsonUtil.format(builder);
  }
Example #6
0
  public String getVacActualizationDate(Employee employee, Integer year, Integer month) {
    Calendar calendarAct = Calendar.getInstance();
    calendarAct.setTime(employee.getStartDate());

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MONTH, --month);
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.DAY_OF_MONTH, calendarAct.get(Calendar.DAY_OF_MONTH));
    return DateTimeUtil.formatDateIntoViewFormat(calendar.getTime());
  }
Example #7
0
 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);
 }
Example #8
0
  public Integer getVacationDaysCount(
      Employee employee, Integer year, Integer month, Boolean fact) {
    VacationDays vacationDays = vacationDaysService.findByEmployee(employee);
    if (vacationDays != null) {
      Calendar calendarAct = Calendar.getInstance();
      calendarAct.setTime(employee.getStartDate());

      Calendar calendar = Calendar.getInstance();
      calendar.set(Calendar.MONTH, --month);
      calendar.set(Calendar.YEAR, year);
      calendar.set(Calendar.DAY_OF_MONTH, calendarAct.get(Calendar.DAY_OF_MONTH));

      Date start = vacationDays.getActualizationDate();
      Date end = calendar.getTime();

      if (start.after(end)) {
        return 0;
      }

      int months = DateTimeUtil.getDiffInMonths(start, end);
      int vacDays = (int) (++months * VACATION_KOEF);
      vacDays += vacationDays.getCountDays();
      Integer vacationsCountByPeriod;
      if (!fact) {
        vacationsCountByPeriod =
            getPlannedVacationsCountByPeriod(employee, vacationDays.getActualizationDate());
      } else {
        vacationsCountByPeriod =
            getFactVacationsCountByPeriod(employee, vacationDays.getActualizationDate());
      }
      if (vacDays > 0) {
        vacDays -= vacationsCountByPeriod;
        return vacDays;
      } else {
        return vacDays;
      }
    }
    return null;
  }
Example #9
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;
 }
Example #10
0
 /**
  * Проверка на РЦК
  *
  * @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());
 }
Example #11
0
  public String getExitToWorkAndCountVacationDayJson(
      String beginDateString, String endDateString, Integer employeeId, Integer vacationTypeId) {
    final JsonObjectNodeBuilder builder = anObjectBuilder();
    try {
      Employee employee = employeeService.find(employeeId);
      final Timestamp beginDate =
          DateTimeUtil.stringToTimestamp(beginDateString, CreateVacationForm.DATE_FORMAT);
      final Timestamp endDate =
          DateTimeUtil.stringToTimestamp(endDateString, CreateVacationForm.DATE_FORMAT);

      // Получаем день выхода на работу
      com.aplana.timesheet.dao.entity.Calendar endDateCalendar = calendarService.find(endDate);
      com.aplana.timesheet.dao.entity.Calendar nextWorkDay =
          calendarService.getNextWorkDay(endDateCalendar, employee.getRegion());
      String format =
          DateFormatUtils.format(nextWorkDay.getCalDate(), CreateVacationForm.DATE_FORMAT);
      builder.withField("exitDate", aStringBuilder(format));

      // Получаем кол-во дней в отпуске за исключением неучитываемых праздников
      Integer vacationDayCountExCons =
          calendarService.getCountDaysForPeriodForRegionExConsiderHolidays(
              beginDate, endDate, employee.getRegion());
      // Получаем кол-во рабочих дней в отпуске
      Integer vacationWorkCount =
          calendarService.getCountWorkDaysForPeriodForRegion(
              beginDate, endDate, employee.getRegion());

      builder.withField("vacationWorkDayCount", aStringBuilder(vacationWorkCount.toString()));
      builder.withField(
          "vacationDayCount",
          aStringBuilder((vacationDayCountExCons <= 0) ? "0" : vacationDayCountExCons.toString()));

      /*  проверка на необходимость вывода информ сообщения
          о необходимости оформления отпуска по вск
          для отпуска с сохранением содержания
      */
      Calendar calendar = java.util.Calendar.getInstance();

      calendar.setTime(beginDate);
      int beginWeekYear = calendar.get(Calendar.WEEK_OF_YEAR);

      calendar.setTime(endDate);
      int endWeekYear = calendar.get(Calendar.WEEK_OF_YEAR);

      calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
      Date beginWeekDate = calendar.getTime();

      int endDay = calendar.get(Calendar.DAY_OF_WEEK);
      int leftDays = Calendar.SATURDAY - endDay;
      calendar.add(Calendar.DATE, ++leftDays);
      Date sunday = calendar.getTime();

      // Количество рабочих дней в отпуске, если конец отпуска приходится
      // на следующую неделю то считается с понедельника след недели по дату конца отпуска
      Integer countWorkDaysVacationPeriod =
          calendarService.getCountWorkDaysForPeriodForRegion(
              beginWeekYear != endWeekYear ? beginWeekDate : beginDate,
              endDate,
              employee.getRegion());

      // Количество рабочих дней в неделе приходящихся на конец отпуска
      Integer countWorkDaysWeek =
          calendarService.getCountWorkDaysForPeriodForRegion(
              beginWeekDate, DateUtils.addDays(beginWeekDate, 6), employee.getRegion());

      // Количество учитываемых дней в период с понедельника последней недели отпуска по конец
      // отпуска
      Integer countVacConsiderDaysOnEndWeek =
          calendarService.getCountDaysForPeriodForRegionExConsiderHolidays(
              beginWeekYear != endWeekYear ? beginWeekDate : beginDate,
              endDate,
              employee.getRegion());

      // Количество учитываемых дней в неделе
      Integer countConsiderDaysOnEndWeek =
          calendarService.getCountDaysForPeriodForRegionExConsiderHolidays(
              beginWeekYear != endWeekYear ? beginWeekDate : beginDate,
              sunday,
              employee.getRegion());

      if (vacationTypeId != null
          && vacationTypeId == VacationTypesEnum.WITH_PAY.getId()
          &&
          // проверка что в отпуск попала не вся учитываемая неделя
          !countVacConsiderDaysOnEndWeek.equals(countConsiderDaysOnEndWeek)
          &&
          // и в этот период попадают все рабочие дни
          countWorkDaysVacationPeriod.equals(countWorkDaysWeek)) {
        builder.withField("vacationFridayInform", aStringBuilder("true"));
      }

      return JsonUtil.format(builder);
    } catch (Exception th) {
      logger.error(CANT_GET_EXIT_TO_WORK_EXCEPTION_MESSAGE, th);
      return CANT_GET_EXIT_TO_WORK_EXCEPTION_MESSAGE;
    }
  }