@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());
  }
  @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");
  }
  @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"));
  }
  @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());
  }
 /**
  * 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());
  }
  @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();
  }
  @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();
  }
  @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 shouldDisableBranchofParentUnit() {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final String userId = "GC CEO";
            login(userId);

            final B2BUnitModel unitUK = b2bUnitService.getUnitForUid("GC Sales UK");

            b2bUnitService.disableBranch(unitUK);

            LOG.debug("Test all units are disabled for : " + unitUK.getUid());

            final Set<B2BUnitModel> allUnitsOfOrganization = b2bUnitService.getBranch(unitUK);

            for (final B2BUnitModel unit : allUnitsOfOrganization) {
              Assert.assertFalse(unit.getActive().booleanValue());
            }
          }
        },
        userService.getAdminUser());
  }
  @Test
  public void testGetApprovalProcessCode() throws Exception {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final String userId = "IC CEO";
            String approvalCode = null;
            login(userId);

            // test findApprovalProcessCodeForUnit
            final B2BUnitModel unit = b2bUnitService.getUnitForUid("IC");
            Assert.assertNotNull(unit);
            // test
            approvalCode = b2bUnitService.getApprovalProcessCodeForUnit(unit);
            Assert.assertNull(approvalCode);

            unit.setApprovalProcessCode("simpleapproval");
            modelService.save(unit);

            approvalCode = b2bUnitService.getApprovalProcessCodeForUnit(unit);
            Assert.assertNotNull(approvalCode);
            // test findApprovalProcessCodeForUnit - get value from parent
            final B2BUnitModel unitSales = b2bUnitService.getUnitForUid("IC Sales");
            Assert.assertNotNull(unitSales);
            approvalCode = b2bUnitService.getApprovalProcessCodeForUnit(unitSales);
            Assert.assertNotNull(approvalCode);

            unit.setApprovalProcessCode(null);
            modelService.save(unit);
            approvalCode = b2bUnitService.getApprovalProcessCodeForUnit(unitSales);
            Assert.assertNull(approvalCode);
          }
        },
        userService.getAdminUser());
  }
  @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 testRestrictionsOfUsersAndUnits() throws Exception {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final String userId = "IC CEO";
            login(userId);

            // test restrictions on units and employees
            Assert.assertNull(b2bUnitService.getUnitForUid("GC"));
            Assert.assertNull(
                baseDao.findFirstByAttribute(B2BCustomer.UID, "GC CEO", B2BCustomerModel.class));

            // test costcenter and budget restriction
            Assert.assertNotNull(
                baseDao.findFirstByAttribute(
                    B2BCostCenterModel.CODE, "IC 0", B2BCostCenterModel.class));
            Assert.assertNull(
                baseDao.findFirstByAttribute(
                    B2BCostCenterModel.CODE, "GC 0", B2BCostCenterModel.class));
            Assert.assertNotNull(
                baseDao.findFirstByAttribute(
                    B2BBudgetModel.CODE, "IC BUDGET EUR 1M", B2BBudgetModel.class));
            Assert.assertNull(
                baseDao.findFirstByAttribute(
                    B2BBudgetModel.CODE, "GC BUDGET EUR 1M", B2BBudgetModel.class));

            // change the session IC_USER to the customer who belongs to different organization
            final UserModel GC_USER =
                (UserModel)
                    sessionService.executeInLocalView(
                        new SessionExecutionBody() {
                          @Override
                          public Object execute() {
                            searchRestrictionService.disableSearchRestrictions();
                            final UserModel user =
                                baseDao.findFirstByAttribute(
                                    B2BCustomerModel.UID, "GC CEO", B2BCustomerModel.class);
                            Assert.assertNotNull(user);
                            return user;
                          }
                        });
            Assert.assertNotNull(GC_USER);
            login(GC_USER);
            // should now we able to see only items linked to C_2.. units
            Assert.assertNull(
                baseDao.findFirstByAttribute(
                    B2BCostCenterModel.CODE, "IC 0", B2BCostCenterModel.class));
            Assert.assertNotNull(
                baseDao.findFirstByAttribute(
                    B2BCostCenterModel.CODE, "GC 0", B2BCostCenterModel.class));
            Assert.assertNull(
                baseDao.findFirstByAttribute(
                    B2BBudgetModel.CODE, "IC BUDGET EUR 1M", B2BBudgetModel.class));
            Assert.assertNotNull(
                baseDao.findFirstByAttribute(
                    B2BBudgetModel.CODE, "GC BUDGET EUR 1M", B2BBudgetModel.class));
          }
        },
        userService.getAdminUser());
  }