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);
  }
  public StringBuffer synchronize() {
    List<DivisionLdap> withBadLeader = new ArrayList<DivisionLdap>();
    List<Division> fromDb = divisionDAO.getDivisionsAll();
    List<DivisionLdap> fromLdap = divisionDAO.getDivisionsFromLDAP();
    StringBuffer sb = new StringBuffer("");

    List<Division> forUpdate = new ArrayList<Division>();
    List<DivisionLdap> forAppend = new ArrayList<DivisionLdap>();

    sb.append("Start synchronization divisions.\n\n");
    for (int indexLdap = 0; indexLdap < fromLdap.size(); indexLdap++) {
      DivisionLdap ldapDiv = fromLdap.get(indexLdap);
      if (ldapDiv.isLeaderVerified()) {
        boolean exist = false;
        for (int indexDb = 0; indexDb < fromDb.size(); indexDb++) {
          Division dbDiv = fromDb.get(indexDb);
          String dbSid = dbDiv.getLdap_objectSid();
          String ldapSid = ldapDiv.getLdapObjectSid();
          if (dbSid != null && dbSid.equals(ldapSid)) {
            if (dbDiv.isActive()) {
              boolean updated = false;
              updated = updated | updateName(dbDiv, ldapDiv);
              updated = updated | updateLeader(dbDiv, ldapDiv);
              if (updated) {
                forUpdate.add(dbDiv);
              }
            }
            exist = true;
            break;
          }
        }
        if (!exist) {
          forAppend.add(ldapDiv);
        }
      } else {
        withBadLeader.add(ldapDiv);
      }
    }

    sb.append(add(forAppend));
    sb.append(divisionDAO.setDivision(forUpdate));

    sendMailService.sendAdminAlert(withBadLeader);
    return sb;

    //		testIdGenerator();
    //		return new StringBuffer("Goo");
  }
  /**
   * Удаляет отчет по 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");
  }
Beispiel #4
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;
    }
  }
  @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 #7
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);
  }