@Before
 public void setUp() throws Exception {
   createCoreData();
   createDefaultUsers();
   createDefaultCatalog();
   product1 = productService.getProductForCode("testProduct1");
   product2 = productService.getProductForCode("testProduct2");
   product3 = productService.getProductForCode("testProduct3");
   product4 = productService.getProductForCode("testProduct4");
 }
  @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);
  }
  @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);
  }
  @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);
  }
 private void setupProducts() {
   final CatalogVersionModel catalogVersionModel =
       catalogVersionService.getCatalogVersion("testCatalog", "Online");
   subscriptionProduct =
       (SubscriptionProductModel)
           productService.getProductForCode(catalogVersionModel, SUBSCRIPTION_PRODUCT_CODE);
 }
  @Test
  public void shouldStartApprovalProcessAndIgnoreInactiveCreditLimit() throws Exception {
    final String userId = "GC S HH";
    login(userId);

    // Set up credit limit data for test
    final B2BUnitModel unitLoggedIn = b2bUnitService.getUnitForUid("GC Sales Hamburg");
    final B2BCreditLimitModel creditLimitToUse =
        b2bUnitService.getParent(unitLoggedIn).getCreditLimit();
    creditLimitToUse.setActive(Boolean.TRUE);
    creditLimitToUse.setDateRange(B2BPeriodRange.DAY);
    creditLimitToUse.setDatePeriod(null);
    modelService.save(creditLimitToUse);

    // Credit Limit is active, so unit is returned
    final B2BUnitModel unitWithCreditLimit = b2bUnitService.getUnitWithCreditLimit(unitLoggedIn);
    Assert.assertNotNull(unitWithCreditLimit);

    // Update credit limit with past start/end dates as date range
    final B2BCreditLimitModel creditLimit = unitWithCreditLimit.getCreditLimit();
    creditLimit.setActive(Boolean.FALSE);

    modelService.save(creditLimit);

    // Create order which crosses credit limit
    final OrderModel order =
        createOrder(
            this.login("GC S HH"),
            140,
            OrderStatus.CREATED,
            productService.getProductForCode("testProduct0"));
    Assert.assertNotNull(order);

    final B2BApprovalProcessModel b2bApprovalProcessModel =
        getB2BApprovalProcessModelForOrder(order);

    // Process does not stop at waitProcessCreditLimit, so it should continue after waitProcess
    if (this.waitForProcessAction(b2bApprovalProcessModel.getCode(), "waitProcess", 20000)) {
      modelService.refresh(order);
      final Collection<WorkflowActionModel> actions =
          b2bWorkflowIntegrationService.getStartWorkflowActions(order.getWorkflow());
      Assert.assertEquals(1, actions.size());
      b2bWorkflowIntegrationService.approveWorkflowAction(actions.iterator().next());
    }

    // Credit limit is inactive, so unit is null
    final B2BUnitModel unitWithCreditLimitNull =
        b2bUnitService.getUnitWithCreditLimit(order.getUnit());
    Assert.assertNull(unitWithCreditLimitNull);

    // Process finishes and order placed above is approved - Order total is more than credit limit
    // amount, but
    // credit limit is inactive, so its ignored
    this.waitForProcessToEnd(b2bApprovalProcessModel.getCode(), 20000);
    this.modelService.refresh(order);
    this.modelService.refresh(b2bApprovalProcessModel);
    Assert.assertEquals(OrderStatus.APPROVED, order.getStatus());
    Assert.assertEquals(ProcessState.SUCCEEDED, b2bApprovalProcessModel.getProcessState());
  }
 private OrderEntryModel createTestOrderEntry(final OrderModel order) {
   final OrderEntryModel entry1 = modelService.create(OrderEntryModel.class);
   entry1.setOrder(order);
   entry1.setQuantity(Long.valueOf(1));
   entry1.setUnit(productService.getOrderableUnit(product1));
   entry1.setProduct(product1);
   return entry1;
 }
  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;
  }
  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 {
    // 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 shouldStartApprovalProcessAndAssertApprovalFromMerchant() throws Exception {
    login("GC S HH");

    // Set up credit limit data for test
    final B2BUnitModel unitLoggedIn = b2bUnitService.getUnitForUid("GC Sales Hamburg");
    final B2BCreditLimitModel creditLimitToUse =
        b2bUnitService.getParent(unitLoggedIn).getCreditLimit();
    creditLimitToUse.setActive(Boolean.TRUE);
    creditLimitToUse.setDateRange(B2BPeriodRange.DAY);
    creditLimitToUse.setDatePeriod(null);
    modelService.save(creditLimitToUse);

    final OrderModel order =
        createOrder(
            this.login("GC S HH"),
            140,
            OrderStatus.CREATED,
            productService.getProductForCode("testProduct0"));
    Assert.assertNotNull(order);

    final B2BApprovalProcessModel b2bApprovalProcessModel =
        getB2BApprovalProcessModelForOrder(order);

    final B2BUnitModel unitWithCreditLimit = b2bUnitService.getUnitWithCreditLimit(order.getUnit());

    Assert.assertEquals("GC Sales DE", unitWithCreditLimit.getUid());

    if (this.waitForProcessAction(b2bApprovalProcessModel.getCode(), "waitProcess", 20000)) {
      modelService.refresh(order);
      final Collection<WorkflowActionModel> actions =
          b2bWorkflowIntegrationService.getStartWorkflowActions(order.getWorkflow());
      Assert.assertEquals(1, actions.size());
      b2bWorkflowIntegrationService.decideAction(
          actions.iterator().next(), B2BWorkflowIntegrationService.DECISIONCODES.APPROVE.name());
    }

    if (this.waitForProcessAction(
        b2bApprovalProcessModel.getCode(), "waitProcessCreditLimit", 20000)) {
      modelService.refresh(order);
      final Collection<WorkflowActionModel> actions =
          b2bWorkflowIntegrationService.getStartWorkflowActions(order.getWorkflow());
      Assert.assertEquals(1, actions.size());
      this.approveWorkflowAction(actions.iterator().next());
    }

    this.waitForProcessToEnd(b2bApprovalProcessModel.getCode(), 20000);
    this.modelService.refresh(order);
    this.modelService.refresh(b2bApprovalProcessModel);
    Assert.assertEquals(OrderStatus.APPROVED, order.getStatus());
    Assert.assertEquals(ProcessState.SUCCEEDED, b2bApprovalProcessModel.getProcessState());
  }
  @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));
  }
  /**
   * Tests promotion with voucher that has product restriction. (currency is Euro)
   *
   * <ul>
   *   <li>product(HW1230-0001) price = 769.00 --> 2x = 1538.00
   *   <li>product(HW2110-0012) price = 81.08 --> 2x = 162.16
   *   <li>so the cart contains products that cost 1700.16 Euro without promotion/voucher.
   *   <li>redeems the voucher that is 10% discount with product restriction: only valid for
   *       [HW1230-0001]
   *   <li>applies the fixed price promotion that is only valid for [HW1230-0001], and the fixed
   *       price is 500
   *   <li>update promotions, and the total discount should be (500 * 2) * 10% = 100
   *   <li>total price of the cart: (500 * 2 + 81.08 * 2) - 100 = 1062.16
   * </ul>
   */
  @Test
  public void testPromotionWithProductRestrictionVoucher()
      throws CalculationException, JaloPriceFactoryException {
    // PRO-70
    promotionGroup = promotionsService.getPromotionGroup("prGroup20");
    final ProductModel productSony = productService.getProductForCode(catVersion, "HW1230-0001");

    cartService.addNewEntry(cart, productSony, 2, productSony.getUnit());
    cartService.addNewEntry(cart, product1, 2, product1.getUnit());
    modelService.save(cart);
    calculationService.calculate(cart);
    modelService.refresh(cart);
    assertEquals(
        "should be 1700.16 euro without promotion/voucher",
        1700.16,
        cart.getTotalPrice().doubleValue(),
        0.01);

    voucherService.redeemVoucher(restrictionProductVoucher, cart);
    modelService.save(cart);

    final List<PromotionGroupModel> groups = new ArrayList<PromotionGroupModel>();
    groups.add(promotionGroup);
    promotionsService.updatePromotions(
        groups,
        cart,
        false,
        AutoApplyMode.APPLY_ALL,
        AutoApplyMode.APPLY_ALL,
        new java.util.Date());
    modelService.refresh(cart);
    assertEquals(
        "should be 100 euro for fixed price discount",
        100.0,
        cart.getTotalDiscounts().doubleValue(),
        0.01);
    assertEquals(
        "should be 1062.16 euro for total", 1062.16, cart.getTotalPrice().doubleValue(), 0.01);
  }
 protected ProductModel processFile(
     final Long productId, final String filePrefix, final FileContent content)
     throws Exception // NOPMD
     {
   File file = null;
   BatchHeader header = null;
   try {
     file = File.createTempFile(filePrefix, ".csv");
     header = createHeader(file);
     createFile(file, productId, content);
     batchTransformerTask.execute(header);
     batchRunnerTask.execute(header);
     return productService.getProductForCode(productId.toString());
   } finally {
     if (file != null) {
       file.delete();
     }
     if (header != null) {
       header.setFile(null);
       batchCleanupTask.execute(header);
     }
   }
 }
 @Test
 public void testVariant() throws Exception {
   processFile(
       productId,
       "base_product-",
       new ProductContent() {
         @Override
         public void writeContent(final PrintWriter writer) throws IOException {
           writer.print("ApparelSizeVariantProduct");
           super.writeContent(writer);
         }
       });
   final Long variantId = Long.valueOf(Math.abs((long) random.nextInt()));
   final ProductModel product =
       processFile(
           productId,
           "variant-",
           new FileContent() {
             @Override
             public void writeContent(final PrintWriter writer) throws IOException {
               writer.print(variantId);
               writer.print(SEPARATOR);
               writer.print(SEPARATOR);
               writer.print("black");
               writer.print(SEPARATOR);
               writer.print("L");
             }
           });
   final ApparelSizeVariantProductModel variant =
       (ApparelSizeVariantProductModel) productService.getProductForCode(variantId.toString());
   Assert.assertEquals("ApparelSizeVariantProduct", product.getVariantType().getCode());
   Assert.assertEquals(product, variant.getBaseProduct());
   Assert.assertEquals("black", variant.getStyle(Locale.ENGLISH));
   Assert.assertNull(variant.getStyle(Locale.GERMAN));
   Assert.assertEquals("L", variant.getSize(Locale.ENGLISH));
   Assert.assertNull(variant.getSize(Locale.GERMAN));
 }
  protected OrderModel placeTestOrder(final boolean valid)
      throws InvalidCartException, CalculationException {
    final CartModel cart = cartService.getSessionCart();
    final UserModel user = userService.getCurrentUser();
    cartService.addNewEntry(cart, productService.getProductForCode("testProduct1"), 1, null);
    cartService.addNewEntry(cart, productService.getProductForCode("testProduct2"), 2, null);
    cartService.addNewEntry(cart, productService.getProductForCode("testProduct3"), 3, null);

    final AddressModel deliveryAddress = new AddressModel();
    deliveryAddress.setOwner(user);
    deliveryAddress.setFirstname("Der");
    deliveryAddress.setLastname("Buck");
    deliveryAddress.setTown("Muenchen");
    deliveryAddress.setCountry(commonI18NService.getCountry("DE"));
    modelService.save(deliveryAddress);

    final DebitPaymentInfoModel paymentInfo = new DebitPaymentInfoModel();
    paymentInfo.setOwner(cart);
    paymentInfo.setBank("MeineBank");
    paymentInfo.setUser(user);
    paymentInfo.setAccountNumber("34434");
    paymentInfo.setBankIDNumber("1111112");
    paymentInfo.setBaOwner("Ich");
    paymentInfo.setCode("testPaymentInfo1");
    modelService.save(paymentInfo);

    cart.setDeliveryMode(deliveryService.getDeliveryModeForCode("free"));
    cart.setDeliveryAddress(deliveryAddress);
    cart.setPaymentInfo(paymentInfo);

    final CardInfo card = new CardInfo();
    card.setCardType(CreditCardType.VISA);
    card.setCardNumber("4111111111111111");
    card.setExpirationMonth(Integer.valueOf(12));
    if (valid) {
      card.setExpirationYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR) + 2));
    } else {
      card.setExpirationYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR) - 2));
    }

    final PaymentTransactionModel paymentTransaction =
        paymentService
            .authorize(
                "code4" + codeNo++,
                BigDecimal.ONE,
                Currency.getInstance("EUR"),
                deliveryAddress,
                deliveryAddress,
                card)
            .getPaymentTransaction();

    cart.setPaymentTransactions(Collections.singletonList(paymentTransaction));
    modelService.save(cart);
    calculationService.calculate(cart);

    final CommerceCheckoutParameter parameter = new CommerceCheckoutParameter();
    parameter.setEnableHooks(true);
    parameter.setCart(cart);
    parameter.setSalesApplication(SalesApplication.WEB);

    return commerceCheckoutService.placeOrder(parameter).getOrder();
  }