/**
   * HW2110-0019(base product): 381.64 Euro, and HW2200-0561(partner product): 86.80 Euro. The
   * ProductOneToOnePerfectPartnerPromotion will be fired if both of them are in the cart and the
   * price is 700 Euro.
   *
   * <ul>
   *   <li>adds the HW2110-0019 in cart, and tests the total price,
   *   <li>updates with the ProductOneToOnePerfectPartnerPromotion, and checks the total price,
   *   <li>now adds the HW2200-0561, and checks the total price,
   *   <li>updates with the ProductOneToOnePerfectPartnerPromotion that should be fired now, and
   *       checks the total price.
   * </ul>
   */
  @Test
  public void testProductOneToOnePerfectPartnerPromotion() throws CalculationException {
    cart = cartService.getSessionCart();
    cartService.addNewEntry(cart, baseProduct, 1, baseProduct.getUnit());
    modelService.save(cart);
    calculationService.calculate(cart);
    assertEquals(
        "before updatePromotions(ProductOneToOnePerfectPartnerPromotion)",
        381.64d,
        cart.getTotalPrice().doubleValue(),
        0.01);

    promotionGroup = promotionsService.getPromotionGroup("prGroup5");
    final Collection<PromotionGroupModel> promotionGroups = new ArrayList<PromotionGroupModel>();
    promotionGroups.add(promotionGroup);
    promotionsService.updatePromotions(
        promotionGroups, cart, false, AutoApplyMode.APPLY_ALL, AutoApplyMode.APPLY_ALL, new Date());
    modelService.refresh(cart);
    assertEquals("without partner product", 381.64d, cart.getTotalPrice().doubleValue(), 0.01);

    cartService.addNewEntry(cart, partnerProduct, 1, partnerProduct.getUnit());
    modelService.saveAll();
    calculationService.calculate(cart);
    assertEquals(
        "with partner product, but without promotion",
        468.44d,
        cart.getTotalPrice().doubleValue(),
        0.01);

    promotionsService.updatePromotions(
        promotionGroups, cart, false, AutoApplyMode.APPLY_ALL, AutoApplyMode.APPLY_ALL, new Date());
    modelService.refresh(cart);
    assertEquals("with partner product now", 400.00d, cart.getTotalPrice().doubleValue(), 0.01);
  }
 @Test
 public void shouldNotCalculateTaxes() {
   final CartModel cart = mock(CartModel.class);
   given(cart.getNet()).willReturn(Boolean.FALSE);
   final boolean calculateTaxes =
       defaultOmsDetermineExternalTaxStrategy.shouldCalculateExternalTaxes(cart);
   Assert.assertEquals(calculateTaxes, false);
 }
 @Test
 public void testAddCommon() {
   final AbstractOrderEntryModel abstractOrderEntryModel = mock(AbstractOrderEntryModel.class);
   given(cartModel.getCode()).willReturn(CART_CODE);
   given(cartModel.getEntries()).willReturn(Collections.singletonList(abstractOrderEntryModel));
   subsOrderPopulator.addCommon(cartModel, cartData);
   Assert.assertEquals(Integer.valueOf(1), cartData.getTotalItems());
 }
 @Test
 public void shouldCreateCardAndAssignUnit() {
   final String userId = "IC CEO";
   final B2BCustomerModel user = login(userId);
   final B2BUnitModel unit = b2bUnitService.getParent(user);
   // Create automatically include B2BUnit
   CartModel cartModel = b2bCartFactory.createCart();
   // Fetch new instance to assert it was indeed saved
   cartModel = (CartModel) modelService.get(cartModel.getPk());
   // Assert cart parent b2bunit is b2bemployee's b2bunit
   Assert.assertEquals(unit, cartModel.getUnit());
 }
  private void applyVouchersAndPromotions(
      final String[] voucherCodes,
      final List<PromotionGroupModel> groups,
      final double expectedTotal)
      throws JaloPriceFactoryException {
    for (final String voucherCode : voucherCodes) {
      voucherService.redeemVoucher(voucherCode, cart);
    }
    modelService.save(cart);

    promotionsService.updatePromotions(
        groups,
        cart,
        false,
        AutoApplyMode.APPLY_ALL,
        AutoApplyMode.APPLY_ALL,
        new java.util.Date());
    modelService.refresh(cart);

    assertEquals(expectedTotal, cart.getTotalPrice().doubleValue(), 0.001);

    for (final String voucherCode : voucherCodes) {
      voucherService.releaseVoucher(voucherCode, cart);
    }
  }
  @Test
  public void testBillingFreqContainer() {
    final CurrencyModel currencyModel = mock(CurrencyModel.class);
    final PriceData priceData = mock(PriceData.class);
    final DeliveryModeModel deliveryMode = mock(DeliveryModeModel.class);
    given(cartModel.getDeliveryMode()).willReturn(deliveryMode);

    given(cartModel.getDeliveryCost()).willReturn(Double.valueOf(3.4));
    given(cartModel.getCurrency()).willReturn(currencyModel);
    given(currencyModel.getIsocode()).willReturn("isoCode");
    given(priceDataFactory.create(PriceDataType.BUY, BigDecimal.valueOf(3.4), currencyModel))
        .willReturn(priceData);

    given(cartModel.getBillingTime()).willReturn(billingTimeModel);
    given(cartModel.getBillingTime().getCode()).willReturn("paynow");

    subsOrderPopulator.addTotals(cartModel, cartData);
    Assert.assertEquals(priceData, cartData.getDeliveryCost());
  }
  /*
   * (non-Javadoc)
   *
   * @see in.com.v2kart.ccavenuepaymentintegration.services.CreateCCAvenuePaymentRequestStrategy#createPaymentRequest (java.lang.String,
   * java.lang.String, java.lang.String, de.hybris.platform.core.model.user.CustomerModel, java.lang.String, java.lang.String,
   * de.hybris.platform.commercefacades.user.data.AddressData, java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  public CCAvenuePaymentRequest createPaymentRequest(
      final String requestUrl,
      final String successUrl,
      final String cancelUrl,
      final CustomerModel customer,
      final String merchantKey,
      final String enforcedPaymentMethod,
      final AddressData addressData,
      final String currency,
      final String language,
      final String phoneNumber) {
    final CartModel cartModel = getCartService().getSessionCart();
    if (cartModel == null) {
      return null;
    }

    final CCAvenuePaymentRequest request = new CCAvenuePaymentRequest();
    request.setRequestUrl(requestUrl);
    request.setCancelUrl(cancelUrl);
    request.setRedirectUrl(successUrl);
    request.setAmount(String.valueOf(cartModel.getTotalPrice()));
    request.setCurrency(currency);
    request.setLanguage(language);
    request.setMerchantId(merchantKey);
    request.setOrderId(cartModel.getCode() + "_" + System.currentTimeMillis());
    request.setPaymentOption(paymentOptionMappings.get(enforcedPaymentMethod));

    if (addressData != null) {
      request.setCustomerBillToData(getCustomerBillToData(addressData));
    } else {
      final AddressModel address = cartModel.getDeliveryAddress();
      request.setCustomerBillToData(getCustomerBillToDataConverter().convert(address));
    }
    request
        .getCustomerBillToData()
        .setBillToEmail(getCustomerEmailResolutionService().getEmailForCustomer(customer));
    request.getCustomerBillToData().setBillToPhoneNumber(phoneNumber);
    final CountryModel countryModel =
        getCommonI18NService().getCountry(PaymentProperties.INDIA_COUNTRY_ISO);
    request.getCustomerBillToData().setBillToCountry(countryModel.getName());
    return request;
  }
  @Test
  public void shouldCalculateTaxes() {
    final AddressModel address = mock(AddressModel.class);

    final DeliveryModeModel deliveryMode = mock(DeliveryModeModel.class);

    final CartModel cart = mock(CartModel.class);
    final BaseStoreModel baseStore = mock(BaseStoreModel.class);
    given(baseStore.getExternalTaxEnabled()).willReturn(Boolean.TRUE);
    given(cart.getStore()).willReturn(baseStore);
    given(cart.getNet()).willReturn(Boolean.TRUE);
    given(cart.getDeliveryAddress()).willReturn(address);
    given(cart.getDeliveryMode()).willReturn(deliveryMode);
    given(defaultOndemandDeliveryAddressStrategy.getDeliveryAddressForOrder(cart))
        .willReturn(address);

    final boolean calculateTaxes =
        defaultOmsDetermineExternalTaxStrategy.shouldCalculateExternalTaxes(cart);
    Assert.assertEquals(calculateTaxes, true);
  }
  @Override
  public void process(final CXML input, final CartModel output) {
    final String cartCode = output.getCode();
    LOG.debug(String.format("Placing an order for cart with code: %s", cartCode));

    try {
      final OrderData orderData = b2bCheckoutFlowFacade.placeOrder();
      LOG.debug(String.format("Order with code %s was placed.", orderData.getCode()));
    } catch (final InvalidCartException e) {
      throw new PunchOutException(PunchOutResponseCode.CONFLICT, "Unable to checkout", e);
    }
  }
  /**
   * 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);
  }
  /**
   * Puts two products in the cart, applies one 10% product promotion, and redeems
   *
   * <ul>
   *   <li>1. one voucher without free shipping or
   *   <li>2. one voucher with free shipping or
   *   <li>3. two vouchers, one with free shipping and the other one without.
   * </ul>
   */
  @Test
  public void testPromotionWithVoucher() throws JaloPriceFactoryException {
    // PRO-64
    promotionGroup = promotionsService.getPromotionGroup("prGroup10");
    final List<PromotionGroupModel> groups = new ArrayList<PromotionGroupModel>();
    groups.add(promotionGroup);

    cartService.addNewEntry(cart, product1, 2, product1.getUnit());
    deliveryModeDhl = deliveryModeService.getDeliveryModeForCode("dhl");
    cart.setDeliveryMode(deliveryModeDhl);
    cart.setDeliveryAddress(user.getDefaultShipmentAddress());

    /**
     * General information:
     *
     * <ul>
     *   <li>product(HW2110-0012) price = 81.08 --> 2x = 162.16, delivery cost 8.0, totally 170.16
     *   <li>applied 10% ProductPercentageDiscountPromotion, 162.16 * 0.9 = 145.94
     * </ul>
     *
     * Three different situations with vouchers:
     *
     * <ul>
     *   <li>1. 5% voucher without free shipping, 145.94 * 0.95 = 138.64, delivery cost 8.0, totally
     *       146.64
     *   <li>2. 20% voucher with free shipping, 145.94 * 0.8 = 116.75, free shipping, totally 116.75
     *   <li>3. both the vouchers above, 145.94 * (1 - 0.05 - 0.20) = 109.45, free shipping, totally
     *       109.45
     * </ul>
     */
    applyVouchersAndPromotions(new String[] {voucherCode}, groups, 146.64);

    applyVouchersAndPromotions(new String[] {freeShippingVoucherCode}, groups, 116.75);

    applyVouchersAndPromotions(new String[] {voucherCode, freeShippingVoucherCode}, groups, 109.45);
  }
  @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());
  }
  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    strategy = new PickUpInStoreCheckoutFlowStrategy();
    strategy.setDefaultStrategy(defaultStrategy);
    strategy.setMultiStepCheckoutFlowStrategy(multiStepCheckoutFlowStrategy);
    strategy.setPickupStrategy(pickupStrategy);

    given(pickupStrategy.getPickupInStoreMode()).willReturn(PickupInStoreMode.BUY_AND_COLLECT);
    given(multiStepCheckoutFlowStrategy.getCheckoutFlow()).willReturn(CheckoutFlowEnum.MULTISTEP);
    given(defaultStrategy.getCheckoutFlow()).willReturn(CheckoutFlowEnum.MULTISTEP);

    given(cartService.getSessionCart()).willReturn(cartModel);
    given(cartModel.getEntries()).willReturn(Collections.singletonList(cartEntry));
  }
 public void testPlaceOrderAction() throws Exception {
   final CartModel sessionCart = cartService.getSessionCart();
   modelService.refresh(sessionCart);
   sessionCart.setCalculated(Boolean.TRUE);
   modelService.save(sessionCart);
   Assert.assertEquals(Boolean.TRUE, sessionCart.getCalculated());
   Assert.assertNotNull("cart not null", sessionCart);
   Assert.assertNotNull("user not null", sessionCart.getUser());
   Assert.assertEquals("DC S No", sessionCart.getUser().getUid());
   Assert.assertNotNull(sessionCart.getPaymentInfo());
   Assert.assertThat(sessionCart.getPaymentInfo(), instanceOf(CreditCardPaymentInfoModel.class));
   final ReplenishmentProcessModel replenishmentProcessModel = createReplenishmentProcess();
   Assert.assertFalse(processParameterHelper.containsParameter(replenishmentProcessModel, "cart"));
   processParameterHelper.setProcessParameter(replenishmentProcessModel, "cart", sessionCart);
   modelService.save(replenishmentProcessModel);
   Assert.assertTrue(processParameterHelper.containsParameter(replenishmentProcessModel, "cart"));
   placeOrderAction.execute(replenishmentProcessModel);
 }
 public void testConfirmationAction() throws Exception {
   Assert.assertNotNull(mockEventService);
   confirmationAction.setEventService(mockEventService);
   final CartModel sessionCart = cartService.getSessionCart();
   modelService.refresh(sessionCart);
   sessionCart.setCalculated(Boolean.TRUE);
   modelService.save(sessionCart);
   Assert.assertEquals(Boolean.TRUE, sessionCart.getCalculated());
   Assert.assertNotNull("cart not null", sessionCart);
   Assert.assertNotNull("user not null", sessionCart.getUser());
   Assert.assertEquals("DC S No", sessionCart.getUser().getUid());
   Assert.assertNotNull(sessionCart.getPaymentInfo());
   final ReplenishmentProcessModel replenishmentProcessModel = createReplenishmentProcess();
   Assert.assertFalse(
       processParameterHelper.containsParameter(replenishmentProcessModel, "order"));
   processParameterHelper.setProcessParameter(
       replenishmentProcessModel,
       "order",
       commerceCheckoutService.placeOrder(cartService.getSessionCart()));
   modelService.save(replenishmentProcessModel);
   Assert.assertTrue(processParameterHelper.containsParameter(replenishmentProcessModel, "order"));
   confirmationAction.executeAction(replenishmentProcessModel);
 }
  @Before
  public void beforeTest() throws Exception {
    MockitoAnnotations.initMocks(this);
    // inject a mock payment provider
    cardPaymentService.setCommandFactoryRegistry(mockupCommandFactoryRegistry);
    paymentService.setCardPaymentService(cardPaymentService);
    commerceCheckoutService.setPaymentService(paymentService);

    createCoreData();
    createDefaultCatalog();

    importCsv("/energizercore/test/testOrganizations.csv", "utf-8");
    importCsv("/energizercore/test/testB2BCommerceCart.csv", "utf-8");

    final CartModel modelByExample = new CartModel();
    modelByExample.setCode("dc_shhCart_b2bas");

    final CartModel cart = flexibleSearchService.getModelByExample(modelByExample);
    Assert.assertNotNull(cart);
    cartService.setSessionCart(cart);
    userService.setCurrentUser(cart.getUser());

    if (flexibleSearchService
        .search(
            "SELECT {"
                + ServicelayerJobModel.PK
                + "} FROM {"
                + ServicelayerJobModel._TYPECODE
                + "} WHERE "
                + "{"
                + ServicelayerJobModel.SPRINGID
                + "}=?springid",
            Collections.singletonMap("springid", "b2bAcceleratorCartToOrderJob"))
        .getResult()
        .isEmpty()) {
      final ServicelayerJobModel servicelayerJobModel =
          modelService.create(ServicelayerJobModel.class);
      servicelayerJobModel.setCode("b2bAcceleratorCartToOrderJob");
      servicelayerJobModel.setSpringId("b2bAcceleratorCartToOrderJob");
      modelService.save(servicelayerJobModel);
    }

    final Date startDate = new Date();
    final Integer day = Integer.valueOf(5);
    final Integer week = Integer.valueOf(2);
    final List<DayOfWeek> days = new ArrayList<DayOfWeek>();
    days.add(DayOfWeek.TUESDAY);
    days.add(DayOfWeek.FRIDAY);
    triggerModel = modelService.create(TriggerModel.class);
    triggerModel.setRelative(Boolean.TRUE);
    triggerModel.setActivationTime(startDate);
    triggerModel.setDay(day);
    triggerModel.setWeekInterval(week);
    triggerModel.setDaysOfWeek(days);

    cartToOrderCronJob = modelService.create(CartToOrderCronJobModel.class);
    cartToOrderCronJob.setCart(cartService.getSessionCart());
    cartToOrderCronJob.setDeliveryAddress(userService.getCurrentUser().getDefaultShipmentAddress());
    cartToOrderCronJob.setPaymentAddress(userService.getCurrentUser().getDefaultPaymentAddress());
    cartToOrderCronJob.setPaymentInfo(cartService.getSessionCart().getPaymentInfo());
    setCronJobToTrigger(cartToOrderCronJob, Collections.singletonList(triggerModel));
    cartToOrderCronJob.setJob(cronJobService.getJob("b2bAcceleratorCartToOrderJob"));
    modelService.save(cartToOrderCronJob);
    final BaseSiteModel site = baseSiteService.getBaseSiteForUID("b2bstoretemplate");
    Assert.assertNotNull("no site found for id 'site'", site);
    baseSiteService.setCurrentBaseSite(site, false);
  }
