@Test
 public void testReferencesForPurchasedInCategory() {
   final UserModel user = userService.getUserForUID("dejol");
   userService.setCurrentUser(user);
   List<ProductData> result =
       simpleSuggestionFacade.getReferencesForPurchasedInCategory(
           "cameras", Collections.EMPTY_LIST, false, null);
   Assert.assertEquals(4, result.size());
   result =
       simpleSuggestionFacade.getReferencesForPurchasedInCategory(
           "cameras", Collections.EMPTY_LIST, false, NumberUtils.INTEGER_ONE);
   Assert.assertEquals(1, result.size());
   result =
       simpleSuggestionFacade.getReferencesForPurchasedInCategory(
           "cameras", Arrays.asList(ProductReferenceTypeEnum.SIMILAR), false, null);
   Assert.assertEquals(1, result.size());
   result =
       simpleSuggestionFacade.getReferencesForPurchasedInCategory(
           "cameras", Arrays.asList(ProductReferenceTypeEnum.ACCESSORIES), false, null);
   Assert.assertEquals(2, result.size());
   result =
       simpleSuggestionFacade.getReferencesForPurchasedInCategory(
           "cameras", Arrays.asList(ProductReferenceTypeEnum.ACCESSORIES), true, null);
   Assert.assertEquals(1, result.size());
   final ProductData product = result.get(0);
   Assert.assertEquals("adapterDC", product.getCode());
   Assert.assertEquals("adapter", product.getName());
 }
  @Test
  public void testHasWriteCollectionRight() {
    final UserModel otherUser = userService.getUserForUID("other");
    final UserModel abrode = userService.getUserForUID("abrode");
    final UserModel deJol = userService.getUserForUID("deJol");

    final List<CockpitObjectAbstractCollectionModel> collections =
        cockpitCollectionService.getCollectionsForUser(deJol);

    assertThat(collections).isNotNull();
    assertThat(collections.size()).isEqualTo(2);

    CockpitObjectAbstractCollectionModel writableCollection = null;
    for (final CockpitObjectAbstractCollectionModel collection : collections) {
      if ("writable".equals(collection.getQualifier())) {
        writableCollection = collection;
        break;
      }
    }

    boolean hasRight =
        cockpitCollectionService.hasWriteCollectionRight(otherUser, writableCollection);
    assertThat(hasRight).isFalse();

    hasRight = cockpitCollectionService.hasWriteCollectionRight(abrode, writableCollection);
    assertThat(hasRight).isTrue();

    hasRight = cockpitCollectionService.hasWriteCollectionRight(deJol, writableCollection);
    assertThat(hasRight).isTrue();
  }
  private void prepareData() {
    catVersion = catalogVersionService.getCatalogVersion("hwcatalog", "Online");
    catalogVersionService.addSessionCatalogVersion(catVersion);

    user = userService.getUserForUID("ariel");
    userService.setCurrentUser(user);
    cart = cartService.getSessionCart();
    commonI18NService.setCurrentCurrency(commonI18NService.getCurrency("EUR"));
    product1 = productService.getProductForCode(catVersion, "HW2110-0012");
  }
  @Before
  public void setUp() throws Exception {
    // Create data for tests
    LOG.info("Creating data for collections ..");
    userService.setCurrentUser(userService.getAdminUser());
    final long startTime = System.currentTimeMillis();
    new CoreBasicDataCreator().createEssentialData(Collections.EMPTY_MAP, null);
    // importing test csv
    importCsv("/test/testCollections.csv", "windows-1252");

    LOG.info("Finished data for collections " + (System.currentTimeMillis() - startTime) + "ms");
  }
  @Test
  public void testIsUserAssignedPrincipalForAdmin() {
    // given
    final WorkflowActionModel mockAction = mock(WorkflowActionModel.class);
    final UserModel mockUser = mock(UserModel.class);
    when(Boolean.valueOf(userService.isAdmin(mockUser))).thenReturn(Boolean.TRUE);
    when(userService.getCurrentUser()).thenReturn(mockUser);

    // when
    final boolean isAssigned = workflowActionService.isUserAssignedPrincipal(mockAction);

    // then
    assertThat(isAssigned).isTrue();
  }
  @Test
  public void testGetCollectionsForUser() {
    UserModel user = userService.getUserForUID("ahertz");
    List<CockpitObjectAbstractCollectionModel> collections =
        cockpitCollectionService.getCollectionsForUser(user);

    assertThat(collections).isNotNull();
    assertThat(collections.size()).isEqualTo(3);

    user = userService.getUserForUID("abrode");
    collections = cockpitCollectionService.getCollectionsForUser(user);

    assertThat(collections).isNotNull();
    assertThat(collections.size()).isEqualTo(4);
  }
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();

    final CatalogVersionModel version =
        catalogVersionService.getCatalogVersion("hwcatalog", "Online");
    catalogVersionService.addSessionCatalogVersion(version);
    baseProduct = productService.getProductForCode(version, "HW2110-0019");
    partnerProduct = productService.getProductForCode(version, "HW2200-0561");
    user = userService.getUserForUID("demo");
    userService.setCurrentUser(user);
    currency = commonI18NService.getCurrency("EUR");
    commonI18NService.setCurrentCurrency(currency);
  }
  @Before
  public void setUp() throws Exception {
    createCoreData();
    createDefaultCatalog();
    productModel01 = productService.getProduct("testProduct1");
    userModel01 = userService.getUser("anonymous");
    userModel02 = userService.getCurrentUser();

    oldMinimalRating = Config.getParameter(CustomerReviewConstants.KEYS.MINIMAL_RATING);
    oldMaximalRating = Config.getParameter(CustomerReviewConstants.KEYS.MAXIMAL_RATING);

    // Set some configuration values to be used generally in the tests
    Config.setParameter(CustomerReviewConstants.KEYS.MINIMAL_RATING, String.valueOf(0));
    Config.setParameter(CustomerReviewConstants.KEYS.MAXIMAL_RATING, String.valueOf(4));
  }
 /*
  * (non-Javadoc)
  *
  * @see de.hybris.platform.b2bacceleratorfacades.company.CompanyB2BCommerceFacade#getContactNumber(java.lang.String)
  */
 @Override
 public String getContactNumber(final String uuid, final CustomerData customerData) {
   final EnergizerB2BCustomerModel model =
       userService.getUserForUID(uuid, EnergizerB2BCustomerModel.class);
   contactNumberPopulator.populate(model, customerData);
   return customerData.getContactNumber();
 }
  @Test
  public void testGetElements() {
    final UserModel user = userService.getUserForUID("abrode");
    final List<CockpitObjectSpecialCollectionModel> collections =
        cockpitCollectionService.getSpecialCollections(user, "quickcollection");
    CockpitObjectSpecialCollectionModel threeElementsCollection = null;
    for (final CockpitObjectSpecialCollectionModel collection : collections) {
      if ("testSpecialB".equals(collection.getQualifier())) {
        threeElementsCollection = collection;
        break;
      }
    }

    assertThat(threeElementsCollection).isNotNull();

    List<ItemModel> elements =
        cockpitCollectionService.getElements(threeElementsCollection, 0, 100);

    assertThat(elements.size()).isEqualTo(3);
    assertThat(elements.get(0) instanceof ProductModel).isTrue();

    elements = cockpitCollectionService.getElements(threeElementsCollection, 0, 2);

    assertThat(elements.size()).isEqualTo(2);
  }
  @Test
  public void testAddToCollection() {
    final UserModel user = userService.getUserForUID("ahertz");
    List<CockpitObjectAbstractCollectionModel> collections =
        cockpitCollectionService.getCollectionsForUser(user);
    CockpitObjectAbstractCollectionModel collection = null;
    for (final CockpitObjectAbstractCollectionModel coll : collections) {
      if ("testA".equals(coll.getQualifier())) {
        collection = coll;
        break;
      }
    }

    assertThat(collection.getElements().size()).isEqualTo(2);

    final CatalogVersionModel catalogVersion =
        catalogService.getCatalogVersion("testCatalog", "Online");
    final List<ItemModel> elements = new ArrayList<ItemModel>();
    elements.add(productService.getProductForCode(catalogVersion, "testProduct4"));

    final int n = cockpitCollectionService.addToCollection(collection, elements);

    collections = cockpitCollectionService.getCollectionsForUser(user);
    CockpitObjectAbstractCollectionModel changedCollection = null;
    for (final CockpitObjectAbstractCollectionModel coll : collections) {
      if ("testA".equals(coll.getQualifier())) {
        changedCollection = coll;
        break;
      }
    }

    assertThat(changedCollection.getElements().size()).isEqualTo(3);
    assertThat(n).isEqualTo(1);
  }
  @Test
  public void shouldUpdateBranchInSession() throws Exception {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final JaloSession currentSession = JaloSession.getCurrentSession();
            final DefaultSession session =
                (DefaultSession) sessionService.getSession(currentSession.getSessionID());
            Assert.assertEquals(currentSession, session.getJaloSession());

            session.setAttribute("test", new Object());
            Assert.assertNotNull(currentSession.getAttribute("test"));
            final B2BCustomerModel user = (B2BCustomerModel) userService.getUserForUID("IC CEO");
            session.setAttribute(B2BConstants.CTX_ATTRIBUTE_BRANCH, null);
            session.setAttribute(B2BConstants.CTX_ATTRIBUTE_ROOTUNIT, null);
            Assert.assertNull(currentSession.getAttribute(B2BConstants.CTX_ATTRIBUTE_BRANCH));
            Assert.assertNull(currentSession.getAttribute(B2BConstants.CTX_ATTRIBUTE_ROOTUNIT));

            b2bUnitService.updateBranchInSession(session, user);
            Assert.assertNotNull(currentSession.getAttribute(B2BConstants.CTX_ATTRIBUTE_BRANCH));
            Assert.assertNotNull(currentSession.getAttribute(B2BConstants.CTX_ATTRIBUTE_ROOTUNIT));
          }
        },
        userService.getAdminUser());
  }
  @Test
  public void testGetBranch() throws Exception {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final String userId = "IC CEO";
            login(userId);

            // test getBranchMethod
            B2BUnitModel unit = b2bUnitService.getUnitForUid("IC");
            Assert.assertNotNull(unit);
            final Set<B2BUnitModel> decendents = b2bUnitService.getBranch(unit);
            Assert.assertNotNull(decendents);
            Assert.assertEquals(11, decendents.size());

            // test getAllUnitsOfOrganization
            final Set<B2BUnitModel> allUnits = b2bUnitService.getBranch(unit);
            Assert.assertNotNull(allUnits);
            Assert.assertEquals(11, allUnits.size());

            unit = b2bUnitService.getUnitForUid("IC Sales");
            Assert.assertNotNull(unit);
            Assert.assertEquals(b2bUnitService.getParent(unit).getUid(), "IC");
            Assert.assertEquals(b2bUnitService.getRootUnit(unit).getUid(), "IC");
            Assert.assertEquals(9, b2bUnitService.getBranch(unit).size());
          }
        },
        userService.getAdminUser());
  }
 @Test
 public void searchRestrictionTest() {
   final UserGroupModel group = new UserGroupModel();
   group.setUid("customergroup");
   modelService.save(group);
   // create test user
   final UserModel user = new UserModel();
   user.setUid(TEST_USER);
   // assign user to customergroup
   user.setGroups(Collections.singleton((PrincipalGroupModel) group));
   modelService.save(user);
   // create test catalog
   final CatalogModel catalog = new CatalogModel();
   catalog.setId(TEST_CATALOG);
   modelService.save(catalog);
   // create test catalog version
   final CatalogVersionModel catalogVersion = new CatalogVersionModel();
   catalogVersion.setCatalog(catalog);
   catalogVersion.setVersion(TEST_VERSION);
   modelService.save(catalogVersion);
   // create test product
   final ProductModel product = new ProductModel();
   product.setCode(TEST_PRODUCT);
   product.setCatalogVersion(catalogVersion);
   modelService.save(product);
   // set current user
   userService.setCurrentUser(user);
   // create search restriction
   commonI18NService.setCurrentLanguage(commonI18NService.getLanguage(LANG_EN));
   final Map<String, String[]> params = new HashMap<String, String[]>();
   params.put("customerreview.searchrestrictions.create", new String[] {"true"});
   final SystemSetupContext ctx =
       new SystemSetupContext(params, Type.ESSENTIAL, Process.ALL, "customerreview");
   customerReviewSystemSetup.createSearchRestrictions(ctx);
   // enable search restrictions
   searchRestrictionService.enableSearchRestrictions();
   // make sure that number of customer reviews is 0
   assertEquals(
       INVALID_NUMBER_OF_CUSTOMER_REVIEWS,
       Integer.valueOf(0),
       customerReviewService.getNumberOfReviews(product));
   // create restricted customer review
   createCustomerReview(null, user, product, CustomerReviewApprovalType.PENDING);
   // create valid customer review
   createCustomerReview("headline", user, product, CustomerReviewApprovalType.APPROVED);
   // make sure that number of customer reviews is 1
   assertEquals(
       INVALID_NUMBER_OF_CUSTOMER_REVIEWS,
       Integer.valueOf(1),
       customerReviewService.getNumberOfReviews(product));
   // disable search restrictions
   searchRestrictionService.disableSearchRestrictions();
   // make sure that number of customer reviews is 2
   assertEquals(
       INVALID_NUMBER_OF_CUSTOMER_REVIEWS,
       Integer.valueOf(2),
       customerReviewService.getNumberOfReviews(product));
 }
  @Test
  public void testCloneCollection() {
    final UserModel user = userService.getUserForUID("ahertz");
    final UserModel userB = userService.getUserForUID("abrode");
    final List<CockpitObjectAbstractCollectionModel> collections =
        cockpitCollectionService.getCollectionsForUser(user);
    final CockpitObjectCollectionModel collection =
        (CockpitObjectCollectionModel) collections.get(0);

    final CockpitObjectAbstractCollectionModel clone =
        cockpitCollectionService.cloneCollection(collection, userB);

    assertThat(clone).isNotNull();
    assertThat(clone.getUser()).isEqualTo(userB);
    assertThat(clone.getQualifier()).isEqualTo(collection.getQualifier());
    assertThat(clone.getElements().size())
        .isEqualTo(Integer.valueOf(collection.getElements().size()));
  }
  @Test
  public void testGetSpecialCollectionsForUser() {
    final UserModel user = userService.getUserForUID("ahertz");
    final List<CockpitObjectSpecialCollectionModel> collections =
        cockpitCollectionService.getSpecialCollectionsForUser(user);

    assertThat(collections).isNotNull();
    assertThat(collections.size()).isEqualTo(1);
    assertThat(collections.get(0).getQualifier()).isEqualTo("testSpecialA");
    assertThat(collections.get(0).getCollectionType().getCode()).isEqualTo("blacklist");
    assertThat(collections.get(0).getElements().size()).isEqualTo(2);
  }
  @Test
  public void testGetSpecialCollections() {
    final UserModel user = userService.getUserForUID("abrode");
    final List<CockpitObjectSpecialCollectionModel> collections =
        cockpitCollectionService.getSpecialCollections(user, "quickcollection");

    assertThat(collections).isNotNull();
    assertThat(collections.size()).isEqualTo(1);
    assertThat(collections.get(0).getQualifier()).isEqualTo("testSpecialB");
    assertThat(collections.get(0).getCollectionType().getCode()).isEqualTo("quickcollection");
    assertThat(collections.get(0).getElements().size()).isEqualTo(3);
  }
  @Before
  public void setUp() throws Exception {
    // final Create data for tests
    LOG.info("Creating data for DefaultChangeProductPriceBundleRuleDaoIntegrationTest ..");
    userService.setCurrentUser(userService.getAdminUser());
    final long startTime = System.currentTimeMillis();
    new CoreBasicDataCreator().createEssentialData(Collections.EMPTY_MAP, null);

    // importing test csv
    final String legacyModeBackup = Config.getParameter(ImpExConstants.Params.LEGACY_MODE_KEY);
    LOG.info(
        "Existing value for " + ImpExConstants.Params.LEGACY_MODE_KEY + " :" + legacyModeBackup);
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "true");
    importCsv("/commerceservices/test/testCommerceCart.csv", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "false");
    importCsv("/subscriptionservices/test/testSubscriptionCommerceCartService.impex", "utf-8");
    importCsv("/configurablebundleservices/test/testBundleCommerceCartService.impex", "utf-8");
    importCsv("/configurablebundleservices/test/testApproveAllBundleTemplates.impex", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, legacyModeBackup);

    LOG.info(
        "Finished data for DefaultChangeProductPriceBundleRuleDaoIntegrationTest "
            + (System.currentTimeMillis() - startTime)
            + "ms");

    baseSiteService.setCurrentBaseSite(baseSiteService.getBaseSiteForUID(TEST_BASESITE_UID), false);
    catalogVersionService.setSessionCatalogVersion("testCatalog", "Online");

    currencyUSD = commonI18NService.getCurrency("USD");
    currencyEUR = commonI18NService.getCurrency("EUR");
    galaxynexus = productService.getProductForCode("GALAXY_NEXUS");
    standardplan1y = productService.getProductForCode("PLAN_STANDARD_1Y");
    standardplan3y = productService.getProductForCode("PLAN_STANDARD_3Y");
    smartPhonePlanBundleTemplate =
        bundleTemplateService.getBundleTemplateForCode("SmartPhonePlanSelection");
    smartPhoneDeviceBundleTemplate =
        bundleTemplateService.getBundleTemplateForCode("SmartPhoneDeviceSelection");

    modelService.detachAll();
  }
  @Test
  public void testRemoveFromCollection() {
    final UserModel user = userService.getUserForUID("ahertz");
    List<CockpitObjectAbstractCollectionModel> collections =
        cockpitCollectionService.getCollectionsForUser(user);
    CockpitObjectAbstractCollectionModel collection = null;

    for (final CockpitObjectAbstractCollectionModel coll : collections) {
      if ("testA".equals(coll.getQualifier())) {
        collection = coll;
        break;
      }
    }

    assertThat(collection.getElements().size()).isEqualTo(2);

    final CatalogVersionModel catalogVersion =
        catalogService.getCatalogVersion("testCatalog", "Online");
    final List<ItemModel> elements = new ArrayList<ItemModel>();
    elements.add(productService.getProductForCode(catalogVersion, "testProduct4"));

    int n = cockpitCollectionService.removeFromCollection(collection, elements);

    collections = cockpitCollectionService.getCollectionsForUser(user);
    CockpitObjectAbstractCollectionModel changedCollection = null;
    for (final CockpitObjectAbstractCollectionModel coll : collections) {
      if ("testA".equals(coll.getQualifier())) {
        changedCollection = coll;
        break;
      }
    }
    // should not change, before we tried to remove the element that does not exist in the
    // collection
    assertThat(changedCollection.getElements().size()).isEqualTo(2);
    assertThat(n).isEqualTo(0);

    elements.clear();
    elements.add(productService.getProductForCode(catalogVersion, "testProduct0"));

    n = cockpitCollectionService.removeFromCollection(collection, elements);

    collections = cockpitCollectionService.getCollectionsForUser(user);
    changedCollection = null;
    for (final CockpitObjectAbstractCollectionModel coll : collections) {
      if ("testA".equals(coll.getQualifier())) {
        changedCollection = coll;
        break;
      }
    }
    assertThat(changedCollection.getElements().size()).isEqualTo(1);
    assertThat(n).isEqualTo(1);
  }
  @Before
  public void setUp() throws Exception {
    LOG.info("Creating data for SubscriptionEntitlementTest ...");
    userService.setCurrentUser(userService.getAdminUser());
    final long startTime = System.currentTimeMillis();
    new CoreBasicDataCreator().createEssentialData(Collections.EMPTY_MAP, null);
    // importing test csv
    final String legacyModeBackup = Config.getParameter(ImpExConstants.Params.LEGACY_MODE_KEY);
    LOG.info(
        "Existing value for " + ImpExConstants.Params.LEGACY_MODE_KEY + " :" + legacyModeBackup);
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "true");
    importCsv("/commerceservices/test/testCommerceCart.csv", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "false");
    importCsv("/subscriptionservices/test/testSubscriptionCommerceCartService.impex", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, legacyModeBackup);

    LOG.info(
        "Finished data for SubscriptionEntitlementTest "
            + (System.currentTimeMillis() - startTime)
            + "ms");
    modelService.detachAll();
  }
  @Test
  public void testHasReadCollectionRight() {
    final UserModel otherUser = userService.getUserForUID("other");
    final UserModel abrode = userService.getUserForUID("abrode");
    final UserModel deJol = userService.getUserForUID("deJol");

    final List<CockpitObjectAbstractCollectionModel> collections =
        cockpitCollectionService.getCollectionsForUser(deJol);

    assertThat(collections).isNotNull();
    assertThat(collections.size()).isEqualTo(2);

    final CockpitObjectAbstractCollectionModel collection = collections.get(0);
    boolean hasRight = cockpitCollectionService.hasReadCollectionRight(otherUser, collection);
    assertThat(hasRight).isFalse();

    hasRight = cockpitCollectionService.hasReadCollectionRight(abrode, collection);
    assertThat(hasRight).isTrue();

    hasRight = cockpitCollectionService.hasReadCollectionRight(deJol, collection);
    assertThat(hasRight).isTrue();
  }
  @Before
  public void beforeTest() throws Exception {
    B2BIntegrationTest.loadTestData();
    importCsv("/b2bapprovalprocess/test/b2borganizations.csv", "UTF-8");
    importCsv("/b2bapprovalprocess/test/creditlimit.impex", "UTF-8");

    sessionService
        .getCurrentSession()
        .setAttribute(
            "user", this.modelService.<Object>toPersistenceLayer(userService.getAdminUser()));
    i18nService.setCurrentLocale(Locale.ENGLISH);
    commonI18NService.setCurrentLanguage(commonI18NService.getLanguage("en"));
    commonI18NService.setCurrentCurrency(commonI18NService.getCurrency("EUR"));
  }
  @Before
  public void setUp() throws Exception {
    // final Create data for tests
    LOG.info("Creating data for BundleSelectionCriteriaIDPrepareInterceptorIntegrationTest ...");
    userService.setCurrentUser(userService.getAdminUser());
    final long startTime = System.currentTimeMillis();
    new CoreBasicDataCreator().createEssentialData(Collections.EMPTY_MAP, null);
    // importing test csv
    final String legacyModeBackup = Config.getParameter(ImpExConstants.Params.LEGACY_MODE_KEY);
    LOG.info(
        "Existing value for " + ImpExConstants.Params.LEGACY_MODE_KEY + " :" + legacyModeBackup);
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "true");
    importCsv("/commerceservices/test/testCommerceCart.csv", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, legacyModeBackup);

    LOG.info(
        "Finished data for BundleSelectionCriteriaIDPrepareInterceptorIntegrationTest "
            + (System.currentTimeMillis() - startTime)
            + "ms");

    baseSiteService.setCurrentBaseSite(baseSiteService.getBaseSiteForUID(TEST_BASESITE_UID), false);
    catalogVersionService.setSessionCatalogVersion("testCatalog", "Online");
  }
  @Test
  public void testOnEvent() throws Exception {
    // get admin user
    final UserModel user = userService.getAdminUser();

    // create session cart, anonymous user is set on cart
    cartService.getSessionCart();

    // set admin user as current
    userService.setCurrentUser(user);

    // AfterSessionUserChangeEvent processed in background
    // ....

    // get current cart
    final CartModel cart = cartService.getSessionCart();

    // refresh cart to ensure that cart user is persisted
    modelService.refresh(cart);

    assertNotNull("Cart is null.", cart);
    assertNotNull("Cart user is null.", cart.getUser());
    assertEquals("Cart user differs.", user, cart.getUser());
  }
  @Test
  public void shouldTriggerCreditAlert() throws Exception {
    // Step 1 There should not be any template for Alert
    final EmployeeModel employeeModel = userService.getAdminUser();
    WorkflowTemplateModel workflowTemplateModel = null;
    try {
      workflowTemplateModel =
          workflowTemplateService.getWorkflowTemplateForCode("B2B-Alert-GC Acct Mgr");
    } catch (final UnknownIdentifierException uie) {
      // Do nothing
    }

    Assert.assertNull(workflowTemplateModel);

    /**
     * Create and order between 8000 - 10000 EUR for unit GC Sales DE Alert should be created for GC
     * Sales Rep
     */
    final OrderModel order = createOrder("GC Sales DE Boss", 900, OrderStatus.CREATED);
    Assert.assertNotNull(order);

    // Set up credit limit data for test so that it generates an Alert
    final B2BUnitModel unitLoggedIn = b2bUnitService.getUnitForUid("GC Sales DE");
    final B2BCreditLimitModel creditLimitToUse = unitLoggedIn.getCreditLimit();
    creditLimitToUse.setActive(Boolean.TRUE);
    creditLimitToUse.setDateRange(B2BPeriodRange.DAY);
    creditLimitToUse.setDatePeriod(null);
    creditLimitToUse.setAlertSentDate(null);
    modelService.save(creditLimitToUse);

    final B2BApprovalProcessModel b2bApprovalProcessModel =
        getB2BApprovalProcessModelForOrder(order);

    this.waitForProcessToEnd(b2bApprovalProcessModel.getCode(), 20000);
    this.modelService.refresh(order);
    this.modelService.refresh(b2bApprovalProcessModel);

    // verify that creditCheckAlert was sent - template and workflow should exist for an Alert
    workflowTemplateModel =
        workflowTemplateService.getWorkflowTemplateForCode("B2B-Alert-GC Acct Mgr");
    Assert.assertNotNull(workflowTemplateModel);
    final List<WorkflowModel> workflowModelList =
        newestWorkflowService.getWorkflowsForTemplateAndUser(workflowTemplateModel, employeeModel);
    Assert.assertTrue(CollectionUtils.isNotEmpty(workflowModelList));

    Assert.assertEquals(OrderStatus.APPROVED, order.getStatus());
    Assert.assertEquals(ProcessState.SUCCEEDED, b2bApprovalProcessModel.getProcessState());
  }
  @Test
  public void testIsUserAssignedPrincipalForSameGroup() {
    // given
    final WorkflowActionModel mockAction = mock(WorkflowActionModel.class);
    final UserModel mockUser = mock(UserModel.class);
    final UserGroupModel mockGroup = mock(UserGroupModel.class);
    when(mockAction.getPrincipalAssigned()).thenReturn(mockGroup);
    when(userService.getCurrentUser()).thenReturn(mockUser);
    when(mockUser.getAllGroups()).thenReturn((Set) Collections.singleton(mockGroup));

    // when
    final boolean isAssigned = workflowActionService.isUserAssignedPrincipal(mockAction);

    // then
    assertThat(isAssigned).isTrue();
  }
 @Override
 public void updateCustomer(final CustomerData customerData) throws DuplicateUidException {
   validateParameterNotNullStandardMessage("customerData", customerData);
   final EnergizerB2BCustomerModel energizerB2BCustomerModel;
   if (StringUtils.isEmpty(customerData.getUid())) {
     energizerB2BCustomerModel = this.getModelService().create(EnergizerB2BCustomerModel.class);
     energizerB2BCustomerModel.setRegistrationEmailFlag(Boolean.TRUE);
   } else {
     energizerB2BCustomerModel =
         (EnergizerB2BCustomerModel) userService.getUserForUID(customerData.getUid());
   }
   if (null != customerData && null != energizerB2BCustomerModel) {
     energizerCustomerReversePopulator.populate(customerData, energizerB2BCustomerModel);
     companyB2BCommerceService.saveModel(energizerB2BCustomerModel);
   }
 }
 /**
  * This test is specially added for fetching the tree of child Unit in the organization hierarchy.
  * So used a user Id which is not the root unit for example GC.
  */
 @Test
 public void shouldGetAllBranchAndParentUnitOfChildUnit() {
   sessionService.executeInLocalView(
       new SessionExecutionBody() {
         @Override
         public void executeWithoutResult() {
           final String userId = "GC Sales UK Boss";
           login(userId);
           final Set<B2BUnitModel> allUnitsOfOrganization =
               b2bUnitService.getAllUnitsOfOrganization(
                   b2bCustomerService.getCurrentB2BCustomer());
           Assert.assertTrue(allUnitsOfOrganization.size() >= 3);
         }
       },
       userService.getAdminUser());
 }
  @Test
  public void shouldGetParentUnitForCustomerWithMultipleUnitsAssigned() {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final B2BCustomerModel user =
                userService.getUserForUID("GC CEO", B2BCustomerModel.class);
            // assign user to session
            login(user);
            final B2BUnitModel parent = b2bUnitService.getParent(user);
            Assert.assertNotNull(parent);
            // try to add the member which the user is already a member of
            b2bUnitService.addMember(parent, user);
            modelService.save(user);
            Assert.assertEquals(
                1,
                CollectionUtils.select(
                        user.getGroups(), PredicateUtils.instanceofPredicate(B2BUnitModel.class))
                    .size());

            // assign a 2nd unit to GC CEO
            final B2BUnitModel unitUK = b2bUnitService.getUnitForUid("GC Sales UK");
            b2bUnitService.addMember(unitUK, user);
            modelService.save(user);
            Assert.assertEquals(
                2,
                CollectionUtils.select(
                        user.getGroups(), PredicateUtils.instanceofPredicate(B2BUnitModel.class))
                    .size());

            b2bUnitService.updateParentB2BUnit(unitUK, user);
            modelService.save(user);

            Assert.assertEquals(unitUK, b2bUnitService.getParent(user));
            // make sure user is still belongs to 2 units
            Assert.assertEquals(
                2,
                CollectionUtils.select(
                        user.getGroups(), PredicateUtils.instanceofPredicate(B2BUnitModel.class))
                    .size());
          }
        },
        userService.getAdminUser());
  }
  private OrderModel createNewOrder() {
    final OrderModel order = modelService.create(OrderModel.class);

    final UserModel user = userService.getCurrentUser();

    order.setUser(user);

    order.setCurrency(commonI18NService.getBaseCurrency());
    order.setDate(new java.util.Date());
    order.setNet(Boolean.FALSE);

    final OrderEntryModel entry1 = modelService.create(OrderEntryModel.class);
    entry1.setOrder(order);
    entry1.setQuantity(Long.valueOf(1));
    entry1.setUnit(productService.getOrderableUnit(product1));
    entry1.setProduct(product1);
    entry1.setEntryNumber(Integer.valueOf(0));

    final OrderEntryModel entry2 = modelService.create(OrderEntryModel.class);
    entry2.setOrder(order);
    entry2.setQuantity(Long.valueOf(1));
    entry2.setUnit(productService.getOrderableUnit(product2));
    entry2.setProduct(product2);
    entry2.setEntryNumber(Integer.valueOf(1));

    final OrderEntryModel entry3 = modelService.create(OrderEntryModel.class);
    entry3.setOrder(order);
    entry3.setQuantity(Long.valueOf(1));
    entry3.setUnit(productService.getOrderableUnit(product3));
    entry3.setProduct(product3);
    entry3.setEntryNumber(Integer.valueOf(2));

    final OrderEntryModel entry4 = modelService.create(OrderEntryModel.class);
    entry4.setOrder(order);
    entry4.setQuantity(Long.valueOf(1));
    entry4.setUnit(productService.getOrderableUnit(product4));
    entry4.setProduct(product4);
    entry4.setEntryNumber(Integer.valueOf(3));

    order.setEntries((List) Arrays.asList(entry1, entry2, entry3, entry4));

    return order;
  }