Beispiel #1
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);
  }
  /**
   * Удаляет отчет по id. В случае если текущий авторизованный пользователь является руководителем
   * сотрудника, добавившего отчет.
   *
   * @param id
   * @return OK или Error
   */
  @RequestMapping(value = "/timesheetDel/{id}", method = RequestMethod.POST)
  public String delTimeSheet(@PathVariable("id") Integer id, HttpServletRequest httpRequest) {
    TimeSheetUser securityUser = securityService.getSecurityPrincipal();
    if (securityUser == null) {
      throw new SecurityException("Не найден пользователь в контексте безопасности.");
    }

    TimeSheet timeSheet = timeSheetService.find(id);

    logger.info(
        "Удаляется отчет " + timeSheet + ". Инициатор: " + securityUser.getEmployee().getName());
    timeSheetService.delete(timeSheet);

    sendMailService.performTimeSheetDeletedMailing(timeSheet);

    return "redirect:" + httpRequest.getHeader("Referer");
  }
  @RequestMapping(value = "/timesheet", method = RequestMethod.POST)
  public ModelAndView sendTimeSheet(
      @ModelAttribute("timeSheetForm") TimeSheetForm tsForm, BindingResult result) {
    logger.info(
        "Processing form validation for employee {} ({}).",
        tsForm.getEmployeeId(),
        tsForm.getCalDate());
    tsFormValidator.validate(tsForm, result);
    if (result.hasErrors()) {
      logger.info(
          "TimeSheetForm for employee {} has errors. Form not validated.", tsForm.getEmployeeId());
      ModelAndView mavWithErrors = new ModelAndView("timesheet");
      mavWithErrors.addObject("timeSheetForm", tsForm);
      mavWithErrors.addObject("errors", result.getAllErrors());
      mavWithErrors.addObject("selectedProjectsJson", getSelectedProjectsJson(tsForm));
      mavWithErrors.addObject("selectedProjectRolesJson", getSelectedProjectRolesJson(tsForm));
      mavWithErrors.addObject("selectedProjectTasksJson", getSelectedProjectTasksJson(tsForm));
      mavWithErrors.addObject("selectedWorkplaceJson", getSelectedWorkplaceJson(tsForm));
      mavWithErrors.addObject("selectedActCategoriesJson", getSelectedActCategoriesJson(tsForm));
      mavWithErrors.addObject(
          "selectedLongVacationIllnessJson", getSelectedLongVacationIllnessJson(tsForm));
      mavWithErrors.addObject("selectedCalDateJson", getSelectedCalDateJson(tsForm));
      mavWithErrors.addObject("getDateByDefault", getDateByDefault(tsForm.getEmployeeId()));
      mavWithErrors.addObject("getFirstWorkDate", getEmployeeFirstWorkDay(tsForm.getEmployeeId()));
      mavWithErrors.addAllObjects(getListsToMAV());

      return mavWithErrors;
    }
    TimeSheet timeSheet = timeSheetService.storeTimeSheet(tsForm);
    overtimeCauseService.store(timeSheet, tsForm);
    sendMailService.performMailing(tsForm);

    ModelAndView mav = new ModelAndView("selected");
    mav.addObject("timeSheetForm", tsForm);
    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

    return mav;
  }
  // Пользователь списывает занятость за продолжительные отпуск или болезнь.
  @RequestMapping(value = "/timesheetLong", method = RequestMethod.POST)
  public ModelAndView sendTimeSheetLong(
      @ModelAttribute("timeSheetForm") TimeSheetForm tsForm, BindingResult result) {
    logger.info(
        "Processing form validation for employee {} ({}) (long).",
        tsForm.getEmployeeId(),
        tsForm.getCalDate());
    tsFormValidator.validate(tsForm, result);
    if (result.hasErrors()) {
      logger.info(
          "TimeSheetForm for employee {} has errors. Form not validated (long).",
          tsForm.getEmployeeId());
      ModelAndView mavWithErrors = new ModelAndView("timesheet");
      mavWithErrors.addObject("timeSheetForm", tsForm);
      mavWithErrors.addObject("errors", result.getAllErrors());
      mavWithErrors.addObject("selectedProjectRolesJson", "[{row:'0', role:''}]");
      mavWithErrors.addObject("selectedProjectTasksJson", "[{row:'0', task:''}]");
      mavWithErrors.addObject("selectedProjectsJson", "[{row:'0', project:''}]");
      mavWithErrors.addObject("selectedActCategoriesJson", "[{row:'0', actCat:''}]");
      mavWithErrors.addObject("selectedWorkplace", "[{row:'0', workplace:''}]");
      mavWithErrors.addObject("selectedCalDateJson", "''");
      mavWithErrors.addObject(
          "selectedLongVacationIllnessJson", getSelectedLongVacationIllnessJson(tsForm));
      mavWithErrors.addAllObjects(getListsToMAV());

      return mavWithErrors;
    }
    timeSheetService.storeTimeSheetLong(tsForm);
    sendMailService.performMailing(tsForm);

    ModelAndView mav = new ModelAndView("selected");
    mav.addObject("timeSheetForm", tsForm);
    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

    return mav;
  }
Beispiel #5
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);
  }