Ejemplo n.º 1
0
  public List<Vacation> getVacationList(VacationsForm vacationsForm) {
    Integer divisionId = vacationsForm.getDivisionId();
    Integer employeeId = vacationsForm.getEmployeeId();
    Date dateFrom = DateTimeUtil.parseStringToDateForDB(vacationsForm.getCalFromDate());
    Date dateTo = DateTimeUtil.parseStringToDateForDB(vacationsForm.getCalToDate());
    Integer projectId = vacationsForm.getProjectId();
    Integer managerId = vacationsForm.getManagerId();
    List<Integer> regions = vacationsForm.getRegions();
    DictionaryItem vacationType =
        vacationsForm.getVacationType() != 0
            ? dictionaryItemService.find(vacationsForm.getVacationType())
            : null;

    List<Vacation> vacations = new ArrayList<Vacation>();
    if (employeeId != null && employeeId != ALL_VALUE) {
      vacations.addAll(findVacations(employeeId, dateFrom, dateTo, vacationType));
    } else {
      List<Employee> employees =
          employeeService.getEmployees(
              employeeService.createDivisionList(divisionId),
              employeeService.createManagerList(managerId),
              employeeService.createRegionsList(regions),
              employeeService.createProjectList(projectId),
              dateFrom,
              dateTo,
              true);
      vacations.addAll(findVacations(employees, dateFrom, dateTo, vacationType));
    }
    sortVacations(vacations);
    return vacations;
  }
Ejemplo n.º 2
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;
  }
Ejemplo n.º 3
0
  @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);
  }
Ejemplo n.º 4
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.º 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);
  }
Ejemplo n.º 6
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;
    }
  }