Exemple #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;
  }
 private String getSelectedCalDateJson(TimeSheetForm tsForm) {
   StringBuilder sb = new StringBuilder();
   String date = "";
   sb.append("'");
   if (DateTimeUtil.isDateValid(tsForm.getCalDate())) {
     date = DateTimeUtil.formatDateString(tsForm.getCalDate());
     sb.append(date);
   }
   sb.append("'");
   logger.debug("SelectedCalDateJson = {}", date);
   return sb.toString();
 }
Exemple #3
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;
  }
Exemple #4
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);
  }
Exemple #5
0
 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;
 }
Exemple #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());
  }
 /**
  * получаем максимальное количество дней, за которое руководители проекта должны согласовать
  * заявление на отпуск
  */
 private Integer getControlTimeForProjectManager(Vacation vacation)
     throws VacationApprovalServiceException {
   Long daysForApprove =
       DateTimeUtil.getAllDaysCount(vacation.getCreationDate(), vacation.getBeginDate());
   Integer vacationTreshold = getVacationTreshold();
   if (daysForApprove >= vacationTreshold) {
     return getVacationProjectManagerOverrideThreshold();
   } else {
     return getVacationUrgentProjectManagerOverrideThreshold();
   }
 }
  public static String increaseDay(String day) {
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(DateTimeUtil.stringToTimestamp(day));

    if (calendar.get(Calendar.DAY_OF_YEAR) == calendar.getActualMaximum(calendar.DAY_OF_YEAR)) {
      calendar.add(Calendar.YEAR, 1);
      calendar.set(Calendar.DAY_OF_YEAR, 1);
    } else calendar.add(Calendar.DAY_OF_YEAR, 1);

    return sdf.format(calendar.getTime());
  }
  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void savePlans(JsonRootNode rootNode, Integer year, Integer month) {
    final Calendar calendar = DateTimeUtil.getCalendar(year, month);

    if (DateUtils.truncatedCompareTo(new Date(), calendar.getTime(), Calendar.MONTH) > 0) {
      throw new IllegalArgumentException("Редактирование планов за предыдущий месяц запрещено");
    }

    final List<EmployeePlan> employeePlans = new ArrayList<EmployeePlan>();
    final List<EmployeeProjectPlan> employeeProjectPlans = new ArrayList<EmployeeProjectPlan>();

    processJsonDataItems(employeePlans, employeeProjectPlans, rootNode, year, month);

    employeePlanService.mergeProjectPlans(employeePlans);
    employeeProjectPlanService.mergeEmployeeProjectPlans(employeeProjectPlans);
  }
Exemple #10
0
  @RequestMapping(value = "/report/{year}/{month}/{day}/{employeeId}", method = RequestMethod.GET)
  public ModelAndView sendViewReports(
      @PathVariable("year") Integer year,
      @PathVariable("month") Integer month,
      @PathVariable("day") Integer day,
      @PathVariable("employeeId") Integer employeeId,
      @ModelAttribute("ReportForm") TimeSheetForm tsForm,
      BindingResult result) {
    logger.info("Date for report: {}.{}", year, month);
    logger.info("Date for report: {}", day);
    ModelAndView mav = new ModelAndView("report");
    mav.addObject("ReportForm", tsForm);
    mav.addObject("year", Integer.toString(year));
    mav.addObject("month", month);
    mav.addObject("day", day);
    mav.addObject("employeeId", employeeId);

    final TimeSheet timeSheet =
        timeSheetService.findForDateAndEmployee(
            year.toString() + "-" + month.toString() + "-" + day.toString(), employeeId);

    if (timeSheet == null) {
      ModelAndView errorMav = new ModelAndView("/errors/commonErrors");
      errorMav.addObject("cause", ERROR_CAUSE);
      logger.error("Trying to view a report that was deleted or placed in draft");
      return errorMav;
    } else {

      mav.addObject(
          "creationDate",
          (timeSheet.getCreationDate() != null)
              ? DateTimeUtil.dateToString(
                  timeSheet.getCreationDate(), DateTimeUtil.VIEW_DATE_TIME_PATTERN)
              : "");
      mav.addObject(
          "report", reportService.modifyURL(sendMailService.initMessageBodyForReport(timeSheet)));

      logger.info("<<<<<<<<< End of RequestMapping <<<<<<<<<<<<<<<<<<<<<<");
      return mav;
    }
  }
  /* Возвращает JSON для формы выбора сотрудников */
  @RequestMapping(
      value = "/employee/getAddEmployeeListAsJSON",
      produces = "text/plain;charset=UTF-8")
  @ResponseBody
  public String showAddEmployeeList(
      @ModelAttribute(AddEmployeeForm.ADD_FORM) AddEmployeeForm form) {
    Date date;
    if (form.getYear() == null || form.getMonth() == null) {
      date = new Date();
    } else {
      date = DateTimeUtil.getLastDayOfAnyMonth(form.getYear(), form.getMonth());
    }
    List<Employee> employeeList =
        employeeService.getDivisionEmployeesByManager(
            form.getDivisionId(),
            date,
            form.getRegionListId(),
            form.getProjectRoleListId(),
            form.getManagerId());

    return employeeService.getEmployeeListAsJson(employeeList, true);
  }
Exemple #12
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;
  }
 /**
  * Возвращает название текущего месяца в виде строки
  *
  * @param dateString
  * @return String
  */
 public static String getMonthTxt(String dateString) {
   SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
   Date date = new Date();
   date.setTime(DateTimeUtil.stringToTimestamp(dateString).getTime());
   return sdf.format(date);
 }
Exemple #14
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;
    }
  }
Exemple #15
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);
  }