Esempio n. 17
0
 @Override
 public void executeAction(final ReplenishmentProcessModel process) throws Exception {
   final CartToOrderCronJobModel cartToOrderCronJob = process.getCartToOrderCronJob();
   final CartModel cronJobCart = cartToOrderCronJob.getCart();
   getUserService().setCurrentUser(cronJobCart.getUser());
   final CartModel clone =
       getCartService()
           .clone(
               getTypeService().getComposedTypeForClass(CartModel.class),
               getTypeService().getComposedTypeForClass(CartEntryModel.class),
               cronJobCart,
               getGuidKeyGenerator().generate().toString());
   clone.setPaymentAddress(cartToOrderCronJob.getPaymentAddress());
   clone.setDeliveryAddress(cartToOrderCronJob.getDeliveryAddress());
   clone.setPaymentInfo(cartToOrderCronJob.getPaymentInfo());
   clone.setStatus(OrderStatus.CREATED);
   clone.setAllPromotionResults(Collections.EMPTY_SET);
   clone.setPaymentTransactions(Collections.EMPTY_LIST);
   clone.setPermissionResults(Collections.EMPTY_LIST);
   clone.setGuid(getGuidKeyGenerator().generate().toString());
   this.modelService.save(clone);
   processParameterHelper.setProcessParameter(process, "cart", clone);
 }
  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();
  }