@RequestMapping(value = "/create", method = RequestMethod.POST)
  @RequireHardLogIn
  public String createUserGroup(
      @Valid final B2BUserGroupForm userGroupForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectModel)
      throws CMSItemNotFoundException {
    storeCmsPageInModel(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs =
        myCompanyBreadcrumbBuilder.createManageUserGroupBreadCrumbs();
    breadcrumbs.add(
        new Breadcrumb(
            "/my-company/organization-management/manage-usergroups/create",
            getMessageSource()
                .getMessage(
                    "text.company.manageUsergroups.createUsergroup.breadcrumb",
                    null,
                    "Create Usergroup ",
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);

    if (bindingResult.hasErrors()) {
      GlobalMessages.addErrorMessage(model, "form.global.error");
      model.addAttribute(userGroupForm);
      return createUserGroup(model);
    }
    if (b2bCommerceB2BUserGroupFacade.getUserGroupDataForUid(userGroupForm.getUid()) != null) {
      // a unit uid is not unique
      GlobalMessages.addErrorMessage(model, "form.global.error");
      bindingResult.rejectValue("uid", "form.b2busergroup.notunique");
      model.addAttribute(userGroupForm);
      return createUserGroup(model);
    }

    final B2BUserGroupData userGroupData = new B2BUserGroupData();
    userGroupData.setUid(userGroupForm.getUid());
    userGroupData.setName(userGroupForm.getName());
    if (StringUtils.isNotBlank(userGroupForm.getParentUnit())) {
      userGroupData.setUnit(companyB2BCommerceFacade.getUnitForUid(userGroupForm.getParentUnit()));
    }

    try {
      b2bCommerceB2BUserGroupFacade.updateUserGroup(userGroupForm.getUid(), userGroupData);
    } catch (final DuplicateUidException e) {
      GlobalMessages.addErrorMessage(model, "form.global.error");
      bindingResult.rejectValue("uid", "form.b2busergroup.notunique");
      return createUserGroup(model);
    }

    GlobalMessages.addFlashMessage(
        redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER, "form.b2busergroup.success");

    return String.format(REDIRECT_TO_USERGROUP_DETAILS, urlEncode(userGroupForm.getUid()));
  }
  @RequestMapping(value = "/placeOrder")
  @RequireHardLogIn
  public String placeOrder(
      final Model model, @Valid final PlaceOrderForm placeOrderForm, final BindingResult result)
      throws CMSItemNotFoundException {
    if (result.hasErrors()) {
      GlobalMessages.addErrorMessage(model, "checkout.placeOrder.failed");

      placeOrderForm.setTermsCheck(false);
      model.addAttribute(placeOrderForm);

      return checkoutSummary(model);
    }

    // placeOrderData is the same as placeOrderForm, should use placeOrderData replace
    // placeOrderForm
    final PlaceOrderData placeOrderData = new PlaceOrderData();
    placeOrderData.setNDays(placeOrderForm.getnDays());
    placeOrderData.setNDaysOfWeek(placeOrderForm.getnDaysOfWeek());
    placeOrderData.setNegotiateQuote(placeOrderForm.isNegotiateQuote());
    placeOrderData.setNthDayOfMonth(placeOrderForm.getNthDayOfMonth());
    placeOrderData.setNWeeks(placeOrderForm.getnWeeks());
    placeOrderData.setQuoteRequestDescription(placeOrderForm.getQuoteRequestDescription());
    placeOrderData.setReplenishmentOrder(placeOrderForm.isReplenishmentOrder());
    placeOrderData.setReplenishmentRecurrence(placeOrderForm.getReplenishmentRecurrence());
    placeOrderData.setReplenishmentStartDate(placeOrderForm.getReplenishmentStartDate());
    placeOrderData.setSecurityCode(placeOrderForm.getSecurityCode());
    placeOrderData.setTermsCheck(placeOrderForm.isTermsCheck());

    try {
      final AbstractOrderData orderData = getB2BCheckoutFacade().placeOrder(placeOrderData);

      if (placeOrderForm.isReplenishmentOrder()) {
        return REDIRECT_PREFIX
            + "/checkout/replenishmentConfirmation/"
            + ((ScheduledCartData) orderData).getJobCode();
      } else if (placeOrderForm.isNegotiateQuote()) {
        return REDIRECT_PREFIX + "/checkout/quoteOrderConfirmation/" + orderData.getCode();
      } else {
        return REDIRECT_PREFIX + "/checkout/orderConfirmation/" + orderData.getCode();
      }
    } catch (final EntityValidationException ve) {
      GlobalMessages.addErrorMessage(model, ve.getLocalizedMessage());

      placeOrderForm.setTermsCheck(false);
      model.addAttribute(placeOrderForm);

      return checkoutSummary(model);
    } catch (final Exception e) {
      GlobalMessages.addErrorMessage(model, "checkout.placeOrder.failed");

      placeOrderForm.setTermsCheck(false);
      model.addAttribute(placeOrderForm);

      return checkoutSummary(model);
    }
  }
  @RequestMapping(value = "/update-profile", method = RequestMethod.POST)
  @RequireHardLogIn
  public String updateProfile(
      final UpdateProfileForm updateProfileForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectAttributes)
      throws CMSItemNotFoundException {
    getProfileValidator().validate(updateProfileForm, bindingResult);

    String returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEditPage;
    final CustomerData currentCustomerData = customerFacade.getCurrentCustomer();
    final CustomerData customerData = new CustomerData();
    customerData.setTitleCode(updateProfileForm.getTitleCode());
    customerData.setFirstName(updateProfileForm.getFirstName());
    customerData.setLastName(updateProfileForm.getLastName());
    customerData.setUid(currentCustomerData.getUid());
    customerData.setDisplayUid(currentCustomerData.getDisplayUid());

    model.addAttribute("titleData", userFacade.getTitles());

    if (bindingResult.hasErrors()) {
      GlobalMessages.addErrorMessage(model, "form.global.error");
    } else {
      try {
        customerFacade.updateProfile(customerData);
        GlobalMessages.addFlashMessage(
            redirectAttributes,
            GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.account.profile.confirmationUpdated",
            null);
        returnAction = REDIRECT_TO_PROFILE_PAGE;
      } catch (final DuplicateUidException e) {
        bindingResult.rejectValue("email", "registration.error.account.exists.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
      }
    }

    storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
    model.addAttribute(
        "breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
    return returnAction;
  }
 protected String errorUpdatingEmail(final Model model) throws CMSItemNotFoundException {
   final String returnAction;
   GlobalMessages.addErrorMessage(model, "form.global.error");
   storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
   setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
   model.addAttribute(
       "breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
   returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage;
   return returnAction;
 }
  @RequestMapping(value = "/update-password", method = RequestMethod.POST)
  @RequireHardLogIn
  public String updatePassword(
      final UpdatePasswordForm updatePasswordForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectAttributes)
      throws CMSItemNotFoundException {
    getPasswordValidator().validate(updatePasswordForm, bindingResult);
    if (!bindingResult.hasErrors()) {
      if (updatePasswordForm.getNewPassword().equals(updatePasswordForm.getCheckNewPassword())) {
        try {
          customerFacade.changePassword(
              updatePasswordForm.getCurrentPassword(), updatePasswordForm.getNewPassword());
        } catch (final PasswordMismatchException localException) {
          bindingResult.rejectValue(
              "currentPassword",
              "profile.currentPassword.invalid",
              new Object[] {},
              "profile.currentPassword.invalid");
        }
      } else {
        bindingResult.rejectValue(
            "checkNewPassword",
            "validation.checkPwd.equals",
            new Object[] {},
            "validation.checkPwd.equals");
      }
    }

    if (bindingResult.hasErrors()) {
      GlobalMessages.addErrorMessage(model, "form.global.error");
      storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
      setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));

      model.addAttribute(
          "breadcrumbs",
          accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile.updatePasswordForm"));
      return ControllerConstants.Views.Pages.Account.AccountChangePasswordPage;
    } else {
      GlobalMessages.addFlashMessage(
          redirectAttributes,
          GlobalMessages.CONF_MESSAGES_HOLDER,
          "text.account.confirmation.password.updated",
          null);
      return REDIRECT_TO_PROFILE_PAGE;
    }
  }
  @RequestMapping(value = "/edit", method = RequestMethod.GET)
  @RequireHardLogIn
  public String editUserGroup(@RequestParam("usergroup") final String usergroup, final Model model)
      throws CMSItemNotFoundException {
    storeCmsPageInModel(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs =
        myCompanyBreadcrumbBuilder.createManageUserGroupDetailsBreadCrumbs(usergroup);
    breadcrumbs.add(
        new Breadcrumb(
            String.format(
                "/my-company/organization-management/manage-usergroups/edit/?usergroup=%s",
                urlEncode(usergroup)),
            getMessageSource()
                .getMessage(
                    "text.company.manageUsergroups.editUsergroup.breadcrumb",
                    new Object[] {usergroup},
                    "Edit {0} Usergroup ",
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);

    if (!model.containsAttribute("b2BUserGroupForm")) {
      final B2BUserGroupForm b2BUserGroupForm = new B2BUserGroupForm();
      final B2BUserGroupData userGroupData =
          b2bCommerceB2BUserGroupFacade.getB2BUserGroup(usergroup);
      if (userGroupData == null) {
        GlobalMessages.addErrorMessage(model, "usergroup.notfound");
      } else {
        b2BUserGroupForm.setOriginalUid(userGroupData.getUid());
        if (userGroupData.getUnit() != null) {
          b2BUserGroupForm.setParentUnit(userGroupData.getUnit().getUid());
        }
        b2BUserGroupForm.setUid(userGroupData.getUid());
        b2BUserGroupForm.setName(userGroupData.getName());
      }
      model.addAttribute(b2BUserGroupForm);
    }

    model.addAttribute(
        "branchSelectOptions",
        getBranchSelectOptions(this.companyB2BCommerceFacade.getBranchNodes()));
    model.addAttribute("metaRobots", "no-index,no-follow");
    return ControllerConstants.Views.Pages.MyCompany.MyCompanyManageUsergroupEditPage;
  }
  @RequestMapping(value = "/details", method = RequestMethod.GET)
  @RequireHardLogIn
  public String viewUserGroupDetails(
      @RequestParam("usergroup") final String usergroup,
      final Model model,
      final HttpServletRequest request)
      throws CMSItemNotFoundException {
    storeCmsPageInModel(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs =
        myCompanyBreadcrumbBuilder.createManageUserGroupDetailsBreadCrumbs(usergroup);
    model.addAttribute("breadcrumbs", breadcrumbs);

    final B2BUserGroupData userGroupData = b2bCommerceB2BUserGroupFacade.getB2BUserGroup(usergroup);
    if (userGroupData == null) {
      GlobalMessages.addErrorMessage(model, "usergroup.notfound");
    } else if (CollectionUtils.isEmpty(userGroupData.getMembers())) {
      GlobalMessages.addInfoMessage(model, "usergroup.disabled");
    }
    model.addAttribute("usergroup", userGroupData);
    model.addAttribute("metaRobots", "no-index,no-follow");
    return ControllerConstants.Views.Pages.MyCompany.MyCompanyManageUsergroupViewPage;
  }
  @RequestMapping(value = "/summary/createUpdatePaymentDetails.json", method = RequestMethod.POST)
  @RequireHardLogIn
  public String createUpdatePaymentDetails(
      final Model model, @Valid final PaymentDetailsForm form, final BindingResult bindingResult) {
    paymentDetailsValidator.validate(form, bindingResult);

    final boolean editMode = StringUtils.isNotBlank(form.getPaymentId());

    if (bindingResult.hasErrors()) {
      model.addAttribute("edit", Boolean.valueOf(editMode));

      return ControllerConstants.Views.Fragments.SingleStepCheckout.PaymentDetailsFormPopup;
    }

    final CCPaymentInfoData paymentInfoData = new CCPaymentInfoData();
    paymentInfoData.setId(form.getPaymentId());
    paymentInfoData.setCardType(form.getCardTypeCode());
    paymentInfoData.setAccountHolderName(form.getNameOnCard());
    paymentInfoData.setCardNumber(form.getCardNumber());
    paymentInfoData.setStartMonth(form.getStartMonth());
    paymentInfoData.setStartYear(form.getStartYear());
    paymentInfoData.setExpiryMonth(form.getExpiryMonth());
    paymentInfoData.setExpiryYear(form.getExpiryYear());
    paymentInfoData.setSaved(Boolean.TRUE.equals(form.getSaveInAccount()));
    paymentInfoData.setIssueNumber(form.getIssueNumber());

    final AddressData addressData;
    if (!editMode && Boolean.FALSE.equals(form.getNewBillingAddress())) {
      addressData = getCheckoutCart().getDeliveryAddress();
      if (addressData == null) {
        GlobalMessages.addErrorMessage(
            model, "checkout.paymentMethod.createSubscription.billingAddress.noneSelected");

        model.addAttribute("edit", Boolean.valueOf(editMode));
        return ControllerConstants.Views.Fragments.SingleStepCheckout.PaymentDetailsFormPopup;
      }

      addressData.setBillingAddress(true); // mark this as billing address
    } else {
      final AddressForm addressForm = form.getBillingAddress();

      addressData = new AddressData();
      if (addressForm != null) {
        addressData.setId(addressForm.getAddressId());
        addressData.setTitleCode(addressForm.getTitleCode());
        addressData.setFirstName(addressForm.getFirstName());
        addressData.setLastName(addressForm.getLastName());
        addressData.setLine1(addressForm.getLine1());
        addressData.setLine2(addressForm.getLine2());
        addressData.setTown(addressForm.getTownCity());
        addressData.setPostalCode(addressForm.getPostcode());
        addressData.setCountry(getI18NFacade().getCountryForIsocode(addressForm.getCountryIso()));
        addressData.setShippingAddress(Boolean.TRUE.equals(addressForm.getShippingAddress()));
        addressData.setBillingAddress(Boolean.TRUE.equals(addressForm.getBillingAddress()));
      }
    }

    paymentInfoData.setBillingAddress(addressData);

    final CCPaymentInfoData newPaymentSubscription =
        getCheckoutFacade().createPaymentSubscription(paymentInfoData);
    if (newPaymentSubscription != null
        && StringUtils.isNotBlank(newPaymentSubscription.getSubscriptionId())) {
      if (Boolean.TRUE.equals(form.getSaveInAccount())
          && getUserFacade().getCCPaymentInfos(true).size() <= 1) {
        getUserFacade().setDefaultPaymentInfo(newPaymentSubscription);
      }
      getCheckoutFacade().setPaymentDetails(newPaymentSubscription.getId());
    } else {
      GlobalMessages.addErrorMessage(model, "checkout.paymentMethod.createSubscription.failed");

      model.addAttribute("edit", Boolean.valueOf(editMode));
      return ControllerConstants.Views.Fragments.SingleStepCheckout.PaymentDetailsFormPopup;
    }

    model.addAttribute("createUpdateStatus", "Success");
    model.addAttribute("paymentId", newPaymentSubscription.getId());

    return REDIRECT_PREFIX
        + "/checkout/single/summary/getPaymentDetailsForm.json?paymentId="
        + paymentInfoData.getId()
        + "&createUpdateStatus=Success";
  }
  @RequestMapping(
      value = "/summary",
      method = {RequestMethod.GET, RequestMethod.POST})
  @RequireHardLogIn
  public String checkoutSummary(final Model model) throws CMSItemNotFoundException {

    if (!b2bUserGroupProvider.isCurrentUserAuthorizedToCheckOut()) {
      GlobalMessages.addErrorMessage(model, "checkout.error.invalid.accountType");
      return FORWARD_PREFIX + "/cart";
    }

    if (!hasItemsInCart()) {
      // no items in the cart
      return FORWARD_PREFIX + "/cart";
    }

    getCheckoutFacade().setDeliveryAddressIfAvailable();
    getCheckoutFacade().setDeliveryModeIfAvailable();
    getCheckoutFacade().setPaymentInfoIfAvailable();

    // Set to default payment type
    final B2BPaymentTypeData paymentTypeData = new B2BPaymentTypeData();
    paymentTypeData.setCode(CheckoutPaymentType.ACCOUNT.getCode());

    final CartData tempCartData = new CartData();
    tempCartData.setPaymentType(paymentTypeData);

    final CartData cartData = getB2BCheckoutFacade().updateCheckoutCart(tempCartData);

    // final CartData cartData = getCheckoutFacade().getCheckoutCart();
    if (cartData.getEntries() != null && !cartData.getEntries().isEmpty()) {
      for (final OrderEntryData entry : cartData.getEntries()) {
        final String productCode = entry.getProduct().getCode();
        final ProductData product =
            productFacade.getProductForCodeAndOptions(
                productCode,
                Arrays.asList(
                    ProductOption.BASIC,
                    ProductOption.PRICE,
                    ProductOption.PRICE_RANGE,
                    ProductOption.VARIANT_MATRIX));
        entry.setProduct(product);
      }
    }

    model.addAttribute("cartData", cartData);
    model.addAttribute("allItems", cartData.getEntries());
    model.addAttribute("deliveryAddress", cartData.getDeliveryAddress());
    model.addAttribute("deliveryMode", cartData.getDeliveryMode());
    model.addAttribute("paymentInfo", cartData.getPaymentInfo());
    model.addAttribute("costCenter", cartData.getCostCenter());
    model.addAttribute("quoteText", new B2BCommentData());
    // TODO:Make configuration hmc driven than hardcoding in controllers
    model.addAttribute("nDays", getNumberRange(1, 30));
    model.addAttribute("nthDayOfMonth", getNumberRange(1, 31));
    model.addAttribute("nthWeek", getNumberRange(1, 12));

    model.addAttribute(new AddressForm());
    model.addAttribute(new PaymentDetailsForm());
    if (!model.containsAttribute("placeOrderForm")) {
      final PlaceOrderForm placeOrderForm = new PlaceOrderForm();
      // TODO: Make setting of default recurrence enum value hmc driven rather hard coding in
      // controller
      placeOrderForm.setReplenishmentRecurrence(B2BReplenishmentRecurrenceEnum.MONTHLY);
      placeOrderForm.setnDays("14");
      final List<DayOfWeek> daysOfWeek = new ArrayList<DayOfWeek>();
      daysOfWeek.add(DayOfWeek.MONDAY);
      placeOrderForm.setnDaysOfWeek(daysOfWeek);
      model.addAttribute("placeOrderForm", placeOrderForm);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(SINGLE_STEP_CHECKOUT_SUMMARY_CMS_PAGE));
    setUpMetaDataForContentPage(
        model, getContentPageForLabelOrId(SINGLE_STEP_CHECKOUT_SUMMARY_CMS_PAGE));
    model.addAttribute("metaRobots", "no-index,no-follow");
    return ControllerConstants.Views.Pages.SingleStepCheckout.CheckoutSummaryPage;
  }
  @RequestMapping(
      value = "/edit-address/" + ADDRESS_CODE_PATH_VARIABLE_PATTERN,
      method = RequestMethod.POST)
  @RequireHardLogIn
  public String editAddress(
      final AddressForm addressForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectModel)
      throws CMSItemNotFoundException {
    getAddressValidator().validate(addressForm, bindingResult);
    if (bindingResult.hasErrors()) {
      GlobalMessages.addErrorMessage(model, "form.global.error");
      storeCmsPageInModel(model, getContentPageForLabelOrId(ADD_EDIT_ADDRESS_CMS_PAGE));
      setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ADD_EDIT_ADDRESS_CMS_PAGE));
      setUpAddressFormAfterError(addressForm, model);
      return ControllerConstants.Views.Pages.Account.AccountEditAddressPage;
    }

    model.addAttribute("metaRobots", "no-index,no-follow");

    final AddressData newAddress = new AddressData();
    newAddress.setId(addressForm.getAddressId());
    newAddress.setTitleCode(addressForm.getTitleCode());
    newAddress.setFirstName(addressForm.getFirstName());
    newAddress.setLastName(addressForm.getLastName());
    newAddress.setLine1(addressForm.getLine1());
    newAddress.setLine2(addressForm.getLine2());
    newAddress.setTown(addressForm.getTownCity());
    newAddress.setPostalCode(addressForm.getPostcode());
    newAddress.setBillingAddress(false);
    newAddress.setShippingAddress(true);
    newAddress.setVisibleInAddressBook(true);
    newAddress.setCountry(getI18NFacade().getCountryForIsocode(addressForm.getCountryIso()));

    if (addressForm.getRegionIso() != null && !StringUtils.isEmpty(addressForm.getRegionIso())) {
      newAddress.setRegion(
          getI18NFacade().getRegion(addressForm.getCountryIso(), addressForm.getRegionIso()));
    }

    if (Boolean.TRUE.equals(addressForm.getDefaultAddress())
        || userFacade.getAddressBook().size() <= 1) {
      newAddress.setDefaultAddress(true);
      newAddress.setVisibleInAddressBook(true);
    }

    final AddressVerificationResult<AddressVerificationDecision> verificationResult =
        getAddressVerificationFacade().verifyAddressData(newAddress);
    final boolean addressRequiresReview =
        getAddressVerificationResultHandler()
            .handleResult(
                verificationResult,
                newAddress,
                model,
                redirectModel,
                bindingResult,
                getAddressVerificationFacade().isCustomerAllowedToIgnoreAddressSuggestions(),
                "checkout.multi.address.updated");

    if (addressRequiresReview) {
      model.addAttribute(
          "regions", getI18NFacade().getRegionsForCountryIso(addressForm.getCountryIso()));
      model.addAttribute("country", addressForm.getCountryIso());
      model.addAttribute("edit", Boolean.TRUE);
      storeCmsPageInModel(model, getContentPageForLabelOrId(ADD_EDIT_ADDRESS_CMS_PAGE));
      setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ADD_EDIT_ADDRESS_CMS_PAGE));
      return ControllerConstants.Views.Pages.Account.AccountEditAddressPage;
    }

    userFacade.editAddress(newAddress);

    return REDIRECT_TO_ADDRESS_BOOK_PAGE;
  }
  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  @RequireHardLogIn
  public String editUserGroup(
      @RequestParam("usergroup") final String usergroup,
      @Valid final B2BUserGroupForm userGroupForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectModel)
      throws CMSItemNotFoundException {
    storeCmsPageInModel(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs =
        myCompanyBreadcrumbBuilder.createManageUserGroupDetailsBreadCrumbs(usergroup);
    breadcrumbs.add(
        new Breadcrumb(
            String.format(
                "/my-company/organization-management/manage-usergroups/edit?usergroup=%s",
                urlEncode(usergroup)),
            getMessageSource()
                .getMessage(
                    "text.company.manageUsergroups.editUsergroup.breadcrumb",
                    new Object[] {usergroup},
                    "Edit {0} Usergroup ",
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);

    if (bindingResult.hasErrors()) {
      GlobalMessages.addErrorMessage(model, "form.global.error");
      model.addAttribute(userGroupForm);
      return editUserGroup(usergroup, model);
    }
    if (!userGroupForm.getUid().equals(usergroup)
        && b2bCommerceB2BUserGroupFacade.getB2BUserGroup(userGroupForm.getUid()) != null) {
      // a unit uid is not unique
      GlobalMessages.addErrorMessage(model, "form.global.error");
      bindingResult.rejectValue("uid", "form.b2busergroup.notunique");
      model.addAttribute(userGroupForm);
      return editUserGroup(usergroup, model);
    }

    final B2BUserGroupData userGroupData = b2bCommerceB2BUserGroupFacade.getB2BUserGroup(usergroup);
    if (userGroupData != null) {
      boolean userGroupUpdated = false;

      userGroupData.setUid(userGroupForm.getUid());
      userGroupData.setName(userGroupForm.getName());
      if (StringUtils.isNotBlank(userGroupForm.getParentUnit())) {
        final B2BUnitData newUserGroup =
            companyB2BCommerceFacade.getUnitForUid(userGroupForm.getParentUnit());
        if (!newUserGroup.getUid().equals(userGroupData.getUnit().getUid())) {
          userGroupUpdated = true;
        }

        userGroupData.setUnit(newUserGroup);
      }

      try {
        b2bCommerceB2BUserGroupFacade.updateUserGroup(
            userGroupForm.getOriginalUid(), userGroupData);
      } catch (final DuplicateUidException e) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        bindingResult.rejectValue("uid", "form.b2busergroup.notunique");
        return editUserGroup(usergroup, model);
      }

      if (userGroupUpdated) {
        GlobalMessages.addFlashMessage(
            redirectModel,
            GlobalMessages.INFO_MESSAGES_HOLDER,
            "form.b2busergroup.parentunit.updated");
      } else {
        GlobalMessages.addFlashMessage(
            redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER, "form.b2busergroup.success");
      }

      return String.format(REDIRECT_TO_USERGROUP_DETAILS, urlEncode(userGroupForm.getUid()));

    } else {
      // user has no permissions to edit the group.
      GlobalMessages.addErrorMessage(model, "form.b2busergroup.noeditpermissions");
      model.addAttribute(userGroupForm);
      return editUserGroup(usergroup, model);
    }
  }