diff --git a/README.md b/README.md index e0ec815d..f2e22fc3 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ About Worldpay: Worldpay (formerly RBS WorldPay) is a payment processing company The extension is crafted for SAP Commerce Cloud as well previous versions of what was formerly called Hybris. ## Release Information -This release is tailored for SAP Commerce Cloud 2005. It is advised to use the latest release available in Github to get the benefits of newest development made to this extension. +This release is tailored for SAP Commerce Cloud 2105. It is advised to use the latest release available in Github to get the benefits of newest development made to this extension. # Installation and Usage @@ -38,14 +38,36 @@ In order to install the AddOn using one of the recipes, run the following comman HYBRIS_HOME/installer$ ./install.sh -r [RECIPE_NAME] perform ## RELEASE NOTES -- A read/write socket connection timeout was configured in the library +##Features: +- SEPA Direct Debit has been integrated as an APM +- Prime routing +- Level2/3 Data +- Request and response payloads are now saved into the Order +- Fraud Sight Integration +- Unprocessed order tickets are now linked to their order + +##Breaking changes: +- Several POJO objects are now created as beans defined in a beans.xml file. +- transformToInternalModel has been removed. New Converters/Populators per each one of the types that we have has been created and are used instead +- Java Classes from the Worldpay's DTD are now generated with JAXB's xjc +- The merchant configuration has been migrated to the data model: + 1. Every merchant.xml file has been deleted from the repository and sensitive data like passwords, macSecret are not visible anymore. + 2. New Types have been added into the DB definition: WorldpayMerchantConfiguration, WorldpayApplePayConfiguration, WorldpayGooglePayConfiguration, WorldpayThreeDS2JsonWebTokenConfiguration. + 3. New enumerations have been added into the DB definition: EnvironmentType, ApplePaySupportedNetworks, ApplePayMerchantCapabilities, GooglePayCardNetworks, GooglePayCardAuthMethods, ChallengePreference + 4. The Merchant Configuration can be found in the backoffice following the path: Worldpay → Merchant Configuration + 5. The Merchant Configuration is related to the Site. Every site will have now a new tab called Worldpay. Inside this type there is the section MERCHANT CONFIGURATION DETAILS in which you can find the new 3 attributes: + - Web Merchant Configuration + - ASM Merchant Configuration + - Replenishment Merchant Configuration +- All of them are of the same type WorldpayMerchantConfiguration. This new configuration represents the old xml configuration of the merchant.xml file. + +##Bugs Fixed: +- Fixed an issue related with date generation that was causing unprocessed order tickets not being created. +- Fixed an issue that was causing customers being redirected to an incorrect HOP URL when using express checkout. +- Fixed a NPE thrown on the summary step of the checkout when a paymentInfo has no bin number set. +- Fixed an issue with Ideal that was making the successURL not being encrypted. +- The profiletagaddon has been added to the project to fix a JSP file not found exception. +- Fixed an issue related to the tax configuration that was causing an error in the Electronics site when paying with a saved card. +- Fixed an issue related to the client side encryption that was causing an error when accessing to the payment details page. +- Fixed an issue with Klarna where an invalid shopper locale was being set. -- ypay-lib was updated to the latest DTD version - -- When upgrading to version 2011 redundant address converters were removed after ootb hybris populated the email - -- A bug was raised to fix hybris ootb causing an order process failure. Unnecessary user rights were removed and warehouse users were imported just for OMS. User rights were also moved to the common impex - -- Added obfuscated cart number, card expiry month and year in the order confirmation page and payment info for googlepay with spartacus - -- Fixed a bug related to saved cards for the b2b accelerator. The issue was caused by order placed with replenishment and card tokenized and saved in the step. The billing address was not saved in this case and it was causing the error when reusing the saved card. diff --git a/YPAY-1823670290-300921-0935.pdf b/YPAY-1823670290-300921-0935.pdf new file mode 100644 index 00000000..45fc9ccd Binary files /dev/null and b/YPAY-1823670290-300921-0935.pdf differ diff --git a/YPAY-902561797-180121-1453.pdf b/YPAY-902561797-180121-1453.pdf deleted file mode 100644 index c696a8f9..00000000 Binary files a/YPAY-902561797-180121-1453.pdf and /dev/null differ diff --git a/YPAY-SAPCommerce2011ConnectorR1.0-B2BTechnicalImplementationGuide-180121-1454.pdf b/YPAY-SAPCommerce2105ConnectorR1.0-B2BTechnicalImplementationGuide-300921-0935.pdf similarity index 89% rename from YPAY-SAPCommerce2011ConnectorR1.0-B2BTechnicalImplementationGuide-180121-1454.pdf rename to YPAY-SAPCommerce2105ConnectorR1.0-B2BTechnicalImplementationGuide-300921-0935.pdf index 2937c073..729441f8 100644 Binary files a/YPAY-SAPCommerce2011ConnectorR1.0-B2BTechnicalImplementationGuide-180121-1454.pdf and b/YPAY-SAPCommerce2105ConnectorR1.0-B2BTechnicalImplementationGuide-300921-0935.pdf differ diff --git a/YPAY-SAPCommerce2011ConnectorR1.0-ImplementationGuide-180121-1454.pdf b/YPAY-SAPCommerce2105ConnectorR1.0-ImplementationGuide-300921-0935.pdf similarity index 54% rename from YPAY-SAPCommerce2011ConnectorR1.0-ImplementationGuide-180121-1454.pdf rename to YPAY-SAPCommerce2105ConnectorR1.0-ImplementationGuide-300921-0935.pdf index aff6a54c..e2e67f26 100644 Binary files a/YPAY-SAPCommerce2011ConnectorR1.0-ImplementationGuide-180121-1454.pdf and b/YPAY-SAPCommerce2105ConnectorR1.0-ImplementationGuide-300921-0935.pdf differ diff --git a/YPAY-SAPCommerce2011ConnectorR1.0-OCCTechnicalImplementationGuide-180121-1454.pdf b/YPAY-SAPCommerce2105ConnectorR1.0-OCCTechnicalImplementationGuide-300921-0935.pdf similarity index 84% rename from YPAY-SAPCommerce2011ConnectorR1.0-OCCTechnicalImplementationGuide-180121-1454.pdf rename to YPAY-SAPCommerce2105ConnectorR1.0-OCCTechnicalImplementationGuide-300921-0935.pdf index dc4a0c5c..f0f7b4c1 100644 Binary files a/YPAY-SAPCommerce2011ConnectorR1.0-OCCTechnicalImplementationGuide-180121-1454.pdf and b/YPAY-SAPCommerce2105ConnectorR1.0-OCCTechnicalImplementationGuide-300921-0935.pdf differ diff --git a/YPAY-SAPCommerce2011ConnectorR1.0-TechnicalImplementationGuide-180121-1454.pdf b/YPAY-SAPCommerce2105ConnectorR1.0-TechnicalImplementationGuide-300921-0947.pdf similarity index 94% rename from YPAY-SAPCommerce2011ConnectorR1.0-TechnicalImplementationGuide-180121-1454.pdf rename to YPAY-SAPCommerce2105ConnectorR1.0-TechnicalImplementationGuide-300921-0947.pdf index 532dc7dc..905137fe 100644 Binary files a/YPAY-SAPCommerce2011ConnectorR1.0-TechnicalImplementationGuide-180121-1454.pdf and b/YPAY-SAPCommerce2105ConnectorR1.0-TechnicalImplementationGuide-300921-0947.pdf differ diff --git a/YPAY-SAPCommerceCloud2011ConnectorR1.0-Documentation-180121-1454.pdf b/YPAY-SAPCommerceCloud2011ConnectorR1.0-Documentation-180121-1454.pdf deleted file mode 100644 index 40f98bc5..00000000 Binary files a/YPAY-SAPCommerceCloud2011ConnectorR1.0-Documentation-180121-1454.pdf and /dev/null differ diff --git a/YPAY-SAPCommerceCloud2105ConnectorR1.0-Documentation-300921-0935.pdf b/YPAY-SAPCommerceCloud2105ConnectorR1.0-Documentation-300921-0935.pdf new file mode 100644 index 00000000..32e243a5 Binary files /dev/null and b/YPAY-SAPCommerceCloud2105ConnectorR1.0-Documentation-300921-0935.pdf differ diff --git a/YPAY-SettingupApplePayMerchantCertificates2011R1.0-180121-1454.pdf b/YPAY-SettingupApplePayMerchantCertificates2011R1.0-180121-1454.pdf deleted file mode 100644 index 878ec4a4..00000000 Binary files a/YPAY-SettingupApplePayMerchantCertificates2011R1.0-180121-1454.pdf and /dev/null differ diff --git a/YPAY-SettingupApplePayMerchantCertificates2105R1.0-300921-0935.pdf b/YPAY-SettingupApplePayMerchantCertificates2105R1.0-300921-0935.pdf new file mode 100644 index 00000000..c7273156 Binary files /dev/null and b/YPAY-SettingupApplePayMerchantCertificates2105R1.0-300921-0935.pdf differ diff --git a/YPAY-TestingApplePay2011R1.0-180121-1454.pdf b/YPAY-TestingApplePay2011R1.0-180121-1454.pdf deleted file mode 100644 index 17f5c424..00000000 Binary files a/YPAY-TestingApplePay2011R1.0-180121-1454.pdf and /dev/null differ diff --git a/YPAY-TestingApplePay2105R1.0-300921-0935.pdf b/YPAY-TestingApplePay2105R1.0-300921-0935.pdf new file mode 100644 index 00000000..2faee04e Binary files /dev/null and b/YPAY-TestingApplePay2105R1.0-300921-0935.pdf differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/GooglePayController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/GooglePayController.java index 87334192..847eb07f 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/GooglePayController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/GooglePayController.java @@ -16,7 +16,8 @@ import de.hybris.platform.commerceservices.strategies.CheckoutCustomerStrategy; import de.hybris.platform.order.InvalidCartException; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -30,7 +31,7 @@ @RequestMapping(value = "/checkout/multi/worldpay/googlepay") public class GooglePayController extends AbstractCheckoutController { - private static final Logger LOG = Logger.getLogger(GooglePayController.class); + private static final Logger LOG = LoggerFactory.getLogger(GooglePayController.class); @Resource private WorldpayDirectOrderFacade worldpayDirectOrderFacade; @@ -81,7 +82,7 @@ protected void setRegion(final AddressData addressData, final GooglePayAddressDa if (region != null) { addressData.setRegion(region); } else { - LOG.debug(MessageFormat.format("Failed to determine region from country {0} and region code {1}", countryIsoCode, administrativeArea)); + LOG.debug("Failed to determine region from country {} and region code {}", countryIsoCode, administrativeArea); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/WorldpayPaymentAPIController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/WorldpayPaymentAPIController.java index dc733b35..3dc24373 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/WorldpayPaymentAPIController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/WorldpayPaymentAPIController.java @@ -23,7 +23,8 @@ import de.hybris.platform.commerceservices.customer.DuplicateUidException; import de.hybris.platform.order.InvalidCartException; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; @@ -42,7 +43,7 @@ @RequestMapping(value = "/checkout/worldpay/payment/api") public class WorldpayPaymentAPIController extends WorldpayChoosePaymentMethodCheckoutStepController { - private static final Logger LOGGER = Logger.getLogger(WorldpayPaymentAPIController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(WorldpayPaymentAPIController.class); @Resource protected Validator cseFormValidator; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepController.java index 62d2b145..a97fc03b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepController.java @@ -30,6 +30,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; +import java.text.SimpleDateFormat; +import java.util.Date; /** * Web controller to handle a CSE checkout step @@ -38,7 +40,8 @@ @RequestMapping(value = "/checkout/multi/worldpay/cse") public class WorldpayCseCheckoutStepController extends AbstractWorldpayDirectCheckoutStepController { - protected static final Logger LOGGER = LogManager.getLogger(WorldpayCseCheckoutStepController.class); + private static final Logger LOGGER = LogManager.getLogger(WorldpayCseCheckoutStepController.class); + protected static final String CSE_PUBLIC_KEY = "csePublicKey"; protected static final String CSE_PAYMENT_FORM = "csePaymentForm"; protected static final String REDIRECT_TO_CSE_PAGE = "redirect:/checkout/multi/worldpay/cse/cse-data"; @@ -131,7 +134,7 @@ public String addCseData(final HttpServletRequest request, final Model model, @V } final CSEAdditionalAuthInfo cseAdditionalAuthInfo = createCSEAdditionalAuthInfo(csePaymentForm); - final WorldpayAdditionalInfoData worldpayAdditionalInfoData = createWorldpayAdditionalInfo(request, csePaymentForm.getCvc(), cseAdditionalAuthInfo); + final WorldpayAdditionalInfoData worldpayAdditionalInfoData = createWorldpayAdditionalInfo(request, csePaymentForm, cseAdditionalAuthInfo); return authoriseAndHandleResponse(model, cseAdditionalAuthInfo, worldpayAdditionalInfoData, response); } @@ -173,9 +176,11 @@ public String getChallengeIframeContent(final Model model) { return worldpayAddonEndpointService.getChallengeIframe3dSecureFlex(); } - protected WorldpayAdditionalInfoData createWorldpayAdditionalInfo(final HttpServletRequest request, final String cvc, final CSEAdditionalAuthInfo cseAdditionalAuthInfo) { + protected WorldpayAdditionalInfoData createWorldpayAdditionalInfo(final HttpServletRequest request, final CSEPaymentForm csePaymentForm, final CSEAdditionalAuthInfo cseAdditionalAuthInfo) { final WorldpayAdditionalInfoData worldpayAdditionalInfo = worldpayAdditionalInfoFacade.createWorldpayAdditionalInfoData(request); - worldpayAdditionalInfo.setSecurityCode(cvc); + worldpayAdditionalInfo.setDateOfBirth(csePaymentForm.getDateOfBirth()); + worldpayAdditionalInfo.setSecurityCode(csePaymentForm.getCvc()); + worldpayAdditionalInfo.setDeviceSession(csePaymentForm.getDeviceSession()); if (cseAdditionalAuthInfo.getAdditional3DS2() != null) { worldpayAdditionalInfo.setAdditional3DS2(cseAdditionalAuthInfo.getAdditional3DS2()); } @@ -188,7 +193,11 @@ protected WorldpayAdditionalInfoData createWorldpayAdditionalInfo(final HttpServ @Override protected void setupAddPaymentPage(final Model model) throws CMSItemNotFoundException { super.setupAddPaymentPage(model); + model.addAttribute(CSE_PAYMENT_FORM, new CSEPaymentForm()); + model.addAttribute(IS_FS_ENABLED, worldpayPaymentCheckoutFacade.isFSEnabled()); + final SimpleDateFormat dateFormat = new SimpleDateFormat(BIRTH_DAY_DATE_FORMAT); + model.addAttribute(CURRENT_DATE, dateFormat.format(new Date())); model.addAttribute(CSE_PUBLIC_KEY, worldpayMerchantConfigDataFacade.getCurrentSiteMerchantConfigData().getCsePublicKey()); model.addAttribute(THREEDSFLEX_EVENT_ORIGIN_DOMAIN, worldpayDDCFacade.getEventOriginDomainForDDC()); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayHopResponseController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayHopResponseController.java index fbd703b6..4f462095 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayHopResponseController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayHopResponseController.java @@ -17,11 +17,12 @@ import de.hybris.platform.order.InvalidCartException; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.servicelayer.dto.converter.Converter; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @@ -31,7 +32,6 @@ import java.util.Set; import static com.worldpay.enums.order.AuthorisedStatus.*; -import static java.text.MessageFormat.format; /** * Web controller to handle HOP responses @@ -40,7 +40,7 @@ @RequestMapping(value = "/checkout/multi/worldpay") public class WorldpayHopResponseController extends WorldpayChoosePaymentMethodCheckoutStepController { - private static final Logger LOG = Logger.getLogger(WorldpayHopResponseController.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayHopResponseController.class); private static final String REDIRECT_URL_ADD_DELIVERY_ADDRESS = REDIRECT_PREFIX + "/checkout/multi/delivery-address/add"; private static final String REDIRECT_URL_CHOOSE_DELIVERY_METHOD = REDIRECT_PREFIX + "/checkout/multi/delivery-method/choose"; @@ -76,7 +76,7 @@ public class WorldpayHopResponseController extends WorldpayChoosePaymentMethodCh * @return */ @RequireHardLogIn - @RequestMapping(value = "/hop-response", method = RequestMethod.GET) + @GetMapping(value = "/hop-response") public String doHandleHopResponse(final HttpServletRequest request, final Model model, final RedirectAttributes redirectAttributes) { final Map requestParameterMap = getRequestParameterMap(request); final RedirectAuthoriseResult response = extractAuthoriseResultFromRequest(request); @@ -97,7 +97,7 @@ public String doHandleHopResponse(final HttpServletRequest request, final Model * @return */ @RequireHardLogIn - @RequestMapping(value = "/hop-pending", method = RequestMethod.GET) + @GetMapping(value = "/hop-pending") public String doHandlePendingHopResponse(final HttpServletRequest request, final Model model, final RedirectAttributes redirectAttributes) { final Map requestParameterMap = getRequestParameterMap(request); AuthorisedStatus paymentStatus = AuthorisedStatus.ERROR; @@ -109,7 +109,7 @@ public String doHandlePendingHopResponse(final HttpServletRequest request, final worldpayHostedOrderFacade.completeRedirectAuthorise(authoriseResult); return placeOrderAndRedirect(model, redirectAttributes); } else { - LOG.error(format("Failed to create payment authorisation for successful hop-response (/hop-pending). Received {0}", paymentStatus.name())); + LOG.error("Failed to create payment authorisation for successful hop-response (/hop-pending). Received {}", paymentStatus); } } return doHostedOrderPageError(paymentStatus.name(), redirectAttributes); @@ -125,7 +125,7 @@ public String doHandlePendingHopResponse(final HttpServletRequest request, final * @return */ @RequireHardLogIn - @RequestMapping(value = "bank-transfer/hop-response", method = RequestMethod.GET) + @GetMapping(value = "bank-transfer/hop-response") public String doHandleBankTransferHopResponse(@RequestParam(value = "orderId") final String orderId, final HttpServletRequest request, final Model model, final RedirectAttributes redirectAttributes) { if (!worldpayOrderCodeVerificationService.isValidEncryptedOrderCode(orderId)) { redirectAttributes.addFlashAttribute(PAYMENT_STATUS_PARAMETER_NAME, REFUSED.name()); @@ -145,11 +145,10 @@ public String doHandleBankTransferHopResponse(@RequestParam(value = "orderId") f * @return */ @RequireHardLogIn - @RequestMapping(value = "bank-transfer/hop-failure", method = RequestMethod.GET) + @GetMapping(value = "bank-transfer/hop-failure") public String doHandleBankTransferHopFailure(final HttpServletRequest request, final RedirectAttributes redirectAttributes) { final Map requestParameterMap = getRequestParameterMap(request); - LOG.info(format("Failed to complete bank transfer for selected payment method. request params {0}", requestParameterMap)); - + LOG.info("Failed to complete bank transfer for selected payment method. request params {}", requestParameterMap); redirectAttributes.addFlashAttribute(PAYMENT_STATUS_PARAMETER_NAME, REFUSED.name()); return REDIRECT_URL_CHOOSE_PAYMENT_METHOD; } @@ -159,7 +158,7 @@ public String doHandleBankTransferHopFailure(final HttpServletRequest request, f * * @return the string */ - @RequestMapping(value = "/hop-cancel", method = RequestMethod.GET) + @GetMapping(value = "/hop-cancel") @RequireHardLogIn public String doCancelPayment() { String redirectUrl = REDIRECT_URL_CHOOSE_PAYMENT_METHOD; @@ -180,7 +179,7 @@ public String doCancelPayment() { * @param redirectAttributes the {@link RedirectAttributes } to be used * @return url for view */ - @RequestMapping(value = "/error", method = RequestMethod.GET) + @GetMapping(value = "/error") @RequireHardLogIn public String doHostedOrderPageError(@RequestParam(value = "paymentStatus", required = false) final String paymentStatus, final RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute(PAYMENT_STATUS_PARAMETER_NAME, paymentStatus != null ? paymentStatus : AuthorisedStatus.ERROR.name()); @@ -193,7 +192,7 @@ public String doHostedOrderPageError(@RequestParam(value = "paymentStatus", requ * @param model the {@link Model} to be used * @return */ - @RequestMapping(value = "/billingaddressform", method = RequestMethod.GET) + @GetMapping(value = "/billingaddressform") public String getCountryAddressForm(@RequestParam("countryIsoCode") final String countryIsoCode, @RequestParam("useDeliveryAddress") final boolean useDeliveryAddress, final Model model) { model.addAttribute("supportedCountries", getCountries()); @@ -228,8 +227,9 @@ protected String processResponse(final Model model, final RedirectAttributes red worldpayHostedOrderFacade.completeRedirectAuthorise(response); return placeOrderAndRedirect(model, redirectAttributes); } else { - LOG.error(format("Failed to create payment authorisation for successful hop-response (/hop-response). Received {0}", paymentStatus.name())); - return doHostedOrderPageError(paymentStatus.name(), redirectAttributes); + final String paymentStatusName = paymentStatus.name(); + LOG.error("Failed to create payment authorisation for successful hop-response (/hop-response). Received {}", paymentStatusName); + return doHostedOrderPageError(paymentStatusName, redirectAttributes); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayIframeCheckoutStepController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayIframeCheckoutStepController.java index b16749b5..236a773b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayIframeCheckoutStepController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayIframeCheckoutStepController.java @@ -11,7 +11,8 @@ import de.hybris.platform.acceleratorstorefrontcommons.annotations.RequireHardLogIn; import de.hybris.platform.acceleratorstorefrontcommons.controllers.util.GlobalMessages; import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; @@ -22,6 +23,7 @@ import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; +import java.util.Date; /** * Web controller to handle the Iframe in a checkout step @@ -30,9 +32,11 @@ @RequestMapping(value = "/checkout/multi/worldpay/iframe") public class WorldpayIframeCheckoutStepController extends WorldpayChoosePaymentMethodCheckoutStepController { + protected static final Logger LOGGER = LogManager.getLogger(WorldpayIframeCheckoutStepController.class); + protected static final String SHOW_NGPP_IFRAME = "showNGPPIframe"; protected static final String REDIRECT_CHECKOUT_MULTI_WORLDPAY_IFRAME_ADD_PAYMENT_DETAILS = REDIRECT_PREFIX + "/checkout/multi/worldpay/iframe/add-payment-details"; - private static final Logger LOGGER = Logger.getLogger(WorldpayIframeCheckoutStepController.class); + @Resource protected WorldpayCartFacade worldpayCartFacade; @Resource @@ -71,7 +75,7 @@ public String addPaymentDetails(final Model model, @Valid final PaymentDetailsFo } try { final AdditionalAuthInfo additionalAuthInfo = createAdditionalAuthInfo(paymentDetailsForm.getSaveInAccount(), paymentMethod); - final PaymentData paymentData = worldpayHostedOrderFacade.redirectAuthorise(additionalAuthInfo, createWorldpayAdditionalInfo(httpServletRequest)); + final PaymentData paymentData = worldpayHostedOrderFacade.redirectAuthorise(additionalAuthInfo, createWorldpayAdditionalInfo(httpServletRequest, paymentDetailsForm.getDateOfBirth())); worldpayHostedOrderFacade.createPaymentInfoModelOnCart(paymentDetailsForm.getSaveInAccount()); redirectAttrs.addFlashAttribute(PAYMENT_DATA, paymentData); redirectAttrs.addFlashAttribute(SHOW_NGPP_IFRAME, true); @@ -83,8 +87,10 @@ public String addPaymentDetails(final Model model, @Valid final PaymentDetailsFo return REDIRECT_CHECKOUT_MULTI_WORLDPAY_IFRAME_ADD_PAYMENT_DETAILS; } - protected WorldpayAdditionalInfoData createWorldpayAdditionalInfo(final HttpServletRequest request) { - return worldpayAdditionalInfoFacade.createWorldpayAdditionalInfoData(request); + protected WorldpayAdditionalInfoData createWorldpayAdditionalInfo(final HttpServletRequest request, final Date dateOfBirth) { + final WorldpayAdditionalInfoData worldpayAdditionalInfoData = worldpayAdditionalInfoFacade.createWorldpayAdditionalInfoData(request); + worldpayAdditionalInfoData.setDateOfBirth(dateOfBirth); + return worldpayAdditionalInfoData; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayKlarnaCheckoutStepController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayKlarnaCheckoutStepController.java index 65218c61..5a32f78f 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayKlarnaCheckoutStepController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayKlarnaCheckoutStepController.java @@ -10,11 +10,12 @@ import de.hybris.platform.acceleratorstorefrontcommons.controllers.AbstractController; import de.hybris.platform.acceleratorstorefrontcommons.controllers.util.GlobalMessages; import de.hybris.platform.order.InvalidCartException; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.annotation.Resource; @@ -27,7 +28,9 @@ @Controller @RequestMapping(value = "/checkout/multi/worldpay") public class WorldpayKlarnaCheckoutStepController extends AbstractController { - private static final Logger LOG = Logger.getLogger(WorldpayHopResponseController.class); + + private static final Logger LOG = LoggerFactory.getLogger(WorldpayKlarnaCheckoutStepController.class); + private static final String KLARNA_RESPONSE_PAGE_DATA_PARAM = "KLARNA_VIEW_DATA"; private static final String CHECKOUT_PLACE_ORDER_FAILED = "checkout.placeOrder.failed"; private static final String PAYMENT_STATUS_PARAMETER_NAME = "paymentStatus"; @@ -49,7 +52,7 @@ public class WorldpayKlarnaCheckoutStepController extends AbstractController { * @param redirectAttributes * @return */ - @RequestMapping(value = "/klarna/confirmation", method = RequestMethod.GET) + @GetMapping(value = "/klarna/confirmation") @RequireHardLogIn public String doHandleKlarnaConfirmation(final Model model, final RedirectAttributes redirectAttributes) { try { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayThreeDSecureEndpointController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayThreeDSecureEndpointController.java index 0444f5ac..e38e0ebf 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayThreeDSecureEndpointController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayThreeDSecureEndpointController.java @@ -9,7 +9,8 @@ import com.worldpay.payment.TransactionStatus; import de.hybris.platform.acceleratorstorefrontcommons.annotations.RequireHardLogIn; import de.hybris.platform.order.InvalidCartException; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @@ -29,7 +30,7 @@ @RequestMapping(value = "/checkout/multi/worldpay/3dsecure/sop/response") public class WorldpayThreeDSecureEndpointController extends WorldpayChoosePaymentMethodCheckoutStepController { - private static final Logger LOG = Logger.getLogger(WorldpayThreeDSecureEndpointController.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayThreeDSecureEndpointController.class); @Resource protected WorldpayDirectOrderFacade worldpayDirectOrderFacade; @@ -56,11 +57,11 @@ public String doHandleThreeDSecureResponse(final HttpServletRequest request, fin if (AUTHORISED.equals(transactionStatus)) { return redirectToOrderConfirmationPage(responseData.getOrderData()); } else { - LOG.error(format("Failed to create payment authorisation for successful 3DSecure response. Received {0} as transactionStatus", transactionStatus)); + LOG.error("Failed to create payment authorisation for successful 3DSecure response. Received {} as transactionStatus", transactionStatus); worldpayCartService.setWorldpayDeclineCodeOnCart(worldpayOrderCode, responseData.getReturnCode()); } } catch (WorldpayException | InvalidCartException e) { - LOG.error(format("There was an error processing the 3d secure payment for order with worldpayOrderCode [{0}]", worldpayOrderCode), e); + LOG.error("There was an error processing the 3d secure payment for order with worldpayOrderCode [{}]", worldpayOrderCode, e); } redirectAttributes.addFlashAttribute(PAYMENT_STATUS_PARAMETER_NAME, transactionStatus.toString()); return REDIRECT_URL_CHOOSE_PAYMENT_METHOD + "?" + PAYMENT_STATUS_PARAMETER_NAME + "=" + transactionStatus; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/forms/validation/CseFormValidator.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/forms/validation/CseFormValidator.java index ff71a69a..19f09109 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/forms/validation/CseFormValidator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/forms/validation/CseFormValidator.java @@ -1,18 +1,27 @@ package com.worldpay.forms.validation; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.forms.CSEPaymentForm; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; +import javax.annotation.Resource; +import java.util.Date; + /** * Class to validate if an object is of CSEPaymentForm */ -@Component ("cseFormValidator") +@Component("cseFormValidator") public class CseFormValidator implements Validator { + protected static final String GLOBAL_MISSING_CSE_TOKEN = "checkout.multi.paymentMethod.cse.invalid"; protected static final String CHECKOUT_ERROR_TERMS_NOT_ACCEPTED = "checkout.error.terms.not.accepted"; + protected static final String CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY = "checkout.error.fraudSight.dob.mandatory"; + + @Resource + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacade; @Override public boolean supports(final Class aClass) { @@ -30,5 +39,19 @@ public void validate(final Object object, final Errors errors) { if (!form.isTermsCheck()) { errors.reject(CHECKOUT_ERROR_TERMS_NOT_ACCEPTED); } + + if (worldpayPaymentCheckoutFacade.isFSEnabled() && form.isDobRequired() && !isValidDate(form.getDateOfBirth())) { + errors.reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + } + + /** + * Checks if the birthday date is in the past + * + * @param birthdayDate the birthday date + * @return true if valid, false otherwise + */ + protected boolean isValidDate(final Date birthdayDate) { + return birthdayDate != null && birthdayDate.before(new Date()); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/security/WorldpayCommerceRedirectStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/security/WorldpayCommerceRedirectStrategy.java new file mode 100644 index 00000000..e5e3e93b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/src/com/worldpay/security/WorldpayCommerceRedirectStrategy.java @@ -0,0 +1,52 @@ +package com.worldpay.security; + +import de.hybris.platform.acceleratorfacades.flow.CheckoutFlowFacade; +import org.apache.commons.lang.StringUtils; +import org.springframework.security.web.DefaultRedirectStrategy; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * A redirect strategy used in + * {@link de.hybris.platform.acceleratorstorefrontcommons.security.StorefrontAuthenticationSuccessHandler} to handle + * express checkout case. + */ +public class WorldpayCommerceRedirectStrategy extends DefaultRedirectStrategy { + + private static final String EXPRESS_CHECKOUT_ENABLED = "expressCheckoutEnabled"; + + private final CheckoutFlowFacade checkoutFlowFacade; + private final String expressTargetUrl; + + public WorldpayCommerceRedirectStrategy(final CheckoutFlowFacade checkoutFlowFacade, final String expressTargetUrl) { + this.checkoutFlowFacade = checkoutFlowFacade; + this.expressTargetUrl = expressTargetUrl; + } + + /** + * {@inheritDoc} + */ + @Override + public void sendRedirect(final HttpServletRequest request, final HttpServletResponse response, final String url) + throws IOException { + super.sendRedirect(request, response, determineRedirectUrl(request, url)); + } + + /** + * Determine the redirect url depending on if express checkout is enabled and request has expressCheckoutEnabled parameter. + * + * @param request the request. + * @param originalUrl the original url. + * @return the calculated url. + */ + protected String determineRedirectUrl(final HttpServletRequest request, final String originalUrl) { + if (checkoutFlowFacade.isExpressCheckoutEnabledForStore() + && StringUtils.isNotEmpty(request.getParameter(EXPRESS_CHECKOUT_ENABLED))) { + return expressTargetUrl; + } else { + return originalUrl; + } + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepControllerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepControllerTest.java index 586f9e23..946ecc89 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepControllerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepControllerTest.java @@ -4,6 +4,7 @@ import com.worldpay.data.Additional3DS2Info; import com.worldpay.data.CSEAdditionalAuthInfo; import com.worldpay.exception.WorldpayException; +import com.worldpay.facades.WorldpayCartFacade; import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.facades.order.impl.WorldpayCheckoutFacadeDecorator; import com.worldpay.facades.payment.WorldpayAdditionalInfoFacade; @@ -47,6 +48,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Collections; +import java.util.Date; import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayDirectCheckoutStepController.CMS_PAGE_MODEL; import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayPaymentMethodCheckoutStepController.*; @@ -82,6 +84,9 @@ public class WorldpayCseCheckoutStepControllerTest { private static final String THREDSFLEX_DDC_PAGE = "ddcIframePage"; private static final String THREEDS_FLEX_CHALLENGE_IFRAME = "threeDSFlexIframePage"; private static final String THREEDSECURE_FLEX_DDC_URL_VALUE = "threeDSecureDDCUrlValue"; + private static final Date CURRENT_DATE_VALUE = new Date(); + private static final String DEVICE_SESSION = "device_session"; + private static final String CURRENT_DATE = "currentDate"; @Spy @InjectMocks @@ -108,6 +113,8 @@ public class WorldpayCseCheckoutStepControllerTest { private BindingResult bindingResultMock; @Mock private WorldpayDirectOrderFacade worldpayDirectOrderFacadeMock; + @Mock + private WorldpayCartFacade worldpayCartFacadeMock; @Mock(name = "cseFormValidator") private Validator cseFormValidatorMock; @Mock(answer = RETURNS_DEEP_STUBS) @@ -159,6 +166,7 @@ public class WorldpayCseCheckoutStepControllerTest { @Mock private HttpServletResponse responseMock; + @Before public void setUp() throws CMSItemNotFoundException { doNothing().when(testObj).handleAndSaveAddresses(paymentDetailsFormMock); @@ -181,6 +189,7 @@ public void setUp() throws CMSItemNotFoundException { when(pageTitleResolverMock.resolveContentPageTitle(anyString())).thenReturn(RESOLVED_PAGE_TITLE); when(checkoutFacadeMock.hasCheckoutCart()).thenReturn(true); when(worldpayAddonEndpointServiceMock.getCSEPaymentDetailsPage()).thenReturn(CSE_PAYMENT_DETAILS_PAGE); + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(true); } @Test @@ -296,14 +305,27 @@ public void shouldCheckForValidCart() throws CMSItemNotFoundException { } @Test - public void shouldAddCMSContentForPageToModel() throws CMSItemNotFoundException { + public void getCseDataPage_WhenFSEnabled_ShouldAddCMSContentForPageToModelAndFSAttributeTrue() throws CMSItemNotFoundException { + testObj.getCseDataPage(modelMock); + + verify(modelMock).addAttribute(CMS_PAGE_MODEL, contentPageModelMock); + verify(modelMock).addAttribute(IS_FS_ENABLED, true); + verify(modelMock).addAttribute(eq(CURRENT_DATE), any(Date.class)); + } + + @Test + public void getCseDataPage_WhenFSDisabled_ShouldAddCMSContentForPageToModelAndFSAttributeFalse() throws CMSItemNotFoundException { + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(false); + testObj.getCseDataPage(modelMock); verify(modelMock).addAttribute(CMS_PAGE_MODEL, contentPageModelMock); + verify(modelMock).addAttribute(IS_FS_ENABLED, false); + verify(modelMock).addAttribute(eq(CURRENT_DATE), any(Date.class)); } @Test - public void shouldAddCartToModel() throws CMSItemNotFoundException { + public void getCseDataPage_shouldAddCartToModel() throws CMSItemNotFoundException { testObj.getCseDataPage(modelMock); verify(modelMock).addAttribute(CART_DATA, cartDataMock); @@ -347,11 +369,16 @@ public void shouldCreateWorldpayAdditionalInfo() { when(cseAdditionalAuthInfoMock.getAdditional3DS2()).thenReturn(additional3DS2InfoMock); when(cseAdditionalAuthInfoMock.getAdditional3DS2().getDfReferenceId()).thenReturn(ID_REFERENCE); when(cseAdditionalAuthInfoMock.getAdditional3DS2().getChallengeWindowSize()).thenReturn(WINDOW_SIZE); + when(csePaymentFormMock.getDateOfBirth()).thenReturn(CURRENT_DATE_VALUE); + when(csePaymentFormMock.getDeviceSession()).thenReturn(DEVICE_SESSION); + when(csePaymentFormMock.getCvc()).thenReturn(CVC); - testObj.createWorldpayAdditionalInfo(httpServletRequestMock, CVC, cseAdditionalAuthInfoMock); + testObj.createWorldpayAdditionalInfo(httpServletRequestMock, csePaymentFormMock, cseAdditionalAuthInfoMock); verify(worldpayAdditionalInfoFacadeMock).createWorldpayAdditionalInfoData(httpServletRequestMock); verify(worldpayAdditionalInfoDataMock).setSecurityCode(CVC); + verify(worldpayAdditionalInfoDataMock).setDateOfBirth(CURRENT_DATE_VALUE); + verify(worldpayAdditionalInfoDataMock).setDeviceSession(DEVICE_SESSION); verify(worldpayAdditionalInfoDataMock).setAdditional3DS2(additional3DS2InfoMock); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayIframeCheckoutStepControllerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayIframeCheckoutStepControllerTest.java index 7438e9a0..4555693b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayIframeCheckoutStepControllerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayIframeCheckoutStepControllerTest.java @@ -27,6 +27,8 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; +import java.util.Calendar; +import java.util.Date; import static java.util.Collections.singleton; import static org.junit.Assert.assertEquals; @@ -45,6 +47,7 @@ public class WorldpayIframeCheckoutStepControllerTest { private static final String SHOW_NGPP_IFRAME = "showNGPPIframe"; private static final String REDIRECT_PREFIX = "redirect:"; private static final String REDIRECT_CHECKOUT_MULTI_WORLDPAY_IFRAME_ADD_PAYMENT_DETAILS = REDIRECT_PREFIX + "/checkout/multi/worldpay/iframe/add-payment-details"; + private static final Date BIRTHDAY_DATE_VALUE = new Date(1990, Calendar.MAY, 17); private static final String PAYMENT_DATA = "paymentData"; private static final String SHOPPER_BANK_CODE = "shopperBankCode"; @@ -122,6 +125,7 @@ public void addPaymentDetailsShouldReturnIframePageWithSaveInAccountSetAsTrue() public void addPaymentDetailsShouldReturnIframePageWithSaveInAccountSetAsFalse() throws WorldpayException, CMSItemNotFoundException { when(worldpayHostedOrderFacadeMock.redirectAuthorise(additionalAuthInfoMock, worldpayAdditionalInfoDataMock)).thenReturn(paymentDataMock); when(worldpayAdditionalInfoFacadeMock.createWorldpayAdditionalInfoData(any())).thenReturn(worldpayAdditionalInfoDataMock); + when(paymentDetailsFormMock.getDateOfBirth()).thenReturn(BIRTHDAY_DATE_VALUE); final String result = testObj.addPaymentDetails(modelMock, paymentDetailsFormMock, httpServletRequestMock, bindingResultMock, redirectAttrbsMock); @@ -132,6 +136,7 @@ public void addPaymentDetailsShouldReturnIframePageWithSaveInAccountSetAsFalse() verify(redirectAttrbsMock).addFlashAttribute(SHOW_NGPP_IFRAME, true); verify(paymentDetailsFormValidatorMock).validate(paymentDetailsFormMock, bindingResultMock); verify(worldpayHostedOrderFacadeMock).createPaymentInfoModelOnCart(Boolean.FALSE); + verify(worldpayAdditionalInfoDataMock).setDateOfBirth(BIRTHDAY_DATE_VALUE); assertEquals(REDIRECT_CHECKOUT_MULTI_WORLDPAY_IFRAME_ADD_PAYMENT_DETAILS, result); } @@ -139,6 +144,7 @@ public void addPaymentDetailsShouldReturnIframePageWithSaveInAccountSetAsFalse() public void addPaymentDetailsShouldReturnBillingPageWithErrors() throws WorldpayException, CMSItemNotFoundException { when(worldpayHostedOrderFacadeMock.redirectAuthorise(additionalAuthInfoMock, worldpayAdditionalInfoDataMock)).thenThrow(new WorldpayException(EXCEPTION_MESSAGE)); when(worldpayAdditionalInfoFacadeMock.createWorldpayAdditionalInfoData(any())).thenReturn(worldpayAdditionalInfoDataMock); + when(paymentDetailsFormMock.getDateOfBirth()).thenReturn(BIRTHDAY_DATE_VALUE); final String result = testObj.addPaymentDetails(modelMock, paymentDetailsFormMock, httpServletRequestMock, bindingResultMock, redirectAttrbsMock); @@ -149,6 +155,7 @@ public void addPaymentDetailsShouldReturnBillingPageWithErrors() throws Worldpay verify(redirectAttrbsMock, never()).addFlashAttribute(eq(PAYMENT_METHOD_PARAM), any()); verify(redirectAttrbsMock, never()).addFlashAttribute(eq(SHOPPER_BANK_CODE), any()); verify(redirectAttrbsMock).addFlashAttribute(SHOW_NGPP_IFRAME, false); + verify(worldpayAdditionalInfoDataMock).setDateOfBirth(BIRTHDAY_DATE_VALUE); assertEquals(REDIRECT_CHECKOUT_MULTI_WORLDPAY_IFRAME_ADD_PAYMENT_DETAILS, result); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/facades/impl/DefaultAPMAvailabilityFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/facades/impl/DefaultAPMAvailabilityFacadeTest.java index e8913e95..e0bb3490 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/facades/impl/DefaultAPMAvailabilityFacadeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/facades/impl/DefaultAPMAvailabilityFacadeTest.java @@ -1,5 +1,6 @@ package com.worldpay.facades.impl; +import com.worldpay.core.services.APMConfigurationLookupService; import com.worldpay.model.WorldpayAPMConfigurationModel; import com.worldpay.service.apm.APMAvailabilityService; import de.hybris.bootstrap.annotations.UnitTest; @@ -23,13 +24,16 @@ public class DefaultAPMAvailabilityFacadeTest { private DefaultAPMAvailabilityFacade testObj; @Mock - private WorldpayAPMConfigurationModel apmConfigurationMock; + private APMAvailabilityService apmAvailabilityServiceMock; + @Mock + private APMConfigurationLookupService apmConfigurationLookupServiceMock; @Mock private CartService cartServiceMock; + @Mock - private CartModel cartModelMock; + private WorldpayAPMConfigurationModel apmConfigurationMock; @Mock - private APMAvailabilityService apmAvailabilityServiceMock; + private CartModel cartModelMock; @Test public void isAvailableInvokesApmAvailabilityService() { @@ -42,4 +46,4 @@ public void isAvailableInvokesApmAvailabilityService() { verify(apmAvailabilityServiceMock).isAvailable(apmConfigurationMock, cartModelMock); } -} \ No newline at end of file +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/forms/validation/CseFormValidatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/forms/validation/CseFormValidatorTest.java index b0aecfc5..0db7f841 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/forms/validation/CseFormValidatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/forms/validation/CseFormValidatorTest.java @@ -1,7 +1,9 @@ package com.worldpay.forms.validation; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.forms.CSEPaymentForm; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -9,21 +11,34 @@ import org.mockito.runners.MockitoJUnitRunner; import org.springframework.validation.Errors; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import static org.mockito.Mockito.*; @UnitTest -@RunWith (MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class CseFormValidatorTest { - public static final String CSE_TOKEN = "cseToken"; + private static final String CSE_TOKEN = "cseToken"; + private static final String BIRTH_DAY_DATE_FORMAT = "dd/MM/yyyy"; + private static final String CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY = "checkout.error.fraudSight.dob.mandatory"; + @InjectMocks private CseFormValidator testObj = new CseFormValidator(); + @Mock private Errors errorsMock; @Mock private CSEPaymentForm csePaymentFormMock; + @Mock + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacadeMock; + + @Before + public void setUp() { + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(true); + when(csePaymentFormMock.isDobRequired()).thenReturn(true); + } @Test public void shouldNotRejectIfCseIsSet() throws Exception { @@ -60,4 +75,43 @@ public void shouldRejectIfTermsIsNotChecked() throws Exception { verify(errorsMock).reject(CseFormValidator.CHECKOUT_ERROR_TERMS_NOT_ACCEPTED); } -} \ No newline at end of file + + @Test + public void validate_WhenFSIsEnabledAndBirthdayDateNull_ShouldAddTheError() { + when(csePaymentFormMock.getDateOfBirth()).thenReturn(null); + + testObj.validate(csePaymentFormMock, errorsMock); + + verify(errorsMock).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + + @Test + public void validate_WhenFSIsDisabledAndBirthdayDateNull_ShouldNotAddTheError() { + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(false); + when(csePaymentFormMock.getDateOfBirth()).thenReturn(null); + + testObj.validate(csePaymentFormMock, errorsMock); + + verify(errorsMock, never()).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + + @Test + public void validate_WhenFSIsEnabledAndBirthdayDateNullAndDobNotRequired_ShouldNotAddTheError() { + when(csePaymentFormMock.isDobRequired()).thenReturn(false); + when(csePaymentFormMock.getDateOfBirth()).thenReturn(null); + + testObj.validate(csePaymentFormMock, errorsMock); + + verify(errorsMock, never()).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + + @Test + public void validate_WhenFSIsEnabledAndBirthdayDateNotInThePast_ShouldAddTheError() throws ParseException { + final SimpleDateFormat df = new SimpleDateFormat(BIRTH_DAY_DATE_FORMAT); + when(csePaymentFormMock.getDateOfBirth()).thenReturn(df.parse("21/10/2100")); + + testObj.validate(csePaymentFormMock, errorsMock); + + verify(errorsMock).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/security/WorldpayCommerceRedirectStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/security/WorldpayCommerceRedirectStrategyTest.java new file mode 100644 index 00000000..ff4960be --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/testsrc/com/worldpay/security/WorldpayCommerceRedirectStrategyTest.java @@ -0,0 +1,72 @@ +package com.worldpay.security; + +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.acceleratorfacades.flow.CheckoutFlowFacade; +import org.apache.logging.log4j.util.Strings; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class WorldpayCommerceRedirectStrategyTest { + + private static final String EXPRESS_CHECKOUT_ENABLED = "expressCheckoutEnabled"; + private static final String EXPRESS_CHECKOUT_ENABLED_TRUE = "True"; + private static final String DEFAULT_URL = "defaultUrl"; + private static final String EXPRESS_CHECKOUT_URL = "expressCheckoutUrl"; + + @InjectMocks + private WorldpayCommerceRedirectStrategy testObj; + + @Mock + private CheckoutFlowFacade checkoutFlowFacadeMock; + + @Mock + private HttpServletRequest requestMock; + @Mock + private HttpServletResponse responseMock; + + @Before + public void setUp() { + testObj = new WorldpayCommerceRedirectStrategy(checkoutFlowFacadeMock, EXPRESS_CHECKOUT_URL); + + when(checkoutFlowFacadeMock.isExpressCheckoutEnabledForStore()).thenReturn(Boolean.TRUE); + when(requestMock.getParameter(EXPRESS_CHECKOUT_ENABLED)).thenReturn(EXPRESS_CHECKOUT_ENABLED_TRUE); + } + + @Test + public void sendRedirect_WhenExpressCheckoutIsNotEnabledForStore_ShouldNotChangeUrl() throws IOException { + when(checkoutFlowFacadeMock.isExpressCheckoutEnabledForStore()).thenReturn(Boolean.FALSE); + + testObj.sendRedirect(requestMock, responseMock, DEFAULT_URL); + + assertThat(testObj.determineRedirectUrl(requestMock, DEFAULT_URL)).isEqualTo(DEFAULT_URL); + } + + @Test + public void sendRedirect_WhenHasNotExpressCheckoutEnabledParameter_ShouldNotChangeUrl() throws IOException { + when(requestMock.getParameter(EXPRESS_CHECKOUT_ENABLED)).thenReturn(Strings.EMPTY); + + testObj.sendRedirect(requestMock, responseMock, DEFAULT_URL); + + assertThat(testObj.determineRedirectUrl(requestMock, DEFAULT_URL)).isEqualTo(DEFAULT_URL); + } + + @Test + public void sendRedirect_WhenExpressCheckoutIsNotEnabledForStoreAndHasExpressCheckoutEnabledParameter_ShouldChangeUrl() throws IOException { + testObj.sendRedirect(requestMock, responseMock, DEFAULT_URL); + + assertThat(testObj.determineRedirectUrl(requestMock, DEFAULT_URL)).isEqualTo(EXPRESS_CHECKOUT_URL); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.properties b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.properties index 4d0c0106..e9e513b6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.properties +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.properties @@ -74,3 +74,7 @@ checkout.multi.3dsecure.autosubmit.form.text2=After you successfully identify yo form.required=Fields marked * are required checkout.billing.address.page.global.field.error=Some fields were not filled in correctly. Please check your details are correct + +payment.dateOfBirth = Date of birth + +checkout.error.fraudSight.dob.mandatory = Date of birth is mandatory and must be in the past diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/dateOfBirthInput.tag b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/dateOfBirthInput.tag new file mode 100644 index 00000000..fcde51ca --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/dateOfBirthInput.tag @@ -0,0 +1,22 @@ +<%@ tag trimDirectiveWhitespaces="true" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> +<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/worldpayCSECardDetails.tag b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/worldpayCSECardDetails.tag index 4265df5f..71bdd1c7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/worldpayCSECardDetails.tag +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/worldpayCSECardDetails.tag @@ -1,5 +1,7 @@ <%@ tag trimDirectiveWhitespaces="true" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="wp-multi-checkout" tagdir="/WEB-INF/tags/addons/worldpayaddon/responsive/checkout/multi" %> @@ -16,7 +18,25 @@ - + + + +
+ + + + + + + +
+
+
@@ -24,10 +44,12 @@
- +
- +
diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseCSEPaymentDetailsPage.jsp b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseCSEPaymentDetailsPage.jsp index b5c2e4b9..ded3a7c2 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseCSEPaymentDetailsPage.jsp +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseCSEPaymentDetailsPage.jsp @@ -55,6 +55,7 @@
+
diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseIframePaymentDetailsPage.jsp b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseIframePaymentDetailsPage.jsp index b213db95..1209b0e5 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseIframePaymentDetailsPage.jsp +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseIframePaymentDetailsPage.jsp @@ -85,7 +85,6 @@ action="${addPaymentAddressUrl}" class="create_update_payment_form"> -
@@ -96,6 +95,9 @@
+ + +
diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseRedirectPaymentDetailsPage.jsp b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseRedirectPaymentDetailsPage.jsp index 572bda05..88b16656 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseRedirectPaymentDetailsPage.jsp +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayChooseRedirectPaymentDetailsPage.jsp @@ -48,6 +48,7 @@
+ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayCollector.js b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayCollector.js new file mode 100644 index 00000000..240530b3 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayCollector.js @@ -0,0 +1,43 @@ +var threatmetrix = threatmetrix || {}; +threatmetrix.version = 3, threatmetrix.create_url = function(t, e, r, n, a) { + function i() { return Math.floor(2742745743359 * Math.random()) } + + function c() { return o(i()) } + + function o(t) { return (t + 78364164096).toString(36) } + var m = i(), + u = i(), + l = 885187064159; + u = ((u = u - u % 256 + threatmetrix.version) + m) % 2742745743359, l = (l + m) % 2742745743359; + var s = "https://" + t + "/" + (m = c() + o(m)) + e, + h = [(u = o(l) + o(u)) + "=" + r, c() + c() + "=" + n]; + return void 0 !== a && a.length > 0 && h.push(c() + c() + "=" + a), s + "?" + h.join("&") +}, threatmetrix.beacon = function(t, e, r, n) { + var a = "turn:aa.online-metrix.net?transport=", + i = "1:" + e + ":" + r, + c = { iceServers: [{ urls: a + "tcp", username: i, credential: r }, { urls: a + "udp", username: i, credential: r }] }; + try { + var o = new RTCPeerConnection(c); + o.createDataChannel(Math.random().toString()); + var m = function() {}, + u = function(t) { o.setLocalDescription(t, m, m) }; + "undefined" == typeof Promise || o.createOffer.length > 0 ? o.createOffer(u, m) : o.createOffer().then(u, m) + } catch (t) {} +}, threatmetrix.load_tags = function(t, e, r, n) { + threatmetrix.beacon(t, e, r, n); + var a = document.getElementsByTagName("head").item(0), + i = document.createElement("script"); + i.id = "tmx_tags_js", i.setAttribute("type", "text/javascript"); + var c = threatmetrix.create_url(t, ".js", e, r, n); + i.setAttribute("src", c), threatmetrix.set_csp_nonce(i), a.appendChild(i) +}, threatmetrix.load_iframe_tags = function(t, e, r, n) { + threatmetrix.beacon(t, e, r, n); + var a = threatmetrix.create_url(t, ".htm", e, r, n), + i = document.createElement("iframe"); + i.title = "empty", i.setAttribute("aria-disabled", "true"), i.width = "0", i.height = "0", i.setAttribute("style", "color:rgba(0,0,0,0); float:left; position:absolute; top:-200; left:-200; border:0px"), i.setAttribute("src", a), document.body.appendChild(i) +}, threatmetrix.csp_nonce = null, threatmetrix.register_csp_nonce = function(t) { + if (void 0 !== t.currentScript && null !== t.currentScript) { + var e = t.currentScript.getAttribute("nonce"); + void 0 !== e && null !== e && "" !== e ? threatmetrix.csp_nonce = e : void 0 !== t.currentScript.nonce && null !== t.currentScript.nonce && "" !== t.currentScript.nonce && (threatmetrix.csp_nonce = t.currentScript.nonce) + } +}, threatmetrix.set_csp_nonce = function(t) { null !== threatmetrix.csp_nonce && (t.setAttribute("nonce", threatmetrix.csp_nonce), t.getAttribute("nonce") !== threatmetrix.csp_nonce && (t.nonce = threatmetrix.csp_nonce)) }, threatmetrix.cleanup = function() { for (; null !== (hp_frame = document.getElementById("tdz_ifrm"));) hp_frame.parentElement.removeChild(hp_frame); for (; null !== (tmx_frame = document.getElementById("tmx_tags_iframe"));) tmx_frame.parentElement.removeChild(tmx_frame); for (; null !== (tmx_script = document.getElementById("tmx_tags_js"));) tmx_script.parentElement.removeChild(tmx_script) }, threatmetrix.prfl = function(t, e, r, n) { threatmetrix.cleanup(), threatmetrix.register_csp_nonce(document), threatmetrix.load_tags(t, e, r, n) }, threatmetrix.prfl_iframe = function(t, e, r, n) { threatmetrix.cleanup(), threatmetrix.register_csp_nonce(document), threatmetrix.load_iframe_tags(t, e, r, n) }; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayaddon.js b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayaddon.js index e6f5bcbd..73db8ef4 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayaddon.js +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayaddon.js @@ -7,6 +7,7 @@ ACC.worldpay = { "populateDeclineCodeTimeout", "hideOrShowSaveDetails", "bindBanks", + ["bindDOBInput", ACC.isFSEnabled === 'true'], "checkPreviouslySelectedPaymentMethod", "onPaymentMethodChange" ], @@ -119,6 +120,7 @@ ACC.worldpay = { setTimeout(function () { populateDeclineCode(); }, waitTimer); + function populateDeclineCode() { $.ajax({ url: ACC.config.encodedContextPath + "/checkout/multi/worldpay/choose-payment-method/getDeclineMessage", @@ -247,6 +249,24 @@ ACC.worldpay = { }); }, + bindDOBInput: function () { + $('.cms-payment-button').on('change', function () { + var selectedCard = $('[name="paymentMethod"]:checked'); + if (selectedCard.attr('id') === 'paymentMethod_CC') { + $('#dobElement').removeClass('hidden'); + $('#dobRequired').val(true); + } else { + $('#dobElement').addClass('hidden'); + $('#dobRequired').val(false); + } + }); + + if ($('[id="paymentMethod_CC"]:checked').length > 0) { + $('#dobElement').removeClass('hidden'); + $('#dobRequired').val(ACC.isFSEnabled); + } + }, + onPaymentMethodChange: function () { const checkboxes = $('[name="paymentMethod"]'); checkboxes.on('change', function (event) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayaddonCSE.js b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayaddonCSE.js index 498fb57d..20890643 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayaddonCSE.js +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/worldpayaddonCSE.js @@ -6,7 +6,8 @@ ACC.worldpayCSE = { "bindPaymentButtons", "bindMessageEventListener", "fillResolutionForWindowChallenge", - "bindPlaceOrderForm" + "bindPlaceOrderForm", + ["performJsc", $("#worldpayCsePaymentForm").length > 0 && ACC.isFSEnabled === 'true'] ], errorCodeMap: {}, @@ -23,7 +24,6 @@ ACC.worldpayCSE = { const encryptedData = Worldpay.encrypt(data, ACC.worldpayCSE.errorHandler); if (encryptedData) { $("#encryptedData").val(encryptedData); - $("#DDCIframe").contents().find('#collectionForm').submit(); return true; } else { return false; @@ -128,7 +128,7 @@ ACC.worldpayCSE = { return xhr; }, success: function (res) { - if (xhr.getResponseHeader('3D-Secure-Flow') === "false" || !xhr.getResponseHeader('3D-Secure-Flow')) { + if (xhr.getResponseHeader('3D-Secure-Flow') === "false" || !xhr.getResponseHeader('3D-Secure-Flow')) { $('body').html(res); window.scrollTo(0, 0); } else { @@ -164,6 +164,26 @@ ACC.worldpayCSE = { }, false); }, + performJsc: function () { + let ndownc = ACC.worldpayCSE.create_uuid(); //that’s the sessionId + let div = $('#worldpayCsePaymentForm'); //suggestion how you can store sessionId for when you need it in payment request + let input = document.createElement('input'); + input.setAttribute('type', 'hidden'); + input.setAttribute('id', 'deviceSession'); + input.setAttribute('name', 'deviceSession'); + input.setAttribute('value', ndownc); + div.append(input); + threatmetrix.prfl(ACC.profilingDomain, ACC.organizationId, ndownc, 1); // Jsc.prfl is the renamed function + }, + + create_uuid: function () { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = Math.random() * 16 | 0, + v = c === 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + }); + }, + populateErrorCodeMap: function () { ACC.worldpayCSE.errorCodeMap["101"] = "error-number"; ACC.worldpayCSE.errorCodeMap["102"] = "error-number"; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/project.properties b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/project.properties index cc657b66..cd974110 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/project.properties +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/project.properties @@ -1,4 +1,4 @@ -#Mon, 18 Jan 2021 14:19:01 +0000 +#Wed, 29 Sep 2021 10:46:17 +0000 # ----------------------------------------------------------------------- # [y] hybris Platform # @@ -30,7 +30,7 @@ storefront.supportedUiExperienceLevels.powertools=DESKTOP,MOBILE # Set the HOP PCI strategy at this level so that it's consistent across stores hop.pci.strategy.enabled=true -worldpayaddon.javascript.paths.responsive=/responsive/common/js/worldpayaddon.js;/responsive/common/js/worldpayaddonCSE.js;/responsive/common/js/worldpayaddonRedirect.js;/responsive/common/js/worldpayGooglePay.js;/responsive/common/js/worldpayApplePay.js +worldpayaddon.javascript.paths.responsive=/responsive/common/js/worldpayaddon.js;/responsive/common/js/worldpayaddonCSE.js;/responsive/common/js/worldpayaddonRedirect.js;/responsive/common/js/worldpayGooglePay.js;/responsive/common/js/worldpayApplePay.js;/responsive/common/js/worldpayCollector.js worldpayaddon.css.paths.responsive=/responsive/common/css/worldpayaddon.css diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/project.properties.template b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/project.properties.template index edc926df..2afa2dbb 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/project.properties.template +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/project.properties.template @@ -34,7 +34,8 @@ worldpayaddon.javascript.paths.responsive=\ /responsive/common/js/worldpayaddonCSE.js;\ /responsive/common/js/worldpayaddonRedirect.js;\ /responsive/common/js/worldpayGooglePay.js;\ - /responsive/common/js/worldpayApplePay.js + /responsive/common/js/worldpayApplePay.js;\ + /responsive/common/js/worldpayCollector.js worldpayaddon.css.paths.responsive=/responsive/common/css/worldpayaddon.css diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/resources/worldpayaddon.build.number b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/resources/worldpayaddon.build.number index 24c7ef68..b595974e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/resources/worldpayaddon.build.number +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/resources/worldpayaddon.build.number @@ -1,11 +1,11 @@ #Ant properties -#Mon Jan 18 14:19:09 UTC 2021 -version.api=2011 +#Wed Sep 29 10:46:25 UTC 2021 +version.api=2105 vendor=hybris group.id=de.hybris.platform name=worldpayaddon description=worldpayaddon -builddate=20210118 1419 -releasedate=20201208 1801 -version=2011.1 +builddate=20210929 1046 +releasedate=20210721 0907 +version=2105.0 module.name=platform-module diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/resources/worldpayaddon/web/spring/worldpayaddon-web-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/resources/worldpayaddon/web/spring/worldpayaddon-web-spring.xml index ad916775..28477552 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddon/resources/worldpayaddon/web/spring/worldpayaddon-web-spring.xml +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddon/resources/worldpayaddon/web/spring/worldpayaddon-web-spring.xml @@ -1,15 +1,4 @@ - + @@ -102,4 +92,13 @@ + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/.classpath b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/.classpath index 482e73a5..912e49ad 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/.classpath +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/.classpath @@ -10,7 +10,6 @@ - diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice-backoffice-config.xml b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice-backoffice-config.xml index 35ad64a9..49ede202 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice-backoffice-config.xml +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice-backoffice-config.xml @@ -4,6 +4,7 @@ xmlns:explorer-tree="http://www.hybris.com/cockpitng/config/explorertree" xmlns:list-view="http://www.hybris.com/cockpitng/component/listView" xmlns:y="http://www.hybris.com/cockpit/config/hybris" + xmlns:simple-search="http://www.hybris.com/cockpitng/config/simplesearch" xmlns:editorArea="http://www.hybris.com/cockpitng/component/editorArea" xmlns:advanced-search="http://www.hybris.com/cockpitng/config/advancedsearch"> @@ -12,6 +13,7 @@ + @@ -43,6 +45,14 @@ + + + + 'risk=' + message + ' score=' + score + + + + @@ -102,18 +112,109 @@ + - - + + + + + + + + + + identifier + ' - ' + code + + + + + + + + name + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -252,4 +353,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice-backoffice-labels/labels_en.properties b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice-backoffice-labels/labels_en.properties index a3201d88..851614ed 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice-backoffice-labels/labels_en.properties +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice-backoffice-labels/labels_en.properties @@ -1,18 +1,13 @@ -# -# [y] hybris Platform -# -# Copyright (c) 2000-2015 hybris AG -# All rights reserved. -# -# This software is the confidential and proprietary information of hybris -# ("Confidential Information"). You shall not disclose such Confidential -# Information and shall use it only in accordance with the terms of the -# license agreement you entered into with hybris. -# - -# in this file you has possibility to override widget labels -# syntax: -# .=value -# -# Example: -# yourCustomLabel=value +tab.configuration.worldpay = Worldpay +sec.configuration.worldpay.pr.section = Prime Routing Configuration +worldpay.merchant.configuration = Merchant Configuration +tab.configuration.worldpay.merchant.essential = Essential +sec.configuration.worldpay.details = Configuration Details +tab.configuration.worldpay.merchant.card.payments = Card Payments +tab.configuration.worldpay.merchant.applepay.payments = ApplePay Payments +tab.configuration.worldpay.merchant.googlepay.payments = GooglePay Payments +sec.configuration.worldpay.merchant.section = Merchant Configuration Details +sec.configuration.worldpay.fs.section = Fraud Sight Configuration +sec.configuration.worldpay.level23Data.section = Level 2/3 Data Configuration +sec.configuration.worldpay.api.payload.section = Api Request/Response Payloads +sec.configuration.worldpay.general.section = General configuration diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice.build.number b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice.build.number index 6886ec1d..d5a8e165 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice.build.number +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/resources/worldpayaddonbackoffice.build.number @@ -1,11 +1,11 @@ #Ant properties -#Mon Jan 18 14:19:10 UTC 2021 -version.api=2011 +#Wed Sep 29 10:46:26 UTC 2021 +version.api=2105 vendor=hybris group.id=de.hybris.platform name=worldpayaddonbackoffice description=worldpayaddonbackoffice -builddate=20210118 1419 -releasedate=20201208 1801 -version=2011.1 +builddate=20210929 1046 +releasedate=20210721 0907 +version=2105.0 module.name=platform-module diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/src/com/worldpay/jalo/WorldpayaddonbackofficeManager.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/src/com/worldpay/jalo/WorldpayaddonbackofficeManager.java index d5841883..3c883bf7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/src/com/worldpay/jalo/WorldpayaddonbackofficeManager.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/src/com/worldpay/jalo/WorldpayaddonbackofficeManager.java @@ -1,130 +1,19 @@ -/* - * [y] hybris Platform - * - * Copyright (c) 2000-2015 hybris AG - * All rights reserved. - * - * This software is the confidential and proprietary information of hybris - * ("Confidential Information"). You shall not disclose such Confidential - * Information and shall use it only in accordance with the terms of the - * license agreement you entered into with hybris. - */ package com.worldpay.jalo; -import de.hybris.platform.core.Registry; -import de.hybris.platform.util.JspContext; - -import java.util.Map; - -import org.apache.log4j.Logger; - import com.worldpay.constants.WorldpayaddonbackofficeConstants; +import de.hybris.platform.jalo.JaloSession; +import de.hybris.platform.jalo.extension.ExtensionManager; +import org.apache.log4j.Logger; - - -/** - * This is the extension manager of the Ybackoffice extension. - */ public class WorldpayaddonbackofficeManager extends GeneratedWorldpayaddonbackofficeManager { - /** Edit the local|project.properties to change logging behavior (properties 'log4j.*'). */ - private static final Logger LOG = Logger.getLogger(WorldpayaddonbackofficeManager.class.getName()); - - /* - * Some important tips for development: - * - * Do NEVER use the default constructor of manager's or items. => If you want to do something whenever the manger is - * created use the init() or destroy() methods described below - * - * Do NEVER use STATIC fields in your manager or items! => If you want to cache anything in a "static" way, use an - * instance variable in your manager, the manager is created only once in the lifetime of a "deployment" or tenant. - */ - - - /** - * Get the valid instance of this manager. - * - * @return the current instance of this manager - */ - public static WorldpayaddonbackofficeManager getInstance() - { - return (WorldpayaddonbackofficeManager) Registry.getCurrentTenant().getJaloConnection().getExtensionManager() - .getExtension(WorldpayaddonbackofficeConstants.EXTENSIONNAME); - } - - - /** - * Never call the constructor of any manager directly, call getInstance() You can place your business logic here - - * like registering a jalo session listener. Each manager is created once for each tenant. - */ - public WorldpayaddonbackofficeManager() // NOPMD - { - if (LOG.isDebugEnabled()) - { - LOG.debug("constructor of WorldpayaddonbackofficeManager called."); - } - } - - /** - * Use this method to do some basic work only ONCE in the lifetime of a tenant resp. "deployment". This method is - * called after manager creation (for example within startup of a tenant). Note that if you have more than one tenant - * you have a manager instance for each tenant. - */ - @Override - public void init() - { - if (LOG.isDebugEnabled()) - { - LOG.debug("init() of YbackofficeManager called. " + getTenant().getTenantID()); - } - } - - /** - * Use this method as a callback when the manager instance is being destroyed (this happens before system - * initialization, at redeployment or if you shutdown your VM). Note that if you have more than one tenant you have a - * manager instance for each tenant. - */ - @Override - public void destroy() - { - if (LOG.isDebugEnabled()) - { - LOG.debug("destroy() of YbackofficeManager called, current tenant: " + getTenant().getTenantID()); - } - } - - /** - * Implement this method to create initial objects. This method will be called by system creator during - * initialization and system update. Be sure that this method can be called repeatedly. - * - * An example usage of this method is to create required cronjobs or modifying the type system (setting e.g some - * default values) - * - * @param params - * the parameters provided by user for creation of objects for the extension - * @param jspc - * the jsp context; you can use it to write progress information to the jsp page during creation - */ - @Override - public void createEssentialData(final Map params, final JspContext jspc) - { - // implement here code creating essential data - } - - /** - * Implement this method to create data that is used in your project. This method will be called during the system - * initialization. - * - * An example use is to import initial data like currencies or languages for your project from an csv file. - * - * @param params - * the parameters provided by user for creation of objects for the extension - * @param jspc - * the jsp context; you can use it to write progress information to the jsp page during creation - */ - @Override - public void createProjectData(final Map params, final JspContext jspc) + @SuppressWarnings("unused") + private static final Logger log = Logger.getLogger( WorldpayaddonbackofficeManager.class.getName() ); + + public static final WorldpayaddonbackofficeManager getInstance() { - // implement here code creating project data + ExtensionManager em = JaloSession.getCurrentSession().getExtensionManager(); + return (WorldpayaddonbackofficeManager) em.getExtension(WorldpayaddonbackofficeConstants.EXTENSIONNAME); } + } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/testsrc/com/hybris/backoffice/jalo/YbackofficeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/testsrc/com/hybris/backoffice/jalo/YbackofficeTest.java deleted file mode 100644 index bede2afe..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddonbackoffice/testsrc/com/hybris/backoffice/jalo/YbackofficeTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * [y] hybris Platform - * - * Copyright (c) 2000-2015 hybris AG - * All rights reserved. - * - * This software is the confidential and proprietary information of hybris - * ("Confidential Information"). You shall not disclose such Confidential - * Information and shall use it only in accordance with the terms of the - * license agreement you entered into with hybris. - */ -package com.hybris.backoffice.jalo; - -import static org.junit.Assert.assertTrue; - -import de.hybris.platform.testframework.HybrisJUnit4TransactionalTest; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - - -/** - * JUnit Tests for the Ybackoffice extension - */ -public class YbackofficeTest extends HybrisJUnit4TransactionalTest -{ - /** Edit the local|project.properties to change logging behaviour (properties log4j.*). */ - @SuppressWarnings("unused") - private static final Logger LOG = Logger.getLogger(YbackofficeTest.class.getName()); - - @Before - public void setUp() - { - // implement here code executed before each test - } - - @After - public void tearDown() - { - // implement here code executed after each test - } - - /** - * This is a sample test method. - */ - @Test - public void testYbackoffice() - { - final boolean testTrue = true; - assertTrue("true is not true", testTrue); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/checkout/steps/validation/WorldpayCheckoutStepValidator.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/checkout/steps/validation/WorldpayCheckoutStepValidator.java index 82341098..fb1dca84 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/checkout/steps/validation/WorldpayCheckoutStepValidator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/checkout/steps/validation/WorldpayCheckoutStepValidator.java @@ -4,12 +4,13 @@ import de.hybris.platform.acceleratorstorefrontcommons.checkout.steps.validation.AbstractCheckoutStepValidator; import de.hybris.platform.acceleratorstorefrontcommons.checkout.steps.validation.ValidationResults; import de.hybris.platform.acceleratorstorefrontcommons.controllers.util.GlobalMessages; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.web.servlet.mvc.support.RedirectAttributes; public class WorldpayCheckoutStepValidator extends AbstractCheckoutStepValidator { - private static final Logger LOG = Logger.getLogger(WorldpayCheckoutStepValidator.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayCheckoutStepValidator.class); /** * {@inheritDoc} @@ -19,7 +20,7 @@ public ValidationResults validateOnEnter(RedirectAttributes redirectAttributes) final CheckoutPciOptionEnum subscriptionPciOption = getCheckoutFlowFacade().getSubscriptionPciOption(); if (!CheckoutPciOptionEnum.HOP.equals(subscriptionPciOption)) { - LOG.error("unexpected PCI option for worldpay [" + subscriptionPciOption + "]"); + LOG.error("unexpected PCI option for worldpay [{}]", subscriptionPciOption); return ValidationResults.REDIRECT_TO_CART; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/AbstractWorldpayDirectCheckoutStepController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/AbstractWorldpayDirectCheckoutStepController.java index f2902bd6..90734140 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/AbstractWorldpayDirectCheckoutStepController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/AbstractWorldpayDirectCheckoutStepController.java @@ -23,6 +23,9 @@ public abstract class AbstractWorldpayDirectCheckoutStepController extends World protected static final String THREEDSECURE_FLEX_DDC_URL = "threeDSecureDDCUrl"; protected static final String THREED_SECURE_FLEX_FLOW = "3D-Secure-Flex-Flow"; protected static final String THREED_SECURE_FLOW = "3D-Secure-Flow"; + protected static final String BIRTH_DAY_DATE_FORMAT = "dd/MM/yyyy"; + protected static final String BIRTHDAY_DATE = "birthdayDate"; + protected static final String DEVICE_SESSION = "DEVICE_SESSION"; @Resource protected WorldpayAddonEndpointService worldpayAddonEndpointService; @@ -66,9 +69,9 @@ public String handleDirectResponse(final Model model, final DirectResponseData d public void setDDCIframeData(final Model model) { final String ddcUrl = Optional.ofNullable(worldpayMerchantConfigDataFacade.getCurrentSiteMerchantConfigData()) - .map(WorldpayMerchantConfigData::getThreeDSFlexJsonWebTokenSettings) - .map(ThreeDSFlexJsonWebTokenCredentials::getDdcUrl) - .orElse(null); + .map(WorldpayMerchantConfigData::getThreeDSFlexJsonWebTokenSettings) + .map(ThreeDSFlexJsonWebTokenCredentials::getDdcUrl) + .orElse(null); model.addAttribute(THREEDSECURE_FLEX_DDC_URL, ddcUrl); model.addAttribute(THREEDSECURE_JWT_FLEX_DDC, worldpayDDCFacade.createJsonWebTokenForDDC()); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayChoosePaymentMethodCheckoutStepController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayChoosePaymentMethodCheckoutStepController.java index d07a3658..3d61e43a 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayChoosePaymentMethodCheckoutStepController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayChoosePaymentMethodCheckoutStepController.java @@ -33,8 +33,11 @@ import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; +import java.text.SimpleDateFormat; +import java.util.Date; import java.util.List; +import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayDirectCheckoutStepController.BIRTH_DAY_DATE_FORMAT; import static org.apache.commons.lang.StringUtils.EMPTY; import static org.apache.commons.lang.StringUtils.isNotBlank; @@ -48,6 +51,8 @@ public class WorldpayChoosePaymentMethodCheckoutStepController extends AbstractW protected static final String PAYMENT_INFOS = "paymentInfos"; protected static final String CHOOSE_PAYMENT_METHOD = "choose-payment-method"; protected static final String SAVED_CARD_SELECTED_ATTRIBUTE = "savedCardSelected"; + protected static final String CURRENT_DATE = "currentDate"; + protected static final String IS_FS_ENABLED = "isFSEnabled"; protected static final String CHECKOUT_MULTI_PAYMENT_METHOD_BREADCRUMB = "checkout.multi.paymentMethod.breadcrumb"; protected static final String TEXT_ACCOUNT_PROFILE_PAYMENT_CART_REMOVED = "text.account.profile.paymentCart.removed"; @@ -102,6 +107,9 @@ public String enterStep(final Model model, final RedirectAttributes redirectAttr setupAddPaymentPage(model); setupPaymentDetailsForm(model); + model.addAttribute(IS_FS_ENABLED, worldpayPaymentCheckoutFacade.isFSEnabled()); + final SimpleDateFormat dateFormat = new SimpleDateFormat(BIRTH_DAY_DATE_FORMAT); + model.addAttribute(CURRENT_DATE, dateFormat.format(new Date())); setCheckoutStepLinksForModel(model, getCheckoutStep()); return getViewForPage(model); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayPaymentMethodCheckoutStepController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayPaymentMethodCheckoutStepController.java index e5c63582..0a704b32 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayPaymentMethodCheckoutStepController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayPaymentMethodCheckoutStepController.java @@ -17,7 +17,8 @@ import de.hybris.platform.acceleratorstorefrontcommons.controllers.util.GlobalMessages; import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException; import de.hybris.platform.cms2.model.pages.ContentPageModel; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @@ -26,15 +27,17 @@ import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; +import java.util.Date; import java.util.List; +import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayDirectCheckoutStepController.BIRTHDAY_DATE; import static de.hybris.platform.acceleratorstorefrontcommons.constants.WebConstants.BREADCRUMBS_KEY; @Controller @RequestMapping(value = "/checkout/multi/worldpay/payment-method") public class WorldpayPaymentMethodCheckoutStepController extends AbstractWorldpayPaymentMethodCheckoutStepController { - private static final Logger LOGGER = Logger.getLogger(WorldpayPaymentMethodCheckoutStepController.class); + private static final Logger LOGGER = LogManager.getLogger(WorldpayPaymentMethodCheckoutStepController.class); protected static final String HOP_DEBUG_MODE_CONFIG = "hop.debug.mode"; protected static final String CHECKOUT_MULTI_PAYMENT_METHOD_BREADCRUMB = "checkout.multi.paymentMethod.breadcrumb"; @@ -166,6 +169,10 @@ public List getKlarnaPayments() { } protected WorldpayAdditionalInfoData createWorldpayAdditionalInfo(final Model model) { - return worldpayAdditionalInfoFacade.createWorldpayAdditionalInfoData((HttpServletRequest) model.asMap().get(REQUEST)); + final WorldpayAdditionalInfoData worldpayAdditionalInfoData = worldpayAdditionalInfoFacade.createWorldpayAdditionalInfoData((HttpServletRequest) model.asMap().get(REQUEST)); + if (worldpayPaymentCheckoutFacade.isFSEnabled()) { + worldpayAdditionalInfoData.setDateOfBirth((Date) model.asMap().get(BIRTHDAY_DATE)); + } + return worldpayAdditionalInfoData; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayRedirectCheckoutStepController.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayRedirectCheckoutStepController.java index 1ff10222..47506244 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayRedirectCheckoutStepController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/controllers/pages/checkout/steps/WorldpayRedirectCheckoutStepController.java @@ -1,6 +1,6 @@ package com.worldpay.controllers.pages.checkout.steps; -import com.worldpay.facades.WorldpayCartFacade; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.forms.PaymentDetailsForm; import de.hybris.platform.acceleratorstorefrontcommons.annotations.RequireHardLogIn; import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException; @@ -14,12 +14,14 @@ import javax.annotation.Resource; import javax.validation.Valid; +import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayDirectCheckoutStepController.BIRTHDAY_DATE; + @Controller @RequestMapping(value = "/checkout/multi/worldpay/redirect") public class WorldpayRedirectCheckoutStepController extends WorldpayChoosePaymentMethodCheckoutStepController { @Resource - private WorldpayCartFacade worldpayCartFacade; + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacade; /** * Validates and saves form details on submit of the payment details form for the HOP payment flow and redirects to Worldpay payment pages @@ -52,6 +54,9 @@ public String addPaymentDetails(final Model model, @Valid final PaymentDetailsFo } redirectAttrs.addFlashAttribute(SAVE_PAYMENT_INFO, paymentDetailsForm.getSaveInAccount()); redirectAttrs.addFlashAttribute(PAYMENT_METHOD_PARAM, paymentDetailsForm.getPaymentMethod()); + if (worldpayPaymentCheckoutFacade.isFSEnabled()) { + redirectAttrs.addFlashAttribute(BIRTHDAY_DATE, paymentDetailsForm.getDateOfBirth()); + } return getRedirectToPaymentMethod(); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/CSEPaymentForm.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/CSEPaymentForm.java index 9a6bc32c..e209a549 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/CSEPaymentForm.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/CSEPaymentForm.java @@ -1,5 +1,9 @@ package com.worldpay.forms; +import org.springframework.format.annotation.DateTimeFormat; + +import java.util.Date; + public class CSEPaymentForm { private boolean termsCheck; @@ -12,6 +16,10 @@ public class CSEPaymentForm { private String expiryMonth; private String referenceId; private String windowSizePreference; + @DateTimeFormat(pattern = "yyyy-MM-dd") + private Date dateOfBirth; + private String deviceSession; + private boolean dobRequired; public String getCseToken() { return cseToken; @@ -92,4 +100,28 @@ public String getSecurityCode() { public void setSecurityCode(final String securityCode) { this.securityCode = securityCode; } + + public Date getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(final Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public String getDeviceSession() { + return deviceSession; + } + + public void setDeviceSession(final String deviceSession) { + this.deviceSession = deviceSession; + } + + public boolean isDobRequired() { + return dobRequired; + } + + public void setDobRequired(final boolean dobRequired) { + this.dobRequired = dobRequired; + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/PaymentDetailsForm.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/PaymentDetailsForm.java index b4671dbe..05d4c88c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/PaymentDetailsForm.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/PaymentDetailsForm.java @@ -1,6 +1,9 @@ package com.worldpay.forms; import de.hybris.platform.acceleratorstorefrontcommons.forms.AddressForm; +import org.springframework.format.annotation.DateTimeFormat; + +import java.util.Date; public class PaymentDetailsForm { @@ -10,6 +13,9 @@ public class PaymentDetailsForm { private String paymentMethod; private AddressForm billingAddress; private String shopperBankCode; + @DateTimeFormat(pattern = "yyyy-MM-dd") + private Date dateOfBirth; + private boolean dobRequired; public String getPaymentMethod() { return paymentMethod; @@ -60,4 +66,19 @@ public void setShopperBankCode(String shopperBankCode) { this.shopperBankCode = shopperBankCode; } + public Date getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(final Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public boolean isDobRequired() { + return dobRequired; + } + + public void setDobRequired(final boolean dobRequired) { + this.dobRequired = dobRequired; + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/validation/PaymentDetailsFormValidator.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/validation/PaymentDetailsFormValidator.java index 6db5da6c..70fa8559 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/validation/PaymentDetailsFormValidator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/forms/validation/PaymentDetailsFormValidator.java @@ -1,6 +1,7 @@ package com.worldpay.forms.validation; import com.worldpay.core.services.APMConfigurationLookupService; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.forms.PaymentDetailsForm; import com.worldpay.model.WorldpayAPMConfigurationModel; import com.worldpay.service.apm.APMAvailabilityService; @@ -13,16 +14,18 @@ import org.springframework.validation.Validator; import javax.annotation.Resource; +import java.util.Date; import static com.worldpay.service.model.payment.PaymentType.ONLINE; import static java.lang.Boolean.FALSE; -@Component ("paymentDetailsFormValidator") +@Component("paymentDetailsFormValidator") public class PaymentDetailsFormValidator implements Validator { protected static final String GLOBAL_MISSING_DELIVERY_ADDRESS = "checkout.multi.paymentMethod.createSubscription.billingAddress.noneSelectedMsg"; protected static final String CHECKOUT_ERROR_TERMS_NOT_ACCEPTED = "checkout.error.terms.not.accepted"; + protected static final String CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY = "checkout.error.fraudSight.dob.mandatory"; protected static final String FIELD_PAYMENT_METHOD = "paymentMethod"; protected static final String FIELD_SHOPPER_BANK_CODE = "shopperBankCode"; @@ -44,9 +47,12 @@ public class PaymentDetailsFormValidator implements Validator { @Resource private APMAvailabilityService apmAvailabilityService; - @Resource (name = "worldpayCheckoutFacade") + @Resource(name = "worldpayCheckoutFacade") private AcceleratorCheckoutFacade checkoutFacade; + @Resource + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacade; + /** * {@inheritDoc} */ @@ -91,6 +97,18 @@ public void validate(final Object object, final Errors errors) { validateField(errors, FIELD_BILLING_ADDRESS_POSTCODE, "address.postcode.invalid"); validateField(errors, FIELD_BILLING_ADDRESS_COUNTRY_ISO, "address.country.invalid"); } + + if (worldpayPaymentCheckoutFacade.isFSEnabled() && form.isDobRequired() && !isValidDate(form.getDateOfBirth())) { + errors.reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + } + + protected boolean isValidDate(final Date birthdayDate) { + if (birthdayDate == null) { + return false; + } + + return birthdayDate.before(new Date()); } protected void validateTermsCheck(final Errors errors, final PaymentDetailsForm form) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/interceptors/beforeview/WorldpayJsVariablesBeforeViewHandler.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/interceptors/beforeview/WorldpayJsVariablesBeforeViewHandler.java index 77635bb8..962ab67e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/interceptors/beforeview/WorldpayJsVariablesBeforeViewHandler.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/src/com/worldpay/interceptors/beforeview/WorldpayJsVariablesBeforeViewHandler.java @@ -1,25 +1,40 @@ package com.worldpay.interceptors.beforeview; +import com.worldpay.config.Environment; +import com.worldpay.service.payment.WorldpayFraudSightStrategy; import de.hybris.platform.acceleratorservices.config.SiteConfigService; import de.hybris.platform.acceleratorservices.storefront.data.JavaScriptVariableData; import de.hybris.platform.addonsupport.config.javascript.JavaScriptVariableDataFactory; import de.hybris.platform.addonsupport.interceptors.BeforeViewHandlerAdaptee; +import org.apache.commons.lang3.BooleanUtils; import org.springframework.ui.ModelMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import static com.worldpay.config.Environment.PROD; + public class WorldpayJsVariablesBeforeViewHandler implements BeforeViewHandlerAdaptee { private static final int SECONDS = 2; private static final String PAYMENT_STATUS = "paymentStatus"; + private static final String ORGANIZATION_ID = "organizationId"; + private static final String PROFILING_DOMAIN = "profilingDomain"; private static final String HOP_DECLINE_MESSAGE_WAIT_TIMER_SECONDS = "hop.decline.message.wait.timer.seconds"; private static final String WORLDPAY_DECLINE_MESSAGE_WAIT_TIMER_SECONDS = "worldpayDeclineMessageWaitTimerSeconds"; + private static final String WORLDPAY_CONFIG_ENVIRONMENT = "worldpay.config.environment"; + private static final String WORLDPAY_CONFIG_PROFILE_DOMAIN_PROD = "worldpay.config.profile.domain.prod"; + private static final String WORLDPAY_CONFIG_PROFILE_DOMAIN_TEST = "worldpay.config.profile.domain.test"; + private static final String WORLDPAY_CONFIG_MERCHANT_ORGANIZATION_ID = "worldpay.merchant.organization.id"; + private static final String IS_FS_ENABLED = "isFSEnabled"; protected final SiteConfigService siteConfigService; + protected final WorldpayFraudSightStrategy worldpayFraudSightStrategy; - public WorldpayJsVariablesBeforeViewHandler(final SiteConfigService siteConfigService) { + public WorldpayJsVariablesBeforeViewHandler(final SiteConfigService siteConfigService, + final WorldpayFraudSightStrategy worldpayFraudSightStrategy) { this.siteConfigService = siteConfigService; + this.worldpayFraudSightStrategy = worldpayFraudSightStrategy; } /** @@ -32,6 +47,26 @@ public String beforeView(final HttpServletRequest request, final HttpServletResp JavaScriptVariableDataFactory.getVariables(model).add(worldpayDeclineMessageWaitTimerSeconds); final JavaScriptVariableData javaScriptVariableData = JavaScriptVariableDataFactory.create(PAYMENT_STATUS, (String) model.get(PAYMENT_STATUS)); JavaScriptVariableDataFactory.getVariables(model).add(javaScriptVariableData); + + final Boolean isFSEnabled = worldpayFraudSightStrategy.isFraudSightEnabled(); + final JavaScriptVariableData javaScriptFSEnabledVariableData = JavaScriptVariableDataFactory.create(IS_FS_ENABLED, isFSEnabled.toString()); + JavaScriptVariableDataFactory.getVariables(model).add(javaScriptFSEnabledVariableData); + + if (BooleanUtils.isTrue(isFSEnabled)) { + final String environment = siteConfigService.getProperty(WORLDPAY_CONFIG_ENVIRONMENT); + final JavaScriptVariableData javaScriptProfilingDomainVariableData; + if (PROD == Environment.valueOf(environment)) { + javaScriptProfilingDomainVariableData = JavaScriptVariableDataFactory.create(PROFILING_DOMAIN, siteConfigService.getProperty(WORLDPAY_CONFIG_PROFILE_DOMAIN_PROD)); + } else { + javaScriptProfilingDomainVariableData = JavaScriptVariableDataFactory.create(PROFILING_DOMAIN, siteConfigService.getProperty(WORLDPAY_CONFIG_PROFILE_DOMAIN_TEST)); + } + JavaScriptVariableDataFactory.getVariables(model).add(javaScriptProfilingDomainVariableData); + + final JavaScriptVariableData javaScriptOrgIdVariableData = JavaScriptVariableDataFactory.create(ORGANIZATION_ID, + siteConfigService.getProperty(WORLDPAY_CONFIG_MERCHANT_ORGANIZATION_ID)); + JavaScriptVariableDataFactory.getVariables(model).add(javaScriptOrgIdVariableData); + } + return viewName; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayChoosePaymentMethodCheckoutStepControllerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayChoosePaymentMethodCheckoutStepControllerTest.java index b83d8891..d2e9e961 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayChoosePaymentMethodCheckoutStepControllerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayChoosePaymentMethodCheckoutStepControllerTest.java @@ -85,6 +85,8 @@ public class WorldpayChoosePaymentMethodCheckoutStepControllerTest { private static final String PHONE_NUMBER = "+44 (0) 123-123-123"; private static final String PAYMENT_STATUS = "paymentStatus"; private static final String SAVED_CARD_SELECTED_ATTRIBUTE = "savedCardSelected"; + private static final String CURRENT_DATE = "currentDate"; + private static final String IS_FS_ENABLED = "isFSEnabled"; @Spy @InjectMocks @@ -316,18 +318,21 @@ public void shouldReturnTheTermsAndConditionsUrl() { } @Test - public void shouldSetupAndRedirectToChoosePaymentPage() throws CMSItemNotFoundException { + public void enterStep_WhenNoPaymentStatusInTheModel_shouldSetupAndRedirectToChoosePaymentPage() throws CMSItemNotFoundException { when(modelMock.asMap().get(PAYMENT_STATUS_PARAMETER_NAME)).thenReturn(null); + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(true); testObj.enterStep(modelMock, redirectAttrsMock); verify(testObj).setupAddPaymentPage(modelMock); verify(modelMock).addAttribute(eq(PAYMENT_DETAILS_FORM), any(PaymentDetailsForm.class)); + verify(modelMock).addAttribute(IS_FS_ENABLED, true); + verify(modelMock).addAttribute(eq(CURRENT_DATE), any(String.class)); verify(modelMock, never()).addAttribute(eq(ERROR_MESSAGES_HOLDER), any()); } @Test - public void shouldAddErrorWhenThereIsAPaymentStatusInTheModel() throws CMSItemNotFoundException { + public void enterStep_WhenThereIsAPaymentStatusInTheModel_ShouldAddError() throws CMSItemNotFoundException { when(modelMock.asMap().get(PAYMENT_STATUS_PARAMETER_NAME)).thenReturn(PAYMENT_STATUS); testObj.enterStep(modelMock, redirectAttrsMock); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayPaymentMethodCheckoutStepControllerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayPaymentMethodCheckoutStepControllerTest.java index 9a405e49..93be6278 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayPaymentMethodCheckoutStepControllerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayPaymentMethodCheckoutStepControllerTest.java @@ -4,6 +4,7 @@ import com.worldpay.data.BankTransferAdditionalAuthInfo; import com.worldpay.exception.WorldpayException; import com.worldpay.facades.WorldpayBankConfigurationFacade; +import com.worldpay.facades.WorldpayCartFacade; import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.facades.payment.WorldpayAdditionalInfoFacade; import com.worldpay.facades.payment.direct.WorldpayDirectOrderFacade; @@ -37,8 +38,11 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; +import java.util.Calendar; +import java.util.Date; import java.util.Map; +import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayDirectCheckoutStepController.BIRTHDAY_DATE; import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayPaymentMethodCheckoutStepController.*; import static com.worldpay.controllers.pages.checkout.steps.WorldpayPaymentMethodCheckoutStepController.REDIRECT_URL_CHOOSE_PAYMENT_METHOD; import static com.worldpay.controllers.pages.checkout.steps.WorldpayPaymentMethodCheckoutStepController.*; @@ -63,6 +67,7 @@ public class WorldpayPaymentMethodCheckoutStepControllerTest { private static final String KLARNA_RESPONSE = "klarnaContent"; private static final String KLARNA_RESPONSE_PAGE_DATA_PARAM = "KLARNA_VIEW_DATA"; private static final String KLARNA_RESPONSE_PAGE = "pages/klarna/klarnaResponseContentPage"; + private static final Date BIRTHDAY_DATE_VALUE = new Date(1990, Calendar.MAY, 17); @Spy @InjectMocks @@ -121,6 +126,8 @@ public class WorldpayPaymentMethodCheckoutStepControllerTest { private AdditionalAuthInfo additionalAuthInfoMock; @Mock private CMSPreviewService cmsPreviewServiceMock; + @Mock + private WorldpayCartFacade worldpayCartFacadeMock; @Before public void setUp() throws Exception { @@ -141,6 +148,8 @@ public void setUp() throws Exception { when(worldpayAdditionalInfoFacadeMock.createWorldpayAdditionalInfoData(httpServletRequestMock)).thenReturn(worldpayAdditionalInfoDataMock); when(siteConfigServiceMock.getBoolean(HOP_DEBUG_MODE_CONFIG, false)).thenReturn(false); when(worldpayAddonEndpointServiceMock.getHostedOrderPostPage()).thenReturn(HOSTED_ORDER_PAGE); + when(modelMock.asMap().get(BIRTHDAY_DATE)).thenReturn(BIRTHDAY_DATE_VALUE); + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(true); } @Test @@ -159,6 +168,7 @@ public void testEnterStepForCard() throws CMSItemNotFoundException { verify(modelMock).addAttribute(HOP_DEBUG_MODE_PARAM, false); verify(paymentDataParametersMock, never()).put(eq(PREFERRED_PAYMENT_METHOD_PARAM), any()); assertEquals(HOSTED_ORDER_PAGE, result); + verify(worldpayAdditionalInfoDataMock).setDateOfBirth(BIRTHDAY_DATE_VALUE); } @Test diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayRedirectCheckoutStepControllerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayRedirectCheckoutStepControllerTest.java index aa87a813..3d086d84 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayRedirectCheckoutStepControllerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayRedirectCheckoutStepControllerTest.java @@ -2,6 +2,7 @@ import com.worldpay.core.services.APMConfigurationLookupService; import com.worldpay.facades.WorldpayCartFacade; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.forms.PaymentDetailsForm; import com.worldpay.forms.validation.PaymentDetailsFormValidator; import de.hybris.bootstrap.annotations.UnitTest; @@ -20,6 +21,10 @@ import org.springframework.validation.BindingResult; import org.springframework.web.servlet.mvc.support.RedirectAttributes; +import java.util.Calendar; +import java.util.Date; + +import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayDirectCheckoutStepController.BIRTHDAY_DATE; import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayPaymentMethodCheckoutStepController.*; import static com.worldpay.service.model.payment.PaymentType.ONLINE; import static java.lang.Boolean.FALSE; @@ -33,14 +38,14 @@ @RunWith(MockitoJUnitRunner.class) public class WorldpayRedirectCheckoutStepControllerTest { - @Spy - @InjectMocks - private WorldpayRedirectCheckoutStepController testObj = new WorldpayRedirectCheckoutStepController(); - private static final String BILLING_ERROR_VIEW = "billingErrorView"; private static final String BANK_CODE = "bankCode"; private static final String PAYMENT_METHOD = "paymentMethod"; + private static final Date BIRTHDAY_DATE_VALUE = new Date(1990, Calendar.MAY, 17); + @Spy + @InjectMocks + private WorldpayRedirectCheckoutStepController testObj = new WorldpayRedirectCheckoutStepController(); @Mock private PaymentDetailsForm paymentDetailsFormMock; @Mock @@ -59,6 +64,8 @@ public class WorldpayRedirectCheckoutStepControllerTest { private APMConfigurationLookupService apmConfigurationServiceMock; @Mock private WorldpayCartFacade worldpayCartFacadeMock; + @Mock + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacadeMock; @Before public void setUp() { @@ -69,12 +76,31 @@ public void setUp() { when(paymentDetailsFormMock.getSaveInAccount()).thenReturn(true); when(paymentDetailsFormMock.getPaymentMethod()).thenReturn(ONLINE.getMethodCode()); when(paymentDetailsFormMock.getBillingAddress()).thenReturn(addressFormMock); + when(paymentDetailsFormMock.getDateOfBirth()).thenReturn(BIRTHDAY_DATE_VALUE); + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(true); + } + + @Test + public void addPaymentDetails_WhenCustomerIsAnonymousAndBillingAddressIsDifferentFromShippingAddressAndWhenFSEnabled_ShouldSaveTheAddressAndAddTheDOBRedirectAttribute() throws CMSItemNotFoundException { + when(paymentDetailsFormMock.getUseDeliveryAddress()).thenReturn(FALSE); + when(userFacadeMock.isAnonymousUser()).thenReturn(TRUE); + + testObj.addPaymentDetails(modelMock, paymentDetailsFormMock, bindingResultMock, redirectAttrsMock); + + verify(paymentDetailsFormValidatorMock).validate(paymentDetailsFormMock, bindingResultMock); + verify(worldpayCartFacadeMock).resetDeclineCodeAndShopperBankOnCart(null); + verify(testObj).handleAndSaveAddresses(paymentDetailsFormMock); + + verify(redirectAttrsMock).addFlashAttribute(SAVE_PAYMENT_INFO, true); + verify(redirectAttrsMock).addFlashAttribute(PAYMENT_METHOD_PARAM, ONLINE.getMethodCode()); + verify(redirectAttrsMock).addFlashAttribute(BIRTHDAY_DATE, BIRTHDAY_DATE_VALUE); } @Test - public void addressShouldBeSavedIfCustomerIsAnonymousAndBillingAddressIsDifferentFromShippingAddress() throws CMSItemNotFoundException { + public void addPaymentDetails_WhenCustomerIsAnonymousAndBillingAddressIsDifferentFromShippingAddressAndWhenFSDisabled_ShouldSaveTheAddressAndNotAddTheDOBRedirectAttribute() throws CMSItemNotFoundException { when(paymentDetailsFormMock.getUseDeliveryAddress()).thenReturn(FALSE); when(userFacadeMock.isAnonymousUser()).thenReturn(TRUE); + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(false); testObj.addPaymentDetails(modelMock, paymentDetailsFormMock, bindingResultMock, redirectAttrsMock); @@ -84,6 +110,7 @@ public void addressShouldBeSavedIfCustomerIsAnonymousAndBillingAddressIsDifferen verify(redirectAttrsMock).addFlashAttribute(SAVE_PAYMENT_INFO, true); verify(redirectAttrsMock).addFlashAttribute(PAYMENT_METHOD_PARAM, ONLINE.getMethodCode()); + verify(redirectAttrsMock, never()).addFlashAttribute(BIRTHDAY_DATE, BIRTHDAY_DATE_VALUE); } @Test diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/forms/validation/CsePaymentDetailsFormValidatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/forms/validation/CsePaymentDetailsFormValidatorTest.java index 2f6e0d5f..a3867718 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/forms/validation/CsePaymentDetailsFormValidatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/forms/validation/CsePaymentDetailsFormValidatorTest.java @@ -1,7 +1,9 @@ package com.worldpay.forms.validation; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.forms.PaymentDetailsForm; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -26,6 +28,14 @@ public class CsePaymentDetailsFormValidatorTest { private PaymentDetailsForm paymentDetailsFormMock; @Mock private Errors errorsMock; + @Mock + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacadeMock; + + @Before + public void setUp() { + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(false); + when(paymentDetailsFormMock.isDobRequired()).thenReturn(false); + } @Test public void shouldNotAddErrorsOnTermsAndConditionsIfPaymentMethodIsOnline() throws Exception { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/forms/validation/PaymentDetailsFormValidatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/forms/validation/PaymentDetailsFormValidatorTest.java index e019a2ca..a0dae4dc 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/forms/validation/PaymentDetailsFormValidatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/forms/validation/PaymentDetailsFormValidatorTest.java @@ -1,6 +1,7 @@ package com.worldpay.forms.validation; import com.worldpay.core.services.APMConfigurationLookupService; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.forms.PaymentDetailsForm; import com.worldpay.model.WorldpayAPMConfigurationModel; import com.worldpay.service.apm.APMAvailabilityService; @@ -20,34 +21,21 @@ import org.mockito.verification.VerificationMode; import org.springframework.validation.Errors; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.CHECKOUT_ERROR_TERMS_NOT_ACCEPTED; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.FIELD_BILLING_ADDRESS_COUNTRY_ISO; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.FIELD_BILLING_ADDRESS_FIRST_NAME; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.FIELD_BILLING_ADDRESS_LAST_NAME; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.FIELD_BILLING_ADDRESS_LINE1; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.FIELD_BILLING_ADDRESS_POSTCODE; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.FIELD_BILLING_ADDRESS_TOWN_CITY; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.FIELD_PAYMENT_METHOD; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.FIELD_SHOPPER_BANK_CODE; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.GLOBAL_MISSING_DELIVERY_ADDRESS; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.WORLDPAY_PAYMENT_METHOD_INVALID; -import static com.worldpay.forms.validation.PaymentDetailsFormValidator.WORLDPAY_PAYMENT_METHOD_NO_SHOPPER_BANK_CODE; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import static com.worldpay.forms.validation.PaymentDetailsFormValidator.*; import static com.worldpay.service.model.payment.PaymentType.ONLINE; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; @UnitTest -@RunWith (MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class PaymentDetailsFormValidatorTest { private static final String APM_PAYMENT_METHOD = "apmPaymentMethod"; private static final String BANK_CODE = "bankCode"; + private static final String BIRTH_DAY_DATE_FORMAT = "dd/MM/yyyy"; @Spy @InjectMocks @@ -73,6 +61,8 @@ public class PaymentDetailsFormValidatorTest { private AddressData deliveryAddressMock; @Mock private CartData checkoutCartMock; + @Mock + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacadeMock; @Before public void setUp() { @@ -82,6 +72,8 @@ public void setUp() { when(checkoutFacadeMock.getCheckoutCart()).thenReturn(checkoutCartMock); when(checkoutCartMock.getDeliveryAddress()).thenReturn(deliveryAddressMock); when(paymentDetailsFormMock.isTermsCheck()).thenReturn(true); + when(paymentDetailsFormMock.isDobRequired()).thenReturn(true); + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(true); } @Test @@ -201,6 +193,44 @@ public void validateAddGlobalErrorWhenNoPaymentMethodIsSelectedAndValueIsNull() verify(errorsMock).reject(WORLDPAY_PAYMENT_METHOD_INVALID); } + @Test + public void validate_WhenFSIsEnabledAndBirthdayDateNull_ShouldAddTheError() { + when(paymentDetailsFormMock.getDateOfBirth()).thenReturn(null); + + testObj.validate(paymentDetailsFormMock, errorsMock); + + verify(errorsMock).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + + @Test + public void validate_WhenFSIsEnabledAndBirthdayDateNotInThePast_ShouldAddTheError() throws ParseException { + final SimpleDateFormat df = new SimpleDateFormat(BIRTH_DAY_DATE_FORMAT); + when(paymentDetailsFormMock.getDateOfBirth()).thenReturn(df.parse("21/10/2100")); + + testObj.validate(paymentDetailsFormMock, errorsMock); + + verify(errorsMock).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + + @Test + public void validate_WhenFSIsDisabledAndBirthdayDateNull_ShouldNotAddTheError() { + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(false); + when(paymentDetailsFormMock.getDateOfBirth()).thenReturn(null); + + testObj.validate(paymentDetailsFormMock, errorsMock); + + verify(errorsMock, never()).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + + @Test + public void validate_WhenFSIsEnabledAndBirthdayDateNullAndDobNotRequired_ShouldNotAddTheError() { + when(paymentDetailsFormMock.isDobRequired()).thenReturn(false); + when(paymentDetailsFormMock.getDateOfBirth()).thenReturn(null); + + testObj.validate(paymentDetailsFormMock, errorsMock); + + verify(errorsMock, never()).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } protected void verifyBillingAddressValidation(VerificationMode verificationMode) { verify(testObj, verificationMode).validateField(eq(errorsMock), eq(FIELD_BILLING_ADDRESS_FIRST_NAME), anyString()); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/interceptors/beforeview/WorldpayJsVariablesBeforeViewHandlerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/interceptors/beforeview/WorldpayJsVariablesBeforeViewHandlerTest.java index 2b7bb817..3d775111 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/interceptors/beforeview/WorldpayJsVariablesBeforeViewHandlerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/commonweb/testsrc/com/worldpay/interceptors/beforeview/WorldpayJsVariablesBeforeViewHandlerTest.java @@ -1,5 +1,6 @@ package com.worldpay.interceptors.beforeview; +import com.worldpay.service.payment.WorldpayFraudSightStrategy; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.acceleratorservices.config.SiteConfigService; import org.junit.Before; @@ -14,14 +15,21 @@ import javax.servlet.http.HttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; @UnitTest @RunWith(MockitoJUnitRunner.class) public class WorldpayJsVariablesBeforeViewHandlerTest { private static final int SECONDS = 2; + private static final String ORGANIZATION_ID_VALUE = "5fd9e78c09c50b2d408f6805"; + private static final String PROFILING_DOMAIN_PROD = "ddc.worldpay.com"; + private static final String PROFILING_DOMAIN_TEST = "ddc-test.worldpay.com"; private static final String HOP_DECLINE_MESSAGE_WAIT_TIMER_SECONDS = "hop.decline.message.wait.timer.seconds"; + private static final String WORLDPAY_CONFIG_ENVIRONMENT = "worldpay.config.environment"; + private static final String WORLDPAY_CONFIG_PROFILE_DOMAIN_PROD = "worldpay.config.profile.domain.prod"; + private static final String WORLDPAY_CONFIG_PROFILE_DOMAIN_TEST = "worldpay.config.profile.domain.test"; + private static final String WORLDPAY_CONFIG_MERCHANT_ORGANIZATION_ID = "worldpay.merchant.organization.id"; private static final String PAYMENT_STATUS = "paymentStatus"; private static final String VIEW_NAME = "viewName"; private static final String PAYMENT_VALUE = "payment value"; @@ -32,6 +40,8 @@ public class WorldpayJsVariablesBeforeViewHandlerTest { @Mock private SiteConfigService siteConfigServiceMock; @Mock + private WorldpayFraudSightStrategy worldpayFraudSightStrategyMock; + @Mock private HttpServletRequest requestMock; @Mock private HttpServletResponse responseMock; @@ -40,14 +50,55 @@ public class WorldpayJsVariablesBeforeViewHandlerTest { @Before public void setUp() { + when(worldpayFraudSightStrategyMock.isFraudSightEnabled()).thenReturn(true); when(siteConfigServiceMock.getInt(HOP_DECLINE_MESSAGE_WAIT_TIMER_SECONDS, SECONDS)).thenReturn(5); when(modelMock.getAttribute(PAYMENT_STATUS)).thenReturn(PAYMENT_VALUE); + when(siteConfigServiceMock.getProperty(WORLDPAY_CONFIG_ENVIRONMENT)).thenReturn("TEST"); + when(siteConfigServiceMock.getProperty(WORLDPAY_CONFIG_PROFILE_DOMAIN_PROD)).thenReturn(PROFILING_DOMAIN_PROD); + when(siteConfigServiceMock.getProperty(WORLDPAY_CONFIG_PROFILE_DOMAIN_TEST)).thenReturn(PROFILING_DOMAIN_TEST); + when(siteConfigServiceMock.getProperty(WORLDPAY_CONFIG_MERCHANT_ORGANIZATION_ID)).thenReturn(ORGANIZATION_ID_VALUE); + } + + @Test + public void beforeView_WhenTestEnvAndFraudSightEnabled_ShouldReturnTheViewNameAndSetFSProperties() { + final String result = testObj.beforeView(requestMock, responseMock, modelMock, VIEW_NAME); + + assertThat(result).isEqualTo(VIEW_NAME); + verify(siteConfigServiceMock).getProperty(WORLDPAY_CONFIG_PROFILE_DOMAIN_TEST); + verify(siteConfigServiceMock).getProperty(WORLDPAY_CONFIG_MERCHANT_ORGANIZATION_ID); + } + + @Test + public void beforeView_WhenTestProdAndFraudSightEnabled_ShouldReturnTheViewNameAndSetFSProperties() { + when(siteConfigServiceMock.getProperty(WORLDPAY_CONFIG_ENVIRONMENT)).thenReturn("PROD"); + + final String result = testObj.beforeView(requestMock, responseMock, modelMock, VIEW_NAME); + + assertThat(result).isEqualTo(VIEW_NAME); + verify(siteConfigServiceMock).getProperty(WORLDPAY_CONFIG_PROFILE_DOMAIN_PROD); + verify(siteConfigServiceMock).getProperty(WORLDPAY_CONFIG_MERCHANT_ORGANIZATION_ID); } @Test - public void beforeView_ShouldReturnTheViewName() { + public void beforeView_WhenTestEnvAndFraudSightDisabled_ShouldReturnTheViewName() { + when(worldpayFraudSightStrategyMock.isFraudSightEnabled()).thenReturn(false); + + final String result = testObj.beforeView(requestMock, responseMock, modelMock, VIEW_NAME); + + assertThat(result).isEqualTo(VIEW_NAME); + verify(siteConfigServiceMock, never()).getProperty(WORLDPAY_CONFIG_PROFILE_DOMAIN_TEST); + verify(siteConfigServiceMock, never()).getProperty(WORLDPAY_CONFIG_MERCHANT_ORGANIZATION_ID); + } + + @Test + public void beforeView_WhenTestProdAndFraudSightDisabled_ShouldReturnTheViewName() { + when(worldpayFraudSightStrategyMock.isFraudSightEnabled()).thenReturn(false); + when(siteConfigServiceMock.getProperty(WORLDPAY_CONFIG_ENVIRONMENT)).thenReturn("PROD"); + final String result = testObj.beforeView(requestMock, responseMock, modelMock, VIEW_NAME); assertThat(result).isEqualTo(VIEW_NAME); + verify(siteConfigServiceMock, never()).getProperty(WORLDPAY_CONFIG_PROFILE_DOMAIN_PROD); + verify(siteConfigServiceMock, never()).getProperty(WORLDPAY_CONFIG_MERCHANT_ORGANIZATION_ID); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/resources/localization/worldpayaddoncommons-locales_en.properties b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/resources/localization/worldpayaddoncommons-locales_en.properties index f20f49ff..4b643f10 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/resources/localization/worldpayaddoncommons-locales_en.properties +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/resources/localization/worldpayaddoncommons-locales_en.properties @@ -1,18 +1 @@ - -# put localizations of item types into this file -# Note that you can also add special locatizations which -# can be retrieved with the -# -# ...tools.localization.Localization.getLocalizedString(...) -# -# methods. -# -# syntax for type localizations: -# -# type..name=XY -# type...name=XY -# type..description=XY -# type...description=XY -# -# yourcustomlocalekey=value - +checkout.error.fraudSight.dob.mandatory = Date of birth is mandatory and must be in the past diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/resources/worldpayaddoncommons.build.number b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/resources/worldpayaddoncommons.build.number index b309915d..c8d7beff 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/resources/worldpayaddoncommons.build.number +++ b/hybris/bin/y-ext/ext-worldpay/worldpayaddoncommons/resources/worldpayaddoncommons.build.number @@ -1,11 +1,11 @@ #Ant properties -#Mon Jan 18 14:19:09 UTC 2021 -version.api=2011 +#Wed Sep 29 10:46:25 UTC 2021 +version.api=2105 vendor=hybris group.id=de.hybris.platform name=worldpayaddoncommons description=worldpayaddoncommons -builddate=20210118 1419 -releasedate=20201208 1801 -version=2011.1 +builddate=20210929 1046 +releasedate=20210721 0907 +version=2105.0 module.name=platform-module diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/.classpath b/hybris/bin/y-ext/ext-worldpay/worldpayapi/.classpath index d0ce2098..5ad02c04 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/.classpath +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/.classpath @@ -7,11 +7,21 @@ + + + + + + + + + + + - diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/buildcallbacks.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/buildcallbacks.xml index 181af8fd..c5eb99b1 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/buildcallbacks.xml +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/buildcallbacks.xml @@ -1,97 +1,34 @@ - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/ant-contrib-1.0b3.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/ant-contrib-1.0b3.jar new file mode 100644 index 00000000..06253766 Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/ant-contrib-1.0b3.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/istack-commons-runtime-4.0.0.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/istack-commons-runtime-4.0.0.jar new file mode 100644 index 00000000..66f9d42d Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/istack-commons-runtime-4.0.0.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/istack-commons-tools-4.0.0.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/istack-commons-tools-4.0.0.jar new file mode 100644 index 00000000..10cd4c08 Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/istack-commons-tools-4.0.0.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jakarta.activation-api-1.2.2.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jakarta.activation-api-1.2.2.jar new file mode 100644 index 00000000..3cc969d8 Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jakarta.activation-api-1.2.2.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jakarta.xml.bind-api-2.3.3.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jakarta.xml.bind-api-2.3.3.jar new file mode 100644 index 00000000..b8c7dc1e Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jakarta.xml.bind-api-2.3.3.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-api-2.3.1.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-api-2.3.1.jar new file mode 100644 index 00000000..45658654 Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-api-2.3.1.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-core-2.3.0.1.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-core-2.3.0.1.jar new file mode 100644 index 00000000..a5d3b65a Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-core-2.3.0.1.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-jxc-2.3.3.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-jxc-2.3.3.jar new file mode 100644 index 00000000..e104936d Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-jxc-2.3.3.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-runtime-2.3.3.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-runtime-2.3.3.jar new file mode 100644 index 00000000..f950209c Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-runtime-2.3.3.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-xjc-2.3.3.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-xjc-2.3.3.jar new file mode 100644 index 00000000..c0638b08 Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/jaxb-xjc-2.3.3.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/txw2-2.3.3.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/txw2-2.3.3.jar new file mode 100644 index 00000000..363dd1b6 Binary files /dev/null and b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/dtd-conversion/txw2-2.3.3.jar differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/worldpay-core-2.8.jar b/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/worldpay-core-2.8.jar deleted file mode 100644 index d366ffa7..00000000 Binary files a/hybris/bin/y-ext/ext-worldpay/worldpayapi/lib/worldpay-core-2.8.jar and /dev/null differ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/project.properties b/hybris/bin/y-ext/ext-worldpay/worldpayapi/project.properties index aab835b6..957b0403 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/project.properties +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/project.properties @@ -1,5 +1,5 @@ # Specifies the location of the spring context file putted automatically to the global platform application context. -worldpayapi.application-context = worldpayapi-spring.xml +worldpayapi.application-context = worldpayapi-spring.xml,worldpayfraudsighttest-spring.xml,worldpaylevel23test-spring.xml #WorldpayCreditCardTypesMap worldpay.creditCard.mappings.VISA-SSL = visa @@ -32,13 +32,6 @@ worldpay.creditCard.mappings.CARD-SSL = card worldpay.APM.minutes.before.inquiring.timeout = 15 worldpay.APM.days.before.stop.inquiring.timeout = 5 -worldpaymerchantconfig = worldpayMerchantConfiguration -worldpaymerchantconfig.electronics-spa = worldpayMerchantConfiguration -worldpaymerchantconfig.electronics = worldpayMerchantConfiguration -worldpaymerchantconfig.apparel-de = worldpayMerchantConfiguration -worldpaymerchantconfig.apparel-uk = worldpayMerchantConfiguration -worldpaymerchantconfig.powertools = worldpayMerchantConfiguration - worldpay.support.email.address = plugins@worldpay.com worldpay.support.email.display.name = Worldpay Support worldpay.support.email.subject = Support Information @@ -78,15 +71,6 @@ worldpay.merchant.token.enabled = false #spring.profiles.active=applepay worldpay.addon.version = a591c6d3 -worldpay.config.3dsecureflex.jwt.iss = 5bd9e0e4444dce153428c940 -worldpay.config.3dsecureflex.jwt.jwtmackey = fa2daee2-1fbb-45ff-4444-52805d5cd9e0 -worldpay.config.3dsecureflex.jwt.orgunitid = 5bd9b55e4444761ac0af1c80 -worldpay.config.3dsecureflex.jwt.alg = hs256 -worldpay.config.3dsecureflex.jwt.challengeurl = https://secure-test.worldpay.com/shopper/3ds/challenge.html -worldpay.config.3dsecureflex.jwt.ddcurl = https://secure-test.worldpay.com/shopper/3ds/ddc.html -worldpay.config.3dsecureflex.jwt.returnurl = /checkout/multi/worldpay/3dsecureflex/sop/response -worldpay.config.3dsecureflex.challengepreference = nopreference -worldpay.config.3dsecureflex.secondauthorisation.submit.url = /checkout/multi/worldpay/3dsecureflex/sop/response/autosubmit worldpay.config.successURL = /checkout/multi/worldpay/hop-response worldpay.config.pendingURL = /checkout/multi/worldpay/hop-pending @@ -98,3 +82,9 @@ worldpay.orderCode.encryption.key = Gr3hIZGUPpOG1aEpXH worldpay.restconfig.http.connectTimeout = 500 worldpay.restconfig.http.readTimeout = 1500 + +# Organization id to be moved after the merchant configuration refactoring +worldpay.merchant.organization.id = 5fd9e78c09c50b2d408f6805 + +worldpay.config.profile.domain.test = ddc-test.worldpay.com +worldpay.config.profile.domain.prod = ddc.worldpay.com diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/dtd/paymentService_v1.dtd b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/dtd/paymentService_v1.dtd new file mode 100644 index 00000000..505df33a --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/dtd/paymentService_v1.dtd @@ -0,0 +1,2896 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/dtd/paymentService_v1_wp_original.dtd b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/dtd/paymentService_v1_wp_original.dtd new file mode 100644 index 00000000..a4d706f9 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/dtd/paymentService_v1_wp_original.dtd @@ -0,0 +1,2895 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/localization/worldpayapi-locales_de.properties b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/localization/worldpayapi-locales_de.properties index f20f49ff..fb41bce4 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/localization/worldpayapi-locales_de.properties +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/localization/worldpayapi-locales_de.properties @@ -1,18 +1,19 @@ - -# put localizations of item types into this file -# Note that you can also add special locatizations which -# can be retrieved with the -# -# ...tools.localization.Localization.getLocalizedString(...) -# -# methods. -# -# syntax for type localizations: -# -# type..name=XY -# type...name=XY -# type..description=XY -# type...description=XY -# -# yourcustomlocalekey=value - + +# put localizations of item types into this file +# Note that you can also add special locatizations which +# can be retrieved with the +# +# ...tools.localization.Localization.getLocalizedString(...) +# +# methods. +# +# syntax for type localizations: +# +# type..name=XY +# type...name=XY +# type..description=XY +# type...description=XY +# +# yourcustomlocalekey=value + +type.WorldpayRiskScore.name = diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/localization/worldpayapi-locales_en.properties b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/localization/worldpayapi-locales_en.properties index 85cac4bc..8ac4ad7e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/localization/worldpayapi-locales_en.properties +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/localization/worldpayapi-locales_en.properties @@ -1,188 +1,356 @@ -type.WorldpayRiskScore.name = Worldpay risk score -type.WorldpayRiskScore.description = Risk score from worldpay. Contains either worldpay risk scores, or RiskGuardian scores if applicable -type.WorldpayRiskScore.code.name = code -type.WorldpayRiskScore.code.description = Unique identifier in hybris. -type.WorldpayRiskScore.value.name = Worldpay risk score -type.WorldpayRiskScore.value.description = Risk score from worldpay - not applicable if RiskGuardian is used. -type.WorldpayRiskScore.provider.name = Provider -type.WorldpayRiskScore.provider.description = The system used to screen the transaction (RiskGuardian or RiskManagement Service). -type.WorldpayRiskScore.id.name = Worldpay id -type.WorldpayRiskScore.id.description = Internal reference number in worldpay -type.WorldpayRiskScore.finalScore.name = Final score -type.WorldpayRiskScore.rgid.name = RiskGuardian id -type.WorldpayRiskScore.rgid.description = Internal reference number in RiskGuardian -type.WorldpayRiskScore.tScore.name = Transaction score -type.WorldpayRiskScore.tScore.description = RiskGuardian score applied to the transaction requested -type.WorldpayRiskScore.tRisk.name = Threshold score -type.WorldpayRiskScore.tRisk.description = Threshold score between 1-100 at the time of the transaction -type.WorldpayRiskScore.message.name = Message -type.WorldpayRiskScore.extendedResponse.name = Extended response - -type.Cart.shopperBankCode.name = Bank name -type.Cart.shopperBankCode.description = Bank chosen in the checkout for an APM through bank transfer - -type.PaymentInfo.worldpayOrderCode.name = Worldpay Order Code -type.PaymentInfo.worldpayOrderCode.description = Stores the Order Code sent to Worldpay -type.PaymentInfo.transactionIdentifier.name = Transaction Identifier -type.PaymentInfo.transactionIdentifier.description = Transaction Identifier for Stored Credentials - -type.PaymentTransaction.name = Payment transaction -type.PaymentTransaction.description = Payment transaction -type.PaymentTransaction.riskScore.name = Worldpay risk score -type.PaymentTransaction.riskScore.description = Risk score from worldpay. Contains either worldpay risk scores, or RiskGuardian scores if applicable -type.PaymentTransaction.apmOpen.name = APM in open state -type.PaymentTransaction.apmOpen.description = Indicates if the APM is Waiting for the asynchronous message from Worldpay -type.PaymentTransaction.worldpayBank.name = Bank name -type.PaymentTransaction.worldpayBank.description = Bank chosen in the checkout for an APM through bank transfer - -type.PaymentTransactionEntry.pending.name = Pending -type.PaymentTransactionEntry.pending.description = Indicates whether the transaction is pending processing at Worldpay -type.PaymentTransactionEntry.aavResponse.name = Worldpay AAV response -type.PaymentTransactionEntry.aavResponse.description = American Express Advanced Verification received from Worldpay. - -type.WorldpayPaymentPage.name = Worldpay Payment Page -type.WorldpayPaymentPage.description = The customer pays through Worldpay, the world's leading payment service provider. - - -type.worldpayapmconfigurationtocountrycountriescoll.name = Enabled countries -type.worldpayapmconfigurationtocountrycountriescoll.description = List of enabled countries for this APM - -typeworldpayapmconfigurationtocurrencycurrenciescoll.name = Enabled currencies -type.worldpayapmconfigurationtocurrencycurrenciescoll.description = List of enabled currencies for this APM - -type.apmauthorisationtype.name = Authorisation Type -type.apmauthorisationtype.description = Type of authorisation for the APM - -type.apmflowtype.name = Flow Type -type.apmflowtype.description = Type of interaction flow with the APM - -type.worldpayapmconfigurationtocountry.name = APM Countries -type.worldpayapmconfigurationtocountry.description = List of countries where the APM is applicable - -type.worldpayapmconfigurationtocurrency.name = APM Currencies -type.worldpayapmconfigurationtocurrency.description = List of currencies where the APM is applicable - -type.worldpayapmconfigurationtocurrencyrange.name = APM currency range -type.worldpayapmconfigurationtocurrencyrange.description = Currency range applicable to the APM - -type.worldpayapmconfiguration.name = Alternative Payment Method -type.worldpayapmconfiguration.description = Alternative Payment Method - -type.worldpayapmconfiguration.authorisationtype.name = Authorisation Type -type.worldpayapmconfiguration.authorisationtype.description = Type of Authorisation supported by the APM -type.worldpayapmconfiguration.code.name = Code -type.worldpayapmconfiguration.code.description = Worldpay APM code -type.worldpayapmconfiguration.countries.name = Countries -type.worldpayapmconfiguration.countries.description = List of countries where the APM is applicable -type.worldpayapmconfiguration.currencies.name = Currencies -type.worldpayapmconfiguration.currencies.description = List of currencies where the APM is applicable -type.worldpayapmconfiguration.currencyRanges.name = Currency ranges -type.worldpayapmconfiguration.currencyRanges.description = Currency range applicable to the APM -type.worldpayapmconfiguration.description.name = Description -type.worldpayapmconfiguration.description.description = Description -type.worldpayapmconfiguration.flowtype.name = Flow type -type.worldpayapmconfiguration.flowtype.description = Type of interaction flow with the APM -type.worldpayapmconfiguration.name.name = Name -type.worldpayapmconfiguration.name.description = Name of the Alternative Payment Method -type.worldpayapmconfiguration.bank.name = Bank Transfer -type.worldpayapmconfiguration.bank.description = This is a Bank Transfer APM -type.worldpayapmconfiguration.autocancelpendingtimeoutinminutes.name = Auto-cancel pending timeout in minutes -type.worldpayapmconfiguration.autocancelpendingtimeoutinminutes.description = Timeout in minutes before the order is auto-cancelled -type.worldpayapmconfiguration.automaticRefunds.name = Automatic Refund -type.worldpayapmconfiguration.automaticRefunds.description = This APM allows automatic refunds -type.worldpayapmconfiguration.bankTransferRefunds.name = Bank Transfer Refund -type.worldpayapmconfiguration.bankTransferRefunds.description = This APM needs to be refunded through Shopper Web Form. - -type.worldpaycurrencyrange.name = Currency range -type.worldpaycurrencyrange.description = Currency range - -type.worldpaycurrencyrange.currency.name = Currency -type.worldpaycurrencyrange.currency.description = Currency -type.worldpaycurrencyrange.max.name = Maximum -type.worldpaycurrencyrange.max.description = Maximum allowed amount of the currency -type.worldpaycurrencyrange.min.name = Minimum -type.worldpaycurrencyrange.min.description = Minimum allowed amount of the currency -type.worldpaycurrencyrange.worldpayapmconfiguration.name = APM -type.worldpaycurrencyrange.worldpayapmconfiguration.description = APM - -type.country.worldpayapmconfiguration.name = Alternative Payment Method -type.country.worldpayapmconfiguration.description = Alternative Payment Method - -type.currency.worldpayapmconfiguration.name = Alternative Payment Method -type.currency.worldpayapmconfiguration.description = Alternative Payment Method - -type.worldpayapmpaymentinfo.name = Worldpay APM Payment Info -type.worldpayapmpaymentinfo.description = Worldpay APM Payment Info -type.worldpayapmpaymentinfo.apmconfiguration.name = APM Configuration -type.worldpayapmpaymentinfo.apmconfiguration.description = Worldpay APM Configuration -type.worldpayapmpaymentinfo.timeoutdate.name = Timeout Date -type.worldpayapmpaymentinfo.timeoutdate.description = Timeout Date -type.worldpayapmpaymentinfo.subscriptionId.name = Payment Token -type.worldpayapmpaymentinfo.subscriptionId.description = Payment Token -type.worldpayapmpaymentinfo.obfuscatedCardNumber.name = Obfuscated Card Number -type.WorldpayAPMPaymentInfo.klarnaPaymentType.name = Klarna Payment Type -type.WorldpayAPMPaymentInfo.klarnaPaymentType.type = Klarna Payment Type -type.WorldpayAPMPaymentInfo.expiryMonth.name = Card expiry month -type.WorldpayAPMPaymentInfo.expiryYear.name = Card expiry year - -type.paymentinfo.paymenttype.name = Payment type -type.paymentinfo.paymenttype.description = Payment type -type.paymentinfo.isApm.name = Is APM -type.paymentinfo.isApm.description = Shows if the payment was made through an APM or not -type.paymentinfo.authenticatedShopperID.name = Authenticated Shopper Id -type.paymentinfo.authenticatedShopperID.description = Contains a unique user reference to the customer -type.paymentinfo.eventReference.name = Token Event Reference -type.paymentinfo.eventReference.description = Identifier used to match the token to a transaction -type.paymentinfo.expiryDate.name = Token Expiry Date -type.paymentinfo.expiryDate.description = Token Expiry Date -type.paymentinfo.merchantId.name = Merchant id -type.paymentinfo.merchantId.description = Merchant id - -type.OrderStatus.PAYMENT_PENDING.name = Pending payment notification -orderStatusDisplay.PAYMENT_PENDING = Awaiting Payment - -type.WorldpayAavResponse.name = Worldpay AAV response -type.WorldpayAavResponse.description = American Express Advanced Verification received from Worldpay. - -type.WorldpayAavResponse.code.name = code -type.WorldpayAavResponse.code.description = Unique identifier in hybris -type.WorldpayAavResponse.aavAddressResultCode.name = AAV Address Result Code -type.WorldpayAavResponse.aavAddressResultCode.description = American Express Advanced Verification addressResultCode received from Worldpay -type.WorldpayAavResponse.aavCardholderNameResultCode.name = AAV Cardholder Name Result Code -type.WorldpayAavResponse.aavCardholderNameResultCode.description = American Express Advanced Verification cardholderNameResultCode received from Worldpay -type.WorldpayAavResponse.aavEmailResultCode.name = AAV Email Result Code -type.WorldpayAavResponse.aavEmailResultCode.description = American Express Advanced Verification emailResultCode received from Worldpay -type.WorldpayAavResponse.aavPostcodeResultCode.name = AAV Postcode Result Code -type.WorldpayAavResponse.aavPostcodeResultCode.description = American Express Advanced Verification postcodeResultCode received from Worldpay -type.WorldpayAavResponse.aavTelephoneResultCode.name = AAV Telephone Result Code -type.WorldpayAavResponse.aavTelephoneResultCode.description = American Express Advanced Verification telephoneResultCode received from Worldpay - -type.WorldpayBankConfiguration.name = Worldpay Bank Configurations -type.WorldpayBankConfiguration.description = Contains the banks used in the Bank Transfer APMs. - -type.WorldpayBankConfiguration.code.name = Bank code -type.WorldpayBankConfiguration.code.description = Represents the bank code -type.WorldpayBankConfiguration.apm.name = APM related to the bank. -type.WorldpayBankConfiguration.apm.description = The APM has a list of banks -type.WorldpayBankConfiguration.name.name = Name of the bank -type.WorldpayBankConfiguration.name.description = Name of the bank -type.WorldpayBankConfiguration.description.name = Bank description -type.WorldpayBankConfiguration.description.description = Bank description -type.WorldpayBankConfiguration.active.name = Active -type.WorldpayBankConfiguration.active.description = Bank is active. And can be chosen on the front-end. - -type.ReturnRequest.paymentTransactionEntry.name = Payment Transaction Entry -type.ReturnRequest.paymentTransactionEntry.description = Payment transaction entry representing the refund. - -type.GooglePayPaymentInfo.name = Payment info for transactions made using Google Pay -type.GooglePayPaymentInfo.protocolVersion.name = Protocol version -type.GooglePayPaymentInfo.protocolVersion.description = Encryption protocol -type.GooglePayPaymentInfo.signature.name = Signature -type.GooglePayPaymentInfo.signature.description = Signature of the encrypted signed message -type.GooglePayPaymentInfo.signedMessage.name = Signed Message -type.GooglePayPaymentInfo.signedMessage.description = Contains the information for Worldpay to decrypt. - -type.ApplePayPaymentInfo.name = ApplePay payment info for transactions made using Apple Pay -type.ApplePayPaymentInfo.transactionId.name = Transaction ID -type.ApplePayPaymentInfo.version.name = Version +type.WorldpayRiskScore.name = Worldpay risk score +type.WorldpayRiskScore.description = Risk score from worldpay. Contains either worldpay risk scores, or RiskGuardian scores if applicable +type.WorldpayRiskScore.code.name = code +type.WorldpayRiskScore.code.description = Unique identifier in hybris. +type.WorldpayRiskScore.value.name = Worldpay risk score +type.WorldpayRiskScore.value.description = Risk score from worldpay - not applicable if RiskGuardian is used. +type.WorldpayRiskScore.provider.name = Provider +type.WorldpayRiskScore.provider.description = The system used to screen the transaction (RiskGuardian or RiskManagement Service). +type.WorldpayRiskScore.id.name = Worldpay id +type.WorldpayRiskScore.id.description = Internal reference number in worldpay +type.WorldpayRiskScore.finalScore.name = Final score +type.WorldpayRiskScore.rgid.name = RiskGuardian id +type.WorldpayRiskScore.rgid.description = Internal reference number in RiskGuardian +type.WorldpayRiskScore.tScore.name = Transaction score +type.WorldpayRiskScore.tScore.description = RiskGuardian score applied to the transaction requested +type.WorldpayRiskScore.tRisk.name = Threshold score +type.WorldpayRiskScore.tRisk.description = Threshold score between 1-100 at the time of the transaction +type.WorldpayRiskScore.message.name = Message +type.WorldpayRiskScore.extendedResponse.name = Extended response +type.Cart.shopperBankCode.name = Bank name +type.Cart.shopperBankCode.description = Bank chosen in the checkout for an APM through bank transfer +type.Cart.threeDSChallengeSession.name = 3DS Challenge session data +type.Cart.threeDSChallengeSession.description = 3DS Challenge session data + +type.Product.commodityCode.name = Commodity code for the product +type.Product.commodityCode.description = Commodity code defined by the National Institute of Governmental Purchasing + +type.AbstractOrder.isPrimeRouteAuth.name = Authorised with Prime Routing? +type.AbstractOrder.isPrimeRouteAuth.description = Determines if the transaction is done using Prime Routing +type.AbstractOrder.requestsPayload.name = Worldpay Requests Payload +type.AbstractOrder.requestsPayload.description = Worldpay Requests Payload +type.AbstractOrder.responsesPayload.name = Worldpay Responses Payload +type.AbstractOrder.responsesPayload.description = Worldpay Responses Payload + +type.Payload.name = Worldpay Payment Payload +type.Payload.description = Worldpay Payment Payload +type.Payload.payload.name = Request/Response Payload +type.Payload.payload.description = Request/Response Payload + +type.PaymentInfo.worldpayOrderCode.name = Worldpay Order Code +type.PaymentInfo.worldpayOrderCode.description = Stores the Order Code sent to Worldpay +type.PaymentInfo.transactionIdentifier.name = Transaction Identifier +type.PaymentInfo.transactionIdentifier.description = Transaction Identifier for Stored Credentials + +type.PaymentTransaction.name = Payment transaction +type.PaymentTransaction.description = Payment transaction +type.PaymentTransaction.riskScore.name = Worldpay risk score +type.PaymentTransaction.riskScore.description = Risk score from worldpay. Contains either worldpay risk scores, or RiskGuardian scores if applicable +type.PaymentTransaction.fraudSight.name = Worldpay Fraud Sight +type.PaymentTransaction.fraudSight.description = Fraud Sight from worldpay. Contains worldpay fraud score, the risk decision and the reasons +type.PaymentTransaction.apmOpen.name = APM in open state +type.PaymentTransaction.apmOpen.description = Indicates if the APM is Waiting for the asynchronous message from Worldpay +type.PaymentTransaction.worldpayBank.name = Bank name +type.PaymentTransaction.worldpayBank.description = Bank chosen in the checkout for an APM through bank transfer + +type.PaymentTransactionEntry.pending.name = Pending +type.PaymentTransactionEntry.pending.description = Indicates whether the transaction is pending processing at Worldpay +type.PaymentTransactionEntry.aavResponse.name = Worldpay AAV response +type.PaymentTransactionEntry.aavResponse.description = American Express Advanced Verification received from Worldpay. + +type.WorldpayPaymentPage.name = Worldpay Payment Page +type.WorldpayPaymentPage.description = The customer pays through Worldpay, the world's leading payment service provider. + + +type.worldpayapmconfigurationtocountrycountriescoll.name = Enabled countries +type.worldpayapmconfigurationtocountrycountriescoll.description = List of enabled countries for this APM + +typeworldpayapmconfigurationtocurrencycurrenciescoll.name = Enabled currencies +type.worldpayapmconfigurationtocurrencycurrenciescoll.description = List of enabled currencies for this APM + +type.apmauthorisationtype.name = Authorisation Type +type.apmauthorisationtype.description = Type of authorisation for the APM + +type.apmflowtype.name = Flow Type +type.apmflowtype.description = Type of interaction flow with the APM + +type.worldpayapmconfigurationtocountry.name = APM Countries +type.worldpayapmconfigurationtocountry.description = List of countries where the APM is applicable + +type.worldpayapmconfigurationtocurrency.name = APM Currencies +type.worldpayapmconfigurationtocurrency.description = List of currencies where the APM is applicable + +type.worldpayapmconfigurationtocurrencyrange.name = APM currency range +type.worldpayapmconfigurationtocurrencyrange.description = Currency range applicable to the APM + +type.worldpayapmconfiguration.name = Alternative Payment Method +type.worldpayapmconfiguration.description = Alternative Payment Method + +type.worldpayapmconfiguration.authorisationtype.name = Authorisation Type +type.worldpayapmconfiguration.authorisationtype.description = Type of Authorisation supported by the APM +type.worldpayapmconfiguration.code.name = Code +type.worldpayapmconfiguration.code.description = Worldpay APM code +type.worldpayapmconfiguration.countries.name = Countries +type.worldpayapmconfiguration.countries.description = List of countries where the APM is applicable +type.worldpayapmconfiguration.currencies.name = Currencies +type.worldpayapmconfiguration.currencies.description = List of currencies where the APM is applicable +type.worldpayapmconfiguration.currencyRanges.name = Currency ranges +type.worldpayapmconfiguration.currencyRanges.description = Currency range applicable to the APM +type.worldpayapmconfiguration.description.name = Description +type.worldpayapmconfiguration.description.description = Description +type.worldpayapmconfiguration.flowtype.name = Flow type +type.worldpayapmconfiguration.flowtype.description = Type of interaction flow with the APM +type.worldpayapmconfiguration.name.name = Name +type.worldpayapmconfiguration.name.description = Name of the Alternative Payment Method +type.worldpayapmconfiguration.bank.name = Bank Transfer +type.worldpayapmconfiguration.bank.description = This is a Bank Transfer APM +type.worldpayapmconfiguration.autocancelpendingtimeoutinminutes.name = Auto-cancel pending timeout in minutes +type.worldpayapmconfiguration.autocancelpendingtimeoutinminutes.description = Timeout in minutes before the order is auto-cancelled +type.worldpayapmconfiguration.automaticRefunds.name = Automatic Refund +type.worldpayapmconfiguration.automaticRefunds.description = This APM allows automatic refunds +type.worldpayapmconfiguration.bankTransferRefunds.name = Bank Transfer Refund +type.worldpayapmconfiguration.bankTransferRefunds.description = This APM needs to be refunded through Shopper Web Form. + +type.worldpaycurrencyrange.name = Currency range +type.worldpaycurrencyrange.description = Currency range + +type.worldpaycurrencyrange.currency.name = Currency +type.worldpaycurrencyrange.currency.description = Currency +type.worldpaycurrencyrange.max.name = Maximum +type.worldpaycurrencyrange.max.description = Maximum allowed amount of the currency +type.worldpaycurrencyrange.min.name = Minimum +type.worldpaycurrencyrange.min.description = Minimum allowed amount of the currency +type.worldpaycurrencyrange.worldpayapmconfiguration.name = APM +type.worldpaycurrencyrange.worldpayapmconfiguration.description = APM + +type.country.worldpayapmconfiguration.name = Alternative Payment Method +type.country.worldpayapmconfiguration.description = Alternative Payment Method + +type.currency.worldpayapmconfiguration.name = Alternative Payment Method +type.currency.worldpayapmconfiguration.description = Alternative Payment Method + +type.worldpayapmpaymentinfo.name = Worldpay APM Payment Info +type.worldpayapmpaymentinfo.description = Worldpay APM Payment Info +type.worldpayapmpaymentinfo.apmconfiguration.name = APM Configuration +type.worldpayapmpaymentinfo.apmconfiguration.description = Worldpay APM Configuration +type.worldpayapmpaymentinfo.timeoutdate.name = Timeout Date +type.worldpayapmpaymentinfo.timeoutdate.description = Timeout Date +type.worldpayapmpaymentinfo.subscriptionId.name = Payment Token +type.worldpayapmpaymentinfo.subscriptionId.description = Payment Token +type.worldpayapmpaymentinfo.obfuscatedCardNumber.name = Obfuscated Card Number +type.WorldpayAPMPaymentInfo.klarnaPaymentType.name = Klarna Payment Type +type.WorldpayAPMPaymentInfo.klarnaPaymentType.type = Klarna Payment Type +type.WorldpayAPMPaymentInfo.expiryMonth.name = Card expiry month +type.WorldpayAPMPaymentInfo.expiryYear.name = Card expiry year + +type.paymentinfo.paymenttype.name = Payment type +type.paymentinfo.paymenttype.description = Payment type +type.paymentinfo.isApm.name = Is APM +type.paymentinfo.isApm.description = Shows if the payment was made through an APM or not +type.paymentinfo.authenticatedShopperID.name = Authenticated Shopper Id +type.paymentinfo.authenticatedShopperID.description = Contains a unique user reference to the customer +type.paymentinfo.eventReference.name = Token Event Reference +type.paymentinfo.eventReference.description = Identifier used to match the token to a transaction +type.paymentinfo.expiryDate.name = Token Expiry Date +type.paymentinfo.expiryDate.description = Token Expiry Date +type.paymentinfo.merchantId.name = Merchant id +type.paymentinfo.merchantId.description = Merchant id + +type.OrderStatus.PAYMENT_PENDING.name = Pending payment notification +orderStatusDisplay.PAYMENT_PENDING = Awaiting Payment + +type.WorldpayAavResponse.name = Worldpay AAV response +type.WorldpayAavResponse.description = American Express Advanced Verification received from Worldpay. + +type.WorldpayAavResponse.code.name = code +type.WorldpayAavResponse.code.description = Unique identifier in hybris +type.WorldpayAavResponse.aavAddressResultCode.name = AAV Address Result Code +type.WorldpayAavResponse.aavAddressResultCode.description = American Express Advanced Verification addressResultCode received from Worldpay +type.WorldpayAavResponse.aavCardholderNameResultCode.name = AAV Cardholder Name Result Code +type.WorldpayAavResponse.aavCardholderNameResultCode.description = American Express Advanced Verification cardholderNameResultCode received from Worldpay +type.WorldpayAavResponse.aavEmailResultCode.name = AAV Email Result Code +type.WorldpayAavResponse.aavEmailResultCode.description = American Express Advanced Verification emailResultCode received from Worldpay +type.WorldpayAavResponse.aavPostcodeResultCode.name = AAV Postcode Result Code +type.WorldpayAavResponse.aavPostcodeResultCode.description = American Express Advanced Verification postcodeResultCode received from Worldpay +type.WorldpayAavResponse.aavTelephoneResultCode.name = AAV Telephone Result Code +type.WorldpayAavResponse.aavTelephoneResultCode.description = American Express Advanced Verification telephoneResultCode received from Worldpay + +type.WorldpayBankConfiguration.name = Worldpay Bank Configurations +type.WorldpayBankConfiguration.description = Contains the banks used in the Bank Transfer APMs. + +type.WorldpayBankConfiguration.code.name = Bank code +type.WorldpayBankConfiguration.code.description = Represents the bank code +type.WorldpayBankConfiguration.apm.name = APM related to the bank. +type.WorldpayBankConfiguration.apm.description = The APM has a list of banks +type.WorldpayBankConfiguration.name.name = Name of the bank +type.WorldpayBankConfiguration.name.description = Name of the bank +type.WorldpayBankConfiguration.description.name = Bank description +type.WorldpayBankConfiguration.description.description = Bank description +type.WorldpayBankConfiguration.active.name = Active +type.WorldpayBankConfiguration.active.description = Bank is active. And can be chosen on the front-end. + +type.ReturnRequest.paymentTransactionEntry.name = Payment Transaction Entry +type.ReturnRequest.paymentTransactionEntry.description = Payment transaction entry representing the refund. + +type.GooglePayPaymentInfo.name = Payment info for transactions made using Google Pay +type.GooglePayPaymentInfo.protocolVersion.name = Protocol version +type.GooglePayPaymentInfo.protocolVersion.description = Encryption protocol +type.GooglePayPaymentInfo.signature.name = Signature +type.GooglePayPaymentInfo.signature.description = Signature of the encrypted signed message +type.GooglePayPaymentInfo.signedMessage.name = Signed Message +type.GooglePayPaymentInfo.signedMessage.description = Contains the information for Worldpay to decrypt. + +type.ApplePayPaymentInfo.name = ApplePay payment info for transactions made using Apple Pay +type.ApplePayPaymentInfo.transactionId.name = Transaction ID +type.ApplePayPaymentInfo.version.name = Version + +### Localization for type BaseSite +type.BaseSite.webMerchantConfiguration.name = Web Merchant Configuration +type.BaseSite.webMerchantConfiguration.description = Merchant Configuration for Web uses +type.BaseSite.asmMerchantConfiguration.name = ASM Merchant Configuration +type.BaseSite.asmMerchantConfiguration.description = Merchant Configuration for ASM uses +type.BaseSite.replenishmentMerchantConfiguration.name = Replenishment Merchant Configuration +type.BaseSite.replenishmentMerchantConfiguration.description = Merchant Configuration for Replenishment uses +type.BaseSite.enableFS.name = Is FraudSight enabled? +type.BaseSite.enableFS.description = Determines whether the FraudSight is enabled +type.BaseSite.enablePR.name = Is Prime Routing enabled? +type.BaseSite.enablePR.description = Determines whether the Prime Routing is enabled +type.BaseSite.enableLevel2.name = Is Level 2 enabled? +type.BaseSite.enableLevel2.description = Determines whether the Level 2 is enabled +type.BaseSite.enableLevel3.name = Is Level 3 enabled? +type.BaseSite.enableLevel3.description = Determines whether the Level 3 is enabled + +### Localization for type WorldpayMerchantConfiguration +type.WorldpayMerchantConfiguration.name = Merchant Configuration +type.WorldpayMerchantConfiguration.description = Merchant Configuration for Worldpay +type.WorldpayMerchantConfiguration.identifier.name = Identifier +type.WorldpayMerchantConfiguration.identifier.description = Unique identifier for the merchant configuration +type.WorldpayMerchantConfiguration.code.name = Merchant Code +type.WorldpayMerchantConfiguration.code.description = Code for the merchant +type.WorldpayMerchantConfiguration.password.name = Password +type.WorldpayMerchantConfiguration.password.description = The valid password of your account +type.WorldpayMerchantConfiguration.macValidation.name = Is Mac Validation enabled? +type.WorldpayMerchantConfiguration.macValidation.description = Determines whether the Mac Validation is enabled +type.WorldpayMerchantConfiguration.macSecret.name = Mac Secret +type.WorldpayMerchantConfiguration.macSecret.description = Mac Secret provided in the Worldpay console +type.WorldpayMerchantConfiguration.csePublicKey.name = CSE Public Key +type.WorldpayMerchantConfiguration.csePublicKey.description = The account CSE Public Key +type.WorldpayMerchantConfiguration.installationId.name = Installation Id +type.WorldpayMerchantConfiguration.installationId.description = The merchant installation id +type.WorldpayMerchantConfiguration.statementNarrative.name = Statement Narrative +type.WorldpayMerchantConfiguration.statementNarrative.description = The statement narrative for the merchant +type.WorldpayMerchantConfiguration.orderContent.name = Order Content +type.WorldpayMerchantConfiguration.orderContent.description = The order content value +type.WorldpayMerchantConfiguration.applePayConfiguration.name = ApplePay Configuration +type.WorldpayMerchantConfiguration.applePayConfiguration.description = The configuration for ApplePay +type.WorldpayMerchantConfiguration.googlePayConfiguration.name = GooglePay Configuration +type.WorldpayMerchantConfiguration.googlePayConfiguration.description = The configuration for GooglePay +type.WorldpayMerchantConfiguration.threeDSFlexJsonWebTokenSettings.name = The 3DS2 Configuration +type.WorldpayMerchantConfiguration.threeDSFlexJsonWebTokenSettings.description = The configuration for 3DS2 +type.WorldpayMerchantConfiguration.threeDSFlexChallengePreference.name = 3DS Flex Challenge Preference +type.WorldpayMerchantConfiguration.threeDSFlexChallengePreference.description = The 3DS flex challenge preference +type.WorldpayMerchantConfiguration.excludedPaymentTypes.name = Excluded payment types +type.WorldpayMerchantConfiguration.excludedPaymentTypes.description = The excluded payment types +type.WorldpayMerchantConfiguration.includedPaymentTypes.name = Included payment types +type.WorldpayMerchantConfiguration.includedPaymentTypes.description = The included payment types +type.WorldpayMerchantConfiguration.cardAcceptorTaxID.name = Card Acceptor Tax ID for Level 2/3 Data +type.WorldpayMerchantConfiguration.cardAcceptorTaxID.description = Card Acceptor Tax ID for Level 2/3 Data + +### Localization for type WorldpayApplePayConfiguration +type.WorldpayApplePayConfiguration.name = ApplePay Configuration +type.WorldpayApplePayConfiguration.description = The Worldpay configuration for ApplePay +type.WorldpayApplePayConfiguration.identifier.name = Identifier +type.WorldpayApplePayConfiguration.identifier.description = Unique Identifier of ApplePay Configuration +type.WorldpayApplePayConfiguration.merchantId.name = Merchant identifier +type.WorldpayApplePayConfiguration.merchantId.description = The merchant identifier you registered with Apple for use with ApplePay. +type.WorldpayApplePayConfiguration.merchantName.name = Merchant Name +type.WorldpayApplePayConfiguration.merchantName.description = Merchant Name for ApplePay +type.WorldpayApplePayConfiguration.countryCode.name = Country Code +type.WorldpayApplePayConfiguration.countryCode.description = The merchant’s two-letter country code. +type.WorldpayApplePayConfiguration.supportedNetworks.name = Payment networks +type.WorldpayApplePayConfiguration.supportedNetworks.description = The payment networks supported by the merchant. +type.WorldpayApplePayConfiguration.merchantCapabilities.name = Payment capabilities +type.WorldpayApplePayConfiguration.merchantCapabilities.description = The payment capabilities, such as credit or debit, supported by the merchant. + +### Localization for type WorldpayGooglePayConfiguration +type.WorldpayGooglePayConfiguration.name = GooglePay Configuration +type.WorldpayGooglePayConfiguration.description = The Worldpay configuration for GooglePay +type.WorldpayGooglePayConfiguration.identifier.name = Identifier +type.WorldpayGooglePayConfiguration.identifier.description = Unique Identifier of GooglePay Configuration +type.WorldpayGooglePayConfiguration.merchantId.name = Merchant identifier +type.WorldpayGooglePayConfiguration.merchantId.description = The merchant identifier you registered with Google for use with GooglePay. +type.WorldpayGooglePayConfiguration.merchantName.name = Merchant Name +type.WorldpayGooglePayConfiguration.merchantName.description = Merchant Name for GooglePay +type.WorldpayGooglePayConfiguration.gatewayMerchantId.name = Gateway merchant ID +type.WorldpayGooglePayConfiguration.gatewayMerchantId.description = Site's gateway merchant identifier +type.WorldpayGooglePayConfiguration.environment.name = Environment +type.WorldpayGooglePayConfiguration.environment.description = Used to return chargeable payment methods when a valid Google merchant ID is specified and configured for the domain +type.WorldpayGooglePayConfiguration.cardType.name = Type +type.WorldpayGooglePayConfiguration.cardType.description = Describe your site's support for the CARD payment method +type.WorldpayGooglePayConfiguration.allowedCardNetworks.name = Allowed Card networks +type.WorldpayGooglePayConfiguration.allowedCardNetworks.description = Card networks supported by your site and your gateway +type.WorldpayGooglePayConfiguration.allowedAuthMethods.name = Allowed Card authentication methods +type.WorldpayGooglePayConfiguration.allowedAuthMethods.description = Card authentication methods supported by your site and your gateway + +### Localization for type WorldpayThreeDS2JsonWebTokenConfiguration +type.WorldpayThreeDS2JsonWebTokenConfiguration.name = 3DS2 Configuration +type.WorldpayThreeDS2JsonWebTokenConfiguration.description = The Worldpay configuration for 3DS2 +type.WorldpayThreeDS2JsonWebTokenConfiguration.identifier.name = Identifier +type.WorldpayThreeDS2JsonWebTokenConfiguration.identifier.description = Unique Identifier of ThreeDS2 Configuration +type.WorldpayThreeDS2JsonWebTokenConfiguration.iss.name = ISS +type.WorldpayThreeDS2JsonWebTokenConfiguration.iss.description = The issuer identifier +type.WorldpayThreeDS2JsonWebTokenConfiguration.jwtMacKey.name = JWT Mac Key +type.WorldpayThreeDS2JsonWebTokenConfiguration.jwtMacKey.description = The 3DS2 JWT mac key +type.WorldpayThreeDS2JsonWebTokenConfiguration.orgUnitId.name = Organisation unit id +type.WorldpayThreeDS2JsonWebTokenConfiguration.orgUnitId.description = The 3DS2 JWT organisation unit id +type.WorldpayThreeDS2JsonWebTokenConfiguration.alg.name = ALG +type.WorldpayThreeDS2JsonWebTokenConfiguration.alg.description = The 3DS2 JWT alg +type.WorldpayThreeDS2JsonWebTokenConfiguration.eventOriginDomain.name = Event Origin Domain +type.WorldpayThreeDS2JsonWebTokenConfiguration.eventOriginDomain.description = The domain origin as TEST, PROD, MOCK +type.WorldpayThreeDS2JsonWebTokenConfiguration.challengeUrl.name = Challenge Url +type.WorldpayThreeDS2JsonWebTokenConfiguration.challengeUrl.description = The 3DS2 JWT challenge url +type.WorldpayThreeDS2JsonWebTokenConfiguration.ddcUrl.name = DDC Url +type.WorldpayThreeDS2JsonWebTokenConfiguration.ddcUrl.description = The 3DS2 JWT ddc url +type.WorldpayThreeDS2JsonWebTokenConfiguration.flowReturnUrl.name = 3DS2 flex flow return url +type.WorldpayThreeDS2JsonWebTokenConfiguration.flowReturnUrl.description = The 3DS2 flex flow return url +type.WorldpayThreeDS2JsonWebTokenConfiguration.authSubmit.name = 3DS2 flex auth submit +type.WorldpayThreeDS2JsonWebTokenConfiguration.authSubmit.description = The 3DS2 flex auth submit +type.WorldpayThreeDS2JsonWebTokenConfiguration.occFlowReturnUrl.name = 3DS2 flex occ flow return url +type.WorldpayThreeDS2JsonWebTokenConfiguration.occFlowReturnUrl.description = The 3DS2 flex occ flow return url + +### Localization for type EnvironmentType +type.EnvironmentType.name = Environment +type.EnvironmentType.description = The Environment enumeration. + +# Localization for enum ApplePaySupportedNetworks +type.ApplePaySupportedNetworks.name = ApplePay payment networks +type.ApplePaySupportedNetworks.description = The payment networks supported by the merchant. + +# Localization for enum ApplePayMerchantCapabilities +type.ApplePayMerchantCapabilities.name = ApplePay payment capabilities +type.ApplePayMerchantCapabilities.description = The payment capabilities, such as credit or debit, supported by the merchant. + +# Localization for enum GooglePayCardNetworks +type.GooglePayCardNetworks.name = GooglePay Card networks supported +type.GooglePayCardNetworks.description = Card networks supported by your site and your gateway. + +# Localization for enum GooglePayCardAuthMethods +type.GooglePayCardAuthMethods.name = GooglePay Card authentication methods +type.GooglePayCardAuthMethods.description = Card authentication methods supported by your site and your gateway. + +# Localization for enum ChallengePreference +type.ChallengePreference.name = 3DS Flex Challenge Preference +type.ChallengePreference.description = The 3DS Flex Challenge Preference + +### Localization for type WorldpayFraudSight +type.WorldpayFraudSight.name = Worldpay Fraud Sight +type.WorldpayFraudSight.description = The Worldpay Fraud Sight information +type.WorldpayFraudSight.id.name = Id +type.WorldpayFraudSight.id.description = The unique identifier generated for the payment event +type.WorldpayFraudSight.score.name = Score +type.WorldpayFraudSight.score.description = The score returned by the FraudSight model +type.WorldpayFraudSight.message.name = Message +type.WorldpayFraudSight.message.description = FraudSight risk decision value +type.WorldpayFraudSight.reasonCodes.name = Reason code values +type.WorldpayFraudSight.reasonCodes.description = Risk reasons triggered by the FraudSight model diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/merchants/merchants-distribution.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/merchants/merchants-distribution.xml deleted file mode 100644 index 5b70e267..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/merchants/merchants-distribution.xml +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PAN_ONLY - - - - - - AMEX - DISCOVER - JCB - MASTERCARD - VISA - - - - - - - - - - - - - - - supportsCredit - supportsDebit - supports3DS - supportsEMV - - - - - amex - - - discover - - - - jcb - maestro - masterCard - - visa - - - - - - - - - - - - - - - diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/merchants/merchants.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/merchants/merchants.xml deleted file mode 100644 index 766618f0..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/merchants/merchants.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/schema/paymentService_v1.xsd b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/schema/paymentService_v1.xsd new file mode 100644 index 00000000..33dfd1d7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/schema/paymentService_v1.xsd @@ -0,0 +1,7032 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-appenders-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-appenders-spring.xml new file mode 100644 index 00000000..ed48d1eb --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-appenders-spring.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/applepay/worldpayapi-applepay-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-applepay-spring.xml similarity index 99% rename from hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/applepay/worldpayapi-applepay-spring.xml rename to hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-applepay-spring.xml index adcc081a..9747d45b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/applepay/worldpayapi-applepay-spring.xml +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-applepay-spring.xml @@ -3,6 +3,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" profile="applepay"> + @@ -17,4 +18,5 @@ + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-commands-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-commands-spring.xml new file mode 100644 index 00000000..a4536efd --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-commands-spring.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + de.hybris.platform.payment.commands.CaptureCommand + + + + + + + + + de.hybris.platform.payment.commands.PartialCaptureCommand + + + + + + + + + de.hybris.platform.payment.commands.VoidCommand + + + + + + + + + de.hybris.platform.payment.commands.FollowOnRefundCommand + + + + + + + + + de.hybris.platform.payment.commands.SubscriptionAuthorizationCommand + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/converters/worldpayapi-converters-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-converters-spring.xml similarity index 74% rename from hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/converters/worldpayapi-converters-spring.xml rename to hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-converters-spring.xml index 15f615db..d705b536 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/converters/worldpayapi-converters-spring.xml +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-converters-spring.xml @@ -7,7 +7,7 @@ - + @@ -17,7 +17,7 @@ - + @@ -40,6 +40,19 @@ + + + + + + + + + + + + + @@ -88,12 +101,12 @@ - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-daos-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-daos-spring.xml new file mode 100644 index 00000000..93e63d8f --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-daos-spring.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-facades-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-facades-spring.xml new file mode 100644 index 00000000..15a1c091 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-facades-spring.xml @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-factories-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-factories-spring.xml new file mode 100644 index 00000000..b75ff0f7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-factories-spring.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/gateway/worldpayapi-gateway-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-gateway-spring.xml similarity index 79% rename from hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/gateway/worldpayapi-gateway-spring.xml rename to hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-gateway-spring.xml index 1195ca9e..2b319d88 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/gateway/worldpayapi-gateway-spring.xml +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-gateway-spring.xml @@ -10,6 +10,8 @@ + + @@ -25,7 +27,10 @@ + class="com.worldpay.service.response.transform.impl.DefaultServiceResponseTransformerHelper"> + + + @@ -41,7 +46,9 @@ parent="abstractServiceResponseTransformer"/> + parent="abstractServiceResponseTransformer"> + + - - + + + + + @@ -89,6 +100,7 @@ + @@ -99,44 +111,55 @@ - + + - + + - + + + + + - + + + + + - + - + - + @@ -152,6 +175,7 @@ + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-handlers-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-handlers-spring.xml new file mode 100644 index 00000000..38d38d7f --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-handlers-spring.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-interceptors-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-interceptors-spring.xml new file mode 100644 index 00000000..cf8a4a3f --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-interceptors-spring.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-internal-converters-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-internal-converters-spring.xml new file mode 100644 index 00000000..17096cec --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-internal-converters-spring.xml @@ -0,0 +1,751 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/fulfilment/worldpayapi-order-actions-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-order-actions-spring.xml similarity index 100% rename from hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/fulfilment/worldpayapi-order-actions-spring.xml rename to hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-order-actions-spring.xml diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-services-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-services-spring.xml new file mode 100644 index 00000000..3270e99b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-services-spring.xml @@ -0,0 +1,364 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-strategies-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-strategies-spring.xml new file mode 100644 index 00000000..5897cd44 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/spring/worldpayapi-strategies-spring.xml @@ -0,0 +1,172 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/test/integration/worldpayAPMComponentTest.impex b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/test/integration/worldpayAPMComponentTest.impex new file mode 100644 index 00000000..3b599e51 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/test/integration/worldpayAPMComponentTest.impex @@ -0,0 +1,31 @@ +$catalog1-id = testCatalog1 +$catalog1-version = Online +$catalogversion1 = catalogversion(catalog(id), version)[unique=true, default=$catalog1-id:$catalog1-version] + +$catalog2-id = testCatalog2 +$catalog2-version = Online +$catalogversion2 = catalogversion(catalog(id), version)[unique=true, default=$catalog2-id:$catalog2-version] + +INSERT_UPDATE Country; isocode[unique = true]; name[lang = en] ; active + ; DE ; Germany ; true + ; US ; United States of America ; true + +INSERT_UPDATE Currency; isocode[unique = true]; name[lang = en]; active; base ; conversion; digits; symbol; ; + ; EUR ; Euro ; true ; true ; 1 ; 2 ; E ; ; + ; USD ; US Dollar ; true ; false ; 1,38 ; 2 ; $ ; ; + +INSERT_UPDATE Catalog; id[unique = true]; name[lang = en]; defaultCatalog + ; $catalog1-id ; $catalog1-id ; true + ; $catalog2-id ; $catalog2-id ; true + +INSERT_UPDATE CatalogVersion; catalog(id)[unique = true]; version[unique = true]; active + ; $catalog1-id ; $catalog1-version ; true + ; $catalog2-id ; $catalog2-version ; true + +INSERT_UPDATE WorldpayAPMConfiguration; code[unique = true]; name[lang = en]; description[lang = en]; bank[default = false]; currencies(isocode); countries(isocode); automaticRefunds[default = false]; bankTransferRefunds[default = false] + ; GIROPAY-SSL ; GIROPAY ; GiroPay ; ; EUR ; DE ; true ; + ; IDEAL-SSL ; iDeal ; iDeal ; true ; USD ; US ; true ; + +INSERT_UPDATE WorldpayAPMComponent; uid[unique = true]; $catalogversion1[unique = true]; name ; apmConfiguration(code) + ; giropayComponent ; ; "Giropay" ; GIROPAY-SSL + ; idealComponent ; ; "iDeal" ; IDEAL-SSL diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-beans.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-beans.xml index a2f74438..1e0173b3 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-beans.xml +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-beans.xml @@ -41,6 +41,7 @@ REFUND_WEBFORM_ISSUED SHOPPER_REDIRECTED FAILURE + VOIDED @@ -52,6 +53,7 @@ LEGACY_FLOW THREEDSFLEX_FLOW + NA FIRST @@ -86,6 +88,12 @@ ERROR_SPLIT_AUTH + + PHYSICAL + DISCOUNT + SHIPPING_FEE + + Used for recurring orders where no CartModel is provided @@ -131,6 +139,8 @@ + + @@ -376,4 +386,591 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-items.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-items.xml index 6fe134ed..4438bb5e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-items.xml +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-items.xml @@ -2,14 +2,22 @@ + + + + + + + @@ -23,6 +31,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -45,11 +126,39 @@ + + + + + + + + + + + + + + + + + + + + - Extending Abstract Order to hold the worldpay order code + Extending Abstract Order to hold the worldpay attributes @@ -59,6 +168,19 @@ Decline code of the transaction if it was refused + + + Determines if the transaction is done using Prime Routing + Boolean.FALSE + + + Worldpay api requests payload + + + + Worldpay api responses payload + + @@ -68,7 +190,7 @@ - Extending Cart to hold bank code + Extending Cart to worldpay attributes @@ -82,6 +204,42 @@ + + + + + + + HYBRIS.LONG_STRING + + + MEDIUMTEXT + + + CLOB + + + TEXT + + + NCLOB + + + + + + + + Extending Product to hold the commodity code + + + + Commodity code for the product + + + + @@ -270,6 +428,10 @@ + + + + @@ -282,6 +444,37 @@ + + + + + + + The unique identifier generated for the payment event + + + + + The score returned by the FraudSight model + + + + + FraudSight risk decision value + + + + + Risk reasons triggered by the FraudSight model + + + + + + + + + + + + + + + Unique Identifier of MerchantConfig + + + + + Code of MerchantConfig. + + + + The valid password of your account. + + + + + java.lang.Boolean.FALSE + Determines whether the Mac Validation is enabled. + + + + Mac Secret provided in the Worldpay console. + + + + + CLOB + + + nvarchar(max) + + + text + + + NCLOB + + + HYBRIS.LONG_STRING + + + The account CSE Public Key. + + + + The merchant installation id. + + + + The statement narrative for the merchant. + + + + + CLOB + + + nvarchar(max) + + + text + + + NCLOB + + + HYBRIS.LONG_STRING + + + The order content value. + + + + The configuration for ApplePay. + + + + The configuration for GooglePay. + + + + The configuration for 3DS2. + + + + The 3DS flex challenge preference. + + + + The excluded payment types. + + + + The included payment types. + + + + Card Acceptor Tax ID for Level 2/3 data + + + + + + + + + + + + + + + + + + Unique Identifier of ApplePay Configuration + + + + + Merchant identifier + + + + Merchant Name + + + + Country Code + + + + + + + + + + Unique Identifier of GooglePay Configuration + + + + + Merchant identifier + + + + Merchant Name + + + + Gateway merchant ID, which is provided by the gateway + + + + The Worldpay environment to which we is integrated. + test + + + + Describe your site's support for the CARD payment method + + + + + + + + + + Unique Identifier of ThreeDS2 Configuration + + + + + The 3DS2 jwt ISS + + + + The 3DS2 jwt mac key + + + + The 3DS2 jwt organisation unit id + + + + The 3DS2 jwt alg + TEST + + + + The domain origin as TEST, PROD, MOCK + + + + The 3DS2 jwt challenge url + + + + The 3DS2 jwt ddc url + + + + The 3DS2 flex flow return url + + + + The 3DS2 flex occ flow return url + + + + The 3DS2 flex auth submit + + + + + + + Extending BaseSite type with additional attributes. + + + + + java.lang.Boolean.FALSE + Enables the Prime Routing + + + Web Merchant Configuration + + + + ASM Merchant Configuration + + + + Replenishment Merchant Configuration + + + + + + java.lang.Boolean.FALSE + Enables the FraudSight + + + + + java.lang.Boolean.FALSE + Enables the Level 2 Data + + + + + java.lang.Boolean.FALSE + Enables the Level 3 Data + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-spring.xml index 59121782..dcaca32f 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-spring.xml +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi-spring.xml @@ -6,497 +6,20 @@ http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - de.hybris.platform.payment.commands.CaptureCommand - - - - - - - - - de.hybris.platform.payment.commands.PartialCaptureCommand - - - - - - - - - de.hybris.platform.payment.commands.VoidCommand - - - - - - - - de.hybris.platform.payment.commands.FollowOnRefundCommand - - - - - - - - - de.hybris.platform.payment.commands.SubscriptionAuthorizationCommand - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi.build.number b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi.build.number index d8005655..8ae4c4f0 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi.build.number +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayapi.build.number @@ -1,11 +1,11 @@ #Ant properties -#Mon Jan 18 14:19:09 UTC 2021 -version.api=2011 +#Wed Sep 29 10:46:25 UTC 2021 +version.api=2105 vendor=hybris group.id=de.hybris.platform name=worldpayapi description=worldpayapi -builddate=20210118 1419 -releasedate=20201208 1801 -version=2011.1 +builddate=20210929 1046 +releasedate=20210721 0907 +version=2105.0 module.name=platform-module diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayfraudsighttest-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayfraudsighttest-spring.xml new file mode 100644 index 00000000..cb52484b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpayfraudsighttest-spring.xml @@ -0,0 +1,13 @@ + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpaylevel23test-spring.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpaylevel23test-spring.xml new file mode 100644 index 00000000..34721111 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/resources/worldpaylevel23test-spring.xml @@ -0,0 +1,12 @@ + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/schemagen-build.xml b/hybris/bin/y-ext/ext-worldpay/worldpayapi/schemagen-build.xml new file mode 100644 index 00000000..5bade5f5 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/schemagen-build.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/attributehandlers/WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandler.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/attributehandlers/WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandler.java index 90022876..863390ff 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/attributehandlers/WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandler.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/attributehandlers/WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandler.java @@ -1,21 +1,28 @@ package com.worldpay.attributehandlers; -import com.worldpay.klarna.WorldpayKlarnaUtils; +import com.worldpay.service.payment.WorldpayKlarnaService; import de.hybris.platform.core.model.order.payment.WorldpayAPMPaymentInfoModel; import de.hybris.platform.servicelayer.model.attribute.DynamicAttributeHandler; public class WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandler implements DynamicAttributeHandler { - private final WorldpayKlarnaUtils worldpayKlarnaUtils; - public WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandler(final WorldpayKlarnaUtils worldpayKlarnaUtils) { - this.worldpayKlarnaUtils = worldpayKlarnaUtils; + private final WorldpayKlarnaService worldpayKlarnaService; + + public WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandler(final WorldpayKlarnaService worldpayKlarnaService) { + this.worldpayKlarnaService = worldpayKlarnaService; } + /** + * {@inheritDoc} + */ @Override public Boolean get(final WorldpayAPMPaymentInfoModel model) { - return worldpayKlarnaUtils.isKlarnaPaymentType(model.getApmConfiguration().getCode()); + return worldpayKlarnaService.isKlarnaPaymentType(model.getApmConfiguration().getCode()); } + /** + * {@inheritDoc} + */ @Override public void set(final WorldpayAPMPaymentInfoModel model, final Boolean paymentTypeCode) { throw new UnsupportedOperationException("Attribute isKlarna is not writable"); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayCaptureCommand.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayCaptureCommand.java index 69a9221d..76b19308 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayCaptureCommand.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayCaptureCommand.java @@ -4,23 +4,24 @@ import com.worldpay.exception.WorldpayException; import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.Date; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.Date; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.request.CaptureServiceRequest; import com.worldpay.service.response.CaptureServiceResponse; import com.worldpay.transaction.WorldpayPaymentTransactionService; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.ordersplitting.model.ConsignmentModel; import de.hybris.platform.payment.commands.CaptureCommand; import de.hybris.platform.payment.commands.request.CaptureRequest; import de.hybris.platform.payment.commands.result.CaptureResult; import de.hybris.platform.servicelayer.dto.converter.Converter; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.math.BigDecimal; -import java.text.MessageFormat; import java.time.LocalDateTime; import java.util.Currency; import java.util.List; @@ -38,7 +39,7 @@ *

*/ public class DefaultWorldpayCaptureCommand extends WorldpayCommand implements CaptureCommand { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayCaptureCommand.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayCaptureCommand.class); protected final Converter captureServiceResponseConverter; protected final WorldpayHybrisOrderService worldpayHybrisOrderService; @@ -64,7 +65,7 @@ public CaptureResult perform(final CaptureRequest request) { final CaptureServiceRequest captureRequest = buildCaptureServiceRequest(orderCode, amount, currency, getShippingInfosFromOrder(orderCode)); return capture(captureRequest); } catch (final WorldpayException e) { - LOG.error(MessageFormat.format("Error during capture of payment with ordercode [{0}] to merchant [{1}]", orderCode, merchantCode), e); + LOG.error("Error during capture of payment with ordercode [{}] to merchant [{}]", orderCode, merchantCode, e); return createErrorCaptureResult(); } } @@ -72,9 +73,9 @@ public CaptureResult perform(final CaptureRequest request) { protected List getShippingInfosFromOrder(final String orderCode) { final OrderModel orderModel = worldpayHybrisOrderService.findOrderByWorldpayOrderCode(orderCode); return orderModel.getConsignments().stream() - .map(ConsignmentModel::getTrackingID) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + .map(ConsignmentModel::getTrackingID) + .filter(Objects::nonNull) + .collect(Collectors.toList()); } private CaptureResult createErrorCaptureResult() { @@ -111,7 +112,7 @@ private CaptureResult capture(final CaptureServiceRequest captureRequest) throws */ private CaptureServiceRequest buildCaptureServiceRequest(final String worldpayOrderCode, final BigDecimal captureAmount, final Currency currency, final List trackingIds) throws WorldpayException { final Amount amount = getWorldpayOrderService().createAmount(currency, captureAmount.doubleValue()); - final Date date = new Date(LocalDateTime.now()); + final Date date = WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(LocalDateTime.now()); final MerchantInfo merchantInfo = getMerchantInfo(worldpayOrderCode); return CaptureServiceRequest.createCaptureRequest(merchantInfo, worldpayOrderCode, amount, date, trackingIds); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayFollowOnRefundCommand.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayFollowOnRefundCommand.java index 2df6b4f2..24459c85 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayFollowOnRefundCommand.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayFollowOnRefundCommand.java @@ -4,8 +4,8 @@ import com.worldpay.exception.WorldpayException; import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.request.RefundServiceRequest; import com.worldpay.service.response.RefundServiceResponse; @@ -14,13 +14,13 @@ import de.hybris.platform.payment.commands.request.FollowOnRefundRequest; import de.hybris.platform.payment.commands.result.RefundResult; import de.hybris.platform.servicelayer.dto.converter.Converter; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Currency; import static de.hybris.platform.payment.dto.TransactionStatus.ERROR; import static de.hybris.platform.payment.dto.TransactionStatusDetails.COMMUNICATION_PROBLEM; -import static java.text.MessageFormat.format; /** @@ -31,7 +31,7 @@ */ public class DefaultWorldpayFollowOnRefundCommand extends WorldpayCommand implements FollowOnRefundCommand { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayFollowOnRefundCommand.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayFollowOnRefundCommand.class); protected final Converter refundServiceResponseConverter; @@ -55,7 +55,7 @@ public RefundResult perform(final FollowOnRefundRequest request) { final RefundServiceRequest refundServiceRequest = buildRefundRequest(request.getMerchantTransactionCode(), orderCode, amount, merchantInfo); return refund(refundServiceRequest); } catch (final WorldpayException e) { - LOG.error(format("Exception raised while issuing a refundRequest: [{0}]", e.getMessage()), e); + LOG.error("Exception raised while issuing a refundRequest: [{}]", e.getMessage(), e); return createErrorRefundResult(); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayTokenisedAuthorizationCommand.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayTokenisedAuthorizationCommand.java index d9770f19..89f37bf9 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayTokenisedAuthorizationCommand.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayTokenisedAuthorizationCommand.java @@ -6,9 +6,9 @@ import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.*; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.token.Token; +import com.worldpay.data.*; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.token.Token; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.payment.request.WorldpayRequestService; import com.worldpay.service.request.AuthoriseRequestParameters; @@ -21,7 +21,8 @@ import de.hybris.platform.payment.commands.result.AuthorizationResult; import de.hybris.platform.payment.dto.BillingInfo; import de.hybris.platform.servicelayer.dto.converter.Converter; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Date; import java.util.Optional; @@ -40,7 +41,7 @@ */ public class DefaultWorldpayTokenisedAuthorizationCommand extends WorldpayCommand implements SubscriptionAuthorizationCommand { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayTokenisedAuthorizationCommand.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayTokenisedAuthorizationCommand.class); private static final String UNKNOWN_MERCHANT_CODE = "unknownMerchantCode"; protected final Converter worldpayBillingInfoAddressConverter; @@ -131,7 +132,8 @@ private DirectAuthoriseServiceRequest buildWorldpayRequest(final SubscriptionAut final BasicOrderInfo orderInfo = getWorldpayOrderService().createBasicOrderInfo(worldpayOrderCode, worldpayOrderCode, amount); final Session session = worldpayRequestService.createSession(additionalInfo); final Browser browser = worldpayRequestService.createBrowser(additionalInfo); - final Additional3DSData additional3DSData = new Additional3DSData(additionalInfo.getAdditional3DS2().getDfReferenceId()); + final Additional3DSData additional3DSData = new Additional3DSData(); + additional3DSData.setDfReferenceId(additionalInfo.getAdditional3DS2().getDfReferenceId()); final String customerEmail = additionalInfo.getCustomerEmail(); final String authenticatedShopperId = additionalInfo.getAuthenticatedShopperId(); final Shopper shopper = worldpayRequestService.createAuthenticatedShopper(customerEmail, authenticatedShopperId, session, browser); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayVoidCommand.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayVoidCommand.java index 86550e26..41668a0c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayVoidCommand.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/commands/impl/DefaultWorldpayVoidCommand.java @@ -1,19 +1,22 @@ - package com.worldpay.commands.impl; +import com.worldpay.core.services.WorldpayPrimeRoutingService; import com.worldpay.exception.WorldpayException; import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.request.CancelServiceRequest; +import com.worldpay.service.request.VoidSaleServiceRequest; import com.worldpay.service.response.CancelServiceResponse; +import com.worldpay.service.response.VoidSaleServiceResponse; import com.worldpay.transaction.WorldpayPaymentTransactionService; import de.hybris.platform.payment.commands.VoidCommand; import de.hybris.platform.payment.commands.request.VoidRequest; import de.hybris.platform.payment.commands.result.VoidResult; import de.hybris.platform.servicelayer.dto.converter.Converter; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static de.hybris.platform.payment.dto.TransactionStatus.ERROR; import static de.hybris.platform.payment.dto.TransactionStatusDetails.COMMUNICATION_PROBLEM; @@ -27,12 +30,20 @@ */ public class DefaultWorldpayVoidCommand extends WorldpayCommand implements VoidCommand { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayVoidCommand.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayVoidCommand.class); + protected final Converter voidServiceResponseConverter; + protected final WorldpayPrimeRoutingService worldpayPrimeRoutingService; - public DefaultWorldpayVoidCommand(final Converter voidServiceResponseConverter, final WorldpayMerchantInfoService worldpayMerchantInfoService, final WorldpayPaymentTransactionService worldpayPaymentTransactionService, final WorldpayOrderService worldpayOrderService, final WorldpayServiceGateway worldpayServiceGateway) { + public DefaultWorldpayVoidCommand(final Converter voidServiceResponseConverter, + final WorldpayMerchantInfoService worldpayMerchantInfoService, + final WorldpayPaymentTransactionService worldpayPaymentTransactionService, + final WorldpayOrderService worldpayOrderService, + final WorldpayServiceGateway worldpayServiceGateway, + final WorldpayPrimeRoutingService worldpayPrimeRoutingService) { super(worldpayMerchantInfoService, worldpayPaymentTransactionService, worldpayOrderService, worldpayServiceGateway); this.voidServiceResponseConverter = voidServiceResponseConverter; + this.worldpayPrimeRoutingService = worldpayPrimeRoutingService; } /** @@ -42,9 +53,31 @@ public DefaultWorldpayVoidCommand(final Converter> paymentConverters; + + public DefaultPaymentConverterStrategy(final Map> paymentConverters) { + this.paymentConverters = paymentConverters; + } + + /** + * {@inheritDoc} + */ + @Override + public Object convertPayment(final Payment payment) { + validateParameterNotNull(payment, "Payment must not be null!"); + + final PaymentType paymentType = PaymentType.getPaymentType(payment.getPaymentType()); + + if (paymentConverters.containsKey(paymentType)) { + return paymentConverters.get(paymentType).convert(payment); + } else { + throw new IllegalArgumentException("Payment converter with key [" + payment.getPaymentType() + "] not supported"); + } + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAPMComponentPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAPMComponentPopulator.java new file mode 100644 index 00000000..eed69910 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAPMComponentPopulator.java @@ -0,0 +1,43 @@ +package com.worldpay.converters.populators; + +import com.worldpay.data.apm.WorldpayAPMConfigurationData; +import com.worldpay.data.cms.WorldpayAPMComponentData; +import com.worldpay.model.WorldpayAPMComponentModel; +import com.worldpay.model.WorldpayAPMConfigurationModel; +import de.hybris.platform.cmsfacades.data.MediaData; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.core.model.media.MediaModel; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populates the {@link WorldpayAPMComponentData} from {@link WorldpayAPMComponentModel} + */ +public class WorldpayAPMComponentPopulator implements Populator { + + protected final Converter worldpayAPMConfigurationConverter; + protected final Converter mediaModelConverter; + + public WorldpayAPMComponentPopulator(final Converter worldpayAPMConfigurationConverter, + final Converter mediaModelConverter) { + this.worldpayAPMConfigurationConverter = worldpayAPMConfigurationConverter; + this.mediaModelConverter = mediaModelConverter; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final WorldpayAPMComponentModel source, + final WorldpayAPMComponentData target) throws ConversionException { + validateParameterNotNull(source, "source must not be null!"); + validateParameterNotNull(target, "target must not be null!"); + + target.setApmConfiguration(worldpayAPMConfigurationConverter.convert(source.getApmConfiguration())); + Optional.ofNullable(source.getMedia()).ifPresent(mediaModel -> target.setMedia(mediaModelConverter.convert(mediaModel))); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAPMConfigurationPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAPMConfigurationPopulator.java new file mode 100644 index 00000000..1c8f6136 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAPMConfigurationPopulator.java @@ -0,0 +1,38 @@ +package com.worldpay.converters.populators; + +import com.worldpay.data.apm.WorldpayAPMConfigurationData; +import com.worldpay.facades.WorldpayBankConfigurationFacade; +import com.worldpay.model.WorldpayAPMConfigurationModel; +import de.hybris.platform.converters.Populator; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populates the {@link WorldpayAPMConfigurationData} from {@link WorldpayAPMConfigurationModel} + */ +public class WorldpayAPMConfigurationPopulator implements Populator { + + protected final WorldpayBankConfigurationFacade worldpayBankConfigurationFacade; + + public WorldpayAPMConfigurationPopulator(final WorldpayBankConfigurationFacade worldpayBankConfigurationFacade) { + this.worldpayBankConfigurationFacade = worldpayBankConfigurationFacade; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final WorldpayAPMConfigurationModel source, final WorldpayAPMConfigurationData target) { + validateParameterNotNull(source, "source must not be null!"); + validateParameterNotNull(target, "target must not be null!"); + + target.setCode(source.getCode()); + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setAutoCancelPendingTimeoutInMinutes(source.getAutoCancelPendingTimeoutInMinutes()); + target.setBank(source.getBank()); + target.setAutomaticRefunds(source.getAutomaticRefunds()); + target.setBankTransferRefunds(source.getBankTransferRefunds()); + target.setBankConfigurations(worldpayBankConfigurationFacade.getBankConfigurationForAPMCode(source.getCode())); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAavResponsePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAavResponsePopulator.java index 793a70bb..b520f20e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAavResponsePopulator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAavResponsePopulator.java @@ -1,7 +1,7 @@ package com.worldpay.converters.populators; import com.worldpay.model.WorldpayAavResponseModel; -import com.worldpay.service.model.PaymentReply; +import com.worldpay.data.PaymentReply; import de.hybris.platform.converters.Populator; import de.hybris.platform.servicelayer.dto.converter.ConversionException; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAddressPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAddressPopulator.java index b6e684e6..0d577b99 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAddressPopulator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAddressPopulator.java @@ -1,6 +1,6 @@ package com.worldpay.converters.populators; -import com.worldpay.service.model.Address; +import com.worldpay.data.Address; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.model.user.AddressModel; import org.apache.commons.lang.StringEscapeUtils; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAuthorizationResultPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAuthorizationResultPopulator.java index 6b365d34..1f9b1b0c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAuthorizationResultPopulator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayAuthorizationResultPopulator.java @@ -1,23 +1,27 @@ package com.worldpay.converters.populators; import com.worldpay.service.WorldpayAuthorisationResultService; -import com.worldpay.service.model.ErrorDetail; -import com.worldpay.service.model.PaymentReply; +import com.worldpay.data.ErrorDetail; +import com.worldpay.data.PaymentReply; import com.worldpay.service.response.DirectAuthoriseServiceResponse; import de.hybris.platform.converters.Populator; import de.hybris.platform.payment.commands.result.AuthorizationResult; import de.hybris.platform.servicelayer.dto.converter.ConversionException; -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Required; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Populator that fills the necessary details on a {@link AuthorizationResult} with the information of a {@link DirectAuthoriseServiceResponse} */ public class WorldpayAuthorizationResultPopulator implements Populator { - private static final Logger LOG = Logger.getLogger(WorldpayAuthorizationResultPopulator.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayAuthorizationResultPopulator.class); - private WorldpayAuthorisationResultService worldpayAuthorisationResultService; + protected final WorldpayAuthorisationResultService worldpayAuthorisationResultService; + + public WorldpayAuthorizationResultPopulator(final WorldpayAuthorisationResultService worldpayAuthorisationResultService) { + this.worldpayAuthorisationResultService = worldpayAuthorisationResultService; + } /** * Populates the data from the {@link DirectAuthoriseServiceResponse} to a {@link AuthorizationResult} @@ -32,16 +36,11 @@ public void populate(final DirectAuthoriseServiceResponse source, final Authoriz LOG.warn("No PaymentReply in response from worldpay"); final ErrorDetail errorDetail = source.getErrorDetail(); if (errorDetail != null) { - LOG.error("Error message from Worldpay: " + errorDetail.getMessage()); + LOG.error("Error message from Worldpay: {}", errorDetail.getMessage()); } worldpayAuthorisationResultService.setAuthoriseResultAsError(target); } else { worldpayAuthorisationResultService.setAuthoriseResultByTransactionStatus(target, paymentReply.getAuthStatus(), source.getOrderCode()); } } - - @Required - public void setWorldpayAuthorisationResultService(final WorldpayAuthorisationResultService worldpayAuthorisationResultService) { - this.worldpayAuthorisationResultService = worldpayAuthorisationResultService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayBillingInfoAddressPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayBillingInfoAddressPopulator.java index 4cba5ac7..73cf9fbb 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayBillingInfoAddressPopulator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayBillingInfoAddressPopulator.java @@ -1,6 +1,6 @@ package com.worldpay.converters.populators; -import com.worldpay.service.model.Address; +import com.worldpay.data.Address; import de.hybris.platform.converters.Populator; import de.hybris.platform.payment.dto.BillingInfo; import de.hybris.platform.servicelayer.dto.converter.ConversionException; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayFraudSightResponsePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayFraudSightResponsePopulator.java new file mode 100644 index 00000000..9318a8d4 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpayFraudSightResponsePopulator.java @@ -0,0 +1,23 @@ +package com.worldpay.converters.populators; + +import com.worldpay.model.WorldpayFraudSightModel; +import com.worldpay.data.FraudSightResponse; +import de.hybris.platform.converters.Populator; + +/** + * Populator to transform a {@link FraudSightResponse} received from Worldpay to a {@link WorldpayFraudSightModel} + */ +public class WorldpayFraudSightResponsePopulator implements Populator { + + /** + * {@inheritDoc} + */ + @Override + public void populate(final FraudSightResponse fraudSightResponse, final WorldpayFraudSightModel worldpayFraudSight) { + worldpayFraudSight.setId(fraudSightResponse.getId()); + worldpayFraudSight.setScore(fraudSightResponse.getScore()); + worldpayFraudSight.setMessage(fraudSightResponse.getMessage()); + + worldpayFraudSight.setReasonCodes(fraudSightResponse.getReasonCodes()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpaySubscriptionAuthoriseResultPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpaySubscriptionAuthoriseResultPopulator.java index 8a333d86..958d415b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpaySubscriptionAuthoriseResultPopulator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/WorldpaySubscriptionAuthoriseResultPopulator.java @@ -3,25 +3,30 @@ import com.worldpay.commands.WorldpaySubscriptionAuthorizeResult; import com.worldpay.enums.order.AuthorisedStatus; import com.worldpay.service.WorldpayAuthorisationResultService; -import com.worldpay.service.model.ErrorDetail; -import com.worldpay.service.model.PaymentReply; +import com.worldpay.data.ErrorDetail; +import com.worldpay.data.PaymentReply; import com.worldpay.service.response.DirectAuthoriseServiceResponse; import de.hybris.platform.converters.Populator; import de.hybris.platform.servicelayer.dto.converter.ConversionException; -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Required; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Populator that fills the necessary details on a {@link WorldpaySubscriptionAuthorizeResult} with the information of a {@link DirectAuthoriseServiceResponse} */ public class WorldpaySubscriptionAuthoriseResultPopulator implements Populator { - private static final Logger LOG = Logger.getLogger(WorldpaySubscriptionAuthoriseResultPopulator.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpaySubscriptionAuthoriseResultPopulator.class); - private WorldpayAuthorisationResultService worldpayAuthorisationResultService; + protected final WorldpayAuthorisationResultService worldpayAuthorisationResultService; + + public WorldpaySubscriptionAuthoriseResultPopulator(final WorldpayAuthorisationResultService worldpayAuthorisationResultService) { + this.worldpayAuthorisationResultService = worldpayAuthorisationResultService; + } /** * Populates the data from the {@link DirectAuthoriseServiceResponse} to a {@link WorldpaySubscriptionAuthorizeResult} + * * @param source a {@link DirectAuthoriseServiceResponse} from Worldpay * @param target a {@link WorldpaySubscriptionAuthorizeResult} in hybris. * @throws ConversionException @@ -39,7 +44,7 @@ public void populate(final DirectAuthoriseServiceResponse source, final Worldpay LOG.warn("No PaymentReply in response from worldpay"); final ErrorDetail errorDetail = source.getErrorDetail(); if (errorDetail != null) { - LOG.error("Error message from Worldpay: " + errorDetail.getMessage()); + LOG.error("Error message from Worldpay: {}", errorDetail.getMessage()); } worldpayAuthorisationResultService.setAuthoriseResultAsError(target); } @@ -48,9 +53,4 @@ public void populate(final DirectAuthoriseServiceResponse source, final Worldpay worldpayAuthorisationResultService.setAuthoriseResultByTransactionStatus(target, status, orderCode); } } - - @Required - public void setWorldpayAuthorisationResultService(final WorldpayAuthorisationResultService worldpayAuthorisationResultService) { - this.worldpayAuthorisationResultService = worldpayAuthorisationResultService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/AddressPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/AddressPopulator.java new file mode 100644 index 00000000..7a0aaa15 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/AddressPopulator.java @@ -0,0 +1,86 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.internal.model.*; +import com.worldpay.data.Address; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import org.apache.commons.lang.StringUtils; + +import java.util.List; +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Address} with the information of a {@link Address} + */ +public class AddressPopulator implements Populator { + + /** + * Populates the data from the {@link Address} to a {@link com.worldpay.internal.model.Address} + * + * @param source a {@link Address} from Worldpay + * @param target a {@link com.worldpay.internal.model.Address} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final Address source, final com.worldpay.internal.model.Address target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + target.setFirstName(source.getFirstName()); + target.setLastName(source.getLastName()); + target.setPostalCode(source.getPostalCode()); + target.setCity(source.getCity()); + target.setState(source.getState()); + target.setCountryCode(source.getCountryCode()); + + final List addressDetails = target.getStreetOrHouseNameOrHouseNumberOrHouseNumberExtensionOrAddress1OrAddress2OrAddress3(); + + Optional.ofNullable(source.getStreet()).ifPresent(street -> { + final Street intStreet = new Street(); + intStreet.setvalue(street); + addressDetails.add(intStreet); + }); + + Optional.ofNullable(source.getHouseName()).ifPresent(houseName -> { + final HouseName intHouseName = new HouseName(); + intHouseName.setvalue(houseName); + addressDetails.add(intHouseName); + }); + + Optional.ofNullable(source.getHouseNumber()).ifPresent(houseNumber -> { + final HouseNumber intHouseNumber = new HouseNumber(); + intHouseNumber.setvalue(houseNumber); + addressDetails.add(intHouseNumber); + }); + + Optional.ofNullable(source.getHouseNumberExtension()).ifPresent(houseNumberExtension -> { + final HouseNumberExtension intHouseNumberExt = new HouseNumberExtension(); + intHouseNumberExt.setvalue(houseNumberExtension); + addressDetails.add(intHouseNumberExt); + }); + + Optional.ofNullable(source.getAddress1()).ifPresent(address1 -> { + final Address1 intAddress1 = new Address1(); + intAddress1.setvalue(address1); + addressDetails.add(intAddress1); + }); + + Optional.ofNullable(source.getAddress2()).ifPresent(address2 -> { + final Address2 intAddress2 = new Address2(); + intAddress2.setvalue(address2); + addressDetails.add(intAddress2); + }); + + Optional.ofNullable(source.getAddress3()).ifPresent(address3 -> { + final Address3 intAddress3 = new Address3(); + intAddress3.setvalue(address3); + addressDetails.add(intAddress3); + }); + + if (StringUtils.isNotBlank(source.getTelephoneNumber())) { + target.setTelephoneNumber(source.getTelephoneNumber()); + } + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/AmountPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/AmountPopulator.java new file mode 100644 index 00000000..ccea4d42 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/AmountPopulator.java @@ -0,0 +1,38 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Address; +import com.worldpay.data.Amount; +import com.worldpay.enums.DebitCreditIndicator; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Amount} with the information of a {@link Amount} + */ +public class AmountPopulator implements Populator { + + /** + * Populates the data from the {@link Amount} to a {@link com.worldpay.internal.model.Amount} + * + * @param source a {@link Amount} from Worldpay + * @param target a {@link com.worldpay.internal.model.Amount} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final Amount source, final com.worldpay.internal.model.Amount target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + target.setValue(source.getValue()); + target.setCurrencyCode(source.getCurrencyCode()); + target.setExponent(source.getExponent()); + + Optional.ofNullable(source.getDebitCreditIndicator()) + .map(DebitCreditIndicator::getCode) + .ifPresent(target::setDebitCreditIndicator); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/BasicOrderConvertersWrapper.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/BasicOrderConvertersWrapper.java new file mode 100644 index 00000000..320b2ce9 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/BasicOrderConvertersWrapper.java @@ -0,0 +1,25 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Address; +import com.worldpay.data.Amount; +import com.worldpay.data.Session; +import com.worldpay.data.Shopper; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +public class BasicOrderConvertersWrapper { + + protected final Converter internalAmountConverter; + protected final Converter internalShopperConverter; + protected final Converter internalAddressConverter; + protected final Converter internalSessionConverter; + + public BasicOrderConvertersWrapper(final Converter internalAmountConverter, + final Converter internalShopperConverter, + final Converter internalAddressConverter, + final Converter internalSessionConverter) { + this.internalAmountConverter = internalAmountConverter; + this.internalShopperConverter = internalShopperConverter; + this.internalAddressConverter = internalAddressConverter; + this.internalSessionConverter = internalSessionConverter; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/BranchSpecificExtensionPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/BranchSpecificExtensionPopulator.java new file mode 100644 index 00000000..b75ca4d6 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/BranchSpecificExtensionPopulator.java @@ -0,0 +1,40 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.BranchSpecificExtension; +import com.worldpay.data.Order; +import com.worldpay.data.Purchase; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.List; +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Order} with the information of a {@link Order}. + */ +public class BranchSpecificExtensionPopulator implements Populator { + + private final Converter internalPurchaseConverter; + + public BranchSpecificExtensionPopulator(final Converter internalPurchaseConverter) { + this.internalPurchaseConverter = internalPurchaseConverter; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final BranchSpecificExtension source, + final com.worldpay.internal.model.BranchSpecificExtension target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + final List targetList = target.getAirlineOrPurchaseOrHotelOrLodging(); + Optional.ofNullable(source.getPurchase()) + .map(internalPurchaseConverter::convertAll) + .ifPresent(targetList::addAll); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/BrowserPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/BrowserPopulator.java new file mode 100644 index 00000000..2d115eff --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/BrowserPopulator.java @@ -0,0 +1,34 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Browser; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Browser} with the information of a {@link Browser} + */ +public class BrowserPopulator implements Populator { + + /** + * Populates the data from the {@link Browser} to a {@link com.worldpay.internal.model.Browser} + * + * @param source a {@link Browser} from Worldpay + * @param target a {@link com.worldpay.internal.model.Browser} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final Browser source, final com.worldpay.internal.model.Browser target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setAcceptHeader(source.getAcceptHeader()); + target.setDeviceOS(source.getDeviceOS()); + target.setDeviceType(source.getDeviceType()); + target.setHttpAcceptLanguage(source.getHttpAcceptLanguage()); + target.setHttpReferer(source.getHttpReferer()); + target.setUserAgentHeader(source.getUserAgentHeader()); + + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/CustomNumericFieldsPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/CustomNumericFieldsPopulator.java new file mode 100644 index 00000000..cc6e9eb9 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/CustomNumericFieldsPopulator.java @@ -0,0 +1,69 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.CustomNumericFields; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.CustomNumericFields} with the information of a {@link CustomNumericFields} + */ +public class CustomNumericFieldsPopulator implements Populator { + + /** + * Populates the data from the {@link CustomNumericFields} to a {@link com.worldpay.internal.model.CustomNumericFields} + * + * @param source a {@link CustomNumericFields} from Worldpay + * @param target a {@link com.worldpay.internal.model.CustomNumericFields} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final CustomNumericFields source, + final com.worldpay.internal.model.CustomNumericFields target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getCustomNumericField1()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField1); + + Optional.ofNullable(source.getCustomNumericField2()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField2); + + Optional.ofNullable(source.getCustomNumericField3()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField3); + + Optional.ofNullable(source.getCustomNumericField4()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField4); + + Optional.ofNullable(source.getCustomNumericField5()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField5); + + Optional.ofNullable(source.getCustomNumericField6()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField6); + + Optional.ofNullable(source.getCustomNumericField7()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField7); + + Optional.ofNullable(source.getCustomNumericField8()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField8); + + Optional.ofNullable(source.getCustomNumericField9()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField9); + + Optional.ofNullable(source.getCustomNumericField10()) + .map(Number::toString) + .ifPresent(target::setCustomNumericField10); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/CustomStringFieldsPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/CustomStringFieldsPopulator.java new file mode 100644 index 00000000..1faefaaf --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/CustomStringFieldsPopulator.java @@ -0,0 +1,36 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.CustomStringFields; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.CustomStringFields} with the information of a {@link CustomStringFields} + */ +public class CustomStringFieldsPopulator implements Populator { + + /** + * Populates the data from the {@link CustomStringFields} to a {@link com.worldpay.internal.model.CustomStringFields} + * @param source a {@link CustomStringFields} from Worldpay + * @param target a {@link com.worldpay.internal.model.CustomStringFields} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final CustomStringFields source, final com.worldpay.internal.model.CustomStringFields target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setCustomStringField1(source.getCustomStringField1()); + target.setCustomStringField2(source.getCustomStringField2()); + target.setCustomStringField3(source.getCustomStringField3()); + target.setCustomStringField4(source.getCustomStringField4()); + target.setCustomStringField5(source.getCustomStringField5()); + target.setCustomStringField6(source.getCustomStringField6()); + target.setCustomStringField7(source.getCustomStringField7()); + target.setCustomStringField8(source.getCustomStringField8()); + target.setCustomStringField9(source.getCustomStringField9()); + target.setCustomStringField10(source.getCustomStringField10()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/DatePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/DatePopulator.java new file mode 100644 index 00000000..a48c0a71 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/DatePopulator.java @@ -0,0 +1,33 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Date; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Date} with the information of a {@link Date} + */ +public class DatePopulator implements Populator { + + /** + * Populates the data from the {@link Date} to a {@link com.worldpay.internal.model.Date} + * + * @param source a {@link Date} from Worldpay + * @param target a {@link com.worldpay.internal.model.Date} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final Date source, final com.worldpay.internal.model.Date target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + target.setYear(source.getYear()); + target.setMonth(source.getMonth()); + target.setDayOfMonth(source.getDayOfMonth()); + target.setHour(source.getHour()); + target.setMinute(source.getMinute()); + target.setSecond(source.getSecond()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/FraudSightDataPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/FraudSightDataPopulator.java new file mode 100644 index 00000000..c20fabe3 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/FraudSightDataPopulator.java @@ -0,0 +1,57 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.CustomNumericFields; +import com.worldpay.data.CustomStringFields; +import com.worldpay.data.FraudSightData; +import com.worldpay.data.ShopperFields; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.FraudSightData} with the information of a {@link FraudSightData} + */ +public class FraudSightDataPopulator implements Populator { + + protected final Converter internalShopperFieldsConverter; + protected final Converter internalCustomNumericFieldsConverter; + protected final Converter internalCustomStringFieldsConverter; + + public FraudSightDataPopulator(final Converter internalShopperFieldsConverter, + final Converter internalCustomNumericFieldsConverter, + final Converter internalCustomStringFieldsConverter) { + this.internalShopperFieldsConverter = internalShopperFieldsConverter; + this.internalCustomNumericFieldsConverter = internalCustomNumericFieldsConverter; + this.internalCustomStringFieldsConverter = internalCustomStringFieldsConverter; + } + + /** + * Populates the data from the {@link FraudSightData} to a {@link com.worldpay.internal.model.FraudSightData} + * + * @param source a {@link FraudSightData} from Worldpay + * @param target a {@link com.worldpay.internal.model.FraudSightData} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final FraudSightData source, + final com.worldpay.internal.model.FraudSightData target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getShopperFields()) + .map(internalShopperFieldsConverter::convert) + .ifPresent(target::setShopperFields); + + Optional.ofNullable(source.getCustomNumericFields()) + .map(internalCustomNumericFieldsConverter::convert) + .ifPresent(target::setCustomNumericFields); + + Optional.ofNullable(source.getCustomStringFields()) + .map(internalCustomStringFieldsConverter::convert) + .ifPresent(target::setCustomStringFields); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ItemPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ItemPopulator.java new file mode 100644 index 00000000..680b0741 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ItemPopulator.java @@ -0,0 +1,79 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.internal.model.*; +import com.worldpay.data.Amount; +import com.worldpay.data.Item; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Item} with the information of a {@link Item} + */ +public class ItemPopulator implements Populator { + + protected final Converter internalAmountConverter; + + public ItemPopulator(final Converter internalAmountConverter) { + this.internalAmountConverter = internalAmountConverter; + } + + /** + * Populates the data from the {@link Item} to a {@link com.worldpay.internal.model.Item} + * + * @param source a {@link Item} from Worldpay + * @param target a {@link com.worldpay.internal.model.Item} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final Item source, + final com.worldpay.internal.model.Item target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + target.setProductCode(source.getProductCode()); + target.setCommodityCode(source.getCommodityCode()); + target.setQuantity(source.getQuantity()); + target.setUnitOfMeasure(source.getUnitOfMeasure()); + + Optional.ofNullable(source.getDescription()).ifPresent(description -> { + final Description intDescription = new Description(); + intDescription.setvalue(description); + target.setDescription(intDescription); + }); + + Optional.ofNullable(source.getUnitCost()).ifPresent(unitCost -> { + final UnitCost intUnitCost = new UnitCost(); + intUnitCost.setAmount(internalAmountConverter.convert(unitCost)); + target.setUnitCost(intUnitCost); + }); + + Optional.ofNullable(source.getItemTotal()).ifPresent(itemTotal -> { + final ItemTotal intItemTotal = new ItemTotal(); + intItemTotal.setAmount(internalAmountConverter.convert(itemTotal)); + target.setItemTotal(intItemTotal); + }); + + Optional.ofNullable(source.getItemTotalWithTax()).ifPresent(itemTotalWithTax -> { + final ItemTotalWithTax intItemTotalWithTax = new ItemTotalWithTax(); + intItemTotalWithTax.setAmount(internalAmountConverter.convert(itemTotalWithTax)); + target.setItemTotalWithTax(intItemTotalWithTax); + }); + + Optional.ofNullable(source.getItemDiscountAmount()).ifPresent(itemDiscountAmount -> { + final ItemDiscountAmount intItemDiscountAmount = new ItemDiscountAmount(); + intItemDiscountAmount.setAmount(internalAmountConverter.convert(itemDiscountAmount)); + target.setItemDiscountAmount(intItemDiscountAmount); + }); + + Optional.ofNullable(source.getTaxAmount()).ifPresent(taxAmount -> { + final TaxAmount intTaxAmount = new TaxAmount(); + intTaxAmount.setAmount(internalAmountConverter.convert(taxAmount)); + target.setTaxAmount(intTaxAmount); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/LineItemPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/LineItemPopulator.java new file mode 100644 index 00000000..3cfb4538 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/LineItemPopulator.java @@ -0,0 +1,71 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.LineItem; +import com.worldpay.data.LineItemReference; +import com.worldpay.enums.lineItem.LineItemType; +import com.worldpay.internal.model.Discount; +import com.worldpay.internal.model.Physical; +import com.worldpay.internal.model.ShippingFee; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.List; +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.LineItem} with the information of a {@link LineItem} + */ +public class LineItemPopulator implements Populator { + + protected Converter internalReferenceConverter; + + public LineItemPopulator(final Converter internalReferenceConverter) { + this.internalReferenceConverter = internalReferenceConverter; + } + + /** + * Populates the data from the {@link LineItem} to a {@link com.worldpay.internal.model.LineItem} + * + * @param source a {@link LineItem} from Worldpay + * @param target a {@link com.worldpay.internal.model.LineItem} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final LineItem source, final com.worldpay.internal.model.LineItem target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setName(source.getName()); + target.setQuantity(source.getQuantity()); + target.setQuantityUnit(source.getQuantityUnit()); + target.setUnitPrice(source.getUnitPrice()); + target.setTaxRate(source.getTaxRate()); + target.setTotalAmount(source.getTotalAmount()); + target.setTotalTaxAmount(source.getTotalTaxAmount()); + target.setTotalDiscountAmount(source.getTotalDiscountAmount()); + + Optional.ofNullable(source.getLineItemReference()) + .map(internalReferenceConverter::convert) + .ifPresent(target::setReference); + + final List targetList = target.getPhysicalOrDiscountOrShippingFeeOrDigitalOrGiftCardOrSalesTaxTypeOrStoreCreditOrSurcharge(); + Optional.ofNullable(source.getLineItemType()) + .map(this::getIntLineItemType) + .ifPresent(targetList::add); + } + + private Object getIntLineItemType(final LineItemType type) { + switch (type) { + case DISCOUNT: + return new Discount(); + case PHYSICAL: + return new Physical(); + case SHIPPING_FEE: + return new ShippingFee(); + } + return null; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/OrderLinesPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/OrderLinesPopulator.java new file mode 100644 index 00000000..1dda3c32 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/OrderLinesPopulator.java @@ -0,0 +1,45 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.LineItem; +import com.worldpay.data.OrderLines; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.List; +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.OrderLines} with the information of a {@link OrderLines} + */ +public class OrderLinesPopulator implements Populator { + + protected Converter internalLineItemConverter; + + public OrderLinesPopulator(final Converter internalLineItemConverter) { + this.internalLineItemConverter = internalLineItemConverter; + } + + /** + * Populates the data from the {@link OrderLines} to a {@link com.worldpay.internal.model.OrderLines} + * + * @param source a {@link OrderLines} from Worldpay + * @param target a {@link com.worldpay.internal.model.OrderLines} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final OrderLines source, final com.worldpay.internal.model.OrderLines target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setOrderTaxAmount(source.getOrderTaxAmount()); + target.setTermsURL(source.getTermsURL()); + + final List targetList = target.getLineItem(); + Optional.ofNullable(source.getLineItems()) + .map(internalLineItemConverter::convertAll) + .ifPresent(targetList::addAll); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/OrderPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/OrderPopulator.java new file mode 100644 index 00000000..e786700a --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/OrderPopulator.java @@ -0,0 +1,191 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.internal.model.*; +import com.worldpay.data.BranchSpecificExtension; +import com.worldpay.data.FraudSightData; +import com.worldpay.data.Order; +import com.worldpay.data.OrderLines; +import com.worldpay.data.token.TokenRequest; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.apache.commons.lang.StringUtils; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Order} with the information of a {@link Order}. + */ +public class OrderPopulator implements Populator { + + protected final Converter internalBranchSpecificExtensionConverter; + protected final Converter internalTokenRequestConverter; + protected final Converter internalOrderLinesConverter; + protected final Converter internalFraudSightDataConverter; + protected final PaymentOrderConvertersWrapper paymentOrderConvertersWrapper; + protected final ThreeDS2OrderConvertersWrapper threeDS2OrderConvertersWrapper; + protected final BasicOrderConvertersWrapper basicOrderConvertersWrapper; + + public OrderPopulator(final Converter internalBranchSpecificExtensionConverter, + final Converter internalTokenRequestConverter, + final Converter internalOrderLinesConverter, + final Converter internalFraudSightDataConverter, + final PaymentOrderConvertersWrapper paymentOrderConvertersWrapper, + final ThreeDS2OrderConvertersWrapper threeDS2OrderConvertersWrapper, + final BasicOrderConvertersWrapper basicOrderConvertersWrapper) { + this.internalBranchSpecificExtensionConverter = internalBranchSpecificExtensionConverter; + this.internalTokenRequestConverter = internalTokenRequestConverter; + this.internalOrderLinesConverter = internalOrderLinesConverter; + this.internalFraudSightDataConverter = internalFraudSightDataConverter; + this.paymentOrderConvertersWrapper = paymentOrderConvertersWrapper; + this.threeDS2OrderConvertersWrapper = threeDS2OrderConvertersWrapper; + this.basicOrderConvertersWrapper = basicOrderConvertersWrapper; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final Order source, final com.worldpay.internal.model.Order target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + final List childElements = target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession(); + + Optional.ofNullable(source.getOrderCode()) + .ifPresent(target::setOrderCode); + + Optional.ofNullable(source.getDescription()).ifPresent(description -> { + final Description intDescription = new Description(); + intDescription.setvalue(source.getDescription()); + childElements.add(intDescription); + }); + + Optional.ofNullable(source.getAmount()) + .map(basicOrderConvertersWrapper.internalAmountConverter::convert) + .ifPresent(childElements::add); + + Optional.ofNullable(source.getInstallationId()) + .ifPresent(target::setInstallationId); + + Optional.ofNullable(source.getOrderContent()).ifPresent(orderContent -> { + final OrderContent intOrderContent = new OrderContent(); + intOrderContent.setvalue(orderContent); + childElements.add(intOrderContent); + }); + + populatePaymentRequestDetails(source, childElements); + + Optional.ofNullable(source.getShopper()) + .map(basicOrderConvertersWrapper.internalShopperConverter::convert) + .ifPresent(childElements::add); + + Optional.ofNullable(source.getShippingAddress()) + .map(basicOrderConvertersWrapper.internalAddressConverter::convert) + .ifPresent(address -> { + final ShippingAddress intShippingAddress = new ShippingAddress(); + intShippingAddress.setAddress(address); + childElements.add(intShippingAddress); + }); + + Optional.ofNullable(source.getBillingAddress()) + .map(basicOrderConvertersWrapper.internalAddressConverter::convert) + .ifPresent(address -> { + final BillingAddress intBillingAddress = new BillingAddress(); + intBillingAddress.setAddress(address); + childElements.add(intBillingAddress); + }); + + Optional.ofNullable(source.getMandateType()) + .ifPresent(mandateType -> { + final Mandate mandate = new Mandate(); + mandate.setMandateType(mandateType); + childElements.add(mandate); + }); + + Optional.ofNullable(source.getBranchSpecificExtension()) + .map(internalBranchSpecificExtensionConverter::convert) + .ifPresent(childElements::add); + + Optional.ofNullable(source.getPaymentMethodAttributes()) + .stream() + .flatMap(Collection::stream) + .map(paymentOrderConvertersWrapper.internalPaymentMethodAttributeConverter::convert) + .forEach(childElements::add); + + Optional.ofNullable(source.getStatementNarrative()) + .ifPresent(statementNarrative -> { + final StatementNarrative intStatementNarrative = new StatementNarrative(); + intStatementNarrative.setvalue(statementNarrative); + childElements.add(intStatementNarrative); + }); + + Optional.ofNullable(source.getEchoData()) + .ifPresent(echoData -> { + final EchoData intEchoData = new EchoData(); + intEchoData.setvalue(echoData); + childElements.add(intEchoData); + }); + + Optional.ofNullable(source.getTokenRequest()) + .map(internalTokenRequestConverter::convert) + .ifPresent(childElements::add); + + Optional.ofNullable(source.getPaResponse()) + .ifPresent(paResponse -> { + final Info3DSecure intInfo3dSecure = new Info3DSecure(); + final PaResponse intPaResponse = new PaResponse(); + intPaResponse.setvalue(paResponse); + intInfo3dSecure.getPaResponseOrMpiProviderOrMpiResponseOrAttemptedAuthenticationOrCompletedAuthenticationOrThreeDSVersionOrMerchantNameOrXidOrDsTransactionIdOrCavvOrEci().add(intPaResponse); + childElements.add(intInfo3dSecure); + }); + + Optional.ofNullable(source.getSession()) + .map(basicOrderConvertersWrapper.internalSessionConverter::convert) + .ifPresent(childElements::add); + + Optional.ofNullable(source.getOrderLines()) + .map(internalOrderLinesConverter::convert) + .ifPresent(childElements::add); + + Optional.ofNullable(source.getDynamicInteractionType()) + .map(Enum::name) + .ifPresent(dynamicInteractionType -> { + final DynamicInteractionType intDynamicInteractionType = new DynamicInteractionType(); + intDynamicInteractionType.setType(dynamicInteractionType); + childElements.add(intDynamicInteractionType); + }); + + Optional.ofNullable(source.getRiskData()) + .map(threeDS2OrderConvertersWrapper.internalRiskDataConverter::convert) + .ifPresent(childElements::add); + + Optional.ofNullable(source.getAdditional3DSData()) + .map(threeDS2OrderConvertersWrapper.internalAdditional3DSDataConverter::convert) + .ifPresent(childElements::add); + + Optional.ofNullable(source.getFraudSightData()) + .map(internalFraudSightDataConverter::convert) + .ifPresent(childElements::add); + + if (StringUtils.isNotBlank(source.getDeviceSession())) { + final DeviceSession intDeviceSession = new DeviceSession(); + intDeviceSession.setSessionId(source.getDeviceSession()); + childElements.add(intDeviceSession); + } + } + + private void populatePaymentRequestDetails(final Order source, final List childElements) { + if (source.getPaymentMethodMask() != null) { + childElements.add(paymentOrderConvertersWrapper.internalPaymentMethodMaskConverter.convert(source.getPaymentMethodMask())); + } else if (source.getPaymentDetails() != null) { + childElements.add(paymentOrderConvertersWrapper.internalPaymentDetailsConverter.convert(source.getPaymentDetails())); + } else if (source.getPayAsOrder() != null) { + childElements.add(paymentOrderConvertersWrapper.internalPayAsOrderConverter.convert(source.getPayAsOrder())); + } + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentDetailsPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentDetailsPopulator.java new file mode 100644 index 00000000..058e0983 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentDetailsPopulator.java @@ -0,0 +1,69 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.converters.internal.model.payment.PaymentConverterStrategy; +import com.worldpay.enums.PaymentAction; +import com.worldpay.internal.model.Info3DSecure; +import com.worldpay.internal.model.PaResponse; +import com.worldpay.data.PaymentDetails; +import com.worldpay.data.Session; +import com.worldpay.data.payment.StoredCredentials; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.List; +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.PaymentDetails} with the information of a {@link PaymentDetails}. + */ +public class PaymentDetailsPopulator implements Populator { + + protected final Converter internalSessionConverter; + protected final Converter internalStoredCredentialsConverter; + protected final PaymentConverterStrategy internalPaymentConverterStrategy; + + public PaymentDetailsPopulator(final Converter internalSessionConverter, + final Converter internalStoredCredentialsConverter, + final PaymentConverterStrategy internalPaymentConverterStrategy) { + this.internalSessionConverter = internalSessionConverter; + this.internalStoredCredentialsConverter = internalStoredCredentialsConverter; + this.internalPaymentConverterStrategy = internalPaymentConverterStrategy; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final PaymentDetails source, final com.worldpay.internal.model.PaymentDetails target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + final List paymentDtl = target.getVISASSLOrECMCSSLOrBHSSSLOrNEWDAYSSLOrIKEASSLOrAMEXSSLOrELVSSLOrSEPADIRECTDEBITSSLOrDINERSSSLOrCBSSLOrAIRPLUSSSLOrUATPSSLOrCARTEBLEUESSLOrSOLOGBSSLOrLASERSSLOrDANKORTSSLOrDISCOVERSSLOrJCBSSLOrAURORESSLOrGECAPITALSSLOrHIPERCARDSSLOrSOROCREDSSLOrELOSSLOrCARNETSSLOrARGENCARDSSLOrCABALSSLOrCENCOSUDSSLOrCOOPEPLUSSSLOrCREDIMASSSLOrITALCREDSSLOrNARANJASSLOrNATIVASSLOrNEVADASSLOrNEXOSSLOrTARJETASHOPPINGSSLOrPERMANENTSIGNEDDDNLFAXOrPERMANENTSIGNEDDDGBSSLOrPERMANENTUNSIGNEDDDGBSSLOrPAYOUTBANKOrVISACHECKOUTSSLOrMASTERPASSSSLOrPAYPALEXPRESSOrGIROPAYSSLOrMAESTROSSLOrSWITCHSSLOrNCPB2BSSLOrNCPSEASONSSLOrNCPGMMSSLOrIDEALSSLOrACHSSLOrACHDIRECTDEBITSSLOrCARDSSLOrABAQOOSSSLOrAGMOSSLOrALIPAYSSLOrALIPAYMOBILESSLOrBALOTOSSLOrBANKAXESSSSLOrBANKLINKNORDEASSLOrBILLDESKSSLOrBILLINGPARTNERSSLOrCASHUSSLOrDINEROMAIL7ELEVENSSLOrDINEROMAILOXXOSSLOrDINEROMAILONLINEBTSSLOrDINEROMAILSERVIPAGSSLOrEKONTOSSLOrEPAYSSLOrEUTELLERSSLOrEWIREDKSSLOrEWIRENOSSLOrEWIRESESSLOrHALCASHSSLOrINSTADEBITSSLOrKONBINISSLOrLOBANETARSSLOrLOBANETBRSSLOrLOBANETCLSSLOrLOBANETMXSSLOrLOBANETPESSLOrLOBANETUYSSLOrMISTERCASHSSLOrMULTIBANCOSSLOrNEOSURFSSLOrPAGASSLOrPAGAVERVESSLOrPAYSAFECARDSSLOrPAYUSSLOrPLUSPAYSSLOrPOLISSLOrPOLINZSSLOrPOSTEPAYSSLOrPRZELEWYSSLOrQIWISSLOrSAFETYPAYSSLOrSIDSSLOrSKRILLSSLOrSOFORTSSLOrSOFORTCHSSLOrSPEEDCARDSSLOrSPOROPAYSSLOrSWIFFSSLOrTELEINGRESOSSLOrTICKETSURFSSLOrTRUSTLYSSLOrTRUSTPAYCZSSLOrTRUSTPAYEESSLOrTRUSTPAYSKSSLOrWEBMONEYSSLOrYANDEXMONEYSSLOrASTROPAYCARDSSLOrBANCOSANTANDERSSLOrBOLETOSSLOrBOLETOHTMLOrMONETASSLOrTODITOCARDSSLOrONLINETRANSFERBRSSLOrONLINETRANSFERMYSSLOrONLINETRANSFERTHSSLOrONLINETRANSFERVNSSLOrOPENBANKINGSSLOrSEVENELEVENMYSSLOrPETRONASSSLOrENETSSGSSLOrCASHTHSSLOrATMIDSSLOrTOKENSSLOrENETSSSLOrCHINAUNIONPAYSSLOrENVOYTRANSFERAUDBANKOrENVOYTRANSFERCADBANKOrENVOYTRANSFERCHFBANKOrENVOYTRANSFERCZKBANKOrENVOYTRANSFERDKKBANKOrENVOYTRANSFEREURBANKOrENVOYTRANSFERGBPBANKOrENVOYTRANSFERHKDBANKOrENVOYTRANSFERHUFBANKOrENVOYTRANSFERJPYBANKOrENVOYTRANSFERNOKBANKOrENVOYTRANSFERNZDBANKOrENVOYTRANSFERPLNBANKOrENVOYTRANSFERRUBBANKOrENVOYTRANSFERSEKBANKOrENVOYTRANSFERSGDBANKOrENVOYTRANSFERTHBBANKOrENVOYTRANSFERTRYBANKOrENVOYTRANSFERUSDBANKOrENVOYTRANSFERZARBANKOrTRANSFERATBANKOrTRANSFERBEBANKOrTRANSFERCHBANKOrTRANSFERDEBANKOrTRANSFERDKBANKOrTRANSFERESBANKOrTRANSFERFIBANKOrTRANSFERFRBANKOrTRANSFERGBBANKOrTRANSFERGRBANKOrTRANSFERITBANKOrTRANSFERJPBANKOrTRANSFERLUBANKOrTRANSFERNLBANKOrTRANSFERNOBANKOrTRANSFERPLBANKOrTRANSFERSEBANKOrTRANSFERUSBANKOrEMVCOTOKENSSLOrAPPLEPAYSSLOrANDROIDPAYSSLOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrKLARNASSLOrKLARNAPAYLATERSSLOrKLARNAPAYNOWSSLOrKLARNASLICEITSSLOrKLARNAV2SSLOrWECHATPAYSSLOrBILLKEYSSLOrINIPAYSSLOrWEBPAYSSLOrPBBASSLOrGPPSSLOrMERCADOPAGOSSLOrPAYPALSSLOrSVSGIFTCARDSSLOrTROYSSLOrUPISSLOrUPEXSSLOrFFDISBURSESSLOrFFMONEYTRANSFERSSLOrEPSENVSSLOrCardNumberOrExpiryDateOrCardHolderNameOrCvcOrIssueNumberOrStartDateOrPOSRequestOrCardSwipeOrCSEDATA(); + Optional.ofNullable(source.getPayment()) + .map(internalPaymentConverterStrategy::convertPayment) + .ifPresent(paymentDtl::add); + + Optional.ofNullable(source.getSession()) + .map(internalSessionConverter::convert) + .ifPresent(target::setSession); + + Optional.ofNullable(source.getPaResponse()).ifPresent(paResponse -> { + final Info3DSecure intInfo3dSecure = new Info3DSecure(); + final PaResponse intPaResponse = new PaResponse(); + intPaResponse.setvalue(paResponse); + intInfo3dSecure.getPaResponseOrMpiProviderOrMpiResponseOrAttemptedAuthenticationOrCompletedAuthenticationOrThreeDSVersionOrMerchantNameOrXidOrDsTransactionIdOrCavvOrEci().add(intPaResponse); + target.setInfo3DSecure(intInfo3dSecure); + }); + + Optional.ofNullable(source.getStoredCredentials()) + .map(internalStoredCredentialsConverter::convert) + .ifPresent(target::setStoredCredentials); + + Optional.ofNullable(source.getAction()) + .map(PaymentAction::name) + .ifPresent(target::setAction); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentMethodAttributePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentMethodAttributePopulator.java new file mode 100644 index 00000000..711a4bfd --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentMethodAttributePopulator.java @@ -0,0 +1,30 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.PaymentMethodAttribute; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.PaymentMethodAttribute} with the information of a {@link PaymentMethodAttribute} + */ +public class PaymentMethodAttributePopulator implements Populator { + + /** + * Populates the data from the {@link PaymentMethodAttribute} to a {@link com.worldpay.internal.model.PaymentMethodAttribute} + * + * @param source a {@link PaymentMethodAttribute} from Worldpay + * @param target a {@link com.worldpay.internal.model.PaymentMethodAttribute} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final PaymentMethodAttribute source, final com.worldpay.internal.model.PaymentMethodAttribute target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setAttrName(source.getAttrName()); + target.setAttrValue(source.getAttrValue()); + target.setPaymentMethod(source.getPaymentMethod()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentMethodMaskPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentMethodMaskPopulator.java new file mode 100644 index 00000000..7f9ce66c --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentMethodMaskPopulator.java @@ -0,0 +1,75 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.internal.model.Exclude; +import com.worldpay.internal.model.Include; +import com.worldpay.data.PaymentMethodMask; +import com.worldpay.data.payment.StoredCredentials; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.apache.commons.collections4.CollectionUtils; + +import java.util.List; +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.PaymentMethodMask} with the information of a {@link PaymentMethodMask}. + */ +public class PaymentMethodMaskPopulator implements Populator { + + protected final Converter internalStoredCredentialsConverter; + + public PaymentMethodMaskPopulator(final Converter internalStoredCredentialsConverter) { + this.internalStoredCredentialsConverter = internalStoredCredentialsConverter; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final PaymentMethodMask source, + final com.worldpay.internal.model.PaymentMethodMask target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + final List includeOrExclude = target.getStoredCredentialsOrIncludeOrExclude(); + + Optional.ofNullable(source.getStoredCredentials()) + .map(internalStoredCredentialsConverter::convert) + .ifPresent(includeOrExclude::add); + + CollectionUtils.emptyIfNull(source.getExcludes()).stream() + .map(this::createIntExclude) + .forEach(includeOrExclude::add); + + CollectionUtils.emptyIfNull(source.getIncludes()).stream() + .map(this::createIntInclude) + .forEach(includeOrExclude::add); + } + + /** + * Creates a {@link com.worldpay.internal.model.Exclude} with the given methodCode. + * + * @param methodCode the method code. + * @return a {@link com.worldpay.internal.model.Exclude}. + */ + protected Exclude createIntExclude(final String methodCode) { + final Exclude intExclude = new Exclude(); + intExclude.setCode(methodCode); + return intExclude; + } + + /** + * Creates a {@link com.worldpay.internal.model.Include} with the given methodCode. + * + * @param methodCode the method code. + * @return a {@link com.worldpay.internal.model.Include}. + */ + protected Include createIntInclude(final String methodCode) { + final Include intInclude = new Include(); + intInclude.setCode(methodCode); + return intInclude; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentOrderConvertersWrapper.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentOrderConvertersWrapper.java new file mode 100644 index 00000000..488af683 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PaymentOrderConvertersWrapper.java @@ -0,0 +1,25 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.PaymentDetails; +import com.worldpay.data.PaymentMethodAttribute; +import com.worldpay.data.PaymentMethodMask; +import com.worldpay.data.payment.PayAsOrder; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +public class PaymentOrderConvertersWrapper { + + protected final Converter internalPaymentMethodMaskConverter; + protected final Converter internalPaymentDetailsConverter; + protected final Converter internalPayAsOrderConverter; + protected final Converter internalPaymentMethodAttributeConverter; + + public PaymentOrderConvertersWrapper(final Converter internalPaymentMethodMaskConverter, + final Converter internalPaymentDetailsConverter, + final Converter internalPayAsOrderConverter, + final Converter internalPaymentMethodAttributeConverter) { + this.internalPaymentMethodMaskConverter = internalPaymentMethodMaskConverter; + this.internalPaymentDetailsConverter = internalPaymentDetailsConverter; + this.internalPayAsOrderConverter = internalPayAsOrderConverter; + this.internalPaymentMethodAttributeConverter = internalPaymentMethodAttributeConverter; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PurchasePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PurchasePopulator.java new file mode 100644 index 00000000..773948ea --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/PurchasePopulator.java @@ -0,0 +1,86 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.internal.model.*; +import com.worldpay.data.Amount; +import com.worldpay.data.Date; +import com.worldpay.data.Item; +import com.worldpay.data.Purchase; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Purchase} with the information of a {@link Purchase} + */ +public class PurchasePopulator implements Populator { + + protected final Converter internalItemConverter; + protected final Converter internalDateConverter; + protected final Converter internalAmountConverter; + + public PurchasePopulator(final Converter internalItemConverter, + final Converter internalDateConverter, + final Converter internalAmountConverter) { + this.internalItemConverter = internalItemConverter; + this.internalDateConverter = internalDateConverter; + this.internalAmountConverter = internalAmountConverter; + } + + /** + * Populates the data from the {@link Purchase} to a {@link com.worldpay.internal.model.Purchase} + * + * @param source a {@link Purchase} from Worldpay + * @param target a {@link com.worldpay.internal.model.Purchase} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final Purchase source, + final com.worldpay.internal.model.Purchase target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + target.setInvoiceReferenceNumber(source.getInvoiceReferenceNumber()); + target.setCustomerReference(source.getCustomerReference()); + target.setCardAcceptorTaxId(source.getCardAcceptorTaxId()); + target.setDestinationCountryCode(source.getDestinationCountryCode()); + target.setDestinationPostalCode(source.getDestinationPostalCode()); + target.setTaxExempt(String.valueOf(source.isTaxExempt())); + + Optional.ofNullable(source.getItem()) + .ifPresent(items -> target.getItem().addAll(internalItemConverter.convertAll(items))); + + Optional.ofNullable(source.getOrderDate()).ifPresent(date -> { + final OrderDate intOrderDate = new OrderDate(); + intOrderDate.setDate(internalDateConverter.convert(date)); + target.setOrderDate(intOrderDate); + }); + + Optional.ofNullable(source.getSalesTax()).ifPresent(amount -> { + final SalesTax intSalesTax = new SalesTax(); + intSalesTax.setAmount(internalAmountConverter.convert(amount)); + target.setSalesTax(intSalesTax); + }); + + Optional.ofNullable(source.getDiscountAmount()).ifPresent(amount -> { + final DiscountAmount intDiscountAmount = new DiscountAmount(); + intDiscountAmount.setAmount(internalAmountConverter.convert(amount)); + target.setDiscountAmount(intDiscountAmount); + }); + + Optional.ofNullable(source.getShippingAmount()).ifPresent(amount -> { + final ShippingAmount intShippingAmount = new ShippingAmount(); + intShippingAmount.setAmount(internalAmountConverter.convert(amount)); + target.setShippingAmount(intShippingAmount); + }); + + Optional.ofNullable(source.getDutyAmount()).ifPresent(amount -> { + final DutyAmount intDutyAmount = new DutyAmount(); + intDutyAmount.setAmount(internalAmountConverter.convert(amount)); + target.setDutyAmount(intDutyAmount); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ReferencePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ReferencePopulator.java new file mode 100644 index 00000000..9f94e6fa --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ReferencePopulator.java @@ -0,0 +1,30 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.internal.model.Reference; +import com.worldpay.data.LineItemReference; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Reference} with the information of a {@link LineItemReference} + */ +public class ReferencePopulator implements Populator { + + /** + * Populates the data from the {@link LineItemReference} to a {@link Reference} + * + * @param source a {@link LineItemReference} from Worldpay + * @param target a {@link Reference} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final LineItemReference source, final Reference target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setId(source.getId()); + target.setvalue(source.getValue()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/SessionPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/SessionPopulator.java new file mode 100644 index 00000000..44cd7152 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/SessionPopulator.java @@ -0,0 +1,30 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Session; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Session} with the information of a {@link Session}. + */ +public class SessionPopulator implements Populator { + + /** + * {@inheritDoc} + */ + @Override + public void populate(final Session source, final com.worldpay.internal.model.Session target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getShopperIPAddress()) + .ifPresent(target::setShopperIPAddress); + + Optional.ofNullable(source.getId()) + .ifPresent(target::setId); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ShopperFieldsPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ShopperFieldsPopulator.java new file mode 100644 index 00000000..44b2989d --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ShopperFieldsPopulator.java @@ -0,0 +1,58 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.internal.model.BirthDate; +import com.worldpay.internal.model.ShopperAddress; +import com.worldpay.data.Address; +import com.worldpay.data.Date; +import com.worldpay.data.ShopperFields; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.ShopperFields} with the information of a {@link ShopperFields} + */ +public class ShopperFieldsPopulator implements Populator { + + protected final Converter internalDateConverter; + protected final Converter internalAddressConverter; + + public ShopperFieldsPopulator(final Converter internalDateConverter, + final Converter internalAddressConverter) { + this.internalDateConverter = internalDateConverter; + this.internalAddressConverter = internalAddressConverter; + } + + /** + * Populates the data from the {@link ShopperFields} to a {@link com.worldpay.internal.model.ShopperFields} + * + * @param source a {@link ShopperFields} from Worldpay + * @param target a {@link com.worldpay.internal.model.ShopperFields} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final ShopperFields source, + final com.worldpay.internal.model.ShopperFields target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + target.setShopperName(source.getShopperName()); + target.setShopperId(source.getShopperId()); + + Optional.ofNullable(source.getBirthDate()).ifPresent(date -> { + final BirthDate intBirthDateData = new BirthDate(); + intBirthDateData.setDate(internalDateConverter.convert(date)); + target.setBirthDate(intBirthDateData); + }); + + Optional.ofNullable(source.getShopperAddress()).ifPresent(address -> { + final ShopperAddress intShopperAddress = new ShopperAddress(); + intShopperAddress.setAddress(internalAddressConverter.convert(source.getShopperAddress())); + target.setShopperAddress(intShopperAddress); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ShopperPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ShopperPopulator.java new file mode 100644 index 00000000..12b729d2 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ShopperPopulator.java @@ -0,0 +1,54 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.internal.model.AuthenticatedShopperID; +import com.worldpay.data.Browser; +import com.worldpay.data.Session; +import com.worldpay.data.Shopper; +import com.worldpay.data.payment.PayAsOrder; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.PayAsOrder} with the information of a {@link PayAsOrder}. + */ +public class ShopperPopulator implements Populator { + + protected final Converter internalBrowserConverter; + protected final Converter internalSessionConverter; + + public ShopperPopulator(final Converter internalBrowserConverter, final Converter internalSessionConverter) { + this.internalBrowserConverter = internalBrowserConverter; + this.internalSessionConverter = internalSessionConverter; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final Shopper source, final com.worldpay.internal.model.Shopper target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getShopperEmailAddress()) + .ifPresent(target::setShopperEmailAddress); + + Optional.ofNullable(source.getAuthenticatedShopperID()).ifPresent(authenticatedShopperID -> { + final AuthenticatedShopperID intAuthenticatedShopperID = new AuthenticatedShopperID(); + intAuthenticatedShopperID.setvalue(authenticatedShopperID); + target.setAuthenticatedShopperID(intAuthenticatedShopperID); + }); + + Optional.ofNullable(source.getBrowser()) + .map(internalBrowserConverter::convert) + .ifPresent(target::setBrowser); + + Optional.ofNullable(source.getSession()) + .map(internalSessionConverter::convert) + .ifPresent(target::setSession); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/StoredCredentialsPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/StoredCredentialsPopulator.java new file mode 100644 index 00000000..07aabce0 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/StoredCredentialsPopulator.java @@ -0,0 +1,37 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; +import com.worldpay.enums.payment.storedCredentials.Usage; +import com.worldpay.data.payment.StoredCredentials; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.StoredCredentials} with the information of a {@link StoredCredentials}. + */ +public class StoredCredentialsPopulator implements Populator { + + /** + * {@inheritDoc} + */ + @Override + public void populate(final StoredCredentials source, + final com.worldpay.internal.model.StoredCredentials target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getMerchantInitiatedReason()) + .map(MerchantInitiatedReason::name) + .ifPresent(target::setMerchantInitiatedReason); + + Optional.ofNullable(source.getUsage()) + .map(Usage::name) + .ifPresent(target::setUsage); + + target.setSchemeTransactionIdentifier(source.getSchemeTransactionIdentifier()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ThreeDS2OrderConvertersWrapper.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ThreeDS2OrderConvertersWrapper.java new file mode 100644 index 00000000..e2555ddd --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/ThreeDS2OrderConvertersWrapper.java @@ -0,0 +1,17 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.threeds2.RiskData; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +public class ThreeDS2OrderConvertersWrapper { + + protected final Converter internalRiskDataConverter; + protected final Converter internalAdditional3DSDataConverter; + + public ThreeDS2OrderConvertersWrapper(final Converter internalRiskDataConverter, + final Converter internalAdditional3DSDataConverter) { + this.internalRiskDataConverter = internalRiskDataConverter; + this.internalAdditional3DSDataConverter = internalAdditional3DSDataConverter; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/applepay/ApplePayPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/applepay/ApplePayPopulator.java new file mode 100644 index 00000000..49ce05b7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/applepay/ApplePayPopulator.java @@ -0,0 +1,46 @@ +package com.worldpay.converters.populators.internal.model.applepay; + +import com.worldpay.internal.model.APPLEPAYSSL; +import com.worldpay.data.applepay.ApplePay; +import com.worldpay.data.applepay.Header; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link APPLEPAYSSL} with the information of a {@link ApplePay} + */ +public class ApplePayPopulator implements Populator { + + protected final Converter internalHeaderConverter; + + public ApplePayPopulator(final Converter internalHeaderConverter) { + this.internalHeaderConverter = internalHeaderConverter; + } + + /** + * Populates the data from the {@link ApplePay} to a {@link APPLEPAYSSL} + * + * @param source a {@link ApplePay} from Worldpay + * @param target a {@link APPLEPAYSSL} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final ApplePay source, final APPLEPAYSSL target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + Optional.ofNullable(source.getHeader()) + .map(internalHeaderConverter::convert) + .ifPresent(target::setHeader); + + target.setData(source.getData()); + target.setSignature(source.getSignature()); + target.setTokenRequestorID(source.getTokenRequestorID()); + target.setVersion(source.getVersion()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/applepay/HeaderPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/applepay/HeaderPopulator.java new file mode 100644 index 00000000..650970dc --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/applepay/HeaderPopulator.java @@ -0,0 +1,31 @@ +package com.worldpay.converters.populators.internal.model.applepay; + +import com.worldpay.data.applepay.Header; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Header} with the information of a {@link Header} + */ +public class HeaderPopulator implements Populator { + + /** + * Populates the data from the {@link Header} to a {@link com.worldpay.internal.model.Header} + * + * @param source a {@link Header} from Worldpay + * @param target a {@link com.worldpay.internal.model.Header} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final Header source, final com.worldpay.internal.model.Header target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setApplicationData(source.getApplicationData()); + target.setEphemeralPublicKey(source.getEphemeralPublicKey()); + target.setPublicKeyHash(source.getPublicKeyHash()); + target.setTransactionId(source.getTransactionId()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayLaterPaymentPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayLaterPaymentPopulator.java new file mode 100644 index 00000000..e291b93b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayLaterPaymentPopulator.java @@ -0,0 +1,34 @@ +package com.worldpay.converters.populators.internal.model.klarna; + +import com.worldpay.internal.model.KLARNAPAYLATERSSL; +import com.worldpay.data.klarna.KlarnaPayment; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link KLARNAPAYLATERSSL} with the information of a {@link KlarnaPayment} + */ +public class KlarnaPayLaterPaymentPopulator implements Populator { + + /** + * Populates the data from the {@link KlarnaPayment} to a {@link KLARNAPAYLATERSSL} + * + * @param source a {@link KlarnaPayment} from Worldpay + * @param target a {@link KLARNAPAYLATERSSL} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final KlarnaPayment source, final KLARNAPAYLATERSSL target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setCancelURL(source.getCancelURL()); + target.setFailureURL(source.getFailureURL()); + target.setPendingURL(source.getPendingURL()); + target.setSuccessURL(source.getSuccessURL()); + target.setLocale(source.getLocale()); + target.setShopperCountryCode(source.getShopperCountryCode()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayNowPaymentPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayNowPaymentPopulator.java new file mode 100644 index 00000000..cf69fc9e --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayNowPaymentPopulator.java @@ -0,0 +1,34 @@ +package com.worldpay.converters.populators.internal.model.klarna; + +import com.worldpay.internal.model.KLARNAPAYNOWSSL; +import com.worldpay.data.klarna.KlarnaPayment; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link KLARNAPAYNOWSSL} with the information of a {@link KlarnaPayment} + */ +public class KlarnaPayNowPaymentPopulator implements Populator { + + /** + * Populates the data from the {@link KlarnaPayment} to a {@link KLARNAPAYNOWSSL} + * + * @param source a {@link KlarnaPayment} from Worldpay + * @param target a {@link KLARNAPAYNOWSSL} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final KlarnaPayment source, final KLARNAPAYNOWSSL target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setCancelURL(source.getCancelURL()); + target.setFailureURL(source.getFailureURL()); + target.setPendingURL(source.getPendingURL()); + target.setSuccessURL(source.getSuccessURL()); + target.setLocale(source.getLocale()); + target.setShopperCountryCode(source.getShopperCountryCode()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaPaymentPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaPaymentPopulator.java new file mode 100644 index 00000000..e2e427c7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaPaymentPopulator.java @@ -0,0 +1,41 @@ +package com.worldpay.converters.populators.internal.model.klarna; + +import com.worldpay.internal.model.KLARNASSL; +import com.worldpay.internal.model.MerchantUrls; +import com.worldpay.data.klarna.KlarnaPayment; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link KLARNASSL} with the information of a {@link KlarnaPayment} + */ +public class KlarnaPaymentPopulator implements Populator { + + /** + * Populates the data from the {@link KlarnaPayment} to a {@link KLARNASSL} + * + * @param source a {@link KlarnaPayment} from Worldpay + * @param target a {@link KLARNASSL} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final KlarnaPayment source, final KLARNASSL target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setExtraMerchantData(source.getExtraMerchantData()); + target.setPurchaseCountry(source.getPurchaseCountry()); + target.setShopperLocale(source.getShopperLocale()); + + Optional.ofNullable(source.getMerchantUrls()).ifPresent(klarnaMerchantUrls -> { + final MerchantUrls internalMerchantUrls = new MerchantUrls(); + internalMerchantUrls.setCheckoutURL(klarnaMerchantUrls.getCheckoutURL()); + internalMerchantUrls.setConfirmationURL(klarnaMerchantUrls.getConfirmationURL()); + target.setMerchantUrls(internalMerchantUrls); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaSliceItPaymentPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaSliceItPaymentPopulator.java new file mode 100644 index 00000000..d7b0f48b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/klarna/KlarnaSliceItPaymentPopulator.java @@ -0,0 +1,34 @@ +package com.worldpay.converters.populators.internal.model.klarna; + +import com.worldpay.internal.model.KLARNASLICEITSSL; +import com.worldpay.data.klarna.KlarnaPayment; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link KLARNASLICEITSSL} with the information of a {@link KlarnaPayment} + */ +public class KlarnaSliceItPaymentPopulator implements Populator { + + /** + * Populates the data from the {@link KlarnaPayment} to a {@link KLARNASLICEITSSL} + * + * @param source a {@link KlarnaPayment} from Worldpay + * @param target a {@link KLARNASLICEITSSL} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final KlarnaPayment source, final KLARNASLICEITSSL target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setCancelURL(source.getCancelURL()); + target.setFailureURL(source.getFailureURL()); + target.setPendingURL(source.getPendingURL()); + target.setSuccessURL(source.getSuccessURL()); + target.setLocale(source.getLocale()); + target.setShopperCountryCode(source.getShopperCountryCode()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/CsePaymentPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/CsePaymentPopulator.java new file mode 100644 index 00000000..97b6b89e --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/CsePaymentPopulator.java @@ -0,0 +1,51 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.internal.model.CSEDATA; +import com.worldpay.internal.model.CardAddress; +import com.worldpay.internal.model.EncryptedData; +import com.worldpay.data.Address; +import com.worldpay.data.payment.Cse; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link CSEDATA} with the information of a {@link Cse} + */ +public class CsePaymentPopulator implements Populator { + + protected final Converter internalAddressConverter; + + public CsePaymentPopulator(final Converter internalAddressConverter) { + this.internalAddressConverter = internalAddressConverter; + } + + /** + * Populates the data from the {@link Cse} to a {@link CSEDATA} + * + * @param source a {@link Cse} from Worldpay + * @param target a {@link CSEDATA} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final Cse source, final CSEDATA target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getAddress()).ifPresent(address -> { + final CardAddress cardAddress = new CardAddress(); + cardAddress.setAddress(internalAddressConverter.convert(address)); + target.setCardAddress(cardAddress); + }); + + Optional.ofNullable(source.getEncryptedData()).ifPresent(encryptedData -> { + final EncryptedData internalEncryptedData = new EncryptedData(); + internalEncryptedData.setvalue(encryptedData); + target.setEncryptedData(internalEncryptedData); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/GooglePaymentPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/GooglePaymentPopulator.java new file mode 100644 index 00000000..2d82aa84 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/GooglePaymentPopulator.java @@ -0,0 +1,34 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.internal.model.PAYWITHGOOGLESSL; +import com.worldpay.data.payment.PayWithGoogleSSL; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.PAYWITHGOOGLESSL} with the information of a {@link PayWithGoogleSSL}. + */ +public class GooglePaymentPopulator implements Populator { + + /** + * {@inheritDoc} + */ + @Override + public void populate(final PayWithGoogleSSL source, final PAYWITHGOOGLESSL target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getProtocolVersion()) + .ifPresent(target::setProtocolVersion); + + Optional.ofNullable(source.getSignature()) + .ifPresent(target::setSignature); + + Optional.ofNullable(source.getSignedMessage()) + .ifPresent(target::setSignedMessage); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/IdealPaymentPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/IdealPaymentPopulator.java new file mode 100644 index 00000000..04c4ec22 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/IdealPaymentPopulator.java @@ -0,0 +1,40 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.internal.model.IDEALSSL; +import com.worldpay.data.payment.AlternativeShopperBankCodePayment; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.IDEALSSL} with the information of a {@link AlternativeShopperBankCodePayment}. + */ +public class IdealPaymentPopulator implements Populator { + + /** + * {@inheritDoc} + */ + @Override + public void populate(final AlternativeShopperBankCodePayment source, final IDEALSSL target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getShopperBankCode()) + .ifPresent(target::setShopperBankCode); + + Optional.ofNullable(source.getSuccessURL()) + .ifPresent(target::setSuccessURL); + + Optional.ofNullable(source.getFailureURL()) + .ifPresent(target::setFailureURL); + + Optional.ofNullable(source.getCancelURL()) + .ifPresent(target::setCancelURL); + + Optional.ofNullable(source.getPendingURL()) + .ifPresent(target::setPendingURL); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/PayAsOrderPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/PayAsOrderPopulator.java new file mode 100644 index 00000000..72f79d47 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/PayAsOrderPopulator.java @@ -0,0 +1,46 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.data.Amount; +import com.worldpay.data.payment.PayAsOrder; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.PayAsOrder} with the information of a {@link PayAsOrder}. + */ +public class PayAsOrderPopulator implements Populator { + + protected final Converter internalAmountConverter; + + public PayAsOrderPopulator(final Converter internalAmountConverter) { + this.internalAmountConverter = internalAmountConverter; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final PayAsOrder source, + final com.worldpay.internal.model.PayAsOrder target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getOriginalMerchantCode()) + .ifPresent(target::setMerchantCode); + + Optional.ofNullable(source.getOriginalOrderCode()) + .ifPresent(target::setOrderCode); + + Optional.ofNullable(source.getAmount()) + .map(internalAmountConverter::convert) + .ifPresent(target::setAmount); + + Optional.ofNullable(source.getCvc()) + .ifPresent(target::setCvc); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/StoredCredentialsPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/StoredCredentialsPopulator.java new file mode 100644 index 00000000..1720d051 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/payment/StoredCredentialsPopulator.java @@ -0,0 +1,37 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; +import com.worldpay.enums.payment.storedCredentials.Usage; +import com.worldpay.data.payment.StoredCredentials; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.StoredCredentials} with the information of a {@link StoredCredentials}. + */ +public class StoredCredentialsPopulator implements Populator { + + /** + * {@inheritDoc} + */ + @Override + public void populate(final StoredCredentials source, + final com.worldpay.internal.model.StoredCredentials target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getMerchantInitiatedReason()) + .map(MerchantInitiatedReason::name) + .ifPresent(target::setMerchantInitiatedReason); + + Optional.ofNullable(source.getUsage()) + .map(Usage::name) + .ifPresent(target::setUsage); + + target.setSchemeTransactionIdentifier(source.getSchemeTransactionIdentifier()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/Additional3DSDataPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/Additional3DSDataPopulator.java new file mode 100644 index 00000000..edb3d56b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/Additional3DSDataPopulator.java @@ -0,0 +1,37 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.data.threeds2.Additional3DSData; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.Additional3DSData} with the information of a {@link Additional3DSData} + */ +public class Additional3DSDataPopulator implements Populator { + + /** + * Populates the data from the {@link Additional3DSData} to a {@link com.worldpay.internal.model.Additional3DSData} + * + * @param source a {@link Additional3DSData} from Worldpay + * @param target a {@link com.worldpay.internal.model.Additional3DSData} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final Additional3DSData source, final com.worldpay.internal.model.Additional3DSData target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + Optional.ofNullable(source.getChallengePreference()) + .ifPresent(target::setChallengePreference); + + Optional.ofNullable(source.getChallengeWindowSize()) + .ifPresent(target::setChallengeWindowSize); + + target.setDfReferenceId(source.getDfReferenceId()); + + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/AuthenticationRiskDataPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/AuthenticationRiskDataPopulator.java new file mode 100644 index 00000000..5ac5e0cf --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/AuthenticationRiskDataPopulator.java @@ -0,0 +1,49 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.internal.model.AuthenticationTimestamp; +import com.worldpay.data.Date; +import com.worldpay.data.threeds2.AuthenticationRiskData; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.AuthenticationRiskData} with the information of a {@link AuthenticationRiskData} + */ +public class AuthenticationRiskDataPopulator implements Populator { + + protected final Converter internalDateConverter; + + public AuthenticationRiskDataPopulator(final Converter internalDateConverter) { + this.internalDateConverter = internalDateConverter; + } + + /** + * Populates the data from the {@link AuthenticationRiskData} to a {@link com.worldpay.internal.model.AuthenticationRiskData} + * + * @param source a {@link AuthenticationRiskData} from Worldpay + * @param target a {@link com.worldpay.internal.model.AuthenticationRiskData} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final AuthenticationRiskData source, final com.worldpay.internal.model.AuthenticationRiskData target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setAuthenticationMethod(source.getAuthenticationMethod()); + + Optional.ofNullable(source.getAuthenticationTimestamp()) + .map(this::createIntAuthenticationTimestamp) + .ifPresent(target::setAuthenticationTimestamp); + } + + private AuthenticationTimestamp createIntAuthenticationTimestamp(final Date date) { + final AuthenticationTimestamp intAuthenticationTimestamp = new AuthenticationTimestamp(); + intAuthenticationTimestamp.setDate(internalDateConverter.convert(date)); + return intAuthenticationTimestamp; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/RiskDataPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/RiskDataPopulator.java new file mode 100644 index 00000000..27d06b3c --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/RiskDataPopulator.java @@ -0,0 +1,57 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.data.threeds2.AuthenticationRiskData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.threeds2.ShopperAccountRiskData; +import com.worldpay.data.threeds2.TransactionRiskData; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.RiskData} with the information of a {@link RiskData} + */ +public class RiskDataPopulator implements Populator { + + protected final Converter internalAuthenticationRiskDataConverter; + protected final Converter internalShopperAccountRiskDataConverter; + protected final Converter internalTransactionRiskDataConverter; + + public RiskDataPopulator(final Converter internalAuthenticationRiskDataConverter, + final Converter internalShopperAccountRiskDataConverter, + final Converter internalTransactionRiskDataConverter) { + + this.internalAuthenticationRiskDataConverter = internalAuthenticationRiskDataConverter; + this.internalShopperAccountRiskDataConverter = internalShopperAccountRiskDataConverter; + this.internalTransactionRiskDataConverter = internalTransactionRiskDataConverter; + } + + /** + * Populates the data from the {@link RiskData} to a {@link com.worldpay.internal.model.RiskData} + * + * @param source a {@link RiskData} from Worldpay + * @param target a {@link com.worldpay.internal.model.RiskData} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final RiskData source, final com.worldpay.internal.model.RiskData target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + Optional.ofNullable(source.getAuthenticationRiskData()) + .map(internalAuthenticationRiskDataConverter::convert) + .ifPresent(target::setAuthenticationRiskData); + + Optional.ofNullable(source.getShopperAccountRiskData()) + .map(internalShopperAccountRiskDataConverter::convert) + .ifPresent(target::setShopperAccountRiskData); + + Optional.ofNullable(source.getTransactionRiskData()) + .map(internalTransactionRiskDataConverter::convert) + .ifPresent(target::setTransactionRiskData); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/ShopperAccountRiskDataPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/ShopperAccountRiskDataPopulator.java new file mode 100644 index 00000000..c08ab602 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/ShopperAccountRiskDataPopulator.java @@ -0,0 +1,79 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.internal.model.*; +import com.worldpay.data.Date; +import com.worldpay.data.threeds2.ShopperAccountRiskData; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.ShopperAccountRiskData} with the information of a {@link ShopperAccountRiskData} + */ +public class ShopperAccountRiskDataPopulator implements Populator { + + protected final Converter internalDateConverter; + + public ShopperAccountRiskDataPopulator(final Converter internalDateConverter) { + this.internalDateConverter = internalDateConverter; + } + + /** + * Populates the data from the {@link ShopperAccountRiskData} to a {@link com.worldpay.internal.model.ShopperAccountRiskData} + * + * @param source a {@link ShopperAccountRiskData} from Worldpay + * @param target a {@link com.worldpay.internal.model.ShopperAccountRiskData} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final ShopperAccountRiskData source, final com.worldpay.internal.model.ShopperAccountRiskData target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setTransactionsAttemptedLastDay(source.getTransactionsAttemptedLastDay()); + target.setTransactionsAttemptedLastYear(source.getTransactionsAttemptedLastYear()); + target.setPurchasesCompletedLastSixMonths(source.getPurchasesCompletedLastSixMonths()); + target.setAddCardAttemptsLastDay(source.getAddCardAttemptsLastDay()); + target.setPreviousSuspiciousActivity(source.getPreviousSuspiciousActivity()); + target.setShippingNameMatchesAccountName(source.getShippingNameMatchesAccountName()); + target.setShopperAccountAgeIndicator(source.getShopperAccountAgeIndicator()); + target.setShopperAccountChangeIndicator(source.getShopperAccountChangeIndicator()); + target.setShopperAccountPasswordChangeIndicator(source.getShopperAccountPasswordChangeIndicator()); + target.setShopperAccountShippingAddressUsageIndicator(source.getShopperAccountShippingAddressUsageIndicator()); + target.setShopperAccountPaymentAccountIndicator(source.getShopperAccountPaymentAccountIndicator()); + + Optional.ofNullable(source.getShopperAccountCreationDate()).ifPresent(date -> { + final ShopperAccountCreationDate accountCreationDate = new ShopperAccountCreationDate(); + accountCreationDate.setDate(internalDateConverter.convert(date)); + target.setShopperAccountCreationDate(accountCreationDate); + }); + + Optional.ofNullable(source.getShopperAccountShippingAddressFirstUseDate()).ifPresent(date -> { + final ShopperAccountShippingAddressFirstUseDate accountShippingAddressFirstUseDate = new ShopperAccountShippingAddressFirstUseDate(); + accountShippingAddressFirstUseDate.setDate(internalDateConverter.convert(date)); + target.setShopperAccountShippingAddressFirstUseDate(accountShippingAddressFirstUseDate); + }); + + Optional.ofNullable(source.getShopperAccountModificationDate()).ifPresent(date -> { + final ShopperAccountModificationDate accountModificationDate = new ShopperAccountModificationDate(); + accountModificationDate.setDate(internalDateConverter.convert(date)); + target.setShopperAccountModificationDate(accountModificationDate); + }); + + Optional.ofNullable(source.getShopperAccountPaymentAccountFirstUseDate()).ifPresent(date -> { + final ShopperAccountPaymentAccountFirstUseDate shopperAccountPaymentAccountFirstUseDate = new ShopperAccountPaymentAccountFirstUseDate(); + shopperAccountPaymentAccountFirstUseDate.setDate(internalDateConverter.convert(date)); + target.setShopperAccountPaymentAccountFirstUseDate(shopperAccountPaymentAccountFirstUseDate); + }); + + Optional.ofNullable(source.getShopperAccountPasswordChangeDate()).ifPresent(date -> { + final ShopperAccountPasswordChangeDate shopperAccountPasswordChangeDate = new ShopperAccountPasswordChangeDate(); + shopperAccountPasswordChangeDate.setDate(internalDateConverter.convert(date)); + target.setShopperAccountPasswordChangeDate(shopperAccountPasswordChangeDate); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataGiftCardAmountPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataGiftCardAmountPopulator.java new file mode 100644 index 00000000..8ab14654 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataGiftCardAmountPopulator.java @@ -0,0 +1,40 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.data.Amount; +import com.worldpay.data.threeds2.TransactionRiskDataGiftCardAmount; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.TransactionRiskDataGiftCardAmount} with the information of a {@link TransactionRiskDataGiftCardAmount} + */ +public class TransactionRiskDataGiftCardAmountPopulator implements Populator { + + protected final Converter internalAmountConverter; + + public TransactionRiskDataGiftCardAmountPopulator(final Converter internalAmountConverter) { + this.internalAmountConverter = internalAmountConverter; + } + + /** + * Populates the data from the {@link TransactionRiskDataGiftCardAmount} to a {@link com.worldpay.internal.model.TransactionRiskDataGiftCardAmount} + * + * @param source a {@link TransactionRiskDataGiftCardAmount} from Worldpay + * @param target a {@link com.worldpay.internal.model.TransactionRiskDataGiftCardAmount} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final TransactionRiskDataGiftCardAmount source, final com.worldpay.internal.model.TransactionRiskDataGiftCardAmount target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + Optional.ofNullable(source.getAmount()) + .map(internalAmountConverter::convert) + .ifPresent(target::setAmount); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataPopulator.java new file mode 100644 index 00000000..0200784b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataPopulator.java @@ -0,0 +1,59 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + + +import com.worldpay.internal.model.TransactionRiskDataPreOrderDate; +import com.worldpay.data.Date; +import com.worldpay.data.threeds2.TransactionRiskData; +import com.worldpay.data.threeds2.TransactionRiskDataGiftCardAmount; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.TransactionRiskData} with the information of a {@link TransactionRiskData} + */ +public class TransactionRiskDataPopulator implements Populator { + + protected final Converter internalDateConverter; + protected final Converter internalTransactionRiskDataGiftCardAmountConverter; + + public TransactionRiskDataPopulator(final Converter internalDateConverter, + final Converter internalTransactionRiskDataGiftCardAmountConverter) { + this.internalDateConverter = internalDateConverter; + this.internalTransactionRiskDataGiftCardAmountConverter = internalTransactionRiskDataGiftCardAmountConverter; + } + + /** + * Populates the data from the {@link TransactionRiskData} to a {@link com.worldpay.internal.model.TransactionRiskData} + * + * @param source a {@link TransactionRiskData} from Worldpay + * @param target a {@link com.worldpay.internal.model.TransactionRiskData} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final TransactionRiskData source, final com.worldpay.internal.model.TransactionRiskData target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target must not be null!"); + + target.setDeliveryEmailAddress(source.getDeliveryEmailAddress()); + target.setDeliveryTimeframe(source.getDeliveryTimeframe()); + target.setGiftCardCount(source.getGiftCardCount()); + target.setPreOrderPurchase(source.getPreOrderPurchase()); + target.setReorderingPreviousPurchases(source.getReorderingPreviousPurchases()); + target.setShippingMethod(source.getShippingMethod()); + + Optional.ofNullable(source.getTransactionRiskDataPreOrderDate()).ifPresent(date -> { + final TransactionRiskDataPreOrderDate transactionRiskDataPreOrderDate = new TransactionRiskDataPreOrderDate(); + transactionRiskDataPreOrderDate.setDate(internalDateConverter.convert(date)); + target.setTransactionRiskDataPreOrderDate(transactionRiskDataPreOrderDate); + }); + + Optional.ofNullable(source.getTransactionRiskDataGiftCardAmount()) + .map(internalTransactionRiskDataGiftCardAmountConverter::convert) + .ifPresent(target::setTransactionRiskDataGiftCardAmount); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/CardDetailsPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/CardDetailsPopulator.java new file mode 100644 index 00000000..3a99fe0a --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/CardDetailsPopulator.java @@ -0,0 +1,72 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.data.token.CardDetails; +import com.worldpay.internal.model.*; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.CardDetails} with the information of a {@link CardDetails}. + */ +public class CardDetailsPopulator implements Populator { + + protected final Converter internalAddressConverter; + protected final Converter internalDateConverter; + + public CardDetailsPopulator(final Converter internalAddressConverter, + final Converter internalDateConverter) { + this.internalAddressConverter = internalAddressConverter; + this.internalDateConverter = internalDateConverter; + } + + /** + * Populates the data from the {@link CardDetails} to a {@link com.worldpay.internal.model.CardDetails} + * + * @param source a {@link CardDetails} from Worldpay + * @param target a {@link com.worldpay.internal.model.TransactionRiskData} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final CardDetails source, final com.worldpay.internal.model.CardDetails target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getCvcNumber()).ifPresent(cvcNumber -> { + final Cvc internalCvc = new Cvc(); + internalCvc.setvalue(cvcNumber); + target.setCvc(internalCvc); + }); + + Optional.ofNullable(source.getCardAddress()).ifPresent(cardAddress -> { + final CardAddress internalCardAddress = new CardAddress(); + internalCardAddress.setAddress(internalAddressConverter.convert(cardAddress)); + target.setCardAddress(internalCardAddress); + }); + + Optional.ofNullable(source.getCardHolderName()).ifPresent(cardHolderName -> { + final CardHolderName internalCardHolderName = new CardHolderName(); + internalCardHolderName.setvalue(cardHolderName); + target.setCardHolderName(internalCardHolderName); + }); + + Optional.ofNullable(source.getExpiryDate()).ifPresent(expiryDate -> { + final ExpiryDate internalExpiryDate = new ExpiryDate(); + internalExpiryDate.setDate(internalDateConverter.convert(expiryDate)); + target.setExpiryDate(internalExpiryDate); + }); + + Optional.ofNullable(source.getCardNumber()).ifPresent(cardNumber -> { + final Derived internalDerived = new Derived(); + internalDerived.setObfuscatedPAN(cardNumber); + internalDerived.setIssuerCountryCode(source.getIssuerCountryCode()); + internalDerived.setCardSubBrand(source.getCardSubBrand()); + internalDerived.setCardBrand(source.getCardBrand()); + target.setDerived(internalDerived); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/PaymentTokenCreatePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/PaymentTokenCreatePopulator.java new file mode 100644 index 00000000..13ebbfa7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/PaymentTokenCreatePopulator.java @@ -0,0 +1,66 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.converters.internal.model.payment.PaymentConverterStrategy; +import com.worldpay.internal.model.AuthenticatedShopperID; +import com.worldpay.internal.model.CreateToken; +import com.worldpay.internal.model.PaymentTokenCreate; +import com.worldpay.internal.model.TransactionRiskData; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.token.CardTokenRequest; +import com.worldpay.data.token.TokenRequest; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link PaymentTokenCreate} with the information of a {@link CardTokenRequest}. + */ +public class PaymentTokenCreatePopulator implements Populator { + + protected final Converter internalTokenRequestConverter; + protected final Converter internalStoredCredentialsConverter; + protected final PaymentConverterStrategy internalPaymentConverterStrategy; + + public PaymentTokenCreatePopulator(final Converter internalTokenRequestConverter, + final Converter internalStoredCredentialsConverter, + final PaymentConverterStrategy internalPaymentConverterStrategy) { + this.internalTokenRequestConverter = internalTokenRequestConverter; + this.internalStoredCredentialsConverter = internalStoredCredentialsConverter; + this.internalPaymentConverterStrategy = internalPaymentConverterStrategy; + } + + /** + * Populates the data from the {@link CardTokenRequest} to a {@link PaymentTokenCreate} + * + * @param source a {@link CardTokenRequest} from Worldpay + * @param target a {@link TransactionRiskData} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final CardTokenRequest source, final PaymentTokenCreate target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getAuthenticatedShopperId()).ifPresent(shopperId -> { + final AuthenticatedShopperID internalAuthenticatedShopperID = new AuthenticatedShopperID(); + internalAuthenticatedShopperID.setvalue(shopperId); + target.setAuthenticatedShopperID(internalAuthenticatedShopperID); + }); + + Optional.ofNullable(source.getTokenRequest()) + .map(internalTokenRequestConverter::convert) + .ifPresent(target::setCreateToken); + + Optional.ofNullable(source.getStoredCredentials()) + .map(internalStoredCredentialsConverter::convert) + .ifPresent(target::setStoredCredentials); + + Optional.ofNullable(source.getPayment()) + .map(internalPaymentConverterStrategy::convertPayment) + .ifPresent(intPayment -> target.getPaymentInstrumentOrCSEDATA().add(intPayment)); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/PaymentTokenDeletePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/PaymentTokenDeletePopulator.java new file mode 100644 index 00000000..c7d823eb --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/PaymentTokenDeletePopulator.java @@ -0,0 +1,54 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.internal.model.*; +import com.worldpay.data.token.DeleteTokenRequest; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link PaymentTokenDelete} with the information of a {@link DeleteTokenRequest}. + */ +public class PaymentTokenDeletePopulator implements Populator { + + private static final String MERCHANT = "merchant"; + + /** + * Populates the data from the {@link DeleteTokenRequest} to a {@link PaymentTokenDelete} + * + * @param source a {@link DeleteTokenRequest} from Worldpay + * @param target a {@link TransactionRiskData} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final DeleteTokenRequest source, final PaymentTokenDelete target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + if (source.getTokenRequest().isMerchantToken()) { + target.setTokenScope(MERCHANT); + } + + Optional.ofNullable(source.getAuthenticatedShopperId()).ifPresent(shopperId -> { + final AuthenticatedShopperID internalAuthenticatedShopperID = new AuthenticatedShopperID(); + internalAuthenticatedShopperID.setvalue(shopperId); + target.setAuthenticatedShopperID(internalAuthenticatedShopperID); + }); + + Optional.ofNullable(source.getPaymentTokenId()).ifPresent(paymentTokenId -> { + final PaymentTokenID internalPaymentTokenIDWrapper = new PaymentTokenID(); + internalPaymentTokenIDWrapper.setvalue(paymentTokenId); + target.setPaymentTokenID(internalPaymentTokenIDWrapper); + }); + + Optional.ofNullable(source.getTokenRequest()).ifPresent(tokenRequest -> { + target.setTokenEventReference(tokenRequest.getTokenEventReference()); + final TokenReason internalTokenReason = new TokenReason(); + internalTokenReason.setvalue(tokenRequest.getTokenReason()); + target.setTokenReason(internalTokenReason); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/PaymentTokenUpdatePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/PaymentTokenUpdatePopulator.java new file mode 100644 index 00000000..0dd28d24 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/PaymentTokenUpdatePopulator.java @@ -0,0 +1,74 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.internal.model.*; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.data.token.UpdateTokenRequest; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.PaymentTokenUpdate} with the information of a {@link UpdateTokenRequest}. + */ +public class PaymentTokenUpdatePopulator implements Populator { + + private static final String MERCHANT = "merchant"; + + protected final Converter internalCardDetailsConverter; + + public PaymentTokenUpdatePopulator(final Converter internalCardDetailsConverter) { + this.internalCardDetailsConverter = internalCardDetailsConverter; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final UpdateTokenRequest source, + final PaymentTokenUpdate target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + if (source.isMerchantToken()) { + target.setTokenScope(MERCHANT); + target.setAuthenticatedShopperID(null); + } else { + Optional.ofNullable(source.getAuthenticatedShopperID()) + .ifPresent(shopperId -> { + final AuthenticatedShopperID intAuthenticatedShopperID = new AuthenticatedShopperID(); + intAuthenticatedShopperID.setvalue(shopperId); + target.setAuthenticatedShopperID(intAuthenticatedShopperID); + }); + } + + final PaymentTokenID intPaymentTokenIDWrapper = new PaymentTokenID(); + intPaymentTokenIDWrapper.setvalue(source.getPaymentTokenId()); + target.setPaymentTokenID(intPaymentTokenIDWrapper); + + Optional.ofNullable(source.getTokenRequest()) + .map(TokenRequest::getTokenEventReference) + .ifPresent(target::setTokenEventReference); + + Optional.ofNullable(source.getCardDetails()) + .map(internalCardDetailsConverter::convert) + .ifPresent(intCardDetails -> { + final PaymentInstrument intPaymentInstrument = new PaymentInstrument(); + intPaymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL() + .add(intCardDetails); + target.setPaymentInstrument(intPaymentInstrument); + }); + + Optional.ofNullable(source.getTokenRequest()) + .map(TokenRequest::getTokenReason) + .ifPresent(tokenReason -> { + final TokenReason intTokenReason = new TokenReason(); + intTokenReason.setvalue(tokenReason); + target.setTokenReason(intTokenReason); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/TokenPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/TokenPopulator.java new file mode 100644 index 00000000..e865987e --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/TokenPopulator.java @@ -0,0 +1,56 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.internal.model.PaymentInstrument; +import com.worldpay.internal.model.PaymentTokenID; +import com.worldpay.internal.model.TOKENSSL; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.Token; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.List; +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.TOKENSSL} with the information of a {@link Token}. + */ +public class TokenPopulator implements Populator { + + private static final String MERCHANT = "merchant"; + private static final String SHOPPER = "shopper"; + + protected final Converter internalCardDetailsConverter; + + public TokenPopulator(final Converter internalCardDetailsConverter) { + this.internalCardDetailsConverter = internalCardDetailsConverter; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(final Token source, final TOKENSSL target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + target.setTokenScope(source.isMerchantToken() ? MERCHANT : SHOPPER); + + final List tokenElements = target.getPaymentTokenIDOrPaymentInstrumentOrCvcOrSession(); + Optional.ofNullable(source.getPaymentTokenID()).ifPresent(tokenId -> { + final PaymentTokenID paymentTokenIDElement = new PaymentTokenID(); + paymentTokenIDElement.setvalue(tokenId); + tokenElements.add(paymentTokenIDElement); + }); + + Optional.ofNullable(source.getPaymentInstrument()) + .map(internalCardDetailsConverter::convert) + .ifPresent(cardDetails -> { + final PaymentInstrument intPaymentInstrument = new PaymentInstrument(); + intPaymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().add(cardDetails); + tokenElements.add(intPaymentInstrument); + }); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/TokenRequestPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/TokenRequestPopulator.java new file mode 100644 index 00000000..4cd27fb5 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/internal/model/token/TokenRequestPopulator.java @@ -0,0 +1,39 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.internal.model.CreateToken; +import com.worldpay.internal.model.TokenReason; +import com.worldpay.data.token.TokenRequest; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link com.worldpay.internal.model.CreateToken} with the information of a {@link TokenRequest}. + */ +public class TokenRequestPopulator implements Populator { + + private static final String MERCHANT = "merchant"; + private static final String SHOPPER = "shopper"; + + /** + * {@inheritDoc} + */ + @Override + public void populate(final TokenRequest source, final CreateToken target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + Optional.ofNullable(source.getTokenReason()).ifPresent(token -> { + final TokenReason intTokenReason = new TokenReason(); + intTokenReason.setvalue(token); + target.setTokenReason(intTokenReason); + }); + + target.setTokenEventReference(source.getTokenEventReference()); + + target.setTokenScope(source.isMerchantToken() ? MERCHANT : SHOPPER); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/reverse/internal/model/AmountReversePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/reverse/internal/model/AmountReversePopulator.java new file mode 100644 index 00000000..acf1e288 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/reverse/internal/model/AmountReversePopulator.java @@ -0,0 +1,37 @@ +package com.worldpay.converters.populators.reverse.internal.model; + +import com.worldpay.data.Amount; +import com.worldpay.enums.DebitCreditIndicator; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link Amount} with the information of a {@link com.worldpay.internal.model.Amount} + */ +public class AmountReversePopulator implements Populator { + + /** + * Populates the data from the {@link com.worldpay.internal.model.Amount} to a {@link Amount} + * + * @param source a {@link com.worldpay.internal.model.Amount} from Worldpay + * @param target a {@link Amount} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final com.worldpay.internal.model.Amount source, Amount target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + target.setValue(source.getValue()); + target.setCurrencyCode(source.getCurrencyCode()); + target.setExponent(source.getExponent()); + Optional.ofNullable(source.getDebitCreditIndicator()) + .map(String::toUpperCase) + .map(DebitCreditIndicator::valueOf) + .ifPresent(target::setDebitCreditIndicator); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/reverse/internal/model/DateReversePopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/reverse/internal/model/DateReversePopulator.java new file mode 100644 index 00000000..8da9c14b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/converters/populators/reverse/internal/model/DateReversePopulator.java @@ -0,0 +1,33 @@ +package com.worldpay.converters.populators.reverse.internal.model; + +import com.worldpay.data.Date; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Populator that fills the necessary details on a {@link Date} with the information of a {@link com.worldpay.internal.model.Date} + */ +public class DateReversePopulator implements Populator { + + /** + * Populates the data from the {@link com.worldpay.internal.model.Date} to a {@link Date} + * + * @param source a {@link com.worldpay.internal.model.Date} from Worldpay + * @param target a {@link Date} in Worldpay. + * @throws ConversionException + */ + @Override + public void populate(final com.worldpay.internal.model.Date source, final Date target) throws ConversionException { + validateParameterNotNull(source, "Source must not be null!"); + validateParameterNotNull(target, "Target list must not be null!"); + + target.setYear(source.getYear()); + target.setMonth(source.getMonth()); + target.setDayOfMonth(source.getDayOfMonth()); + target.setHour(source.getHour()); + target.setMinute(source.getMinute()); + target.setSecond(source.getSecond()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/checkout/WorldpayCheckoutService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/checkout/WorldpayCheckoutService.java index df1f81a0..8e6544b4 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/checkout/WorldpayCheckoutService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/checkout/WorldpayCheckoutService.java @@ -11,8 +11,16 @@ public interface WorldpayCheckoutService { /** * This method is used for saving the billing address in the cartModel * - * @param cartModel the cart model + * @param cartModel the cart model * @param addressModel the address model */ - void setPaymentAddress(final CartModel cartModel, final AddressModel addressModel); + void setPaymentAddress(CartModel cartModel, AddressModel addressModel); + + /** + * This method is used for saving the shipping and billing address in the cartModel + * + * @param cartModel the cart model + * @param addressModel the address model + */ + void setShippingAndPaymentAddress(CartModel cartModel, AddressModel addressModel); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/checkout/impl/DefaultWorldpayCheckoutService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/checkout/impl/DefaultWorldpayCheckoutService.java index 1ec93a59..46547314 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/checkout/impl/DefaultWorldpayCheckoutService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/checkout/impl/DefaultWorldpayCheckoutService.java @@ -4,7 +4,7 @@ import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.user.AddressModel; import de.hybris.platform.servicelayer.model.ModelService; -import org.springframework.beans.factory.annotation.Required; +import de.hybris.platform.servicelayer.user.AddressService; /** * Provides specific behaviour to the commerce checkout service to set the merchant transaction code in the same style @@ -12,7 +12,13 @@ */ public class DefaultWorldpayCheckoutService implements WorldpayCheckoutService { - private ModelService modelService; + protected final ModelService modelService; + protected final AddressService addressService; + + public DefaultWorldpayCheckoutService(final ModelService modelService, final AddressService addressService) { + this.modelService = modelService; + this.addressService = addressService; + } /** * {@inheritDoc} @@ -20,17 +26,21 @@ public class DefaultWorldpayCheckoutService implements WorldpayCheckoutService { @Override public void setPaymentAddress(final CartModel cartModel, final AddressModel addressModel) { cartModel.setPaymentAddress(addressModel); - getModelService().save(cartModel); + modelService.save(cartModel); - getModelService().refresh(cartModel); + modelService.refresh(cartModel); } - public ModelService getModelService() { - return modelService; - } + /** + * {@inheritDoc} + */ + @Override + public void setShippingAndPaymentAddress(final CartModel cartModel, final AddressModel addressModel) { + cartModel.setDeliveryAddress(addressModel); + final AddressModel paymentAddress = addressService.cloneAddress(addressModel); + cartModel.setPaymentAddress(paymentAddress); + modelService.saveAll(paymentAddress, cartModel); - @Required - public void setModelService(final ModelService modelService) { - this.modelService = modelService; + modelService.refresh(cartModel); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/dao/WorldpayAPMComponentDao.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/dao/WorldpayAPMComponentDao.java new file mode 100644 index 00000000..d64b0fda --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/dao/WorldpayAPMComponentDao.java @@ -0,0 +1,21 @@ +package com.worldpay.core.dao; + +import com.worldpay.model.WorldpayAPMComponentModel; +import de.hybris.platform.catalog.model.CatalogVersionModel; + +import java.util.Collection; +import java.util.List; + +/** + * Data access to {@link WorldpayAPMComponentModel} + */ +public interface WorldpayAPMComponentDao { + + /** + * Find all {@link WorldpayAPMComponentModel} for the given catalog versions. + * + * @param catalogVersionModels catalog versions. + * @return a list of {@link WorldpayAPMComponentModel}. + */ + List findAllApmComponents(final Collection catalogVersionModels); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/dao/impl/DefaultWorldpayAPMComponentDao.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/dao/impl/DefaultWorldpayAPMComponentDao.java new file mode 100644 index 00000000..742bc6c8 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/dao/impl/DefaultWorldpayAPMComponentDao.java @@ -0,0 +1,34 @@ +package com.worldpay.core.dao.impl; + +import com.worldpay.core.dao.WorldpayAPMComponentDao; +import com.worldpay.model.WorldpayAPMComponentModel; +import de.hybris.platform.catalog.model.CatalogVersionModel; +import de.hybris.platform.cms2.model.contents.CMSItemModel; +import de.hybris.platform.cms2.servicelayer.daos.impl.AbstractCMSItemDao; +import de.hybris.platform.core.model.ItemModel; +import de.hybris.platform.servicelayer.search.SearchResult; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * {@inheritDoc} + */ +public class DefaultWorldpayAPMComponentDao extends AbstractCMSItemDao implements WorldpayAPMComponentDao { + + private static final String QUERY = "SELECT {wc." + ItemModel.PK + "} " + + "FROM {" + WorldpayAPMComponentModel._TYPECODE + " AS wc} " + + "WHERE {wc." + CMSItemModel.CATALOGVERSION + "} IN (?catalogVersions)"; + + /** + * {@inheritDoc} + */ + @Override + public List findAllApmComponents(final Collection catalogVersionModels) { + final Map params = Map.of("catalogVersions", catalogVersionModels); + + final SearchResult searchResult = getFlexibleSearchService().search(QUERY, params); + return searchResult.getResult(); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/OrderInquiryService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/OrderInquiryService.java index 30dd76ce..112426a6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/OrderInquiryService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/OrderInquiryService.java @@ -2,7 +2,7 @@ import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.response.OrderInquiryServiceResponse; import de.hybris.platform.payment.model.PaymentTransactionModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayAPMComponentService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayAPMComponentService.java new file mode 100644 index 00000000..0878f2ab --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayAPMComponentService.java @@ -0,0 +1,18 @@ +package com.worldpay.core.services; + +import com.worldpay.model.WorldpayAPMComponentModel; + +import java.util.List; + +/** + * Exposes a method for getting all available Worldpay apm components. + */ +public interface WorldpayAPMComponentService { + + /** + * Get all available {@link WorldpayAPMComponentModel}. + * + * @return a list with all available WorldpayAPMComponentModel. + */ + List getAllAvailableWorldpayAPMComponents(); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayCartService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayCartService.java index 89e361fa..e8f2cf3d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayCartService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayCartService.java @@ -1,6 +1,10 @@ package com.worldpay.core.services; +import com.worldpay.data.AdditionalAuthInfo; +import com.worldpay.data.Address; +import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.core.model.order.CartModel; +import de.hybris.platform.core.model.user.AddressModel; /** * Service providing extended Worldpay cart service functionality. @@ -14,7 +18,7 @@ public interface WorldpayCartService { * * @param shopperBankCode the shopper bank code */ - void resetDeclineCodeAndShopperBankOnCart(final String shopperBankCode); + void resetDeclineCodeAndShopperBankOnCart(String shopperBankCode); /** * Sets worldpay decline code on the {@link de.hybris.platform.core.model.order.CartModel}. @@ -22,7 +26,7 @@ public interface WorldpayCartService { * @param worldpayOrderCode the worldpay order code * @param declineCode the decline code */ - void setWorldpayDeclineCodeOnCart(final String worldpayOrderCode, final String declineCode); + void setWorldpayDeclineCodeOnCart(String worldpayOrderCode, String declineCode); /** * Returns the cart for the given WorldpayOrderCode @@ -30,12 +34,55 @@ public interface WorldpayCartService { * @param worldpayOrderCode * @return cart for the given worldpayCode */ - CartModel findCartByWorldpayOrderCode(final String worldpayOrderCode); + CartModel findCartByWorldpayOrderCode(String worldpayOrderCode); /** * Store the session id from the initial payment request on the cart * * @param sessionId */ - void setSessionId(final String sessionId); + void setSessionId(String sessionId); + + /** + * Returns a unique authenticated shopper ID. + * + * @param cartModel {@link CartModel} + * @return AuthenticatedShopperId + */ + String getAuthenticatedShopperId(AbstractOrderModel cartModel); + + + /** + * Gets the delivery Address for given cart, id delivery address true will return the delivery address, otherwise payment address + * + * @param abstractOrder + * @param isDeliveryAddress if it's delivery addresss + * @return {@link Address} + */ + Address getAddressFromCart(AbstractOrderModel abstractOrder, boolean isDeliveryAddress); + + /** + * Gets the billing address from cart + * + * @param cartModel + * @param additionalAuthInfo + * @return {@link Address} + */ + Address getBillingAddress(CartModel cartModel, AdditionalAuthInfo additionalAuthInfo); + + /** + * Converts the addressModel type to an address + * + * @param addressModel the model to convert + * @return {@link Address} + */ + Address convertAddressModelToAddress(AddressModel addressModel); + + /** + * Get customer email + * + * @param cart the customer cart + * @return the customer email + */ + String getEmailForCustomer(AbstractOrderModel cart); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayHybrisOrderService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayHybrisOrderService.java index 8c9028fd..becee9bd 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayHybrisOrderService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayHybrisOrderService.java @@ -15,7 +15,7 @@ public interface WorldpayHybrisOrderService { * @param worldpayOrderCode the worldpay order code * @param declineCode the decline code */ - void setWorldpayDeclineCodeOnOrder(final String worldpayOrderCode, final String declineCode); + void setWorldpayDeclineCodeOnOrder(String worldpayOrderCode, String declineCode); /** * Returns the order by WorldpayOrderCode diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayPaymentInfoService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayPaymentInfoService.java index 98e2c96f..a089570b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayPaymentInfoService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayPaymentInfoService.java @@ -3,9 +3,9 @@ import com.worldpay.data.ApplePayAdditionalAuthInfo; import com.worldpay.data.GooglePayAdditionalAuthInfo; import com.worldpay.exception.WorldpayConfigurationException; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.payment.Card; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.payment.Card; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.notification.OrderNotificationMessage; import com.worldpay.service.request.UpdateTokenServiceRequest; import com.worldpay.service.response.CreateTokenResponse; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayPrimeRoutingService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayPrimeRoutingService.java new file mode 100644 index 00000000..bb5d19df --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/WorldpayPrimeRoutingService.java @@ -0,0 +1,34 @@ +package com.worldpay.core.services; + +import de.hybris.platform.core.model.order.AbstractOrderModel; + +/** + * Prime Routing service interface. This service is responsible for verifying if prime routing is enabled and other prime routing functionalities + */ +public interface WorldpayPrimeRoutingService { + + /** + * Verifies if prime routing is enable for the given cart. + * For it to be enabled feature must be enabled on the base site and billing address must be a US address + * + * @param cartModel the cart + * @return true if prime routing is enabled, false otherwise + */ + boolean isPrimeRoutingEnabled(AbstractOrderModel cartModel); + + /** + * Sets the flag authorised with prime routing to true + * + * @param cart the cart + */ + void setAuthorisedWithPrimeRoutingOnCart(AbstractOrderModel cart); + + /** + * Returns true if order with the given code is authorised with prime routing + * + * @param worldpayOrderCode teh worldpay order code + * @return true if it's authorised with Prime Routing, false otherwise + */ + boolean isOrderAuthorisedWithPrimeRouting(String worldpayOrderCode); + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultAPMConfigurationLookupService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultAPMConfigurationLookupService.java index 93cac680..4e365811 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultAPMConfigurationLookupService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultAPMConfigurationLookupService.java @@ -4,10 +4,9 @@ import com.worldpay.core.services.APMConfigurationLookupService; import com.worldpay.model.WorldpayAPMConfigurationModel; import com.worldpay.service.model.payment.PaymentType; -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Required; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.text.MessageFormat; import java.util.*; /** @@ -15,9 +14,13 @@ */ public class DefaultAPMConfigurationLookupService implements APMConfigurationLookupService { - private static final Logger LOG = Logger.getLogger(DefaultAPMConfigurationLookupService.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultAPMConfigurationLookupService.class); - private WorldpayAPMConfigurationDao worldpayAPMConfigurationDao; + protected final WorldpayAPMConfigurationDao worldpayAPMConfigurationDao; + + public DefaultAPMConfigurationLookupService(final WorldpayAPMConfigurationDao worldpayAPMConfigurationDao) { + this.worldpayAPMConfigurationDao = worldpayAPMConfigurationDao; + } /** * {@inheritDoc} @@ -27,12 +30,12 @@ public WorldpayAPMConfigurationModel getAPMConfigurationForCode(final String pay final Map queryParams = Collections.singletonMap(WorldpayAPMConfigurationModel.CODE, paymentTypeCode); final List worldpayAPMConfigurationModels = worldpayAPMConfigurationDao.find(queryParams); if (worldpayAPMConfigurationModels.isEmpty()) { - LOG.error(MessageFormat.format("Could not find unique WorldpayAlternativePaymentMethod with code [{0}]", paymentTypeCode)); + LOG.error("Could not find unique WorldpayAlternativePaymentMethod with code [{}]", paymentTypeCode); return null; } else { final WorldpayAPMConfigurationModel worldpayAPMConfigurationModel = worldpayAPMConfigurationModels.get(0); if (worldpayAPMConfigurationModels.size() > 1) { - LOG.error(MessageFormat.format("Multiple WorldpayAPMConfiguration with code [{0}], returning first [{1}]", paymentTypeCode, worldpayAPMConfigurationModel.getCode())); + LOG.error("Multiple WorldpayAPMConfiguration with code [{}], returning first [{}]", paymentTypeCode, worldpayAPMConfigurationModel.getCode()); return worldpayAPMConfigurationModel; } else { return worldpayAPMConfigurationModel; @@ -55,8 +58,4 @@ public Set getAllApmPaymentTypeCodes() { return apmPaymentTypesCodes; } - @Required - public void setWorldpayAPMConfigurationDao(final WorldpayAPMConfigurationDao worldpayAPMConfigurationDao) { - this.worldpayAPMConfigurationDao = worldpayAPMConfigurationDao; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultOrderInquiryService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultOrderInquiryService.java index 01b5bfe5..8afcca13 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultOrderInquiryService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultOrderInquiryService.java @@ -11,7 +11,7 @@ import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.exception.WorldpayException; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.AbstractServiceRequest; import com.worldpay.service.request.KlarnaOrderInquiryServiceRequest; import com.worldpay.service.request.OrderInquiryServiceRequest; @@ -19,14 +19,12 @@ import de.hybris.platform.core.model.order.payment.WorldpayAPMPaymentInfoModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.servicelayer.config.ConfigurationService; -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Required; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.temporal.ChronoUnit; import java.util.concurrent.Callable; -import static java.text.MessageFormat.format; - /** * Default implementation fo the {@link OrderInquiryService}. *

@@ -35,16 +33,24 @@ *

*/ public class DefaultOrderInquiryService implements OrderInquiryService { - private static final Logger LOG = Logger.getLogger(DefaultOrderInquiryService.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultOrderInquiryService.class); private static final String WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES = "worldpayapi.inquiry.max.number.of.retries"; private static final int DEFAULT_WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES_VALUE = 3; private static final String WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES = "worldpayapi.inquiry.delay.between.retries"; private static final int DEFAULT_WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES_VALUE = 3; - private WorldpayPaymentInfoService worldpayPaymentInfoService; - private ConfigurationService configurationService; - private WorldpayServiceGateway worldpayServiceGateway; + protected final WorldpayPaymentInfoService worldpayPaymentInfoService; + protected final ConfigurationService configurationService; + protected final WorldpayServiceGateway worldpayServiceGateway; + + public DefaultOrderInquiryService(final WorldpayPaymentInfoService worldpayPaymentInfoService, + final ConfigurationService configurationService, + final WorldpayServiceGateway worldpayServiceGateway) { + this.worldpayPaymentInfoService = worldpayPaymentInfoService; + this.configurationService = configurationService; + this.worldpayServiceGateway = worldpayServiceGateway; + } /** * {@inheritDoc} @@ -64,13 +70,13 @@ public void processOrderInquiryServiceResponse(final PaymentTransactionModel pay if (!orderInquiryServiceResponse.isError()) { final String methodCode = orderInquiryServiceResponse.getPaymentReply().getPaymentMethodCode(); worldpayPaymentInfoService.savePaymentType(paymentTransactionModel, methodCode); - if (paymentTransactionModel.getInfo().getIsApm()) { + if (Boolean.TRUE.equals(paymentTransactionModel.getInfo().getIsApm())) { worldpayPaymentInfoService.createWorldpayApmPaymentInfo(paymentTransactionModel); - LOG.info(format("Converting PaymentInfo to WorldpayAPMPaymentInfo and setting timeout-date for PaymentTransaction with code [{0}] on order with code [{1}]", - paymentTransactionModel.getCode(), paymentTransactionModel.getOrder().getCode())); + LOG.info("Converting PaymentInfo to WorldpayAPMPaymentInfo and setting timeout-date for PaymentTransaction with code [{}] on order with code [{}]", + paymentTransactionModel.getCode(), paymentTransactionModel.getOrder().getCode()); } } else { - LOG.error(format("Order inquiry service returned error [{0}]", orderInquiryServiceResponse.getErrorDetail().getMessage())); + LOG.error("Order inquiry service returned error [{}]", orderInquiryServiceResponse.getErrorDetail().getMessage()); } } @@ -118,11 +124,11 @@ private Callable getOrderInquiryServiceResponseCall private RetryConfig buildRetryConfig() { return new RetryConfigBuilder() - .retryOnSpecificExceptions(WorldpayException.class) - .withMaxNumberOfTries(configurationService.getConfiguration().getInt(WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES_VALUE)) - .withDelayBetweenTries(configurationService.getConfiguration().getInt(WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES_VALUE), ChronoUnit.SECONDS) - .withFixedBackoff() - .build(); + .retryOnSpecificExceptions(WorldpayException.class) + .withMaxNumberOfTries(configurationService.getConfiguration().getInt(WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES_VALUE)) + .withDelayBetweenTries(configurationService.getConfiguration().getInt(WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES_VALUE), ChronoUnit.SECONDS) + .withFixedBackoff() + .build(); } protected Status executeInquiryCallable(final Callable callable, final RetryConfig config) { @@ -137,18 +143,4 @@ protected KlarnaOrderInquiryServiceRequest createKlarnaOrderInquiryServiceReques return KlarnaOrderInquiryServiceRequest.createKlarnaOrderInquiryRequest(merchantInfo, orderCode); } - @Required - public void setWorldpayPaymentInfoService(final WorldpayPaymentInfoService worldpayPaymentInfoService) { - this.worldpayPaymentInfoService = worldpayPaymentInfoService; - } - - @Required - public void setWorldpayServiceGateway(final WorldpayServiceGateway worldpayServiceGateway) { - this.worldpayServiceGateway = worldpayServiceGateway; - } - - @Required - public void setConfigurationService(final ConfigurationService configurationService) { - this.configurationService = configurationService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayAPMComponentService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayAPMComponentService.java new file mode 100644 index 00000000..b960dd58 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayAPMComponentService.java @@ -0,0 +1,43 @@ +package com.worldpay.core.services.impl; + +import com.worldpay.core.dao.WorldpayAPMComponentDao; +import com.worldpay.core.services.WorldpayAPMComponentService; +import com.worldpay.model.WorldpayAPMComponentModel; +import com.worldpay.service.apm.APMAvailabilityService; +import de.hybris.platform.catalog.CatalogVersionService; +import de.hybris.platform.order.CartService; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * {@inheritDoc} + */ +public class DefaultWorldpayAPMComponentService implements WorldpayAPMComponentService { + + protected final WorldpayAPMComponentDao worldpayAPMComponentDao; + protected final CatalogVersionService catalogVersionService; + protected final CartService cartService; + protected final APMAvailabilityService apmAvailabilityService; + + public DefaultWorldpayAPMComponentService(final WorldpayAPMComponentDao worldpayAPMComponentDao, + final CatalogVersionService catalogVersionService, + final CartService cartService, + final APMAvailabilityService apmAvailabilityService) { + this.worldpayAPMComponentDao = worldpayAPMComponentDao; + this.catalogVersionService = catalogVersionService; + this.cartService = cartService; + this.apmAvailabilityService = apmAvailabilityService; + } + + /** + * {@inheritDoc} + */ + @Override + public List getAllAvailableWorldpayAPMComponents() { + return worldpayAPMComponentDao.findAllApmComponents(catalogVersionService.getSessionCatalogVersions()).stream() + .filter(worldpayAPMComponentModel -> worldpayAPMComponentModel.getApmConfiguration() != null) + .filter(worldpayAPMComponentModel -> apmAvailabilityService.isAvailable(worldpayAPMComponentModel.getApmConfiguration(), cartService.getSessionCart())) + .collect(Collectors.toList()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayBankConfigurationLookupService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayBankConfigurationLookupService.java index be4e2d2a..cef120c1 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayBankConfigurationLookupService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayBankConfigurationLookupService.java @@ -6,7 +6,6 @@ import com.worldpay.model.WorldpayAPMConfigurationModel; import com.worldpay.model.WorldpayBankConfigurationModel; import de.hybris.platform.servicelayer.internal.dao.GenericDao; -import org.springframework.beans.factory.annotation.Required; import java.util.HashMap; import java.util.List; @@ -19,8 +18,14 @@ */ public class DefaultWorldpayBankConfigurationLookupService implements WorldpayBankConfigurationLookupService { - private APMConfigurationLookupService apmConfigurationLookupService; - private GenericDao worldpayBankConfigurationGenericDao; + protected final APMConfigurationLookupService apmConfigurationLookupService; + protected final GenericDao worldpayBankConfigurationGenericDao; + + public DefaultWorldpayBankConfigurationLookupService(final APMConfigurationLookupService apmConfigurationLookupService, + final GenericDao worldpayBankConfigurationGenericDao) { + this.apmConfigurationLookupService = apmConfigurationLookupService; + this.worldpayBankConfigurationGenericDao = worldpayBankConfigurationGenericDao; + } /** * {@inheritDoc} @@ -51,14 +56,4 @@ public WorldpayBankConfigurationModel getBankConfigurationForBankCode(final Stri final List bankList = worldpayBankConfigurationGenericDao.find(ImmutableMap.of(WorldpayBankConfigurationModel.CODE, bankCode)); return bankList.get(0); } - - @Required - public void setApmConfigurationLookupService(final APMConfigurationLookupService apmConfigurationLookupService) { - this.apmConfigurationLookupService = apmConfigurationLookupService; - } - - @Required - public void setWorldpayBankConfigurationGenericDao(final GenericDao worldpayBankConfigurationGenericDao) { - this.worldpayBankConfigurationGenericDao = worldpayBankConfigurationGenericDao; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayCartService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayCartService.java index c9dd4bcc..ad881ffd 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayCartService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayCartService.java @@ -1,34 +1,57 @@ package com.worldpay.core.services.impl; +import com.google.common.base.Preconditions; import com.worldpay.core.dao.WorldpayCartDao; import com.worldpay.core.services.WorldpayCartService; +import com.worldpay.data.AdditionalAuthInfo; +import com.worldpay.data.Address; import com.worldpay.service.payment.WorldpaySessionService; import com.worldpay.service.payment.impl.OccWorldpaySessionService; +import com.worldpay.strategy.WorldpayDeliveryAddressStrategy; +import de.hybris.platform.commerceservices.customer.CustomerEmailResolutionService; +import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.core.model.order.CartModel; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.core.model.user.CustomerModel; +import de.hybris.platform.core.model.user.UserModel; import de.hybris.platform.order.CartService; +import de.hybris.platform.servicelayer.dto.converter.Converter; import de.hybris.platform.servicelayer.exceptions.AmbiguousIdentifierException; import de.hybris.platform.servicelayer.exceptions.ModelNotFoundException; -import org.apache.log4j.Logger; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.text.MessageFormat; +import static java.text.MessageFormat.format; + /** * {@inheritDoc} */ public class DefaultWorldpayCartService implements WorldpayCartService { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayCartService.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayCartService.class); protected final WorldpayCartDao worldpayCartDao; protected final CartService cartService; protected final WorldpaySessionService worldpaySessionService; + protected final Converter worldpayAddressConverter; + protected final WorldpayDeliveryAddressStrategy worldpayDeliveryAddressStrategy; + protected final CustomerEmailResolutionService customerEmailResolutionService; public DefaultWorldpayCartService(final WorldpayCartDao worldpayCartDao, final CartService cartService, - final WorldpaySessionService worldpaySessionService) { + final WorldpaySessionService worldpaySessionService, + final Converter worldpayAddressConverter, + final WorldpayDeliveryAddressStrategy worldpayDeliveryAddressStrategy, + final CustomerEmailResolutionService customerEmailResolutionService) { this.worldpayCartDao = worldpayCartDao; this.cartService = cartService; this.worldpaySessionService = worldpaySessionService; + this.worldpayAddressConverter = worldpayAddressConverter; + this.worldpayDeliveryAddressStrategy = worldpayDeliveryAddressStrategy; + this.customerEmailResolutionService = customerEmailResolutionService; } /** @@ -77,4 +100,60 @@ public void setSessionId(final String sessionId) { ((OccWorldpaySessionService) worldpaySessionService).setSessionIdFor3dSecure(sessionId); } } + + /** + * {@inheritDoc} + */ + @Override + public String getAuthenticatedShopperId(final AbstractOrderModel cartModel) { + final UserModel userModel = cartModel.getUser(); + + Preconditions.checkNotNull(userModel, "The user is null"); + if (userModel instanceof CustomerModel) { + final String customerID = ((CustomerModel) userModel).getCustomerID(); + return StringUtils.defaultIfBlank(customerID, ((CustomerModel) userModel).getOriginalUid()); + } + throw new IllegalArgumentException(format("The user {0} is not of type Customer.", userModel)); + } + + /** + * {@inheritDoc} + */ + @Override + public Address getAddressFromCart(final AbstractOrderModel abstractOrder, final boolean isDeliveryAddress) { + final AddressModel address = isDeliveryAddress ? worldpayDeliveryAddressStrategy.getDeliveryAddress(abstractOrder) : abstractOrder.getPaymentAddress(); + return convertAddressModelToAddress(address); + } + + /** + * {@inheritDoc} + */ + @Override + public Address getBillingAddress(final CartModel cartModel, final AdditionalAuthInfo additionalAuthInfo) { + final AddressModel deliveryAddressModel = cartModel.getDeliveryAddress(); + if (deliveryAddressModel != null && Boolean.TRUE.equals(additionalAuthInfo.getUsingShippingAsBilling())) { + return convertAddressModelToAddress(deliveryAddressModel); + } else { + if (cartModel.getPaymentAddress() != null) { + return convertAddressModelToAddress(cartModel.getPaymentAddress()); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Address convertAddressModelToAddress(final AddressModel address) { + return worldpayAddressConverter.convert(address); + } + + /** + * {@inheritDoc} + */ + @Override + public String getEmailForCustomer(final AbstractOrderModel cart) { + return customerEmailResolutionService.getEmailForCustomer((CustomerModel) cart.getUser()); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayHybrisOrderService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayHybrisOrderService.java index cafb7c83..a14f1e86 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayHybrisOrderService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayHybrisOrderService.java @@ -4,15 +4,19 @@ import com.worldpay.core.services.WorldpayHybrisOrderService; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.servicelayer.model.ModelService; -import org.springframework.beans.factory.annotation.Required; /** * {@inheritDoc} */ public class DefaultWorldpayHybrisOrderService implements WorldpayHybrisOrderService { - private WorldpayHybrisOrderDao worldpayHybrisOrderDao; - private ModelService modelService; + protected final WorldpayHybrisOrderDao worldpayHybrisOrderDao; + protected final ModelService modelService; + + public DefaultWorldpayHybrisOrderService(final WorldpayHybrisOrderDao worldpayHybrisOrderDao, final ModelService modelService) { + this.worldpayHybrisOrderDao = worldpayHybrisOrderDao; + this.modelService = modelService; + } /** * {@inheritDoc} @@ -25,31 +29,19 @@ public void setWorldpayDeclineCodeOnOrder(final String worldpayOrderCode, final modelService.save(orderModel); } + /** + * {@inheritDoc} + */ @Override public OrderModel findOrderByWorldpayOrderCode(final String worldpayOrderCode) { return worldpayHybrisOrderDao.findOrderByWorldpayOrderCode(worldpayOrderCode); } + /** + * {@inheritDoc} + */ @Override public String findOrderCodeByWorldpayOrderCode(final String worldpayOrderCode) { return findOrderByWorldpayOrderCode(worldpayOrderCode).getCode(); } - - @Required - public void setWorldpayHybrisOrderDao(final WorldpayHybrisOrderDao worldpayHybrisOrderDao) { - this.worldpayHybrisOrderDao = worldpayHybrisOrderDao; - } - - public WorldpayHybrisOrderDao getWorldpayHybrisOrderDao() { - return worldpayHybrisOrderDao; - } - - @Required - public void setModelService(final ModelService modelService) { - this.modelService = modelService; - } - - public ModelService getModelService() { - return modelService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoService.java index 72ff5d74..64747db5 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoService.java @@ -2,22 +2,18 @@ import com.worldpay.core.services.APMConfigurationLookupService; import com.worldpay.core.services.WorldpayPaymentInfoService; -import com.worldpay.data.ApplePayAdditionalAuthInfo; -import com.worldpay.data.GooglePayAdditionalAuthInfo; +import com.worldpay.data.*; +import com.worldpay.data.payment.Card; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.TokenDetails; +import com.worldpay.data.token.TokenReply; import com.worldpay.enums.token.TokenEvent; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.model.ApplePayPaymentInfoModel; import com.worldpay.model.GooglePayPaymentInfoModel; import com.worldpay.model.WorldpayAPMConfigurationModel; -import com.worldpay.service.model.Date; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.SchemeResponse; -import com.worldpay.service.model.payment.Card; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.TokenDetails; -import com.worldpay.service.model.token.TokenReply; import com.worldpay.service.notification.OrderNotificationMessage; import com.worldpay.service.request.UpdateTokenServiceRequest; import de.hybris.platform.commerceservices.order.CommerceCheckoutService; @@ -37,7 +33,8 @@ import de.hybris.platform.servicelayer.user.AddressService; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateUtils; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.text.MessageFormat; import java.time.LocalDate; @@ -58,7 +55,7 @@ */ public class DefaultWorldpayPaymentInfoService implements WorldpayPaymentInfoService { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayPaymentInfoService.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayPaymentInfoService.class); private static final String WORLDPAY_CREDIT_CARD_MAPPINGS = "worldpay.creditCard.mappings."; private static final String CART_MODEL_CANNOT_BE_NULL = "CartModel cannot be null"; @@ -360,7 +357,7 @@ protected void removePaymentInfoWhenCreatingNewOneFromNotification(final Abstrac protected void setPaymentTypeAndCreditCardType(final CreditCardPaymentInfoModel creditCardPaymentInfoModel, final Card paymentInstrument) { if (paymentInstrument != null && paymentInstrument.getPaymentType() != null) { - doSetCreditCardTypeAndPaymentType(creditCardPaymentInfoModel, paymentInstrument.getPaymentType().getMethodCode()); + doSetCreditCardTypeAndPaymentType(creditCardPaymentInfoModel, paymentInstrument.getPaymentType()); } else { doSetCreditCardTypeAndPaymentType(creditCardPaymentInfoModel, PaymentType.CARD_SSL.getMethodCode()); } @@ -372,7 +369,7 @@ protected PaymentInfoModel getPaymentInfoModel(final PaymentTransactionModel pay final PaymentReply paymentReply = orderNotificationMessage.getPaymentReply(); savePaymentType(paymentTransactionModel, paymentReply.getPaymentMethodCode()); final PaymentInfoModel paymentTransactionModelInfo = paymentTransactionModel.getInfo(); - if (paymentTransactionModelInfo.getIsApm()) { + if (Boolean.TRUE.equals(paymentTransactionModelInfo.getIsApm())) { final TokenReply tokenReply = orderNotificationMessage.getTokenReply(); if (tokenReply != null && orderNotificationMessage.getPaymentReply().getPaymentMethodCode().equalsIgnoreCase(PaymentType.PAYPAL.getMethodCode())) { return createPaypalTokenisedPaymentInfo(paymentTransactionModel, orderNotificationMessage, tokenReply); @@ -499,7 +496,7 @@ protected LocalDate getDateTime(final Date paymentTokenExpiryDate) { protected java.util.Date calculateAPMTimeoutDate(final java.util.Date creationTime, final WorldpayAPMConfigurationModel apmConfiguration) { final Integer autoCancelPendingTimeoutInMinutes = apmConfiguration.getAutoCancelPendingTimeoutInMinutes(); if (autoCancelPendingTimeoutInMinutes == null) { - LOG.warn(MessageFormat.format("No auto cancel pending timeout found for APM configuration with code [{0}]", apmConfiguration.getCode())); + LOG.warn("No auto cancel pending timeout found for APM configuration with code [{}]", apmConfiguration.getCode()); return null; } return addMinutesToDate(creationTime, autoCancelPendingTimeoutInMinutes); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayPrimeRoutingService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayPrimeRoutingService.java new file mode 100644 index 00000000..8e78d6e5 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/core/services/impl/DefaultWorldpayPrimeRoutingService.java @@ -0,0 +1,62 @@ +package com.worldpay.core.services.impl; + +import com.worldpay.core.services.WorldpayCartService; +import com.worldpay.core.services.WorldpayHybrisOrderService; +import com.worldpay.core.services.WorldpayPrimeRoutingService; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.order.CartModel; +import de.hybris.platform.core.model.order.OrderModel; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.order.CartService; + +import java.util.Objects; + +/** + * Default implementation fo the {@link WorldpayPrimeRoutingService}. + */ +public class DefaultWorldpayPrimeRoutingService implements WorldpayPrimeRoutingService { + + private static final String US_COUNTRY_ISO_CODE = "US"; + + protected final WorldpayCartService worldpayCartService; + protected final CartService cartService; + protected final WorldpayHybrisOrderService worldpayHybrisOrderService; + + public DefaultWorldpayPrimeRoutingService(final WorldpayCartService worldpayCartService, + final CartService cartService, + final WorldpayHybrisOrderService worldpayHybrisOrderService) { + this.worldpayCartService = worldpayCartService; + this.cartService = cartService; + this.worldpayHybrisOrderService = worldpayHybrisOrderService; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPrimeRoutingEnabled(final AbstractOrderModel cart) { + final AddressModel paymentAddress = cart.getPaymentAddress(); + if (Objects.nonNull(paymentAddress)) { + return cart.getSite().getEnablePR() && US_COUNTRY_ISO_CODE.equals(paymentAddress.getCountry().getIsocode()); + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public void setAuthorisedWithPrimeRoutingOnCart(final AbstractOrderModel cart) { + cart.setIsPrimeRouteAuth(Boolean.TRUE); + cartService.saveOrder((CartModel) cart); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isOrderAuthorisedWithPrimeRouting(final String worldpayOrderCode) { + final OrderModel order = worldpayHybrisOrderService.findOrderByWorldpayOrderCode(worldpayOrderCode); + return order.getIsPrimeRouteAuth(); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/customer/impl/DefaultWorldpayCustomerAccountService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/customer/impl/DefaultWorldpayCustomerAccountService.java index 1619b8e1..c58cb9e8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/customer/impl/DefaultWorldpayCustomerAccountService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/customer/impl/DefaultWorldpayCustomerAccountService.java @@ -3,14 +3,15 @@ import com.worldpay.customer.WorldpayCustomerAccountService; import com.worldpay.exception.WorldpayException; import com.worldpay.merchant.WorldpayMerchantInfoService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayDirectOrderService; import de.hybris.platform.commerceservices.customer.impl.DefaultCustomerAccountService; import de.hybris.platform.core.model.order.payment.CreditCardPaymentInfoModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.core.model.order.payment.WorldpayAPMPaymentInfoModel; import de.hybris.platform.core.model.user.CustomerModel; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; @@ -24,7 +25,7 @@ public class DefaultWorldpayCustomerAccountService extends DefaultCustomerAccoun protected WorldpayMerchantInfoService worldpayMerchantInfoService; protected WorldpayDirectOrderService worldpayDirectOrderService; - private static final Logger LOG = Logger.getLogger(DefaultWorldpayCustomerAccountService.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayCustomerAccountService.class); /** * Fist delete token at Worldpay than call super diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/APMAvailabilityFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/APMAvailabilityFacade.java index 45c4659f..d6f46482 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/APMAvailabilityFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/APMAvailabilityFacade.java @@ -13,4 +13,11 @@ public interface APMAvailabilityFacade { * @return true or false depending on if the apm configuration is available */ boolean isAvailable(final WorldpayAPMConfigurationModel apmConfiguration); + + /** + * Method to check if APM configuration is currently available given code of APM + * @param paymentMethod code of APM + * @return true or false depending on if the apm configuration is available + */ + boolean isAvailable(String paymentMethod); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/WorldpayAPMComponentFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/WorldpayAPMComponentFacade.java new file mode 100644 index 00000000..c7bb95f7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/WorldpayAPMComponentFacade.java @@ -0,0 +1,18 @@ +package com.worldpay.facades; + +import com.worldpay.data.cms.WorldpayAPMComponentData; + +import java.util.List; + +/** + * Exposes a method for getting all available Worldpay apm components. + */ +public interface WorldpayAPMComponentFacade { + + /** + * Get all available {@link WorldpayAPMComponentData}. + * + * @return a list with all available WorldpayAPMComponentData. + */ + List getAllAvailableWorldpayAPMComponents(); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/WorldpayCartFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/WorldpayCartFacade.java index dfa91294..d8a6055a 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/WorldpayCartFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/WorldpayCartFacade.java @@ -16,5 +16,4 @@ public interface WorldpayCartFacade { * Sets the payment address from the paymentInfo */ void setBillingAddressFromPaymentInfo(); - } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/impl/DefaultAPMAvailabilityFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/impl/DefaultAPMAvailabilityFacade.java index 723928b3..d6928afc 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/impl/DefaultAPMAvailabilityFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/impl/DefaultAPMAvailabilityFacade.java @@ -1,10 +1,10 @@ package com.worldpay.facades.impl; +import com.worldpay.core.services.APMConfigurationLookupService; import com.worldpay.facades.APMAvailabilityFacade; import com.worldpay.model.WorldpayAPMConfigurationModel; import com.worldpay.service.apm.APMAvailabilityService; import de.hybris.platform.order.CartService; -import org.springframework.beans.factory.annotation.Required; /** @@ -12,23 +12,33 @@ */ public class DefaultAPMAvailabilityFacade implements APMAvailabilityFacade { - private APMAvailabilityService apmAvailabilityService; - private CartService cartService; + private final APMAvailabilityService apmAvailabilityService; + private final CartService cartService; + private final APMConfigurationLookupService apmConfigurationLookupService; + + public DefaultAPMAvailabilityFacade(final APMAvailabilityService apmAvailabilityService, final CartService cartService, final APMConfigurationLookupService apmConfigurationLookupService) { + this.apmAvailabilityService = apmAvailabilityService; + this.cartService = cartService; + this.apmConfigurationLookupService = apmConfigurationLookupService; + } /** * {@inheritDoc} */ + @Override public boolean isAvailable(final WorldpayAPMConfigurationModel apmConfiguration) { return apmAvailabilityService.isAvailable(apmConfiguration, cartService.getSessionCart()); } - @Required - public void setApmAvailabilityService(final APMAvailabilityService apmAvailabilityService) { - this.apmAvailabilityService = apmAvailabilityService; - } - - @Required - public void setCartService(CartService cartService) { - this.cartService = cartService; + /** + * {@inheritDoc} + */ + @Override + public boolean isAvailable(final String paymentMethod) { + final WorldpayAPMConfigurationModel apmConfiguration = apmConfigurationLookupService.getAPMConfigurationForCode(paymentMethod); + if (apmConfiguration != null) { + return this.isAvailable(apmConfiguration); + } + return false; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/impl/DefaultWorldpayAPMComponentFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/impl/DefaultWorldpayAPMComponentFacade.java new file mode 100644 index 00000000..14cdbf95 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/impl/DefaultWorldpayAPMComponentFacade.java @@ -0,0 +1,32 @@ +package com.worldpay.facades.impl; + +import com.worldpay.core.services.WorldpayAPMComponentService; +import com.worldpay.data.cms.WorldpayAPMComponentData; +import com.worldpay.facades.WorldpayAPMComponentFacade; +import com.worldpay.model.WorldpayAPMComponentModel; +import de.hybris.platform.servicelayer.dto.converter.Converter; + +import java.util.List; + +/** + * {@inheritDoc} + */ +public class DefaultWorldpayAPMComponentFacade implements WorldpayAPMComponentFacade { + + protected final WorldpayAPMComponentService worldpayAPMComponentService; + protected final Converter worldpayAPMComponentConverter; + + public DefaultWorldpayAPMComponentFacade(final WorldpayAPMComponentService worldpayAPMComponentService, + final Converter worldpayAPMComponentConverter) { + this.worldpayAPMComponentService = worldpayAPMComponentService; + this.worldpayAPMComponentConverter = worldpayAPMComponentConverter; + } + + /** + * {@inheritDoc} + */ + @Override + public List getAllAvailableWorldpayAPMComponents() { + return worldpayAPMComponentConverter.convertAll(worldpayAPMComponentService.getAllAvailableWorldpayAPMComponents()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/WorldpayPaymentCheckoutFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/WorldpayPaymentCheckoutFacade.java index 62c7de2d..b2c2944c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/WorldpayPaymentCheckoutFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/WorldpayPaymentCheckoutFacade.java @@ -2,9 +2,8 @@ import de.hybris.platform.commercefacades.user.data.AddressData; - /** - * worldpay specific checkout facade interface. This is overridden from the standard to ensure the worldpay information + * Worldpay specific checkout facade interface. This is overridden from the standard to ensure the worldpay information * is included at the correct point. Adds convenience methods required for worldpay interaction */ public interface WorldpayPaymentCheckoutFacade { @@ -14,8 +13,14 @@ public interface WorldpayPaymentCheckoutFacade { * * @param addressData the address data */ - void setBillingDetails(final AddressData addressData); + void setBillingDetails(AddressData addressData); + /** + * Sets shipping and billing details to the session cart + * + * @param addressData the address data + */ + void setShippingAndBillingDetails(AddressData addressData); /** * Does the session cart have a billing details (payment address) @@ -23,4 +28,11 @@ public interface WorldpayPaymentCheckoutFacade { * @return the boolean */ boolean hasBillingDetails(); + + /** + * Return true if Fraud Sight is enabled, false otherwise + * + * @return true if enabled, false otherwise + */ + boolean isFSEnabled(); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/DefaultWorldpayKlarnaPaymentCheckoutFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/DefaultWorldpayKlarnaPaymentCheckoutFacade.java index 88eb32cc..46b888c1 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/DefaultWorldpayKlarnaPaymentCheckoutFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/DefaultWorldpayKlarnaPaymentCheckoutFacade.java @@ -7,7 +7,7 @@ import com.worldpay.facades.order.WorldpayKlarnaPaymentCheckoutFacade; import com.worldpay.hostedorderpage.data.KlarnaRedirectAuthoriseResult; import com.worldpay.merchant.WorldpayMerchantInfoService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.response.OrderInquiryServiceResponse; import de.hybris.platform.commercefacades.order.CheckoutFacade; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/DefaultWorldpayPaymentCheckoutFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/DefaultWorldpayPaymentCheckoutFacade.java index 0395881a..7bb2c2cd 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/DefaultWorldpayPaymentCheckoutFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/DefaultWorldpayPaymentCheckoutFacade.java @@ -2,6 +2,7 @@ import com.worldpay.core.checkout.WorldpayCheckoutService; import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; +import com.worldpay.service.payment.WorldpayFraudSightStrategy; import de.hybris.platform.commercefacades.order.CheckoutFacade; import de.hybris.platform.commercefacades.user.data.AddressData; import de.hybris.platform.commerceservices.customer.CustomerAccountService; @@ -15,16 +16,23 @@ * Worldpay checkout facade to ensure Worldpay details are included in correct place */ public class DefaultWorldpayPaymentCheckoutFacade implements WorldpayPaymentCheckoutFacade { + protected final CheckoutFacade checkoutFacade; protected final WorldpayCheckoutService worldpayCheckoutService; protected final CartService cartService; protected final CustomerAccountService customerAccountService; + protected final WorldpayFraudSightStrategy worldpayFraudSightStrategy; - public DefaultWorldpayPaymentCheckoutFacade(final CheckoutFacade checkoutFacade, final WorldpayCheckoutService worldpayCheckoutService, final CartService cartService, final CustomerAccountService customerAccountService) { + public DefaultWorldpayPaymentCheckoutFacade(final CheckoutFacade checkoutFacade, + final WorldpayCheckoutService worldpayCheckoutService, + final CartService cartService, + final CustomerAccountService customerAccountService, + final WorldpayFraudSightStrategy worldpayFraudSightStrategy) { this.checkoutFacade = checkoutFacade; this.worldpayCheckoutService = worldpayCheckoutService; this.cartService = cartService; this.customerAccountService = customerAccountService; + this.worldpayFraudSightStrategy = worldpayFraudSightStrategy; } /** @@ -35,7 +43,19 @@ public void setBillingDetails(final AddressData addressData) { final CartModel cartModel = getCart(); if (cartModel != null && addressData != null) { Optional.ofNullable(customerAccountService.getAddressForCode((CustomerModel) cartModel.getUser(), addressData.getId())) - .ifPresent(addressModel -> worldpayCheckoutService.setPaymentAddress(cartModel, addressModel)); + .ifPresent(addressModel -> worldpayCheckoutService.setPaymentAddress(cartModel, addressModel)); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void setShippingAndBillingDetails(final AddressData addressData) { + final CartModel cartModel = getCart(); + if (cartModel != null && addressData != null) { + Optional.ofNullable(customerAccountService.getAddressForCode((CustomerModel) cartModel.getUser(), addressData.getId())) + .ifPresent(addressModel -> worldpayCheckoutService.setShippingAndPaymentAddress(cartModel, addressModel)); } } @@ -48,6 +68,14 @@ public boolean hasBillingDetails() { return cartModel != null && cartModel.getPaymentAddress() != null; } + /** + * {@inheritDoc} + */ + @Override + public boolean isFSEnabled() { + return worldpayFraudSightStrategy.isFraudSightEnabled(); + } + protected CartModel getCart() { return checkoutFacade.hasCheckoutCart() ? cartService.getSessionCart() : null; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/WorldpayCheckoutFacadeDecorator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/WorldpayCheckoutFacadeDecorator.java index e3e64c18..f42cf3e0 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/WorldpayCheckoutFacadeDecorator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/order/impl/WorldpayCheckoutFacadeDecorator.java @@ -24,6 +24,7 @@ import org.apache.logging.log4j.Logger; import java.util.List; +import java.util.Optional; import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNullStandardMessage; @@ -447,10 +448,17 @@ protected CustomerModel getCurrentUserForCheckout() { return checkoutCustomerStrategy.getCurrentUserForCheckout(); } + /** + * If payment info has billing address it will be set as payment address in session cart. + */ protected void setPaymentInfoBillingAddressOnSessionCart() { final CartModel sessionCart = getSessionCart(); - sessionCart.setPaymentAddress(sessionCart.getPaymentInfo().getBillingAddress()); - cartService.saveOrder(sessionCart); + Optional.ofNullable(sessionCart.getPaymentInfo()) + .map(PaymentInfoModel::getBillingAddress) + .ifPresent(paymentAddress -> { + sessionCart.setPaymentAddress(paymentAddress); + cartService.saveOrder(sessionCart); + }); } protected CommerceCheckoutParameter createCommerceCheckoutParameter(final CartModel cart, final boolean enableHooks) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/direct/WorldpayDirectOrderFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/direct/WorldpayDirectOrderFacade.java index 7a842ea4..35ccada5 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/direct/WorldpayDirectOrderFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/direct/WorldpayDirectOrderFacade.java @@ -4,7 +4,6 @@ import com.worldpay.exception.WorldpayException; import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.payment.DirectResponseData; -import com.worldpay.service.model.MerchantInfo; import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.order.InvalidCartException; @@ -71,13 +70,11 @@ String authoriseBankTransferRedirect(final BankTransferAdditionalAuthInfo bankTr * * @param abstractOrderModel The abstractOrderModel to authorise. * @param worldpayAdditionalInfoData Object that contains information about the current session, browser used, and cookies. - * @param merchantInfo The Worldpay merchant * @return {@link DirectResponseData} Wrapper object containing information on the response from Worldpay * @throws WorldpayException - something went wrong * @throws InvalidCartException - something went wrong */ - DirectResponseData authoriseRecurringPayment(final AbstractOrderModel abstractOrderModel, final WorldpayAdditionalInfoData worldpayAdditionalInfoData, - final MerchantInfo merchantInfo) throws WorldpayException, InvalidCartException; + DirectResponseData authoriseRecurringPayment(final AbstractOrderModel abstractOrderModel, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws WorldpayException, InvalidCartException; /** * Performs a request to Worldpay to retrieve the URL to redirect to when using Klarna. @@ -166,4 +163,5 @@ DirectResponseData authoriseRecurringPayment(final AbstractOrderModel abstractOr * @throws WorldpayException */ DirectResponseData executeSecondPaymentAuthorisation3DSecure(final String worldpayOrderCode) throws WorldpayException, InvalidCartException; + } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/direct/impl/DefaultWorldpayDirectOrderFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/direct/impl/DefaultWorldpayDirectOrderFacade.java index 140b3461..71522fdf 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/direct/impl/DefaultWorldpayDirectOrderFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/direct/impl/DefaultWorldpayDirectOrderFacade.java @@ -10,21 +10,17 @@ import com.worldpay.facades.payment.direct.WorldpayDirectOrderFacade; import com.worldpay.facades.payment.merchant.WorldpayMerchantConfigDataFacade; import com.worldpay.model.GooglePayPaymentInfoModel; -import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.payment.DirectResponseData; import com.worldpay.payment.TransactionStatus; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.Request3DInfo; -import com.worldpay.service.model.payment.Card; -import com.worldpay.service.model.token.TokenDetails; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.Request3DInfo; +import com.worldpay.data.payment.Card; +import com.worldpay.data.token.TokenDetails; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.payment.WorldpayDirectOrderService; import com.worldpay.service.response.DirectAuthoriseServiceResponse; -import com.worldpay.strategy.WorldpayAuthenticatedShopperIdStrategy; import de.hybris.platform.acceleratorfacades.order.AcceleratorCheckoutFacade; -import de.hybris.platform.commercefacades.order.CartFacade; import de.hybris.platform.commercefacades.order.data.CCPaymentInfoData; import de.hybris.platform.commercefacades.order.data.OrderData; import de.hybris.platform.converters.Populator; @@ -32,13 +28,14 @@ import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.core.model.order.payment.WorldpayAPMPaymentInfoModel; -import de.hybris.platform.core.model.user.UserModel; import de.hybris.platform.order.CartService; import de.hybris.platform.order.InvalidCartException; import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.nio.charset.StandardCharsets; +import java.text.MessageFormat; import java.util.Base64; import java.util.Objects; import java.util.Optional; @@ -52,43 +49,35 @@ @SuppressWarnings("java:S107") public class DefaultWorldpayDirectOrderFacade implements WorldpayDirectOrderFacade { - protected static final String ERROR_AUTHORISING_ORDER = "There was a problem authorising the order with worldpayOrderCode [{0}]"; - protected static final String THERE_WAS_AN_ERROR_COMMUNICATING_WITH_WORLDPAY = "There was an error communicating with Worldpay"; - protected static final String THERE_WAS_AN_ERROR_IN_THE_SERVICE_GATEWAY_MESSAGE = "There was an error in the service gateway: [{0}]"; - private static final Logger LOG = Logger.getLogger(DefaultWorldpayDirectOrderFacade.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayDirectOrderFacade.class); + + private static final String ERROR_AUTHORISING_ORDER = "There was a problem authorising the order with worldpayOrderCode [{0}]"; + private static final String THERE_WAS_AN_ERROR_COMMUNICATING_WITH_WORLDPAY = "There was an error communicating with Worldpay"; + private static final String THERE_WAS_AN_ERROR_IN_THE_SERVICE_GATEWAY_MESSAGE = "There was an error in the service gateway: [{0}]"; private static final String THERE_IS_NO_CONFIGURATION = "There is no configuration for the requested merchant. Please review your settings."; private static final String CANNOT_AUTHORIZE_PAYMENT_WHERE_THERE_IS_NO_CART_MESSAGE = "Cannot authorize payment where there is no cart"; - protected final WorldpayAuthenticatedShopperIdStrategy worldpayAuthenticatedShopperIdStrategy; protected final WorldpayDirectOrderService worldpayDirectOrderService; protected final CartService cartService; protected final AcceleratorCheckoutFacade acceleratorCheckoutFacade; protected final WorldpayPaymentInfoService worldpayPaymentInfoService; protected final WorldpayMerchantConfigDataFacade worldpayMerchantConfigDataFacade; - protected final CartFacade cartFacade; protected final WorldpayCartService worldpayCartService; - protected final WorldpayMerchantInfoService worldpayMerchantInfoService; protected final Populator apmPaymentInfoPopulator; - public DefaultWorldpayDirectOrderFacade(final WorldpayAuthenticatedShopperIdStrategy worldpayAuthenticatedShopperIdStrategy, - final WorldpayDirectOrderService worldpayDirectOrderService, + public DefaultWorldpayDirectOrderFacade(final WorldpayDirectOrderService worldpayDirectOrderService, final CartService cartService, final AcceleratorCheckoutFacade acceleratorCheckoutFacade, final WorldpayPaymentInfoService worldpayPaymentInfoService, final WorldpayMerchantConfigDataFacade worldpayMerchantConfigDataFacade, - final CartFacade cartFacade, final WorldpayCartService worldpayCartService, - final WorldpayMerchantInfoService worldpayMerchantInfoService, final Populator apmPaymentInfoPopulator) { - this.worldpayAuthenticatedShopperIdStrategy = worldpayAuthenticatedShopperIdStrategy; this.worldpayDirectOrderService = worldpayDirectOrderService; this.cartService = cartService; this.acceleratorCheckoutFacade = acceleratorCheckoutFacade; this.worldpayPaymentInfoService = worldpayPaymentInfoService; this.worldpayMerchantConfigDataFacade = worldpayMerchantConfigDataFacade; - this.cartFacade = cartFacade; this.worldpayCartService = worldpayCartService; - this.worldpayMerchantInfoService = worldpayMerchantInfoService; this.apmPaymentInfoPopulator = apmPaymentInfoPopulator; } @@ -113,18 +102,20 @@ public void tokenize(final CartModel cartModel, final CSEAdditionalAuthInfo cseA public void tokenize(final CSEAdditionalAuthInfo cseAdditionalAuthInfo, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws WorldpayException { Preconditions.checkState(cartService.hasSessionCart(), CANNOT_AUTHORIZE_PAYMENT_WHERE_THERE_IS_NO_CART_MESSAGE); final CartModel cartModel = cartService.getSessionCart(); - setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, cartModel.getUser()); + setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, cartModel); tokenize(cartModel, cseAdditionalAuthInfo, worldpayAdditionalInfoData); } + /** + * {@inheritDoc} + */ @Override public DirectResponseData executeFirstPaymentAuthorisation3DSecure(final CSEAdditionalAuthInfo cseAdditionalAuthInfo, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws WorldpayException, InvalidCartException { final DirectResponseData directResponseData; if (StringUtils.isEmpty(cseAdditionalAuthInfo.getEncryptedData())) { final CartModel cart = cartService.getSessionCart(); - final MerchantInfo merchantInfo = worldpayMerchantInfoService.getCurrentSiteMerchant(); - directResponseData = authoriseRecurringPayment(cart, worldpayAdditionalInfoData, merchantInfo); + directResponseData = authoriseRecurringPayment(cart, worldpayAdditionalInfoData); } else { directResponseData = authoriseAndTokenize(worldpayAdditionalInfoData, cseAdditionalAuthInfo); } @@ -158,8 +149,7 @@ public DirectResponseData authoriseRecurringPayment(final WorldpayAdditionalInfo */ @Override public DirectResponseData authoriseRecurringPayment(final AbstractOrderModel abstractOrderModel, - final WorldpayAdditionalInfoData worldpayAdditionalInfoData, - final MerchantInfo merchantInfo) throws WorldpayException, InvalidCartException { + final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws WorldpayException, InvalidCartException { return internalAuthoriseRecurringPayment(abstractOrderModel, worldpayAdditionalInfoData); } @@ -174,8 +164,7 @@ public String authoriseKlarnaRedirect(final WorldpayAdditionalInfoData worldpayA final String klarnaRedirectContentEncoded = handleAuthoriseRedirectServiceResponse(serviceResponse); return new String(Base64.getDecoder().decode(klarnaRedirectContentEncoded), StandardCharsets.UTF_8); } catch (final WorldpayConfigurationException e) { - LOG.error(THERE_IS_NO_CONFIGURATION, e); - throw e; + throw new WorldpayConfigurationException(THERE_IS_NO_CONFIGURATION); } } @@ -193,8 +182,7 @@ public DirectResponseData authoriseApplePayDirect(final ApplePayAdditionalAuthIn } return handleDirectServiceResponse(directAuthoriseServiceResponse, cart); } catch (final WorldpayConfigurationException e) { - LOG.error(THERE_IS_NO_CONFIGURATION, e); - throw e; + throw new WorldpayConfigurationException(THERE_IS_NO_CONFIGURATION); } } @@ -219,8 +207,7 @@ public DirectResponseData authoriseGooglePayDirect(final GooglePayAdditionalAuth } return handleDirectServiceResponse(directAuthoriseServiceResponse, cart); } catch (final WorldpayConfigurationException e) { - LOG.error(THERE_IS_NO_CONFIGURATION, e); - throw e; + throw new WorldpayConfigurationException(THERE_IS_NO_CONFIGURATION); } } @@ -302,14 +289,13 @@ public DirectResponseData executeSecondPaymentAuthorisation3DSecure(final String throw new WorldpayException(THERE_WAS_AN_ERROR_COMMUNICATING_WITH_WORLDPAY); } - /** * {@inheritDoc} */ @Override public DirectResponseData authoriseAndTokenize(final WorldpayAdditionalInfoData worldpayAdditionalInfoData, final CSEAdditionalAuthInfo cseAdditionalAuthInfo) throws WorldpayException, InvalidCartException { final CartModel cart = cartService.getSessionCart(); - setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, cart.getUser()); + setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, cart); if (Boolean.TRUE.equals(cseAdditionalAuthInfo.getSaveCard())) { return internalTokenizeAndAuthorise(cart, worldpayAdditionalInfoData, cseAdditionalAuthInfo); } else { @@ -334,7 +320,7 @@ protected ApplePayOrderUpdate createNoop() { final ApplePayLineItem newTotalLineItem = new ApplePayLineItem(); newTotalLineItem.setType("final"); newTotalLineItem.setLabel(worldpayMerchantConfigDataFacade.getCurrentSiteMerchantConfigData().getApplePaySettings().getMerchantName()); - newTotalLineItem.setAmount(cartFacade.getSessionCart().getTotalPrice().getValue().toString()); + newTotalLineItem.setAmount(cartService.getSessionCart().getTotalPrice().toString()); final ApplePayOrderUpdate update = new ApplePayOrderUpdate(); update.setNewTotal(newTotalLineItem); @@ -345,7 +331,7 @@ protected ApplePayOrderUpdate createNoop() { protected DirectResponseData internalAuthoriseRecurringPayment(final AbstractOrderModel abstractOrderModel, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws WorldpayException, InvalidCartException { try { - setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, abstractOrderModel.getUser()); + setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, abstractOrderModel); final var directAuthoriseServiceResponse = worldpayDirectOrderService.authoriseRecurringPayment( abstractOrderModel, worldpayAdditionalInfoData); @@ -354,14 +340,13 @@ protected DirectResponseData internalAuthoriseRecurringPayment(final AbstractOrd LOG.error(THERE_IS_NO_CONFIGURATION); throw e; } catch (final InvalidCartException e) { - LOG.error(format("There was an error placing the order for cart [{0}]", abstractOrderModel.getCode()), e); - throw e; + throw new InvalidCartException(MessageFormat.format("There was an error placing the order for cart [{}]", abstractOrderModel.getCode())); } } protected DirectResponseData internalAuthorise(final CartModel cart, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws WorldpayException, InvalidCartException { try { - setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, cart.getUser()); + setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, cart); final DirectAuthoriseServiceResponse serviceResponse = worldpayDirectOrderService.authorise(cart, worldpayAdditionalInfoData); return handleDirectServiceResponse(serviceResponse, cart); @@ -371,8 +356,8 @@ protected DirectResponseData internalAuthorise(final CartModel cart, final World } } - private void setAuthenticatedShopperIdOnAdditionalInfoData(final WorldpayAdditionalInfoData worldpayAdditionalInfoData, final UserModel user) { - final String authenticatedShopperId = worldpayAuthenticatedShopperIdStrategy.getAuthenticatedShopperId(user); + private void setAuthenticatedShopperIdOnAdditionalInfoData(final WorldpayAdditionalInfoData worldpayAdditionalInfoData, final AbstractOrderModel cart) { + final String authenticatedShopperId = worldpayCartService.getAuthenticatedShopperId(cart); worldpayAdditionalInfoData.setAuthenticatedShopperId(authenticatedShopperId); } @@ -396,7 +381,7 @@ protected DirectResponseData handleDirectServiceResponse(final DirectAuthoriseSe protected DirectResponseData internalAuthorise3DSecure(final AbstractOrderModel abstractOrderModel, final String paResponse, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws WorldpayException, InvalidCartException { - setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, abstractOrderModel.getUser()); + setAuthenticatedShopperIdOnAdditionalInfoData(worldpayAdditionalInfoData, abstractOrderModel); final DirectAuthoriseServiceResponse serviceResponse = worldpayDirectOrderService.authorise3DSecure( abstractOrderModel.getWorldpayOrderCode(), diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayAfterRedirectValidationFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayAfterRedirectValidationFacade.java index d050e754..bb023f4a 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayAfterRedirectValidationFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayAfterRedirectValidationFacade.java @@ -2,7 +2,7 @@ import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.merchant.WorldpayMerchantInfoService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayAfterRedirectValidationService; import de.hybris.platform.servicelayer.session.SessionService; import org.apache.logging.log4j.LogManager; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayHostedOrderFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayHostedOrderFacade.java index f83426b6..6abea741 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayHostedOrderFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayHostedOrderFacade.java @@ -10,7 +10,7 @@ import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.merchant.strategies.WorldpayOrderInfoStrategy; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayRedirectOrderService; import de.hybris.platform.acceleratorservices.payment.data.PaymentData; import de.hybris.platform.core.model.order.CartModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/merchant/converters/populators/WorldPayMerchantConfigDataPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/merchant/converters/populators/WorldPayMerchantConfigDataPopulator.java new file mode 100644 index 00000000..dfd26425 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/merchant/converters/populators/WorldPayMerchantConfigDataPopulator.java @@ -0,0 +1,118 @@ +package com.worldpay.facades.payment.merchant.converters.populators; + +import com.worldpay.config.merchant.ApplePayConfigData; +import com.worldpay.config.merchant.GooglePayConfigData; +import com.worldpay.config.merchant.ThreeDSFlexJsonWebTokenCredentials; +import com.worldpay.config.merchant.WorldpayMerchantConfigData; +import com.worldpay.enums.*; +import com.worldpay.model.WorldpayApplePayConfigurationModel; +import com.worldpay.model.WorldpayGooglePayConfigurationModel; +import com.worldpay.model.WorldpayMerchantConfigurationModel; +import com.worldpay.model.WorldpayThreeDS2JsonWebTokenConfigurationModel; +import de.hybris.platform.converters.Populator; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; +import org.apache.commons.collections.CollectionUtils; +import org.springframework.util.Assert; + +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * Populates the ApplePaySettingsData from the CheckoutComApplePayConfigurationModel + */ +public class WorldPayMerchantConfigDataPopulator implements Populator { + + /** + * {@inheritDoc} + */ + @Override + public void populate(final WorldpayMerchantConfigurationModel source, final WorldpayMerchantConfigData target) throws ConversionException { + Assert.notNull(source, "Source WorldpayMerchantConfiguration cannot be null."); + Assert.notNull(target, "Target WorldpayMerchantConfigData cannot be null."); + + target.setCode(source.getCode()); + target.setPassword(source.getPassword()); + target.setMacValidation(source.getMacValidation()); + target.setMacSecret(source.getMacSecret()); + target.setCsePublicKey(source.getCsePublicKey()); + target.setInstallationId(source.getInstallationId()); + target.setStatementNarrative(source.getStatementNarrative()); + target.setOrderContent(source.getOrderContent()); + + Optional.ofNullable(source.getApplePayConfiguration()) + .map(this::createApplePayConfigData) + .ifPresent(target::setApplePaySettings); + + Optional.ofNullable(source.getGooglePayConfiguration()) + .map(this::createGooglePayConfigData) + .ifPresent(target::setGooglePaySettings); + + Optional.ofNullable(source.getThreeDSFlexJsonWebTokenSettings()) + .map(this::createThreeDSFlexJsonWebTokenSettings) + .ifPresent(target::setThreeDSFlexJsonWebTokenSettings); + + Optional.ofNullable(source.getThreeDSFlexChallengePreference()) + .map(ChallengePreference::getCode) + .ifPresent(target::setThreeDSFlexChallengePreference); + } + + private ApplePayConfigData createApplePayConfigData(final WorldpayApplePayConfigurationModel applePayConfiguration) { + final ApplePayConfigData applePaySettings = new ApplePayConfigData(); + applePaySettings.setMerchantId(applePayConfiguration.getMerchantId()); + applePaySettings.setMerchantName(applePayConfiguration.getMerchantName()); + applePaySettings.setCountryCode(applePayConfiguration.getCountryCode()); + + if (CollectionUtils.isNotEmpty(applePayConfiguration.getMerchantCapabilities())) { + applePaySettings.setMerchantCapabilities(applePayConfiguration.getMerchantCapabilities() + .stream() + .map(ApplePayMerchantCapabilities::getCode) + .collect(Collectors.toList())); + } + + if (CollectionUtils.isNotEmpty(applePayConfiguration.getSupportedNetworks())) { + applePaySettings.setSupportedNetworks(applePayConfiguration.getSupportedNetworks() + .stream() + .map(ApplePaySupportedNetworks::getCode) + .collect(Collectors.toList())); + + } + return applePaySettings; + } + + private GooglePayConfigData createGooglePayConfigData(final WorldpayGooglePayConfigurationModel googlePayConfiguration) { + final GooglePayConfigData googlePayConfigData = new GooglePayConfigData(); + googlePayConfigData.setMerchantId(googlePayConfiguration.getMerchantId()); + googlePayConfigData.setMerchantName(googlePayConfiguration.getMerchantName()); + googlePayConfigData.setEnvironment(googlePayConfiguration.getEnvironment().getCode()); + googlePayConfigData.setGatewayMerchantId(googlePayConfiguration.getGatewayMerchantId()); + googlePayConfigData.setCardType(googlePayConfiguration.getCardType()); + + if (CollectionUtils.isNotEmpty(googlePayConfiguration.getAllowedCardNetworks())) { + googlePayConfigData.setAllowedCardNetworks(googlePayConfiguration.getAllowedCardNetworks() + .stream() + .map(GooglePayCardNetworks::getCode) + .collect(Collectors.toList())); + } + + if (CollectionUtils.isNotEmpty(googlePayConfiguration.getAllowedAuthMethods())) { + googlePayConfigData.setAllowedAuthMethods(googlePayConfiguration.getAllowedAuthMethods() + .stream() + .map(GooglePayCardAuthMethods::getCode) + .collect(Collectors.toList())); + + } + return googlePayConfigData; + } + + private ThreeDSFlexJsonWebTokenCredentials createThreeDSFlexJsonWebTokenSettings(final WorldpayThreeDS2JsonWebTokenConfigurationModel threeDS2JsonWebTokenConfiguration) { + final ThreeDSFlexJsonWebTokenCredentials threeDSFlexJsonWebTokenCredentials = new ThreeDSFlexJsonWebTokenCredentials(); + threeDSFlexJsonWebTokenCredentials.setIss(threeDS2JsonWebTokenConfiguration.getIss()); + threeDSFlexJsonWebTokenCredentials.setJwtMacKey(threeDS2JsonWebTokenConfiguration.getJwtMacKey()); + threeDSFlexJsonWebTokenCredentials.setAlg(threeDS2JsonWebTokenConfiguration.getAlg()); + threeDSFlexJsonWebTokenCredentials.setOrgUnitId(threeDS2JsonWebTokenConfiguration.getOrgUnitId()); + threeDSFlexJsonWebTokenCredentials.setEventOriginDomain(threeDS2JsonWebTokenConfiguration.getEventOriginDomain()); + threeDSFlexJsonWebTokenCredentials.setChallengeUrl(threeDS2JsonWebTokenConfiguration.getChallengeUrl()); + threeDSFlexJsonWebTokenCredentials.setDdcUrl(threeDS2JsonWebTokenConfiguration.getDdcUrl()); + return threeDSFlexJsonWebTokenCredentials; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/merchant/impl/DefaultWorldpayMerchantConfigDataFacade.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/merchant/impl/DefaultWorldpayMerchantConfigDataFacade.java index 8f890c30..a3a9b2c7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/merchant/impl/DefaultWorldpayMerchantConfigDataFacade.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/facades/payment/merchant/impl/DefaultWorldpayMerchantConfigDataFacade.java @@ -2,8 +2,9 @@ import com.worldpay.config.merchant.WorldpayMerchantConfigData; import com.worldpay.facades.payment.merchant.WorldpayMerchantConfigDataFacade; +import com.worldpay.model.WorldpayMerchantConfigurationModel; import com.worldpay.strategy.WorldpayMerchantStrategy; -import org.springframework.beans.factory.annotation.Required; +import de.hybris.platform.servicelayer.dto.converter.Converter; /** @@ -11,18 +12,20 @@ */ public class DefaultWorldpayMerchantConfigDataFacade implements WorldpayMerchantConfigDataFacade { - private WorldpayMerchantStrategy worldpayMerchantStrategy; + protected final WorldpayMerchantStrategy worldpayMerchantStrategy; + protected final Converter worldPayMerchantConfigDataConverter; + + public DefaultWorldpayMerchantConfigDataFacade(final WorldpayMerchantStrategy worldpayMerchantStrategy, + final Converter worldPayMerchantConfigDataConverter) { + this.worldpayMerchantStrategy = worldpayMerchantStrategy; + this.worldPayMerchantConfigDataConverter = worldPayMerchantConfigDataConverter; + } /** * {@inheritDoc} */ @Override public WorldpayMerchantConfigData getCurrentSiteMerchantConfigData() { - return worldpayMerchantStrategy.getMerchant(); - } - - @Required - public void setWorldpayMerchantStrategy(final WorldpayMerchantStrategy worldpayMerchantStrategy) { - this.worldpayMerchantStrategy = worldpayMerchantStrategy; + return worldPayMerchantConfigDataConverter.convert(worldpayMerchantStrategy.getMerchant()); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fraud/symptoms/WorldpayRiskGuardianFraudSymptom.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fraud/symptoms/WorldpayRiskGuardianFraudSymptom.java index ec7c499c..a5af5e5d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fraud/symptoms/WorldpayRiskGuardianFraudSymptom.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fraud/symptoms/WorldpayRiskGuardianFraudSymptom.java @@ -4,7 +4,8 @@ import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.fraud.impl.FraudServiceResponse; import de.hybris.platform.payment.model.PaymentTransactionModel; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.text.MessageFormat; import java.util.List; @@ -15,7 +16,7 @@ */ public class WorldpayRiskGuardianFraudSymptom extends AbstractWorldpayOrderFraudSymptomDetection { - private static final Logger LOG = Logger.getLogger(WorldpayRiskGuardianFraudSymptom.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayRiskGuardianFraudSymptom.class); @Override public FraudServiceResponse recognizeSymptom(final FraudServiceResponse fraudServiceResponse, final AbstractOrderModel abstractOrderModel) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fraud/symptoms/WorldpayRiskScoreFraudSymptom.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fraud/symptoms/WorldpayRiskScoreFraudSymptom.java index 7cbecb52..b2e34fa9 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fraud/symptoms/WorldpayRiskScoreFraudSymptom.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fraud/symptoms/WorldpayRiskScoreFraudSymptom.java @@ -4,7 +4,8 @@ import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.fraud.impl.FraudServiceResponse; import de.hybris.platform.payment.model.PaymentTransactionModel; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.Objects; @@ -16,7 +17,7 @@ */ public class WorldpayRiskScoreFraudSymptom extends AbstractWorldpayOrderFraudSymptomDetection { - private static final Logger LOG = Logger.getLogger(WorldpayRiskScoreFraudSymptom.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayRiskScoreFraudSymptom.class); @Override public FraudServiceResponse recognizeSymptom(final FraudServiceResponse fraudServiceResponse, final AbstractOrderModel abstractOrderModel) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fulfilmentprocess/actions/order/WorldpayFraudCheckOrderInternalAction.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fulfilmentprocess/actions/order/WorldpayFraudCheckOrderInternalAction.java index 92e50b41..7a08ae49 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fulfilmentprocess/actions/order/WorldpayFraudCheckOrderInternalAction.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fulfilmentprocess/actions/order/WorldpayFraudCheckOrderInternalAction.java @@ -1,10 +1,5 @@ package com.worldpay.fulfilmentprocess.actions.order; -import static de.hybris.platform.basecommerce.enums.FraudStatus.CHECK; -import static de.hybris.platform.basecommerce.enums.FraudStatus.OK; - -import java.text.MessageFormat; - import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.enums.OrderStatus; import de.hybris.platform.core.model.order.OrderModel; @@ -15,15 +10,18 @@ import de.hybris.platform.orderprocessing.model.OrderProcessModel; import de.hybris.platform.servicelayer.util.ServicesUtil; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; +import static de.hybris.platform.basecommerce.enums.FraudStatus.CHECK; + /** * Worldpay fraud check action - using the hybris fraud service */ public class WorldpayFraudCheckOrderInternalAction extends WorldpayAbstractFraudCheckAction { - private static final Logger LOG = Logger.getLogger(WorldpayFraudCheckOrderInternalAction.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayFraudCheckOrderInternalAction.class); private FraudService fraudService; private String providerName; @@ -47,10 +45,10 @@ public String executeAction(final OrderProcessModel process) { modelService.save(order); return OK; } else { - LOG.warn(MessageFormat.format("The order [{0}] is potentially fraudulent. Sent into Fraud Review state", order.getCode())); + LOG.warn("The order [{}] is potentially fraudulent. Sent into Fraud Review state", order.getCode()); final FraudReportModel fraudReport = createFraudReport(providerName, response, order, CHECK); final OrderHistoryEntryModel historyEntry = createHistoryLog(providerName, order, CHECK, - fraudReport.getCode()); + fraudReport.getCode()); order.setFraudulent(Boolean.FALSE); order.setPotentiallyFraudulent(Boolean.TRUE); order.setStatus(OrderStatus.FRAUD_CHECKED); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fulfilmentprocess/actions/order/WorldpayTakePaymentAction.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fulfilmentprocess/actions/order/WorldpayTakePaymentAction.java index 89d3c2f5..129905b8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fulfilmentprocess/actions/order/WorldpayTakePaymentAction.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/fulfilmentprocess/actions/order/WorldpayTakePaymentAction.java @@ -9,9 +9,9 @@ import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.processengine.action.AbstractAction; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.text.MessageFormat; import java.util.List; import java.util.Set; @@ -23,7 +23,7 @@ * Action that handles payment transactions and update order status */ public class WorldpayTakePaymentAction extends AbstractAction { - private static final Logger LOG = Logger.getLogger(WorldpayTakePaymentAction.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayTakePaymentAction.class); private static final String OK = "OK"; private static final String NOK = "NOK"; @@ -60,9 +60,9 @@ public String execute(final OrderProcessModel process) { } protected String handleMultipleTransactionEntries(final OrderProcessModel process, final OrderModel order, final PaymentTransactionModel paymentTransaction, final List entries) { - LOG.error(MessageFormat.format("Found {0} PaymentTransactionEntries with " + - "type CAPTURE for PaymentTransaction with code {1} and orderProcess " + - "with code {2}. There should be exactly 1", entries.size(), paymentTransaction.getCode(), process.getCode())); + LOG.error("Found {} PaymentTransactionEntries with " + + "type CAPTURE for PaymentTransaction with code {} and orderProcess " + + "with code {}. There should be exactly 1", entries.size(), paymentTransaction.getCode(), process.getCode()); setOrderStatus(order, PAYMENT_NOT_CAPTURED); return NOK; } @@ -83,7 +83,7 @@ protected boolean shouldIssueCaptureRequest(final PaymentInfoModel paymentTransa protected boolean checkForPendingStatus(final OrderModel order, final PaymentTransactionModel txn) { // wait if any capture entries are still pending if (worldpayPaymentTransactionService.isPaymentTransactionPending(txn, CAPTURE)) { - LOG.info(MessageFormat.format("Still waiting for capture on order: {0} ", order)); + LOG.info("Still waiting for capture on order: {} ", order); return true; } return false; @@ -92,7 +92,7 @@ protected boolean checkForPendingStatus(final OrderModel order, final PaymentTra protected boolean checkForNotAccepted(final OrderModel order, final PaymentTransactionModel transaction) { // NOK if all capture entries have not been accepted if (!worldpayPaymentTransactionService.areAllPaymentTransactionsAcceptedForType(order, CAPTURE)) { - LOG.error("The payment transaction capture has failed. Order: " + order.getCode() + ". Transaction: " + transaction.getCode()); + LOG.error("The payment transaction capture has failed. Order: {}. Transaction: {}" , order.getCode(), transaction.getCode()); setOrderStatus(order, PAYMENT_NOT_CAPTURED); return true; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/hostedorderpage/converters/RedirectAuthoriseResultPopulator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/hostedorderpage/converters/RedirectAuthoriseResultPopulator.java index f0bc3bd6..4a5db307 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/hostedorderpage/converters/RedirectAuthoriseResultPopulator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/hostedorderpage/converters/RedirectAuthoriseResultPopulator.java @@ -2,13 +2,14 @@ import com.worldpay.enums.order.AuthorisedStatus; import com.worldpay.hostedorderpage.data.RedirectAuthoriseResult; -import com.worldpay.service.model.Amount; +import com.worldpay.data.Amount; import com.worldpay.service.payment.WorldpayOrderService; import de.hybris.platform.acceleratorservices.payment.cybersource.converters.populators.response.AbstractResultPopulator; import de.hybris.platform.converters.Populator; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.text.MessageFormat; @@ -23,7 +24,7 @@ */ public class RedirectAuthoriseResultPopulator implements Populator, RedirectAuthoriseResult> { - private static final Logger LOG = Logger.getLogger(RedirectAuthoriseResultPopulator.class); + private static final Logger LOG = LoggerFactory.getLogger(RedirectAuthoriseResultPopulator.class); private static final String PAYMENT_STATUS = "paymentStatus"; private static final String STATUS = "status"; @@ -79,7 +80,7 @@ private BigDecimal getPaymentAmount(final Map source) { if (StringUtils.isNotEmpty(source.get(PAYMENT_AMOUNT)) && StringUtils.isNotEmpty(source.get(PAYMENT_CURRENCY))) { try { final Currency currency = Currency.getInstance(source.get(PAYMENT_CURRENCY)); - Amount amount = worldpayOrderService.createAmount(currency, Integer.valueOf(source.get(PAYMENT_AMOUNT))); + final Amount amount = worldpayOrderService.createAmount(currency, Integer.parseInt(source.get(PAYMENT_AMOUNT))); return new BigDecimal(amount.getValue()); } catch (IllegalArgumentException exception) { LOG.error(MessageFormat.format("Received invalid currency isoCode: [{0}]", source.get(PAYMENT_CURRENCY)), exception); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/hostedorderpage/service/impl/DefaultWorldpayURIService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/hostedorderpage/service/impl/DefaultWorldpayURIService.java index 461b8ea4..05e55f68 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/hostedorderpage/service/impl/DefaultWorldpayURIService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/hostedorderpage/service/impl/DefaultWorldpayURIService.java @@ -4,7 +4,8 @@ import com.worldpay.hostedorderpage.service.WorldpayURIService; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URIBuilder; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import java.net.URISyntaxException; import java.text.MessageFormat; @@ -16,7 +17,7 @@ */ public class DefaultWorldpayURIService implements WorldpayURIService { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayURIService.class); + private static final Logger LOG = LogManager.getLogger(DefaultWorldpayURIService.class); protected static final String UNABLE_TO_PARSE_URL = "Unable to parse url [{0}]"; protected static final String UNABLE_TO_PARSE_URL_REDIRECT_URL = "Unable to parse url redirect url"; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/interceptors/WorldpayPaymentInfoRemoveInterceptor.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/interceptors/WorldpayPaymentInfoRemoveInterceptor.java index e943ba0a..7d1df9ef 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/interceptors/WorldpayPaymentInfoRemoveInterceptor.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/interceptors/WorldpayPaymentInfoRemoveInterceptor.java @@ -1,18 +1,17 @@ package com.worldpay.interceptors; -import com.worldpay.core.services.impl.DefaultWorldpayPaymentInfoService; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.exception.WorldpayException; import com.worldpay.merchant.WorldpayMerchantInfoService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayDirectOrderService; import de.hybris.platform.core.model.order.payment.CreditCardPaymentInfoModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.core.model.order.payment.WorldpayAPMPaymentInfoModel; import de.hybris.platform.servicelayer.interceptor.InterceptorContext; import de.hybris.platform.servicelayer.interceptor.RemoveInterceptor; -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Required; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.text.MessageFormat; @@ -22,10 +21,15 @@ */ public class WorldpayPaymentInfoRemoveInterceptor implements RemoveInterceptor { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayPaymentInfoService.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayPaymentInfoRemoveInterceptor.class); - private WorldpayMerchantInfoService worldpayMerchantInfoService; - private WorldpayDirectOrderService worldpayDirectOrderService; + protected final WorldpayMerchantInfoService worldpayMerchantInfoService; + protected final WorldpayDirectOrderService worldpayDirectOrderService; + + public WorldpayPaymentInfoRemoveInterceptor(final WorldpayMerchantInfoService worldpayMerchantInfoService, final WorldpayDirectOrderService worldpayDirectOrderService) { + this.worldpayMerchantInfoService = worldpayMerchantInfoService; + this.worldpayDirectOrderService = worldpayDirectOrderService; + } @Override public void onRemove(final PaymentInfoModel paymentInfoModel, final InterceptorContext interceptorContext) { @@ -34,8 +38,7 @@ public void onRemove(final PaymentInfoModel paymentInfoModel, final InterceptorC if (!shouldNotDeleteToken(creditCardPaymentInfoModel)) { deleteToken(creditCardPaymentInfoModel, creditCardPaymentInfoModel.getSubscriptionId()); } - } - else if (paymentInfoModel instanceof WorldpayAPMPaymentInfoModel) { + } else if (paymentInfoModel instanceof WorldpayAPMPaymentInfoModel) { final WorldpayAPMPaymentInfoModel apmPaymentInfoModel = (WorldpayAPMPaymentInfoModel) paymentInfoModel; if (!shouldNotDeleteToken(apmPaymentInfoModel)) { deleteToken(apmPaymentInfoModel, apmPaymentInfoModel.getSubscriptionId()); @@ -48,12 +51,11 @@ private void deleteToken(final PaymentInfoModel paymentInfoModel, final String s try { final MerchantInfo merchantInfo = worldpayMerchantInfoService.getMerchantInfoByCode(merchantId); worldpayDirectOrderService.deleteToken(merchantInfo, paymentInfoModel, subscriptionId); - LOG.info(MessageFormat.format("Deleting worldpay token for user with authenticated shopper id {0}", - paymentInfoModel.getAuthenticatedShopperID())); + LOG.info("Deleting worldpay token for user with authenticated shopper id {}", paymentInfoModel.getAuthenticatedShopperID()); } catch (final WorldpayConfigurationException e) { LOG.error(MessageFormat.format( - "Could not find merchant configuration for merchant id [{0}]. The token was not deleted in Worldpay - subscription id [{1}]", - merchantId, subscriptionId), e); + "Could not find merchant configuration for merchant id [{0}]. The token was not deleted in Worldpay - subscription id [{1}]", + merchantId, subscriptionId), e); } catch (final WorldpayException e) { LOG.error(MessageFormat.format("Failed to delete token in worldpay, subscription id [{0}]", subscriptionId), e); } @@ -67,14 +69,4 @@ private boolean shouldNotDeleteToken(final CreditCardPaymentInfoModel creditCard private boolean shouldNotDeleteToken(final WorldpayAPMPaymentInfoModel apmPaymentInfoModel) { return apmPaymentInfoModel.getUser() == null || apmPaymentInfoModel.getDuplicate() || apmPaymentInfoModel.getSubscriptionId() == null; } - - @Required - public void setWorldpayMerchantInfoService(final WorldpayMerchantInfoService worldpayMerchantInfoService) { - this.worldpayMerchantInfoService = worldpayMerchantInfoService; - } - - @Required - public void setWorldpayDirectOrderService(final WorldpayDirectOrderService worldpayDirectOrderService) { - this.worldpayDirectOrderService = worldpayDirectOrderService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/Payload.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/Payload.java new file mode 100644 index 00000000..12af75d9 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/Payload.java @@ -0,0 +1,22 @@ +package com.worldpay.jalo; + +import de.hybris.platform.jalo.Item; +import de.hybris.platform.jalo.JaloBusinessException; +import de.hybris.platform.jalo.SessionContext; +import de.hybris.platform.jalo.type.ComposedType; +import org.apache.log4j.Logger; + +public class Payload extends GeneratedPayload +{ + @SuppressWarnings("unused") + private static final Logger LOG = Logger.getLogger( Payload.class.getName() ); + + @Override + protected Item createItem(final SessionContext ctx, final ComposedType type, final ItemAttributeMap allAttributes) throws JaloBusinessException + { + // business code placed here will be executed before the item is created + // then create the item + return super.createItem( ctx, type, allAttributes ); + } + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayApplePayConfiguration.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayApplePayConfiguration.java new file mode 100644 index 00000000..a638dcda --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayApplePayConfiguration.java @@ -0,0 +1,25 @@ +package com.worldpay.jalo; + +import de.hybris.platform.jalo.Item; +import de.hybris.platform.jalo.JaloBusinessException; +import de.hybris.platform.jalo.SessionContext; +import de.hybris.platform.jalo.type.ComposedType; +import org.apache.log4j.Logger; + +public class WorldpayApplePayConfiguration extends GeneratedWorldpayApplePayConfiguration +{ + @SuppressWarnings("unused") + private static final Logger LOG = Logger.getLogger( WorldpayApplePayConfiguration.class.getName() ); + + @Override + protected Item createItem(final SessionContext ctx, final ComposedType type, final ItemAttributeMap allAttributes) throws JaloBusinessException + { + // business code placed here will be executed before the item is created + // then create the item + final Item item = super.createItem( ctx, type, allAttributes ); + // business code placed here will be executed after the item was created + // and return the item + return item; + } + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayFraudSight.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayFraudSight.java new file mode 100644 index 00000000..71003aa4 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayFraudSight.java @@ -0,0 +1,25 @@ +package com.worldpay.jalo; + +import de.hybris.platform.jalo.Item; +import de.hybris.platform.jalo.JaloBusinessException; +import de.hybris.platform.jalo.SessionContext; +import de.hybris.platform.jalo.type.ComposedType; +import org.apache.log4j.Logger; + +public class WorldpayFraudSight extends GeneratedWorldpayFraudSight +{ + @SuppressWarnings("unused") + private static final Logger LOG = Logger.getLogger( WorldpayFraudSight.class.getName() ); + + @Override + protected Item createItem(final SessionContext ctx, final ComposedType type, final ItemAttributeMap allAttributes) throws JaloBusinessException + { + // business code placed here will be executed before the item is created + // then create the item + final Item item = super.createItem( ctx, type, allAttributes ); + // business code placed here will be executed after the item was created + // and return the item + return item; + } + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayGooglePayConfiguration.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayGooglePayConfiguration.java new file mode 100644 index 00000000..22a10b13 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayGooglePayConfiguration.java @@ -0,0 +1,25 @@ +package com.worldpay.jalo; + +import de.hybris.platform.jalo.Item; +import de.hybris.platform.jalo.JaloBusinessException; +import de.hybris.platform.jalo.SessionContext; +import de.hybris.platform.jalo.type.ComposedType; +import org.apache.log4j.Logger; + +public class WorldpayGooglePayConfiguration extends GeneratedWorldpayGooglePayConfiguration +{ + @SuppressWarnings("unused") + private static final Logger LOG = Logger.getLogger( WorldpayGooglePayConfiguration.class.getName() ); + + @Override + protected Item createItem(final SessionContext ctx, final ComposedType type, final ItemAttributeMap allAttributes) throws JaloBusinessException + { + // business code placed here will be executed before the item is created + // then create the item + final Item item = super.createItem( ctx, type, allAttributes ); + // business code placed here will be executed after the item was created + // and return the item + return item; + } + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayMerchantConfiguration.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayMerchantConfiguration.java new file mode 100644 index 00000000..9261a219 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayMerchantConfiguration.java @@ -0,0 +1,25 @@ +package com.worldpay.jalo; + +import de.hybris.platform.jalo.Item; +import de.hybris.platform.jalo.JaloBusinessException; +import de.hybris.platform.jalo.SessionContext; +import de.hybris.platform.jalo.type.ComposedType; +import org.apache.log4j.Logger; + +public class WorldpayMerchantConfiguration extends GeneratedWorldpayMerchantConfiguration +{ + @SuppressWarnings("unused") + private static final Logger LOG = Logger.getLogger( WorldpayMerchantConfiguration.class.getName() ); + + @Override + protected Item createItem(final SessionContext ctx, final ComposedType type, final ItemAttributeMap allAttributes) throws JaloBusinessException + { + // business code placed here will be executed before the item is created + // then create the item + final Item item = super.createItem( ctx, type, allAttributes ); + // business code placed here will be executed after the item was created + // and return the item + return item; + } + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayThreeDS2JsonWebTokenConfiguration.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayThreeDS2JsonWebTokenConfiguration.java new file mode 100644 index 00000000..2cf14d59 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/jalo/WorldpayThreeDS2JsonWebTokenConfiguration.java @@ -0,0 +1,25 @@ +package com.worldpay.jalo; + +import de.hybris.platform.jalo.Item; +import de.hybris.platform.jalo.JaloBusinessException; +import de.hybris.platform.jalo.SessionContext; +import de.hybris.platform.jalo.type.ComposedType; +import org.apache.log4j.Logger; + +public class WorldpayThreeDS2JsonWebTokenConfiguration extends GeneratedWorldpayThreeDS2JsonWebTokenConfiguration +{ + @SuppressWarnings("unused") + private static final Logger LOG = Logger.getLogger( WorldpayThreeDS2JsonWebTokenConfiguration.class.getName() ); + + @Override + protected Item createItem(final SessionContext ctx, final ComposedType type, final ItemAttributeMap allAttributes) throws JaloBusinessException + { + // business code placed here will be executed before the item is created + // then create the item + final Item item = super.createItem( ctx, type, allAttributes ); + // business code placed here will be executed after the item was created + // and return the item + return item; + } + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/klarna/WorldpayKlarnaUtils.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/klarna/WorldpayKlarnaUtils.java deleted file mode 100644 index ea7faf4c..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/klarna/WorldpayKlarnaUtils.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.worldpay.klarna; - -/** - * Utils class for Klarna Payment methods - */ -public interface WorldpayKlarnaUtils { - /** - * Checkes wether the paymentCode passed is or not a Klarna valid payment method type code - * - * @param paymentCode - * @return - */ - boolean isKlarnaPaymentType(final String paymentCode); -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/klarna/impl/DefaultWorldpayKlarnaUtils.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/klarna/impl/DefaultWorldpayKlarnaUtils.java deleted file mode 100644 index 115d7bd0..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/klarna/impl/DefaultWorldpayKlarnaUtils.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.worldpay.klarna.impl; - -import com.worldpay.klarna.WorldpayKlarnaUtils; - -import java.util.List; -import java.util.Objects; - -public class DefaultWorldpayKlarnaUtils implements WorldpayKlarnaUtils { - private final List klarnaPayments; - - public DefaultWorldpayKlarnaUtils(final List klarnaPayments) { - this.klarnaPayments = klarnaPayments; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isKlarnaPaymentType(final String paymentCode) { - return Objects.nonNull(paymentCode) && klarnaPayments.stream().anyMatch(paymentCode::equals); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/WorldpayMerchantConfigDataService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/WorldpayMerchantConfigDataService.java deleted file mode 100644 index 489f54e6..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/WorldpayMerchantConfigDataService.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.worldpay.merchant; - -import com.worldpay.config.merchant.WorldpayMerchantConfigData; - -import java.util.Map; - -/** - * Interface that provides the method to retrieve the MerchantConfigurations. - */ -public interface WorldpayMerchantConfigDataService { - /** - * Returns the merchant configuration configured for the current application. - * - * @return Map that contains the configured merchants for the application. - */ - Map getMerchantConfiguration(); -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/WorldpayMerchantInfoService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/WorldpayMerchantInfoService.java index 120c4ece..81969198 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/WorldpayMerchantInfoService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/WorldpayMerchantInfoService.java @@ -1,7 +1,8 @@ package com.worldpay.merchant; import com.worldpay.exception.WorldpayConfigurationException; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; +import de.hybris.platform.basecommerce.model.site.BaseSiteModel; import de.hybris.platform.payment.model.PaymentTransactionModel; /** @@ -13,6 +14,7 @@ public interface WorldpayMerchantInfoService { /** * Returns the merchant configured to be used depending on the UI experience level. + * * @return * @throws WorldpayConfigurationException */ @@ -20,24 +22,28 @@ public interface WorldpayMerchantInfoService { /** * Returns the merchant configured to be used for order replenishment (B2B) - * @return + * + * @param site the site for which retrieve the merchant info + * @return the populated {@link MerchantInfo} * @throws WorldpayConfigurationException */ - MerchantInfo getReplenishmentMerchant() throws WorldpayConfigurationException; + MerchantInfo getReplenishmentMerchant(BaseSiteModel site) throws WorldpayConfigurationException; /** * Returns the merchantConfiguration for a known merchantCode. + * * @param merchantCode * @return * @throws WorldpayConfigurationException */ - MerchantInfo getMerchantInfoByCode(final String merchantCode) throws WorldpayConfigurationException; + MerchantInfo getMerchantInfoByCode(String merchantCode) throws WorldpayConfigurationException; /** * Returns the merchantConfiguration for the merchant used in the transaction {@link PaymentTransactionModel} + * * @param paymentTransactionModel * @return * @throws WorldpayConfigurationException */ - MerchantInfo getMerchantInfoFromTransaction(final PaymentTransactionModel paymentTransactionModel) throws WorldpayConfigurationException; + MerchantInfo getMerchantInfoFromTransaction(PaymentTransactionModel paymentTransactionModel) throws WorldpayConfigurationException; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/configuration/services/WorldpayMerchantConfigurationService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/configuration/services/WorldpayMerchantConfigurationService.java new file mode 100644 index 00000000..ffe690df --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/configuration/services/WorldpayMerchantConfigurationService.java @@ -0,0 +1,39 @@ +package com.worldpay.merchant.configuration.services; + +import com.worldpay.model.WorldpayMerchantConfigurationModel; + +import java.util.Set; + +/** + * Manages the merchant configurations + */ +public interface WorldpayMerchantConfigurationService { + + /** + * Returns the WorldpayMerchantConfigurationModel for the current site and web configuration + * + * @return a {@link WorldpayMerchantConfigurationModel} + */ + WorldpayMerchantConfigurationModel getCurrentWebConfiguration(); + + /** + * Returns the WorldpayMerchantConfigurationModel for the current site and asm configuration + * + * @return a {@link WorldpayMerchantConfigurationModel} + */ + WorldpayMerchantConfigurationModel getCurrentAsmConfiguration(); + + /** + * Returns the set of WorldpayMerchantConfigurationModel for the current site + * + * @return a {@link Set} + */ + Set getAllCurrentSiteMerchantConfigurations(); + + /** + * Returns the set of WorldpayMerchantConfigurationModel related to all the active sites in the system + * + * @return a {@link Set} + */ + Set getAllSystemActiveSiteMerchantConfigurations(); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/configuration/services/impl/DefaultWorldpayMerchantConfigurationService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/configuration/services/impl/DefaultWorldpayMerchantConfigurationService.java new file mode 100644 index 00000000..4968a41a --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/configuration/services/impl/DefaultWorldpayMerchantConfigurationService.java @@ -0,0 +1,83 @@ +package com.worldpay.merchant.configuration.services.impl; + +import com.worldpay.merchant.configuration.services.WorldpayMerchantConfigurationService; +import com.worldpay.model.WorldpayMerchantConfigurationModel; +import de.hybris.platform.basecommerce.model.site.BaseSiteModel; +import de.hybris.platform.cms2.model.site.CMSSiteModel; +import de.hybris.platform.site.BaseSiteService; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static com.google.common.base.Preconditions.checkArgument; +import static java.util.Arrays.asList; + +/** + * Default implementation of the {@link WorldpayMerchantConfigurationService} + */ +public class DefaultWorldpayMerchantConfigurationService implements WorldpayMerchantConfigurationService { + + private static final String CURRENT_BASE_SITE_CANNOT_BE_NULL = "Current base site cannot be null"; + + protected final BaseSiteService baseSiteService; + + public DefaultWorldpayMerchantConfigurationService(final BaseSiteService baseSiteService) { + this.baseSiteService = baseSiteService; + } + + /** + * {@inheritDoc} + */ + @Override + public WorldpayMerchantConfigurationModel getCurrentWebConfiguration() { + final BaseSiteModel currentBaseSite = baseSiteService.getCurrentBaseSite(); + checkArgument(currentBaseSite != null, CURRENT_BASE_SITE_CANNOT_BE_NULL); + + return currentBaseSite.getWebMerchantConfiguration(); + } + + /** + * {@inheritDoc} + */ + @Override + public WorldpayMerchantConfigurationModel getCurrentAsmConfiguration() { + final BaseSiteModel currentBaseSite = baseSiteService.getCurrentBaseSite(); + checkArgument(currentBaseSite != null, CURRENT_BASE_SITE_CANNOT_BE_NULL); + + return currentBaseSite.getAsmMerchantConfiguration(); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getAllCurrentSiteMerchantConfigurations() { + final BaseSiteModel currentBaseSite = baseSiteService.getCurrentBaseSite(); + checkArgument(currentBaseSite != null, CURRENT_BASE_SITE_CANNOT_BE_NULL); + + return Set.of(currentBaseSite.getWebMerchantConfiguration(), currentBaseSite.getAsmMerchantConfiguration(), currentBaseSite.getReplenishmentMerchantConfiguration()); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getAllSystemActiveSiteMerchantConfigurations() { + final List allActiveSites = baseSiteService.getAllBaseSites() + .stream() + .map(CMSSiteModel.class::cast) + .filter(CMSSiteModel::getActive) + .collect(Collectors.toList()); + + final Set systemMerchantConfigurations = new HashSet<>(); + allActiveSites.forEach(site -> systemMerchantConfigurations.addAll(asList( + site.getWebMerchantConfiguration(), + site.getAsmMerchantConfiguration(), + site.getReplenishmentMerchantConfiguration()))); + systemMerchantConfigurations.remove(null); + + return systemMerchantConfigurations; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/impl/DefaultWorldpayMerchantConfigDataService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/impl/DefaultWorldpayMerchantConfigDataService.java deleted file mode 100644 index a8f9d3d1..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/impl/DefaultWorldpayMerchantConfigDataService.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.worldpay.merchant.impl; - -import com.worldpay.config.merchant.WorldpayMerchantConfigData; -import com.worldpay.merchant.WorldpayMerchantConfigDataService; -import de.hybris.platform.acceleratorservices.config.SiteConfigService; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.Required; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -import java.util.Map; - -/** - * Default implementation of {@link WorldpayMerchantConfigDataService} - */ -public class DefaultWorldpayMerchantConfigDataService implements WorldpayMerchantConfigDataService, ApplicationContextAware { - - protected static final String WORLDPAY_MERCHANT_CONFIG = "worldpaymerchantconfig"; - - private SiteConfigService siteConfigService; - private ApplicationContext applicationContext; - - /** - * {@inheritDoc} - */ - @Override - public Map getMerchantConfiguration() { - final String merchantConfigurationBeanName = siteConfigService.getProperty(WORLDPAY_MERCHANT_CONFIG); - return getConfiguredMerchants(merchantConfigurationBeanName); - } - - private Map getConfiguredMerchants(final String merchantConfigurationBeanName) { - return (Map) applicationContext.getBean(merchantConfigurationBeanName); - } - - @Override - public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - @Required - public void setSiteConfigService(final SiteConfigService siteConfigService) { - this.siteConfigService = siteConfigService; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/impl/DefaultWorldpayMerchantInfoService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/impl/DefaultWorldpayMerchantInfoService.java index d135b2a8..0664fdb1 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/impl/DefaultWorldpayMerchantInfoService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/merchant/impl/DefaultWorldpayMerchantInfoService.java @@ -1,18 +1,20 @@ package com.worldpay.merchant.impl; -import com.worldpay.config.merchant.WorldpayMerchantConfigData; +import com.worldpay.data.MerchantInfo; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.merchant.WorldpayMerchantInfoService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.merchant.configuration.services.WorldpayMerchantConfigurationService; +import com.worldpay.model.WorldpayMerchantConfigurationModel; import com.worldpay.strategy.WorldpayMerchantStrategy; import de.hybris.platform.acceleratorservices.config.SiteConfigService; +import de.hybris.platform.basecommerce.model.site.BaseSiteModel; import de.hybris.platform.payment.model.PaymentTransactionModel; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Required; +import org.apache.commons.lang3.BooleanUtils; import org.springframework.context.ApplicationContextAware; import java.text.MessageFormat; -import java.util.List; + +import static com.google.common.base.Preconditions.checkArgument; /** * This implementation of {@link WorldpayMerchantInfoService} uses looks the configured map of merchants configured in Spring @@ -21,41 +23,48 @@ */ public class DefaultWorldpayMerchantInfoService implements WorldpayMerchantInfoService { - private WorldpayMerchantStrategy worldpayMerchantStrategy; + private static final String CURRENT_BASE_SITE_CANNOT_BE_NULL = "Current base site cannot be null"; + + protected final WorldpayMerchantStrategy worldpayMerchantStrategy; + protected final WorldpayMerchantConfigurationService worldpayMerchantConfigurationService; - @Autowired - private List configuredMerchants; + public DefaultWorldpayMerchantInfoService(final WorldpayMerchantStrategy worldpayMerchantStrategy, + final WorldpayMerchantConfigurationService worldpayMerchantConfigurationService) { + this.worldpayMerchantStrategy = worldpayMerchantStrategy; + this.worldpayMerchantConfigurationService = worldpayMerchantConfigurationService; + } /** * {@inheritDoc} */ @Override public MerchantInfo getCurrentSiteMerchant() { - final WorldpayMerchantConfigData currentSiteMerchantConfigData = worldpayMerchantStrategy.getMerchant(); - return createMerchantInfo(currentSiteMerchantConfigData); + final WorldpayMerchantConfigurationModel currentSiteMerchantConfig = worldpayMerchantStrategy.getMerchant(); + return createMerchantInfo(currentSiteMerchantConfig); } /** * {@inheritDoc} */ @Override - public MerchantInfo getReplenishmentMerchant() { - final WorldpayMerchantConfigData replensihmentMerchantConfigData = worldpayMerchantStrategy.getReplenishmentMerchant(); - return createMerchantInfo(replensihmentMerchantConfigData); + public MerchantInfo getReplenishmentMerchant(final BaseSiteModel site) { + checkArgument(site != null, CURRENT_BASE_SITE_CANNOT_BE_NULL); + checkArgument(site.getReplenishmentMerchantConfiguration() != null, "The Replenishment for site " + site.getUid() + " cannot be null"); + + return createMerchantInfo(site.getReplenishmentMerchantConfiguration()); } /** * {@inheritDoc} - * - * @return */ @Override public MerchantInfo getMerchantInfoByCode(final String merchantCode) throws WorldpayConfigurationException { - final WorldpayMerchantConfigData worldpayMerchantConfigData = configuredMerchants.stream() - .filter(config -> config.getCode().equals(merchantCode)) - .findAny() - .orElseThrow(() -> new WorldpayConfigurationException(MessageFormat.format("No merchant configuration found for merchant code {0}", merchantCode))); - return createMerchantInfo(worldpayMerchantConfigData); + final WorldpayMerchantConfigurationModel worldpayMerchantConfiguration = worldpayMerchantConfigurationService.getAllSystemActiveSiteMerchantConfigurations() + .stream() + .filter(merchantConfig -> merchantCode.equalsIgnoreCase(merchantConfig.getCode())) + .findAny() + .orElseThrow(() -> new WorldpayConfigurationException(MessageFormat.format("No merchant configuration found for merchant code {0}", merchantCode))); + return createMerchantInfo(worldpayMerchantConfiguration); } /** @@ -67,25 +76,15 @@ public MerchantInfo getMerchantInfoFromTransaction(final PaymentTransactionModel } - protected MerchantInfo createMerchantInfo(final WorldpayMerchantConfigData worldpayMerchantConfigData) { - final MerchantInfo merchantInfo = new MerchantInfo(worldpayMerchantConfigData.getCode(), worldpayMerchantConfigData.getPassword()); - if (worldpayMerchantConfigData.getMacValidation()) { + protected MerchantInfo createMerchantInfo(final WorldpayMerchantConfigurationModel worldpayMerchantConfiguration) { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantCode(worldpayMerchantConfiguration.getCode()); + merchantInfo.setMerchantPassword(worldpayMerchantConfiguration.getPassword()); + merchantInfo.setUsingMacValidation(false); + if (BooleanUtils.isTrue(worldpayMerchantConfiguration.getMacValidation())) { merchantInfo.setUsingMacValidation(true); - merchantInfo.setMacSecret(worldpayMerchantConfigData.getMacSecret()); + merchantInfo.setMacSecret(worldpayMerchantConfiguration.getMacSecret()); } return merchantInfo; } - - @Required - public void setWorldpayMerchantStrategy(final WorldpayMerchantStrategy worldpayMerchantStrategy) { - this.worldpayMerchantStrategy = worldpayMerchantStrategy; - } - - public void setConfiguredMerchants(final List configuredMerchants) { - this.configuredMerchants = configuredMerchants; - } - - public List getConfiguredMerchants() { - return configuredMerchants; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/ordercancel/impl/denialstrategies/WorldpayApmOrderCancelDenialStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/ordercancel/impl/denialstrategies/WorldpayApmOrderCancelDenialStrategy.java index 38157ea7..7f14aad7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/ordercancel/impl/denialstrategies/WorldpayApmOrderCancelDenialStrategy.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/ordercancel/impl/denialstrategies/WorldpayApmOrderCancelDenialStrategy.java @@ -9,18 +9,17 @@ import de.hybris.platform.ordercancel.model.OrderCancelConfigModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; -import static java.text.MessageFormat.format; - /** * Strategy that avoids an order cancellation when has been paid with an APM or the payment method is still unknown. */ public class WorldpayApmOrderCancelDenialStrategy extends AbstractCancelDenialStrategy implements OrderCancelDenialStrategy { - private static final Logger LOG = Logger.getLogger(WorldpayApmOrderCancelDenialStrategy.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayApmOrderCancelDenialStrategy.class); /** * @param orderCancelConfigModel @@ -38,7 +37,7 @@ public OrderCancelDenialReason getCancelDenialReason(final OrderCancelConfigMode for (final PaymentTransactionModel paymentTransaction : paymentTransactions) { final PaymentInfoModel paymentInfo = paymentTransaction.getInfo(); if (shouldReturnCancelReason(paymentInfo)) { - LOG.warn(format("The order [{0}] cannot be cancelled as the payment was made through an APM or is still unknown", orderModel.getCode())); + LOG.warn("The order [{}] cannot be cancelled as the payment was made through an APM or is still unknown", orderModel.getCode()); return getReason(); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/ordercancel/impl/denialstrategies/WorldpayOrderCancelDenialStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/ordercancel/impl/denialstrategies/WorldpayOrderCancelDenialStrategy.java index 44c74598..55c8a741 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/ordercancel/impl/denialstrategies/WorldpayOrderCancelDenialStrategy.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/ordercancel/impl/denialstrategies/WorldpayOrderCancelDenialStrategy.java @@ -8,19 +8,19 @@ import de.hybris.platform.ordercancel.model.OrderCancelConfigModel; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import static de.hybris.platform.payment.enums.PaymentTransactionType.CAPTURE; -import static java.text.MessageFormat.format; /** * Implementation of a OrderCancelDenialStrategy taking into consideration the conditions for Worldpay */ public class WorldpayOrderCancelDenialStrategy extends AbstractCancelDenialStrategy implements OrderCancelDenialStrategy { - private static final Logger LOG = Logger.getLogger(WorldpayOrderCancelDenialStrategy.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayOrderCancelDenialStrategy.class); /** * Implementation of getCancelDenialReason that checks if the order has a confirmed captured paymentTransactionEntry. @@ -48,7 +48,7 @@ private OrderCancelDenialReason findReason(final OrderModel orderModel, final Li final List entries = paymentTransaction.getEntries(); for (final PaymentTransactionEntryModel entry : entries) { if (shouldReturnDenialReason(entry)) { - LOG.warn(format("The order {0} cannot be cancelled because the transaction entry with requestId {1} is captured", orderModel.getCode(), entry.getRequestId())); + LOG.warn("The order {} cannot be cancelled because the transaction entry with requestId {} is captured", orderModel.getCode(), entry.getRequestId()); return getReason(); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/orderprocess/strategies/cancel/impl/DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/orderprocess/strategies/cancel/impl/DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategy.java index 668b80d2..5db5eba5 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/orderprocess/strategies/cancel/impl/DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategy.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/orderprocess/strategies/cancel/impl/DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategy.java @@ -19,6 +19,7 @@ public class DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategy implements WorldpayCancelWholeOrderDueToCancelNotificationStrategy { private static final Logger LOG = LogManager.getLogger(DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategy.class); + protected final WorldpayPaymentTransactionService worldpayPaymentTransactionService; protected final ModelService modelService; @@ -36,17 +37,19 @@ public DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategy(final Worl public void cancelOrder(final OrderProcessModel orderProcessModel) { final OrderModel orderModel = orderProcessModel.getOrder(); - LOG.debug("The order {} is being cancelled.", orderModel::getCode); + if (!OrderStatus.CANCELLED.equals(orderModel.getStatus())) { + LOG.debug("The order {} is being cancelled.", orderModel::getCode); - Optional.ofNullable(worldpayPaymentTransactionService.getPaymentTransactionFromCode(orderModel.getWorldpayOrderCode())) + Optional.ofNullable(worldpayPaymentTransactionService.getPaymentTransactionFromCode(orderModel.getWorldpayOrderCode())) .ifPresentOrElse( - paymentTransactionModel -> { - createAndSaveCancelTransactionEntry(paymentTransactionModel); - orderModel.setStatus(OrderStatus.CANCELLED); - }, - () -> orderModel.setStatus(OrderStatus.PROCESSING_ERROR) + paymentTransactionModel -> { + createAndSaveCancelTransactionEntry(paymentTransactionModel); + orderModel.setStatus(OrderStatus.CANCELLED); + }, + () -> orderModel.setStatus(OrderStatus.PROCESSING_ERROR) ); - modelService.save(orderModel); + modelService.save(orderModel); + } } protected void createAndSaveCancelTransactionEntry(final PaymentTransactionModel paymentTransactionModel) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/DefaultWorldpayServiceGateway.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/DefaultWorldpayServiceGateway.java index 2847413c..baccf29c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/DefaultWorldpayServiceGateway.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/DefaultWorldpayServiceGateway.java @@ -1,9 +1,11 @@ package com.worldpay.service; +import com.google.common.collect.ImmutableMap; import com.worldpay.config.Environment; import com.worldpay.exception.WorldpayException; import com.worldpay.exception.WorldpayValidationException; import com.worldpay.internal.model.PaymentService; +import com.worldpay.model.PayloadModel; import com.worldpay.service.http.ServiceReply; import com.worldpay.service.http.WorldpayConnector; import com.worldpay.service.request.*; @@ -11,11 +13,18 @@ import com.worldpay.service.request.validation.WorldpayXMLValidator; import com.worldpay.service.response.*; import com.worldpay.service.response.transform.ServiceResponseTransformer; +import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.internal.dao.GenericDao; +import de.hybris.platform.servicelayer.model.ModelService; +import org.apache.commons.lang.StringUtils; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; +import java.util.ArrayList; +import java.util.List; import java.util.Map; +import java.util.Optional; import static com.worldpay.config.Environment.PROD; import static com.worldpay.util.WorldpayConstants.JAXB_CONTEXT; @@ -34,17 +43,24 @@ public class DefaultWorldpayServiceGateway implements WorldpayServiceGateway { protected final ConfigurationService configurationService; protected final Map responseTransformerStrategyMap; protected final Map requestTransformerStrategyMap; + protected final GenericDao abstractOrderGenericDao; + protected final ModelService modelService; + public DefaultWorldpayServiceGateway(final WorldpayConnector worldpayConnector, final WorldpayXMLValidator worldpayXMLValidator, final ConfigurationService configurationService, final Map responseTransformerStrategyMap, - final Map requestTransformerStrategyMap) { + final Map requestTransformerStrategyMap, + final GenericDao abstractOrderGenericDao, + final ModelService modelService) { this.worldpayConnector = worldpayConnector; this.worldpayXMLValidator = worldpayXMLValidator; this.configurationService = configurationService; this.responseTransformerStrategyMap = responseTransformerStrategyMap; this.requestTransformerStrategyMap = requestTransformerStrategyMap; + this.abstractOrderGenericDao = abstractOrderGenericDao; + this.modelService = modelService; } /** @@ -103,6 +119,14 @@ public CancelServiceResponse cancel(final CancelServiceRequest request) throws W return (CancelServiceResponse) service(request); } + /** + * {@inheritDoc} + */ + @Override + public VoidSaleServiceResponse voidSale(final VoidSaleServiceRequest request) throws WorldpayException { + return (VoidSaleServiceResponse) service(request); + } + /** * {@inheritDoc} */ @@ -146,8 +170,10 @@ public DirectAuthoriseServiceResponse sendSecondThreeDSecurePayment(final Second protected ServiceResponse service(final ServiceRequest request) throws WorldpayException { final ServiceRequestTransformer requestTransformer = requestTransformerStrategyMap.get(request.getClass().getName()); final PaymentService paymentService = requestTransformer.transform(request); + String paymentRequest; + try { - logPaymentServiceXML(paymentService); + paymentRequest = logPaymentServiceXML(paymentService); worldpayXMLValidator.validate(paymentService); } catch (final WorldpayValidationException e) { throw new WorldpayValidationException("Error validating XML: " + e.getMessage(), e); @@ -156,20 +182,60 @@ protected ServiceResponse service(final ServiceRequest request) throws WorldpayE final ServiceReply reply = worldpayConnector.send(paymentService, request.getMerchantInfo(), request.getCookie()); final ServiceResponseTransformer responseTransformer = responseTransformerStrategyMap.get(request.getClass().getName()); - logPaymentServiceXML(reply.getPaymentService()); + final String paymentResponse = logPaymentServiceXML(reply.getPaymentService()); + saveRequestAndResponseInOrder(request.getOrderCode(), paymentRequest, paymentResponse); return responseTransformer.transform(reply); } - private void logPaymentServiceXML(PaymentService paymentService) throws WorldpayValidationException { + private String logPaymentServiceXML(final PaymentService paymentService) throws WorldpayValidationException { final String environment = configurationService.getConfiguration().getString(WORLDPAY_CONFIG_ENVIRONMENT); if (PROD != Environment.valueOf(environment)) { try { final Marshaller marshaller = JAXB_CONTEXT.createMarshaller(); marshaller.setProperty(JAXB_FRAGMENT, TRUE); - worldpayConnector.logXMLOut(paymentService); + return worldpayConnector.logXMLOut(paymentService); } catch (final JAXBException jaxbException) { throw new WorldpayValidationException(jaxbException.getMessage(), jaxbException); } } + return null; + } + + private void saveRequestAndResponseInOrder(final String orderCode, final String request, final String response) { + if (StringUtils.isNotBlank(orderCode)) { + final List results = abstractOrderGenericDao.find(ImmutableMap.of( + AbstractOrderModel.WORLDPAYORDERCODE, orderCode + )); + if (!results.isEmpty()) { + final AbstractOrderModel abstractOrder = results.get(0); + setPaymentRequestPayload(request, abstractOrder); + setPaymentResponsePayload(response, abstractOrder); + modelService.save(abstractOrder); + } + } + } + + private void setPaymentRequestPayload(final String request, final AbstractOrderModel abstractOrder) { + Optional.ofNullable(request).ifPresent(paymentRequest -> { + final List requestList = new ArrayList<>(abstractOrder.getRequestsPayload()); + requestList.add(createPayloadModel(request)); + abstractOrder.setRequestsPayload(requestList); + }); + } + + private void setPaymentResponsePayload(final String response, final AbstractOrderModel abstractOrder) { + Optional.ofNullable(response).ifPresent(paymentResponse -> { + final List requestList = new ArrayList<>(abstractOrder.getResponsesPayload()); + requestList.add(createPayloadModel(response)); + abstractOrder.setResponsesPayload(requestList); + + }); + } + + protected PayloadModel createPayloadModel(final String payload) { + final PayloadModel payloadModel = modelService.create(PayloadModel.class); + payloadModel.setPayload(payload); + modelService.save(payloadModel); + return payloadModel; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/WorldpayServiceGateway.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/WorldpayServiceGateway.java index 8039a22a..3f9906e6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/WorldpayServiceGateway.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/WorldpayServiceGateway.java @@ -104,6 +104,15 @@ public interface WorldpayServiceGateway { */ CancelServiceResponse cancel(CancelServiceRequest request) throws WorldpayException; + /** + * Make a void request with Worldpay + * + * @param request Use the convenience method in {@link VoidSaleServiceRequest} to create the request. Ensures the correct details are set before making the call + * @return {@link CancelServiceResponse} object with the reply details. + * @throws WorldpayException if there have been issues making the request + */ + VoidSaleServiceResponse voidSale(VoidSaleServiceRequest request) throws WorldpayException; + /** * Make a refund request with Worldpay. Can only be invoked if the funds have been captured * diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/WorldpayUrlService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/WorldpayUrlService.java index dbe52317..e1bf01a7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/WorldpayUrlService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/WorldpayUrlService.java @@ -1,6 +1,7 @@ package com.worldpay.service; import com.worldpay.exception.WorldpayConfigurationException; +import com.worldpay.model.WorldpayThreeDS2JsonWebTokenConfigurationModel; /** * Interface defining the WorldpayUrlService. Implementing service needs to be able to provide fully qualified urls for @@ -101,4 +102,11 @@ public interface WorldpayUrlService { * @return */ String getFullThreeDSecureFlexAutosubmitUrl() throws WorldpayConfigurationException; + + /** + * Gets the 3DS2 configuration model for the current base site + * + * @return the configuration + */ + WorldpayThreeDS2JsonWebTokenConfigurationModel getThreeDS2Configuration(); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/hop/WorldpayHOPPService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/hop/WorldpayHOPPService.java index a307a85c..b8572fde 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/hop/WorldpayHOPPService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/hop/WorldpayHOPPService.java @@ -3,7 +3,7 @@ import com.worldpay.data.AdditionalAuthInfo; import com.worldpay.exception.WorldpayException; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import de.hybris.platform.acceleratorservices.payment.data.PaymentData; import de.hybris.platform.core.model.order.CartModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/hop/impl/DefaultWorldpayHOPService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/hop/impl/DefaultWorldpayHOPService.java index 57b0814a..f396b7a7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/hop/impl/DefaultWorldpayHOPService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/hop/impl/DefaultWorldpayHOPService.java @@ -7,8 +7,8 @@ import com.worldpay.service.WorldpayServiceGateway; import com.worldpay.service.WorldpayUrlService; import com.worldpay.service.hop.WorldpayHOPPService; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.RedirectReference; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.RedirectReference; import com.worldpay.service.payment.request.WorldpayRequestFactory; import com.worldpay.service.request.RedirectAuthoriseServiceRequest; import com.worldpay.service.response.RedirectAuthoriseServiceResponse; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/http/WorldpayConnector.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/http/WorldpayConnector.java index 3ec35fcc..25bc8d65 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/http/WorldpayConnector.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/http/WorldpayConnector.java @@ -4,7 +4,7 @@ import com.worldpay.exception.WorldpayException; import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.PaymentService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; /** * Interface template for the connector required to send the xml {@link PaymentService} to Worldpay. @@ -29,5 +29,5 @@ public interface WorldpayConnector { * * @param paymentService */ - void logXMLOut(final PaymentService paymentService); + String logXMLOut(final PaymentService paymentService); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/http/impl/DefaultWorldpayConnector.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/http/impl/DefaultWorldpayConnector.java index 17599cde..2d790771 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/http/impl/DefaultWorldpayConnector.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/http/impl/DefaultWorldpayConnector.java @@ -6,12 +6,13 @@ import com.worldpay.service.http.ServiceReply; import com.worldpay.service.http.WorldpayConnector; import com.worldpay.service.marshalling.PaymentServiceMarshaller; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.util.WorldpayConstants; import de.hybris.platform.servicelayer.config.ConfigurationService; import org.apache.commons.io.IOUtils; import org.apache.http.entity.ContentType; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; @@ -35,7 +36,7 @@ */ public class DefaultWorldpayConnector implements WorldpayConnector { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayConnector.class); + private static final Logger LOG = LogManager.getLogger(DefaultWorldpayConnector.class); protected static final String WORLDPAY_CONFIG_CONTEXT = "worldpay.config.context"; protected static final String WORLDPAY_CONFIG_DOMAIN = "worldpay.config.domain"; @@ -114,13 +115,16 @@ private ServiceReply processResponseXML(final ResponseEntity responseXML } @Override - public void logXMLOut(final PaymentService paymentService) { + public String logXMLOut(final PaymentService paymentService) { try { LOG.info("*** XML OUT ***"); - LOG.info(paymentServiceMarshaller.marshal(paymentService)); + final String parsedPaymentService = paymentServiceMarshaller.marshal(paymentService); + LOG.info(parsedPaymentService); LOG.info("*** XML OUT END ***"); + return parsedPaymentService; } catch (final WorldpayException e) { LOG.debug("There was an error marshalling the paymentService for debug logging", e); } + return null; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/AbstractWorldpayUrlService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/AbstractWorldpayUrlService.java index c83edacf..8cce8a73 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/AbstractWorldpayUrlService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/AbstractWorldpayUrlService.java @@ -15,12 +15,10 @@ public abstract class AbstractWorldpayUrlService implements WorldpayUrlService { private String failurePath; private String cancelPath; private String threeDSecureTermPath; - private String threeDSecureFlexFlowReturnUrl; private String threeDSecureQuoteTermPath; private String errorPath; private String termsPath; private String klarnaConfirmationPath; - private String threeDSecureFlexAuthSubmit; public String getSuccessPath() { return successPath; @@ -102,22 +100,4 @@ public String getKlarnaConfirmationPath() { public void setKlarnaConfirmationPath(final String klarnaConfirmationPath) { this.klarnaConfirmationPath = klarnaConfirmationPath; } - - public String getThreeDSecureFlexFlowReturnUrl() { - return threeDSecureFlexFlowReturnUrl; - } - - @Required - public void setThreeDSecureFlexFlowReturnUrl(final String threeDSecureFlexFlowReturnUrl) { - this.threeDSecureFlexFlowReturnUrl = threeDSecureFlexFlowReturnUrl; - } - - public String getThreeDSecureFlexAuthSubmit() { - return threeDSecureFlexAuthSubmit; - } - - @Required - public void setThreeDSecureFlexAuthSubmit(final String threeDSecureFlexAuthSubmit) { - this.threeDSecureFlexAuthSubmit = threeDSecureFlexAuthSubmit; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/DefaultWorldpayAuthorisationResultService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/DefaultWorldpayAuthorisationResultService.java index 5dcc3a0a..9815e742 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/DefaultWorldpayAuthorisationResultService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/DefaultWorldpayAuthorisationResultService.java @@ -3,12 +3,13 @@ import com.worldpay.commands.WorldpaySubscriptionAuthorizeResult; import com.worldpay.enums.order.AuthorisedStatus; import com.worldpay.service.WorldpayAuthorisationResultService; -import com.worldpay.service.model.RedirectReference; +import com.worldpay.data.RedirectReference; import com.worldpay.service.response.DirectAuthoriseServiceResponse; import de.hybris.platform.payment.commands.result.AbstractResult; import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.dto.TransactionStatusDetails; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static de.hybris.platform.payment.dto.TransactionStatus.*; import static de.hybris.platform.payment.dto.TransactionStatusDetails.*; @@ -18,7 +19,7 @@ */ public class DefaultWorldpayAuthorisationResultService implements WorldpayAuthorisationResultService { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayAuthorisationResultService.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayAuthorisationResultService.class); /** * {@inheritDoc} @@ -36,7 +37,7 @@ public void setAuthoriseResultByTransactionStatus(final AbstractResult target, f switch (status) { case ERROR: // Default Error response - LOG.warn("Error Response from worldpay for transaction: " + orderCode); + LOG.warn("Error Response from worldpay for transaction: {}", orderCode); setSubscriptionAuthoriseResult(target, ERROR, GENERAL_SYSTEM_ERROR); break; case AUTHORISED: @@ -44,7 +45,7 @@ public void setAuthoriseResultByTransactionStatus(final AbstractResult target, f setSubscriptionAuthoriseResult(target, ACCEPTED, SUCCESFULL); break; default: - LOG.debug(status + " Response from worldpay for transaction: " + orderCode); + LOG.debug("{} Response from worldpay for transaction: {}", status, orderCode); setSubscriptionAuthoriseResult(target, REJECTED, UNKNOWN_CODE); break; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/DefaultWorldpayUrlService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/DefaultWorldpayUrlService.java index 6a995e9e..0f281a03 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/DefaultWorldpayUrlService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/impl/DefaultWorldpayUrlService.java @@ -1,11 +1,11 @@ package com.worldpay.service.impl; import com.worldpay.exception.WorldpayConfigurationException; +import com.worldpay.model.WorldpayThreeDS2JsonWebTokenConfigurationModel; import com.worldpay.service.WorldpayUrlService; import de.hybris.platform.acceleratorservices.urlresolver.SiteBaseUrlResolutionService; import de.hybris.platform.basecommerce.model.site.BaseSiteModel; import de.hybris.platform.site.BaseSiteService; -import org.springframework.beans.factory.annotation.Required; /** * Default implementation of the {@link WorldpayUrlService} @@ -17,8 +17,15 @@ public class DefaultWorldpayUrlService extends AbstractWorldpayUrlService { private static final String EMPTY_STRING = ""; - private BaseSiteService baseSiteService; - private SiteBaseUrlResolutionService siteBaseUrlResolutionService; + + protected final BaseSiteService baseSiteService; + protected final SiteBaseUrlResolutionService siteBaseUrlResolutionService; + + public DefaultWorldpayUrlService(final BaseSiteService baseSiteService, + final SiteBaseUrlResolutionService siteBaseUrlResolutionService) { + this.baseSiteService = baseSiteService; + this.siteBaseUrlResolutionService = siteBaseUrlResolutionService; + } @Override public String getWebsiteUrlForCurrentSite() { @@ -33,7 +40,7 @@ public String getWebsiteUrlForCurrentSite() { * @return a full URL including HTTP protocol, server, port, path etc. */ protected String getFullUrl(final String url, final boolean isSecure) throws WorldpayConfigurationException { - final BaseSiteModel currentBaseSite = getBaseSiteService().getCurrentBaseSite(); + final BaseSiteModel currentBaseSite = baseSiteService.getCurrentBaseSite(); final String fullResponseUrl = siteBaseUrlResolutionService.getWebsiteUrlForSite(currentBaseSite, isSecure, url); if (fullResponseUrl == null) { @@ -124,26 +131,16 @@ public String getKlarnaConfirmationURL() throws WorldpayConfigurationException { @Override public String getFullThreeDSecureFlexFlowReturnUrl() throws WorldpayConfigurationException { - return getFullUrl(getThreeDSecureFlexFlowReturnUrl(), true); + return getFullUrl(getThreeDS2Configuration().getFlowReturnUrl(), true); } @Override public String getFullThreeDSecureFlexAutosubmitUrl() throws WorldpayConfigurationException { - return getFullUrl(getThreeDSecureFlexAuthSubmit(), true); - } - - public BaseSiteService getBaseSiteService() { - return baseSiteService; + return getFullUrl(getThreeDS2Configuration().getAuthSubmit(), true); } - @Required - public void setBaseSiteService(final BaseSiteService baseSiteService) { - this.baseSiteService = baseSiteService; - } - - @Required - public void setSiteBaseUrlResolutionService(final SiteBaseUrlResolutionService siteBaseUrlResolutionService) { - this.siteBaseUrlResolutionService = siteBaseUrlResolutionService; + @Override + public WorldpayThreeDS2JsonWebTokenConfigurationModel getThreeDS2Configuration() { + return baseSiteService.getCurrentBaseSite().getWebMerchantConfiguration().getThreeDSFlexJsonWebTokenSettings(); } - } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/mac/MacValidator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/mac/MacValidator.java index e3ef76a9..fd7fb603 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/mac/MacValidator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/mac/MacValidator.java @@ -2,7 +2,7 @@ import com.worldpay.enums.order.AuthorisedStatus; import com.worldpay.exception.WorldpayMacValidationException; -import com.worldpay.service.model.RedirectReference; +import com.worldpay.data.RedirectReference; /** * Class to validate of a mac code. diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/AccountTransaction.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/AccountTransaction.java deleted file mode 100644 index 7c45bc0b..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/AccountTransaction.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; - -/** - * POJO representation of an AccountTx returned in a notification message - */ -public class AccountTransaction implements Serializable { - - private String accountType; - private String batchId; - private Amount amount; - - public String getAccountType() { - return accountType; - } - - public void setAccountType(String accountType) { - this.accountType = accountType; - } - - public String getBatchId() { - return batchId; - } - - public void setBatchId(String batchId) { - this.batchId = batchId; - } - - public Amount getAmount() { - return amount; - } - - public void setAmount(Amount amount) { - this.amount = amount; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AccountTransaction [accountType=" + accountType + ", batchId=" + batchId + ", amount=" + amount + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Address.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Address.java deleted file mode 100644 index 60ce70bf..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Address.java +++ /dev/null @@ -1,246 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.*; -import com.worldpay.service.request.transform.InternalModelTransformer; -import org.apache.commons.lang.StringUtils; - -import java.io.Serializable; -import java.util.List; - -/** - * POJO representation of an address - */ -public class Address implements InternalModelTransformer, Serializable { - - private String firstName; - private String lastName; - private String street; - private String houseName; - private String houseNumber; - private String houseNumberExtension; - private String address1; - private String address2; - private String address3; - private String postalCode; - private String city; - private String state; - private String countryCode; - private String telephoneNumber; - - /** - * Empty constructor to allow Address to be created - */ - public Address() { - } - - /** - * Constructor with full list of fields - * - * @param firstName - * @param lastName - * @param address1 - * @param address2 - * @param address3 - * @param postalCode - * @param city - * @param countryCode - */ - public Address(final String firstName, final String lastName, final String address1, final String address2, final String address3, final String postalCode, final String city, final String countryCode) { - this.firstName = firstName; - this.lastName = lastName; - this.address1 = address1; - this.address2 = address2; - this.address3 = address3; - this.postalCode = postalCode; - this.city = city; - this.countryCode = countryCode; - } - - @Override - public InternalModelObject transformToInternalModel() { - final com.worldpay.internal.model.Address intAddress = new com.worldpay.internal.model.Address(); - - intAddress.setFirstName(firstName); - intAddress.setLastName(lastName); - intAddress.setPostalCode(postalCode); - intAddress.setCity(city); - intAddress.setState(state); - intAddress.setCountryCode(countryCode); - - List addressDetails = intAddress.getStreetOrHouseNameOrHouseNumberOrHouseNumberExtensionOrAddress1OrAddress2OrAddress3(); - if (street != null) { - final Street intStreet = new Street(); - intStreet.setvalue(street); - addressDetails.add(intStreet); - } - if (houseName != null) { - final HouseName intHouseName = new HouseName(); - intHouseName.setvalue(houseName); - addressDetails.add(intHouseName); - } - if (houseNumber != null) { - final HouseNumber intHouseNumber = new HouseNumber(); - intHouseNumber.setvalue(houseNumber); - addressDetails.add(intHouseNumber); - } - if (houseNumberExtension != null) { - final HouseNumberExtension intHouseNumberExt = new HouseNumberExtension(); - intHouseNumberExt.setvalue(houseNumberExtension); - addressDetails.add(intHouseNumberExt); - } - if (address1 != null) { - final Address1 intAddress1 = new Address1(); - intAddress1.setvalue(address1); - addressDetails.add(intAddress1); - } - if (address2 != null) { - final Address2 intAddress2 = new Address2(); - intAddress2.setvalue(address2); - addressDetails.add(intAddress2); - } - if (address3 != null) { - final Address3 intAddress3 = new Address3(); - intAddress3.setvalue(address3); - addressDetails.add(intAddress3); - } - - if (StringUtils.isNotBlank(telephoneNumber)) { - intAddress.setTelephoneNumber(telephoneNumber); - } - - return intAddress; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(final String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(final String lastName) { - this.lastName = lastName; - } - - public String getStreet() { - return street; - } - - public void setStreet(final String street) { - this.street = street; - } - - public String getHouseName() { - return houseName; - } - - public void setHouseName(final String houseName) { - this.houseName = houseName; - } - - public String getHouseNumberExtension() { - return houseNumberExtension; - } - - public void setHouseNumberExtension(final String houseNumberExtension) { - this.houseNumberExtension = houseNumberExtension; - } - - public String getAddress1() { - return address1; - } - - public void setAddress1(final String address1) { - this.address1 = address1; - } - - public String getAddress2() { - return address2; - } - - public void setAddress2(final String address2) { - this.address2 = address2; - } - - public String getAddress3() { - return address3; - } - - public void setAddress3(final String address3) { - this.address3 = address3; - } - - public String getPostalCode() { - return postalCode; - } - - public void setPostalCode(final String postalCode) { - this.postalCode = postalCode; - } - - public String getCity() { - return city; - } - - public void setCity(final String city) { - this.city = city; - } - - public String getState() { - return state; - } - - public void setState(final String state) { - this.state = state; - } - - public String getCountryCode() { - return countryCode; - } - - public void setCountryCode(final String countryCode) { - this.countryCode = countryCode; - } - - public String getTelephoneNumber() { - return telephoneNumber; - } - - public void setTelephoneNumber(final String telephoneNumber) { - this.telephoneNumber = telephoneNumber; - } - - public String getHouseNumber() { - return houseNumber; - } - - public void setHouseNumber(final String houseNumber) { - this.houseNumber = houseNumber; - } - - @Override - public String toString() { - return "Address{" + - "firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", street='" + street + '\'' + - ", houseName='" + houseName + '\'' + - ", houseNumber='" + houseNumber + '\'' + - ", houseNumberExtension='" + houseNumberExtension + '\'' + - ", address1='" + address1 + '\'' + - ", address2='" + address2 + '\'' + - ", address3='" + address3 + '\'' + - ", postalCode='" + postalCode + '\'' + - ", city='" + city + '\'' + - ", state='" + state + '\'' + - ", countryCode='" + countryCode + '\'' + - ", telephoneNumber='" + telephoneNumber + '\'' + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Amount.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Amount.java deleted file mode 100644 index 9d43f0d6..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Amount.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.worldpay.service.model; - - -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -/** - * POJO representation of an amount - */ -public class Amount implements InternalModelTransformer, Serializable { - - private String value; - private String currencyCode; - private String exponent; - private DebitCreditIndicator debitCreditIndicator; - - /** - * Constructor assumes that the debit credit indicator is CREDIT - * - * @param value - * @param currencyCode - * @param exponent - */ - public Amount(String value, String currencyCode, String exponent) { - this.value = value; - this.currencyCode = currencyCode; - this.exponent = exponent; - this.debitCreditIndicator = DebitCreditIndicator.CREDIT; - } - - /** - * Constructor with full list of fields - * - * @param value - * @param currencyCode - * @param exponent - * @param debitCreditIndicator - */ - public Amount(String value, String currencyCode, String exponent, DebitCreditIndicator debitCreditIndicator) { - this.value = value; - this.currencyCode = currencyCode; - this.exponent = exponent; - this.debitCreditIndicator = debitCreditIndicator; - } - - @Override - public com.worldpay.internal.model.Amount transformToInternalModel() { - final var intAmount = new com.worldpay.internal.model.Amount(); - intAmount.setValue(value); - intAmount.setCurrencyCode(currencyCode); - intAmount.setExponent(exponent); - - if (debitCreditIndicator != null) { - intAmount.setDebitCreditIndicator(debitCreditIndicator.getCode()); - } - return intAmount; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public String getCurrencyCode() { - return currencyCode; - } - - public void setCurrencyCode(String currencyCode) { - this.currencyCode = currencyCode; - } - - public String getExponent() { - return exponent; - } - - public void setExponent(String exponent) { - this.exponent = exponent; - } - - public DebitCreditIndicator getDebitCreditIndicator() { - return debitCreditIndicator; - } - - public void setDebitCreditIndicator(DebitCreditIndicator debitCreditIndicator) { - this.debitCreditIndicator = debitCreditIndicator; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "Amount [value=" + value + ", currencyCode=" + currencyCode + ", exponent=" + exponent + ", debitCreditIndicator=" + debitCreditIndicator + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/BasicOrderInfo.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/BasicOrderInfo.java deleted file mode 100644 index f15eee7a..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/BasicOrderInfo.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; - -/** - * POJO representation of the basic order information - */ -public class BasicOrderInfo implements Serializable { - - private String orderCode; - private String description; - private Amount amount; - - - /** - * Constructor with full list of fields - * - * @param orderCode - * @param description - * @param amount - */ - public BasicOrderInfo(String orderCode, String description, Amount amount) { - this.orderCode = orderCode; - this.description = description; - this.amount = amount; - } - - public String getOrderCode() { - return orderCode; - } - - public void setOrderCode(String orderCode) { - this.orderCode = orderCode; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Amount getAmount() { - return amount; - } - - public void setAmount(Amount amount) { - this.amount = amount; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "BasicOrderInfo [orderCode=" + orderCode + ", description=" + description + ", amount=" + amount + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Browser.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Browser.java deleted file mode 100644 index 01b53d3c..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Browser.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -/** - * POJO representation of the browser details - */ -public class Browser implements InternalModelTransformer, Serializable { - - private String acceptHeader; - private String userAgentHeader; - private String deviceType; - private String deviceOS; - private String httpAcceptLanguage; - private String httpReferer; - - /** - * Constructor with full list of fields - * - * @param acceptHeader - * @param userAgentHeader - * @param deviceType - * @param deviceOs - */ - public Browser(String acceptHeader, String userAgentHeader, String deviceType, final String deviceOs, final String httpAcceptLanguage, final String httpReferer) { - this.deviceType = deviceType; - this.acceptHeader = acceptHeader; - this.userAgentHeader = userAgentHeader; - this.deviceOS = deviceOs; - this.httpAcceptLanguage = httpAcceptLanguage; - this.httpReferer = httpReferer; - } - - public Browser(String acceptHeader, String userAgentHeader, String deviceType) { - this.deviceType = deviceType; - this.acceptHeader = acceptHeader; - this.userAgentHeader = userAgentHeader; - } - - @Override - public InternalModelObject transformToInternalModel() throws WorldpayModelTransformationException { - com.worldpay.internal.model.Browser intBrowser = new com.worldpay.internal.model.Browser(); - - intBrowser.setAcceptHeader(acceptHeader); - intBrowser.setUserAgentHeader(userAgentHeader); - intBrowser.setDeviceType(deviceType); - intBrowser.setDeviceOS(deviceOS); - intBrowser.setHttpAcceptLanguage(httpAcceptLanguage); - intBrowser.setHttpReferer(httpReferer); - - return intBrowser; - } - - public String getAcceptHeader() { - return acceptHeader; - } - - public void setAcceptHeader(String acceptHeader) { - this.acceptHeader = acceptHeader; - } - - public String getUserAgentHeader() { - return userAgentHeader; - } - - public void setUserAgentHeader(String userAgentHeader) { - this.userAgentHeader = userAgentHeader; - } - - public String getDeviceType() { - return deviceType; - } - - public void setDeviceType(String deviceType) { - this.deviceType = deviceType; - } - - public String getDeviceOS() { - return deviceOS; - } - - public void setDeviceOS(String deviceOS) { - this.deviceOS = deviceOS; - } - - public String getHttpAcceptLanguage() { - return httpAcceptLanguage; - } - - public void setHttpAcceptLanguage(String httpAcceptLanguage) { - this.httpAcceptLanguage = httpAcceptLanguage; - } - - public String getHttpReferer() { - return httpReferer; - } - - public void setHttpReferer(String httpReferer) { - this.httpReferer = httpReferer; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "Browser [acceptHeader=" + acceptHeader + ", userAgentHeader=" + userAgentHeader + ", deviceType=" + deviceType + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Date.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Date.java deleted file mode 100644 index 72bfe111..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Date.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.time.LocalDateTime; - -/** - * POJO representation of a date - */ -public class Date implements InternalModelTransformer, Serializable { - - private String dayOfMonth; - private String month; - private String year; - private String hour; - private String minute; - private String second; - - /** - * Constructor that takes a standard java util LocalDateTime object and turns it into a date pojo - * - * @param localDateTime - */ - public Date(final LocalDateTime localDateTime) { - this.dayOfMonth = String.valueOf(localDateTime.getDayOfMonth()); - this.month = String.valueOf(localDateTime.getMonth().getValue()); - this.year = String.valueOf(localDateTime.getYear()); - this.hour = String.valueOf(localDateTime.getHour()); - this.minute = String.valueOf(localDateTime.getMinute()); - this.second = String.valueOf(localDateTime.getSecond()); - } - - /** - * Constructor with full list of fields - * - * @param dayOfMonth - * @param month - * @param year - * @param hour - * @param minute - * @param second - */ - public Date(final String dayOfMonth, final String month, final String year, final String hour, final String minute, final String second) { - this.dayOfMonth = dayOfMonth; - this.month = month; - this.year = year; - this.hour = hour; - this.minute = minute; - this.second = second; - } - - /** - * Constructor with just month and year for expiry date type fields - * - * @param month - * @param year - */ - public Date(final String month, final String year) { - this.dayOfMonth = null; - this.month = month; - this.year = year; - this.hour = null; - this.minute = null; - this.second = null; - } - - @Override - public com.worldpay.internal.model.Date transformToInternalModel() { - com.worldpay.internal.model.Date intDate = new com.worldpay.internal.model.Date(); - intDate.setDayOfMonth(dayOfMonth); - intDate.setHour(hour); - intDate.setMinute(minute); - intDate.setMonth(month); - intDate.setSecond(second); - intDate.setYear(year); - return intDate; - } - - public String getDayOfMonth() { - return dayOfMonth; - } - - public void setDayOfMonth(String dayOfMonth) { - this.dayOfMonth = dayOfMonth; - } - - public String getMonth() { - return month; - } - - public void setMonth(String month) { - this.month = month; - } - - public String getYear() { - return year; - } - - public void setYear(String year) { - this.year = year; - } - - public String getHour() { - return hour; - } - - public void setHour(String hour) { - this.hour = hour; - } - - public String getMinute() { - return minute; - } - - public void setMinute(String minute) { - this.minute = minute; - } - - public String getSecond() { - return second; - } - - public void setSecond(String second) { - this.second = second; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "Date [dayOfMonth=" + dayOfMonth + ", month=" + month + ", year=" + year + ", hour=" + hour + ", minute=" + minute + ", second=" + second + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/DebitCreditIndicator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/DebitCreditIndicator.java deleted file mode 100644 index d5cc2c19..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/DebitCreditIndicator.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -/** - * Enum of the Debit/Credit status associated to an {@link Amount} - */ -public enum DebitCreditIndicator implements Serializable { - - DEBIT("debit"), - CREDIT("credit"), - ; - - private static final Map lookup = new HashMap<>(); - - static { - for (final DebitCreditIndicator code : EnumSet.allOf(DebitCreditIndicator.class)) { - lookup.put(code.getCode().toUpperCase(), code); - } - } - - protected final String code; - - DebitCreditIndicator(final String code) { - this.code = code; - } - - public String getCode() { - return code; - } - - /** - * Lookup the enum representation of a debit credit indicator code - * - * @param code to be looked up - * @return DebitCreditIndicator representation of the supplied code, or null if it can't be found - */ - public static DebitCreditIndicator getDebitCreditIndicator(final String code) { - return code == null ? null : lookup.get(code.toUpperCase()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/ErrorDetail.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/ErrorDetail.java deleted file mode 100644 index 11cb2d46..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/ErrorDetail.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; - -/** - * POJO representation of the Error details - */ -public class ErrorDetail implements Serializable { - - private String code; - private String message; - - public ErrorDetail(String code, String message) { - this.code = code; - this.message = message; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public String toString() { - return "ErrorDetail [code=" + code + ", message=" + message + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/JournalReply.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/JournalReply.java deleted file mode 100644 index 2d49acf3..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/JournalReply.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.enums.order.AuthorisedStatus; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * POJO representation of the journal returned from a notification message - */ -public class JournalReply implements Serializable { - - private AuthorisedStatus journalType; - private Date bookingDate; - private List accountTransactions; - - public AuthorisedStatus getJournalType() { - return journalType; - } - - public void setJournalType(AuthorisedStatus journalType) { - this.journalType = journalType; - } - - public Date getBookingDate() { - return bookingDate; - } - - public void setBookingDate(Date bookingDate) { - this.bookingDate = bookingDate; - } - - public List getAccountTransactions() { - return accountTransactions; - } - - public void setAccountTransactions(List accountTransactions) { - this.accountTransactions = accountTransactions; - } - - /** - * Convenience method to add an {@link AccountTransaction} to the list of account transactions - * - * @param accountTransaction the accountTransaction to add to the list - */ - public void addAccountTransaction(AccountTransaction accountTransaction) { - if (accountTransactions == null) { - accountTransactions = new ArrayList<>(); - } - accountTransactions.add(accountTransaction); - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "JournalReply [journalType=" + journalType.name() + ", bookingDate=" + bookingDate + ", accountTransactions=" + accountTransactions + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/LineItem.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/LineItem.java deleted file mode 100644 index cb2518cd..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/LineItem.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.Discount; -import com.worldpay.internal.model.Physical; -import com.worldpay.internal.model.Reference; -import com.worldpay.internal.model.ShippingFee; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -public class LineItem implements InternalModelTransformer, Serializable { - private String name; - private String quantity; - private String quantityUnit; - private String unitPrice; - private String taxRate; - private String totalAmount; - private String totalTaxAmount; - private double totalTaxAmountValue; - private String totalDiscountAmount; - private LineItemReference lineItemReference; - private LINE_ITEM_TYPE lineItemType; - - public enum LINE_ITEM_TYPE {PHYSICAL, DISCOUNT, SHIPPING_FEE} - - @Override - public InternalModelObject transformToInternalModel() throws WorldpayModelTransformationException { - final com.worldpay.internal.model.LineItem intLineItem = new com.worldpay.internal.model.LineItem(); - - intLineItem.setName(name); - intLineItem.setQuantity(quantity); - intLineItem.setQuantityUnit(quantityUnit); - intLineItem.setUnitPrice(unitPrice); - intLineItem.setTaxRate(taxRate); - intLineItem.setTotalAmount(totalAmount); - intLineItem.setTotalTaxAmount(totalTaxAmount); - intLineItem.setTotalDiscountAmount(totalDiscountAmount); - - if (lineItemReference != null) { - intLineItem.setReference((Reference) lineItemReference.transformToInternalModel()); - } - - intLineItem.getPhysicalOrDiscountOrShippingFeeOrDigitalOrGiftCardOrSalesTaxTypeOrStoreCreditOrSurcharge().add(getIntLineItemType()); - return intLineItem; - } - - private InternalModelObject getIntLineItemType() { - InternalModelObject intLineItemType = null; - switch (lineItemType) { - case DISCOUNT: - intLineItemType = new Discount(); - break; - case PHYSICAL: - intLineItemType = new Physical(); - break; - case SHIPPING_FEE: - intLineItemType = new ShippingFee(); - break; - } - return intLineItemType; - } - - public LineItemReference getLineItemReference() { - return lineItemReference; - } - - public void setLineItemReference(final LineItemReference lineItemReference) { - this.lineItemReference = lineItemReference; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getQuantity() { - return quantity; - } - - public void setQuantity(final String quantity) { - this.quantity = quantity; - } - - public String getQuantityUnit() { - return quantityUnit; - } - - public void setQuantityUnit(final String quantityUnit) { - this.quantityUnit = quantityUnit; - } - - public String getUnitPrice() { - return unitPrice; - } - - public void setUnitPrice(final String unitPrice) { - this.unitPrice = unitPrice; - } - - public String getTaxRate() { - return taxRate; - } - - public void setTaxRate(final String taxRate) { - this.taxRate = taxRate; - } - - public String getTotalAmount() { - return totalAmount; - } - - public void setTotalAmount(final String totalAmount) { - this.totalAmount = totalAmount; - } - - public String getTotalTaxAmount() { - return totalTaxAmount; - } - - public void setTotalTaxAmount(final String totalTaxAmount) { - this.totalTaxAmount = totalTaxAmount; - } - - public String getTotalDiscountAmount() { - return totalDiscountAmount; - } - - public void setTotalDiscountAmount(final String totalDiscountAmount) { - this.totalDiscountAmount = totalDiscountAmount; - } - - public LINE_ITEM_TYPE getLineItemType() { - return lineItemType; - } - - public void setLineItemType(final LINE_ITEM_TYPE lineItemType) { - this.lineItemType = lineItemType; - } - - public double getTotalTaxAmountValue() { - return totalTaxAmountValue; - } - - public void setTotalTaxAmountValue(double totalTaxAmountValue) { - this.totalTaxAmountValue = totalTaxAmountValue; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/LineItemReference.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/LineItemReference.java deleted file mode 100644 index a6213536..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/LineItemReference.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.Reference; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -public class LineItemReference implements InternalModelTransformer, Serializable { - private final String id; - private final String value; - - public LineItemReference(final String id, final String value) { - this.id = id; - this.value = value; - } - - @Override - public InternalModelObject transformToInternalModel() { - final Reference intReference = new Reference(); - intReference.setId(id); - intReference.setvalue(value); - return intReference; - } - - public String getId() { - return id; - } - - public String getValue() { - return value; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/MerchantInfo.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/MerchantInfo.java deleted file mode 100644 index 3a1d0f70..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/MerchantInfo.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; - -/** - * POJO representation of the merchant information - */ -public class MerchantInfo implements Serializable { - - private String merchantCode; - private String merchantPassword; - private boolean usingMacValidation; - private String macSecret; - - /** - * Constructor with full list of fields - * - * @param merchantCode - * @param merchantPassword - * @param usingMacValidation - * @param macSecret - */ - public MerchantInfo(String merchantCode, String merchantPassword, boolean usingMacValidation, String macSecret) { - this.merchantCode = merchantCode; - this.merchantPassword = merchantPassword; - this.usingMacValidation = usingMacValidation; - this.macSecret = macSecret; - } - - /** - * Constructor with just merchant code and password. Assumes not using mac validation - * - * @param merchantCode - * @param merchantPassword - */ - public MerchantInfo(String merchantCode, String merchantPassword) { - this.merchantCode = merchantCode; - this.merchantPassword = merchantPassword; - this.usingMacValidation = false; - } - - public String getMerchantCode() { - return merchantCode; - } - - public void setMerchantCode(String merchantCode) { - this.merchantCode = merchantCode; - } - - public String getMerchantPassword() { - return merchantPassword; - } - - public void setMerchantPassword(String merchantPassword) { - this.merchantPassword = merchantPassword; - } - - public boolean isUsingMacValidation() { - return usingMacValidation; - } - - public void setUsingMacValidation(boolean usingMacValidation) { - this.usingMacValidation = usingMacValidation; - } - - public String getMacSecret() { - return macSecret; - } - - public void setMacSecret(String macSecret) { - this.macSecret = macSecret; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "MerchantInfo [merchantCode=" + merchantCode + ", merchantPassword=" + merchantPassword + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Order.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Order.java deleted file mode 100644 index 93c7e8cd..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Order.java +++ /dev/null @@ -1,310 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.enums.order.DynamicInteractionType; -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.*; -import com.worldpay.service.model.payment.PayAsOrder; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.threeds2.RiskData; -import com.worldpay.service.model.token.TokenRequest; -import com.worldpay.service.request.transform.InternalModelTransformer; -import org.apache.commons.collections.CollectionUtils; - -import java.io.Serializable; -import java.util.List; - -/** - * POJO representation of an order - */ -@SuppressWarnings("squid:S3776") -public class Order extends BasicOrderInfo implements InternalModelTransformer, Serializable { - - private String installationId; - private String orderContent; - private PaymentMethodMask paymentMethodMask; - private PaymentDetails paymentDetails; - private PayAsOrder payAsOrder; - private Shopper shopper; - private Address shippingAddress; - private Address billingAddress; - private String statementNarrative; - private String echoData; - private TokenRequest tokenRequest; - private Session session; - private String paResponse; - private OrderLines orderLines; - private DynamicInteractionType dynamicInteractionType; - private Additional3DSData additional3DSData; - private RiskData riskData; - private List paymentMethodAttributes; - - /** - * Constructor with full list of fields - * - * @param orderCode - * @param description - * @param amount - */ - public Order(final String orderCode, final String description, final Amount amount) { - super(orderCode, description, amount); - } - - @Override - public com.worldpay.internal.model.Order transformToInternalModel() throws WorldpayModelTransformationException { - var intOrder = new com.worldpay.internal.model.Order(); - final List childElements = intOrder.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - - if (getOrderCode() != null) { - intOrder.setOrderCode(getOrderCode()); - } - - if (getDescription() != null) { - final Description intDescription = new Description(); - intDescription.setvalue(getDescription()); - childElements.add(intDescription); - } - - if (getAmount() != null) { - childElements.add(getAmount().transformToInternalModel()); - } - - if (installationId != null) { - intOrder.setInstallationId(installationId); - } - - if (orderContent != null) { - final OrderContent intOrderContent = new OrderContent(); - intOrderContent.setvalue(orderContent); - childElements.add(intOrderContent); - } - - populatePaymentRequestDetails(childElements); - - if (shopper != null) { - childElements.add(shopper.transformToInternalModel()); - } - - if (shippingAddress != null) { - final ShippingAddress intShippingAddress = new ShippingAddress(); - intShippingAddress.setAddress((com.worldpay.internal.model.Address) shippingAddress.transformToInternalModel()); - childElements.add(intShippingAddress); - } - - if (billingAddress != null) { - final BillingAddress intBillingAddress = new BillingAddress(); - intBillingAddress.setAddress((com.worldpay.internal.model.Address) billingAddress.transformToInternalModel()); - childElements.add(intBillingAddress); - } - - if (CollectionUtils.isNotEmpty(paymentMethodAttributes)) { - paymentMethodAttributes.stream() - .map(PaymentMethodAttribute::transformToInternalModel) - .forEach(childElements::add); - } - - if (statementNarrative != null) { - final StatementNarrative intStatementNarrative = new StatementNarrative(); - intStatementNarrative.setvalue(statementNarrative); - childElements.add(intStatementNarrative); - } - - if (echoData != null) { - final EchoData intEchoData = new EchoData(); - intEchoData.setvalue(echoData); - childElements.add(intEchoData); - } - - if (tokenRequest != null) { - childElements.add(tokenRequest.transformToInternalModel()); - } - - if (paResponse != null) { - final Info3DSecure intInfo3dSecure = new Info3DSecure(); - final PaResponse intPaResponse = new PaResponse(); - intPaResponse.setvalue(getPaResponse()); - intInfo3dSecure.getPaResponseOrMpiProviderOrMpiResponseOrAttemptedAuthenticationOrCompletedAuthenticationOrThreeDSVersionOrMerchantNameOrXidOrDsTransactionIdOrCavvOrEci().add(intPaResponse); - childElements.add(intInfo3dSecure); - } - - if (session != null) { - childElements.add(session.transformToInternalModel()); - } - - if (orderLines != null) { - childElements.add(orderLines.transformToInternalModel()); - } - - populateDynamicInteractionType(childElements); - - if (riskData != null) { - childElements.add(riskData.transformToInternalModel()); - } - - if (additional3DSData != null) { - childElements.add(additional3DSData.transformToInternalModel()); - } - return intOrder; - } - - private void populatePaymentRequestDetails(final List childElements) throws WorldpayModelTransformationException { - if (paymentMethodMask != null) { - childElements.add(paymentMethodMask.transformToInternalModel()); - } else if (paymentDetails != null) { - childElements.add(paymentDetails.transformToInternalModel()); - } else if (payAsOrder != null) { - childElements.add(payAsOrder.transformToInternalModel()); - } - } - - private void populateDynamicInteractionType(final List childElements) { - if (dynamicInteractionType != null) { - final var internalDynamicInteractionType = new com.worldpay.internal.model.DynamicInteractionType(); - internalDynamicInteractionType.setType(dynamicInteractionType.name()); - childElements.add(internalDynamicInteractionType); - } - } - - public String getInstallationId() { - return installationId; - } - - public void setInstallationId(final String installationId) { - this.installationId = installationId; - } - - public String getOrderContent() { - return orderContent; - } - - public void setOrderContent(final String orderContent) { - this.orderContent = orderContent; - } - - public PaymentMethodMask getPaymentMethodMask() { - return paymentMethodMask; - } - - public void setPaymentMethodMask(final PaymentMethodMask paymentMethodMask) { - this.paymentMethodMask = paymentMethodMask; - } - - public PaymentDetails getPaymentDetails() { - return paymentDetails; - } - - public void setPaymentDetails(final PaymentDetails paymentDetails) { - this.paymentDetails = paymentDetails; - } - - public PayAsOrder getPayAsOrder() { - return payAsOrder; - } - - public void setPayAsOrder(final PayAsOrder payAsOrder) { - this.payAsOrder = payAsOrder; - } - - public Shopper getShopper() { - return shopper; - } - - public void setShopper(final Shopper shopper) { - this.shopper = shopper; - } - - public Address getShippingAddress() { - return shippingAddress; - } - - public void setShippingAddress(final Address shippingAddress) { - this.shippingAddress = shippingAddress; - } - - public String getStatementNarrative() { - return statementNarrative; - } - - public void setStatementNarrative(final String statementNarrative) { - this.statementNarrative = statementNarrative; - } - - public String getEchoData() { - return echoData; - } - - public void setEchoData(final String echoData) { - this.echoData = echoData; - } - - public Address getBillingAddress() { - return billingAddress; - } - - public void setBillingAddress(final Address billingAddress) { - this.billingAddress = billingAddress; - } - - public TokenRequest getTokenRequest() { - return tokenRequest; - } - - public void setTokenRequest(final TokenRequest tokenRequest) { - this.tokenRequest = tokenRequest; - } - - public Session getSession() { - return session; - } - - public void setSession(final Session session) { - this.session = session; - } - - public String getPaResponse() { - return paResponse; - } - - public void setPaResponse(final String paResponse) { - this.paResponse = paResponse; - } - - public OrderLines getOrderLines() { - return orderLines; - } - - public void setOrderLines(final OrderLines orderLines) { - this.orderLines = orderLines; - } - - public void setDynamicInteractionType(final DynamicInteractionType dynamicInteractionType) { - this.dynamicInteractionType = dynamicInteractionType; - } - - public DynamicInteractionType getDynamicInteractionType() { - return dynamicInteractionType; - } - - public Additional3DSData getAdditional3DSData() { - return additional3DSData; - } - - public void setAdditional3DSData(final Additional3DSData additional3DSData) { - this.additional3DSData = additional3DSData; - } - - public RiskData getRiskData() { - return riskData; - } - - public void setRiskData(final RiskData riskData) { - this.riskData = riskData; - } - - public List getPaymentMethodAttributes() { - return paymentMethodAttributes; - } - - public void setPaymentMethodAttributes(List paymentMethodAttributes) { - this.paymentMethodAttributes = paymentMethodAttributes; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/OrderLines.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/OrderLines.java deleted file mode 100644 index f90dfb2e..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/OrderLines.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.service.request.transform.InternalModelTransformer; -import org.apache.log4j.Logger; - -import java.io.Serializable; -import java.util.List; - -public class OrderLines implements InternalModelTransformer, Serializable { - private static final Logger LOG = Logger.getLogger(OrderLines.class); - - private final String orderTaxAmount; - private final String termsURL; - private final List lineItems; - - public OrderLines(final String orderTaxAmount, final String termsURL, final List lineItems) { - this.orderTaxAmount = orderTaxAmount; - this.termsURL = termsURL; - this.lineItems = lineItems; - } - - @Override - public InternalModelObject transformToInternalModel() { - final com.worldpay.internal.model.OrderLines intOrderLines = new com.worldpay.internal.model.OrderLines(); - intOrderLines.setOrderTaxAmount(orderTaxAmount); - intOrderLines.setTermsURL(termsURL); - - if (lineItems != null && !lineItems.isEmpty()) { - final List intLineItems = intOrderLines.getLineItem(); - lineItems.forEach(lineItem -> { - try { - intLineItems.add((com.worldpay.internal.model.LineItem) lineItem.transformToInternalModel()); - } catch (final WorldpayModelTransformationException e) { - LOG.error("Error during transformation of line items", e); - } - }); - } - - return intOrderLines; - } - - public String getOrderTaxAmount() { - return orderTaxAmount; - } - - public String getTermsURL() { - return termsURL; - } - - public List getLineItems() { - return lineItems; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentDetails.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentDetails.java deleted file mode 100644 index d5ba1e7a..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentDetails.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.Info3DSecure; -import com.worldpay.internal.model.PaResponse; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.util.List; -import java.util.Objects; - -/** - * POJO representation of the payment details - */ -public class PaymentDetails implements InternalModelTransformer, Serializable { - - private Payment payment; - private Session session; - private String paResponse; - private StoredCredentials storedCredentials; - - /** - * Constructor with full list of fields - * - * @param payment - * @param session - * @param paResponse - */ - public PaymentDetails(Payment payment, Session session, String paResponse) { - this.payment = payment; - this.session = session; - this.paResponse = paResponse; - } - - /** - * Constructor taking payment and session objects - * - * @param payment - * @param session - */ - public PaymentDetails(Payment payment, Session session) { - this.payment = payment; - this.session = session; - } - - public PaymentDetails(final Payment payment, final Session session, final StoredCredentials storedCredentials) { - this.payment = payment; - this.session = session; - this.storedCredentials = storedCredentials; - } - - @Override - public InternalModelObject transformToInternalModel() throws WorldpayModelTransformationException { - com.worldpay.internal.model.PaymentDetails intPaymentDetails = new com.worldpay.internal.model.PaymentDetails(); - if (payment != null) { - final List paymentDtl = intPaymentDetails.getVISASSLOrECMCSSLOrBHSSSLOrNEWDAYSSLOrIKEASSLOrAMEXSSLOrELVSSLOrSEPADIRECTDEBITSSLOrDINERSSSLOrCBSSLOrAIRPLUSSSLOrUATPSSLOrCARTEBLEUESSLOrSOLOGBSSLOrLASERSSLOrDANKORTSSLOrDISCOVERSSLOrJCBSSLOrAURORESSLOrGECAPITALSSLOrHIPERCARDSSLOrSOROCREDSSLOrELOSSLOrCARNETSSLOrARGENCARDSSLOrCABALSSLOrCENCOSUDSSLOrCOOPEPLUSSSLOrCREDIMASSSLOrITALCREDSSLOrNARANJASSLOrNATIVASSLOrNEVADASSLOrNEXOSSLOrTARJETASHOPPINGSSLOrPERMANENTSIGNEDDDNLFAXOrPERMANENTSIGNEDDDGBSSLOrPERMANENTUNSIGNEDDDGBSSLOrPAYOUTBANKOrVISACHECKOUTSSLOrMASTERPASSSSLOrPAYPALEXPRESSOrGIROPAYSSLOrMAESTROSSLOrSWITCHSSLOrNCPB2BSSLOrNCPSEASONSSLOrNCPGMMSSLOrIDEALSSLOrACHSSLOrACHDIRECTDEBITSSLOrCARDSSLOrABAQOOSSSLOrAGMOSSLOrALIPAYSSLOrALIPAYMOBILESSLOrBALOTOSSLOrBANKAXESSSSLOrBANKLINKNORDEASSLOrBILLDESKSSLOrBILLINGPARTNERSSLOrCASHUSSLOrDINEROMAIL7ELEVENSSLOrDINEROMAILOXXOSSLOrDINEROMAILONLINEBTSSLOrDINEROMAILSERVIPAGSSLOrEKONTOSSLOrEPAYSSLOrEUTELLERSSLOrEWIREDKSSLOrEWIRENOSSLOrEWIRESESSLOrHALCASHSSLOrINSTADEBITSSLOrKONBINISSLOrLOBANETARSSLOrLOBANETBRSSLOrLOBANETCLSSLOrLOBANETMXSSLOrLOBANETPESSLOrLOBANETUYSSLOrMISTERCASHSSLOrMULTIBANCOSSLOrNEOSURFSSLOrPAGASSLOrPAGAVERVESSLOrPAYSAFECARDSSLOrPAYUSSLOrPLUSPAYSSLOrPOLISSLOrPOLINZSSLOrPOSTEPAYSSLOrPRZELEWYSSLOrQIWISSLOrSAFETYPAYSSLOrSIDSSLOrSKRILLSSLOrSOFORTSSLOrSOFORTCHSSLOrSPEEDCARDSSLOrSPOROPAYSSLOrSWIFFSSLOrTELEINGRESOSSLOrTICKETSURFSSLOrTRUSTLYSSLOrTRUSTPAYCZSSLOrTRUSTPAYEESSLOrTRUSTPAYSKSSLOrWEBMONEYSSLOrYANDEXMONEYSSLOrASTROPAYCARDSSLOrBANCOSANTANDERSSLOrBOLETOSSLOrBOLETOHTMLOrMONETASSLOrTODITOCARDSSLOrONLINETRANSFERBRSSLOrONLINETRANSFERMYSSLOrONLINETRANSFERTHSSLOrONLINETRANSFERVNSSLOrOPENBANKINGSSLOrSEVENELEVENMYSSLOrPETRONASSSLOrENETSSGSSLOrCASHTHSSLOrATMIDSSLOrTOKENSSLOrENETSSSLOrCHINAUNIONPAYSSLOrENVOYTRANSFERAUDBANKOrENVOYTRANSFERCADBANKOrENVOYTRANSFERCHFBANKOrENVOYTRANSFERCZKBANKOrENVOYTRANSFERDKKBANKOrENVOYTRANSFEREURBANKOrENVOYTRANSFERGBPBANKOrENVOYTRANSFERHKDBANKOrENVOYTRANSFERHUFBANKOrENVOYTRANSFERJPYBANKOrENVOYTRANSFERNOKBANKOrENVOYTRANSFERNZDBANKOrENVOYTRANSFERPLNBANKOrENVOYTRANSFERRUBBANKOrENVOYTRANSFERSEKBANKOrENVOYTRANSFERSGDBANKOrENVOYTRANSFERTHBBANKOrENVOYTRANSFERTRYBANKOrENVOYTRANSFERUSDBANKOrENVOYTRANSFERZARBANKOrTRANSFERATBANKOrTRANSFERBEBANKOrTRANSFERCHBANKOrTRANSFERDEBANKOrTRANSFERDKBANKOrTRANSFERESBANKOrTRANSFERFIBANKOrTRANSFERFRBANKOrTRANSFERGBBANKOrTRANSFERGRBANKOrTRANSFERITBANKOrTRANSFERJPBANKOrTRANSFERLUBANKOrTRANSFERNLBANKOrTRANSFERNOBANKOrTRANSFERPLBANKOrTRANSFERSEBANKOrTRANSFERUSBANKOrEMVCOTOKENSSLOrAPPLEPAYSSLOrANDROIDPAYSSLOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrKLARNASSLOrKLARNAPAYLATERSSLOrKLARNAPAYNOWSSLOrKLARNASLICEITSSLOrKLARNAV2SSLOrWECHATPAYSSLOrBILLKEYSSLOrINIPAYSSLOrWEBPAYSSLOrPBBASSLOrGPPSSLOrMERCADOPAGOSSLOrPAYPALSSLOrSVSGIFTCARDSSLOrTROYSSLOrUPISSLOrUPEXSSLOrFFDISBURSESSLOrFFMONEYTRANSFERSSLOrEPSENVSSLOrCardNumberOrExpiryDateOrCardHolderNameOrCvcOrIssueNumberOrStartDateOrPOSRequestOrCardSwipeOrCSEDATA(); - - InternalModelObject internalPayment = payment.transformToInternalModel(); - paymentDtl.add(internalPayment); - } - if (session != null) { - intPaymentDetails.setSession((com.worldpay.internal.model.Session) session.transformToInternalModel()); - } - if (getPaResponse() != null) { - Info3DSecure intInfo3dSecure = new Info3DSecure(); - PaResponse intPaResponse = new PaResponse(); - intPaResponse.setvalue(getPaResponse()); - intInfo3dSecure.getPaResponseOrMpiProviderOrMpiResponseOrAttemptedAuthenticationOrCompletedAuthenticationOrThreeDSVersionOrMerchantNameOrXidOrDsTransactionIdOrCavvOrEci().add(intPaResponse); - intPaymentDetails.setInfo3DSecure(intInfo3dSecure); - } - - if (Objects.nonNull(getStoredCredentials())) { - final com.worldpay.internal.model.StoredCredentials intStoredCredentials = getStoredCredentials().transformToInternalModel(); - intPaymentDetails.setStoredCredentials(intStoredCredentials); - } - return intPaymentDetails; - } - - public Payment getPayment() { - return payment; - } - - public void setPayment(Payment payment) { - this.payment = payment; - } - - public Session getSession() { - return session; - } - - public void setSession(Session session) { - this.session = session; - } - - public String getPaResponse() { - return paResponse; - } - - public void setPaResponse(String paResponse) { - this.paResponse = paResponse; - } - - - public StoredCredentials getStoredCredentials() { - return storedCredentials; - } - - public void setStoredCredentials(final StoredCredentials storedCredentials) { - this.storedCredentials = storedCredentials; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "PaymentDetails{" + - "payment=" + payment + - ", session=" + session + - ", paResponse='" + paResponse + '\'' + - ", storedCredentials=" + storedCredentials + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentMethodAttribute.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentMethodAttribute.java deleted file mode 100644 index 81f4a961..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentMethodAttribute.java +++ /dev/null @@ -1,59 +0,0 @@ - -package com.worldpay.service.model; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -public class PaymentMethodAttribute implements InternalModelTransformer, Serializable { - - private String paymentMethod; - - private String attrName; - - private String attrValue; - - @Override - public InternalModelObject transformToInternalModel() { - final com.worldpay.internal.model.PaymentMethodAttribute intPaymentMethodAttribute = new com.worldpay.internal.model.PaymentMethodAttribute(); - intPaymentMethodAttribute.setAttrName(this.attrName); - intPaymentMethodAttribute.setAttrValue(this.attrValue); - intPaymentMethodAttribute.setPaymentMethod(this.paymentMethod); - return intPaymentMethodAttribute; - } - - - public void setPaymentMethod(final String paymentMethod) { - this.paymentMethod = paymentMethod; - } - - public String getPaymentMethod() { - return paymentMethod; - } - - public void setAttrName(final String attrName) { - this.attrName = attrName; - } - - public String getAttrName() { - return attrName; - } - - public void setAttrValue(final String attrValue) { - this.attrValue = attrValue; - } - - public String getAttrValue() { - return attrValue; - } - - @Override - public String toString() { - return "PaymentMethodAttribute{" + - "paymentMethod='" + paymentMethod + '\'' + - ", attrName='" + attrName + '\'' + - ", attrValue='" + attrValue + '\'' + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentMethodMask.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentMethodMask.java deleted file mode 100644 index c94aac1b..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentMethodMask.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.Exclude; -import com.worldpay.internal.model.Include; -import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.request.transform.InternalModelTransformer; -import org.apache.commons.collections4.CollectionUtils; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/** - * POJO representation of the payment method mask - */ -public class PaymentMethodMask implements InternalModelTransformer, Serializable { - - private List includes; - private List excludes; - private StoredCredentials storedCredentials; - - public PaymentMethodMask() { - } - - /** - * Constructor with full list of fields - * - * @param includes - * @param excludes - */ - public PaymentMethodMask(final List includes, final List excludes, final StoredCredentials storedCredentials) { - this.includes = includes; - this.excludes = excludes; - this.storedCredentials = storedCredentials; - } - - @Override - public InternalModelObject transformToInternalModel() { - final com.worldpay.internal.model.PaymentMethodMask intPaymentMethodMask = new com.worldpay.internal.model.PaymentMethodMask(); - final List includeOrExclude = intPaymentMethodMask.getStoredCredentialsOrIncludeOrExclude(); - - Optional.ofNullable(storedCredentials) - .map(StoredCredentials::transformToInternalModel) - .ifPresent(includeOrExclude::add); - - CollectionUtils.emptyIfNull(excludes).stream() - .map(PaymentType::getMethodCode) - .map(this::createIntExclude) - .forEach(includeOrExclude::add); - - CollectionUtils.emptyIfNull(includes).stream() - .map(PaymentType::getMethodCode) - .map(this::createIntInclude) - .forEach(includeOrExclude::add); - - return intPaymentMethodMask; - } - - /** - * Add an item to the list of payment methods that are included - * - * @param paymentType PaymentType to be included - */ - public void addInclude(PaymentType paymentType) { - if (includes == null) { - includes = new ArrayList<>(); - } - includes.add(paymentType); - } - - /** - * Add an item to the list of payment methods that are excluded - * - * @param paymentType PaymentType to be excluded - */ - public void addExclude(PaymentType paymentType) { - if (excludes == null) { - excludes = new ArrayList<>(); - } - excludes.add(paymentType); - } - - public List getIncludes() { - return includes; - } - - public void setIncludes(List includes) { - this.includes = includes; - } - - public List getExcludes() { - return excludes; - } - - public void setExcludes(List excludes) { - this.excludes = excludes; - } - - public StoredCredentials getStoredCredentials() { - return storedCredentials; - } - - public void setStoredCredentials(final StoredCredentials storedCredentials) { - this.storedCredentials = storedCredentials; - } - - protected Exclude createIntExclude(final String methodCode) { - final Exclude intExclude = new Exclude(); - intExclude.setCode(methodCode); - return intExclude; - } - - protected Include createIntInclude(final String methodCode) { - final Include intInclude = new Include(); - intInclude.setCode(methodCode); - return intInclude; - } - - @Override - public String toString() { - return "PaymentMethodMask{" + - "includes=" + includes + - ", excludes=" + excludes + - ", storedCredentials=" + storedCredentials + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentReply.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentReply.java deleted file mode 100644 index d8b60cfd..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/PaymentReply.java +++ /dev/null @@ -1,229 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.enums.order.AuthorisedStatus; -import com.worldpay.service.model.payment.Card; - -import java.io.Serializable; - -/** - * POJO representation of the payment returned in a reply message - */ -public class PaymentReply implements Serializable { - - private String paymentMethodCode; - private Amount amount; - private AuthorisedStatus authStatus; - private String cvcResultDescription; - private String balanceAccountType; - private Amount balanceAmount; - private String cardNumber; - private String returnCode; - private RiskScore riskScore; - private String cardHolderName; - private Card cardDetails; - private String aavAddressResultCode; - private String aavCardholderNameResultCode; - private String aavEmailResultCode; - private String aavPostcodeResultCode; - private String aavTelephoneResultCode; - private String refundReference; - private String authorisationId; - private String authorisedBy; - private String threeDSecureResultDescription; - private SchemeResponse schemeResponse; - - public Card getCardDetails() { - return cardDetails; - } - - public void setCardDetails(final Card cardDetails) { - this.cardDetails = cardDetails; - } - - public String getCardHolderName() { - return cardHolderName; - } - - public void setCardHolderName(String cardHolderName) { - this.cardHolderName = cardHolderName; - } - - public String getPaymentMethodCode() { - return paymentMethodCode; - } - - public void setPaymentMethodCode(String paymentMethodCode) { - this.paymentMethodCode = paymentMethodCode; - } - - public Amount getAmount() { - return amount; - } - - public void setAmount(Amount amount) { - this.amount = amount; - } - - public AuthorisedStatus getAuthStatus() { - return authStatus; - } - - public void setAuthStatus(AuthorisedStatus authStatus) { - this.authStatus = authStatus; - } - - public String getCvcResultDescription() { - return cvcResultDescription; - } - - public void setCvcResultDescription(String cvcResultDescription) { - this.cvcResultDescription = cvcResultDescription; - } - - public String getBalanceAccountType() { - return balanceAccountType; - } - - public void setBalanceAccountType(String balanceAccountType) { - this.balanceAccountType = balanceAccountType; - } - - public Amount getBalanceAmount() { - return balanceAmount; - } - - public void setBalanceAmount(Amount balanceAmount) { - this.balanceAmount = balanceAmount; - } - - public String getCardNumber() { - return cardNumber; - } - - public void setCardNumber(String cardNumber) { - this.cardNumber = cardNumber; - } - - public String getReturnCode() { - return returnCode; - } - - public void setReturnCode(String returnCode) { - this.returnCode = returnCode; - } - - public RiskScore getRiskScore() { - return riskScore; - } - - public void setRiskScore(RiskScore riskScore) { - this.riskScore = riskScore; - } - - public String getAavAddressResultCode() { - return aavAddressResultCode; - } - - public void setAavAddressResultCode(final String aavAddressResultCode) { - this.aavAddressResultCode = aavAddressResultCode; - } - - public String getAavCardholderNameResultCode() { - return aavCardholderNameResultCode; - } - - public void setAavCardholderNameResultCode(final String aavCardholderNameResultCode) { - this.aavCardholderNameResultCode = aavCardholderNameResultCode; - } - - public String getAavEmailResultCode() { - return aavEmailResultCode; - } - - public void setAavEmailResultCode(final String aavEmailResultCode) { - this.aavEmailResultCode = aavEmailResultCode; - } - - public String getAavPostcodeResultCode() { - return aavPostcodeResultCode; - } - - public void setAavPostcodeResultCode(final String aavPostcodeResultCode) { - this.aavPostcodeResultCode = aavPostcodeResultCode; - } - - public String getAavTelephoneResultCode() { - return aavTelephoneResultCode; - } - - public void setAavTelephoneResultCode(final String aavTelephoneResultCode) { - this.aavTelephoneResultCode = aavTelephoneResultCode; - } - - public String getRefundReference() { - return refundReference; - } - - public void setRefundReference(final String refundReference) { - this.refundReference = refundReference; - } - - public String getAuthorisationId() { - return authorisationId; - } - - public void setAuthorisationId(String authorisationId) { - this.authorisationId = authorisationId; - } - - public String getThreeDSecureResultDescription() { - return threeDSecureResultDescription; - } - - public void setThreeDSecureResultDescription(final String threeDSecureResultDescription) { - this.threeDSecureResultDescription = threeDSecureResultDescription; - } - - public String getAuthorisedBy() { - return authorisedBy; - } - - public void setAuthorisedBy(String authorisedBy) { - this.authorisedBy = authorisedBy; - } - - public SchemeResponse getSchemeResponse() { - return schemeResponse; - } - - public void setSchemeResponse(final SchemeResponse schemeResponse) { - this.schemeResponse = schemeResponse; - } - - @Override - public String toString() { - return "PaymentReply{" + - "methodCode='" + paymentMethodCode + '\'' + - ", amount=" + amount + - ", authStatus=" + authStatus + - ", cvcResultDescription='" + cvcResultDescription + '\'' + - ", balanceAccountType='" + balanceAccountType + '\'' + - ", balanceAmount=" + balanceAmount + - ", cardNumber='" + cardNumber + '\'' + - ", returnCode='" + returnCode + '\'' + - ", riskScore=" + riskScore + - ", cardHolderName='" + cardHolderName + '\'' + - ", cardDetails=" + cardDetails + - ", aavAddressResultCode='" + aavAddressResultCode + '\'' + - ", aavCardholderNameResultCode='" + aavCardholderNameResultCode + '\'' + - ", aavEmailResultCode='" + aavEmailResultCode + '\'' + - ", aavPostcodeResultCode='" + aavPostcodeResultCode + '\'' + - ", aavTelephoneResultCode='" + aavTelephoneResultCode + '\'' + - ", refundReference='" + refundReference + '\'' + - ", authorisationId='" + authorisationId + '\'' + - ", authorisedBy='" + authorisedBy + '\'' + - ", threeDSecureResultDescription='" + threeDSecureResultDescription + '\'' + - ", schemeResponse=" + schemeResponse + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/RedirectReference.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/RedirectReference.java deleted file mode 100644 index 96b67499..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/RedirectReference.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; - -/** - * POJO representation of the reference returned as a result of a redirect authorise - * - */ -public class RedirectReference implements Serializable { - - private String id; - private String value; - - /** - * Constructor with full list of fields - * - * @param id id of the reference sent by Worldpay - * @param value this property can be a URL or a Base64-encoded HTML content. - */ - public RedirectReference(String id, String value) { - this.id = id; - this.value = value; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getValue() { - return value; - } - - public void setValue(final String value) { - this.value = value; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "RedirectReference [id=" + id + ", value=" + value + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Request3DInfo.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Request3DInfo.java deleted file mode 100644 index 706613e3..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Request3DInfo.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; - -/** - * POJO representation of the request 3D info - */ -public class Request3DInfo implements Serializable { - - private String paRequest; - private String issuerUrl; - private String transactionId3DS; - private String major3DSVersion; - private String issuerPayload; - - public Request3DInfo() { - } - - /** - * Constructor for legacy flow - * @param paRequest - * @param issuerUrl - */ - public Request3DInfo(final String paRequest, final String issuerUrl) { - this.paRequest = paRequest; - this.issuerUrl = issuerUrl; - } - - /** - * Constructor for 3ds Flex flow - * - * @param issuerUrl - * @param transactionId3DS - * @param major3DSVersion - * @param issuerPayload - */ - public Request3DInfo(final String issuerUrl, final String transactionId3DS, final String major3DSVersion, final String issuerPayload) { - this.issuerUrl = issuerUrl; - this.transactionId3DS = transactionId3DS; - this.major3DSVersion = major3DSVersion; - this.issuerPayload = issuerPayload; - } - - public String getPaRequest() { - return paRequest; - } - - public void setPaRequest(final String paRequest) { - this.paRequest = paRequest; - } - - public String getIssuerUrl() { - return issuerUrl; - } - - public void setIssuerUrl(final String issuerUrl) { - this.issuerUrl = issuerUrl; - } - - public String getTransactionId3DS() { - return transactionId3DS; - } - - public void setTransactionId3DS(final String transactionId3DS) { - this.transactionId3DS = transactionId3DS; - } - - public String getMajor3DSVersion() { - return major3DSVersion; - } - - public void setMajor3DSVersion(final String major3DSVersion) { - this.major3DSVersion = major3DSVersion; - } - - - public String getIssuerPayload() { - return issuerPayload; - } - - public void setIssuerPayload(final String issuerPayload) { - this.issuerPayload = issuerPayload; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "Request3DInfo [" - + "paRequest=" + paRequest + - ", issuerUrl=" + issuerUrl + - ", transactionId3DS=" + transactionId3DS + - ", major3DSVersion=" + major3DSVersion + - ", issuerPayload=" + issuerPayload - + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/ReturnCode.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/ReturnCode.java deleted file mode 100644 index a48646db..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/ReturnCode.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -/** - * Enum representation of the ISO8583 response codes - */ -public enum ReturnCode implements Serializable { - - AUTHORISED("0", "AUTHORISED"), - REFERRED("2", "REFERRED"), - HOLD_CARD("4", "HOLD CARD"), - REFUSED("5", "REFUSED"), - APPROVE_AFTER_IDENTIFICATION("8", "APPROVE AFTER IDENTIFICATION"), - INVALID_AMOUNT("13", "INVALID AMOUNT"), - INVALID_CARD_ISSUER("15", "INVALID CARD ISSUER"), - ANNULATION_BY_CLIENT("17", "ANNULATION BY CLIENT"), - ACCESS_DENIED("28", "ACCESS DENIED"), - IMPOSSIBLE_REFERENCE_NUMBER("29", "IMPOSSIBLE REFERENCE NUMBER"), - CARD_EXPIRED("33", "CARD EXPIRED"), - FRAUD_SUSPICION("34", "FRAUD SUSPICION"), - SECURITY_CODE_EXPIRED("38", "SECURITY CODE EXPIRED"), - LOST_CARD("41", "LOST CARD"), - STOLEN("43", "STOLEN"), - REJECTED_BY_CARD_ISSUER("85", "REJECTED BY CARD ISSUER"), - CREDITCARD_ISSUER_TEMPORARILY_NOT_REACHABLE("91", "CREDITCARD ISSUER TEMPORARILY NOT REACHABLE"), - SECURITY_BREACH("97", "SECURITY BREACH"), - INVALID_ACCEPTOR("3", "INVALID ACCEPTOR"), - INVALID_TRANSACTION("12", "INVALID TRANSACTION"), - INVALID_ACCOUNT("14", "INVALID ACCOUNT"), - REPEAT_OF_LAST_TRANSACTION("19", "REPEAT OF LAST TRANSACTION"), - ACQUIRER_ERROR("20", "ACQUIRER ERROR"), - REVERSAL_NOT_PROCESSED_MISSING_AUTHORITY("21", "REVERSAL NOT PROCESSED, MISSING AUTHORISATION"), - UPDATE_OF_FILE_IMPOSSIBLE("24", "UPDATE OF FILE IMPOSSIBLE"), - REFERENCE_NUMBER_CANNOT_BE_FOUND("25", "REFERENCE NUMBER CANNOT BE FOUND"), - DUPLICATE_REEFERENCE_NUMBER("26", "DUPLICATE REFERENCE NUMBER"), - ERROR_IN_REFERENCE_NUMBER_FIELD("27", "ERROR IN REFERENCE NUMBER FIELD"), - FORMAT_ERROR("30", "FORMAT ERROR"), - UNKNOWN_ACQUIRER_ACCOUNT_CODE("31", "UNKNOWN ACQUIRER ACCOUNT CODE"), - REQUESTED_FUNCTION_NOT_SUPPORTED("40", "REQUESTED FUNCTION NOT SUPPORTED"), - TRANSACTION_NOT_PERMITTED("58", "TRANSACTION NOT PERMITTED"), - AMOUNT_HIGHER_THAN_PREVIOUS_TRANSACTION_AMOUNT("64", "AMOUNT HIGHER THAN PREVIOUS TRANSACTION AMOUNT"), - TRANSACTION_TIMED_OUT("68", "TRANSACTION TIMED OUT"), - AMOUNT_NO_LONGER_AVAILABLE_AUTHORISATION_EXPIRED("80", "AMOUNT NO LONGER AVAILABLE, AUTHORISATION EXPIRED"), - CREDITCARD_TYPE_NOT_PROCESSED_BY_ACQUIRER("92", "CREDITCARD TYPE NOT PROCESSED BY ACQUIRER"), - DUPLICATE_REQUEST_ERROR("94", "DUPLICATE REQUEST ERROR"), - ; - - private static final Map lookup = new HashMap<>(); - - static { - for (final ReturnCode code : EnumSet.allOf(ReturnCode.class)) { - lookup.put(code.getCode(), code); - } - } - - protected final String code; - protected final String description; - - ReturnCode(final String code, final String description) { - this.code = code; - this.description = description; - } - - public String getCode() { - return code; - } - - public String getDescription() { - return description; - } - - /** - * Lookup the enum representation of a return code - * - * @param code to be looked up - * @return ReturnCode representation of the supplied code, or null if it can't be found - */ - public static ReturnCode getReturnCode(final String code) { - return code == null ? null : lookup.get(code); - } - -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/RiskScore.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/RiskScore.java deleted file mode 100644 index 9af8ddae..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/RiskScore.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; - -public class RiskScore implements Serializable { - private String value; - private String provider; - private String id; - private String finalScore; - private String rgid; - private String tScore; - private String tRisk; - private String message; - private String extendedResponse; - - public String getValue() { - return this.value; - } - - public void setValue(String value) { - this.value = value; - } - - public String getProvider() { - return this.provider; - } - - public void setProvider(String value) { - this.provider = value; - } - - public String getId() { - return this.id; - } - - public void setId(String value) { - this.id = value; - } - - public String getFinalScore() { - return this.finalScore; - } - - public void setFinalScore(String value) { - this.finalScore = value; - } - - public String getRGID() { - return this.rgid; - } - - public void setRGID(String value) { - this.rgid = value; - } - - public String getTScore() { - return this.tScore; - } - - public void setTScore(String value) { - this.tScore = value; - } - - public String getTRisk() { - return this.tRisk; - } - - public void setTRisk(String value) { - this.tRisk = value; - } - - public String getMessage() { - return this.message; - } - - public void setMessage(String value) { - this.message = value; - } - - public String getExtendedResponse() { - return this.extendedResponse; - } - - public void setExtendedResponse(String value) { - this.extendedResponse = value; - } - - @Override - public String toString() { - return "RiskScore{" + - "value='" + value + '\'' + - ", provider='" + provider + '\'' + - ", id='" + id + '\'' + - ", finalScore='" + finalScore + '\'' + - ", rgid='" + rgid + '\'' + - ", tScore='" + tScore + '\'' + - ", tRisk='" + tRisk + '\'' + - ", message='" + message + '\'' + - ", extendedResponse='" + extendedResponse + '\'' + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/SchemeResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/SchemeResponse.java deleted file mode 100644 index d4f90c91..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/SchemeResponse.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; - -public class SchemeResponse implements Serializable { - - private String schemeName; - private String actionCode; - private String responseCode; - private String transactionIdentifier; - - public String getSchemeName() { - return schemeName; - } - - public void setSchemeName(final String schemeName) { - this.schemeName = schemeName; - } - - public String getActionCode() { - return actionCode; - } - - public void setActionCode(final String actionCode) { - this.actionCode = actionCode; - } - - public String getResponseCode() { - return responseCode; - } - - public void setResponseCode(final String responseCode) { - this.responseCode = responseCode; - } - - public String getTransactionIdentifier() { - return transactionIdentifier; - } - - public void setTransactionIdentifier(final String transactionIdentifier) { - this.transactionIdentifier = transactionIdentifier; - } - - @Override - public String toString() { - return "SchemeResponse{" + - "schemeName='" + schemeName + '\'' + - ", actionCode='" + actionCode + '\'' + - ", responseCode='" + responseCode + '\'' + - ", transactionIdentifier='" + transactionIdentifier + '\'' + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Session.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Session.java deleted file mode 100644 index 79d1112b..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Session.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -/** - * POJO representation of a session - */ -public class Session implements InternalModelTransformer, Serializable { - - private String shopperIPAddress; - private String id; - - /** - * Constructor with full list of fields - * - * @param shopperIPAddress - * @param id - */ - public Session(String shopperIPAddress, String id) { - super(); - this.shopperIPAddress = shopperIPAddress; - this.id = id; - } - - @Override - public InternalModelObject transformToInternalModel() { - com.worldpay.internal.model.Session intSession = new com.worldpay.internal.model.Session(); - if (shopperIPAddress != null) { - intSession.setShopperIPAddress(shopperIPAddress); - } - if (id != null) { - intSession.setId(id); - } - return intSession; - } - - public String getShopperIPAddress() { - return shopperIPAddress; - } - - public void setShopperIPAddress(String shopperIPAddress) { - this.shopperIPAddress = shopperIPAddress; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "Session [shopperIPAddress=" + shopperIPAddress + ", id=" + id + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Shopper.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Shopper.java deleted file mode 100644 index 98ef2a84..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/Shopper.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.AuthenticatedShopperID; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -/** - * POJO representation of a shopper - */ -public class Shopper implements InternalModelTransformer, Serializable { - - private String shopperEmailAddress; - private String authenticatedShopperID; - private Browser browser; - private Session session; - - public Shopper(final String shopperEmailAddress, final String authenticatedShopperID, final Browser browser, final Session session) { - this.shopperEmailAddress = shopperEmailAddress; - this.authenticatedShopperID = authenticatedShopperID; - this.browser = browser; - this.session = session; - } - - @Override - public InternalModelObject transformToInternalModel() throws WorldpayModelTransformationException { - com.worldpay.internal.model.Shopper intShopper = new com.worldpay.internal.model.Shopper(); - if (shopperEmailAddress != null) { - intShopper.setShopperEmailAddress(shopperEmailAddress); - } - if (authenticatedShopperID != null) { - final AuthenticatedShopperID intAuthenticatedShopperID = new AuthenticatedShopperID(); - intAuthenticatedShopperID.setvalue(authenticatedShopperID); - intShopper.setAuthenticatedShopperID(intAuthenticatedShopperID); - } - if (browser != null) { - intShopper.setBrowser((com.worldpay.internal.model.Browser) browser.transformToInternalModel()); - } - if (session != null) { - intShopper.setSession((com.worldpay.internal.model.Session) session.transformToInternalModel()); - } - return intShopper; - } - - public String getShopperEmailAddress() { - return shopperEmailAddress; - } - - public void setShopperEmailAddress(String shopperEmailAddress) { - this.shopperEmailAddress = shopperEmailAddress; - } - - public Browser getBrowser() { - return browser; - } - - public void setBrowser(Browser browser) { - this.browser = browser; - } - - public String getAuthenticatedShopperID() { - return authenticatedShopperID; - } - - public void setAuthenticatedShopperID(final String authenticatedShopperID) { - this.authenticatedShopperID = authenticatedShopperID; - } - - public Session getSession() { - return session; - } - - public void setSession(final Session session) { - this.session = session; - } - - @Override - public String toString() { - return "Shopper{" + - "shopperEmailAddress='" + shopperEmailAddress + '\'' + - ", authenticatedShopperID='" + authenticatedShopperID + '\'' + - ", browser=" + browser + - ", session=" + session + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/WebformRefundReply.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/WebformRefundReply.java deleted file mode 100644 index 65d3664c..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/WebformRefundReply.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.worldpay.service.model; - -import java.io.Serializable; - - -public class WebformRefundReply implements Serializable { - private String webformId; - private String paymentId; - private String webformStatus; - private Amount amount; - private String reason; - private String webformURL; - private String refundId; - - public String getPaymentId() { - return paymentId; - } - - public void setPaymentId(String paymentId) { - this.paymentId = paymentId; - } - - public String getWebformStatus() { - return webformStatus; - } - - public void setWebformStatus(String webformStatus) { - this.webformStatus = webformStatus; - } - - public Amount getAmount() { - return amount; - } - - public void setAmount(Amount amount) { - this.amount = amount; - } - - public String getReason() { - return reason; - } - - public void setReason(String reason) { - this.reason = reason; - } - - public String getWebformURL() { - return webformURL; - } - - public void setWebformURL(String webformURL) { - this.webformURL = webformURL; - } - - public String getRefundId() { - return refundId; - } - - public void setRefundId(String refundId) { - this.refundId = refundId; - } - - - public String getWebformId() { - return webformId; - } - - public void setWebformId(String webformId) { - this.webformId = webformId; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/applepay/ApplePay.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/applepay/ApplePay.java deleted file mode 100644 index 42c20da4..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/applepay/ApplePay.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.worldpay.service.model.applepay; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.service.model.payment.AbstractPayment; -import com.worldpay.service.model.payment.PaymentType; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class ApplePay extends AbstractPayment { - - private Header header; - private String signature; - private String version; - private String data; - private String tokenRequestorID; - - public ApplePay(final Header header, final String signature, final String version, final String data, final String tokenRequestorID) { - this.paymentType = PaymentType.APPLEPAYSSL; - this.header = header; - this.signature = signature; - this.version = version; - this.data = data; - this.tokenRequestorID = tokenRequestorID; - } - - @Override - public void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException, WorldpayModelTransformationException { - final String methodName = method.getName(); - - if ("setHeader".equals(methodName) && header != null) { - method.invoke(targetObject, header.transformToInternalModel()); - } - if ("setSignature".equals(methodName) && signature != null) { - method.invoke(targetObject, signature); - } - if ("setVersion".equals(methodName) && version != null) { - method.invoke(targetObject, version); - } - if ("setData".equals(methodName) && data != null) { - method.invoke(targetObject, data); - } - if ("setTokenRequestorID".equals(methodName) && tokenRequestorID != null) { - method.invoke(targetObject, tokenRequestorID); - } - } - - - public String getSignature() { - return signature; - } - - public void setSignature(final String signature) { - this.signature = signature; - } - - public String getVersion() { - return version; - } - - public void setVersion(final String version) { - this.version = version; - } - - public String getData() { - return data; - } - - public void setData(final String data) { - this.data = data; - } - - public String getTokenRequestorID() { - return tokenRequestorID; - } - - public void setTokenRequestorID(final String tokenRequestorID) { - this.tokenRequestorID = tokenRequestorID; - } - - public Header getHeader() { - return header; - } - - public void setHeader(final Header header) { - this.header = header; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/applepay/Header.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/applepay/Header.java deleted file mode 100644 index 65f913e1..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/applepay/Header.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.worldpay.service.model.applepay; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -public class Header implements InternalModelTransformer, Serializable { - - private String ephemeralPublicKey; - private String publicKeyHash; - private String transactionId; - private String applicationData; - - public Header(final String ephemeralPublicKey, final String publicKeyHash, final String transactionId, final String applicationData) { - this.ephemeralPublicKey = ephemeralPublicKey; - this.publicKeyHash = publicKeyHash; - this.transactionId = transactionId; - this.applicationData = applicationData; - } - - @Override - public InternalModelObject transformToInternalModel() throws WorldpayModelTransformationException { - com.worldpay.internal.model.Header intHeader = new com.worldpay.internal.model.Header(); - intHeader.setApplicationData(applicationData); - intHeader.setEphemeralPublicKey(ephemeralPublicKey); - intHeader.setPublicKeyHash(publicKeyHash); - intHeader.setTransactionId(transactionId); - return intHeader; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/klarna/KlarnaMerchantUrls.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/klarna/KlarnaMerchantUrls.java deleted file mode 100644 index b4be602b..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/klarna/KlarnaMerchantUrls.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.worldpay.service.model.klarna; - -import java.io.Serializable; - -public class KlarnaMerchantUrls implements Serializable { - private static final long serialVersionUID = 1L; - private String checkoutURL; - private String confirmationURL; - - public KlarnaMerchantUrls(final String checkoutURL, final String confirmationURL) { - this.checkoutURL = checkoutURL; - this.confirmationURL = confirmationURL; - } - - public String getCheckoutURL() { - return checkoutURL; - } - - public void setCheckoutURL(final String checkoutURL) { - this.checkoutURL = checkoutURL; - } - - public String getConfirmationURL() { - return confirmationURL; - } - - public void setConfirmationURL(final String confirmationURL) { - this.confirmationURL = confirmationURL; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/klarna/KlarnaPayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/klarna/KlarnaPayment.java deleted file mode 100644 index f982dadc..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/klarna/KlarnaPayment.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.worldpay.service.model.klarna; - -import com.worldpay.internal.model.MerchantUrls; -import com.worldpay.service.model.payment.AbstractPayment; -import com.worldpay.service.model.payment.PaymentType; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import static com.worldpay.service.model.payment.PaymentType.KLARNASSL; - -public class KlarnaPayment extends AbstractPayment { - - private String purchaseCountry; - private String shopperCountryCode; - private String locale; - private String shopperLocale; - private String successURL; - private String pendingURL; - private String failureURL; - private String cancelURL; - private KlarnaMerchantUrls merchantUrls; - private final String extraMerchantData; - - - public KlarnaPayment(final String purchaseCountry, final String shopperLocale, final KlarnaMerchantUrls merchantUrls, final String extraMerchantData) { - this.setPaymentType(KLARNASSL); - this.purchaseCountry = purchaseCountry; - this.shopperLocale = shopperLocale; - this.merchantUrls = merchantUrls; - this.extraMerchantData = extraMerchantData; - } - - public KlarnaPayment(final String purchaseCountry, final String shopperLocale, final String extraMerchantData, - final String klarnaPaymentMethod, final KlarnaRedirectURLs klarnaRedirectURLs) { - this.setPaymentType(PaymentType.getPaymentType(klarnaPaymentMethod)); - this.shopperCountryCode = purchaseCountry; - this.locale = shopperLocale; - this.successURL = klarnaRedirectURLs.getSuccessURL(); - this.pendingURL = klarnaRedirectURLs.getPendingURL(); - this.failureURL = klarnaRedirectURLs.getFailureURL(); - this.cancelURL = klarnaRedirectURLs.getCancelURL(); - this.extraMerchantData = extraMerchantData; - } - - @SuppressWarnings("java:S3776") - @Override - public void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - final String methodName = method.getName(); - if ("setPurchaseCountry".equals(methodName) && purchaseCountry != null) { - method.invoke(targetObject, purchaseCountry); - } - if ("setShopperLocale".equals(methodName) && shopperLocale != null) { - method.invoke(targetObject, shopperLocale); - } - if ("setShopperCountryCode".equals(methodName) && shopperCountryCode != null) { - method.invoke(targetObject, shopperCountryCode); - } - if ("setLocale".equals(methodName) && locale != null) { - method.invoke(targetObject, locale); - } - if ("setSuccessURL".equals(methodName) && successURL != null) { - method.invoke(targetObject, successURL); - } - if ("setPendingURL".equals(methodName) && pendingURL != null) { - method.invoke(targetObject, pendingURL); - } - if ("setFailureURL".equals(methodName) && failureURL != null) { - method.invoke(targetObject, failureURL); - } - if ("setCancelURL".equals(methodName) && cancelURL != null) { - method.invoke(targetObject, cancelURL); - } - if ("setMerchantUrls".equals(methodName) && merchantUrls != null) { - final MerchantUrls intMerchantUrls = new MerchantUrls(); - intMerchantUrls.setCheckoutURL(merchantUrls.getCheckoutURL()); - intMerchantUrls.setConfirmationURL(merchantUrls.getConfirmationURL()); - method.invoke(targetObject, intMerchantUrls); - } - if ("setExtraMerchantData".equals(methodName) && extraMerchantData != null) { - method.invoke(targetObject, extraMerchantData); - } - - } - - public String getPurchaseCountry() { - return purchaseCountry; - } - - public String getShopperCountryCode() { - return shopperCountryCode; - } - - public String getLocale() { - return locale; - } - - public String getShopperLocale() { - return shopperLocale; - } - - public KlarnaMerchantUrls getMerchantUrls() { - return merchantUrls; - } - - public String getExtraMerchantData() { - return extraMerchantData; - } - - public String getSuccessURL() { - return successURL; - } - - public String getPendingURL() { - return pendingURL; - } - - public String getFailureURL() { - return failureURL; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/klarna/KlarnaRedirectURLs.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/klarna/KlarnaRedirectURLs.java deleted file mode 100644 index 9dc51fec..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/klarna/KlarnaRedirectURLs.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.worldpay.service.model.klarna; - -import java.io.Serializable; - -public class KlarnaRedirectURLs implements Serializable { - - private String successURL; - private String cancelURL; - private String pendingURL; - private String failureURL; - - public KlarnaRedirectURLs(String successURL, String cancelURL, String pendingURL, String failureURL) { - this.successURL = successURL; - this.cancelURL = cancelURL; - this.pendingURL = pendingURL; - this.failureURL = failureURL; - } - - public String getSuccessURL() { - return successURL; - } - - public String getCancelURL() { - return cancelURL; - } - - public String getPendingURL() { - return pendingURL; - } - - public String getFailureURL() { - return failureURL; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AbstractPayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AbstractPayment.java deleted file mode 100644 index 19dd0af5..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AbstractPayment.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; - -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * Abstract class that templates part of the transformToInternalModel method for {@link Payment} implementors. Obviously each type of payment will have different - * fields so reflection is used to get the list of methods for an implementation and then it's up to the subclass to implement the correct logic for any setter - * methods - */ -public abstract class AbstractPayment implements Payment, Serializable { - - protected PaymentType paymentType; - - @Override - public InternalModelObject transformToInternalModel() throws WorldpayModelTransformationException { - try { - final Class modelClass = paymentType.getModelClass(); - final InternalModelObject instance = (InternalModelObject) modelClass.getDeclaredConstructor().newInstance(); - final Method[] declaredMethods = modelClass.getDeclaredMethods(); - for (final Method method : declaredMethods) { - invokeSetter(method, instance); - } - - return instance; - } catch (final InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new WorldpayModelTransformationException("Exception while attempting to transform Card", e); - } - } - - /** - * Set the relevant field on the internal model object from the external model representation. - *

- * The {@link #transformToInternalModel()} method uses reflection to find all the methods supported by the internal model object and then invokes this method to - * correctly set the details of each field against the target object - * - * @param method Method that can be invoked on the internal model object targetObject - * @param targetObject internal model object that we are trying to transform to - * @throws IllegalAccessException if the method is not accessible - * @throws InvocationTargetException if method cannot be invoked against the supplied target object - */ - public abstract void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException, WorldpayModelTransformationException; - - @Override - public PaymentType getPaymentType() { - return paymentType; - } - - @Override - public void setPaymentType(final PaymentType paymentType) { - this.paymentType = paymentType; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AchPayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AchPayment.java deleted file mode 100644 index c88bc481..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AchPayment.java +++ /dev/null @@ -1,216 +0,0 @@ -/** - * - */ -package com.worldpay.service.model.payment; - -import com.worldpay.internal.model.Authentication; -import com.worldpay.internal.model.Deposit; -import com.worldpay.internal.model.Validation; -import com.worldpay.internal.model.Verification; -import com.worldpay.service.model.Address; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; - -/** - * POJO representation of an ACH {@link Payment} type - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class AchPayment extends AbstractPayment { - - private AchType achType; - private String firstName; - private String lastName; - private Address address; - private String bankAccountType; - private String routingNumber; - private String accountNumber; - - /** - * Constructor with full list of fields - * - * @param firstName - * @param lastName - * @param address - * @param bankAccountType - * @param routingNumber - * @param accountNumber - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public AchPayment(final PaymentType paymentType, final AchType achType, final String firstName, final String lastName, final Address address, final String bankAccountType, final String routingNumber, final String accountNumber) { - this.paymentType = paymentType; - this.achType = achType; - this.firstName = firstName; - this.lastName = lastName; - this.address = address; - this.bankAccountType = bankAccountType; - this.routingNumber = routingNumber; - this.accountNumber = accountNumber; - } - - /** - * Static convenience method to create an Authentication ACH Payment - * - * @param firstName - * @param lastName - * @param address - * @return AchPayment object - */ - public static AchPayment createAuthenticationAchPayment(final String firstName, final String lastName, final Address address) { - return new AchPayment(PaymentType.ACH, AchType.AUTHENTICATION, firstName, lastName, address, null, null, null); - } - - /** - * Static convenience method to create a Deposit ACH Payment - * - * @param firstName - * @param lastName - * @param bankAccountType - * @param routingNumber - * @param accountNumber - * @return AchPayment object - */ - public static AchPayment createDepositAchPayment(final String firstName, final String lastName, final String bankAccountType, final String routingNumber, final String accountNumber) { - return new AchPayment(PaymentType.ACH, AchType.DEPOSIT, firstName, lastName, null, bankAccountType, routingNumber, accountNumber); - } - - /** - * Static convenience method to create a Validation ACH Payment - * - * @param firstName - * @param lastName - * @param bankAccountType - * @param routingNumber - * @param accountNumber - * @return AchPayment object - */ - public static AchPayment createValidationAchPayment(final String firstName, final String lastName, final String bankAccountType, final String routingNumber, final String accountNumber) { - return new AchPayment(PaymentType.ACH, AchType.VALIDATION, firstName, lastName, null, bankAccountType, routingNumber, accountNumber); - } - - /** - * Static convenience method to create a Verification ACH Payment - * - * @param bankAccountType - * @param routingNumber - * @param accountNumber - * @return AchPayment object - */ - public static AchPayment createVerificationAchPayment(final String bankAccountType, final String routingNumber, final String accountNumber) { - return new AchPayment(PaymentType.ACH, AchType.VERIFICATION, null, null, null, bankAccountType, routingNumber, accountNumber); - } - - /* (non-Javadoc) - * @see AbstractPayment#invokeSetter(java.lang.reflect.Method, java.lang.Object) - */ - @Override - @SuppressWarnings("unchecked") - public void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - String methodName = method.getName(); - if ("getAuthenticationOrDepositOrValidationOrVerification".equals(methodName)) { - final List intAchType = (List) method.invoke(targetObject); - if (achType.equals(AchType.AUTHENTICATION)) { - final Authentication intAuth = new Authentication(); - intAuth.setFirstName(firstName); - intAuth.setLastName(lastName); - intAuth.setAddress((com.worldpay.internal.model.Address) address.transformToInternalModel()); - - intAchType.add(intAuth); - } else if (AchType.DEPOSIT.equals(achType)) { - final Deposit intDeposit = new Deposit(); - intDeposit.setFirstName(firstName); - intDeposit.setLastName(lastName); - intDeposit.setBankAccountType(bankAccountType); - intDeposit.setRoutingNumber(routingNumber); - intDeposit.setAccountNumber(accountNumber); - - intAchType.add(intDeposit); - } else if (AchType.VALIDATION.equals(achType)) { - final Validation intValidation = new Validation(); - intValidation.setFirstName(firstName); - intValidation.setLastName(lastName); - intValidation.setBankAccountType(bankAccountType); - intValidation.setRoutingNumber(routingNumber); - intValidation.setAccountNumber(accountNumber); - - intAchType.add(intValidation); - } else if (AchType.VERIFICATION.equals(achType)) { - final Verification intVerification = new Verification(); - intVerification.setBankAccountType(bankAccountType); - intVerification.setRoutingNumber(routingNumber); - intVerification.setAccountNumber(accountNumber); - - intAchType.add(intVerification); - } - } - } - - public AchType getAchType() { - return achType; - } - - public void setAchType(final AchType achType) { - this.achType = achType; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(final String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(final String lastName) { - this.lastName = lastName; - } - - public Address getAddress() { - return address; - } - - public void setAddress(final Address address) { - this.address = address; - } - - public String getBankAccountType() { - return bankAccountType; - } - - public void setBankAccountType(final String bankAccountType) { - this.bankAccountType = bankAccountType; - } - - public String getRoutingNumber() { - return routingNumber; - } - - public void setRoutingNumber(final String routingNumber) { - this.routingNumber = routingNumber; - } - - public String getAccountNumber() { - return accountNumber; - } - - public void setAccountNumber(final String accountNumber) { - this.accountNumber = accountNumber; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AchPayment [achType=" + achType + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address + ", bankAccountType=" - + bankAccountType + ", routingNumber=" + routingNumber + ", accountNumber=" + accountNumber + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AchType.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AchType.java deleted file mode 100644 index e2131ca0..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AchType.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.worldpay.service.model.payment; - -import java.io.Serializable; - -/** - * Enum representation of the ACH Payment types - */ -public enum AchType implements Serializable { - - AUTHENTICATION("authentication"), - DEPOSIT("deposit"), - VALIDATION("validation"), - VERIFICATION("verification"),; - - private String typeName; - - private AchType(final String typeName) { - this.typeName = typeName; - } - - public String getTypeName() { - return typeName; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeAccNoPayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeAccNoPayment.java deleted file mode 100644 index a005e890..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeAccNoPayment.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.worldpay.service.model.payment; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link AlternativePayment} type with account number and password - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class AlternativeAccNoPayment extends AlternativePayment { - - private String accountNumber; - private String accountPassword; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param shopperCountryCode - * @param successURL - * @param failureURL - * @param cancelURL - * @param pendingURL - * @param accountNumber - * @param accountPassword - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public AlternativeAccNoPayment(final PaymentType paymentType, final String shopperCountryCode, final String successURL, final String failureURL, final String cancelURL, final String pendingURL, final String accountNumber, final String accountPassword) { - super(paymentType, shopperCountryCode, successURL, failureURL, cancelURL, pendingURL); - this.accountNumber = accountNumber; - this.accountPassword = accountPassword; - } - - @Override - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - super.invokeExtraSetters(method, targetObject); - final String methodName = method.getName(); - if ("setAccountNumber".equals(methodName) && getAccountNumber() != null) { - method.invoke(targetObject, getAccountNumber()); - } - if ("setAccountPassword".equals(methodName) && getAccountPassword() != null) { - method.invoke(targetObject, getAccountPassword()); - } - } - - public String getAccountNumber() { - return accountNumber; - } - - public void setAccountNumber(final String accountNumber) { - this.accountNumber = accountNumber; - } - - public String getAccountPassword() { - return accountPassword; - } - - public void setAccountPassword(final String accountPassword) { - this.accountPassword = accountPassword; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AlternativeAccNoPayment [accountNumber=" + accountNumber + ", accountPassword=" + accountPassword + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeBankCodePayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeBankCodePayment.java deleted file mode 100644 index 3882baf6..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeBankCodePayment.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.worldpay.service.model.payment; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link AlternativePayment} type with bank code - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class AlternativeBankCodePayment extends AlternativePayment { - - private String bankCode; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param shopperCountryCode - * @param successURL - * @param failureURL - * @param cancelURL - * @param pendingURL - * @param bankCode - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public AlternativeBankCodePayment(final PaymentType paymentType, final String shopperCountryCode, final String successURL, final String failureURL, final String cancelURL, String pendingURL, String bankCode) { - super(paymentType, shopperCountryCode, successURL, failureURL, cancelURL, pendingURL); - this.bankCode = bankCode; - } - - @Override - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - super.invokeExtraSetters(method, targetObject); - final String methodName = method.getName(); - if ("setBankCode".equals(methodName) && bankCode != null) { - method.invoke(targetObject, bankCode); - } - } - - public String getBankCode() { - return bankCode; - } - - public void setBankCode(final String bankCode) { - this.bankCode = bankCode; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AlternativeBankCodePayment [bankCode=" + bankCode + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeCardAddressPayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeCardAddressPayment.java deleted file mode 100644 index ce50a3a9..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeCardAddressPayment.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.internal.model.CardAddress; -import com.worldpay.service.model.Address; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link AlternativePayment} type with card address - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class AlternativeCardAddressPayment extends AlternativePayment { - - private Address cardAddress; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param shopperCountryCode - * @param successURL - * @param failureURL - * @param cancelURL - * @param pendingURL - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public AlternativeCardAddressPayment(final PaymentType paymentType, final String shopperCountryCode, final String successURL, final String failureURL, final String cancelURL, String pendingURL, Address cardAddress) { - super(paymentType, shopperCountryCode, successURL, failureURL, cancelURL, pendingURL); - this.cardAddress = cardAddress; - } - - @Override - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - super.invokeExtraSetters(method, targetObject); - final String methodName = method.getName(); - if ("setCardAddress".equals(methodName) && cardAddress != null) { - final CardAddress intCardAddress = new CardAddress(); - intCardAddress.setAddress((com.worldpay.internal.model.Address) cardAddress.transformToInternalModel()); - method.invoke(targetObject, intCardAddress); - } - } - - public Address getCardAddress() { - return cardAddress; - } - - public void setCardAddress(final Address cardAddress) { - this.cardAddress = cardAddress; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AlternativeCardAddressPayment [cardAddress=" + cardAddress + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePanCvvPayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePanCvvPayment.java deleted file mode 100644 index 7bf51ac0..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePanCvvPayment.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.internal.model.ExpiryDate; -import com.worldpay.service.model.Date; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link AlternativePayment} type with pan, cvv and expiry date - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class AlternativePanCvvPayment extends AlternativePayment { - - private String pan; - private String cvv; - private Date expiryDate; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param shopperCountryCode - * @param successURL - * @param failureURL - * @param cancelURL - * @param pendingURL - * @param pan - * @param cvv - * @param expiryDate - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public AlternativePanCvvPayment(final PaymentType paymentType, final String shopperCountryCode, final String successURL, final String failureURL, final String cancelURL, final String pendingURL, String pan, String cvv, Date expiryDate) { - super(paymentType, shopperCountryCode, successURL, failureURL, cancelURL, pendingURL); - this.pan = pan; - this.cvv = cvv; - this.expiryDate = expiryDate; - } - - @Override - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - super.invokeExtraSetters(method, targetObject); - final String methodName = method.getName(); - if ("setPan".equals(methodName) && getPan() != null) { - method.invoke(targetObject, getPan()); - } - if ("setCvv".equals(methodName) && getCvv() != null) { - method.invoke(targetObject, getCvv()); - } - if ("setExpiryDate".equals(methodName) && getExpiryDate() != null) { - final ExpiryDate intExpiryDate = new ExpiryDate(); - intExpiryDate.setDate((com.worldpay.internal.model.Date) getExpiryDate().transformToInternalModel()); - method.invoke(targetObject, intExpiryDate); - } - } - - public String getPan() { - return pan; - } - - public void setPan(final String pan) { - this.pan = pan; - } - - public String getCvv() { - return cvv; - } - - public void setCvv(final String cvv) { - this.cvv = cvv; - } - - public Date getExpiryDate() { - return expiryDate; - } - - public void setExpiryDate(final Date expiryDate) { - this.expiryDate = expiryDate; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AlternativePanCvvPayment [pan=" + pan + ", cvv=" + cvv + ", expiryDate=" + expiryDate + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePanPinPayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePanPinPayment.java deleted file mode 100644 index 5b6a55a8..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePanPinPayment.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * - */ -package com.worldpay.service.model.payment; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link AlternativePayment} type with pan and pin - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class AlternativePanPinPayment extends AlternativePayment { - - private String pan; - private String pin; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param shopperCountryCode - * @param successURL - * @param failureURL - * @param cancelURL - * @param pendingURL - * @param pan - * @param pin - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public AlternativePanPinPayment(final PaymentType paymentType, final String shopperCountryCode, final String successURL, final String failureURL, final String cancelURL, final String pendingURL, final String pan, final String pin) { - super(paymentType, shopperCountryCode, successURL, failureURL, cancelURL, pendingURL); - this.pan = pan; - this.pin = pin; - } - - @Override - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - super.invokeExtraSetters(method, targetObject); - final String methodName = method.getName(); - if ("setPan".equals(methodName) && getPan() != null) { - method.invoke(targetObject, getPan()); - } - if ("setPin".equals(methodName) && getPin() != null) { - method.invoke(targetObject, getPin()); - } - } - - public String getPan() { - return pan; - } - - public void setPan(final String pan) { - this.pan = pan; - } - - public String getPin() { - return pin; - } - - public void setPin(final String pin) { - this.pin = pin; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AlternativePanPinPayment [pan=" + pan + ", pin=" + pin + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePayPalPayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePayPalPayment.java deleted file mode 100644 index ca433e6e..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePayPalPayment.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.worldpay.service.model.payment; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link AlternativePayment} type with paypal first in billing run parameter - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class AlternativePayPalPayment extends AlternativePayment { - - private String firstInBillingRun; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param shopperCountryCode - * @param successURL - * @param failureURL - * @param cancelURL - * @param pendingURL - * @param firstInBillingRun - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public AlternativePayPalPayment(final PaymentType paymentType, final String shopperCountryCode, final String successURL, final String failureURL, final String cancelURL, final String pendingURL, final String firstInBillingRun) { - super(paymentType, shopperCountryCode, successURL, failureURL, cancelURL, pendingURL); - this.firstInBillingRun = firstInBillingRun; - } - - @Override - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - super.invokeExtraSetters(method, targetObject); - final String methodName = method.getName(); - if ("setFirstInBillingRun".equals(methodName) && firstInBillingRun != null) { - method.invoke(targetObject, firstInBillingRun); - } - } - - public String getFirstInBillingRun() { - return firstInBillingRun; - } - - public void setFirstInBillingRun(final String firstInBillingRun) { - this.firstInBillingRun = firstInBillingRun; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AlternativePayPalPayment [firstInBillingRun=" + firstInBillingRun + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePayment.java deleted file mode 100644 index 86c514a1..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativePayment.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.worldpay.service.model.payment; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link Payment} type for alternative payments - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class AlternativePayment extends AbstractPayment { - - private String shopperCountryCode; - private String successURL; - private String failureURL; - private String cancelURL; - private String pendingURL; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param shopperCountryCode - * @param successURL - * @param failureURL - * @param cancelURL - * @param pendingURL - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public AlternativePayment(final PaymentType paymentType, final String shopperCountryCode, final String successURL, final String failureURL, final String cancelURL, final String pendingURL) { - this.paymentType = paymentType; - this.shopperCountryCode = shopperCountryCode; - this.successURL = successURL; - this.failureURL = failureURL; - this.cancelURL = cancelURL; - this.pendingURL = pendingURL; - } - - @Override - public void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - boolean methodInvoked = false; - final String methodName = method.getName(); - if (methodName.startsWith("set")) { - if ("setShopperCountryCode".equals(methodName) && shopperCountryCode != null) { - method.invoke(targetObject, shopperCountryCode); - methodInvoked = true; - } - if ("setSuccessURL".equals(methodName) && successURL != null) { - method.invoke(targetObject, successURL); - methodInvoked = true; - } - if ("setFailureURL".equals(methodName) && failureURL != null) { - method.invoke(targetObject, failureURL); - methodInvoked = true; - } - if ("setCancelURL".equals(methodName) && cancelURL != null) { - method.invoke(targetObject, cancelURL); - methodInvoked = true; - } - if ("setPendingURL".equals(methodName) && pendingURL != null) { - method.invoke(targetObject, pendingURL); - methodInvoked = true; - } - } - - if (!methodInvoked) { - invokeExtraSetters(method, targetObject); - } - } - - /** - * Method to be used by overriding classes in order to ensure that extra fields that they implement get set when the {@link #transformToInternalModel()} method is - * invoked. Default implementation does nothing so just provides the hook for overriding classes - * - * @param method Method that can be invoked on the internal model object targetObject - * @param targetObject internal model object that we are trying to transform to - * @throws IllegalArgumentException if the method is invoked with incorrect parameters - * @throws IllegalAccessException if the method is not accessible - * @throws InvocationTargetException if method cannot be invoked against the supplied target object - */ - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - // Do nothing. This provides a hook for subclasses to add extra functionality - } - - public String getShopperCountryCode() { - return shopperCountryCode; - } - - public void setShopperCountryCode(final String shopperCountryCode) { - this.shopperCountryCode = shopperCountryCode; - } - - public String getSuccessURL() { - return successURL; - } - - public void setSuccessURL(final String successURL) { - this.successURL = successURL; - } - - public String getFailureURL() { - return failureURL; - } - - public void setFailureURL(final String failureURL) { - this.failureURL = failureURL; - } - - public String getCancelURL() { - return cancelURL; - } - - public void setCancelURL(final String cancelURL) { - this.cancelURL = cancelURL; - } - - public String getPendingURL() { - return pendingURL; - } - - public void setPendingURL(final String pendingURL) { - this.pendingURL = pendingURL; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AlternativePayment [shopperCountryCode=" + shopperCountryCode + ", successURL=" + successURL + ", failureURL=" + failureURL + - ", cancelURL=" + cancelURL + ", pendingURL=" + pendingURL + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeShopperBankCodePayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeShopperBankCodePayment.java deleted file mode 100644 index 1ed5b276..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/AlternativeShopperBankCodePayment.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.worldpay.service.model.payment; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link AlternativePayment} type with shopper bank code - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class AlternativeShopperBankCodePayment extends AlternativePayment { - - private String shopperBankCode; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param shopperCountryCode - * @param successURL - * @param failureURL - * @param cancelURL - * @param pendingURL - * @param shopperBankCode - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public AlternativeShopperBankCodePayment(final PaymentType paymentType, final String shopperCountryCode, final String successURL, final String failureURL, final String cancelURL, final String pendingURL, final String shopperBankCode) { - super(paymentType, shopperCountryCode, successURL, failureURL, cancelURL, pendingURL); - this.shopperBankCode = shopperBankCode; - } - - @Override - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - super.invokeExtraSetters(method, targetObject); - final String methodName = method.getName(); - if ("setShopperBankCode".equals(methodName) && shopperBankCode != null) { - method.invoke(targetObject, shopperBankCode); - } - } - - public String getShopperBankCode() { - return shopperBankCode; - } - - public void setShopperBankCode(final String shopperBankCode) { - this.shopperBankCode = shopperBankCode; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "AlternativeShopperBankCodePayment [shopperBankCode=" + shopperBankCode + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/BankAccount.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/BankAccount.java deleted file mode 100644 index f2dccba3..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/BankAccount.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.internal.model.BirthDate; -import com.worldpay.internal.model.CreditScoring; -import com.worldpay.service.model.Address; -import com.worldpay.service.model.Date; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link Payment} type for bank account payments - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class BankAccount extends AbstractPayment { - - private String accountHolderName; - private String accountNumber; - private String bankName; - private String bankLocation; - private String bankLocationId; - private Date birthDate; - private Address address; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param accountHolderName - * @param accountNumber - * @param bankName - * @param bankLocation - * @param bankLocationId - * @param birthDate - * @param address - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public BankAccount(final PaymentType paymentType, final String accountHolderName, final String accountNumber, final String bankName, final String bankLocation, final String bankLocationId, final Date birthDate, final Address address) { - this.paymentType = paymentType; - this.accountHolderName = accountHolderName; - this.accountNumber = accountNumber; - this.bankName = bankName; - this.bankLocation = bankLocation; - this.bankLocationId = bankLocationId; - this.birthDate = birthDate; - this.address = address; - } - - @Override - public void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - boolean methodInvoked = false; - final String methodName = method.getName(); - if (methodName.startsWith("set")) { - if ("setAccountHolderName".equals(methodName) && accountHolderName != null) { - method.invoke(targetObject, accountHolderName); - methodInvoked = true; - } - if ("setBankAccountNr".equals(methodName) && accountNumber != null) { - method.invoke(targetObject, accountNumber); - methodInvoked = true; - } - if ("setBankName".equals(methodName) && bankName != null) { - method.invoke(targetObject, bankName); - methodInvoked = true; - } - if ("setBankLocation".equals(methodName) && bankLocation != null) { - method.invoke(targetObject, bankLocation); - methodInvoked = true; - } - if ("setBankLocationId".equals(methodName) && bankLocationId != null) { - method.invoke(targetObject, bankLocationId); - methodInvoked = true; - } - if ("setCreditScoring".equals(methodName) && birthDate != null && address != null) { - final CreditScoring intCreditScoring = new CreditScoring(); - intCreditScoring.setAddress((com.worldpay.internal.model.Address) address.transformToInternalModel()); - final BirthDate intBirthDate = new BirthDate(); - intBirthDate.setDate((com.worldpay.internal.model.Date) address.transformToInternalModel()); - intCreditScoring.setBirthDate(intBirthDate); - method.invoke(targetObject, intCreditScoring); - methodInvoked = true; - } - } - - if (!methodInvoked) { - invokeExtraSetters(method, targetObject); - } - } - - /** - * Method to be used by overriding classes in order to ensure that extra fields that they implement get set when the {@link #transformToInternalModel()} method is - * invoked. Default implementation does nothing so just provides the hook for overriding classes - * - * @param method Method that can be invoked on the internal model object targetObject - * @param targetObject internal model object that we are trying to transform to - * @throws IllegalArgumentException if the method is invoked with incorrect parameters - * @throws IllegalAccessException if the method is not accessible - * @throws InvocationTargetException if method cannot be invoked against the supplied target object - */ - protected void invokeExtraSetters(Method method, Object targetObject) throws IllegalAccessException, InvocationTargetException { - // Do nothing. This provides a hook for subclasses to add extra functionality - } - - public String getAccountHolderName() { - return accountHolderName; - } - - public void setAccountHolderName(final String accountHolderName) { - this.accountHolderName = accountHolderName; - } - - public String getAccountNumber() { - return accountNumber; - } - - public void setAccountNumber(final String accountNumber) { - this.accountNumber = accountNumber; - } - - public String getBankName() { - return bankName; - } - - public void setBankName(final String bankName) { - this.bankName = bankName; - } - - public String getBankLocation() { - return bankLocation; - } - - public void setBankLocation(final String bankLocation) { - this.bankLocation = bankLocation; - } - - public String getBankLocationId() { - return bankLocationId; - } - - public void setBankLocationId(final String bankLocationId) { - this.bankLocationId = bankLocationId; - } - - public Date getBirthDate() { - return birthDate; - } - - public void setBirthDate(final Date birthDate) { - this.birthDate = birthDate; - } - - public Address getAddress() { - return address; - } - - public void setAddress(final Address address) { - this.address = address; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "BankAccount [accountHolderName=" + accountHolderName + ", accountNumber=" + accountNumber + ", bankName=" + bankName + ", bankLocation=" - + bankLocation + ", bankLocationId=" + bankLocationId + ", birthDate=" + birthDate + ", address=" + address + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/Card.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/Card.java deleted file mode 100644 index 0fa6933c..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/Card.java +++ /dev/null @@ -1,235 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.internal.model.*; -import com.worldpay.service.model.Address; -import com.worldpay.service.model.Date; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; - -/** - * POJO representation of {@link Payment} type for card payments - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class Card extends AbstractPayment { - - private String cardNumber; - private String cvc; - private Date expiryDate; - private String cardHolderName; - private Address cardAddress; - private Date birthDate; - private Date startDate; - private String issueNumber; - private String bin; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param cardNumber - * @param cvc - * @param expiryDate - * @param cardHolderName - * @param cardAddress - * @param birthDate - * @param startDate - * @param issueNumber - * @param bin - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public Card(final PaymentType paymentType, final String cardNumber, final String cvc, final Date expiryDate, final String cardHolderName, final Address cardAddress, - final Date birthDate, final Date startDate, final String issueNumber, final String bin) { - this.bin = bin; - this.paymentType = paymentType; - this.cardNumber = cardNumber; - this.cvc = cvc; - this.expiryDate = expiryDate; - this.cardHolderName = cardHolderName; - this.cardAddress = cardAddress; - this.birthDate = birthDate; - this.startDate = startDate; - this.issueNumber = issueNumber; - } - - @Override - @SuppressWarnings("unchecked") - public void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - boolean methodInvoked = false; - final String methodName = method.getName(); - if (methodName.startsWith("set")) { - if ("setCardNumber".equals(methodName) && cardNumber != null) { - final CardNumber intCardNumber = new CardNumber(); - intCardNumber.setvalue(cardNumber); - method.invoke(targetObject, intCardNumber); - methodInvoked = true; - } - if ("setCvc".equals(methodName) && cvc != null) { - final Cvc intCvc = new Cvc(); - intCvc.setvalue(cvc); - method.invoke(targetObject, intCvc); - methodInvoked = true; - } - if ("setExpiryDate".equals(methodName) && expiryDate != null) { - final ExpiryDate intExpiryDate = new ExpiryDate(); - intExpiryDate.setDate((com.worldpay.internal.model.Date) expiryDate.transformToInternalModel()); - method.invoke(targetObject, intExpiryDate); - methodInvoked = true; - } - if ("setCardHolderName".equals(methodName) && cardHolderName != null) { - final CardHolderName intCardHolderName = new CardHolderName(); - intCardHolderName.setvalue(cardHolderName); - method.invoke(targetObject, intCardHolderName); - methodInvoked = true; - } - if ("setCardAddress".equals(methodName) && cardAddress != null) { - final CardAddress intCardAddress = new CardAddress(); - intCardAddress.setAddress((com.worldpay.internal.model.Address) cardAddress.transformToInternalModel()); - method.invoke(targetObject, intCardAddress); - methodInvoked = true; - } - if ("setBirthDate".equals(methodName) && birthDate != null) { - final BirthDate intBirthDate = new BirthDate(); - intBirthDate.setDate((com.worldpay.internal.model.Date) birthDate.transformToInternalModel()); - method.invoke(targetObject, intBirthDate); - methodInvoked = true; - } - if ("setStartDate".equals(methodName) && startDate != null) { - final StartDate intStartDate = new StartDate(); - intStartDate.setDate((com.worldpay.internal.model.Date) startDate.transformToInternalModel()); - method.invoke(targetObject, intStartDate); - methodInvoked = true; - } - if ("setIssueNumber".equals(methodName) && issueNumber != null) { - final IssueNumber intIssueNumber = new IssueNumber(); - intIssueNumber.setvalue(issueNumber); - method.invoke(targetObject, intIssueNumber); - methodInvoked = true; - } - if ("setBin".equals(methodName) && bin != null) { - method.invoke(targetObject, cvc); - methodInvoked = true; - } - } else if ("getIssueNumberOrStartDate".equals(methodName) && (issueNumber != null || startDate != null)) { - final List issueNumberOrStartDate = (List) method.invoke(targetObject); - if (issueNumber != null) { - final IssueNumber intIssueNumber = new IssueNumber(); - intIssueNumber.setvalue(issueNumber); - issueNumberOrStartDate.add(intIssueNumber); - } - if (startDate != null) { - final StartDate intStartDate = new StartDate(); - intStartDate.setDate((com.worldpay.internal.model.Date) startDate.transformToInternalModel()); - issueNumberOrStartDate.add(intStartDate); - } - methodInvoked = true; - } - - if (!methodInvoked) { - invokeExtraSetters(method, targetObject); - } - } - - /** - * Method to be used by overriding classes in order to ensure that extra fields that they implement get set when the {@link #transformToInternalModel()} method is - * invoked. Default implementation does nothing so just provides the hook for overriding classes - * - * @param method Method that can be invoked on the internal model object targetObject - * @param targetObject internal model object that we are trying to transform to - * @throws IllegalArgumentException if the method is invoked with incorrect parameters - * @throws IllegalAccessException if the method is not accessible - * @throws InvocationTargetException if method cannot be invoked against the supplied target object - */ - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - // Do nothing. This provides a hook for subclasses to add extra functionality - } - - public String getCardNumber() { - return cardNumber; - } - - public void setCardNumber(final String cardNumber) { - this.cardNumber = cardNumber; - } - - public String getCvc() { - return cvc; - } - - public void setCvc(final String cvc) { - this.cvc = cvc; - } - - public Date getExpiryDate() { - return expiryDate; - } - - public void setExpiryDate(final Date expiryDate) { - this.expiryDate = expiryDate; - } - - public String getCardHolderName() { - return cardHolderName; - } - - public void setCardHolderName(final String cardHolderName) { - this.cardHolderName = cardHolderName; - } - - public Address getCardAddress() { - return cardAddress; - } - - public void setCardAddress(final Address cardAddress) { - this.cardAddress = cardAddress; - } - - public Date getBirthDate() { - return birthDate; - } - - public void setBirthDate(final Date birthDate) { - this.birthDate = birthDate; - } - - public Date getStartDate() { - return startDate; - } - - public void setStartDate(final Date startDate) { - this.startDate = startDate; - } - - public String getIssueNumber() { - return issueNumber; - } - - public void setIssueNumber(final String issueNumber) { - this.issueNumber = issueNumber; - } - - public String getBin() { - return bin; - } - - public void setBin(final String bin) { - this.bin = bin; - } - - @Override - public String toString() { - return "Card{" + - "cardNumber='" + cardNumber + '\'' + - ", cvc='" + cvc + '\'' + - ", expiryDate=" + expiryDate + - ", cardHolderName='" + cardHolderName + '\'' + - ", cardAddress=" + cardAddress + - ", birthDate=" + birthDate + - ", startDate=" + startDate + - ", issueNumber='" + issueNumber + '\'' + - ", bin='" + bin + '\'' + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/Cse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/Cse.java deleted file mode 100644 index f2dc2012..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/Cse.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.internal.model.CardAddress; -import com.worldpay.service.model.Address; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import static com.worldpay.service.model.payment.PaymentType.CSEDATA; - -public class Cse extends AbstractPayment { - - private String encryptedData; - private Address address; - - public Cse(final String encryptedData, final Address address) { - this.encryptedData = encryptedData; - this.address = address; - this.paymentType = CSEDATA; - } - - @Override - public void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - final String methodName = method.getName(); - if ("setEncryptedData".equals(methodName) && encryptedData != null) { - method.invoke(targetObject, encryptedData); - } - if ("setCardAddress".equals(methodName) && address != null) { - final CardAddress intCardAddress = new CardAddress(); - intCardAddress.setAddress((com.worldpay.internal.model.Address) address.transformToInternalModel()); - method.invoke(targetObject, intCardAddress); - } - } - - public String getEncryptedData() { - return encryptedData; - } - - public void setEncryptedData(final String encrypedData) { - this.encryptedData = encrypedData; - } - - public Address getAddress() { - return address; - } - - public void setAddress(final Address address) { - this.address = address; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/EnvoyTransferPayment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/EnvoyTransferPayment.java deleted file mode 100644 index dc1a3954..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/EnvoyTransferPayment.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.worldpay.service.model.payment; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * POJO representation of {@link Payment} type for envoy transfer payments - * - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ -public class EnvoyTransferPayment extends AbstractPayment { - - private String shopperCountryCode; - - /** - * Constructor with full list of fields - * - * @param paymentType - * @param shopperCountryCode - * @see PaymentBuilder PaymentBuilder for simple static creation methods - */ - public EnvoyTransferPayment(final PaymentType paymentType, final String shopperCountryCode) { - this.setPaymentType(paymentType); - this.shopperCountryCode = shopperCountryCode; - } - - /** - * (non-Javadoc) - * - * @see com.worldpay.service.model.payment.AbstractPayment#invokeSetter(Method, Object) - */ - @Override - public void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - boolean methodInvoked = false; - final String methodName = method.getName(); - if (methodName.startsWith("set") && "setShopperCountryCode".equals(methodName) && shopperCountryCode != null) { - method.invoke(targetObject, shopperCountryCode); - methodInvoked = true; - } - - if (!methodInvoked) { - invokeExtraSetters(method, targetObject); - } - } - - /** - * Method to be used by overriding classes in order to ensure that extra fields that they implement get set when the {@link #transformToInternalModel()} method is - * invoked. Default implementation does nothing so just provides the hook for overriding classes - * - * @param method Method that can be invoked on the internal model object targetObject - * @param targetObject internal model object that we are trying to transform to - * @throws IllegalArgumentException if the method is invoked with incorrect parameters - * @throws IllegalAccessException if the method is not accessible - * @throws InvocationTargetException if method cannot be invoked against the supplied target object - */ - protected void invokeExtraSetters(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - // Do nothing. This provides a hook for subclasses to add extra functionality - } - - public String getShopperCountryCode() { - return shopperCountryCode; - } - - public void setShopperCountryCode(final String shopperCountryCode) { - this.shopperCountryCode = shopperCountryCode; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "EnvoyTransferPayment [shopperCountryCode=" + shopperCountryCode + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PayAsOrder.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PayAsOrder.java deleted file mode 100644 index efdc0da0..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PayAsOrder.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.service.model.Amount; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -/** - * POJO representation of pay as order payment - */ -public class PayAsOrder implements InternalModelTransformer, Serializable { - - private String originalMerchantCode; - private String originalOrderCode; - private Amount amount; - private String cvc; - - /** - * Constructor with full list of fields - * - * @param originalMerchantCode - * @param originalOrderCode - * @param amount - * @param cvc - */ - public PayAsOrder(final String originalMerchantCode, final String originalOrderCode, final Amount amount, final String cvc) { - this.originalMerchantCode = originalMerchantCode; - this.originalOrderCode = originalOrderCode; - this.amount = amount; - this.cvc = cvc; - } - - @Override - public InternalModelObject transformToInternalModel() throws WorldpayModelTransformationException { - final com.worldpay.internal.model.PayAsOrder intPayAsOrder = new com.worldpay.internal.model.PayAsOrder(); - if (originalMerchantCode != null) { - intPayAsOrder.setMerchantCode(originalMerchantCode); - } - if (originalOrderCode != null) { - intPayAsOrder.setOrderCode(originalOrderCode); - } - if (amount != null) { - intPayAsOrder.setAmount((com.worldpay.internal.model.Amount) amount.transformToInternalModel()); - } - if (cvc != null) { - intPayAsOrder.setCvc(cvc); - } - - return intPayAsOrder; - } - - public String getOriginalMerchantCode() { - return originalMerchantCode; - } - - public void setOriginalMerchantCode(final String originalMerchantCode) { - this.originalMerchantCode = originalMerchantCode; - } - - public String getOriginalOrderCode() { - return originalOrderCode; - } - - public void setOriginalOrderCode(final String originalOrderCode) { - this.originalOrderCode = originalOrderCode; - } - - public Amount getAmount() { - return amount; - } - - public void setAmount(final Amount amount) { - this.amount = amount; - } - - public String getCvc() { - return cvc; - } - - public void setCvc(final String cvc) { - this.cvc = cvc; - } - - /** - * (non-Javadoc) - * - * @see Object#toString() - */ - @Override - public String toString() { - return "PayAsOrder [originalMerchantCode=" + originalMerchantCode + ", originalOrderCode=" + originalOrderCode + ", amount=" + amount + ", cvc=" + cvc - + "]"; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PayWithGoogleSSL.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PayWithGoogleSSL.java deleted file mode 100644 index 7c76c1c9..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PayWithGoogleSSL.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.worldpay.service.model.payment; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class PayWithGoogleSSL extends AbstractPayment { - private String protocolVersion; - private String signature; - private String signedMessage; - - public PayWithGoogleSSL(final String protocolVersion, final String signature, final String signedMessage) { - this.protocolVersion = protocolVersion; - this.signature = signature; - this.signedMessage = signedMessage; - this.setPaymentType(PaymentType.PAYWITHGOOGLESSL); - } - - @Override - public void invokeSetter(final Method method, final Object targetObject) throws IllegalAccessException, InvocationTargetException { - final String methodName = method.getName(); - if ("setProtocolVersion".equals(methodName) && protocolVersion != null) { - method.invoke(targetObject, protocolVersion); - } - if ("setSignature".equals(methodName) && signature != null) { - method.invoke(targetObject, signature); - } - if ("setSignedMessage".equals(methodName) && signedMessage != null) { - method.invoke(targetObject, signedMessage); - } - } - - public String getProtocolVersion() { - return protocolVersion; - } - - public void setProtocolVersion(final String protocolVersion) { - this.protocolVersion = protocolVersion; - } - - public String getSignature() { - return signature; - } - - public void setSignature(final String signature) { - this.signature = signature; - } - - public String getSignedMessage() { - return signedMessage; - } - - public void setSignedMessage(final String signedMessage) { - this.signedMessage = signedMessage; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/Payment.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/Payment.java deleted file mode 100644 index 6d347c28..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/Payment.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -/** - * Interface marker for a Payment object. - */ -public interface Payment extends InternalModelTransformer, Serializable { - - PaymentType getPaymentType(); - - void setPaymentType(final PaymentType paymentType); -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PaymentBuilder.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PaymentBuilder.java deleted file mode 100644 index 734588cd..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PaymentBuilder.java +++ /dev/null @@ -1,1289 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.service.model.Address; -import com.worldpay.service.model.Date; -import com.worldpay.service.model.klarna.KlarnaMerchantUrls; -import com.worldpay.service.model.klarna.KlarnaPayment; -import com.worldpay.service.model.klarna.KlarnaRedirectURLs; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.Token; - -/** - * Convenience class grouping methods that create all the different types of {@link Payment} objects. Provides clean interface with only the required - * parameters for the specific payment methods to be passed - */ -public class PaymentBuilder { - - private PaymentBuilder() { - } - - // Cards - - /** - * Create a CSE payment - * - * @param encryptedData - * @param cardAddress - * @return Cse object - */ - public static Cse createCSE(final String encryptedData, final Address cardAddress) { - return new Cse(encryptedData, cardAddress); - } - - /** - * Create a Visa card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createVISASSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.VISA, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a Mastercard - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createECMCSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.MASTERCARD, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a BHS card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createBHSSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.BHS, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create an IKEA card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createIKEASSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.IKEA, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create an American Express card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createAMEXSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.AMERICAN_EXPRESS, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a Diners Club card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createDINERSSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.DINERS, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a Carte Bancaire card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createCBSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.CARTE_BANCAIRE, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create an Airplus card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createAIRPLUSSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.AIRPLUS, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create an UATP card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createUATPSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.UATP, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a Carte Bleue card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createCARTEBLEUESSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.CARTE_BLEUE, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a SOLO card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @param issueNumber - * @param startDate - * @return Card object - */ - public static Card createSOLOGBSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress, final String issueNumber, final Date startDate) { - return new Card(PaymentType.SOLO, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, startDate, issueNumber, null); - } - - /** - * Create a Laser card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @param startDate - * @return Card object - */ - public static Card createLASERSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress, final Date startDate) { - return new Card(PaymentType.LASER_CARD, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, startDate, null, null); - } - - /** - * Create a Dankort card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createDANKORTSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.DANKORT, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a Discover card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createDISCOVERSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.DISCOVER, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a JCB card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createJCBSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.JCB, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create an Aurore card - * - * @param cardNumber - * @param birthDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createAURORESSL(final String cardNumber, final Date birthDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.AURORE, cardNumber, cvc, null, cardHolderName, cardAddress, birthDate, null, null, null); - } - - /** - * Create a GE Capital card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createGECAPITALSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.GE_CAPITAL, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a Maestro card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @param issueNumber - * @param startDate - * @return Card object - */ - public static Card createMAESTROSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress, final String issueNumber, final Date startDate) { - return new Card(PaymentType.MAESTRO, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, startDate, issueNumber, null); - } - - /** - * Create a Switch card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @param issueNumber - * @param startDate - * @return Card object - */ - public static Card createSWITCHSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress, final String issueNumber, final Date startDate) { - return new Card(PaymentType.SWITCH, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, startDate, issueNumber, null); - } - - /** - * Create a NCPB2B card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createNCPB2BSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.NCPB2B, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a NCP Season card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createNCPSEASONSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.NCPSEASON, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - /** - * Create a Card card - * - * @param cardNumber - * @param expiryDate - * @param cardHolderName - * @param cvc - * @param cardAddress - * @return Card object - */ - public static Card createCARDSSL(final String cardNumber, final Date expiryDate, final String cardHolderName, final String cvc, final Address cardAddress) { - return new Card(PaymentType.CARD_SSL, cardNumber, cvc, expiryDate, cardHolderName, cardAddress, null, null, null, null); - } - - // Bank Accounts - - /** - * Create an ELV bank account - * - * @param accountHolderName - * @param accountNumber - * @param bankName - * @param bankLocation - * @param bankLocationId - * @param birthDate - * @param address - * @return BankAccount object - */ - public static BankAccount createELVSSL(final String accountHolderName, final String accountNumber, final String bankName, final String bankLocation, final String bankLocationId, final Date birthDate, final Address address) { - return new BankAccount(PaymentType.ELV, accountHolderName, accountNumber, bankName, bankLocation, bankLocationId, birthDate, address); - } - - /** - * Create a Payout bank account - * - * @return BankAccount object - */ - public static BankAccount createPAYOUTBANK() { - return new BankAccount(PaymentType.PAYOUT, null, null, null, null, null, null, null); - } - - // Alternative Payment Methods - - /** - * Create a PayPal Express alternative payment - * - * @param firstInBillingRun - * @param successURL - * @param failureURL - * @param cancelURL - * @return AlternativePayment object - */ - public static AlternativePayment createPAYPALEXPRESS(final String firstInBillingRun, final String successURL, final String failureURL, final String cancelURL) { - return new AlternativePayPalPayment(PaymentType.PAYPAL, null, successURL, failureURL, cancelURL, null, firstInBillingRun); - } - - /** - * Create a GIRO pay alternative payment - * - * @param bankCode - * @param successURL - * @param failureURL - * @param cancelURL - * @return AlternativePayment object - */ - public static AlternativePayment createGIROPAYSSL(final String bankCode, final String successURL, final String failureURL, final String cancelURL) { - return new AlternativeBankCodePayment(PaymentType.GIROPAY, null, successURL, failureURL, cancelURL, null, bankCode); - } - - /** - * Create an IDEAL alternative payment - * - * @param shopperBankCode - * @param successURL - * @param failureURL - * @param cancelURL - * @return AlternativePayment object - */ - public static AlternativePayment createIDEALSSL(final String shopperBankCode, final String successURL, final String failureURL, final String cancelURL) { - return new AlternativeShopperBankCodePayment(PaymentType.IDEAL, null, successURL, failureURL, cancelURL, null, shopperBankCode); - } - - /** - * Create an ACH alternative payment - * - * @param achType - * @param firstName - * @param lastName - * @param address - * @param bankAccountType - * @param routingNumber - * @param accountNumber - * @return AchPayment object - */ - public static AchPayment createACHSSL(final AchType achType, final String firstName, final String lastName, final Address address, final String bankAccountType, final String routingNumber, final String accountNumber) { - return new AchPayment(PaymentType.ACH, achType, firstName, lastName, address, bankAccountType, routingNumber, accountNumber); - } - - /** - * Create an ABAQOOS alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createABAQOOSSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.ABAQOOS, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an ALIPAY alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createALIPAYSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.ALIPAY, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an ALIPAY mobile alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createALIPAYMOBILESSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.ALIPAY_MOBILE, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Baloto alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createBALOTOSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.BALOTO, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Billing Partner alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createBILLINGPARTNERSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.BILLINGPARTNER, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a CashU alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createCASHUSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.CASHU, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Dineromail 7Eleven alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createDINEROMAIL7ELEVENSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.DINEROMAIL_7ELEVEN, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Dineromail Oxxo alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createDINEROMAILOXXOSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.DINEROMAIL_OXXO, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an EKONTO alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createEKONTOSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.EKONTO, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an EPay alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createEPAYSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.EPAY, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an Euteller alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createEUTELLERSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.EUTELLER, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an Ewire dk alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createEWIREDKSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.EWIREDK, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an Ewire no alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createEWIRENOSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.EWIRENO, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an Ewire sl alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createEWIRESESSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.EWIRESE, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an Halcash alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createHALCASHSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.HALCASH, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an Instadebit alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createINSTADEBITSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.INSTADEBIT, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Lobanet ar alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createLOBANETARSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.LOBANET_AR, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Lobanet br alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createLOBANETBRSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.LOBANET_BR, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Lobanet cl alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createLOBANETCLSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.LOBANET_CL, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Lobanet mx alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createLOBANETMXSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.LOBANET_MX, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Lobanet pe alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createLOBANETPESSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.LOBANET_PE, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Lobanet uy alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createLOBANETUYSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.LOBANET_UY, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Mister Cash alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createMISTERCASHSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.MISTERCASH, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a MultiBanco alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createMULTIBANCOSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.MULTIBANCO, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Neosurf alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createNEOSURFSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.NEOSURF, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Paga alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createPAGASSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.PAGA, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Paga Serve alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createPAGAVERVESSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.PAGA_VERVE, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Paysafe Card alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createPAYSAFECARDSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.PAYSAFECARD, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a PayU alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createPAYUSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.PAYU, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a PlusPay alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createPLUSPAYSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.PLUSPAY, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Poli alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createPOLISSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.POLI, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Polinz alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createPOLINZSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.POLINZ, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a PostePay alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createPOSTEPAYSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.POSTEPAY, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Przelewy alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createPRZELEWYSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.PRZELEWY, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Qiwi alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createQIWISSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.QIWI, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a SID alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createSIDSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.SID, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Skrill alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createSKRILLSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.SKRILL, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Sofort alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createSOFORTSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.SOFORT, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a SporoPay alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createSPOROPAYSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.SPOROPAY, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Swiff alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @param pan - * @param cvv - * @param expiryDate - * @return AlternativePayment object - */ - public static AlternativePayment createSWIFFSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL, final String pan, final String cvv, final Date expiryDate) { - return new AlternativePanCvvPayment(PaymentType.SWIFF, shopperCountryCode, successURL, null, cancelURL, pendingURL, pan, cvv, expiryDate); - } - - /** - * Create a TeleIngreso alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createTELEINGRESOSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.TELEINGRESO, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a TicketSurf alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createTICKETSURFSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.TICKETSURF, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a TrustPay cz alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createTRUSTPAYCZSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.TRUSTPAY_CZ, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a TrustPay ee alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createTRUSTPAYEESSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.TRUSTPAY_EE, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a TrustPay sk alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createTRUSTPAYSKSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.TRUSTPAY_SK, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a WebMoney alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createWEBMONEYSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.WEBMONEY, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create a Yandex Money alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @return AlternativePayment object - */ - public static AlternativePayment createYANDEXMONEYSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL) { - return new AlternativePayment(PaymentType.YANDEXMONEY, shopperCountryCode, successURL, null, cancelURL, pendingURL); - } - - /** - * Create an AstroPay Card alternative payment - * - * @param shopperCountryCode - * @param successURL - * @param cancelURL - * @param pendingURL - * @param pan - * @param cvv - * @param expiryDate - * @return AlternativePayment object - */ - public static AlternativePayment createASTROPAYCARDSSL(final String shopperCountryCode, final String successURL, final String cancelURL, final String pendingURL, final String pan, final String cvv, final Date expiryDate) { - return new AlternativePanCvvPayment(PaymentType.ASTROPAYCARD, shopperCountryCode, successURL, null, cancelURL, pendingURL, pan, cvv, expiryDate); - } - - // Envoy Transfer Payments - - /** - * Create an AUD envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERAUDBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_AUD, shopperCountryCode); - } - - /** - * Create a CAD envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERCADBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_CAD, shopperCountryCode); - } - - /** - * Create a CHF envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERCHFBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_CHF, shopperCountryCode); - } - - /** - * Create a CZK envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERCZKBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_CZK, shopperCountryCode); - } - - /** - * Create a DKK envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERDKKBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_DKK, shopperCountryCode); - } - - /** - * Create an EUR envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFEREURBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_EUR, shopperCountryCode); - } - - /** - * Create a GBP envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERGBPBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_GBP, shopperCountryCode); - } - - /** - * Create an HKD envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERHKDBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_HKD, shopperCountryCode); - } - - /** - * Create an HUF envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERHUFBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_HUF, shopperCountryCode); - } - - /** - * Create a JPY envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERJPYBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_JPY, shopperCountryCode); - } - - /** - * Create a NOK envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERNOKBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_NOK, shopperCountryCode); - } - - /** - * Create a NZD envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERNZDBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_NZD, shopperCountryCode); - } - - /** - * Create a PLN envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERPLNBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_PLN, shopperCountryCode); - } - - /** - * Create a SEK envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERSEKBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_SEK, shopperCountryCode); - } - - /** - * Create a SGD envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERSGDBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_SGD, shopperCountryCode); - } - - /** - * Create a THB envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERTHBBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_THB, shopperCountryCode); - } - - /** - * Create an USD envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERUSDBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_USD, shopperCountryCode); - } - - /** - * Create a ZAR envoy transfer payment - * - * @param shopperCountryCode - * @return EnvoyTransferPayment object - */ - public static EnvoyTransferPayment createENVOYTRANSFERZARBANK(final String shopperCountryCode) { - return new EnvoyTransferPayment(PaymentType.ENVOY_TRANSFER_ZAR, shopperCountryCode); - } - - /** - * Creates a token with details - * - * @param subscriptionId Subscription id from Worldpay - * @param cvc cvc code of the payment method used - * @param merchantToken if true, the token will have "merchant" scope, otherwise, will be "shopper" scope. - * @return Token object - */ - public static Token createToken(final String subscriptionId, final String cvc, final boolean merchantToken) { - if (cvc != null) { - final CardDetails cardDetails = new CardDetails(); - cardDetails.setCvcNumber(cvc); - return new Token(subscriptionId, cardDetails, merchantToken); - } - return new Token(subscriptionId, merchantToken); - } - - /** - * Creates a Klarna payment type - * - * @param purchaseCountry - * @param shopperLocale - * @param merchantUrls - * @param extraMerchantData - * @return - */ - public static KlarnaPayment createKlarnaPayment(final String purchaseCountry, final String shopperLocale, final KlarnaMerchantUrls merchantUrls, final String extraMerchantData) { - return new KlarnaPayment(purchaseCountry, shopperLocale, merchantUrls, extraMerchantData); - } - - /** - * Creates a Klarna payment type - * - * @param purchaseCountry - * @param shopperLocale - * @param extraMerchantData - * @param klarnaPaymentMethod - * @param klarnaURL - * @return - */ - public static KlarnaPayment createKlarnaPayment(final String purchaseCountry, final String shopperLocale, final String extraMerchantData, - final String klarnaPaymentMethod, final KlarnaRedirectURLs klarnaURL) { - return new KlarnaPayment(purchaseCountry, shopperLocale, extraMerchantData, klarnaPaymentMethod, klarnaURL); - } - -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PaymentType.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PaymentType.java index ccfaea3c..97604f66 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PaymentType.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/PaymentType.java @@ -96,6 +96,7 @@ public enum PaymentType implements Serializable { BANCOSANTANDER("BANCOSANTANDER-SSL", BANCOSANTANDERSSL.class), BOLETO("BOLETO-SSL", BOLETOSSL.class), MONETA("MONETA-SSL", MONETASSL.class), + SEPA("SEPA_DIRECT_DEBIT-SSL", SEPADIRECTDEBITSSL.class), TODITOCARD("TODITOCARD-SSL", TODITOCARDSSL.class), CHINA_UNION_PAY("CHINAUNIONPAY-SSL", CHINAUNIONPAYSSL.class), ENETS("ENETS-SSL", ENETSSSL.class), diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/StoredCredentials.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/StoredCredentials.java deleted file mode 100644 index 39cb0d6b..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/payment/StoredCredentials.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; -import com.worldpay.enums.payment.storedCredentials.Usage; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.util.Optional; - -public class StoredCredentials implements InternalModelTransformer, Serializable { - - private MerchantInitiatedReason merchantInitiatedReason; - private String schemeTransactionIdentifier; - private Usage usage; - - public StoredCredentials() { - } - - public StoredCredentials(final MerchantInitiatedReason merchantInitiatedReason, final String schemeTransactionIdentifier, final Usage usage) { - this.merchantInitiatedReason = merchantInitiatedReason; - this.schemeTransactionIdentifier = schemeTransactionIdentifier; - this.usage = usage; - } - - @Override - public com.worldpay.internal.model.StoredCredentials transformToInternalModel() { - final com.worldpay.internal.model.StoredCredentials intStoredCredentials = new com.worldpay.internal.model.StoredCredentials(); - - Optional.ofNullable(merchantInitiatedReason) - .map(MerchantInitiatedReason::name) - .ifPresent(intStoredCredentials::setMerchantInitiatedReason); - Optional.ofNullable(usage) - .map(Usage::name) - .ifPresent(intStoredCredentials::setUsage); - - intStoredCredentials.setSchemeTransactionIdentifier(schemeTransactionIdentifier); - return intStoredCredentials; - } - - public void setMerchantInitiatedReason(final MerchantInitiatedReason merchantInitiatedReason) { - this.merchantInitiatedReason = merchantInitiatedReason; - } - - public void setSchemeTransactionIdentifier(final String schemeTransactionIdentifier) { - this.schemeTransactionIdentifier = schemeTransactionIdentifier; - } - - public void setUsage(final Usage usage) { - this.usage = usage; - } - - public MerchantInitiatedReason getMerchantInitiatedReason() { - return merchantInitiatedReason; - } - - public String getSchemeTransactionIdentifier() { - return schemeTransactionIdentifier; - } - - public Usage getUsage() { - return usage; - } - -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/Additional3DSData.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/Additional3DSData.java deleted file mode 100644 index bb4a75f4..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/Additional3DSData.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.service.request.transform.InternalModelTransformer; -import com.worldpay.threedsecureflexenums.ChallengePreferenceEnum; -import com.worldpay.threedsecureflexenums.ChallengeWindowSizeEnum; - -import java.io.Serializable; - -public class Additional3DSData implements InternalModelTransformer, Serializable { - private String dfReferenceId; - private ChallengePreferenceEnum challengePreference; - private ChallengeWindowSizeEnum challengeWindowSize; - - public Additional3DSData() { - } - - public Additional3DSData(final String referenceId) { - this.dfReferenceId = referenceId; - } - - @Override - public com.worldpay.internal.model.Additional3DSData transformToInternalModel() { - final com.worldpay.internal.model.Additional3DSData intAdditional3DSData = new com.worldpay.internal.model.Additional3DSData(); - intAdditional3DSData.setDfReferenceId(getDfReferenceId()); - if (challengePreference != null) { - intAdditional3DSData.setChallengePreference(challengePreference.toString()); - } - if (challengeWindowSize != null) { - intAdditional3DSData.setChallengeWindowSize(challengeWindowSize.toString()); - } - - return intAdditional3DSData; - } - - public ChallengePreferenceEnum getChallengePreference() { - return challengePreference; - } - - public void setChallengePreference(final ChallengePreferenceEnum challengePreference) { - this.challengePreference = challengePreference; - } - - public String getDfReferenceId() { - return dfReferenceId; - } - - public void setDfReferenceId(final String dfReferenceId) { - this.dfReferenceId = dfReferenceId; - } - - public ChallengeWindowSizeEnum getChallengeWindowSize() { - return challengeWindowSize; - } - - public void setChallengeWindowSize(final ChallengeWindowSizeEnum challengeWindowSize) { - this.challengeWindowSize = challengeWindowSize; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/AuthenticationRiskData.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/AuthenticationRiskData.java deleted file mode 100644 index 9c799cea..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/AuthenticationRiskData.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.internal.model.AuthenticationTimestamp; -import com.worldpay.service.model.Date; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.util.Optional; - -public class AuthenticationRiskData implements InternalModelTransformer, Serializable { - - private String authenticationMethod; - private Date authenticationTimestamp; - - @Override - public com.worldpay.internal.model.AuthenticationRiskData transformToInternalModel() { - final com.worldpay.internal.model.AuthenticationRiskData internalAuthenticationRiskData = new com.worldpay.internal.model.AuthenticationRiskData(); - internalAuthenticationRiskData.setAuthenticationMethod(authenticationMethod); - Optional.ofNullable(authenticationTimestamp) - .map(Date::transformToInternalModel) - .map(this::createIntAuthenticationTimestamp) - .ifPresent(internalAuthenticationRiskData::setAuthenticationTimestamp); - return internalAuthenticationRiskData; - } - - private AuthenticationTimestamp createIntAuthenticationTimestamp(com.worldpay.internal.model.Date intDate) { - final AuthenticationTimestamp intAuthenticationTimestamp = new AuthenticationTimestamp(); - intAuthenticationTimestamp.setDate(intDate); - return intAuthenticationTimestamp; - } - - public Date getAuthenticationTimestamp() { - return authenticationTimestamp; - } - - public void setAuthenticationTimestamp(final Date authenticationTimestamp) { - this.authenticationTimestamp = authenticationTimestamp; - } - - public String getAuthenticationMethod() { - return authenticationMethod; - } - - public void setAuthenticationMethod(final String authenticationMethod) { - this.authenticationMethod = authenticationMethod; - } - - @Override - public String toString() { - return "AuthenticationRiskData{" + - "authenticationTimestamp=" + authenticationTimestamp + - ", authenticationMethod='" + authenticationMethod + '\'' + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/RiskData.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/RiskData.java deleted file mode 100644 index c42afa64..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/RiskData.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.util.Optional; - -public class RiskData implements InternalModelTransformer, Serializable { - - private TransactionRiskData transactionRiskData; - private ShopperAccountRiskData shopperAccountRiskData; - private AuthenticationRiskData authenticationRiskData; - - @Override - public com.worldpay.internal.model.RiskData transformToInternalModel() throws WorldpayModelTransformationException { - final var internalRiskData = new com.worldpay.internal.model.RiskData(); - Optional.ofNullable(authenticationRiskData) - .map(AuthenticationRiskData::transformToInternalModel) - .ifPresent(internalRiskData::setAuthenticationRiskData); - - Optional.ofNullable(shopperAccountRiskData) - .map(ShopperAccountRiskData::transformToInternalModel) - .ifPresent(internalRiskData::setShopperAccountRiskData); - - Optional.ofNullable(transactionRiskData) - .map(TransactionRiskData::transformToInternalModel) - .ifPresent(internalRiskData::setTransactionRiskData); - - return internalRiskData; - } - - public TransactionRiskData getTransactionRiskData() { - return transactionRiskData; - } - - public void setTransactionRiskData(TransactionRiskData transactionRiskData) { - this.transactionRiskData = transactionRiskData; - } - - public ShopperAccountRiskData getShopperAccountRiskData() { - return shopperAccountRiskData; - } - - public void setShopperAccountRiskData(ShopperAccountRiskData shopperAccountRiskData) { - this.shopperAccountRiskData = shopperAccountRiskData; - } - - public AuthenticationRiskData getAuthenticationRiskData() { - return authenticationRiskData; - } - - public void setAuthenticationRiskData(AuthenticationRiskData authenticationRiskData) { - this.authenticationRiskData = authenticationRiskData; - } - - @Override - public String toString() { - return "RiskData{" + - "transactionRiskData=" + transactionRiskData + - ", shopperAccountRiskData=" + shopperAccountRiskData + - ", authenticationRiskData=" + authenticationRiskData + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/ShopperAccountRiskData.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/ShopperAccountRiskData.java deleted file mode 100644 index c9871621..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/ShopperAccountRiskData.java +++ /dev/null @@ -1,248 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.internal.model.*; -import com.worldpay.service.model.Date; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.util.Optional; - -public class ShopperAccountRiskData implements InternalModelTransformer, Serializable { - - private String shopperAccountAgeIndicator; - private String transactionsAttemptedLastDay; - private String shopperAccountPaymentAccountIndicator; - private String shopperAccountChangeIndicator; - private String shopperAccountPasswordChangeIndicator; - private String previousSuspiciousActivity; - private String addCardAttemptsLastDay; - private String transactionsAttemptedLastYear; - private String purchasesCompletedLastSixMonths; - private String shopperAccountShippingAddressUsageIndicator; - private String shippingNameMatchesAccountName; - - private Date shopperAccountCreationDate; - private Date shopperAccountShippingAddressFirstUseDate; - private Date shopperAccountModificationDate; - private Date shopperAccountPaymentAccountFirstUseDate; - private Date shopperAccountPasswordChangeDate; - - @Override - public com.worldpay.internal.model.ShopperAccountRiskData transformToInternalModel() { - final var internalShopperAccountRiskData = new com.worldpay.internal.model.ShopperAccountRiskData(); - internalShopperAccountRiskData.setTransactionsAttemptedLastDay(transactionsAttemptedLastDay); - internalShopperAccountRiskData.setTransactionsAttemptedLastYear(transactionsAttemptedLastYear); - internalShopperAccountRiskData.setPurchasesCompletedLastSixMonths(purchasesCompletedLastSixMonths); - internalShopperAccountRiskData.setAddCardAttemptsLastDay(addCardAttemptsLastDay); - internalShopperAccountRiskData.setPreviousSuspiciousActivity(previousSuspiciousActivity); - internalShopperAccountRiskData.setShippingNameMatchesAccountName(shippingNameMatchesAccountName); - internalShopperAccountRiskData.setShopperAccountAgeIndicator(shopperAccountAgeIndicator); - internalShopperAccountRiskData.setShopperAccountChangeIndicator(shopperAccountChangeIndicator); - internalShopperAccountRiskData.setShopperAccountPasswordChangeIndicator(shopperAccountPasswordChangeIndicator); - internalShopperAccountRiskData.setShopperAccountShippingAddressUsageIndicator(shopperAccountShippingAddressUsageIndicator); - internalShopperAccountRiskData.setShopperAccountPaymentAccountIndicator(shopperAccountPaymentAccountIndicator); - - Optional.ofNullable(shopperAccountCreationDate) - .map(this::createShopperAccountCreationDate) - .ifPresent(internalShopperAccountRiskData::setShopperAccountCreationDate); - - Optional.ofNullable(shopperAccountShippingAddressFirstUseDate) - .map(this::createShopperAccountShippingAddressFirstUseDate) - .ifPresent(internalShopperAccountRiskData::setShopperAccountShippingAddressFirstUseDate); - - Optional.ofNullable(shopperAccountModificationDate) - .map(this::createShopperAccountModificationDate) - .ifPresent(internalShopperAccountRiskData::setShopperAccountModificationDate); - - Optional.ofNullable(shopperAccountPaymentAccountFirstUseDate) - .map(this::createShopperAccountPaymentAccountFirstUseDate) - .ifPresent(internalShopperAccountRiskData::setShopperAccountPaymentAccountFirstUseDate); - - Optional.ofNullable(shopperAccountPasswordChangeDate) - .map(this::createShopperAccountPasswordChangeDate) - .ifPresent(internalShopperAccountRiskData::setShopperAccountPasswordChangeDate); - - return internalShopperAccountRiskData; - } - - private ShopperAccountCreationDate createShopperAccountCreationDate(final Date shopperAccountCreationDate) { - final ShopperAccountCreationDate internalShopperAccountCreationDate = new ShopperAccountCreationDate(); - internalShopperAccountCreationDate.setDate(shopperAccountCreationDate.transformToInternalModel()); - return internalShopperAccountCreationDate; - } - - private ShopperAccountModificationDate createShopperAccountModificationDate(final Date shopperAccountModificationDate) { - final ShopperAccountModificationDate internalShopperAccountModificationDate = new ShopperAccountModificationDate(); - internalShopperAccountModificationDate.setDate(shopperAccountModificationDate.transformToInternalModel()); - return internalShopperAccountModificationDate; - } - - private ShopperAccountPasswordChangeDate createShopperAccountPasswordChangeDate(final Date shopperAccountPasswordChangeDate) { - final ShopperAccountPasswordChangeDate internalShopperAccountPasswordChangeDate = new ShopperAccountPasswordChangeDate(); - internalShopperAccountPasswordChangeDate.setDate(shopperAccountPasswordChangeDate.transformToInternalModel()); - return internalShopperAccountPasswordChangeDate; - } - - private ShopperAccountShippingAddressFirstUseDate createShopperAccountShippingAddressFirstUseDate(final Date shopperAccountShippingAddressFirstUseDate) { - final ShopperAccountShippingAddressFirstUseDate internalShopperAccountShippingAddressFirstUseDate = new ShopperAccountShippingAddressFirstUseDate(); - internalShopperAccountShippingAddressFirstUseDate.setDate(shopperAccountShippingAddressFirstUseDate.transformToInternalModel()); - return internalShopperAccountShippingAddressFirstUseDate; - } - - private ShopperAccountPaymentAccountFirstUseDate createShopperAccountPaymentAccountFirstUseDate(final Date shopperAccountPaymentAccountFirstUseDate) { - final ShopperAccountPaymentAccountFirstUseDate internalShopperAccountPaymentAccountFirstUseDate = new ShopperAccountPaymentAccountFirstUseDate(); - internalShopperAccountPaymentAccountFirstUseDate.setDate(shopperAccountPaymentAccountFirstUseDate.transformToInternalModel()); - return internalShopperAccountPaymentAccountFirstUseDate; - } - - public String getShopperAccountAgeIndicator() { - return shopperAccountAgeIndicator; - } - - public void setShopperAccountAgeIndicator(String shopperAccountAgeIndicator) { - this.shopperAccountAgeIndicator = shopperAccountAgeIndicator; - } - - public String getTransactionsAttemptedLastDay() { - return transactionsAttemptedLastDay; - } - - public void setTransactionsAttemptedLastDay(String transactionsAttemptedLastDay) { - this.transactionsAttemptedLastDay = transactionsAttemptedLastDay; - } - - public String getShopperAccountPaymentAccountIndicator() { - return shopperAccountPaymentAccountIndicator; - } - - public void setShopperAccountPaymentAccountIndicator(String shopperAccountPaymentAccountIndicator) { - this.shopperAccountPaymentAccountIndicator = shopperAccountPaymentAccountIndicator; - } - - public String getShopperAccountChangeIndicator() { - return shopperAccountChangeIndicator; - } - - public void setShopperAccountChangeIndicator(String shopperAccountChangeIndicator) { - this.shopperAccountChangeIndicator = shopperAccountChangeIndicator; - } - - public String getShopperAccountPasswordChangeIndicator() { - return shopperAccountPasswordChangeIndicator; - } - - public void setShopperAccountPasswordChangeIndicator(String shopperAccountPasswordChangeIndicator) { - this.shopperAccountPasswordChangeIndicator = shopperAccountPasswordChangeIndicator; - } - - public String getPreviousSuspiciousActivity() { - return previousSuspiciousActivity; - } - - public void setPreviousSuspiciousActivity(String previousSuspiciousActivity) { - this.previousSuspiciousActivity = previousSuspiciousActivity; - } - - public String getAddCardAttemptsLastDay() { - return addCardAttemptsLastDay; - } - - public void setAddCardAttemptsLastDay(String addCardAttemptsLastDay) { - this.addCardAttemptsLastDay = addCardAttemptsLastDay; - } - - public String getTransactionsAttemptedLastYear() { - return transactionsAttemptedLastYear; - } - - public void setTransactionsAttemptedLastYear(String transactionsAttemptedLastYear) { - this.transactionsAttemptedLastYear = transactionsAttemptedLastYear; - } - - public String getPurchasesCompletedLastSixMonths() { - return purchasesCompletedLastSixMonths; - } - - public void setPurchasesCompletedLastSixMonths(String purchasesCompletedLastSixMonths) { - this.purchasesCompletedLastSixMonths = purchasesCompletedLastSixMonths; - } - - public String getShopperAccountShippingAddressUsageIndicator() { - return shopperAccountShippingAddressUsageIndicator; - } - - public void setShopperAccountShippingAddressUsageIndicator(String shopperAccountShippingAddressUsageIndicator) { - this.shopperAccountShippingAddressUsageIndicator = shopperAccountShippingAddressUsageIndicator; - } - - public String getShippingNameMatchesAccountName() { - return shippingNameMatchesAccountName; - } - - public void setShippingNameMatchesAccountName(String shippingNameMatchesAccountName) { - this.shippingNameMatchesAccountName = shippingNameMatchesAccountName; - } - - public Date getShopperAccountCreationDate() { - return shopperAccountCreationDate; - } - - public void setShopperAccountCreationDate(Date shopperAccountCreationDate) { - this.shopperAccountCreationDate = shopperAccountCreationDate; - } - - public Date getShopperAccountShippingAddressFirstUseDate() { - return shopperAccountShippingAddressFirstUseDate; - } - - public void setShopperAccountShippingAddressFirstUseDate(Date shopperAccountShippingAddressFirstUseDate) { - this.shopperAccountShippingAddressFirstUseDate = shopperAccountShippingAddressFirstUseDate; - } - - public Date getShopperAccountModificationDate() { - return shopperAccountModificationDate; - } - - public void setShopperAccountModificationDate(Date shopperAccountModificationDate) { - this.shopperAccountModificationDate = shopperAccountModificationDate; - } - - public Date getShopperAccountPaymentAccountFirstUseDate() { - return shopperAccountPaymentAccountFirstUseDate; - } - - public void setShopperAccountPaymentAccountFirstUseDate(Date shopperAccountPaymentAccountFirstUseDate) { - this.shopperAccountPaymentAccountFirstUseDate = shopperAccountPaymentAccountFirstUseDate; - } - - public Date getShopperAccountPasswordChangeDate() { - return shopperAccountPasswordChangeDate; - } - - public void setShopperAccountPasswordChangeDate(Date shopperAccountPasswordChangeDate) { - this.shopperAccountPasswordChangeDate = shopperAccountPasswordChangeDate; - } - - @Override - public String toString() { - return "ShopperAccountRiskData{" + - "shopperAccountAgeIndicator='" + shopperAccountAgeIndicator + '\'' + - ", transactionsAttemptedLastDay='" + transactionsAttemptedLastDay + '\'' + - ", shopperAccountPaymentAccountIndicator='" + shopperAccountPaymentAccountIndicator + '\'' + - ", shopperAccountShippingAddressFirstUseDate=" + shopperAccountShippingAddressFirstUseDate + - ", shopperAccountModificationDate=" + shopperAccountModificationDate + - ", shopperAccountChangeIndicator='" + shopperAccountChangeIndicator + '\'' + - ", shopperAccountPasswordChangeIndicator='" + shopperAccountPasswordChangeIndicator + '\'' + - ", shopperAccountPaymentAccountFirstUseDate=" + shopperAccountPaymentAccountFirstUseDate + - ", previousSuspiciousActivity='" + previousSuspiciousActivity + '\'' + - ", shopperAccountPasswordChangeDate=" + shopperAccountPasswordChangeDate + - ", addCardAttemptsLastDay='" + addCardAttemptsLastDay + '\'' + - ", transactionsAttemptedLastYear='" + transactionsAttemptedLastYear + '\'' + - ", purchasesCompletedLastSixMonths='" + purchasesCompletedLastSixMonths + '\'' + - ", shopperAccountShippingAddressUsageIndicator='" + shopperAccountShippingAddressUsageIndicator + '\'' + - ", shopperAccountCreationDate=" + shopperAccountCreationDate + - ", shippingNameMatchesAccountName='" + shippingNameMatchesAccountName + '\'' + - '}'; - } - -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/TransactionRiskData.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/TransactionRiskData.java deleted file mode 100644 index 0f23ca07..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/TransactionRiskData.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.internal.model.TransactionRiskDataPreOrderDate; -import com.worldpay.service.model.Date; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.util.Optional; - -public class TransactionRiskData implements InternalModelTransformer, Serializable { - - private String deliveryTimeframe; - private String deliveryEmailAddress; - private String preOrderPurchase; - private String shippingMethod; - private String giftCardCount; - private String reorderingPreviousPurchases; - - private Date transactionRiskDataPreOrderDate; - private TransactionRiskDataGiftCardAmount transactionRiskDataGiftCardAmount; - - @Override - public com.worldpay.internal.model.TransactionRiskData transformToInternalModel() { - final var intTransactionRiskData = new com.worldpay.internal.model.TransactionRiskData(); - intTransactionRiskData.setDeliveryEmailAddress(deliveryEmailAddress); - intTransactionRiskData.setDeliveryTimeframe(deliveryTimeframe); - intTransactionRiskData.setGiftCardCount(giftCardCount); - intTransactionRiskData.setPreOrderPurchase(preOrderPurchase); - intTransactionRiskData.setReorderingPreviousPurchases(reorderingPreviousPurchases); - intTransactionRiskData.setShippingMethod(shippingMethod); - - Optional.ofNullable(transactionRiskDataPreOrderDate) - .map(Date::transformToInternalModel) - .map(this::createTransactionRiskDataPreorderDate) - .ifPresent(intTransactionRiskData::setTransactionRiskDataPreOrderDate); - - Optional.ofNullable(transactionRiskDataGiftCardAmount) - .map(TransactionRiskDataGiftCardAmount::transformToInternalModel) - .ifPresent(intTransactionRiskData::setTransactionRiskDataGiftCardAmount); - - return intTransactionRiskData; - } - - private TransactionRiskDataPreOrderDate createTransactionRiskDataPreorderDate(final com.worldpay.internal.model.Date transactionDataPreorderDate) { - final TransactionRiskDataPreOrderDate intTransactionRiskDataPreOrderDate = new TransactionRiskDataPreOrderDate(); - intTransactionRiskDataPreOrderDate.setDate(transactionDataPreorderDate); - return intTransactionRiskDataPreOrderDate; - } - - public String getDeliveryTimeframe() { - return deliveryTimeframe; - } - - public void setDeliveryTimeframe(final String deliveryTimeframe) { - this.deliveryTimeframe = deliveryTimeframe; - } - - public String getDeliveryEmailAddress() { - return deliveryEmailAddress; - } - - public void setDeliveryEmailAddress(final String deliveryEmailAddress) { - this.deliveryEmailAddress = deliveryEmailAddress; - } - - public String getPreOrderPurchase() { - return preOrderPurchase; - } - - public void setPreOrderPurchase(final String preOrderPurchase) { - this.preOrderPurchase = preOrderPurchase; - } - - public String getShippingMethod() { - return shippingMethod; - } - - public void setShippingMethod(final String shippingMethod) { - this.shippingMethod = shippingMethod; - } - - public Date getTransactionRiskDataPreOrderDate() { - return transactionRiskDataPreOrderDate; - } - - public void setTransactionRiskDataPreOrderDate(final Date transactionRiskDataPreOrderDate) { - this.transactionRiskDataPreOrderDate = transactionRiskDataPreOrderDate; - } - - public String getGiftCardCount() { - return giftCardCount; - } - - public void setGiftCardCount(final String giftCardCount) { - this.giftCardCount = giftCardCount; - } - - public TransactionRiskDataGiftCardAmount getTransactionRiskDataGiftCardAmount() { - return transactionRiskDataGiftCardAmount; - } - - public void setTransactionRiskDataGiftCardAmount(final TransactionRiskDataGiftCardAmount transactionRiskDataGiftCardAmount) { - this.transactionRiskDataGiftCardAmount = transactionRiskDataGiftCardAmount; - } - - public String getReorderingPreviousPurchases() { - return reorderingPreviousPurchases; - } - - public void setReorderingPreviousPurchases(final String reorderingPreviousPurchases) { - this.reorderingPreviousPurchases = reorderingPreviousPurchases; - } - - @Override - public String toString() { - return "TransactionRiskData{" + - "deliveryTimeframe='" + deliveryTimeframe + '\'' + - ", deliveryEmailAddress='" + deliveryEmailAddress + '\'' + - ", preOrderPurchase='" + preOrderPurchase + '\'' + - ", shippingMethod='" + shippingMethod + '\'' + - ", transactionRiskDataPreOrderDate=" + transactionRiskDataPreOrderDate + - ", giftCardCount='" + giftCardCount + '\'' + - ", transactionRiskDataGiftCardAmount=" + transactionRiskDataGiftCardAmount + - ", reorderingPreviousPurchases='" + reorderingPreviousPurchases + '\'' + - '}'; - } - - -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/TransactionRiskDataGiftCardAmount.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/TransactionRiskDataGiftCardAmount.java deleted file mode 100644 index 5efc30e1..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/threeds2/TransactionRiskDataGiftCardAmount.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.service.model.Amount; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -public class TransactionRiskDataGiftCardAmount implements InternalModelTransformer, Serializable { - - private Amount amount; - - @Override - public com.worldpay.internal.model.TransactionRiskDataGiftCardAmount transformToInternalModel() { - final var intTransactionRiskDataGiftCardAmount = new com.worldpay.internal.model.TransactionRiskDataGiftCardAmount(); - intTransactionRiskDataGiftCardAmount.setAmount(amount.transformToInternalModel()); - return intTransactionRiskDataGiftCardAmount; - } - - public Amount getAmount() { - return amount; - } - - public void setAmount(final Amount amount) { - this.amount = amount; - } - - @Override - public String toString() { - return "TransactionRiskDataGiftCardAmount{" + - "amount=" + amount + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/CardDetails.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/CardDetails.java deleted file mode 100644 index 17dedf47..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/CardDetails.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.*; -import com.worldpay.service.model.Address; -import com.worldpay.service.model.Date; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -public class CardDetails implements InternalModelTransformer, Serializable { - - private String cardHolderName; - private String cvcNumber; - private String cardBrand; - private String cardSubBrand; - private String issuerCountryCode; - private String cardNumber; - private Date expiryDate; - private Address cardAddress; - - @Override - public InternalModelObject transformToInternalModel() { - final com.worldpay.internal.model.CardDetails intCardDetails = new com.worldpay.internal.model.CardDetails(); - - if (cvcNumber != null) { - final Cvc intCvc = new Cvc(); - intCvc.setvalue(cvcNumber); - intCardDetails.setCvc(intCvc); - } - - if (cardAddress != null) { - final CardAddress intCardAddress = new CardAddress(); - intCardAddress.setAddress((com.worldpay.internal.model.Address) cardAddress.transformToInternalModel()); - intCardDetails.setCardAddress(intCardAddress); - } - if (cardHolderName != null) { - final CardHolderName intCardHolderName = new CardHolderName(); - intCardHolderName.setvalue(cardHolderName); - intCardDetails.setCardHolderName(intCardHolderName); - } - - if (expiryDate != null) { - final ExpiryDate intExpiryDate = new ExpiryDate(); - intExpiryDate.setDate((com.worldpay.internal.model.Date) expiryDate.transformToInternalModel()); - intCardDetails.setExpiryDate(intExpiryDate); - } - - if(cardNumber != null) { - final Derived intDerived = new Derived(); - intDerived.setObfuscatedPAN(cardNumber); - intDerived.setIssuerCountryCode(issuerCountryCode); - intDerived.setCardSubBrand(cardSubBrand); - intDerived.setCardBrand(cardBrand); - intCardDetails.setDerived(intDerived); - } - - return intCardDetails; - } - - public String getCardNumber() { - return cardNumber; - } - - public void setCardNumber(String cardNumber) { - this.cardNumber = cardNumber; - } - - public String getIssuerCountryCode() { - return issuerCountryCode; - } - - public void setIssuerCountryCode(String issuerCountryCode) { - this.issuerCountryCode = issuerCountryCode; - } - - public String getCardSubBrand() { - return cardSubBrand; - } - - public void setCardSubBrand(String cardSubBrand) { - this.cardSubBrand = cardSubBrand; - } - - public Date getExpiryDate() { - return expiryDate; - } - - public void setExpiryDate(final Date expiryDate) { - this.expiryDate = expiryDate; - } - - public String getCardHolderName() { - return cardHolderName; - } - - public void setCardHolderName(final String cardHolderName) { - this.cardHolderName = cardHolderName; - } - - public String getCvcNumber() { - return cvcNumber; - } - - public void setCvcNumber(final String cvcNumber) { - this.cvcNumber = cvcNumber; - } - - public Address getCardAddress() { - return cardAddress; - } - - public void setCardAddress(final Address cardAddress) { - this.cardAddress = cardAddress; - } - - public String getCardBrand() { - return cardBrand; - } - - public void setCardBrand(final String cardBrand) { - this.cardBrand = cardBrand; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/CardTokenRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/CardTokenRequest.java deleted file mode 100644 index f11893fa..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/CardTokenRequest.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.worldpay.service.model.token; - - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.AuthenticatedShopperID; -import com.worldpay.internal.model.CreateToken; -import com.worldpay.internal.model.PaymentTokenCreate; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.util.Optional; - -public class CardTokenRequest implements InternalModelTransformer, Serializable { - - private TokenRequest tokenRequest; - private String authenticatedShopperId; - private Payment payment; - private StoredCredentials storedCredentials; - - public CardTokenRequest(final TokenRequest tokenRequest, final String authenticatedShopperId, final Payment payment, final StoredCredentials storedCredentials) { - this.tokenRequest = tokenRequest; - this.authenticatedShopperId = authenticatedShopperId; - this.payment = payment; - this.storedCredentials = storedCredentials; - } - - public CardTokenRequest(final TokenRequest tokenRequest, final String authenticatedShopperId, final Payment payment) { - this.tokenRequest = tokenRequest; - this.authenticatedShopperId = authenticatedShopperId; - this.payment = payment; - } - - public CardTokenRequest(final TokenRequest tokenRequest, final Payment payment) { - this.tokenRequest = tokenRequest; - this.payment = payment; - } - - @Override - public InternalModelObject transformToInternalModel() throws WorldpayModelTransformationException { - final PaymentTokenCreate paymentTokenCreate = new PaymentTokenCreate(); - - Optional.ofNullable(authenticatedShopperId) - .map(shopperId -> { - final AuthenticatedShopperID intAuthenticatedShopperID = new AuthenticatedShopperID(); - intAuthenticatedShopperID.setvalue(shopperId); - return intAuthenticatedShopperID; - }) - .ifPresent(paymentTokenCreate::setAuthenticatedShopperID); - - Optional.ofNullable(tokenRequest) - .map(TokenRequest::transformToInternalModel) - .map(CreateToken.class::cast) - .ifPresent(paymentTokenCreate::setCreateToken); - - Optional.ofNullable(storedCredentials) - .map(StoredCredentials::transformToInternalModel) - .ifPresent(paymentTokenCreate::setStoredCredentials); - - paymentTokenCreate.getPaymentInstrumentOrCSEDATA().add(payment.transformToInternalModel()); - return paymentTokenCreate; - } - - public TokenRequest getTokenRequest() { - return tokenRequest; - } - - public String getAuthenticatedShopperId() { - return authenticatedShopperId; - } - - public Payment getPayment() { - return payment; - } - - public void setTokenRequest(final TokenRequest tokenRequest) { - this.tokenRequest = tokenRequest; - } - - public void setAuthenticatedShopperId(final String authenticatedShopperId) { - this.authenticatedShopperId = authenticatedShopperId; - } - - public void setPayment(final Payment payment) { - this.payment = payment; - } - - public StoredCredentials getStoredCredentials() { - return storedCredentials; - } - - public void setStoredCredentials(final StoredCredentials storedCredentials) { - this.storedCredentials = storedCredentials; - } - - @Override - public String toString() { - return "CardTokenRequest{" + - "tokenRequest=" + tokenRequest + - ", authenticatedShopperId='" + authenticatedShopperId + '\'' + - ", payment=" + payment + - ", storedCredentials=" + storedCredentials + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/DeleteTokenReply.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/DeleteTokenReply.java deleted file mode 100644 index 2a6b6b12..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/DeleteTokenReply.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.worldpay.service.model.token; - -public class DeleteTokenReply { - - private String paymentTokenId; - - public String getPaymentTokenId() { - return paymentTokenId; - } - - public void setPaymentTokenId(final String paymentTokenId) { - this.paymentTokenId = paymentTokenId; - } - -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/DeleteTokenRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/DeleteTokenRequest.java deleted file mode 100644 index 0276562a..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/DeleteTokenRequest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.AuthenticatedShopperID; -import com.worldpay.internal.model.PaymentTokenDelete; -import com.worldpay.internal.model.PaymentTokenID; -import com.worldpay.internal.model.TokenReason; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.util.Optional; - -public class DeleteTokenRequest implements InternalModelTransformer, Serializable { - - private String authenticatedShopperId; - private String paymentTokenId; - private TokenRequest tokenRequest; - - public DeleteTokenRequest(final String paymentTokenId, final String authenticatedShopperId, final TokenRequest tokenRequest) { - this.authenticatedShopperId = authenticatedShopperId; - this.tokenRequest = tokenRequest; - this.paymentTokenId = paymentTokenId; - } - - @Override - public InternalModelObject transformToInternalModel() { - final PaymentTokenDelete intPaymentTokenDelete = new PaymentTokenDelete(); - if (tokenRequest.isMerchantToken()) { - intPaymentTokenDelete.setTokenScope("merchant"); - } - Optional.ofNullable(authenticatedShopperId) - .map(shopperId -> { - final AuthenticatedShopperID authenticatedShopperID = new AuthenticatedShopperID(); - authenticatedShopperID.setvalue(shopperId); - return authenticatedShopperID; - }) - .ifPresent(intPaymentTokenDelete::setAuthenticatedShopperID); - - final PaymentTokenID paymentTokenIDWrapper = new PaymentTokenID(); - paymentTokenIDWrapper.setvalue(paymentTokenId); - intPaymentTokenDelete.setPaymentTokenID(paymentTokenIDWrapper); - intPaymentTokenDelete.setTokenEventReference(tokenRequest.getTokenEventReference()); - - final TokenReason tokenReason = new TokenReason(); - tokenReason.setvalue(tokenRequest.getTokenReason()); - intPaymentTokenDelete.setTokenReason(tokenReason); - - return intPaymentTokenDelete; - } - - public String getAuthenticatedShopperId() { - return authenticatedShopperId; - } - - public void setAuthenticatedShopperId(final String authenticatedShopperId) { - this.authenticatedShopperId = authenticatedShopperId; - } - - public TokenRequest getTokenRequest() { - return tokenRequest; - } - - public void setTokenReason(final TokenRequest tokenRequest) { - this.tokenRequest = tokenRequest; - } - - public String getPaymentTokenId() { - return paymentTokenId; - } - - public void setPaymentTokenId(final String paymentTokenId) { - this.paymentTokenId = paymentTokenId; - } - -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/Token.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/Token.java deleted file mode 100644 index 84c5ebab..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/Token.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.PaymentInstrument; -import com.worldpay.internal.model.PaymentTokenID; -import com.worldpay.internal.model.TOKENSSL; -import com.worldpay.service.model.payment.AbstractPayment; - -import java.lang.reflect.Method; -import java.util.List; - -import static com.worldpay.service.model.payment.PaymentType.TOKENSSL; - -public class Token extends AbstractPayment { - - private String paymentTokenID; - private CardDetails paymentInstrument; - private boolean merchantToken; - - public Token(final String paymentTokenID, final boolean merchantToken) { - this.paymentTokenID = paymentTokenID; - this.paymentType = TOKENSSL; - this.merchantToken = merchantToken; - } - - public Token(final String paymentTokenID, final CardDetails paymentInstrument, final boolean merchantToken) { - this.paymentTokenID = paymentTokenID; - this.paymentInstrument = paymentInstrument; - this.merchantToken = merchantToken; - this.paymentType = TOKENSSL; - } - - @Override - public InternalModelObject transformToInternalModel() { - final TOKENSSL tokenssl = new TOKENSSL(); - tokenssl.setTokenScope(merchantToken ? "merchant" : "shopper"); - - final List tokenElements = tokenssl.getPaymentTokenIDOrPaymentInstrumentOrCvcOrSession(); - if (paymentTokenID != null) { - final PaymentTokenID paymentTokenIDElement = new PaymentTokenID(); - paymentTokenIDElement.setvalue(paymentTokenID); - tokenElements.add(paymentTokenIDElement); - } - if (paymentInstrument != null) { - final PaymentInstrument intPaymentInstrument = new PaymentInstrument(); - final com.worldpay.internal.model.CardDetails intCardDetails = (com.worldpay.internal.model.CardDetails) paymentInstrument.transformToInternalModel(); - intPaymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().add(intCardDetails); - tokenElements.add(intPaymentInstrument); - } - - return tokenssl; - } - - @Override - public void invokeSetter(final Method method, final Object targetObject) { - // DO nothing - } - - public String getPaymentTokenID() { - return paymentTokenID; - } - - public void setPaymentTokenID(final String paymentTokenID) { - this.paymentTokenID = paymentTokenID; - } - - public CardDetails getPaymentInstrument() { - return paymentInstrument; - } - - public void setPaymentInstrument(CardDetails paymentInstrument) { - this.paymentInstrument = paymentInstrument; - } - - public boolean isMerchantToken() { - return merchantToken; - } - - public void setMerchantToken(final boolean merchantToken) { - this.merchantToken = merchantToken; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/TokenDetails.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/TokenDetails.java deleted file mode 100644 index f70e2568..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/TokenDetails.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.service.model.Date; - -import java.io.Serializable; - -public class TokenDetails implements Serializable { - - private String tokenEvent; - private String paymentTokenID; - private String reportingTokenID; - private String tokenReason; - private String tokenEventReference; - private Date paymentTokenExpiry; - private Date reportingTokenExpiry; - - public String getTokenEvent() { - return tokenEvent; - } - - public void setTokenEvent(final String tokenEvent) { - this.tokenEvent = tokenEvent; - } - - public String getPaymentTokenID() { - return paymentTokenID; - } - - public void setPaymentTokenID(final String paymentTokenID) { - this.paymentTokenID = paymentTokenID; - } - - public String getReportingTokenID() { - return reportingTokenID; - } - - public void setReportingTokenID(final String reportingTokenID) { - this.reportingTokenID = reportingTokenID; - } - - public String getTokenReason() { - return tokenReason; - } - - public void setTokenReason(final String tokenReason) { - this.tokenReason = tokenReason; - } - - public String getTokenEventReference() { - return tokenEventReference; - } - - public void setTokenEventReference(final String tokenEventReference) { - this.tokenEventReference = tokenEventReference; - } - - public Date getPaymentTokenExpiry() { - return paymentTokenExpiry; - } - - public void setPaymentTokenExpiry(final Date paymentTokenExpiry) { - this.paymentTokenExpiry = paymentTokenExpiry; - } - - public Date getReportingTokenExpiry() { - return reportingTokenExpiry; - } - - public void setReportingTokenExpiry(final Date reportingTokenExpiry) { - this.reportingTokenExpiry = reportingTokenExpiry; - } - - @Override - public String toString() { - return "TokenDetails{" + - "tokenEvent='" + tokenEvent + '\'' + - ", paymentTokenID='" + paymentTokenID + '\'' + - ", reportingTokenID='" + reportingTokenID + '\'' + - ", tokenReason='" + tokenReason + '\'' + - ", tokenEventReference='" + tokenEventReference + '\'' + - ", paymentTokenExpiry=" + paymentTokenExpiry + - ", reportingTokenExpiry=" + reportingTokenExpiry + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/TokenReply.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/TokenReply.java deleted file mode 100644 index 59599e6b..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/TokenReply.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.service.model.ErrorDetail; -import com.worldpay.service.model.payment.Card; - -import java.io.Serializable; - -public class TokenReply implements Serializable { - - private String authenticatedShopperID; - private String tokenEventReference; - private String tokenReason; - private TokenDetails tokenDetails; - private Card paymentInstrument; - private ErrorDetail error; - - public String getAuthenticatedShopperID() { - return authenticatedShopperID; - } - - public void setAuthenticatedShopperID(String authenticatedShopperID) { - this.authenticatedShopperID = authenticatedShopperID; - } - - public String getTokenEventReference() { - return tokenEventReference; - } - - public void setTokenEventReference(String tokenEventReference) { - this.tokenEventReference = tokenEventReference; - } - - public String getTokenReason() { - return tokenReason; - } - - public void setTokenReason(String tokenReason) { - this.tokenReason = tokenReason; - } - - public TokenDetails getTokenDetails() { - return tokenDetails; - } - - public void setTokenDetails(final TokenDetails tokenDetails) { - this.tokenDetails = tokenDetails; - } - - public Card getPaymentInstrument() { - return paymentInstrument; - } - - public void setPaymentInstrument(final Card paymentInstrument) { - this.paymentInstrument = paymentInstrument; - } - - public ErrorDetail getError() { - return error; - } - - public void setError(final ErrorDetail error) { - this.error = error; - } - - @Override - public String toString() { - return "TokenReply{" + - "authenticatedShopperID='" + authenticatedShopperID + '\'' + - ", tokenEventReference='" + tokenEventReference + '\'' + - ", tokenReason='" + tokenReason + '\'' + - ", tokenDetails=" + tokenDetails + - ", paymentInstrument=" + paymentInstrument + - ", error=" + error + - '}'; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/TokenRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/TokenRequest.java deleted file mode 100644 index 2611d5d7..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/TokenRequest.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.CreateToken; -import com.worldpay.internal.model.TokenReason; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; - -public class TokenRequest implements InternalModelTransformer, Serializable { - - private String tokenEventReference; - private String tokenReason; - private boolean merchantToken; - - public TokenRequest(final String tokenEventReference, final String tokenReason) { - this.tokenEventReference = tokenEventReference; - this.tokenReason = tokenReason; - this.merchantToken = false; - } - - public TokenRequest(final String tokenEventReference, final String tokenReason, final boolean merchantToken) { - this.tokenEventReference = tokenEventReference; - this.tokenReason = tokenReason; - this.merchantToken = merchantToken; - } - - @Override - public InternalModelObject transformToInternalModel() { - final CreateToken intCreateToken = new CreateToken(); - if (tokenReason != null) { - final TokenReason intTokenReason = new TokenReason(); - intTokenReason.setvalue(tokenReason); - intCreateToken.setTokenReason(intTokenReason); - } - intCreateToken.setTokenEventReference(tokenEventReference); - if (merchantToken) { - intCreateToken.setTokenScope("merchant"); - } else { - intCreateToken.setTokenScope("shopper"); - } - return intCreateToken; - } - - public String getTokenEventReference() { - return tokenEventReference; - } - - public void setTokenEventReference(String tokenEventReference) { - this.tokenEventReference = tokenEventReference; - } - - public String getTokenReason() { - return tokenReason; - } - - public void setTokenReason(final String tokenReason) { - this.tokenReason = tokenReason; - } - - public boolean isMerchantToken() { - return merchantToken; - } - - public void setMerchantToken(final boolean merchantToken) { - this.merchantToken = merchantToken; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/UpdateTokenReply.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/UpdateTokenReply.java deleted file mode 100644 index 7faf92b2..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/UpdateTokenReply.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.worldpay.service.model.token; - -public class UpdateTokenReply { - - private String paymentTokenId; - - public String getPaymentTokenId() { - return paymentTokenId; - } - - public void setPaymentTokenId(final String paymentTokenId) { - this.paymentTokenId = paymentTokenId; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/UpdateTokenRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/UpdateTokenRequest.java deleted file mode 100644 index 55795ae2..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/model/token/UpdateTokenRequest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.*; -import com.worldpay.service.request.transform.InternalModelTransformer; - -import java.io.Serializable; -import java.util.Optional; - -public class UpdateTokenRequest implements InternalModelTransformer, Serializable { - - private String paymentTokenId; - private String authenticatedShopperID; - private CardDetails cardDetails; - private TokenRequest tokenRequest; - private boolean merchantToken; - - public UpdateTokenRequest(final String paymentTokenId, final String authenticatedShopperID, final CardDetails cardDetails, final TokenRequest tokenRequest, final boolean merchantToken) { - this.paymentTokenId = paymentTokenId; - this.authenticatedShopperID = authenticatedShopperID; - this.cardDetails = cardDetails; - this.tokenRequest = tokenRequest; - this.merchantToken = merchantToken; - } - - @Override - public InternalModelObject transformToInternalModel() { - final PaymentTokenUpdate intPaymentTokenUpdate = new PaymentTokenUpdate(); - if (merchantToken) { - intPaymentTokenUpdate.setTokenScope("merchant"); - intPaymentTokenUpdate.setAuthenticatedShopperID(null); - } else { - Optional.ofNullable(authenticatedShopperID) - .map(shopperId -> { - final AuthenticatedShopperID intAuthenticatedShopperID = new AuthenticatedShopperID(); - intAuthenticatedShopperID.setvalue(shopperId); - return intAuthenticatedShopperID; - }) - .ifPresent(intPaymentTokenUpdate::setAuthenticatedShopperID); - } - - final PaymentTokenID paymentTokenIDWrapper = new PaymentTokenID(); - paymentTokenIDWrapper.setvalue(paymentTokenId); - intPaymentTokenUpdate.setPaymentTokenID(paymentTokenIDWrapper); - intPaymentTokenUpdate.setTokenEventReference(tokenRequest.getTokenEventReference()); - - final PaymentInstrument intPaymentInstrument = new PaymentInstrument(); - final com.worldpay.internal.model.CardDetails intCardDetails = (com.worldpay.internal.model.CardDetails) cardDetails.transformToInternalModel(); - intPaymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().add(intCardDetails); - intPaymentTokenUpdate.setPaymentInstrument(intPaymentInstrument); - final TokenReason tokenReason = new TokenReason(); - tokenReason.setvalue(tokenRequest.getTokenReason()); - intPaymentTokenUpdate.setTokenReason(tokenReason); - - return intPaymentTokenUpdate; - } - - public TokenRequest getTokenRequest() { - return tokenRequest; - } - - public String getPaymentTokenId() { - return paymentTokenId; - } - - public void setAuthenticatedShopperID(String authenticatedShopperID) { - this.authenticatedShopperID = authenticatedShopperID; - } - - public void setTokenRequest(TokenRequest tokenRequest) { - this.tokenRequest = tokenRequest; - } - - public void setPaymentTokenId(String paymentTokenId) { - this.paymentTokenId = paymentTokenId; - } - - public String getAuthenticatedShopperID() { - return authenticatedShopperID; - } - - public void setCardDetails(CardDetails cardDetails) { - this.cardDetails = cardDetails; - } - - public CardDetails getCardDetails() { - return cardDetails; - } - - public boolean isMerchantToken() { - return merchantToken; - } - - public void setMerchantToken(final boolean merchantToken) { - this.merchantToken = merchantToken; - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/notification/OrderNotificationMessage.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/notification/OrderNotificationMessage.java index 4dfc6cee..5170988d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/notification/OrderNotificationMessage.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/notification/OrderNotificationMessage.java @@ -1,9 +1,9 @@ package com.worldpay.service.notification; -import com.worldpay.service.model.JournalReply; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.WebformRefundReply; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.data.JournalReply; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.WebformRefundReply; +import com.worldpay.data.token.TokenReply; import java.io.Serializable; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAdditionalDataRequestStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAdditionalDataRequestStrategy.java new file mode 100644 index 00000000..9dd891ef --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAdditionalDataRequestStrategy.java @@ -0,0 +1,22 @@ +package com.worldpay.service.payment; + +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; +import de.hybris.platform.core.model.order.AbstractOrderModel; + +/** + * Strategy to handle the request additional data + */ +public interface WorldpayAdditionalDataRequestStrategy { + + /** + * Populates the request with additional data based on the strategy + * + * @param cart the cart + * @param worldpayAdditionalInfoData additionalInfoData + * @param authoriseRequestParametersCreator request parameters + */ + void populateRequestWithAdditionalData(AbstractOrderModel cart, + WorldpayAdditionalInfoData worldpayAdditionalInfoData, + AuthoriseRequestParametersCreator authoriseRequestParametersCreator); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAdditionalRequestDataService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAdditionalRequestDataService.java new file mode 100644 index 00000000..9a5bd15b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAdditionalRequestDataService.java @@ -0,0 +1,29 @@ +package com.worldpay.service.payment; + +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; +import de.hybris.platform.core.model.order.AbstractOrderModel; + +/** + * Service to handle additional data for the payment request strategies + */ +public interface WorldpayAdditionalRequestDataService { + + /** + * Populated the request additional data for direct integrations + * + * @param cart the cart model + * @param worldpayAdditionalInfoData + * @param authoriseRequestParametersCreator + */ + void populateDirectRequestAdditionalData(AbstractOrderModel cart, WorldpayAdditionalInfoData worldpayAdditionalInfoData, AuthoriseRequestParametersCreator authoriseRequestParametersCreator); + + /** + * Populated the request additional data for redirect integrations + * + * @param cart the cart model + * @param worldpayAdditionalInfoData + * @param authoriseRequestParametersCreator + */ + void populateRedirectRequestAdditionalData(AbstractOrderModel cart, WorldpayAdditionalInfoData worldpayAdditionalInfoData, AuthoriseRequestParametersCreator authoriseRequestParametersCreator); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAfterRedirectValidationService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAfterRedirectValidationService.java index 2199603d..6afb6a4e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAfterRedirectValidationService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayAfterRedirectValidationService.java @@ -1,6 +1,6 @@ package com.worldpay.service.payment; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import java.util.Map; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayDirectOrderService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayDirectOrderService.java index 8340237d..be64c8e1 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayDirectOrderService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayDirectOrderService.java @@ -4,7 +4,7 @@ import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.exception.WorldpayException; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.DirectAuthoriseServiceRequest; import com.worldpay.service.response.DirectAuthoriseServiceResponse; import de.hybris.platform.core.model.order.AbstractOrderModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayFraudSightStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayFraudSightStrategy.java new file mode 100644 index 00000000..7d7b2a44 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayFraudSightStrategy.java @@ -0,0 +1,48 @@ +package com.worldpay.service.payment; + +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.data.FraudSightData; +import com.worldpay.data.PaymentReply; +import de.hybris.platform.basecommerce.model.site.BaseSiteModel; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.payment.model.PaymentTransactionModel; + +/** + * Strategy to handle the Fraud Sight logic. + */ +public interface WorldpayFraudSightStrategy { + + /** + * Checks if the Fraud Sight is enabled for the session site + * + * @return true if enabled, false otherwise + */ + boolean isFraudSightEnabled(); + + /** + * Checks if the Fraud Sight is enabled for the given site + * + * @param baseSite the given site + * @return true if enabled, false otherwise + */ + boolean isFraudSightEnabled(BaseSiteModel baseSite); + + /** + * Creates the FraudSightData based on the abstractOrder details and worldpayAdditionalInfoData. Override this method if you want to customize + * the logic related tot he Fraud Sight payload + * + * @param abstractOrder the cart + * @param worldpayAdditionalInfoData the additional info + * @return a populated {@link FraudSightData} + */ + FraudSightData createFraudSightData(AbstractOrderModel abstractOrder, WorldpayAdditionalInfoData worldpayAdditionalInfoData); + + /** + * Sets the fraud sight on a paymentTransactionEntryModel + * + * @param paymentTransactionModel the payment transaction + * @param paymentReply the payment response from Worldpay + */ + void addFraudSight(final PaymentTransactionModel paymentTransactionModel, final PaymentReply paymentReply); + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayKlarnaStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayKlarnaService.java similarity index 52% rename from hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayKlarnaStrategy.java rename to hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayKlarnaService.java index 2699a302..5957acb8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayKlarnaStrategy.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayKlarnaService.java @@ -1,13 +1,13 @@ package com.worldpay.service.payment; import com.worldpay.exception.WorldpayConfigurationException; -import com.worldpay.service.model.OrderLines; +import com.worldpay.data.OrderLines; import de.hybris.platform.core.model.order.CartModel; /** - * Strategy to create the order lines necessary for Klarna Integration + * Service to create the order lines necessary for Klarna Integration and other Klarna functionalities */ -public interface WorldpayKlarnaStrategy { +public interface WorldpayKlarnaService { /** * @param cartModel the current cart @@ -15,4 +15,12 @@ public interface WorldpayKlarnaStrategy { * @throws WorldpayConfigurationException Exception thrown when the URL for the terms and conditions is not configured */ OrderLines createOrderLines(CartModel cartModel) throws WorldpayConfigurationException; + + /** + * Checks whether the paymentCode passed is or not a Klarna valid payment method type code + * + * @param paymentCode the payment code + * @return true if it is klarna payment, false otherwise + */ + boolean isKlarnaPaymentType(final String paymentCode); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayLevel23DataValidator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayLevel23DataValidator.java new file mode 100644 index 00000000..b7522f70 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayLevel23DataValidator.java @@ -0,0 +1,25 @@ +package com.worldpay.service.payment; + +import com.worldpay.data.Purchase; + +import java.util.List; + +public interface WorldpayLevel23DataValidator { + + /** + * Checks if the Purchase is valid for level 3 data + * + * @param purchaseData list of Purchase objects + * @return true if all data is valid, false otherwise + */ + boolean isValidLevel3Data(final List purchaseData); + + /** + * Checks if the Purchase is valid for level 2 data + * Cleans up the invalid optional fields to make a valid level 2 request + * + * @param purchaseData list of Purchase objects + * @return true if all data is valid, false otherwise + */ + boolean isValidLevel2Data(final List purchaseData); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayLevel23Strategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayLevel23Strategy.java new file mode 100644 index 00000000..0586e909 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayLevel23Strategy.java @@ -0,0 +1,20 @@ +package com.worldpay.service.payment; + +import com.worldpay.data.BranchSpecificExtension; +import com.worldpay.data.FraudSightData; +import de.hybris.platform.core.model.order.AbstractOrderModel; + +/** + * Strategy to handle the Level 2/3 logic. + */ +public interface WorldpayLevel23Strategy { + + /** + * Creates the {@link BranchSpecificExtension} based on the abstractOrder details + * + * @param abstractOrder the cart + * @return a populated {@link FraudSightData} + */ + BranchSpecificExtension createLevel23Data(AbstractOrderModel abstractOrder); + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayOrderService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayOrderService.java index f96d96c5..8c237fcd 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayOrderService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayOrderService.java @@ -3,12 +3,12 @@ import com.worldpay.data.ApplePayAdditionalAuthInfo; import com.worldpay.data.CSEAdditionalAuthInfo; import com.worldpay.exception.WorldpayConfigurationException; -import com.worldpay.service.model.Address; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.BasicOrderInfo; -import com.worldpay.service.model.payment.Cse; -import com.worldpay.service.model.payment.PayWithGoogleSSL; -import com.worldpay.service.model.payment.Payment; +import com.worldpay.data.Address; +import com.worldpay.data.Amount; +import com.worldpay.data.BasicOrderInfo; +import com.worldpay.data.payment.Cse; +import com.worldpay.data.payment.PayWithGoogleSSL; +import com.worldpay.data.payment.Payment; import de.hybris.platform.commerceservices.service.data.CommerceCheckoutParameter; import de.hybris.platform.core.model.c2l.CurrencyModel; import de.hybris.platform.core.model.c2l.LanguageModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayRedirectOrderService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayRedirectOrderService.java index c9202379..ac7d58f6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayRedirectOrderService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayRedirectOrderService.java @@ -4,7 +4,7 @@ import com.worldpay.exception.WorldpayException; import com.worldpay.hostedorderpage.data.RedirectAuthoriseResult; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import de.hybris.platform.acceleratorservices.payment.data.PaymentData; import de.hybris.platform.core.model.order.CartModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayRiskDataService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayRiskDataService.java index 724c2920..e0177435 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayRiskDataService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/WorldpayRiskDataService.java @@ -1,10 +1,10 @@ package com.worldpay.service.payment; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.threeds2.AuthenticationRiskData; -import com.worldpay.service.model.threeds2.RiskData; -import com.worldpay.service.model.threeds2.ShopperAccountRiskData; -import com.worldpay.service.model.threeds2.TransactionRiskData; +import com.worldpay.data.threeds2.AuthenticationRiskData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.threeds2.ShopperAccountRiskData; +import com.worldpay.data.threeds2.TransactionRiskData; import de.hybris.platform.core.model.order.CartModel; /** diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/AbstractWorldpayFraudSightStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/AbstractWorldpayFraudSightStrategy.java new file mode 100644 index 00000000..f4574adb --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/AbstractWorldpayFraudSightStrategy.java @@ -0,0 +1,25 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.data.CustomNumericFields; +import com.worldpay.data.CustomStringFields; +import com.worldpay.service.payment.WorldpayFraudSightStrategy; + +/** + * Abstract implementation of {@link WorldpayFraudSightStrategy} + */ +public abstract class AbstractWorldpayFraudSightStrategy implements WorldpayFraudSightStrategy { + + /** + * Creates and populates the CustomStringFields. + * + * @return the {@link CustomStringFields} + */ + protected abstract CustomStringFields createCustomStringFields(); + + /** + * Creates and populates the CustomNumericFields. + * + * @return the {@link CustomNumericFields} + */ + protected abstract CustomNumericFields createCustomNumericFields(); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/AbstractWorldpayLevel23Strategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/AbstractWorldpayLevel23Strategy.java new file mode 100644 index 00000000..3c91e86b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/AbstractWorldpayLevel23Strategy.java @@ -0,0 +1,28 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.data.Item; +import com.worldpay.data.Purchase; +import com.worldpay.service.payment.WorldpayLevel23Strategy; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.product.ProductModel; + +/** + * Abstract implementation of {@link WorldpayLevel23Strategy} + */ +public abstract class AbstractWorldpayLevel23Strategy implements WorldpayLevel23Strategy { + + /** + * Populates the customer reference. Override this method with real values based on business requirements + */ + protected abstract void setCustomerReference(AbstractOrderModel order, Purchase purchase); + + /** + * Populates the product description. Override this method with real values based on business requirements + */ + protected abstract void setProductDescription(ProductModel product, Item item); + + /** + * Populates the duty amount. Override this method with real values based on business requirements + */ + protected abstract void setDutyAmount(AbstractOrderModel order, Purchase purchase); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultTestWorldpayFraudSightStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultTestWorldpayFraudSightStrategy.java new file mode 100644 index 00000000..e96506b0 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultTestWorldpayFraudSightStrategy.java @@ -0,0 +1,66 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.core.services.WorldpayCartService; +import com.worldpay.model.WorldpayFraudSightModel; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.data.*; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import de.hybris.platform.servicelayer.model.ModelService; +import de.hybris.platform.site.BaseSiteService; + +import java.util.Optional; + +/** + * Extension of {@link DefaultWorldpayFraudSightStrategy} in order to allow the testing of Fraud Sight functionality + */ +public class DefaultTestWorldpayFraudSightStrategy extends DefaultWorldpayFraudSightStrategy { + + public DefaultTestWorldpayFraudSightStrategy(final WorldpayCartService worldpayCartService, + final Converter worldpayAddressConverter, + final BaseSiteService baseSiteService, + final Converter worldpayFraudSightResponseConverter, + final ModelService modelService) { + super(worldpayCartService, worldpayAddressConverter, baseSiteService, worldpayFraudSightResponseConverter, modelService); + } + + /** + * {@inheritDoc} + */ + @Override + protected ShopperFields createShopperFields(final AbstractOrderModel abstractOrder, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) { + final ShopperFields shopperFields = callSuperCreateShopperFields(abstractOrder, worldpayAdditionalInfoData); + + // This has been done to perform testing with the address line 3. The billing address ootb does not have + // any address line 3. So it will be populated from line 2 + Optional.ofNullable(abstractOrder.getPaymentAddress()) + .ifPresent(address -> shopperFields.getShopperAddress().setAddress3(address.getLine2())); + + return shopperFields; + } + + /** + * {@inheritDoc} + */ + @Override + protected CustomStringFields createCustomStringFields() { + final CustomStringFields customStringFields = new CustomStringFields(); + customStringFields.setCustomStringField1("abc"); + return customStringFields; + } + + /** + * {@inheritDoc} + */ + @Override + protected CustomNumericFields createCustomNumericFields() { + final CustomNumericFields customNumericFields = new CustomNumericFields(); + customNumericFields.setCustomNumericField1(123); + return customNumericFields; + } + + protected ShopperFields callSuperCreateShopperFields(final AbstractOrderModel abstractOrder, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) { + return super.createShopperFields(abstractOrder, worldpayAdditionalInfoData); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultTestWorldpayLevel23Strategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultTestWorldpayLevel23Strategy.java new file mode 100644 index 00000000..447763b5 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultTestWorldpayLevel23Strategy.java @@ -0,0 +1,48 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.data.Item; +import com.worldpay.data.Purchase; +import com.worldpay.service.payment.WorldpayLevel23DataValidator; +import com.worldpay.service.payment.WorldpayOrderService; +import com.worldpay.strategy.WorldpayMerchantStrategy; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.product.ProductModel; +import org.apache.commons.lang3.RandomStringUtils; + +/** + * Extension of {@link DefaultWorldpayLevel23Strategy} in order to allow the testing of Level 2/3 functionality + */ +public class DefaultTestWorldpayLevel23Strategy extends DefaultWorldpayLevel23Strategy { + + public DefaultTestWorldpayLevel23Strategy(final WorldpayMerchantStrategy worldpayMerchantStrategy, + final WorldpayOrderService worldpayOrderService, + final WorldpayLevel23DataValidator worldpayLevel23DataValidator) { + super(worldpayMerchantStrategy, worldpayOrderService, worldpayLevel23DataValidator); + } + + /** + * {@inheritDoc} + */ + @Override + protected void setCustomerReference(final AbstractOrderModel order, final Purchase purchase) { + purchase.setCustomerReference(RandomStringUtils.randomAlphanumeric(17)); + } + + /** + * {@inheritDoc} + */ + @Override + protected void setProductDescription(final ProductModel product, final Item item) { + final String name = product.getName(); + final String productName = name.length() > 26 ? name.substring(0, 26) : name; + item.setDescription(productName); + } + + /** + * {@inheritDoc} + */ + @Override + protected void setDutyAmount(final AbstractOrderModel order, final Purchase purchase) { + purchase.setDutyAmount(worldpayOrderService.createAmount(order.getCurrency(), 0)); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayAdditionalRequestDataService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayAdditionalRequestDataService.java new file mode 100644 index 00000000..e0d07eaa --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayAdditionalRequestDataService.java @@ -0,0 +1,44 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.payment.WorldpayAdditionalDataRequestStrategy; +import com.worldpay.service.payment.WorldpayAdditionalRequestDataService; +import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; +import de.hybris.platform.core.model.order.AbstractOrderModel; + +import java.util.List; + +/** + * {@inheritDoc} + */ +public class DefaultWorldpayAdditionalRequestDataService implements WorldpayAdditionalRequestDataService { + + protected final List worldpayDirectDataRequestStrategies; + protected final List worldpayRedirectDataRequestStrategies; + + public DefaultWorldpayAdditionalRequestDataService(final List worldpayDirectDataRequestStrategies, + final List worldpayRedirectDataRequestStrategies) { + this.worldpayDirectDataRequestStrategies = worldpayDirectDataRequestStrategies; + this.worldpayRedirectDataRequestStrategies = worldpayRedirectDataRequestStrategies; + } + + /** + * {@inheritDoc} + */ + @Override + public void populateDirectRequestAdditionalData(final AbstractOrderModel cart, + final WorldpayAdditionalInfoData worldpayAdditionalInfoData, + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator) { + worldpayDirectDataRequestStrategies.forEach(strategy -> strategy.populateRequestWithAdditionalData(cart, worldpayAdditionalInfoData, authoriseRequestParametersCreator)); + } + + /** + * {@inheritDoc} + */ + @Override + public void populateRedirectRequestAdditionalData(final AbstractOrderModel cart, + final WorldpayAdditionalInfoData worldpayAdditionalInfoData, + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator) { + worldpayRedirectDataRequestStrategies.forEach(strategy -> strategy.populateRequestWithAdditionalData(cart, worldpayAdditionalInfoData, authoriseRequestParametersCreator)); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayAfterRedirectValidationService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayAfterRedirectValidationService.java index 785ea4ce..bd3e88d5 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayAfterRedirectValidationService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayAfterRedirectValidationService.java @@ -3,17 +3,18 @@ import com.worldpay.enums.order.AuthorisedStatus; import com.worldpay.exception.WorldpayMacValidationException; import com.worldpay.service.mac.MacValidator; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayAfterRedirectValidationService; import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Map; import static com.worldpay.enums.order.AuthorisedStatus.AUTHORISED; public class DefaultWorldpayAfterRedirectValidationService implements WorldpayAfterRedirectValidationService { - protected static final Logger LOG = Logger.getLogger(DefaultWorldpayAfterRedirectValidationService.class); + protected static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayAfterRedirectValidationService.class); private static final String KEY_MAC = "mac"; private static final String KEY_MAC2 = "mac2"; private static final String ORDER_KEY = "orderKey"; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayDirectOrderService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayDirectOrderService.java index 1d23c8fb..edc17830 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayDirectOrderService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayDirectOrderService.java @@ -7,8 +7,9 @@ import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.SchemeResponse; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.SchemeResponse; import com.worldpay.service.payment.WorldpayDirectOrderService; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.payment.WorldpaySessionService; @@ -238,7 +239,8 @@ public void completeAuthorise(final DirectAuthoriseServiceResponse serviceRespon final String merchantCode = worldpayMerchantInfoService.getCurrentSiteMerchant().getMerchantCode(); final PaymentInfoModel paymentInfoModel = Optional.ofNullable(abstractOrderModel.getPaymentInfo()) .orElseGet(() -> createCreditCardPaymentInfo(serviceResponse, abstractOrderModel, merchantCode)); - final BigDecimal authorisationAmount = worldpayOrderService.convertAmount(serviceResponse.getPaymentReply().getAmount()); + final PaymentReply paymentReply = serviceResponse.getPaymentReply(); + final BigDecimal authorisationAmount = worldpayOrderService.convertAmount(paymentReply.getAmount()); final CommerceCheckoutParameter commerceCheckoutParameter; if (abstractOrderModel instanceof CartModel) { @@ -250,16 +252,18 @@ public void completeAuthorise(final DirectAuthoriseServiceResponse serviceRespon } final PaymentTransactionModel paymentTransaction = worldpayPaymentTransactionService.createPaymentTransaction(false, merchantCode, commerceCheckoutParameter); - worldpayPaymentTransactionService.addRiskScore(paymentTransaction, serviceResponse.getPaymentReply()); + worldpayPaymentTransactionService.addRiskScore(paymentTransaction, paymentReply); + + worldpayPaymentTransactionService.addFraudSightToPaymentTransaction(paymentTransaction, paymentReply); final PaymentTransactionEntryModel transactionEntry = worldpayPaymentTransactionService.createNonPendingAuthorisePaymentTransactionEntry(paymentTransaction, - merchantCode, - abstractOrderModel, - authorisationAmount); - worldpayPaymentTransactionService.addAavFields(transactionEntry, serviceResponse.getPaymentReply()); + merchantCode, + abstractOrderModel, + authorisationAmount); + worldpayPaymentTransactionService.addAavFields(transactionEntry, paymentReply); getTransactionIdentifier(serviceResponse) - .ifPresent(transactionIdentifier -> - worldpayPaymentInfoService.setTransactionIdentifierOnPaymentInfo(paymentInfoModel, transactionIdentifier)); + .ifPresent(transactionIdentifier -> + worldpayPaymentInfoService.setTransactionIdentifierOnPaymentInfo(paymentInfoModel, transactionIdentifier)); worldpayPaymentInfoService.updateAndAttachPaymentInfoModel(paymentTransaction, abstractOrderModel, paymentInfoModel); } @@ -278,9 +282,9 @@ public void completeAuthoriseGooglePay(final DirectAuthoriseServiceResponse serv commerceCheckoutParameter = worldpayOrderService.createCheckoutParameterAndSetPaymentInfo(paymentInfoModel, authorisationAmount, cartModel); final PaymentTransactionModel paymentTransaction = worldpayPaymentTransactionService.createPaymentTransaction(false, merchantCode, commerceCheckoutParameter); worldpayPaymentTransactionService.createPendingAuthorisePaymentTransactionEntry(paymentTransaction, - merchantCode, - cartModel, - authorisationAmount); + merchantCode, + cartModel, + authorisationAmount); worldpayPaymentInfoService.updateAndAttachPaymentInfoModel(paymentTransaction, abstractOrderModel, paymentInfoModel); } } @@ -295,7 +299,7 @@ public void completeAuthorise3DSecure(final AbstractOrderModel abstractOrderMode protected Optional getTransactionIdentifier(final DirectAuthoriseServiceResponse serviceResponse) { return Optional.ofNullable(serviceResponse.getPaymentReply().getSchemeResponse()) - .map(SchemeResponse::getTransactionIdentifier); + .map(SchemeResponse::getTransactionIdentifier); } protected CreditCardPaymentInfoModel createCreditCardPaymentInfo(final DirectAuthoriseServiceResponse serviceResponse, final AbstractOrderModel abstractOrderModel, final String merchantCode) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayFraudSightStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayFraudSightStrategy.java new file mode 100644 index 00000000..6c77173d --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayFraudSightStrategy.java @@ -0,0 +1,164 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.core.services.WorldpayCartService; +import com.worldpay.data.*; +import com.worldpay.model.WorldpayFraudSightModel; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.payment.WorldpayAdditionalDataRequestStrategy; +import com.worldpay.service.payment.WorldpayFraudSightStrategy; +import com.worldpay.service.request.AuthoriseRequestParameters; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; +import de.hybris.platform.basecommerce.model.site.BaseSiteModel; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.payment.model.PaymentTransactionModel; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import de.hybris.platform.servicelayer.model.ModelService; +import de.hybris.platform.site.BaseSiteService; +import org.apache.commons.lang3.NotImplementedException; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Optional; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; +import static org.apache.commons.lang3.StringUtils.isNotBlank; + +/** + * Default implementation of {@link WorldpayFraudSightStrategy}. + * Extend this strategy if you want customize the Fraud Sight Data payload + */ +public class DefaultWorldpayFraudSightStrategy extends AbstractWorldpayFraudSightStrategy implements WorldpayAdditionalDataRequestStrategy { + + protected final WorldpayCartService worldpayCartService; + protected final Converter worldpayAddressConverter; + protected final BaseSiteService baseSiteService; + protected final Converter worldpayFraudSightResponseConverter; + protected final ModelService modelService; + + public DefaultWorldpayFraudSightStrategy(final WorldpayCartService worldpayCartService, + final Converter worldpayAddressConverter, + final BaseSiteService baseSiteService, + final Converter worldpayFraudSightResponseConverter, + final ModelService modelService) { + this.worldpayCartService = worldpayCartService; + this.worldpayAddressConverter = worldpayAddressConverter; + this.baseSiteService = baseSiteService; + this.worldpayFraudSightResponseConverter = worldpayFraudSightResponseConverter; + this.modelService = modelService; + } + + /** + * {@inheritDoc} + */ + @Override + public void populateRequestWithAdditionalData(final AbstractOrderModel cart, + final WorldpayAdditionalInfoData worldpayAdditionalInfoData, + final AuthoriseRequestParameters.AuthoriseRequestParametersCreator authoriseRequestParametersCreator) { + if (isFraudSightEnabled()) { + + final FraudSightData fraudSightData = createFraudSightData(cart, worldpayAdditionalInfoData); + authoriseRequestParametersCreator.withFraudSightData(fraudSightData); + + if (isNotBlank(worldpayAdditionalInfoData.getDeviceSession())) { + authoriseRequestParametersCreator.withDeviceSession(worldpayAdditionalInfoData.getDeviceSession()); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isFraudSightEnabled() { + return baseSiteService.getCurrentBaseSite().getEnableFS(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isFraudSightEnabled(final BaseSiteModel baseSite) { + return baseSite.getEnableFS(); + } + + /** + * {@inheritDoc} + */ + @Override + public FraudSightData createFraudSightData(final AbstractOrderModel abstractOrder, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) { + validateParameterNotNull(abstractOrder, "The cart is null"); + + final ShopperFields shopperFields = createShopperFields(abstractOrder, worldpayAdditionalInfoData); + final CustomNumericFields customNumericFields = createCustomNumericFields(); + final CustomStringFields customStringFields = createCustomStringFields(); + + final FraudSightData fraudSightData = new FraudSightData(); + fraudSightData.setShopperFields(shopperFields); + fraudSightData.setCustomNumericFields(customNumericFields); + fraudSightData.setCustomStringFields(customStringFields); + + return fraudSightData; + } + + /** + * {@inheritDoc} + */ + @Override + public void addFraudSight(final PaymentTransactionModel paymentTransactionModel, final PaymentReply paymentReply) { + Optional.ofNullable(paymentReply.getFraudSight()) + .map(worldpayFraudSightResponseConverter::convert) + .map(fraudSight -> { + paymentTransactionModel.setFraudSight(fraudSight); + return paymentTransactionModel; + }) + .ifPresent(modelService::save); + } + + /** + * Creates and populates the ShopperFields + * + * @param abstractOrder the cart + * @param worldpayAdditionalInfoData the additional data + * @return the {@link ShopperFields} + */ + protected ShopperFields createShopperFields(final AbstractOrderModel abstractOrder, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) { + final ShopperFields shopperFields = new ShopperFields(); + + validateParameterNotNull(abstractOrder.getUser(), "The customer is null"); + + shopperFields.setShopperId(worldpayCartService.getAuthenticatedShopperId(abstractOrder)); + shopperFields.setShopperName(abstractOrder.getUser().getName()); + + Optional.ofNullable(abstractOrder.getPaymentAddress()) + .map(worldpayAddressConverter::convert) + .ifPresent(shopperFields::setShopperAddress); + + Optional.ofNullable(worldpayAdditionalInfoData.getDateOfBirth()).ifPresent(dob -> { + final LocalDateTime dateOfBirth = Instant.ofEpochMilli(dob.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + shopperFields.setBirthDate(WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(dateOfBirth)); + }); + return shopperFields; + } + + /** + * Creates and populates the CustomStringFields. Override this method with Real values based on business requirements + * + * @return the {@link CustomStringFields} + */ + protected CustomStringFields createCustomStringFields() { + throw new NotImplementedException("Implement this method based on business requirements"); + } + + /** + * Creates and populates the CustomNumericFields. Override this method with Real values based on business requirements + * + * @return the {@link CustomNumericFields} + */ + protected CustomNumericFields createCustomNumericFields() { + throw new NotImplementedException("Implement this method based on business requirements"); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaService.java similarity index 78% rename from hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaStrategy.java rename to hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaService.java index d288ae5f..0434dacb 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaStrategy.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaService.java @@ -1,11 +1,12 @@ package com.worldpay.service.payment.impl; +import com.worldpay.data.LineItem; +import com.worldpay.data.LineItemReference; +import com.worldpay.data.OrderLines; +import com.worldpay.enums.lineItem.LineItemType; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.service.WorldpayUrlService; -import com.worldpay.service.model.LineItem; -import com.worldpay.service.model.LineItemReference; -import com.worldpay.service.model.OrderLines; -import com.worldpay.service.payment.WorldpayKlarnaStrategy; +import com.worldpay.service.payment.WorldpayKlarnaService; import de.hybris.platform.core.model.order.AbstractOrderEntryModel; import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.servicelayer.i18n.CommonI18NService; @@ -16,25 +17,30 @@ import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; +import java.util.Objects; -import static com.worldpay.service.model.LineItem.LINE_ITEM_TYPE.DISCOUNT; -import static com.worldpay.service.model.LineItem.LINE_ITEM_TYPE.SHIPPING_FEE; import static java.util.stream.Collectors.toList; /** * {@inheritDoc} */ -public class DefaultWorldpayKlarnaStrategy implements WorldpayKlarnaStrategy { +public class DefaultWorldpayKlarnaService implements WorldpayKlarnaService { private static final String ORDER_DISCOUNT = "ORDER_DISCOUNT"; private static final String DISCOUNT_LINE_ITEM_REFERENCE = "DISCOUNT_LINE_ITEM_REFERENCE"; + private static final String SHIPPING_LINE_ITEM_REFERENCE = "SHIPPING_LINE_ITEM_REFERENCE"; + private static final String DISCOUNT = "discount"; + private static final String SHIPPING = "shipping"; protected final CommonI18NService commonI18NService; protected final WorldpayUrlService worldpayUrlService; + protected final List klarnaPayments; - public DefaultWorldpayKlarnaStrategy(final CommonI18NService commonI18NService, final WorldpayUrlService worldpayUrlService) { + public DefaultWorldpayKlarnaService(final CommonI18NService commonI18NService, final WorldpayUrlService worldpayUrlService, + final List klarnaPayments) { this.commonI18NService = commonI18NService; this.worldpayUrlService = worldpayUrlService; + this.klarnaPayments = klarnaPayments; } /** @@ -56,13 +62,26 @@ public OrderLines createOrderLines(final CartModel cartModel) throws WorldpayCon lineItems.add(createDiscountLineItem(cartModel, digits)); } - final OrderLines orderLines = new OrderLines(orderTaxAmount, termsURL, lineItems); + final OrderLines orderLines = new OrderLines(); + orderLines.setOrderTaxAmount(orderTaxAmount); + orderLines.setTermsURL(termsURL); + orderLines.setLineItems(lineItems); + if (orderLines.getLineItems().size() > 1) { verifySweepPennies(cartModel, orderLines); } + return orderLines; } + /** + * {@inheritDoc} + */ + @Override + public boolean isKlarnaPaymentType(final String paymentCode) { + return Objects.nonNull(paymentCode) && klarnaPayments.stream().anyMatch(paymentCode::equals); + } + private void verifySweepPennies(final CartModel cartModel, final OrderLines orderLines) { final int digits = cartModel.getCurrency().getDigits(); final double totalTax = cartModel.getTotalTax(); @@ -72,18 +91,18 @@ private void verifySweepPennies(final CartModel cartModel, final OrderLines orde if (BigDecimal.valueOf(totalTax).compareTo(BigDecimal.valueOf(roundedCalculatedTotalTaxAmount)) != 0) { final double taxRoundingDifference = Math.abs(totalTax - roundedCalculatedTotalTaxAmount); orderLines.getLineItems().stream() - .filter(lineItem1 -> DISCOUNT.equals(lineItem1.getLineItemType())) + .filter(lineItem1 -> LineItemType.DISCOUNT.equals(lineItem1.getLineItemType())) + .findAny() + .ifPresentOrElse(discountLine -> { + final double adjustedLineItemTaxAmount = discountLine.getTotalTaxAmountValue() - taxRoundingDifference; + discountLine.setTotalTaxAmount(convertDoubleToStringFormat(digits, adjustedLineItemTaxAmount)); + }, () -> orderLines.getLineItems().stream() + .filter(lineItem1 -> LineItemType.SHIPPING_FEE.equals(lineItem1.getLineItemType())) .findAny() - .ifPresentOrElse(discountLine -> { - final double adjustedLineItemTaxAmount = discountLine.getTotalTaxAmountValue() - taxRoundingDifference; - discountLine.setTotalTaxAmount(convertDoubleToStringFormat(digits, adjustedLineItemTaxAmount)); - }, () -> orderLines.getLineItems().stream() - .filter(lineItem1 -> SHIPPING_FEE.equals(lineItem1.getLineItemType())) - .findAny() - .ifPresent(shippingLineItem -> { - final double adjustedLineItemTaxAmount = shippingLineItem.getTotalTaxAmountValue() - taxRoundingDifference; - shippingLineItem.setTotalTaxAmount(convertDoubleToStringFormat(digits, adjustedLineItemTaxAmount)); - })); + .ifPresent(shippingLineItem -> { + final double adjustedLineItemTaxAmount = shippingLineItem.getTotalTaxAmountValue() - taxRoundingDifference; + shippingLineItem.setTotalTaxAmount(convertDoubleToStringFormat(digits, adjustedLineItemTaxAmount)); + })); } } @@ -91,8 +110,9 @@ private LineItem createLineItem(final AbstractOrderEntryModel entry) { final Integer digits = entry.getOrder().getCurrency().getDigits(); final LineItem lineItem = new LineItem(); - lineItem.setLineItemType(LineItem.LINE_ITEM_TYPE.PHYSICAL); - final LineItemReference lineItemReference = new LineItemReference(null, String.valueOf(entry.getEntryNumber())); + lineItem.setLineItemType(LineItemType.PHYSICAL); + final LineItemReference lineItemReference = new LineItemReference(); + lineItemReference.setValue(String.valueOf(entry.getEntryNumber())); lineItem.setLineItemReference(lineItemReference); lineItem.setName(StringEscapeUtils.escapeXml(entry.getProduct().getName())); lineItem.setQuantity(String.valueOf(entry.getQuantity())); @@ -110,12 +130,13 @@ private LineItem createLineItem(final AbstractOrderEntryModel entry) { private void addShippingFeeLineItem(final CartModel cartModel, final Integer digits, final List lineItems) { final LineItem shippingFeeLineItem = new LineItem(); - shippingFeeLineItem.setLineItemType(SHIPPING_FEE); - final LineItemReference lineItemReference = new LineItemReference(null, "SHIPPING_LINE_ITEM_REFERENCE"); + shippingFeeLineItem.setLineItemType(LineItemType.SHIPPING_FEE); + final LineItemReference lineItemReference = new LineItemReference(); + lineItemReference.setValue(SHIPPING_LINE_ITEM_REFERENCE); shippingFeeLineItem.setLineItemReference(lineItemReference); shippingFeeLineItem.setName(cartModel.getDeliveryMode().getName()); shippingFeeLineItem.setQuantity("1"); - shippingFeeLineItem.setQuantityUnit("shipping"); + shippingFeeLineItem.setQuantityUnit(SHIPPING); shippingFeeLineItem.setUnitPrice(convertDoubleToStringFormat(digits, cartModel.getDeliveryCost())); shippingFeeLineItem.setTotalAmount(convertDoubleToStringFormat(digits, cartModel.getDeliveryCost())); shippingFeeLineItem.setTotalDiscountAmount("0"); @@ -129,13 +150,14 @@ private void addShippingFeeLineItem(final CartModel cartModel, final Integer dig private LineItem createDiscountLineItem(final CartModel cartModel, final Integer digits) { final LineItem lineItem = new LineItem(); - lineItem.setLineItemType(DISCOUNT); - final LineItemReference lineItemReference = new LineItemReference(null, DISCOUNT_LINE_ITEM_REFERENCE); + lineItem.setLineItemType(LineItemType.DISCOUNT); + final LineItemReference lineItemReference = new LineItemReference(); + lineItemReference.setValue(DISCOUNT_LINE_ITEM_REFERENCE); lineItem.setLineItemReference(lineItemReference); cartModel.getTotalTax(); lineItem.setName(ORDER_DISCOUNT); lineItem.setQuantity("1"); - lineItem.setQuantityUnit("discount"); + lineItem.setQuantityUnit(DISCOUNT); lineItem.setUnitPrice("0"); final double discountValue = cartModel.getGlobalDiscountValues().stream().filter(DiscountValue::isAbsolute).mapToDouble(DiscountValue::getAppliedValue).sum(); lineItem.setTotalAmount(convertDoubleToStringFormat(digits, -discountValue)); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayLevel23DataValidator.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayLevel23DataValidator.java new file mode 100644 index 00000000..bb3b5457 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayLevel23DataValidator.java @@ -0,0 +1,115 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.data.Item; +import com.worldpay.data.Purchase; +import com.worldpay.service.payment.WorldpayLevel23DataValidator; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; + +import java.util.List; +import java.util.Objects; + +/** + * Default implementation of {@link WorldpayLevel23DataValidator} + */ +public class DefaultWorldpayLevel23DataValidator implements WorldpayLevel23DataValidator { + + /** + * {@inheritDoc} + */ + @Override + public boolean isValidLevel2Data(final List purchaseList) { + final Purchase purchaseData = purchaseList.get(0); + + boolean isValid = isValidField(purchaseData.getCustomerReference(), 17) + && isValidField(purchaseData.getCardAcceptorTaxId(), 20); + + if (isValid) { + if (!isValidField(purchaseData.getDestinationPostalCode(), 10)) { + purchaseData.setDestinationPostalCode(null); + } + final List items = purchaseData.getItem(); + if (CollectionUtils.isEmpty(items)) { + return true; + } + return items.stream() + .filter(Objects::nonNull) + .map(this::validateItemForLevel2AndRemoveInvalidOptionalData) + .reduce(Boolean::logicalAnd).orElse(false); + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isValidLevel3Data(final List purchaseList) { + final Purchase purchaseData = purchaseList.get(0); + return isValidField(purchaseData.getCustomerReference(), 17) + && isValidField(purchaseData.getCardAcceptorTaxId(), 20) + && isValidField(purchaseData.getDestinationPostalCode(), 10) + && Objects.nonNull(purchaseData.getItem()) + && isItemObjectValidForLevel3Data(purchaseData.getItem()); + } + + /** + * Validates the mandatory field for level 2 data , and removes invalid optional fields + * + * @param item the item to validate + * @return true if item is valid for level 2, false otherwise + */ + protected boolean validateItemForLevel2AndRemoveInvalidOptionalData(final Item item) { + if (isValidField(item.getDescription(), 26)) { + if (!isValidField(item.getProductCode(), 12)) { + item.setProductCode(null); + } + if (!isValidField(item.getCommodityCode(), 12)) { + item.setCommodityCode(null); + } + if (!isValidField(item.getUnitOfMeasure(), 12)) { + item.setUnitOfMeasure(null); + } + return true; + } + return false; + } + + /** + * Checks if the list of Item objects are valid for level 3 data + * + * @param items list of items + * @return true if all valid, false otherwise + */ + protected boolean isItemObjectValidForLevel3Data(final List items) { + return items.stream() + .map(this::validateItemForLevel3Data) + .allMatch(item -> item.equals(true)); + } + + /** + * Checks if the mandatory fields for level 3 data in the item object are present and valid + * + * @param item the item to validate + * @return true if item is valid, false otherwise + */ + protected boolean validateItemForLevel3Data(final Item item) { + return Objects.nonNull(item) + && isValidField(item.getDescription(), 26) + && isValidField(item.getProductCode(), 12) + && isValidField(item.getCommodityCode(), 12) + && isValidField(item.getUnitOfMeasure(), 12); + } + + /** + * returns true if the field is not blank and within the max size + * + * @param object the object to check + * @param maxSize the max size allowed + * @return returns true if field is valid, false otherwise + */ + protected boolean isValidField(final String object, final int maxSize) { + return StringUtils.isNotBlank(object) + && object.length() <= maxSize; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayLevel23Strategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayLevel23Strategy.java new file mode 100644 index 00000000..dc6b41ff --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayLevel23Strategy.java @@ -0,0 +1,233 @@ +package com.worldpay.service.payment.impl; + +import com.google.common.collect.ImmutableList; +import com.worldpay.data.BranchSpecificExtension; +import com.worldpay.data.Item; +import com.worldpay.data.Purchase; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.payment.WorldpayAdditionalDataRequestStrategy; +import com.worldpay.service.payment.WorldpayLevel23DataValidator; +import com.worldpay.service.payment.WorldpayLevel23Strategy; +import com.worldpay.service.payment.WorldpayOrderService; +import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; +import com.worldpay.strategy.WorldpayMerchantStrategy; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; +import de.hybris.platform.core.model.c2l.CurrencyModel; +import de.hybris.platform.core.model.order.AbstractOrderEntryModel; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.product.ProductModel; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.util.DiscountValue; +import de.hybris.platform.util.TaxValue; +import org.apache.commons.lang3.NotImplementedException; + +import java.math.BigDecimal; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; +import static java.lang.String.valueOf; + +/** + * Default implementation of {@link WorldpayLevel23Strategy}. + */ +public class DefaultWorldpayLevel23Strategy extends AbstractWorldpayLevel23Strategy implements WorldpayAdditionalDataRequestStrategy { + + private static final String US_COUNTRY_ISO_CODE = "US"; + private static final String CA_COUNTRY_ISO_CODE = "CA"; + private static final String NOT_IMPLEMENTED_ERROR_MESSAGE = "Implement this method based on business requirements"; + + protected final WorldpayMerchantStrategy worldpayMerchantStrategy; + protected final WorldpayOrderService worldpayOrderService; + protected final WorldpayLevel23DataValidator worldpayLevel23DataValidator; + + public DefaultWorldpayLevel23Strategy(final WorldpayMerchantStrategy worldpayMerchantStrategy, + final WorldpayOrderService worldpayOrderService, + final WorldpayLevel23DataValidator worldpayLevel23DataValidator) { + this.worldpayMerchantStrategy = worldpayMerchantStrategy; + this.worldpayOrderService = worldpayOrderService; + this.worldpayLevel23DataValidator = worldpayLevel23DataValidator; + } + + /** + * {@inheritDoc} + */ + @Override + public void populateRequestWithAdditionalData(final AbstractOrderModel cart, + final WorldpayAdditionalInfoData worldpayAdditionalInfoData, + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator) { + if (isLevel3Enabled(cart) || isLevel2Enabled(cart)) { + final BranchSpecificExtension level23Data = createLevel23Data(cart); + if (worldpayLevel23DataValidator.isValidLevel3Data(level23Data.getPurchase()) || worldpayLevel23DataValidator.isValidLevel2Data(level23Data.getPurchase())) { + authoriseRequestParametersCreator.withLevel23Data(level23Data); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public BranchSpecificExtension createLevel23Data(final AbstractOrderModel abstractOrder) { + validateParameterNotNull(abstractOrder, "The cart is null"); + + final Purchase purchase = new Purchase(); + setCustomerReference(abstractOrder, purchase); + purchase.setCardAcceptorTaxId(worldpayMerchantStrategy.getMerchant().getCardAcceptorTaxID()); + + final CurrencyModel currency = abstractOrder.getCurrency(); + setSalesTaxAndTaxExempt(purchase, currency, abstractOrder); + + purchase.setDiscountAmount(worldpayOrderService.createAmount(currency, abstractOrder.getTotalDiscounts())); + purchase.setShippingAmount(worldpayOrderService.createAmount(currency, abstractOrder.getDeliveryCost())); + setDutyAmount(abstractOrder, purchase); + + final AddressModel deliveryAddress = abstractOrder.getDeliveryAddress(); + purchase.setDestinationCountryCode(deliveryAddress.getCountry().getIsocode()); + purchase.setDestinationPostalCode(deliveryAddress.getPostalcode()); + + final LocalDateTime orderDate = Instant.ofEpochMilli(abstractOrder.getDate().getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + purchase.setOrderDate(WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(orderDate)); + + final List items = abstractOrder.getEntries().stream() + .map(orderEntry -> createItem(orderEntry, currency)) + .collect(Collectors.toList()); + purchase.setItem(items); + + final BranchSpecificExtension branchSpecificExtension = new BranchSpecificExtension(); + branchSpecificExtension.setPurchase(List.of(purchase)); + + return branchSpecificExtension; + } + + /** + * Populates the customer reference. Override this method with real values based on business requirements + */ + @Override + protected void setCustomerReference(final AbstractOrderModel order, final Purchase purchase) { + throw new NotImplementedException(NOT_IMPLEMENTED_ERROR_MESSAGE); + } + + /** + * Populates the product description. Override this method with real values based on business requirements + */ + @Override + protected void setProductDescription(final ProductModel product, final Item item) { + throw new NotImplementedException(NOT_IMPLEMENTED_ERROR_MESSAGE); + } + + /** + * Populates the duty amount. Override this method with real values based on business requirements + */ + @Override + protected void setDutyAmount(final AbstractOrderModel order, final Purchase purchase) { + throw new NotImplementedException(NOT_IMPLEMENTED_ERROR_MESSAGE); + } + + /** + * Checks if the Level 2 is enabled for the cart + * + * @param abstractOrder the cart + * @return true if enabled, false otherwise + */ + protected boolean isLevel2Enabled(final AbstractOrderModel abstractOrder) { + return abstractOrder.getSite().getEnableLevel2() + && isBillingAddressUSorCA(abstractOrder); + } + + /** + * Checks if the Level 3 is enabled for the cart + * + * @param abstractOrder the cart + * @return true if enabled, false otherwise + */ + protected boolean isLevel3Enabled(final AbstractOrderModel abstractOrder) { + return abstractOrder.getSite().getEnableLevel3() + && isBillingAddressUSorCA(abstractOrder); + } + + /** + * Sets the sales tax of the order on the purchase item. + * + * @param purchase the purchase item + * @param currency the order currency + * @param abstractOrder the order + */ + protected void setSalesTaxAndTaxExempt(final Purchase purchase, final CurrencyModel currency, final AbstractOrderModel abstractOrder) { + final Double totalTax = abstractOrder.getTotalTax(); + purchase.setSalesTax(worldpayOrderService.createAmount(currency, totalTax)); + purchase.setTaxExempt(BigDecimal.ZERO.compareTo(BigDecimal.valueOf(totalTax)) == 0); + } + + /** + * Create an Item for every order entry + * + * @param orderEntry the order entry + * @param currency currency of the order + * @return {@link Item} + */ + protected Item createItem(final AbstractOrderEntryModel orderEntry, final CurrencyModel currency) { + final Item item = new Item(); + final ProductModel product = orderEntry.getProduct(); + item.setProductCode(product.getCode()); + setProductDescription(product, item); + item.setCommodityCode(product.getCommodityCode()); + item.setQuantity(valueOf(orderEntry.getQuantity())); + item.setUnitCost(worldpayOrderService.createAmount(currency, orderEntry.getBasePrice())); + item.setUnitOfMeasure(orderEntry.getUnit().getCode()); + + final Double totalPriceWithTax = orderEntry.getTotalPrice(); + item.setItemTotalWithTax(worldpayOrderService.createAmount(currency, totalPriceWithTax)); + final Double appliedTax = getAppliedTaxValue(orderEntry); + item.setTaxAmount(worldpayOrderService.createAmount(currency, appliedTax)); + item.setItemTotal(worldpayOrderService.createAmount(currency, totalPriceWithTax - appliedTax)); + item.setItemDiscountAmount(worldpayOrderService.createAmount(currency, getDiscountValue(orderEntry))); + + return item; + } + + /** + * Returns true if shipping address of the cart is Canada or United States + * + * @param abstractOrder the cart + * @return true if address in US or CA, false otherwise + */ + protected boolean isBillingAddressUSorCA(final AbstractOrderModel abstractOrder) { + final AddressModel paymentAddress = abstractOrder.getPaymentAddress(); + if (Objects.nonNull(paymentAddress)) { + final String countryIsoCode = paymentAddress.getCountry().getIsocode(); + return US_COUNTRY_ISO_CODE.equals(countryIsoCode) || CA_COUNTRY_ISO_CODE.equals(countryIsoCode); + } + return false; + } + + /** + * Sums the discount values applied to an order entry + * + * @param orderEntry the order entry + * @return the discount value + */ + protected Double getDiscountValue(final AbstractOrderEntryModel orderEntry) { + return orderEntry.getDiscountValues().stream() + .map(DiscountValue::getAppliedValue) + .reduce(0d, Double::sum); + } + + /** + * Returns the sum of applied tax values for the order entry + * + * @param orderEntry the order entry + * @return the applied tax value + */ + protected double getAppliedTaxValue(final AbstractOrderEntryModel orderEntry) { + return orderEntry.getTaxValues().stream() + .map(TaxValue::getAppliedValue) + .reduce(0d, Double::sum); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayOrderService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayOrderService.java index 7d09dac0..e6610346 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayOrderService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayOrderService.java @@ -1,18 +1,21 @@ package com.worldpay.service.payment.impl; import com.worldpay.core.services.strategies.RecurringGenerateMerchantTransactionCodeStrategy; -import com.worldpay.data.ApplePayAdditionalAuthInfo; -import com.worldpay.data.CSEAdditionalAuthInfo; +import com.worldpay.data.*; +import com.worldpay.data.applepay.ApplePay; +import com.worldpay.data.applepay.Header; +import com.worldpay.data.klarna.KlarnaMerchantUrls; +import com.worldpay.data.klarna.KlarnaPayment; +import com.worldpay.data.klarna.KlarnaRedirectURLs; +import com.worldpay.data.payment.Cse; +import com.worldpay.data.payment.PayWithGoogleSSL; +import com.worldpay.data.payment.Payment; import com.worldpay.exception.WorldpayConfigurationException; -import com.worldpay.klarna.WorldpayKlarnaUtils; import com.worldpay.service.WorldpayUrlService; -import com.worldpay.service.model.*; -import com.worldpay.service.model.applepay.ApplePay; -import com.worldpay.service.model.applepay.Header; -import com.worldpay.service.model.klarna.KlarnaMerchantUrls; -import com.worldpay.service.model.klarna.KlarnaRedirectURLs; -import com.worldpay.service.model.payment.*; +import com.worldpay.service.model.payment.PaymentType; +import com.worldpay.service.payment.WorldpayKlarnaService; import com.worldpay.service.payment.WorldpayOrderService; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; import de.hybris.platform.commerceservices.order.CommerceCheckoutService; import de.hybris.platform.commerceservices.service.data.CommerceCheckoutParameter; import de.hybris.platform.core.model.c2l.CurrencyModel; @@ -26,6 +29,8 @@ import java.util.Currency; import java.util.Objects; +import static com.worldpay.service.model.payment.PaymentType.CSEDATA; + /** * {@inheritDoc} */ @@ -33,18 +38,18 @@ public class DefaultWorldpayOrderService implements WorldpayOrderService { protected final CommonI18NService commonI18NService; protected final WorldpayUrlService worldpayUrlService; - protected final WorldpayKlarnaUtils worldpayKlarnaUtils; + protected final WorldpayKlarnaService worldpayKlarnaService; protected final CommerceCheckoutService commerceCheckoutService; protected final RecurringGenerateMerchantTransactionCodeStrategy recurringGenerateMerchantTransactionCodeStrategy; public DefaultWorldpayOrderService(final CommonI18NService commonI18NService, final WorldpayUrlService worldpayUrlService, - final WorldpayKlarnaUtils worldpayKlarnaUtils, + final WorldpayKlarnaService worldpayKlarnaService, final CommerceCheckoutService commerceCheckoutService, final RecurringGenerateMerchantTransactionCodeStrategy recurringGenerateMerchantTransactionCodeStrategy) { this.commonI18NService = commonI18NService; this.worldpayUrlService = worldpayUrlService; - this.worldpayKlarnaUtils = worldpayKlarnaUtils; + this.worldpayKlarnaService = worldpayKlarnaService; this.commerceCheckoutService = commerceCheckoutService; this.recurringGenerateMerchantTransactionCodeStrategy = recurringGenerateMerchantTransactionCodeStrategy; } @@ -55,7 +60,11 @@ public DefaultWorldpayOrderService(final CommonI18NService commonI18NService, @Override public Amount createAmount(final Currency currency, final int amount) { final Double roundedValue = commonI18NService.convertAndRoundCurrency(Math.pow(10, currency.getDefaultFractionDigits()), 1, currency.getDefaultFractionDigits(), amount); - return new Amount(String.valueOf(roundedValue), currency.getCurrencyCode(), String.valueOf(currency.getDefaultFractionDigits())); + final Amount amountData = new Amount(); + amountData.setCurrencyCode(currency.getCurrencyCode()); + amountData.setValue(String.valueOf(roundedValue)); + amountData.setExponent(String.valueOf(currency.getDefaultFractionDigits())); + return amountData; } /** @@ -73,7 +82,11 @@ public Amount createAmount(final CurrencyModel currencyModel, final double amoun @Override public Amount createAmount(final Currency currency, final double amount) { final Double roundedValue = commonI18NService.convertAndRoundCurrency(1, Math.pow(10, currency.getDefaultFractionDigits()), 0, amount); - return new Amount(String.valueOf(roundedValue.intValue()), currency.getCurrencyCode(), String.valueOf(currency.getDefaultFractionDigits())); + final Amount amountData = new Amount(); + amountData.setCurrencyCode(currency.getCurrencyCode()); + amountData.setValue(String.valueOf(roundedValue.intValue())); + amountData.setExponent(String.valueOf(currency.getDefaultFractionDigits())); + return amountData; } /** @@ -90,7 +103,11 @@ public BigDecimal convertAmount(final Amount amount) { */ @Override public BasicOrderInfo createBasicOrderInfo(final String worldpayOrderCode, final String description, final Amount amount) { - return new BasicOrderInfo(worldpayOrderCode, description, amount); + final BasicOrderInfo basicOrderInfor = new BasicOrderInfo(); + basicOrderInfor.setAmount(amount); + basicOrderInfor.setDescription(description); + basicOrderInfor.setOrderCode(worldpayOrderCode); + return basicOrderInfor; } /** @@ -100,18 +117,24 @@ public BasicOrderInfo createBasicOrderInfo(final String worldpayOrderCode, final public Payment createKlarnaPayment(final String countryCode, final LanguageModel language, final String extraMerchantData, final String klarnaPaymentMethod) throws WorldpayConfigurationException { PaymentType klarnaPaymentType = null; - if (worldpayKlarnaUtils.isKlarnaPaymentType(klarnaPaymentMethod)) { + if (worldpayKlarnaService.isKlarnaPaymentType(klarnaPaymentMethod)) { klarnaPaymentType = PaymentType.getPaymentType(klarnaPaymentMethod); } final String languageCode = commonI18NService.getLocaleForLanguage(language).toLanguageTag(); + final String locale = languageCode.concat("-").concat(countryCode); if (Objects.nonNull(klarnaPaymentType) && PaymentType.KLARNASSL.equals(klarnaPaymentType)) { - final KlarnaMerchantUrls merchantUrls = new KlarnaMerchantUrls(worldpayUrlService.getBaseWebsiteUrlForSite(), worldpayUrlService.getKlarnaConfirmationURL()); - return PaymentBuilder.createKlarnaPayment(countryCode, languageCode, - merchantUrls, extraMerchantData); + final KlarnaMerchantUrls merchantUrls = new KlarnaMerchantUrls(); + merchantUrls.setCheckoutURL(worldpayUrlService.getBaseWebsiteUrlForSite()); + merchantUrls.setConfirmationURL(worldpayUrlService.getKlarnaConfirmationURL()); + return WorldpayInternalModelTransformerUtil.createKlarnaPayment(countryCode, locale, merchantUrls, extraMerchantData); } else if (Objects.nonNull(klarnaPaymentType)) { - final KlarnaRedirectURLs klarnaRedirectURLs = new KlarnaRedirectURLs(worldpayUrlService.getFullSuccessURL(), worldpayUrlService.getFullCancelURL(), worldpayUrlService.getFullPendingURL(), worldpayUrlService.getFullFailureURL()); - return PaymentBuilder.createKlarnaPayment(countryCode, languageCode, extraMerchantData, klarnaPaymentMethod, klarnaRedirectURLs); + final KlarnaRedirectURLs klarnaRedirectURLs = new KlarnaRedirectURLs(); + klarnaRedirectURLs.setSuccessURL(worldpayUrlService.getFullSuccessURL()); + klarnaRedirectURLs.setCancelURL(worldpayUrlService.getFullCancelURL()); + klarnaRedirectURLs.setPendingURL(worldpayUrlService.getFullPendingURL()); + klarnaRedirectURLs.setFailureURL(worldpayUrlService.getFullFailureURL()); + return WorldpayInternalModelTransformerUtil.createKlarnaPayment(countryCode, locale, extraMerchantData, klarnaPaymentMethod, klarnaRedirectURLs); } else { throw new WorldpayConfigurationException("Invalid Klarna Payment Method"); } @@ -122,8 +145,18 @@ public Payment createKlarnaPayment(final String countryCode, final LanguageModel */ @Override public Payment createApplePayPayment(final ApplePayAdditionalAuthInfo worldpayAdditionalInfoApplePayData) { - final Header header = new Header(worldpayAdditionalInfoApplePayData.getHeader().getEphemeralPublicKey(), worldpayAdditionalInfoApplePayData.getHeader().getPublicKeyHash(), worldpayAdditionalInfoApplePayData.getHeader().getTransactionId(), null); - return new ApplePay(header, worldpayAdditionalInfoApplePayData.getSignature(), worldpayAdditionalInfoApplePayData.getVersion(), worldpayAdditionalInfoApplePayData.getData(), null); + final Header header = new Header(); + header.setEphemeralPublicKey(worldpayAdditionalInfoApplePayData.getHeader().getEphemeralPublicKey()); + header.setPublicKeyHash(worldpayAdditionalInfoApplePayData.getHeader().getPublicKeyHash()); + header.setTransactionId(worldpayAdditionalInfoApplePayData.getHeader().getTransactionId()); + + final ApplePay applePay = new ApplePay(); + applePay.setHeader(header); + applePay.setSignature(worldpayAdditionalInfoApplePayData.getSignature()); + applePay.setVersion(worldpayAdditionalInfoApplePayData.getVersion()); + applePay.setData(worldpayAdditionalInfoApplePayData.getData()); + + return applePay; } /** @@ -131,7 +164,12 @@ public Payment createApplePayPayment(final ApplePayAdditionalAuthInfo worldpayAd */ @Override public Cse createCsePayment(final CSEAdditionalAuthInfo cseAdditionalAuthInfo, final Address billingAddress) { - return PaymentBuilder.createCSE(cseAdditionalAuthInfo.getEncryptedData(), billingAddress); + final Cse cse = new Cse(); + cse.setAddress(billingAddress); + cse.setEncryptedData(cseAdditionalAuthInfo.getEncryptedData()); + cse.setPaymentType(CSEDATA.getMethodCode()); + + return cse; } /** @@ -139,7 +177,13 @@ public Cse createCsePayment(final CSEAdditionalAuthInfo cseAdditionalAuthInfo, f */ @Override public PayWithGoogleSSL createGooglePayPayment(final String protocolVersion, final String signature, final String signedMessage) { - return new PayWithGoogleSSL(protocolVersion, signature, signedMessage); + final PayWithGoogleSSL payWithGoogleSSL = new PayWithGoogleSSL(); + payWithGoogleSSL.setProtocolVersion(protocolVersion); + payWithGoogleSSL.setSignature(signature); + payWithGoogleSSL.setSignedMessage(signedMessage); + payWithGoogleSSL.setPaymentType(PaymentType.PAYWITHGOOGLESSL.getMethodCode()); + + return payWithGoogleSSL; } /** @@ -174,8 +218,8 @@ public CommerceCheckoutParameter createCommerceCheckoutParameter(final AbstractO * {@inheritDoc} */ @Override - public String generateWorldpayOrderCode(final AbstractOrderModel abstractOrderModel){ - return recurringGenerateMerchantTransactionCodeStrategy.generateCode(abstractOrderModel); + public String generateWorldpayOrderCode(final AbstractOrderModel abstractOrderModel) { + return recurringGenerateMerchantTransactionCodeStrategy.generateCode(abstractOrderModel); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayPrimeRoutingStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayPrimeRoutingStrategy.java new file mode 100644 index 00000000..09893ff9 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayPrimeRoutingStrategy.java @@ -0,0 +1,37 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.core.services.WorldpayPrimeRoutingService; +import com.worldpay.enums.PaymentAction; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.payment.WorldpayAdditionalDataRequestStrategy; +import com.worldpay.service.payment.WorldpayLevel23Strategy; +import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.order.CartModel; + +/** + * Default implementation of {@link WorldpayLevel23Strategy}. + */ +public class DefaultWorldpayPrimeRoutingStrategy implements WorldpayAdditionalDataRequestStrategy { + + protected final WorldpayPrimeRoutingService worldpayPrimeRoutingService; + + public DefaultWorldpayPrimeRoutingStrategy(final WorldpayPrimeRoutingService worldpayPrimeRoutingService) { + this.worldpayPrimeRoutingService = worldpayPrimeRoutingService; + } + + /** + * {@inheritDoc} + */ + @Override + public void populateRequestWithAdditionalData(final AbstractOrderModel cart, + final WorldpayAdditionalInfoData worldpayAdditionalInfoData, + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator) { + final CartModel cartModel = (CartModel) cart; + if (worldpayPrimeRoutingService.isPrimeRoutingEnabled(cartModel)) { + authoriseRequestParametersCreator + .withPaymentDetailsAction(PaymentAction.SALE); + worldpayPrimeRoutingService.setAuthorisedWithPrimeRoutingOnCart(cartModel); + } + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayRedirectOrderService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayRedirectOrderService.java index cabfb7e7..78427fb4 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayRedirectOrderService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayRedirectOrderService.java @@ -7,7 +7,7 @@ import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.service.WorldpayServiceGateway; import com.worldpay.service.hop.WorldpayHOPPService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.payment.WorldpayRedirectOrderService; import com.worldpay.transaction.WorldpayPaymentTransactionService; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayRiskDataService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayRiskDataService.java index 7c8b8ce8..f1f3a595 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayRiskDataService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpayRiskDataService.java @@ -1,7 +1,7 @@ package com.worldpay.service.payment.impl; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.threeds2.RiskData; +import com.worldpay.data.threeds2.RiskData; import com.worldpay.service.payment.WorldpayRiskDataService; import de.hybris.platform.core.model.order.CartModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpaySepaMandateStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpaySepaMandateStrategy.java new file mode 100644 index 00000000..de0d96f2 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/impl/DefaultWorldpaySepaMandateStrategy.java @@ -0,0 +1,30 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.internal.model.SEPADIRECTDEBITSSL; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.payment.WorldpayAdditionalDataRequestStrategy; +import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; +import de.hybris.platform.core.model.order.AbstractOrderModel; + +import java.util.Collection; +import java.util.stream.Stream; + +public class DefaultWorldpaySepaMandateStrategy implements WorldpayAdditionalDataRequestStrategy { + + private static final String MANDATE_TYPE = "ONE-OFF"; + + /** + * {@inheritDoc} + */ + @Override + public void populateRequestWithAdditionalData(final AbstractOrderModel cart, + final WorldpayAdditionalInfoData worldpayAdditionalInfoData, + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator) { + + Stream.ofNullable(authoriseRequestParametersCreator.build().getIncludedPTs()) + .flatMap(Collection::stream) + .filter(paymentType -> SEPADIRECTDEBITSSL.class.equals(paymentType.getModelClass())) + .findAny() + .ifPresent(paymentType -> authoriseRequestParametersCreator.withMandateType(MANDATE_TYPE)); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/WorldpayRequestFactory.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/WorldpayRequestFactory.java index bda3095c..94ed6f97 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/WorldpayRequestFactory.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/WorldpayRequestFactory.java @@ -3,7 +3,7 @@ import com.worldpay.data.*; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.*; import com.worldpay.service.response.CreateTokenResponse; import de.hybris.platform.core.model.order.AbstractOrderModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/WorldpayRequestService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/WorldpayRequestService.java index e9e9ac69..a1cc762c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/WorldpayRequestService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/WorldpayRequestService.java @@ -1,26 +1,24 @@ package com.worldpay.service.payment.request; -import com.worldpay.data.AdditionalAuthInfo; import com.worldpay.data.CSEAdditionalAuthInfo; import com.worldpay.enums.order.DynamicInteractionType; import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; import com.worldpay.enums.payment.storedCredentials.Usage; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.Token; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.data.Browser; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.Session; +import com.worldpay.data.Shopper; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.Token; +import com.worldpay.data.token.TokenRequest; import com.worldpay.service.request.CreateTokenServiceRequest; import com.worldpay.service.request.UpdateTokenServiceRequest; -import de.hybris.platform.core.model.order.AbstractOrderModel; -import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.user.AddressModel; -import de.hybris.platform.core.model.user.CustomerModel; - /** * Request factory for building request to Worldpay @@ -96,9 +94,9 @@ CreateTokenServiceRequest createTokenServiceRequest(final MerchantInfo merchantI /** * Creates a payment element to be used in bank transfers * - * @param worldpayOrderCode worldpay order code - * @param paymentMethod indicates which payment method for bank transfer is going to be used (IDEAL-SSL,...) - * @param shopperBankCode indicates the selected bank by the user + * @param worldpayOrderCode worldpay order code + * @param paymentMethod indicates which payment method for bank transfer is going to be used (IDEAL-SSL,...) + * @param shopperBankCode indicates the selected bank by the user * @return Payment object */ Payment createBankPayment(final String worldpayOrderCode, final String paymentMethod, final String shopperBankCode) throws WorldpayConfigurationException; @@ -154,22 +152,6 @@ UpdateTokenServiceRequest createUpdateTokenServiceRequest(final MerchantInfo mer */ CardDetails createCardDetails(final CSEAdditionalAuthInfo cseAdditionalAuthInfo, final AddressModel paymentAddress); - /** - * Gets the delivery Address for given cart, id delivery address true will return the delivery address, otherwise payment address - * - * @param abstractOrder - * @param isDeliveryAddress if it's delivery addresss - * @return {@link Address} - */ - Address getAddressFromCart(final AbstractOrderModel abstractOrder, final boolean isDeliveryAddress); - - /** - * @param cartModel - * @param additionalAuthInfo - * @return - */ - Address getBillingAddress(final CartModel cartModel, final AdditionalAuthInfo additionalAuthInfo); - /** * Get the Dynamic Interaction type for the worldpay additional data * @@ -177,13 +159,4 @@ UpdateTokenServiceRequest createUpdateTokenServiceRequest(final MerchantInfo mer * @return the {@link DynamicInteractionType} */ DynamicInteractionType getDynamicInteractionType(final WorldpayAdditionalInfoData worldpayAdditionalInfoData); - - /** - * Get customer email - * - * @param customerModel them customer model - * @return the cuatomer email - */ - String getEmailForCustomer(final CustomerModel customerModel); - } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestFactory.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestFactory.java index 95ffabc7..d60a03ba 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestFactory.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestFactory.java @@ -1,29 +1,26 @@ package com.worldpay.service.payment.request.impl; +import com.worldpay.core.services.WorldpayCartService; import com.worldpay.data.*; import com.worldpay.enums.order.DynamicInteractionType; import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; import com.worldpay.enums.payment.storedCredentials.Usage; import com.worldpay.exception.WorldpayConfigurationException; -import com.worldpay.klarna.WorldpayKlarnaUtils; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.*; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.threeds2.RiskData; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.Token; -import com.worldpay.service.model.token.TokenRequest; -import com.worldpay.service.payment.WorldpayKlarnaStrategy; -import com.worldpay.service.payment.WorldpayOrderService; -import com.worldpay.service.payment.WorldpayRiskDataService; -import com.worldpay.service.payment.WorldpayTokenEventReferenceCreationStrategy; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.payment.*; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.Token; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.service.model.payment.PaymentType; +import com.worldpay.service.payment.*; import com.worldpay.service.payment.request.WorldpayRequestFactory; import com.worldpay.service.payment.request.WorldpayRequestService; import com.worldpay.service.request.*; import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; import com.worldpay.service.response.CreateTokenResponse; -import com.worldpay.strategy.WorldpayAuthenticatedShopperIdStrategy; import de.hybris.platform.core.model.c2l.CurrencyModel; import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.core.model.order.CartModel; @@ -50,26 +47,26 @@ public class DefaultWorldpayRequestFactory implements WorldpayRequestFactory { protected final WorldpayTokenEventReferenceCreationStrategy worldpayTokenEventReferenceCreationStrategy; protected final WorldpayOrderService worldpayOrderService; - protected final WorldpayKlarnaStrategy worldpayKlarnaStrategy; + protected final WorldpayKlarnaService worldpayKlarnaService; protected final WorldpayRiskDataService worldpayRiskDataService; - protected final WorldpayAuthenticatedShopperIdStrategy worldpayAuthenticatedShopperIdStrategy; - protected final WorldpayKlarnaUtils worldpayKlarnaUtils; + protected final WorldpayCartService worldpayCartService; protected final WorldpayRequestService worldpayRequestService; + protected final WorldpayAdditionalRequestDataService worldpayAdditionalRequestDataService; public DefaultWorldpayRequestFactory(final WorldpayTokenEventReferenceCreationStrategy worldpayTokenEventReferenceCreationStrategy, final WorldpayOrderService worldpayOrderService, - final WorldpayKlarnaStrategy worldpayKlarnaStrategy, + final WorldpayKlarnaService worldpayKlarnaService, final WorldpayRiskDataService worldpayRiskDataService, - final WorldpayAuthenticatedShopperIdStrategy worldpayAuthenticatedShopperIdStrategy, - final WorldpayKlarnaUtils worldpayKlarnaUtils, - final WorldpayRequestService worldpayRequestService) { + final WorldpayCartService worldpayCartService, + final WorldpayRequestService worldpayRequestService, + final WorldpayAdditionalRequestDataService worldpayAdditionalRequestDataService) { this.worldpayTokenEventReferenceCreationStrategy = worldpayTokenEventReferenceCreationStrategy; this.worldpayOrderService = worldpayOrderService; - this.worldpayKlarnaStrategy = worldpayKlarnaStrategy; + this.worldpayKlarnaService = worldpayKlarnaService; this.worldpayRiskDataService = worldpayRiskDataService; - this.worldpayAuthenticatedShopperIdStrategy = worldpayAuthenticatedShopperIdStrategy; - this.worldpayKlarnaUtils = worldpayKlarnaUtils; + this.worldpayCartService = worldpayCartService; this.worldpayRequestService = worldpayRequestService; + this.worldpayAdditionalRequestDataService = worldpayAdditionalRequestDataService; } /** @@ -79,7 +76,7 @@ public DefaultWorldpayRequestFactory(final WorldpayTokenEventReferenceCreationSt public CreateTokenServiceRequest buildTokenRequest(final MerchantInfo merchantInfo, final CartModel cartModel, final CSEAdditionalAuthInfo cseAdditionalAuthInfo, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) { - final Address billingAddress = worldpayRequestService.getBillingAddress(cartModel, cseAdditionalAuthInfo); + final Address billingAddress = worldpayCartService.getBillingAddress(cartModel, cseAdditionalAuthInfo); final String tokenEventReference = getWorldpayTokenEventReferenceCreationStrategy().createTokenEventReference(); final TokenRequest tokenRequest = worldpayRequestService.createTokenRequest(tokenEventReference, null); final Cse csePayment = worldpayOrderService.createCsePayment(cseAdditionalAuthInfo, billingAddress); @@ -127,7 +124,7 @@ public DirectAuthoriseServiceRequest buildDirectAuthoriseRequestWithTokenForCSE( final RiskData riskData = worldpayRiskDataService.createRiskData(cartModel, worldpayAdditionalInfoData); final Token token = worldpayRequestService.createToken(((CreditCardPaymentInfoModel) cartModel.getPaymentInfo()).getSubscriptionId(), worldpayAdditionalInfoData.getSecurityCode()); - final String shopperEmailAddress = worldpayRequestService.getEmailForCustomer((CustomerModel) cartModel.getUser()); + final String shopperEmailAddress = worldpayCartService.getEmailForCustomer(cartModel); final Session session = worldpayRequestService.createSession(worldpayAdditionalInfoData); final Browser browser = worldpayRequestService.createBrowser(worldpayAdditionalInfoData); @@ -137,21 +134,22 @@ public DirectAuthoriseServiceRequest buildDirectAuthoriseRequestWithTokenForCSE( final DynamicInteractionType dynamicInteractionType = worldpayRequestService.getDynamicInteractionType(worldpayAdditionalInfoData); final StoredCredentials storedCredentials = createStoredCredentials(worldpayAdditionalInfoData); - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(orderInfo) .withPayment(token) .withShopper(authenticatedShopper) - .withShippingAddress(worldpayRequestService.getAddressFromCart(cartModel, true)) + .withShippingAddress(worldpayCartService.getAddressFromCart(cartModel, true)) .withBillingAddress(null) .withStatementNarrative(null) .withDynamicInteractionType(dynamicInteractionType) .withAdditional3DSData(additional3DSData) .withRiskData(riskData) - .withStoredCredentials(storedCredentials) - .build(); + .withStoredCredentials(storedCredentials); - return createTokenisedDirectAuthoriseRequest(requestParameters); + worldpayAdditionalRequestDataService.populateDirectRequestAdditionalData(cartModel, worldpayAdditionalInfoData, authoriseRequestParametersCreator); + return createTokenisedDirectAuthoriseRequest(authoriseRequestParametersCreator + .build()); } /** @@ -166,20 +164,19 @@ public DirectAuthoriseServiceRequest buildDirectAuthoriseGooglePayRequest(final final PayWithGoogleSSL googlePayPayment = worldpayOrderService.createGooglePayPayment(googlePayAdditionalAuthInfo.getProtocolVersion(), googlePayAdditionalAuthInfo.getSignature(), googlePayAdditionalAuthInfo.getSignedMessage()); - final CustomerModel customerModel = (CustomerModel) cartModel.getUser(); - final String shopperEmailAddress = worldpayRequestService.getEmailForCustomer(customerModel); + final String shopperEmailAddress = worldpayCartService.getEmailForCustomer(cartModel); final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(orderInfo) .withPayment(googlePayPayment) - .withShippingAddress(worldpayRequestService.getAddressFromCart(cartModel, true)) - .withBillingAddress(worldpayRequestService.getAddressFromCart(cartModel, false)) + .withShippingAddress(worldpayCartService.getAddressFromCart(cartModel, true)) + .withBillingAddress(worldpayCartService.getAddressFromCart(cartModel, false)) .withStatementNarrative(null) .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE); if (googlePayAdditionalAuthInfo.getSaveCard()) { - final String authenticatedShopperId = worldpayAuthenticatedShopperIdStrategy.getAuthenticatedShopperId(customerModel); + final String authenticatedShopperId = worldpayCartService.getAuthenticatedShopperId(cartModel); final String tokenEventReference = worldpayTokenEventReferenceCreationStrategy.createTokenEventReference(); final TokenRequest tokenRequest = worldpayRequestService.createTokenRequest(tokenEventReference, null); final StoredCredentials storedCredentials = worldpayRequestService.createStoredCredentials(Usage.FIRST, null, null); @@ -235,12 +232,12 @@ public DirectAuthoriseServiceRequest buildDirectAuthoriseBankTransferRequest(fin final Amount amount = worldpayOrderService.createAmount(cartModel.getCurrency(), cartModel.getTotalPrice()); final BasicOrderInfo orderInfo = worldpayOrderService.createBasicOrderInfo(orderCode, orderCode, amount); - final Address billingAddress = worldpayRequestService.getBillingAddress(cartModel, bankTransferAdditionalAuthInfo); + final Address billingAddress = worldpayCartService.getBillingAddress(cartModel, bankTransferAdditionalAuthInfo); final Payment payment = worldpayRequestService.createBankPayment(orderCode, bankTransferAdditionalAuthInfo.getPaymentMethod(), bankTransferAdditionalAuthInfo.getShopperBankCode()); - final String shopperEmailAddress = worldpayRequestService.getEmailForCustomer((CustomerModel) cartModel.getUser()); + final String shopperEmailAddress = worldpayCartService.getEmailForCustomer(cartModel); final String statementNarrative = bankTransferAdditionalAuthInfo.getStatementNarrative(); @@ -254,7 +251,7 @@ public DirectAuthoriseServiceRequest buildDirectAuthoriseBankTransferRequest(fin .withOrderInfo(orderInfo) .withPayment(payment) .withShopper(shopper) - .withShippingAddress(worldpayRequestService.getAddressFromCart(cartModel, true)) + .withShippingAddress(worldpayCartService.getAddressFromCart(cartModel, true)) .withBillingAddress(billingAddress) .withStatementNarrative(statementNarrative) .withDynamicInteractionType(dynamicInteractionType) @@ -276,15 +273,15 @@ public DirectAuthoriseServiceRequest buildDirectAuthoriseRecurringPayment(final final Session session = worldpayRequestService.createSession(worldpayAdditionalInfoData); final Browser browser = worldpayRequestService.createBrowser(worldpayAdditionalInfoData); - final String customerEmail = worldpayRequestService.getEmailForCustomer((CustomerModel) abstractOrderModel.getUser()); + final String customerEmail = worldpayCartService.getEmailForCustomer(abstractOrderModel); final Shopper shopper = worldpayRequestService.createAuthenticatedShopper(customerEmail, worldpayAdditionalInfoData.getAuthenticatedShopperId(), session, browser); final String subscriptionId = getSubscriptionId(abstractOrderModel); final Token token = worldpayRequestService.createToken(subscriptionId, worldpayAdditionalInfoData.getSecurityCode()); - final Address shippingAddress = worldpayRequestService.getAddressFromCart(abstractOrderModel, true); + final Address shippingAddress = worldpayCartService.getAddressFromCart(abstractOrderModel, true); final DynamicInteractionType dynamicInteractionType = worldpayRequestService.getDynamicInteractionType(worldpayAdditionalInfoData); final StoredCredentials storedCredentials = createRecurringStoredCredentials(abstractOrderModel, dynamicInteractionType); - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(orderInfo) .withPayment(token) @@ -294,10 +291,12 @@ public DirectAuthoriseServiceRequest buildDirectAuthoriseRecurringPayment(final .withStatementNarrative(null) .withDynamicInteractionType(dynamicInteractionType) .withAdditional3DSData(additional3DSData) - .withStoredCredentials(storedCredentials) - .build(); + .withStoredCredentials(storedCredentials); - return createTokenisedDirectAuthoriseRequest(requestParameters); + worldpayAdditionalRequestDataService.populateDirectRequestAdditionalData(abstractOrderModel, worldpayAdditionalInfoData, authoriseRequestParametersCreator); + + return createTokenisedDirectAuthoriseRequest(authoriseRequestParametersCreator + .build()); } protected String getSubscriptionId(final AbstractOrderModel abstractOrderModel) { @@ -323,14 +322,14 @@ public DirectAuthoriseServiceRequest buildDirectAuthoriseKlarnaRequest(final Mer final Amount amount = worldpayOrderService.createAmount(cartModel.getCurrency(), cartModel.getTotalPrice()); final BasicOrderInfo orderInfo = worldpayOrderService.createBasicOrderInfo(orderCode, orderCode, amount); - final Address billingAddress = worldpayRequestService.getBillingAddress(cartModel, additionalAuthInfo); - final Address shippingAddress = worldpayRequestService.getAddressFromCart(cartModel, true); + final Address billingAddress = worldpayCartService.getBillingAddress(cartModel, additionalAuthInfo); + final Address shippingAddress = worldpayCartService.getAddressFromCart(cartModel, true); final CustomerModel customerModel = (CustomerModel) cartModel.getUser(); final Payment payment = worldpayOrderService.createKlarnaPayment(billingAddress.getCountryCode(), customerModel.getSessionLanguage(), null, additionalAuthInfo.getPaymentMethod()); - final OrderLines orderLines = worldpayKlarnaStrategy.createOrderLines(cartModel); - final String shopperEmailAddress = worldpayRequestService.getEmailForCustomer(customerModel); + final OrderLines orderLines = worldpayKlarnaService.createOrderLines(cartModel); + final String shopperEmailAddress = worldpayCartService.getEmailForCustomer(cartModel); final String statementNarrative = additionalAuthInfo.getStatementNarrative(); final Session session = worldpayRequestService.createSession(worldpayAdditionalInfoData); @@ -360,9 +359,9 @@ public DirectAuthoriseServiceRequest buildApplePayDirectAuthorisationRequest(fin final BasicOrderInfo orderInfo = worldpayOrderService.createBasicOrderInfo(orderCode, orderCode, amount); final Payment payment = worldpayOrderService.createApplePayPayment(worldpayAdditionalInfoApplePayData); - final String shopperEmailAddress = worldpayRequestService.getEmailForCustomer((CustomerModel) cartModel.getUser()); + final String shopperEmailAddress = worldpayCartService.getEmailForCustomer(cartModel); final Shopper shopper = worldpayRequestService.createShopper(shopperEmailAddress, null, null); - final Address shippingAddress = worldpayRequestService.getAddressFromCart(cartModel, true); + final Address shippingAddress = worldpayCartService.getAddressFromCart(cartModel, true); final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) @@ -383,13 +382,13 @@ public DirectAuthoriseServiceRequest buildDirectTokenAndAuthorise(final Merchant final String orderCode = worldpayOrderService.generateWorldpayOrderCode(cartModel); final Amount amount = worldpayOrderService.createAmount(cartModel.getCurrency(), cartModel.getTotalPrice()); final BasicOrderInfo orderInfo = worldpayOrderService.createBasicOrderInfo(orderCode, orderCode, amount); - final Address billingAddress = worldpayRequestService.getBillingAddress(cartModel, cseAdditionalAuthInfo); - final Address shippingAddress = worldpayRequestService.getAddressFromCart(cartModel, true); + final Address billingAddress = worldpayCartService.getBillingAddress(cartModel, cseAdditionalAuthInfo); + final Address shippingAddress = worldpayCartService.getAddressFromCart(cartModel, true); final Additional3DSData additional3DSData = worldpayRequestService.createAdditional3DSData(worldpayAdditionalInfoData); final RiskData riskData = worldpayRiskDataService.createRiskData(cartModel, worldpayAdditionalInfoData); final Cse csePayment = worldpayOrderService.createCsePayment(cseAdditionalAuthInfo, billingAddress); - final String shopperEmailAddress = worldpayRequestService.getEmailForCustomer((CustomerModel) cartModel.getUser()); + final String shopperEmailAddress = worldpayCartService.getEmailForCustomer(cartModel); final String statementNarrative = cseAdditionalAuthInfo.getStatementNarrative(); final Session session = worldpayRequestService.createSession(worldpayAdditionalInfoData); @@ -400,7 +399,7 @@ public DirectAuthoriseServiceRequest buildDirectTokenAndAuthorise(final Merchant final TokenRequest tokenRequest = worldpayRequestService.createTokenRequest(tokenEventReference, null); final StoredCredentials storedCredentials = worldpayRequestService.createStoredCredentials(Usage.FIRST, null, null); - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(orderInfo) .withPayment(csePayment) @@ -413,9 +412,12 @@ public DirectAuthoriseServiceRequest buildDirectTokenAndAuthorise(final Merchant .withTokenRequest(tokenRequest) .withStoredCredentials(cseAdditionalAuthInfo.getSaveCard() ? storedCredentials : null) .withRiskData(riskData) - .withAdditional3DSData(additional3DSData) - .build(); - return buildDirectTokenAndAuthoriseRequest(requestParameters); + .withAdditional3DSData(additional3DSData); + + worldpayAdditionalRequestDataService.populateDirectRequestAdditionalData(cartModel, worldpayAdditionalInfoData, authoriseRequestParametersCreator); + + return buildDirectTokenAndAuthoriseRequest(authoriseRequestParametersCreator.build()); + } /** @@ -432,21 +434,16 @@ public SecondThreeDSecurePaymentRequest buildSecondThreeDSecurePaymentRequest(fi * {@inheritDoc} */ @Override - public RedirectAuthoriseServiceRequest buildRedirectAuthoriseRequest(final MerchantInfo merchantInfo, final CartModel cartModel, final AdditionalAuthInfo additionalAuthInfo, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws WorldpayConfigurationException { - final String orderCode = worldpayOrderService.generateWorldpayOrderCode(cartModel); - final CurrencyModel currencyModel = cartModel.getCurrency(); - final Amount amount = worldpayOrderService.createAmount(currencyModel, cartModel.getTotalPrice()); - final BasicOrderInfo orderInfo = worldpayOrderService.createBasicOrderInfo(orderCode, orderCode, amount); - final Address shippingAddress = worldpayRequestService.getAddressFromCart(cartModel, true); - final Address billingAddress = worldpayRequestService.getBillingAddress(cartModel, additionalAuthInfo); - final RiskData riskData = worldpayRiskDataService.createRiskData(cartModel, worldpayAdditionalInfoData); - - final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = internalCreateCommonRedirectAuthoriseServiceRequest(merchantInfo, orderInfo, shippingAddress, billingAddress, riskData); + public RedirectAuthoriseServiceRequest buildRedirectAuthoriseRequest(final MerchantInfo merchantInfo, + final CartModel cartModel, + final AdditionalAuthInfo additionalAuthInfo, + final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws WorldpayConfigurationException { + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = internalCreateCommonRedirectAuthoriseServiceRequest(merchantInfo, cartModel, additionalAuthInfo, worldpayAdditionalInfoData); - if (worldpayKlarnaUtils.isKlarnaPaymentType(additionalAuthInfo.getPaymentMethod())) { + if (worldpayKlarnaService.isKlarnaPaymentType(additionalAuthInfo.getPaymentMethod())) { return internalGetRedirectAuthoriseServiceRequestForKlarna(cartModel, additionalAuthInfo, authoriseRequestParametersCreator); } else { - return internalGetRedirectAuthoriseServiceRequest(cartModel, additionalAuthInfo, authoriseRequestParametersCreator); + return internalGetRedirectAuthoriseServiceRequest(cartModel, additionalAuthInfo, authoriseRequestParametersCreator, worldpayAdditionalInfoData); } } @@ -521,25 +518,39 @@ protected DirectAuthoriseServiceRequest buildDirectTokenAndAuthoriseRequest(fina return DirectAuthoriseServiceRequest.createDirectTokenAndAuthoriseRequest(requestParameters); } - protected AuthoriseRequestParametersCreator internalCreateCommonRedirectAuthoriseServiceRequest(final MerchantInfo merchantInfo, final BasicOrderInfo orderInfo, final Address shippingAddress, final Address billingAddress, final RiskData riskData) { - return AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + protected AuthoriseRequestParametersCreator internalCreateCommonRedirectAuthoriseServiceRequest(final MerchantInfo merchantInfo, final CartModel cartModel, final AdditionalAuthInfo additionalAuthInfo, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) { + final String orderCode = worldpayOrderService.generateWorldpayOrderCode(cartModel); + final CurrencyModel currencyModel = cartModel.getCurrency(); + final Amount amount = worldpayOrderService.createAmount(currencyModel, cartModel.getTotalPrice()); + final BasicOrderInfo orderInfo = worldpayOrderService.createBasicOrderInfo(orderCode, orderCode, amount); + final Address shippingAddress = worldpayCartService.getAddressFromCart(cartModel, true); + final Address billingAddress = worldpayCartService.getBillingAddress(cartModel, additionalAuthInfo); + final RiskData riskData = worldpayRiskDataService.createRiskData(cartModel, worldpayAdditionalInfoData); + + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withOrderInfo(orderInfo) .withShippingAddress(shippingAddress) .withBillingAddress(billingAddress) .withMerchantInfo(merchantInfo) .withRiskData(riskData); + + worldpayAdditionalRequestDataService.populateRedirectRequestAdditionalData(cartModel, worldpayAdditionalInfoData, authoriseRequestParametersCreator); + + return authoriseRequestParametersCreator; } - protected RedirectAuthoriseServiceRequest internalGetRedirectAuthoriseServiceRequest(final CartModel cartModel, final AdditionalAuthInfo additionalAuthInfo, final AuthoriseRequestParametersCreator authoriseRequestParametersCreator) { - final CustomerModel customerModel = (CustomerModel) cartModel.getUser(); - final String customerEmail = worldpayRequestService.getEmailForCustomer(customerModel); + protected RedirectAuthoriseServiceRequest internalGetRedirectAuthoriseServiceRequest(final CartModel cartModel, + final AdditionalAuthInfo additionalAuthInfo, + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator, + final WorldpayAdditionalInfoData worldpayAdditionalInfoData) { + final String customerEmail = worldpayCartService.getEmailForCustomer(cartModel); final List includedPTs = getIncludedPaymentTypeList(additionalAuthInfo); authoriseRequestParametersCreator.withInstallationId(additionalAuthInfo.getInstallationId()) .withIncludedPTs(includedPTs); if (additionalAuthInfo.getSaveCard()) { - final String authenticatedShopperId = worldpayAuthenticatedShopperIdStrategy.getAuthenticatedShopperId(customerModel); + final String authenticatedShopperId = worldpayCartService.getAuthenticatedShopperId(cartModel); final Shopper shopper = worldpayRequestService.createAuthenticatedShopper(customerEmail, authenticatedShopperId, null, null); final String tokenEventReference = worldpayTokenEventReferenceCreationStrategy.createTokenEventReference(); final TokenRequest tokenRequest = worldpayRequestService.createTokenRequest(tokenEventReference, null); @@ -556,16 +567,19 @@ protected RedirectAuthoriseServiceRequest internalGetRedirectAuthoriseServiceReq final Shopper shopper = worldpayRequestService.createShopper(customerEmail, null, null); authoriseRequestParametersCreator.withShopper(shopper); } + + worldpayAdditionalRequestDataService.populateRedirectRequestAdditionalData(cartModel, worldpayAdditionalInfoData, authoriseRequestParametersCreator); + return createRedirectAuthoriseRequest(authoriseRequestParametersCreator.build()); } protected RedirectAuthoriseServiceRequest internalGetRedirectAuthoriseServiceRequestForKlarna(final CartModel cartModel, final AdditionalAuthInfo additionalAuthInfo, final AuthoriseRequestParametersCreator authoriseRequestParametersCreator) throws WorldpayConfigurationException { final CustomerModel customerModel = (CustomerModel) cartModel.getUser(); - final Payment payment = worldpayOrderService.createKlarnaPayment(worldpayRequestService.getBillingAddress(cartModel, additionalAuthInfo).getCountryCode(), + final Payment payment = worldpayOrderService.createKlarnaPayment(worldpayCartService.getBillingAddress(cartModel, additionalAuthInfo).getCountryCode(), customerModel.getSessionLanguage(), null, additionalAuthInfo.getPaymentMethod()); - final OrderLines orderLines = worldpayKlarnaStrategy.createOrderLines(cartModel); - final String shopperEmailAddress = worldpayRequestService.getEmailForCustomer(customerModel); + final OrderLines orderLines = worldpayKlarnaService.createOrderLines(cartModel); + final String shopperEmailAddress = worldpayCartService.getEmailForCustomer(cartModel); final String statementNarrative = additionalAuthInfo.getStatementNarrative(); final Shopper shopper = worldpayRequestService.createShopper(shopperEmailAddress, null, null); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestService.java index 564d0fbf..7e9e1416 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestService.java @@ -1,8 +1,14 @@ package com.worldpay.service.payment.request.impl; import com.google.common.base.Preconditions; -import com.worldpay.data.AdditionalAuthInfo; -import com.worldpay.data.CSEAdditionalAuthInfo; +import com.worldpay.core.services.WorldpayCartService; +import com.worldpay.data.*; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.Token; +import com.worldpay.data.token.TokenRequest; import com.worldpay.enums.order.DynamicInteractionType; import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; import com.worldpay.enums.payment.storedCredentials.Usage; @@ -11,30 +17,20 @@ import com.worldpay.service.WorldpayUrlService; import com.worldpay.service.hop.WorldpayOrderCodeVerificationService; import com.worldpay.service.interaction.WorldpayDynamicInteractionResolverService; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.payment.PaymentBuilder; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.Token; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.service.model.payment.PaymentType; import com.worldpay.service.payment.request.WorldpayRequestService; import com.worldpay.service.request.CreateTokenServiceRequest; import com.worldpay.service.request.UpdateTokenServiceRequest; -import com.worldpay.strategy.WorldpayDeliveryAddressStrategy; import com.worldpay.threedsecureflexenums.ChallengePreferenceEnum; import com.worldpay.threedsecureflexenums.ChallengeWindowSizeEnum; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; import de.hybris.platform.acceleratorservices.config.SiteConfigService; -import de.hybris.platform.commerceservices.customer.CustomerEmailResolutionService; -import de.hybris.platform.core.model.order.AbstractOrderModel; -import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.user.AddressModel; -import de.hybris.platform.core.model.user.CustomerModel; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.lang.StringUtils; -import org.springframework.core.convert.converter.Converter; +import org.springframework.web.util.UriUtils; +import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Objects; import java.util.Optional; @@ -47,26 +43,20 @@ public class DefaultWorldpayRequestService implements WorldpayRequestService { protected final WorldpayUrlService bankWorldpayUrlService; protected final SiteConfigService siteConfigService; - protected final Converter worldpayAddressConverter; - protected final WorldpayDeliveryAddressStrategy worldpayDeliveryAddressStrategy; protected final WorldpayDynamicInteractionResolverService worldpayDynamicInteractionResolverService; - protected final CustomerEmailResolutionService customerEmailResolutionService; protected final WorldpayOrderCodeVerificationService worldpayOrderCodeVerificationService; + protected final WorldpayCartService worldpayCartService; public DefaultWorldpayRequestService(final WorldpayUrlService bankWorldpayUrlService, final SiteConfigService siteConfigService, - final Converter worldpayAddressConverter, - final WorldpayDeliveryAddressStrategy worldpayDeliveryAddressStrategy, final WorldpayDynamicInteractionResolverService worldpayDynamicInteractionResolverService, - final CustomerEmailResolutionService customerEmailResolutionService, - final WorldpayOrderCodeVerificationService worldpayOrderCodeVerificationService) { + final WorldpayOrderCodeVerificationService worldpayOrderCodeVerificationService, + final WorldpayCartService worldpayCartService) { this.bankWorldpayUrlService = bankWorldpayUrlService; this.siteConfigService = siteConfigService; - this.worldpayAddressConverter = worldpayAddressConverter; - this.worldpayDeliveryAddressStrategy = worldpayDeliveryAddressStrategy; this.worldpayDynamicInteractionResolverService = worldpayDynamicInteractionResolverService; - this.customerEmailResolutionService = customerEmailResolutionService; this.worldpayOrderCodeVerificationService = worldpayOrderCodeVerificationService; + this.worldpayCartService = worldpayCartService; } /** @@ -74,7 +64,10 @@ public DefaultWorldpayRequestService(final WorldpayUrlService bankWorldpayUrlSer */ @Override public Session createSession(final WorldpayAdditionalInfoData worldpayAdditionalInfo) { - return new Session(worldpayAdditionalInfo.getCustomerIPAddress(), worldpayAdditionalInfo.getSessionId()); + final Session session = new Session(); + session.setId(worldpayAdditionalInfo.getSessionId()); + session.setShopperIPAddress(worldpayAdditionalInfo.getCustomerIPAddress()); + return session; } /** @@ -82,7 +75,11 @@ public Session createSession(final WorldpayAdditionalInfoData worldpayAdditional */ @Override public Browser createBrowser(final WorldpayAdditionalInfoData worldpayAdditionalInfo) { - return new Browser(worldpayAdditionalInfo.getAcceptHeader(), worldpayAdditionalInfo.getUserAgentHeader(), worldpayAdditionalInfo.getDeviceType()); + final Browser browser = new Browser(); + browser.setAcceptHeader(worldpayAdditionalInfo.getAcceptHeader()); + browser.setUserAgentHeader(worldpayAdditionalInfo.getUserAgentHeader()); + browser.setDeviceType(worldpayAdditionalInfo.getDeviceType()); + return browser; } /** @@ -90,7 +87,12 @@ public Browser createBrowser(final WorldpayAdditionalInfoData worldpayAdditional */ @Override public Shopper createShopper(final String customerEmail, final Session session, final Browser browser) { - return new Shopper(customerEmail, null, browser, session); + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(customerEmail); + shopper.setBrowser(browser); + shopper.setSession(session); + + return shopper; } /** @@ -98,21 +100,22 @@ public Shopper createShopper(final String customerEmail, final Session session, */ @Override public Shopper createAuthenticatedShopper(final String customerEmail, final String authenticatedShopperID, final Session session, final Browser browser) { - if (isMerchantTokenEnabled()) { - return new Shopper(customerEmail, null, browser, session); - } - return new Shopper(customerEmail, authenticatedShopperID, browser, session); + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(customerEmail); + shopper.setBrowser(browser); + shopper.setSession(session); + shopper.setAuthenticatedShopperID(isMerchantTokenEnabled() ? null : authenticatedShopperID); + + return shopper; } + /** * {@inheritDoc} */ @Override public TokenRequest createTokenRequest(final String tokenEventReference, final String tokenReason) { - if (isMerchantTokenEnabled()) { - return createMerchantTokenRequest(tokenEventReference, tokenReason); - } - return createShopperTokenRequest(tokenEventReference, tokenReason); + return createTokenRequest(tokenEventReference, tokenReason, isMerchantTokenEnabled()); } /** @@ -120,12 +123,10 @@ public TokenRequest createTokenRequest(final String tokenEventReference, final S */ @Override public TokenRequest createTokenRequestForDeletion(final String tokenEventReference, final String tokenReason, final String authenticatedShopperId) { - if (StringUtils.isBlank(authenticatedShopperId)) { - return createMerchantTokenRequest(tokenEventReference, tokenReason); - } - return createShopperTokenRequest(tokenEventReference, tokenReason); + return createTokenRequest(tokenEventReference, tokenReason, StringUtils.isBlank(authenticatedShopperId)); } + /** * {@inheritDoc} */ @@ -153,8 +154,9 @@ public Payment createBankPayment(final String worldpayOrderCode, final String pa throw new ConversionException(e.getMessage(), e); } - final String successURL = bankWorldpayUrlService.getFullSuccessURL() + "?orderId=" + encryptedOrderCode; - return PaymentBuilder.createIDEALSSL(shopperBankCode, successURL, bankWorldpayUrlService.getFullFailureURL(), bankWorldpayUrlService.getFullCancelURL()); + final String successURL = bankWorldpayUrlService.getFullSuccessURL() + "?orderId=" + UriUtils.encode(encryptedOrderCode, StandardCharsets.UTF_8.toString()); + + return WorldpayInternalModelTransformerUtil.createAlternativeShopperBankCodePayment(PaymentType.IDEAL, shopperBankCode, successURL, bankWorldpayUrlService.getFullFailureURL(), bankWorldpayUrlService.getFullCancelURL(), null, null); } return null; } @@ -164,7 +166,17 @@ public Payment createBankPayment(final String worldpayOrderCode, final String pa */ @Override public Token createToken(final String subscriptionId, final String securityCode) { - return PaymentBuilder.createToken(subscriptionId, securityCode, isMerchantTokenEnabled()); + final Token token = new Token(); + token.setMerchantToken(isMerchantTokenEnabled()); + token.setPaymentTokenID(subscriptionId); + token.setPaymentType(PaymentType.TOKENSSL.getMethodCode()); + if (securityCode != null) { + final CardDetails cardDetails = new CardDetails(); + cardDetails.setCvcNumber(securityCode); + token.setPaymentInstrument(cardDetails); + } + + return token; } /** @@ -188,14 +200,11 @@ public Additional3DSData createAdditional3DSData(final WorldpayAdditionalInfoDat return Optional.ofNullable(worldpayAdditionalInfoData.getAdditional3DS2()).map(additional3DS2Info -> { final Additional3DSData additional3DSData = new Additional3DSData(); additional3DSData.setDfReferenceId(additional3DS2Info.getDfReferenceId()); - - final ChallengeWindowSizeEnum challengeWindowSizeEnum = ChallengeWindowSizeEnum.getEnum(additional3DS2Info.getChallengeWindowSize()); - additional3DSData.setChallengeWindowSize(challengeWindowSizeEnum); - - if (additional3DS2Info.getChallengePreference() != null) { - final ChallengePreferenceEnum challengePreferenceEnum = ChallengePreferenceEnum.getEnum(additional3DS2Info.getChallengePreference()); - additional3DSData.setChallengePreference(challengePreferenceEnum); - } + additional3DSData.setChallengeWindowSize(ChallengeWindowSizeEnum.getEnum(additional3DS2Info.getChallengeWindowSize()).toString()); + Optional.ofNullable(additional3DS2Info.getChallengePreference()) + .map(ChallengePreferenceEnum::getEnum) + .map(ChallengePreferenceEnum::toString). + ifPresent(additional3DSData::setChallengePreference); return additional3DSData; @@ -208,50 +217,30 @@ public Additional3DSData createAdditional3DSData(final WorldpayAdditionalInfoDat @Override public StoredCredentials createStoredCredentials(final Usage usage, final MerchantInitiatedReason merchantInitiatedReason, final String transactionIdentifier) { Preconditions.checkArgument(Objects.nonNull(usage), "Usage must be specified when creating a storedCredentials"); - return new StoredCredentials(merchantInitiatedReason, transactionIdentifier, usage); + final StoredCredentials storedCredentials = new StoredCredentials(); + storedCredentials.setMerchantInitiatedReason(merchantInitiatedReason); + storedCredentials.setSchemeTransactionIdentifier(transactionIdentifier); + storedCredentials.setUsage(usage); + return storedCredentials; } - /** * {@inheritDoc} */ @Override public CardDetails createCardDetails(final CSEAdditionalAuthInfo cseAdditionalAuthInfo, final AddressModel paymentAddress) { final CardDetails cardDetails = new CardDetails(); - final Date expiryDate = new Date(cseAdditionalAuthInfo.getExpiryMonth(), cseAdditionalAuthInfo.getExpiryYear()); + final Date expiryDate = new Date(); + expiryDate.setMonth(cseAdditionalAuthInfo.getExpiryMonth()); + expiryDate.setYear(cseAdditionalAuthInfo.getExpiryYear()); cardDetails.setExpiryDate(expiryDate); cardDetails.setCardHolderName(cseAdditionalAuthInfo.getCardHolderName()); Optional.ofNullable(paymentAddress) - .map(worldpayAddressConverter::convert) + .map(worldpayCartService::convertAddressModelToAddress) .ifPresent(cardDetails::setCardAddress); return cardDetails; } - /** - * {@inheritDoc} - */ - @Override - public Address getAddressFromCart(final AbstractOrderModel abstractOrder, final boolean isDeliveryAddress) { - final AddressModel address = isDeliveryAddress ? worldpayDeliveryAddressStrategy.getDeliveryAddress(abstractOrder) : abstractOrder.getPaymentAddress(); - return worldpayAddressConverter.convert(address); - } - - /** - * {@inheritDoc} - */ - @Override - public Address getBillingAddress(final CartModel cartModel, final AdditionalAuthInfo additionalAuthInfo) { - final AddressModel deliveryAddressModel = cartModel.getDeliveryAddress(); - if (deliveryAddressModel != null && Boolean.TRUE.equals(additionalAuthInfo.getUsingShippingAsBilling())) { - return worldpayAddressConverter.convert(deliveryAddressModel); - } else { - if (cartModel.getPaymentAddress() != null) { - return worldpayAddressConverter.convert(cartModel.getPaymentAddress()); - } - } - return null; - } - /** * {@inheritDoc} */ @@ -260,23 +249,15 @@ public DynamicInteractionType getDynamicInteractionType(final WorldpayAdditional return worldpayDynamicInteractionResolverService.resolveInteractionTypeForDirectIntegration(worldpayAdditionalInfoData); } - /** - * {@inheritDoc} - */ - @Override - public String getEmailForCustomer(final CustomerModel customerModel) { - return customerEmailResolutionService.getEmailForCustomer(customerModel); - } - private boolean isMerchantTokenEnabled() { return siteConfigService.getBoolean(WORLDPAY_MERCHANT_TOKEN_ENABLED, false); } - private TokenRequest createMerchantTokenRequest(final String tokenEventReference, final String tokenReason) { - return new TokenRequest(tokenEventReference, tokenReason, true); - } - - private TokenRequest createShopperTokenRequest(final String tokenEventReference, final String tokenReason) { - return new TokenRequest(tokenEventReference, tokenReason, false); + private TokenRequest createTokenRequest(final String tokenEventReference, final String tokenReason, final boolean merchant) { + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenEventReference(tokenEventReference); + tokenRequest.setTokenReason(tokenReason); + tokenRequest.setMerchantToken(merchant); + return tokenRequest; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AbstractServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AbstractServiceRequest.java index 8a4fab85..cb7bafd8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AbstractServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AbstractServiceRequest.java @@ -1,6 +1,6 @@ package com.worldpay.service.request; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; /** * Template implementation of a {@link ServiceRequest} providing {@link MerchantInfo} and order code diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AddBackOfficeCodeServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AddBackOfficeCodeServiceRequest.java index 792ff853..70504b0c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AddBackOfficeCodeServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AddBackOfficeCodeServiceRequest.java @@ -1,7 +1,7 @@ package com.worldpay.service.request; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; /** * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#addBackOfficeCode(AddBackOfficeCodeServiceRequest) addBackOfficeCode()} in the diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthorisationCodeServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthorisationCodeServiceRequest.java index d8651a14..e7bf638b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthorisationCodeServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthorisationCodeServiceRequest.java @@ -1,7 +1,7 @@ package com.worldpay.service.request; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; /** * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#authorisationCode(AuthorisationCodeServiceRequest) authorisationCode()} in the diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthoriseRequestParameters.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthoriseRequestParameters.java index 0f4bf63d..709bde81 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthoriseRequestParameters.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthoriseRequestParameters.java @@ -1,13 +1,14 @@ package com.worldpay.service.request; +import com.worldpay.data.*; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.enums.PaymentAction; import com.worldpay.enums.order.DynamicInteractionType; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Payment; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.threeds2.RiskData; -import com.worldpay.service.model.token.TokenRequest; import java.util.List; @@ -32,6 +33,11 @@ public final class AuthoriseRequestParameters { private String installationId; private String orderContent; private List paymentMethodAttributes; + private FraudSightData fraudSightData; + private String deviceSession; + private PaymentAction action; + private BranchSpecificExtension branchSpecificExtension; + private String mandateType; private AuthoriseRequestParameters() { } @@ -92,14 +98,14 @@ public TokenRequest getTokenRequest() { return tokenRequest; } - public void setIncludedPTs(final List includedPTs) { - this.includedPTs = includedPTs; - } - public List getIncludedPTs() { return includedPTs; } + public void setIncludedPTs(final List includedPTs) { + this.includedPTs = includedPTs; + } + public String getInstallationId() { return installationId; } @@ -140,6 +146,46 @@ public void setPaymentMethodAttributes(List paymentMetho this.paymentMethodAttributes = paymentMethodAttributes; } + public FraudSightData getFraudSightData() { + return fraudSightData; + } + + public void setFraudSightData(final FraudSightData fraudSightData) { + this.fraudSightData = fraudSightData; + } + + public String getDeviceSession() { + return deviceSession; + } + + public void setDeviceSession(final String deviceSession) { + this.deviceSession = deviceSession; + } + + public PaymentAction getAction() { + return action; + } + + public void setAction(final PaymentAction action) { + this.action = action; + } + + public BranchSpecificExtension getBranchSpecificExtension() { + return branchSpecificExtension; + } + + public void setBranchSpecificExtension(final BranchSpecificExtension branchSpecificExtension) { + this.branchSpecificExtension = branchSpecificExtension; + } + + public String getMandateType() { + return mandateType; + } + + public void setMandateType(final String mandateType) { + this.mandateType = mandateType; + } + public interface AuthoriseRequestParametersCreator { AuthoriseRequestParametersCreator withOrderLines(OrderLines orderLines); @@ -181,6 +227,16 @@ public interface AuthoriseRequestParametersCreator { AuthoriseRequestParametersCreator withPaymentMethodAttributes(List paymentMethodAttributes); + AuthoriseRequestParametersCreator withFraudSightData(FraudSightData fraudSightData); + + AuthoriseRequestParametersCreator withDeviceSession(String deviceSession); + + AuthoriseRequestParametersCreator withPaymentDetailsAction(PaymentAction action); + + AuthoriseRequestParametersCreator withLevel23Data(BranchSpecificExtension branchSpecificExtension); + + AuthoriseRequestParametersCreator withMandateType(String mandateType); + AuthoriseRequestParameters build(); } @@ -206,6 +262,11 @@ public static class AuthoriseRequestParametersBuilder implements AuthoriseReques private List excludedPTs; private String orderContent; private List paymentMethodAttributes; + private FraudSightData fraudSightData; + private String deviceSession; + private PaymentAction action; + private BranchSpecificExtension branchSpecificExtension; + private String mandateType; private AuthoriseRequestParametersBuilder() { } @@ -339,9 +400,39 @@ public AuthoriseRequestParametersCreator withPaymentMethodAttributes(final List< return this; } + @Override + public AuthoriseRequestParametersCreator withFraudSightData(final FraudSightData fraudSightData) { + this.fraudSightData = fraudSightData; + return this; + } + + @Override + public AuthoriseRequestParametersCreator withDeviceSession(final String deviceSession) { + this.deviceSession = deviceSession; + return this; + } + + @Override + public AuthoriseRequestParametersCreator withPaymentDetailsAction(final PaymentAction action) { + this.action = action; + return this; + } + + @Override + public AuthoriseRequestParametersCreator withLevel23Data(final BranchSpecificExtension branchSpecificExtension) { + this.branchSpecificExtension = branchSpecificExtension; + return this; + } + + @Override + public AuthoriseRequestParametersCreator withMandateType(final String mandateType) { + this.mandateType = mandateType; + return this; + } + @Override public AuthoriseRequestParameters build() { - AuthoriseRequestParameters parameters = new AuthoriseRequestParameters(); + final AuthoriseRequestParameters parameters = new AuthoriseRequestParameters(); parameters.merchantInfo = merchantInfo; parameters.orderInfo = orderInfo; @@ -363,6 +454,11 @@ public AuthoriseRequestParameters build() { parameters.excludedPTs = excludedPTs; parameters.orderContent = orderContent; parameters.paymentMethodAttributes = paymentMethodAttributes; + parameters.fraudSightData = fraudSightData; + parameters.deviceSession = deviceSession; + parameters.action = action; + parameters.branchSpecificExtension = branchSpecificExtension; + parameters.mandateType = mandateType; return parameters; } @@ -391,6 +487,11 @@ public String toString() { ", installationId='" + installationId + '\'' + ", orderContent='" + orderContent + '\'' + ", paymentMethodAttributes=" + paymentMethodAttributes + + ", fraudSightData='" + fraudSightData + '\'' + + ", deviceSession='" + deviceSession + '\'' + + ", level23data='" + branchSpecificExtension + '\'' + + ", mandateType='" + mandateType + '\'' + + ", action=" + action.name() + '}'; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthoriseServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthoriseServiceRequest.java index 7ad007d4..b9d62cba 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthoriseServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/AuthoriseServiceRequest.java @@ -1,11 +1,11 @@ package com.worldpay.service.request; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.Order; -import com.worldpay.service.model.applepay.ApplePay; -import com.worldpay.service.model.payment.PayWithGoogleSSL; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.token.Token; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.Order; +import com.worldpay.data.applepay.ApplePay; +import com.worldpay.data.payment.PayWithGoogleSSL; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.token.Token; /** * This class adds the {@link Order} details to the AbstractServiceRequest and forms the superclass of all authorise requests. It's not used directly as the diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CancelServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CancelServiceRequest.java index 35da9e67..108b50ef 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CancelServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CancelServiceRequest.java @@ -2,7 +2,7 @@ import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; /** * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#cancel(CancelServiceRequest) cancel()} in the @@ -12,7 +12,7 @@ */ public class CancelServiceRequest extends AbstractServiceRequest { - protected CancelServiceRequest(MerchantInfo merchantInfo, String orderCode) { + protected CancelServiceRequest(final MerchantInfo merchantInfo,final String orderCode) { super(merchantInfo, orderCode); } @@ -23,7 +23,7 @@ protected CancelServiceRequest(MerchantInfo merchantInfo, String orderCode) { * @param orderCode orderCode to be used in the Worldpay call * @return new instance of the CancelServiceRequest initialised with input parameters */ - public static CancelServiceRequest createCancelRequest(MerchantInfo merch, String orderCode) { + public static CancelServiceRequest createCancelRequest(final MerchantInfo merch, final String orderCode) { if (merch == null || orderCode == null) { throw new IllegalArgumentException("WorldpayConfig, MerchantInfo and Order Code cannot be null"); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CaptureServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CaptureServiceRequest.java index 6e4a8efd..d3c411ac 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CaptureServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CaptureServiceRequest.java @@ -1,9 +1,9 @@ package com.worldpay.service.request; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.Date; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.Date; +import com.worldpay.data.MerchantInfo; import java.util.List; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CreateTokenServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CreateTokenServiceRequest.java index eeae90cf..a4ba0396 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CreateTokenServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/CreateTokenServiceRequest.java @@ -1,10 +1,10 @@ package com.worldpay.service.request; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.token.CardTokenRequest; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.token.CardTokenRequest; +import com.worldpay.data.token.TokenRequest; /** @@ -33,7 +33,11 @@ public static CreateTokenServiceRequest createTokenRequestForShopperToken(final checkParameters("CreateTokenServiceRequest", merchantInfo, payment); final CreateTokenServiceRequest request = new CreateTokenServiceRequest(merchantInfo, null); - request.setCardTokenRequest(new CardTokenRequest(tokenRequest, authenticatedShopperId, payment)); + final CardTokenRequest cardTokenRequest = new CardTokenRequest(); + cardTokenRequest.setAuthenticatedShopperId(authenticatedShopperId); + cardTokenRequest.setPayment(payment); + cardTokenRequest.setTokenRequest(tokenRequest); + request.setCardTokenRequest(cardTokenRequest); return request; } @@ -49,7 +53,10 @@ public static CreateTokenServiceRequest createTokenRequestForMerchantToken(final checkParameters("CreateTokenServiceRequest", merchantInfo, payment); final CreateTokenServiceRequest request = new CreateTokenServiceRequest(merchantInfo, null); - request.setCardTokenRequest(new CardTokenRequest(tokenRequest, payment)); + final CardTokenRequest cardTokenRequest = new CardTokenRequest(); + cardTokenRequest.setPayment(payment); + cardTokenRequest.setTokenRequest(tokenRequest); + request.setCardTokenRequest(cardTokenRequest); return request; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/DeleteTokenServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/DeleteTokenServiceRequest.java index 9fc5006e..349fb5d9 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/DeleteTokenServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/DeleteTokenServiceRequest.java @@ -1,9 +1,9 @@ package com.worldpay.service.request; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.token.DeleteTokenRequest; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.token.DeleteTokenRequest; +import com.worldpay.data.token.TokenRequest; /** * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#deleteToken(DeleteTokenServiceRequest)} in the WorldpayServiceGateway @@ -36,11 +36,14 @@ public static DeleteTokenServiceRequest deleteTokenRequest(final MerchantInfo me checkParameters("DeleteTokenServiceRequest", merchantInfo); final DeleteTokenServiceRequest request = new DeleteTokenServiceRequest(merchantInfo, null); - request.setDeleteTokenRequest(new DeleteTokenRequest(paymentTokenId, authenticatedShopperId, tokenRequest)); + final DeleteTokenRequest deleteTokenRequest = new DeleteTokenRequest(); + deleteTokenRequest.setPaymentTokenId(paymentTokenId); + deleteTokenRequest.setAuthenticatedShopperId(authenticatedShopperId); + deleteTokenRequest.setTokenRequest(tokenRequest); + request.setDeleteTokenRequest(deleteTokenRequest); return request; } - public DeleteTokenRequest getDeleteTokenRequest() { return deleteTokenRequest; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/DirectAuthoriseServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/DirectAuthoriseServiceRequest.java index cdc851b1..898b5e9e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/DirectAuthoriseServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/DirectAuthoriseServiceRequest.java @@ -1,9 +1,10 @@ package com.worldpay.service.request; +import com.worldpay.data.*; +import com.worldpay.data.payment.Payment; import com.worldpay.enums.order.DynamicInteractionType; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Payment; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; /** * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#directAuthorise(DirectAuthoriseServiceRequest)} (DirectAuthoriseServiceRequest) @@ -30,17 +31,15 @@ public static DirectAuthoriseServiceRequest createDirectAuthoriseRequest(final A final BasicOrderInfo orderInfo = requestParameters.getOrderInfo(); checkParameters(DIRECT_AUTHORISE_SERVICE_REQUEST, merchantInfo, orderInfo, merchantInfo.getMerchantCode(), merchantInfo.getMerchantPassword()); final DirectAuthoriseServiceRequest authRequest = new DirectAuthoriseServiceRequest(merchantInfo, orderInfo.getOrderCode()); - final Shopper shopper = requestParameters.getShopper(); - final PaymentDetails paymentDetails = new PaymentDetails(requestParameters.getPayment(), shopper != null ? shopper.getSession() : null); final Order reqOrder = new OrderBuilder() - .withOrderInfo(orderInfo) - .withShopper(shopper) - .withShippingAddress(requestParameters.getShippingAddress()) - .withBillingAddress(requestParameters.getBillingAddress()) - .withStatementNarrative(requestParameters.getStatementNarrative()) - .withPaymentDetails(paymentDetails) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) - .build(); + .withOrderInfo(orderInfo) + .withShopper(requestParameters.getShopper()) + .withShippingAddress(requestParameters.getShippingAddress()) + .withBillingAddress(requestParameters.getBillingAddress()) + .withStatementNarrative(requestParameters.getStatementNarrative()) + .withPaymentDetails(WorldpayInternalModelTransformerUtil.createPaymentDetailsFromRequestParameters(requestParameters)) + .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) + .build(); reqOrder.setOrderLines(requestParameters.getOrderLines()); authRequest.setOrder(reqOrder); @@ -61,20 +60,16 @@ public static DirectAuthoriseServiceRequest createKlarnaDirectAuthoriseRequest(f final DirectAuthoriseServiceRequest authRequest = new DirectAuthoriseServiceRequest(merchantInfo, orderInfo.getOrderCode()); - final Shopper shopper = requestParameters.getShopper(); - - final PaymentDetails paymentDetails = new PaymentDetails(requestParameters.getPayment(), shopper != null ? shopper.getSession() : null); - final Order reqOrder = new OrderBuilder() - .withOrderInfo(orderInfo) - .withShopper(shopper) - .withShippingAddress(requestParameters.getShippingAddress()) - .withBillingAddress(requestParameters.getBillingAddress()) - .withStatementNarrative(requestParameters.getStatementNarrative()) - .withPaymentDetails(paymentDetails) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) - .withOrderLines(requestParameters.getOrderLines()) - .build(); + .withOrderInfo(orderInfo) + .withShopper(requestParameters.getShopper()) + .withShippingAddress(requestParameters.getShippingAddress()) + .withBillingAddress(requestParameters.getBillingAddress()) + .withStatementNarrative(requestParameters.getStatementNarrative()) + .withPaymentDetails(WorldpayInternalModelTransformerUtil.createPaymentDetailsFromRequestParameters(requestParameters)) + .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) + .withOrderLines(requestParameters.getOrderLines()) + .build(); authRequest.setOrder(reqOrder); @@ -94,18 +89,21 @@ public static DirectAuthoriseServiceRequest createTokenisedDirectAuthoriseReques checkParameters(DIRECT_AUTHORISE_SERVICE_REQUEST, merchantInfo, orderInfo, shopper); checkInstanceOfToken(requestParameters.getPayment()); final DirectAuthoriseServiceRequest authRequest = new DirectAuthoriseServiceRequest(merchantInfo, orderInfo.getOrderCode()); - final PaymentDetails paymentDetails = new PaymentDetails(requestParameters.getPayment(), shopper != null ? shopper.getSession() : null, requestParameters.getStoredCredentials()); + // Passing billing address as null as the token has one in Worldpay. final Order order = new OrderBuilder() - .withOrderInfo(orderInfo) - .withShopper(shopper) - .withShippingAddress(requestParameters.getShippingAddress()) - .withStatementNarrative(requestParameters.getStatementNarrative()) - .withPaymentDetails(paymentDetails) - .withDynamicInteractionType(requestParameters.getDynamicInteractionType()) - .withRiskData(requestParameters.getRiskData()) - .withAdditional3DSData(requestParameters.getAdditional3DSData()) - .build(); + .withOrderInfo(orderInfo) + .withShopper(shopper) + .withShippingAddress(requestParameters.getShippingAddress()) + .withStatementNarrative(requestParameters.getStatementNarrative()) + .withPaymentDetails(WorldpayInternalModelTransformerUtil.createPaymentDetailsFromRequestParameters(requestParameters)) + .withDynamicInteractionType(requestParameters.getDynamicInteractionType()) + .withRiskData(requestParameters.getRiskData()) + .withAdditional3DSData(requestParameters.getAdditional3DSData()) + .withFraudSightAttribute(requestParameters.getFraudSightData()) + .withDeviceSession(requestParameters.getDeviceSession()) + .withLevel23Data(requestParameters.getBranchSpecificExtension()) + .build(); authRequest.setOrder(order); return authRequest; } @@ -124,15 +122,14 @@ public static DirectAuthoriseServiceRequest createApplePayDirectAuthoriseRequest final Payment payment = requestParameters.getPayment(); checkInstanceOfApplePay(payment); final DirectAuthoriseServiceRequest authRequest = new DirectAuthoriseServiceRequest(merchantInfo, orderInfo.getOrderCode()); - final PaymentDetails paymentDetails = new PaymentDetails(payment, shopper != null ? shopper.getSession() : null); // Passing billing address as null as the token has one in Worldpay. final Order order = new OrderBuilder() - .withOrderInfo(orderInfo) - .withShopper(shopper) - .withShippingAddress(requestParameters.getShippingAddress()) - .withPaymentDetails(paymentDetails) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) - .build(); + .withOrderInfo(orderInfo) + .withShopper(shopper) + .withShippingAddress(requestParameters.getShippingAddress()) + .withPaymentDetails(WorldpayInternalModelTransformerUtil.createPaymentDetailsFromRequestParameters(requestParameters)) + .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) + .build(); authRequest.setOrder(order); return authRequest; } @@ -151,18 +148,17 @@ public static DirectAuthoriseServiceRequest createGooglePayDirectAuthoriseReques final Payment payment = requestParameters.getPayment(); checkInstanceOfGooglePay(payment); final DirectAuthoriseServiceRequest authRequest = new DirectAuthoriseServiceRequest(merchantInfo, orderInfo.getOrderCode()); - final PaymentDetails paymentDetails = new PaymentDetails(payment, shopper != null ? shopper.getSession() : null); // Passing billing address as null as the token has one in Worldpay. final Order reqOrder = new OrderBuilder() - .withOrderInfo(orderInfo) - .withShopper(shopper) - .withShippingAddress(requestParameters.getShippingAddress()) - .withBillingAddress(requestParameters.getBillingAddress()) - .withStatementNarrative(requestParameters.getStatementNarrative()) - .withPaymentDetails(paymentDetails) - .withTokenRequest(requestParameters.getTokenRequest()) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) - .build(); + .withOrderInfo(orderInfo) + .withShopper(shopper) + .withShippingAddress(requestParameters.getShippingAddress()) + .withBillingAddress(requestParameters.getBillingAddress()) + .withStatementNarrative(requestParameters.getStatementNarrative()) + .withPaymentDetails(WorldpayInternalModelTransformerUtil.createPaymentDetailsFromRequestParameters(requestParameters)) + .withTokenRequest(requestParameters.getTokenRequest()) + .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) + .build(); authRequest.setOrder(reqOrder); return authRequest; } @@ -182,7 +178,8 @@ public static DirectAuthoriseServiceRequest createDirect3DAuthoriseRequest(final final DirectAuthoriseServiceRequest authRequest = new DirectAuthoriseServiceRequest(merchantInfo, orderInfo.getOrderCode()); - final Order reqOrder = new Order(orderInfo.getOrderCode(), null, null); + final Order reqOrder = new Order(); + reqOrder.setOrderCode(orderInfo.getOrderCode()); reqOrder.setSession(requestParameters.getShopper().getSession()); reqOrder.setPaResponse(requestParameters.getPaRes()); authRequest.setOrder(reqOrder); @@ -191,27 +188,28 @@ public static DirectAuthoriseServiceRequest createDirect3DAuthoriseRequest(final /** * Creates a DirectAuthoriseServiceRequest given the requestParameters passed + * * @param requestParameters * @return new instance of the DirectAuthoriseServiceRequest initialised with input parameters */ public static DirectAuthoriseServiceRequest createDirectTokenAndAuthoriseRequest(final AuthoriseRequestParameters requestParameters) { final DirectAuthoriseServiceRequest authRequest = new DirectAuthoriseServiceRequest(requestParameters.getMerchantInfo(), requestParameters.getOrderInfo().getOrderCode()); - final PaymentDetails paymentDetails = new PaymentDetails(requestParameters.getPayment(), requestParameters.getShopper().getSession()); - paymentDetails.setStoredCredentials(requestParameters.getStoredCredentials()); - final Order reqOrder = new OrderBuilder() - .withOrderInfo(requestParameters.getOrderInfo()) - .withShopper(requestParameters.getShopper()) - .withTokenRequest(requestParameters.getTokenRequest()) - .withShippingAddress(requestParameters.getShippingAddress()) - .withBillingAddress(requestParameters.getBillingAddress()) - .withStatementNarrative(requestParameters.getStatementNarrative()) - .withPaymentDetails(paymentDetails) - .withDynamicInteractionType(requestParameters.getDynamicInteractionType()) - .withRiskData(requestParameters.getRiskData()) - .withAdditional3DSData(requestParameters.getAdditional3DSData()) - .build(); + .withOrderInfo(requestParameters.getOrderInfo()) + .withShopper(requestParameters.getShopper()) + .withTokenRequest(requestParameters.getTokenRequest()) + .withShippingAddress(requestParameters.getShippingAddress()) + .withBillingAddress(requestParameters.getBillingAddress()) + .withStatementNarrative(requestParameters.getStatementNarrative()) + .withPaymentDetails(WorldpayInternalModelTransformerUtil.createPaymentDetailsFromRequestParameters(requestParameters)) + .withDynamicInteractionType(requestParameters.getDynamicInteractionType()) + .withRiskData(requestParameters.getRiskData()) + .withAdditional3DSData(requestParameters.getAdditional3DSData()) + .withFraudSightAttribute(requestParameters.getFraudSightData()) + .withDeviceSession(requestParameters.getDeviceSession()) + .withLevel23Data(requestParameters.getBranchSpecificExtension()) + .build(); authRequest.setOrder(reqOrder); return authRequest; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/KlarnaOrderInquiryServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/KlarnaOrderInquiryServiceRequest.java index c644f55d..171e6c31 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/KlarnaOrderInquiryServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/KlarnaOrderInquiryServiceRequest.java @@ -1,7 +1,7 @@ package com.worldpay.service.request; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; /** * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#orderInquiry(AbstractServiceRequest)} in the diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/OrderBuilder.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/OrderBuilder.java index c476a5b2..580b1046 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/OrderBuilder.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/OrderBuilder.java @@ -1,14 +1,15 @@ package com.worldpay.service.request; +import com.worldpay.data.*; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.token.TokenRequest; import com.worldpay.enums.order.DynamicInteractionType; -import com.worldpay.service.model.*; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.threeds2.RiskData; -import com.worldpay.service.model.token.TokenRequest; import org.apache.commons.collections4.CollectionUtils; +import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -32,6 +33,10 @@ public class OrderBuilder { private List excludedPaymentMethods; private StoredCredentials storedCredentials; private List paymentMethodAttributes; + private FraudSightData fraudSightData; + private String deviceSession; + private BranchSpecificExtension branchSpecificExtension; + private String mandateType; public OrderBuilder withOrderContent(String orderContent) { this.orderContent = orderContent; @@ -123,8 +128,31 @@ OrderBuilder withPaymentMethodAttribute(final List payme return this; } + OrderBuilder withFraudSightAttribute(final FraudSightData fraudSightData) { + this.fraudSightData = fraudSightData; + return this; + } + + OrderBuilder withDeviceSession(final String deviceSession) { + this.deviceSession = deviceSession; + return this; + } + + OrderBuilder withLevel23Data(final BranchSpecificExtension branchSpecificExtension) { + this.branchSpecificExtension = branchSpecificExtension; + return this; + } + + OrderBuilder withMandateType(final String mandateType) { + this.mandateType = mandateType; + return this; + } + public Order build() { - final Order order = new Order(orderInfo.getOrderCode(), orderInfo.getDescription(), orderInfo.getAmount()); + final Order order = new Order(); + order.setOrderCode(orderInfo.getOrderCode()); + order.setDescription(orderInfo.getDescription()); + order.setAmount(orderInfo.getAmount()); order.setPaymentDetails(paymentDetails); order.setShopper(shopper); order.setShippingAddress(shippingAddress); @@ -143,6 +171,10 @@ public Order build() { Optional.ofNullable(excludedPaymentMethods).ifPresent(excludedPTs -> addPaymentTypesExcluded(order, excludedPTs)); Optional.ofNullable(storedCredentials).ifPresent(credentials -> addStoredCredentials(order, credentials)); Optional.ofNullable(paymentMethodAttributes).ifPresent(order::setPaymentMethodAttributes); + Optional.ofNullable(fraudSightData).ifPresent(order::setFraudSightData); + Optional.ofNullable(deviceSession).ifPresent(order::setDeviceSession); + Optional.ofNullable(branchSpecificExtension).ifPresent(order::setBranchSpecificExtension); + Optional.ofNullable(mandateType).ifPresent(order::setMandateType); return order; } @@ -155,14 +187,40 @@ protected void addStoredCredentials(final Order reqOrder, final StoredCredential protected void addPaymentTypesExcluded(final Order reqOrder, final List excludedPTs) { final PaymentMethodMask pmm = Optional.ofNullable(reqOrder.getPaymentMethodMask()).orElseGet(PaymentMethodMask::new); - CollectionUtils.emptyIfNull(excludedPTs).forEach(pmm::addExclude); + CollectionUtils.emptyIfNull(excludedPTs).forEach(paymentType -> addExclude(paymentType, pmm)); reqOrder.setPaymentMethodMask(pmm); } protected void addPaymentTypesIncluded(final Order reqOrder, final List includedPTs) { final PaymentMethodMask pmm = Optional.ofNullable(reqOrder.getPaymentMethodMask()).orElseGet(PaymentMethodMask::new); - CollectionUtils.emptyIfNull(includedPTs).forEach(pmm::addInclude); + CollectionUtils.emptyIfNull(includedPTs).forEach(paymentType -> addInclude(paymentType, pmm)); reqOrder.setPaymentMethodMask(pmm); } + + /** + * Add an item to the list of payment methods that are included + * + * @param paymentType PaymentType to be included + */ + private void addInclude(PaymentType paymentType, PaymentMethodMask pmm) { + + if (pmm.getIncludes() == null) { + pmm.setIncludes(new ArrayList<>()); + } + pmm.getIncludes().add(paymentType.getMethodCode()); + } + + /** + * Add an item to the list of payment methods that are excluded + * + * @param paymentType PaymentType to be excluded + */ + private void addExclude(PaymentType paymentType, PaymentMethodMask pmm) { + + if (pmm.getExcludes() == null) { + pmm.setExcludes(new ArrayList<>()); + } + pmm.getExcludes().add(paymentType.getMethodCode()); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/OrderInquiryServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/OrderInquiryServiceRequest.java index abf31209..8b00374f 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/OrderInquiryServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/OrderInquiryServiceRequest.java @@ -1,7 +1,7 @@ package com.worldpay.service.request; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; /** * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#orderInquiry(AbstractServiceRequest) orderInquiry()} in the diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/RedirectAuthoriseServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/RedirectAuthoriseServiceRequest.java index 0c260223..afb35e9e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/RedirectAuthoriseServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/RedirectAuthoriseServiceRequest.java @@ -1,9 +1,10 @@ package com.worldpay.service.request; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.Order; -import com.worldpay.service.model.PaymentDetails; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.Order; +import com.worldpay.data.PaymentDetails; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; /** * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#redirectAuthorise(RedirectAuthoriseServiceRequest) redirectAuthorise()} in the @@ -25,7 +26,6 @@ protected RedirectAuthoriseServiceRequest(final MerchantInfo merchantInfo, final */ public static RedirectAuthoriseServiceRequest createRedirectAuthoriseRequest(final AuthoriseRequestParameters requestParameters) { final RedirectAuthoriseServiceRequest authRequest = new RedirectAuthoriseServiceRequest(requestParameters.getMerchantInfo(), requestParameters.getOrderInfo().getOrderCode()); - final PaymentDetails paymentDetails = new PaymentDetails(requestParameters.getPayment(), requestParameters.getShopper().getSession(), requestParameters.getStoredCredentials()); final Order reqOrder = new OrderBuilder() .withOrderInfo(requestParameters.getOrderInfo()) @@ -38,12 +38,15 @@ public static RedirectAuthoriseServiceRequest createRedirectAuthoriseRequest(fin .withShippingAddress(requestParameters.getShippingAddress()) .withBillingAddress(requestParameters.getBillingAddress()) .withStatementNarrative(requestParameters.getStatementNarrative()) - .withPaymentDetails(paymentDetails) + .withPaymentDetails(WorldpayInternalModelTransformerUtil.createPaymentDetailsFromRequestParameters(requestParameters)) .withDynamicInteractionType(requestParameters.getDynamicInteractionType()) .withStoredCredentials(requestParameters.getStoredCredentials()) .withPaymentMethodAttribute(requestParameters.getPaymentMethodAttributes()) .withOrderLines(requestParameters.getOrderLines()) .withRiskData(requestParameters.getRiskData()) + .withFraudSightAttribute(requestParameters.getFraudSightData()) + .withLevel23Data(requestParameters.getBranchSpecificExtension()) + .withMandateType(requestParameters.getMandateType()) .build(); authRequest.setOrder(reqOrder); return authRequest; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/RefundServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/RefundServiceRequest.java index 1ab713f2..30709af2 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/RefundServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/RefundServiceRequest.java @@ -1,8 +1,8 @@ package com.worldpay.service.request; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; /** * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#refund(RefundServiceRequest) refund()} in the diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/SecondThreeDSecurePaymentRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/SecondThreeDSecurePaymentRequest.java index 8e5f8b2a..8c4c9f72 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/SecondThreeDSecurePaymentRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/SecondThreeDSecurePaymentRequest.java @@ -1,6 +1,6 @@ package com.worldpay.service.request; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; public class SecondThreeDSecurePaymentRequest extends AbstractServiceRequest { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/ServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/ServiceRequest.java index 8233cbce..aac1c446 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/ServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/ServiceRequest.java @@ -1,7 +1,7 @@ package com.worldpay.service.request; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; /** * Interface representation of a Service Request that will be used to make the calls through to Worldpay. diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/UpdateTokenServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/UpdateTokenServiceRequest.java index 01064f20..b4130b0e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/UpdateTokenServiceRequest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/UpdateTokenServiceRequest.java @@ -1,10 +1,10 @@ package com.worldpay.service.request; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.data.token.UpdateTokenRequest; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.TokenRequest; -import com.worldpay.service.model.token.UpdateTokenRequest; /** @@ -40,24 +40,35 @@ public static UpdateTokenServiceRequest updateTokenRequestWithShopperScope(final checkParameters("UpdateTokenServiceRequest", merchantInfo, cardDetails); final UpdateTokenServiceRequest request = new UpdateTokenServiceRequest(merchantInfo, null); - request.setUpdateTokenRequest(new UpdateTokenRequest(paymentTokenId, authenticatedShopperId, cardDetails, tokenRequest, false)); + final UpdateTokenRequest updateTokenRequest = new UpdateTokenRequest(); + updateTokenRequest.setPaymentTokenId(paymentTokenId); + updateTokenRequest.setAuthenticatedShopperID(authenticatedShopperId); + updateTokenRequest.setCardDetails(cardDetails); + updateTokenRequest.setTokenRequest(tokenRequest); + updateTokenRequest.setMerchantToken(false); + request.setUpdateTokenRequest(updateTokenRequest); return request; } /** * Static convenience method for creating an instance of the UpdateTokenServiceRequest with merchant scope * - * @param merchantInfo merchantInfo to be used in the Worldpay call - * @param paymentTokenId the payment token id to update - * @param tokenRequest contains the information to request a new token - * @param cardDetails payment to be used in the Worldpay call + * @param merchantInfo merchantInfo to be used in the Worldpay call + * @param paymentTokenId the payment token id to update + * @param tokenRequest contains the information to request a new token + * @param cardDetails payment to be used in the Worldpay call * @return new instance of the UpdateTokenServiceRequest initialised with input parameters */ public static UpdateTokenServiceRequest updateTokenRequestWithMerchantScope(final MerchantInfo merchantInfo, final String paymentTokenId, final TokenRequest tokenRequest, final CardDetails cardDetails) { checkParameters("UpdateTokenServiceRequest", merchantInfo, cardDetails); final UpdateTokenServiceRequest request = new UpdateTokenServiceRequest(merchantInfo, null); - request.setUpdateTokenRequest(new UpdateTokenRequest(paymentTokenId, null, cardDetails, tokenRequest, true)); + final UpdateTokenRequest updateTokenRequest = new UpdateTokenRequest(); + updateTokenRequest.setPaymentTokenId(paymentTokenId); + updateTokenRequest.setCardDetails(cardDetails); + updateTokenRequest.setTokenRequest(tokenRequest); + updateTokenRequest.setMerchantToken(true); + request.setUpdateTokenRequest(updateTokenRequest); return request; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/VoidSaleServiceRequest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/VoidSaleServiceRequest.java new file mode 100644 index 00000000..90dfdade --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/VoidSaleServiceRequest.java @@ -0,0 +1,32 @@ +package com.worldpay.service.request; + + +import com.worldpay.service.WorldpayServiceGateway; +import com.worldpay.data.MerchantInfo; + +/** + * This class represents the details that must be passed to a call to {@link WorldpayServiceGateway#voidSale(VoidSaleServiceRequest)} (VoidSaleServiceRequest) voidSale()} in the + * WorldpayServiceGateway + *

+ *

No further parameters are required on top of the standard ones

+ */ +public class VoidSaleServiceRequest extends AbstractServiceRequest { + + protected VoidSaleServiceRequest(final MerchantInfo merchantInfo, final String orderCode) { + super(merchantInfo, orderCode); + } + + /** + * Static convenience method for creating an instance of the VoidSaleServiceRequest + * + * @param merch merchantInfo to be used in the Worldpay call + * @param orderCode orderCode to be used in the Worldpay call + * @return new instance of the VoidSaleServiceRequest initialised with input parameters + */ + public static VoidSaleServiceRequest createVoidSaleRequest(final MerchantInfo merch, final String orderCode) { + if (merch == null || orderCode == null) { + throw new IllegalArgumentException("WorldpayConfig, MerchantInfo and Order Code cannot be null"); + } + return new VoidSaleServiceRequest(merch, orderCode); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AddBackOfficeCodeRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AddBackOfficeCodeRequestTransformer.java index e1c7c886..4280114d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AddBackOfficeCodeRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AddBackOfficeCodeRequestTransformer.java @@ -8,7 +8,6 @@ import com.worldpay.service.request.AddBackOfficeCodeServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; -import org.springframework.beans.factory.annotation.Required; /** * Specific class for transforming an {@link AddBackOfficeCodeServiceRequest} into a {@link PaymentService} object @@ -29,7 +28,11 @@ public class AddBackOfficeCodeRequestTransformer implements ServiceRequestTransformer { private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; - private ConfigurationService configurationService; + protected final ConfigurationService configurationService; + + public AddBackOfficeCodeRequestTransformer(final ConfigurationService configurationService) { + this.configurationService = configurationService; + } /** * (non-Javadoc) @@ -61,8 +64,4 @@ public PaymentService transform(final ServiceRequest request) throws WorldpayMod return paymentService; } - @Required - public void setConfigurationService(final ConfigurationService configurationService) { - this.configurationService = configurationService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AuthorisationCodeRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AuthorisationCodeRequestTransformer.java index 1e1a2b76..124686f1 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AuthorisationCodeRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AuthorisationCodeRequestTransformer.java @@ -8,7 +8,6 @@ import com.worldpay.service.request.AuthorisationCodeServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; -import org.springframework.beans.factory.annotation.Required; /** * Specific class for transforming an {@link AuthorisationCodeServiceRequest} into a {@link PaymentService} object @@ -29,7 +28,11 @@ public class AuthorisationCodeRequestTransformer implements ServiceRequestTransformer { private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; - private ConfigurationService configurationService; + protected final ConfigurationService configurationService; + + public AuthorisationCodeRequestTransformer(final ConfigurationService configurationService) { + this.configurationService = configurationService; + } /** * (non-Javadoc) @@ -61,9 +64,4 @@ public PaymentService transform(final ServiceRequest request) throws WorldpayMod paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().add(modify); return paymentService; } - - @Required - public void setConfigurationService(final ConfigurationService configurationService) { - this.configurationService = configurationService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AuthoriseRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AuthoriseRequestTransformer.java index f63b9fd9..3a516de7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AuthoriseRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/AuthoriseRequestTransformer.java @@ -7,6 +7,7 @@ import com.worldpay.service.request.AuthoriseServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; /** * Specific class for transforming an {@link AuthoriseServiceRequest} into a {@link PaymentService} object @@ -53,11 +54,16 @@ *

*/ public class AuthoriseRequestTransformer implements ServiceRequestTransformer { + private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; + protected final ConfigurationService configurationService; + protected final Converter internalOrderConverter; - public AuthoriseRequestTransformer(final ConfigurationService configurationService) { + public AuthoriseRequestTransformer(final ConfigurationService configurationService, + final Converter internalOrderConverter) { this.configurationService = configurationService; + this.internalOrderConverter = internalOrderConverter; } /** @@ -80,7 +86,7 @@ public PaymentService transform(final ServiceRequest request) throws WorldpayMod throw new WorldpayModelTransformationException("No order object to transform on the authorise request"); } final Submit submit = new Submit(); - final Order order = (Order) authRequest.getOrder().transformToInternalModel(); + final Order order = internalOrderConverter.convert(authRequest.getOrder()); submit.getOrderOrOrderBatchOrShopperOrFuturePayAgreementOrMakeFuturePayPaymentOrIdentifyMeRequestOrPaymentTokenCreateOrChallenge().add(order); paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().add(submit); return paymentService; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CancelRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CancelRequestTransformer.java index bb9a862c..2cad615b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CancelRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CancelRequestTransformer.java @@ -11,7 +11,6 @@ import com.worldpay.service.request.CancelServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; -import org.springframework.beans.factory.annotation.Required; /** * Specific class for transforming an {@link CancelServiceRequest} into a {@link PaymentService} object @@ -32,7 +31,11 @@ public class CancelRequestTransformer implements ServiceRequestTransformer { private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; - private ConfigurationService configurationService; + protected final ConfigurationService configurationService; + + public CancelRequestTransformer(final ConfigurationService configurationService) { + this.configurationService = configurationService; + } /** * (non-Javadoc) @@ -40,7 +43,7 @@ public class CancelRequestTransformer implements ServiceRequestTransformer { * @see com.worldpay.service.request.transform.ServiceRequestTransformer#transform(com.worldpay.service.request.ServiceRequest) */ @Override - public PaymentService transform(ServiceRequest request) throws WorldpayModelTransformationException { + public PaymentService transform(final ServiceRequest request) throws WorldpayModelTransformationException { if (request == null || request.getMerchantInfo() == null || request.getOrderCode() == null) { throw new WorldpayModelTransformationException("Request provided to do the cancelOrRefund is invalid."); } @@ -52,14 +55,9 @@ public PaymentService transform(ServiceRequest request) throws WorldpayModelTran final OrderModification orderModification = new OrderModification(); orderModification.setOrderCode(request.getOrderCode()); final CancelOrRefund cancelOrRefund = new CancelOrRefund(); - orderModification. getCancelOrCaptureOrRefundOrRevokeOrAddBackOfficeCodeOrAuthoriseOrIncreaseAuthorisationOrCancelOrRefundOrDefendOrShopperWebformRefundDetailsOrExtendExpiryDateOrCancelRefundOrCancelRetryOrVoidSaleOrApprove().add(cancelOrRefund); + orderModification.getCancelOrCaptureOrRefundOrRevokeOrAddBackOfficeCodeOrAuthoriseOrIncreaseAuthorisationOrCancelOrRefundOrDefendOrShopperWebformRefundDetailsOrExtendExpiryDateOrCancelRefundOrCancelRetryOrVoidSaleOrApprove().add(cancelOrRefund); modify.getOrderModificationOrBatchModificationOrAccountBatchModificationOrFuturePayAgreementModificationOrPaymentTokenUpdateOrPaymentTokenDelete().add(orderModification); paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().add(modify); return paymentService; } - - @Required - public void setConfigurationService(final ConfigurationService configurationService) { - this.configurationService = configurationService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CaptureRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CaptureRequestTransformer.java index e184fcb0..8f4c9a8d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CaptureRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CaptureRequestTransformer.java @@ -5,6 +5,7 @@ import com.worldpay.service.request.CaptureServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.apache.commons.collections.CollectionUtils; import java.util.List; @@ -33,9 +34,15 @@ public class CaptureRequestTransformer implements ServiceRequestTransformer { private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; protected final ConfigurationService configurationService; + protected final Converter internalAmountConverter; + protected final Converter internalDateConverter; - public CaptureRequestTransformer(final ConfigurationService configurationService) { + public CaptureRequestTransformer(final ConfigurationService configurationService, + final Converter internalAmountConverter, + final Converter internalDateConverter) { this.configurationService = configurationService; + this.internalAmountConverter = internalAmountConverter; + this.internalDateConverter = internalDateConverter; } /** @@ -61,9 +68,9 @@ public PaymentService transform(final ServiceRequest request) throws WorldpayMod final OrderModification orderModification = new OrderModification(); orderModification.setOrderCode(request.getOrderCode()); final Capture capture = new Capture(); - capture.setAmount((Amount) captureRequest.getAmount().transformToInternalModel()); + capture.setAmount(internalAmountConverter.convert(captureRequest.getAmount())); if (captureRequest.getDate() != null) { - capture.setDate((Date) captureRequest.getDate().transformToInternalModel()); + capture.setDate(internalDateConverter.convert(captureRequest.getDate())); } setShippingInfo(captureRequest.getTrackingIds(), capture); @@ -84,8 +91,8 @@ protected void setShippingInfo(final List trackingIds, final Capture cap protected List getShippingInfos(final List trackingIds) { return trackingIds.stream() - .map(this::getShippingInfoWithTrackingId) - .collect(Collectors.toList()); + .map(this::getShippingInfoWithTrackingId) + .collect(Collectors.toList()); } protected ShippingInfo getShippingInfoWithTrackingId(final String trackingId) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CreateTokenRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CreateTokenRequestTransformer.java index a2a99a87..d67002dc 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CreateTokenRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/CreateTokenRequestTransformer.java @@ -4,10 +4,11 @@ import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.PaymentTokenCreate; import com.worldpay.internal.model.Submit; +import com.worldpay.data.token.CardTokenRequest; import com.worldpay.service.request.CreateTokenServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; -import org.springframework.beans.factory.annotation.Required; +import de.hybris.platform.servicelayer.dto.converter.Converter; /** * Transformer/Converter class that transforms a CreateTokenServiceRequest (abstraction) into a PaymentService (XML model) @@ -16,7 +17,14 @@ public class CreateTokenRequestTransformer implements ServiceRequestTransformer { private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; - private ConfigurationService configurationService; + protected final ConfigurationService configurationService; + protected final Converter internalPaymentTokenCreateConverter; + + public CreateTokenRequestTransformer(final ConfigurationService configurationService, + final Converter internalPaymentTokenCreateConverter) { + this.configurationService = configurationService; + this.internalPaymentTokenCreateConverter = internalPaymentTokenCreateConverter; + } /** * (non-Javadoc) @@ -34,15 +42,11 @@ public PaymentService transform(final ServiceRequest request) throws WorldpayMod paymentService.setMerchantCode(tokenRequest.getMerchantInfo().getMerchantCode()); paymentService.setVersion(configurationService.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)); - final PaymentTokenCreate paymentTokenCreate = (PaymentTokenCreate) tokenRequest.getCardTokenRequest().transformToInternalModel(); + final PaymentTokenCreate paymentTokenCreate = internalPaymentTokenCreateConverter.convert(tokenRequest.getCardTokenRequest()); final Submit submit = new Submit(); submit.getOrderOrOrderBatchOrShopperOrFuturePayAgreementOrMakeFuturePayPaymentOrIdentifyMeRequestOrPaymentTokenCreateOrChallenge().add(paymentTokenCreate); paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().add(submit); return paymentService; } - @Required - public void setConfigurationService(final ConfigurationService configurationService) { - this.configurationService = configurationService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/DeleteTokenRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/DeleteTokenRequestTransformer.java index 488ec3e5..64788a2a 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/DeleteTokenRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/DeleteTokenRequestTransformer.java @@ -4,19 +4,28 @@ import com.worldpay.internal.model.Modify; import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.PaymentTokenDelete; +import com.worldpay.data.token.DeleteTokenRequest; import com.worldpay.service.request.DeleteTokenServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; -import org.springframework.beans.factory.annotation.Required; +import de.hybris.platform.servicelayer.dto.converter.Converter; /** * Transformer/Converter class that transforms a DeleteTokenRequestTransformer (abstraction) into a PaymentService (XML model) * to be sent as an XML file to Worldpay */ public class DeleteTokenRequestTransformer implements ServiceRequestTransformer { + private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; - private ConfigurationService configurationService; + protected final ConfigurationService configurationService; + protected final Converter internalPaymentTokenDeleteConverter; + + public DeleteTokenRequestTransformer(final ConfigurationService configurationService, + final Converter internalPaymentTokenDeleteConverter) { + this.configurationService = configurationService; + this.internalPaymentTokenDeleteConverter = internalPaymentTokenDeleteConverter; + } @Override public PaymentService transform(ServiceRequest request) throws WorldpayModelTransformationException { @@ -30,7 +39,7 @@ public PaymentService transform(ServiceRequest request) throws WorldpayModelTran paymentService.setMerchantCode(deleteTokenRequest.getMerchantInfo().getMerchantCode()); paymentService.setVersion(configurationService.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)); - final PaymentTokenDelete deleteToken = (PaymentTokenDelete) deleteTokenRequest.getDeleteTokenRequest().transformToInternalModel(); + final PaymentTokenDelete deleteToken = internalPaymentTokenDeleteConverter.convert(deleteTokenRequest.getDeleteTokenRequest()); final Modify modify = new Modify(); modify.getOrderModificationOrBatchModificationOrAccountBatchModificationOrFuturePayAgreementModificationOrPaymentTokenUpdateOrPaymentTokenDelete().add(deleteToken); @@ -38,9 +47,4 @@ public PaymentService transform(ServiceRequest request) throws WorldpayModelTran return paymentService; } - - @Required - public void setConfigurationService(final ConfigurationService configurationService) { - this.configurationService = configurationService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/InternalModelTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/InternalModelTransformer.java deleted file mode 100644 index ab993ceb..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/InternalModelTransformer.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.worldpay.service.request.transform; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.helper.InternalModelObject; - -/** - * Interface to provide functionality to transform the existing object into an internal model representation - */ -public interface InternalModelTransformer { - - /** - * Transform the existing object into an internal model object representation. If the object is a complex type then encapsulated objects may need to have this - * method invoked recursively to generate the full model - * - * @return An {@link InternalModelObject} representation of this external facing model object - * @throws WorldpayModelTransformationException if there has been some issue transforming the object - */ - InternalModelObject transformToInternalModel() throws WorldpayModelTransformationException; -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/OrderInquiryRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/OrderInquiryRequestTransformer.java index e4ae4879..2d91a3e0 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/OrderInquiryRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/OrderInquiryRequestTransformer.java @@ -9,7 +9,6 @@ import com.worldpay.service.request.OrderInquiryServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; -import org.springframework.beans.factory.annotation.Required; /** * Specific class for transforming an {@link OrderInquiryServiceRequest} into a {@link PaymentService} object @@ -28,7 +27,11 @@ public class OrderInquiryRequestTransformer implements ServiceRequestTransformer { private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; - private ConfigurationService configurationService; + protected final ConfigurationService configurationService; + + public OrderInquiryRequestTransformer(final ConfigurationService configurationService) { + this.configurationService = configurationService; + } /** * (non-Javadoc) @@ -61,9 +64,4 @@ private void buildInquiry(final ServiceRequest request, final Inquiry inquiry) { inquiry.getOrderInquiryOrKlarnaConfirmationInquiryOrBatchInquiryOrAccountBatchInquiryOrRefundableAmountInquiryOrShopperAuthenticationOrPriceInquiryOrBankAccountInquiryOrIdentifyMeInquiryOrPaymentOptionsInquiryOrPaymentTokenInquiryOrShopperTokenRetrievalOrCardCheckInquiry().add(klarnaConfirmationInquiry); } } - - @Required - public void setConfigurationService(final ConfigurationService configurationService) { - this.configurationService = configurationService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/RefundRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/RefundRequestTransformer.java index e5f51aa4..129ef9c9 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/RefundRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/RefundRequestTransformer.java @@ -1,10 +1,15 @@ package com.worldpay.service.request.transform; import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.*; +import com.worldpay.internal.model.Modify; +import com.worldpay.internal.model.OrderModification; +import com.worldpay.internal.model.PaymentService; +import com.worldpay.internal.model.Refund; +import com.worldpay.data.Amount; import com.worldpay.service.request.RefundServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; /** * Specific class for transforming an {@link RefundServiceRequest} into a {@link PaymentService} object @@ -28,9 +33,12 @@ public class RefundRequestTransformer implements ServiceRequestTransformer { private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; protected final ConfigurationService configurationService; + protected final Converter internalAmountConverter; - public RefundRequestTransformer(final ConfigurationService configurationService) { + public RefundRequestTransformer(final ConfigurationService configurationService, + final Converter internalAmountConverter) { this.configurationService = configurationService; + this.internalAmountConverter = internalAmountConverter; } /* (non-Javadoc) @@ -58,7 +66,8 @@ public PaymentService transform(final ServiceRequest request) throws WorldpayMod if (Boolean.TRUE.equals(refundRequest.getShopperWebformRefund())) { refund.setShopperWebformRefund(Boolean.TRUE.toString()); } - refund.setAmount((Amount) refundRequest.getAmount().transformToInternalModel()); + + refund.setAmount(internalAmountConverter.convert(refundRequest.getAmount())); orderModification.getCancelOrCaptureOrRefundOrRevokeOrAddBackOfficeCodeOrAuthoriseOrIncreaseAuthorisationOrCancelOrRefundOrDefendOrShopperWebformRefundDetailsOrExtendExpiryDateOrCancelRefundOrCancelRetryOrVoidSaleOrApprove().add(refund); modify.getOrderModificationOrBatchModificationOrAccountBatchModificationOrFuturePayAgreementModificationOrPaymentTokenUpdateOrPaymentTokenDelete().add(orderModification); paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().add(modify); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/SecondThreeDSecurePaymentRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/SecondThreeDSecurePaymentRequestTransformer.java index 235c1fbc..7598450f 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/SecondThreeDSecurePaymentRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/SecondThreeDSecurePaymentRequestTransformer.java @@ -58,7 +58,7 @@ public PaymentService transform(final ServiceRequest request) throws WorldpayMod final Order order = new Order(); order.setOrderCode(request.getOrderCode()); submitElements.add(order); - final List orderElements = order.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); + final List orderElements = order.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession(); final Info3DSecure info3DSecure = new Info3DSecure(); final List completedAuthenticationList = info3DSecure.getPaResponseOrMpiProviderOrMpiResponseOrAttemptedAuthenticationOrCompletedAuthenticationOrThreeDSVersionOrMerchantNameOrXidOrDsTransactionIdOrCavvOrEci(); completedAuthenticationList.add(new CompletedAuthentication()); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/UpdateTokenRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/UpdateTokenRequestTransformer.java index c7e4126a..e4b85c17 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/UpdateTokenRequestTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/UpdateTokenRequestTransformer.java @@ -4,10 +4,11 @@ import com.worldpay.internal.model.Modify; import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.PaymentTokenUpdate; +import com.worldpay.data.token.UpdateTokenRequest; import com.worldpay.service.request.ServiceRequest; import com.worldpay.service.request.UpdateTokenServiceRequest; import de.hybris.platform.servicelayer.config.ConfigurationService; -import org.springframework.beans.factory.annotation.Required; +import de.hybris.platform.servicelayer.dto.converter.Converter; /** * Transformer/Converter class that transforms a CreateTokenServiceRequest (abstraction) into a PaymentService (XML model) @@ -16,7 +17,14 @@ public class UpdateTokenRequestTransformer implements ServiceRequestTransformer { private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; - private ConfigurationService configurationService; + protected final ConfigurationService configurationService; + protected final Converter internalPaymentTokenUpdateConverter; + + public UpdateTokenRequestTransformer(final ConfigurationService configurationService, + final Converter internalPaymentTokenUpdateConverter) { + this.configurationService = configurationService; + this.internalPaymentTokenUpdateConverter = internalPaymentTokenUpdateConverter; + } @Override public PaymentService transform(final ServiceRequest request) throws WorldpayModelTransformationException { @@ -30,7 +38,7 @@ public PaymentService transform(final ServiceRequest request) throws WorldpayMod paymentService.setMerchantCode(updateTokenRequest.getMerchantInfo().getMerchantCode()); paymentService.setVersion(configurationService.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)); - final PaymentTokenUpdate updateToken = (PaymentTokenUpdate) updateTokenRequest.getUpdateTokenRequest().transformToInternalModel(); + final PaymentTokenUpdate updateToken = internalPaymentTokenUpdateConverter.convert(updateTokenRequest.getUpdateTokenRequest()); final Modify modify = new Modify(); modify.getOrderModificationOrBatchModificationOrAccountBatchModificationOrFuturePayAgreementModificationOrPaymentTokenUpdateOrPaymentTokenDelete().add(updateToken); @@ -39,8 +47,4 @@ public PaymentService transform(final ServiceRequest request) throws WorldpayMod return paymentService; } - @Required - public void setConfigurationService(final ConfigurationService configurationService) { - this.configurationService = configurationService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/VoidRequestTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/VoidRequestTransformer.java new file mode 100644 index 00000000..798b9a7d --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/request/transform/VoidRequestTransformer.java @@ -0,0 +1,60 @@ +package com.worldpay.service.request.transform; + +import com.worldpay.exception.WorldpayModelTransformationException; +import com.worldpay.internal.model.Modify; +import com.worldpay.internal.model.OrderModification; +import com.worldpay.internal.model.PaymentService; +import com.worldpay.internal.model.VoidSale; +import com.worldpay.service.request.ServiceRequest; +import com.worldpay.service.request.VoidSaleServiceRequest; +import de.hybris.platform.servicelayer.config.ConfigurationService; + +/** + * Specific class for transforming an {@link VoidSaleServiceRequest} into a {@link PaymentService} object + *

+ *

The external model objects each know how to transform themselves into an internal model object representation. This class adds the surrounding classes that are required + * to generate xml in the form: + *

+ *  <paymentService merchantCode="MYMERCHANT" version="1.4">
+ *      <modify>
+ *          <orderModification orderCode="1234">
+ *              <voidSale/>
+ *          </orderModification>
+ *      </modify>
+ *  </paymentService>
+ * 
+ *

+ */ +public class VoidRequestTransformer implements ServiceRequestTransformer { + private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; + + protected final ConfigurationService configurationService; + + public VoidRequestTransformer(final ConfigurationService configurationService) { + this.configurationService = configurationService; + } + + /** + * (non-Javadoc) + * + * @see ServiceRequestTransformer#transform(ServiceRequest) + */ + @Override + public PaymentService transform(final ServiceRequest request) throws WorldpayModelTransformationException { + if (request == null || request.getMerchantInfo() == null || request.getOrderCode() == null) { + throw new WorldpayModelTransformationException("Request provided to do the void is invalid."); + } + final PaymentService paymentService = new PaymentService(); + paymentService.setMerchantCode(request.getMerchantInfo().getMerchantCode()); + paymentService.setVersion(configurationService.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)); + + final Modify modify = new Modify(); + final OrderModification orderModification = new OrderModification(); + orderModification.setOrderCode(request.getOrderCode()); + final VoidSale voidSale = new VoidSale(); + orderModification.getCancelOrCaptureOrRefundOrRevokeOrAddBackOfficeCodeOrAuthoriseOrIncreaseAuthorisationOrCancelOrRefundOrDefendOrShopperWebformRefundDetailsOrExtendExpiryDateOrCancelRefundOrCancelRetryOrVoidSaleOrApprove().add(voidSale); + modify.getOrderModificationOrBatchModificationOrAccountBatchModificationOrFuturePayAgreementModificationOrPaymentTokenUpdateOrPaymentTokenDelete().add(orderModification); + paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().add(modify); + return paymentService; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/AbstractServiceResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/AbstractServiceResponse.java index 4961ff16..f590659a 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/AbstractServiceResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/AbstractServiceResponse.java @@ -1,6 +1,6 @@ package com.worldpay.service.response; -import com.worldpay.service.model.ErrorDetail; +import com.worldpay.data.ErrorDetail; /** * Template implementation of a {@link ServiceResponse} providing order code and {@link ErrorDetail} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/CaptureServiceResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/CaptureServiceResponse.java index 2189d0e0..75e443ed 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/CaptureServiceResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/CaptureServiceResponse.java @@ -1,15 +1,15 @@ package com.worldpay.service.response; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.Amount; +import com.worldpay.data.Amount; import com.worldpay.service.request.CaptureServiceRequest; /** * This class represents the details that are passed back from a call to {@link WorldpayServiceGateway#capture(CaptureServiceRequest)} capture()} in the * WorldpayServiceGateway - * + * *

On top of the standard parameters it provides the amount captured

- * + * */ public class CaptureServiceResponse extends AbstractServiceResponse { @@ -22,5 +22,5 @@ public Amount getAmount() { public void setAmount(Amount amount) { this.amount = amount; } - + } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/CreateTokenResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/CreateTokenResponse.java index 07297d03..98fdc2e0 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/CreateTokenResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/CreateTokenResponse.java @@ -1,7 +1,7 @@ package com.worldpay.service.response; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.request.CreateTokenServiceRequest; /** diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/DeleteTokenResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/DeleteTokenResponse.java index 6a881613..6cae3a65 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/DeleteTokenResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/DeleteTokenResponse.java @@ -1,6 +1,6 @@ package com.worldpay.service.response; -import com.worldpay.service.model.token.DeleteTokenReply; +import com.worldpay.data.token.DeleteTokenReply; /** * Object representing the response of a delete token request. diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/DirectAuthoriseServiceResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/DirectAuthoriseServiceResponse.java index ee8b34d3..db90b0e9 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/DirectAuthoriseServiceResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/DirectAuthoriseServiceResponse.java @@ -3,10 +3,10 @@ import com.worldpay.enums.order.ThreeDSecureFlowEnum; import com.worldpay.enums.order.ThreeDSecureVersionEnum; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.RedirectReference; -import com.worldpay.service.model.Request3DInfo; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.RedirectReference; +import com.worldpay.data.Request3DInfo; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.request.DirectAuthoriseServiceRequest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/OrderInquiryServiceResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/OrderInquiryServiceResponse.java index 68c39f4d..b90446f8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/OrderInquiryServiceResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/OrderInquiryServiceResponse.java @@ -1,7 +1,7 @@ package com.worldpay.service.response; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.RedirectReference; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.RedirectReference; /** * This class represents the details that are passed back from a call to {@link com.worldpay.service.WorldpayServiceGateway#orderInquiry(com.worldpay.service.request.AbstractServiceRequest) orderInquiry()} in the diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/RedirectAuthoriseServiceResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/RedirectAuthoriseServiceResponse.java index bdb95834..38b8bc05 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/RedirectAuthoriseServiceResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/RedirectAuthoriseServiceResponse.java @@ -1,8 +1,8 @@ package com.worldpay.service.response; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.RedirectReference; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.data.RedirectReference; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.request.RedirectAuthoriseServiceRequest; /** diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/RefundServiceResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/RefundServiceResponse.java index 8f267120..6e97cc8d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/RefundServiceResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/RefundServiceResponse.java @@ -1,7 +1,7 @@ package com.worldpay.service.response; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.Amount; +import com.worldpay.data.Amount; import com.worldpay.service.request.RefundServiceRequest; /** diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/SecondThreeDSecurePaymentServiceResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/SecondThreeDSecurePaymentServiceResponse.java index c8200007..728b6371 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/SecondThreeDSecurePaymentServiceResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/SecondThreeDSecurePaymentServiceResponse.java @@ -1,6 +1,6 @@ package com.worldpay.service.response; -import com.worldpay.service.model.PaymentReply; +import com.worldpay.data.PaymentReply; /** * This class represents the details that are passed back from a call to diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/ServiceResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/ServiceResponse.java index 07f7a610..02d881af 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/ServiceResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/ServiceResponse.java @@ -1,6 +1,6 @@ package com.worldpay.service.response; -import com.worldpay.service.model.ErrorDetail; +import com.worldpay.data.ErrorDetail; /** * Interface representation of a Service Response that will be returned from the calls through to Worldpay. diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/UpdateTokenResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/UpdateTokenResponse.java index abaddcb2..e8839711 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/UpdateTokenResponse.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/UpdateTokenResponse.java @@ -1,6 +1,6 @@ package com.worldpay.service.response; -import com.worldpay.service.model.token.UpdateTokenReply; +import com.worldpay.data.token.UpdateTokenReply; public class UpdateTokenResponse extends AbstractServiceResponse { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/VoidSaleServiceResponse.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/VoidSaleServiceResponse.java new file mode 100644 index 00000000..70ce0ec7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/VoidSaleServiceResponse.java @@ -0,0 +1,13 @@ +package com.worldpay.service.response; + +import com.worldpay.service.WorldpayServiceGateway; + +/** + * This class represents the details that are passed back from a call to {@link WorldpayServiceGateway#voidSale(com.worldpay.service.request.VoidSaleServiceRequest) voidSale()} in the + * WorldpayServiceGateway + *

+ *

No further parameters are returned on top of the standard ones

+ */ +public class VoidSaleServiceResponse extends CancelServiceResponse { + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/AddBackOfficeCodeResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/AddBackOfficeCodeResponseTransformer.java index 910087a0..b74dcaa6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/AddBackOfficeCodeResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/AddBackOfficeCodeResponseTransformer.java @@ -19,33 +19,36 @@ public class AddBackOfficeCodeResponseTransformer extends AbstractServiceRespons * @see com.worldpay.service.response.transform.AbstractServiceResponseTransformer#transform(com.worldpay.internal.model.PaymentService) */ @Override - public ServiceResponse transform(PaymentService reply) throws WorldpayModelTransformationException { - AddBackOfficeCodeServiceResponse addBackOfficeCodeResponse = new AddBackOfficeCodeServiceResponse(); + public ServiceResponse transform(final PaymentService reply) throws WorldpayModelTransformationException { + final AddBackOfficeCodeServiceResponse addBackOfficeCodeResponse = new AddBackOfficeCodeServiceResponse(); + + final Reply intReply = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); - final Object responseType = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - final Reply intReply = (Reply) responseType; if (getServiceResponseTransformerHelper().checkForError(addBackOfficeCodeResponse, intReply)) { return addBackOfficeCodeResponse; } - final Ok intOk = (Ok) intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); - if (intOk == null) { - throw new WorldpayModelTransformationException("No ok status returned in Worldpay reply message"); - } - final Object receivedType = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived().get(0); - if (receivedType instanceof BackofficeCodeReceived) { - BackofficeCodeReceived intBackOfficeCodeReceived = (BackofficeCodeReceived) receivedType; - addBackOfficeCodeResponse.setOrderCode(intBackOfficeCodeReceived.getOrderCode()); - addBackOfficeCodeResponse.setBackOfficeCode(intBackOfficeCodeReceived.getBackOfficeCode()); - } else { - throw new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for add back office code"); - } + final Ok intOk = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(Ok.class::isInstance) + .map(Ok.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("No ok status returned in Worldpay reply message")); + + final BackofficeCodeReceived intBackOfficeCodeReceived = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived() + .stream() + .filter(BackofficeCodeReceived.class::isInstance) + .map(BackofficeCodeReceived.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for add back office code")); + + addBackOfficeCodeResponse.setOrderCode(intBackOfficeCodeReceived.getOrderCode()); + addBackOfficeCodeResponse.setBackOfficeCode(intBackOfficeCodeReceived.getBackOfficeCode()); return addBackOfficeCodeResponse; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/AuthorisationCodeResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/AuthorisationCodeResponseTransformer.java index feef6338..00a1ee18 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/AuthorisationCodeResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/AuthorisationCodeResponseTransformer.java @@ -19,33 +19,37 @@ public class AuthorisationCodeResponseTransformer extends AbstractServiceRespons * @see com.worldpay.service.response.transform.AbstractServiceResponseTransformer#transform(com.worldpay.internal.model.PaymentService) */ @Override - public ServiceResponse transform(PaymentService reply) throws WorldpayModelTransformationException { - AuthorisationCodeServiceResponse authorisationCodeResponse = new AuthorisationCodeServiceResponse(); + public ServiceResponse transform(final PaymentService reply) throws WorldpayModelTransformationException { + final AuthorisationCodeServiceResponse authorisationCodeResponse = new AuthorisationCodeServiceResponse(); + + final Reply intReply = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); - final Object responseType = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - final Reply intReply = (Reply) responseType; if (getServiceResponseTransformerHelper().checkForError(authorisationCodeResponse, intReply)) { return authorisationCodeResponse; } - final Ok intOk = (Ok) intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); - if (intOk == null) { - throw new WorldpayModelTransformationException("No ok status returned in Worldpay reply message"); - } - final Object receivedType = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived().get(0); - if (receivedType instanceof AuthorisationCodeReceived) { - AuthorisationCodeReceived intAuthorisationCodeReceived = (AuthorisationCodeReceived) receivedType; - authorisationCodeResponse.setOrderCode(intAuthorisationCodeReceived.getOrderCode()); - authorisationCodeResponse.setAuthorisationCode(intAuthorisationCodeReceived.getAuthorisationCode()); - } else { - throw new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for authorisation code"); - } + final Ok intOk = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(Ok.class::isInstance) + .map(Ok.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("No ok status returned in Worldpay reply message")); + + + final AuthorisationCodeReceived intAuthorisationCodeReceived = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived() + .stream() + .filter(AuthorisationCodeReceived.class::isInstance) + .map(AuthorisationCodeReceived.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for authorisation code")); + + authorisationCodeResponse.setOrderCode(intAuthorisationCodeReceived.getOrderCode()); + authorisationCodeResponse.setAuthorisationCode(intAuthorisationCodeReceived.getAuthorisationCode()); return authorisationCodeResponse; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CancelResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CancelResponseTransformer.java index c28b12ef..27c4d4cb 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CancelResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CancelResponseTransformer.java @@ -19,32 +19,35 @@ public class CancelResponseTransformer extends AbstractServiceResponseTransforme * @see com.worldpay.service.response.transform.AbstractServiceResponseTransformer#transform(com.worldpay.internal.model.PaymentService) */ @Override - public ServiceResponse transform(PaymentService reply) throws WorldpayModelTransformationException { + public ServiceResponse transform(final PaymentService reply) throws WorldpayModelTransformationException { final CancelServiceResponse response = new CancelServiceResponse(); - final Object responseType = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - final Reply intReply = (Reply) responseType; + final Reply intReply = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); + if (getServiceResponseTransformerHelper().checkForError(response, intReply)) { return response; } - final Ok intOk = (Ok) intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); - if (intOk == null) { - throw new WorldpayModelTransformationException("No ok status returned in Worldpay reply message"); - } - final Object receivedType = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived().get(0); - if (receivedType instanceof VoidReceived) { - final VoidReceived intVoidReceived = (VoidReceived) receivedType; - response.setOrderCode(intVoidReceived.getOrderCode()); - } else { - throw new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for cancel"); - } + final Ok intOk = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(Ok.class::isInstance) + .map(Ok.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("No ok status returned in Worldpay reply message")); + + final VoidReceived receivedType = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived() + .stream() + .filter(VoidReceived.class::isInstance) + .map(VoidReceived.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for cancel")); + + response.setOrderCode(receivedType.getOrderCode()); return response; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CaptureResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CaptureResponseTransformer.java index 1aaa90f5..53b2df07 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CaptureResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CaptureResponseTransformer.java @@ -1,54 +1,62 @@ package com.worldpay.service.response.transform; +import com.worldpay.data.Amount; import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.CaptureReceived; import com.worldpay.internal.model.Ok; import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.Reply; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.DebitCreditIndicator; import com.worldpay.service.response.CaptureServiceResponse; import com.worldpay.service.response.ServiceResponse; +import de.hybris.platform.servicelayer.dto.converter.Converter; /** * Specific class for transforming a {@link PaymentService} into a {@link CaptureServiceResponse} object */ public class CaptureResponseTransformer extends AbstractServiceResponseTransformer { - /** (non-Javadoc) + protected final Converter internalAmountReverseConverter; + + public CaptureResponseTransformer(final Converter internalAmountReverseConverter) { + this.internalAmountReverseConverter = internalAmountReverseConverter; + } + + /** + * (non-Javadoc) + * * @see com.worldpay.service.response.transform.AbstractServiceResponseTransformer#transform(com.worldpay.internal.model.PaymentService) */ @Override - public ServiceResponse transform(PaymentService reply) throws WorldpayModelTransformationException { + public ServiceResponse transform(final PaymentService reply) throws WorldpayModelTransformationException { final CaptureServiceResponse captureResponse = new CaptureServiceResponse(); - final Object responseType = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - final Reply intReply = (Reply) responseType; + final Reply intReply = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); + if (getServiceResponseTransformerHelper().checkForError(captureResponse, intReply)) { return captureResponse; } - final Ok intOk = (Ok) intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); - if (intOk == null) { - throw new WorldpayModelTransformationException("No ok status returned in Worldpay reply message"); - } - final Object receivedType = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived().get(0); - if (receivedType instanceof CaptureReceived) { - CaptureReceived intCaptureReceived = (CaptureReceived) receivedType; - captureResponse.setOrderCode(intCaptureReceived.getOrderCode()); - - com.worldpay.internal.model.Amount intAmount = intCaptureReceived.getAmount(); - Amount amount = new Amount(intAmount.getValue(), intAmount.getCurrencyCode(), intAmount.getExponent(), DebitCreditIndicator.getDebitCreditIndicator(intAmount.getDebitCreditIndicator())); - captureResponse.setAmount(amount); - } else { - throw new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for capture"); - } + final Ok intOk = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(Ok.class::isInstance) + .map(Ok.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("No ok status returned in Worldpay reply message")); + + final CaptureReceived intCaptureReceived = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived() + .stream() + .filter(CaptureReceived.class::isInstance) + .map(CaptureReceived.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for capture")); + + captureResponse.setOrderCode(intCaptureReceived.getOrderCode()); + captureResponse.setAmount(internalAmountReverseConverter.convert(intCaptureReceived.getAmount())); return captureResponse; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CreateTokenResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CreateTokenResponseTransformer.java index 03df2d18..dd279ffd 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CreateTokenResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/CreateTokenResponseTransformer.java @@ -17,24 +17,22 @@ public class CreateTokenResponseTransformer extends AbstractServiceResponseTrans public ServiceResponse transform(final PaymentService paymentService) throws WorldpayModelTransformationException { final CreateTokenResponse createTokenResponse = new CreateTokenResponse(); - final Object responseType = paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay create token response"); - } - - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - - final Reply intReply = (Reply) responseType; - - final Object response = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); + final Reply intReply = paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); if (getServiceResponseTransformerHelper().checkForError(createTokenResponse, intReply)) { return createTokenResponse; - } else if (response instanceof Token) { - createTokenResponse.setToken(getServiceResponseTransformerHelper().buildTokenReply((Token) response)); } + intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(Token.class::isInstance) + .map(Token.class::cast) + .findAny() + .ifPresent(response -> createTokenResponse.setToken(getServiceResponseTransformerHelper().buildTokenReply(response))); return createTokenResponse; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/DeleteTokenResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/DeleteTokenResponseTransformer.java index 6b7de6cb..ecddddd4 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/DeleteTokenResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/DeleteTokenResponseTransformer.java @@ -17,30 +17,32 @@ public class DeleteTokenResponseTransformer extends AbstractServiceResponseTrans @Override public ServiceResponse transform(final PaymentService paymentService) throws WorldpayModelTransformationException { - final Object responseType = paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay delete token response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - - final Reply intReply = (Reply) responseType; - - final Object response = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); + final Reply intReply = paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); final DeleteTokenResponse deleteTokenResponse = new DeleteTokenResponse(); if (getServiceResponseTransformerHelper().checkForError(deleteTokenResponse, intReply)) { return deleteTokenResponse; } - if (!(response instanceof Ok)) { - throw new WorldpayModelTransformationException("DeleteTokenResponse did not contain an OK object"); - } - final Ok okResponse = (Ok) response; - final Object deleteTokenReceived = okResponse.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived().get(0); - if (deleteTokenReceived instanceof DeleteTokenReceived) { - deleteTokenResponse.setDeleteTokenResponse(getServiceResponseTransformerHelper().buildDeleteTokenReply((DeleteTokenReceived) deleteTokenReceived)); - } + + final Ok okResponse = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(Ok.class::isInstance) + .map(Ok.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("DeleteTokenResponse did not contain an OK object")); + + okResponse.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived() + .stream() + .filter(DeleteTokenReceived.class::isInstance) + .map(DeleteTokenReceived.class::cast) + .findAny() + .ifPresent(deleteTokenReceived -> deleteTokenResponse.setDeleteTokenResponse(getServiceResponseTransformerHelper().buildDeleteTokenReply(deleteTokenReceived))); + return deleteTokenResponse; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/DirectAuthoriseResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/DirectAuthoriseResponseTransformer.java index f1e5797c..e00da6e0 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/DirectAuthoriseResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/DirectAuthoriseResponseTransformer.java @@ -2,8 +2,8 @@ import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.*; -import com.worldpay.service.model.RedirectReference; -import com.worldpay.service.model.Request3DInfo; +import com.worldpay.data.RedirectReference; +import com.worldpay.data.Request3DInfo; import com.worldpay.service.response.DirectAuthoriseServiceResponse; import com.worldpay.service.response.ServiceResponse; @@ -22,32 +22,32 @@ public class DirectAuthoriseResponseTransformer extends AbstractServiceResponseT @Override public ServiceResponse transform(final PaymentService paymentServiceReply) throws WorldpayModelTransformationException { - final Object responseType = paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - final Reply intReply = (Reply) responseType; + final Reply intReply = paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); final DirectAuthoriseServiceResponse authResponse = new DirectAuthoriseServiceResponse(); if (getServiceResponseTransformerHelper().checkForError(authResponse, intReply)) { return authResponse; } - final Object response = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); - if (response instanceof OrderStatus) { - final OrderStatus intOrderStatus = (OrderStatus) response; + final OrderStatus intOrderStatus = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(OrderStatus.class::isInstance) + .map(OrderStatus.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("No order status returned in Worldpay reply message")); + authResponse.setOrderCode(intOrderStatus.getOrderCode()); final List intOrderStatusElements = intOrderStatus.getReferenceOrBankAccountOrApmEnrichedDataOrErrorOrPaymentOrQrCodeOrCardBalanceOrPaymentAdditionalDetailsOrBillingAddressDetailsOrExemptionResponseOrOrderModificationOrJournalOrRequestInfoOrChallengeRequiredOrFxApprovalRequiredOrPbbaRTPOrContentOrJournalTypeDetailOrTokenOrDateOrEchoDataOrPayAsOrderUseNewOrderCodeOrAuthenticateResponse(); for (final Object orderStatusType : intOrderStatusElements) { transformOrderStatus(authResponse, intOrderStatus, orderStatusType); } - } else { - throw new WorldpayModelTransformationException("No order status returned in Worldpay reply message"); - } + return authResponse; } @@ -77,7 +77,12 @@ private void transformOrderStatus(final DirectAuthoriseServiceResponse authRespo .filter(Reference.class::isInstance) .map(Reference.class::cast) .findAny() - .map(reference -> new RedirectReference(reference.getId(), reference.getvalue())) + .map(reference -> { + final RedirectReference redirectReference = new RedirectReference(); + redirectReference.setValue(reference.getvalue()); + redirectReference.setId(reference.getId()); + return redirectReference; + }) .ifPresent(authResponse::setRedirectReference); intOrderStatuses.stream() diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/OrderInquiryResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/OrderInquiryResponseTransformer.java index 2e2abd8e..4159e542 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/OrderInquiryResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/OrderInquiryResponseTransformer.java @@ -2,8 +2,8 @@ import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.*; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.RedirectReference; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.RedirectReference; import com.worldpay.service.response.OrderInquiryServiceResponse; import com.worldpay.service.response.ServiceResponse; @@ -18,25 +18,27 @@ public class OrderInquiryResponseTransformer extends AbstractServiceResponseTran * @see AbstractServiceResponseTransformer#transform(com.worldpay.internal.model.PaymentService) */ @Override - public ServiceResponse transform(PaymentService reply) throws WorldpayModelTransformationException { - OrderInquiryServiceResponse orderInquiryResponse = new OrderInquiryServiceResponse(); + public ServiceResponse transform(final PaymentService reply) throws WorldpayModelTransformationException { + final OrderInquiryServiceResponse orderInquiryResponse = new OrderInquiryServiceResponse(); + + final Reply intReply = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); - final Object responseType = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - final Reply intReply = (Reply) responseType; if (getServiceResponseTransformerHelper().checkForError(orderInquiryResponse, intReply)) { return orderInquiryResponse; } - final OrderStatus intOrderStatus = (OrderStatus) intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); - if (intOrderStatus == null) { - throw new WorldpayModelTransformationException("No order status returned in Worldpay reply message"); - } + final OrderStatus intOrderStatus = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(OrderStatus.class::isInstance) + .map(OrderStatus.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("No order status returned in Worldpay reply message")); + orderInquiryResponse.setOrderCode(intOrderStatus.getOrderCode()); final List orderStatusElements = intOrderStatus.getReferenceOrBankAccountOrApmEnrichedDataOrErrorOrPaymentOrQrCodeOrCardBalanceOrPaymentAdditionalDetailsOrBillingAddressDetailsOrExemptionResponseOrOrderModificationOrJournalOrRequestInfoOrChallengeRequiredOrFxApprovalRequiredOrPbbaRTPOrContentOrJournalTypeDetailOrTokenOrDateOrEchoDataOrPayAsOrderUseNewOrderCodeOrAuthenticateResponse(); @@ -47,7 +49,9 @@ public ServiceResponse transform(PaymentService reply) throws WorldpayModelTrans orderInquiryResponse.setPaymentReply(paymentReply); } else if (orderStatusElement instanceof Reference) { final Reference intReference = (Reference) orderStatusElement; - final RedirectReference reference = new RedirectReference(intReference.getId(), intReference.getvalue()); + final RedirectReference reference = new RedirectReference(); + reference.setId(intReference.getId()); + reference.setValue(intReference.getvalue()); orderInquiryResponse.setReference(reference); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/RedirectAuthoriseResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/RedirectAuthoriseResponseTransformer.java index a43f8583..6ea2b16f 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/RedirectAuthoriseResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/RedirectAuthoriseResponseTransformer.java @@ -2,7 +2,7 @@ import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.*; -import com.worldpay.service.model.RedirectReference; +import com.worldpay.data.RedirectReference; import com.worldpay.service.response.RedirectAuthoriseServiceResponse; import com.worldpay.service.response.ServiceResponse; @@ -22,22 +22,24 @@ public class RedirectAuthoriseResponseTransformer extends AbstractServiceRespons public ServiceResponse transform(final PaymentService paymentServiceReply) throws WorldpayModelTransformationException { final RedirectAuthoriseServiceResponse authResponse = new RedirectAuthoriseServiceResponse(); - final Object responseType = paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - final Reply intReply = (Reply) responseType; + final Reply intReply = paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); + if (getServiceResponseTransformerHelper().checkForError(authResponse, intReply)) { return authResponse; } - final OrderStatus intOrderStatus = (OrderStatus) intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); - if (intOrderStatus == null) { - throw new WorldpayModelTransformationException("No order status returned in Worldpay reply message"); - } + final OrderStatus intOrderStatus = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(OrderStatus.class::isInstance) + .map(OrderStatus.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("No order status returned in Worldpay reply message")); + authResponse.setOrderCode(intOrderStatus.getOrderCode()); final List intOrderData = intOrderStatus.getReferenceOrBankAccountOrApmEnrichedDataOrErrorOrPaymentOrQrCodeOrCardBalanceOrPaymentAdditionalDetailsOrBillingAddressDetailsOrExemptionResponseOrOrderModificationOrJournalOrRequestInfoOrChallengeRequiredOrFxApprovalRequiredOrPbbaRTPOrContentOrJournalTypeDetailOrTokenOrDateOrEchoDataOrPayAsOrderUseNewOrderCodeOrAuthenticateResponse(); @@ -55,7 +57,10 @@ public ServiceResponse transform(final PaymentService paymentServiceReply) throw .findAny() .orElseThrow(() -> new WorldpayModelTransformationException("Order status type returned in Worldpay reply message is not one of the expected types for redirect authorise")); - final RedirectReference redirectReference = new RedirectReference(reference.getId(), reference.getvalue()); + + final RedirectReference redirectReference = new RedirectReference(); + redirectReference.setValue(reference.getvalue()); + redirectReference.setId(reference.getId()); authResponse.setRedirectReference(redirectReference); return authResponse; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/RefundResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/RefundResponseTransformer.java index 39cd7478..4d6af352 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/RefundResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/RefundResponseTransformer.java @@ -1,55 +1,60 @@ package com.worldpay.service.response.transform; +import com.worldpay.data.Amount; import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.Ok; import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.RefundReceived; import com.worldpay.internal.model.Reply; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.DebitCreditIndicator; import com.worldpay.service.response.RefundServiceResponse; import com.worldpay.service.response.ServiceResponse; +import de.hybris.platform.servicelayer.dto.converter.Converter; /** * Specific class for transforming a {@link PaymentService} into an {@link RefundServiceResponse} object */ public class RefundResponseTransformer extends AbstractServiceResponseTransformer { + protected final Converter internalAmountReverseConverter; + + public RefundResponseTransformer(final Converter internalAmountReverseConverter) { + this.internalAmountReverseConverter = internalAmountReverseConverter; + } + /* (non-Javadoc) * @see AbstractServiceResponseTransformer#transform(com.worldpay.internal.model.PaymentService) */ @Override - public ServiceResponse transform(PaymentService reply) throws WorldpayModelTransformationException { - RefundServiceResponse refundResponse = new RefundServiceResponse(); + public ServiceResponse transform(final PaymentService reply) throws WorldpayModelTransformationException { + final RefundServiceResponse refundResponse = new RefundServiceResponse(); + + final Reply intReply = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); - final Object responseType = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - final Reply intReply = (Reply) responseType; if (getServiceResponseTransformerHelper().checkForError(refundResponse, intReply)) { return refundResponse; } - final Ok intOk = (Ok) intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); - if (intOk == null) { - throw new WorldpayModelTransformationException("No ok status returned in Worldpay reply message"); - } - final Object receivedType = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived().get(0); - if (receivedType instanceof RefundReceived) { - RefundReceived intRefundReceived = (RefundReceived) receivedType; - refundResponse.setOrderCode(intRefundReceived.getOrderCode()); - - com.worldpay.internal.model.Amount intAmount = intRefundReceived.getAmount(); - Amount amount = new Amount(intAmount.getValue(), intAmount.getCurrencyCode(), intAmount.getExponent(), DebitCreditIndicator.getDebitCreditIndicator(intAmount.getDebitCreditIndicator())); - refundResponse.setAmount(amount); - } else { - throw new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for refund"); - } + final Ok intOk = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(Ok.class::isInstance) + .map(Ok.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("No ok status returned in Worldpay reply message")); + + final RefundReceived intRefundReceived = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived() + .stream() + .filter(RefundReceived.class::isInstance) + .map(RefundReceived.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for refund")); + refundResponse.setOrderCode(intRefundReceived.getOrderCode()); + refundResponse.setAmount(internalAmountReverseConverter.convert(intRefundReceived.getAmount())); return refundResponse; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/SecondThreeDSecurePaymentResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/SecondThreeDSecurePaymentResponseTransformer.java index 5e800b07..a0c5b0bd 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/SecondThreeDSecurePaymentResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/SecondThreeDSecurePaymentResponseTransformer.java @@ -7,7 +7,6 @@ import com.worldpay.internal.model.Reply; import com.worldpay.service.response.SecondThreeDSecurePaymentServiceResponse; import com.worldpay.service.response.ServiceResponse; -import org.apache.commons.collections4.CollectionUtils; import java.util.List; @@ -28,14 +27,12 @@ public ServiceResponse transform(final PaymentService paymentServiceReply) throw throw new WorldpayModelTransformationException("The Worldpay response is null"); } - if (CollectionUtils.isEmpty(paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify()) || paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0) == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay response"); - } - final Object responseType = paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - final Reply intReply = (Reply) responseType; + final Reply intReply = paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); final SecondThreeDSecurePaymentServiceResponse response = new SecondThreeDSecurePaymentServiceResponse(); if (getServiceResponseTransformerHelper().checkForError(response, intReply)) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/ServiceResponseTransformerHelper.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/ServiceResponseTransformerHelper.java index f4aa081c..d9f75c47 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/ServiceResponseTransformerHelper.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/ServiceResponseTransformerHelper.java @@ -1,13 +1,13 @@ package com.worldpay.service.response.transform; import com.worldpay.internal.model.*; -import com.worldpay.service.model.ErrorDetail; -import com.worldpay.service.model.JournalReply; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.WebformRefundReply; -import com.worldpay.service.model.token.DeleteTokenReply; -import com.worldpay.service.model.token.TokenReply; -import com.worldpay.service.model.token.UpdateTokenReply; +import com.worldpay.data.ErrorDetail; +import com.worldpay.data.JournalReply; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.WebformRefundReply; +import com.worldpay.data.token.DeleteTokenReply; +import com.worldpay.data.token.TokenReply; +import com.worldpay.data.token.UpdateTokenReply; import com.worldpay.service.response.ServiceResponse; /** diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/UpdateTokenResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/UpdateTokenResponseTransformer.java index d230f889..5b07ba57 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/UpdateTokenResponseTransformer.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/UpdateTokenResponseTransformer.java @@ -5,6 +5,7 @@ import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.Reply; import com.worldpay.internal.model.UpdateTokenReceived; +import com.worldpay.data.token.UpdateTokenReply; import com.worldpay.service.response.ServiceResponse; import com.worldpay.service.response.UpdateTokenResponse; @@ -17,29 +18,35 @@ public class UpdateTokenResponseTransformer extends AbstractServiceResponseTrans @Override public ServiceResponse transform(final PaymentService paymentService) throws WorldpayModelTransformationException { - final Object responseType = paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - if (responseType == null) { - throw new WorldpayModelTransformationException("No reply message in Worldpay update token response"); - } - if (!(responseType instanceof Reply)) { - throw new WorldpayModelTransformationException("Reply type from Worldpay not the expected type"); - } - - final Reply intReply = (Reply) responseType; - final Object response = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken().get(0); + final Reply intReply = paymentService.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Update Token Response has no reply message or the reply type is not the expected one")); final UpdateTokenResponse updateTokenResponse = new UpdateTokenResponse(); if (getServiceResponseTransformerHelper().checkForError(updateTokenResponse, intReply)) { return updateTokenResponse; } - if (!(response instanceof Ok)) { - throw new WorldpayModelTransformationException("UpdateTokenResponse did not contain an OK object"); - } - final Ok okResponse = (Ok) response; - final Object updateTokenReceived = okResponse.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived().get(0); - if (updateTokenReceived instanceof UpdateTokenReceived) { - updateTokenResponse.setUpdateTokenReply(getServiceResponseTransformerHelper().buildUpdateTokenReply((UpdateTokenReceived) updateTokenReceived)); - } + final Ok okResponse = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(Ok.class::isInstance) + .map(Ok.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("UpdateTokenResponse did not contain an OK object")); + + okResponse.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived() + .stream() + .filter(UpdateTokenReceived.class::isInstance) + .map(UpdateTokenReceived.class::cast) + .findAny() + .ifPresent(updateTokenReceived -> updateTokenResponse.setUpdateTokenReply(buildUpdateReplyToken(updateTokenReceived))); + return updateTokenResponse; } + + private UpdateTokenReply buildUpdateReplyToken(final UpdateTokenReceived updateTokenReceived) { + return getServiceResponseTransformerHelper().buildUpdateTokenReply(updateTokenReceived); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/VoidSaleResponseTransformer.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/VoidSaleResponseTransformer.java new file mode 100644 index 00000000..d56d325f --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/VoidSaleResponseTransformer.java @@ -0,0 +1,54 @@ +package com.worldpay.service.response.transform; + +import com.worldpay.exception.WorldpayModelTransformationException; +import com.worldpay.internal.model.Ok; +import com.worldpay.internal.model.PaymentService; +import com.worldpay.internal.model.Reply; +import com.worldpay.internal.model.VoidSaleReceived; +import com.worldpay.service.response.ServiceResponse; +import com.worldpay.service.response.VoidSaleServiceResponse; + +/** + * Specific class for transforming a {@link PaymentService} into a {@link VoidSaleServiceResponse} object + */ +public class VoidSaleResponseTransformer extends AbstractServiceResponseTransformer { + + /** + * (non-Javadoc) + * + * @see AbstractServiceResponseTransformer#transform(PaymentService) + */ + @Override + public ServiceResponse transform(final PaymentService reply) throws WorldpayModelTransformationException { + final VoidSaleServiceResponse response = new VoidSaleServiceResponse(); + + final Reply intReply = reply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify() + .stream() + .filter(Reply.class::isInstance) + .map(Reply.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Reply has no reply message or the reply type is not the expected one")); + + if (getServiceResponseTransformerHelper().checkForError(response, intReply)) { + return response; + } + + final Ok intOk = intReply.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken() + .stream() + .filter(Ok.class::isInstance) + .map(Ok.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("No ok status returned in Worldpay reply message")); + + final VoidSaleReceived receivedType = intOk.getCancelReceivedOrVoidReceivedOrCaptureReceivedOrRevokeReceivedOrRefundReceivedOrBackofficeCodeReceivedOrAuthorisationCodeReceivedOrDefenceReceivedOrUpdateTokenReceivedOrDeleteTokenReceivedOrExtendExpiryDateReceivedOrOrderReceivedOrCancelRetryDoneOrVoidSaleReceived() + .stream() + .filter(VoidSaleReceived.class::isInstance) + .map(VoidSaleReceived.class::cast) + .findAny() + .orElseThrow(() -> new WorldpayModelTransformationException("Ok received type returned in Worldpay reply message is not one of the expected types for void")); + + response.setOrderCode(receivedType.getOrderCode()); + + return response; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/impl/DefaultServiceResponseTransformerHelper.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/impl/DefaultServiceResponseTransformerHelper.java index 75e15794..483bf1a3 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/impl/DefaultServiceResponseTransformerHelper.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/service/response/transform/impl/DefaultServiceResponseTransformerHelper.java @@ -1,32 +1,45 @@ package com.worldpay.service.response.transform.impl; +import com.worldpay.data.Address; +import com.worldpay.data.Amount; +import com.worldpay.data.Date; +import com.worldpay.data.RiskScore; +import com.worldpay.data.SchemeResponse; +import com.worldpay.data.*; +import com.worldpay.data.token.DeleteTokenReply; +import com.worldpay.data.token.TokenReply; +import com.worldpay.data.token.UpdateTokenReply; import com.worldpay.enums.order.AuthorisedStatus; import com.worldpay.internal.model.Error; import com.worldpay.internal.model.*; -import com.worldpay.service.model.Address; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.Date; -import com.worldpay.service.model.RiskScore; -import com.worldpay.service.model.SchemeResponse; -import com.worldpay.service.model.*; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.token.DeleteTokenReply; -import com.worldpay.service.model.token.TokenReply; -import com.worldpay.service.model.token.UpdateTokenReply; import com.worldpay.service.response.ServiceResponse; import com.worldpay.service.response.transform.ServiceResponseTransformerHelper; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; /** * Default implementation of {@link ServiceResponseTransformerHelper} */ public class DefaultServiceResponseTransformerHelper implements ServiceResponseTransformerHelper { + protected final Converter internalAmountReverseConverter; + protected final Converter internalDateReverseConverter; + + public DefaultServiceResponseTransformerHelper(final Converter internalAmountReverseConverter, + final Converter internalDateReverseConverter) { + this.internalAmountReverseConverter = internalAmountReverseConverter; + this.internalDateReverseConverter = internalDateReverseConverter; + } + + /** * {@inheritDoc} */ @@ -54,7 +67,10 @@ public boolean checkForError(final ServiceResponse response, final Reply reply) } private ErrorDetail buildErrorDetail(final com.worldpay.internal.model.Error intError) { - return new ErrorDetail(intError.getCode(), intError.getvalue()); + final ErrorDetail error = new ErrorDetail(); + error.setCode(intError.getCode()); + error.setMessage(intError.getvalue()); + return error; } /** @@ -73,6 +89,7 @@ public PaymentReply buildPaymentReply(final Payment intPayment) { setBalanceList(intPayment, paymentReply); setReturnCode(intPayment, paymentReply); setRiskScore(intPayment, paymentReply); + setFraudSight(intPayment, paymentReply); setAAVCodes(intPayment, paymentReply); setRefundReference(intPayment, paymentReply); setAuthorisationId(intPayment, paymentReply); @@ -110,6 +127,29 @@ private void setRiskScore(final Payment intPayment, final PaymentReply paymentRe Optional.ofNullable(intPayment.getRiskScore()).map(this::buildRiskScore).ifPresent(paymentReply::setRiskScore); } + private void setFraudSight(final Payment intPayment, final PaymentReply paymentReply) { + final FraudSight intFraudSight = intPayment.getFraudSight(); + + if (intFraudSight != null) { + + final FraudSightResponse fraudSight = new FraudSightResponse(); + fraudSight.setId(intFraudSight.getId()); + fraudSight.setScore(Double.parseDouble(intFraudSight.getScore())); + fraudSight.setMessage(intFraudSight.getMessage()); + + if (intFraudSight.getReasonCodes() != null && CollectionUtils.isNotEmpty(intFraudSight.getReasonCodes().getReasonCode())) { + + fraudSight.setReasonCodes(intFraudSight.getReasonCodes() + .getReasonCode() + .stream() + .map(ReasonCode::getvalue) + .collect(Collectors.toList())); + } + + paymentReply.setFraudSight(fraudSight); + } + } + private void setCvcResult(final Payment intPayment, final PaymentReply paymentReply) { final CVCResultCode intCvcResultCode = intPayment.getCVCResultCode(); if (intCvcResultCode != null) { @@ -217,12 +257,12 @@ public TokenReply buildTokenReply(final Token intToken) { if (tokenInformationField instanceof TokenReason) { tokenReply.setTokenReason(((TokenReason) tokenInformationField).getvalue()); } else if (tokenInformationField instanceof TokenDetails) { - final com.worldpay.service.model.token.TokenDetails tokenDetails = transformTokenDetails((TokenDetails) tokenInformationField); + final com.worldpay.data.token.TokenDetails tokenDetails = transformTokenDetails((TokenDetails) tokenInformationField); tokenReply.setTokenDetails(tokenDetails); } else if (tokenInformationField instanceof PaymentInstrument) { final Object paymentInstrument = ((PaymentInstrument) tokenInformationField).getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().get(0); if (paymentInstrument instanceof CardDetails) { - final com.worldpay.service.model.payment.Card card = transformCard((CardDetails) paymentInstrument); + final com.worldpay.data.payment.Card card = transformCard((CardDetails) paymentInstrument); tokenReply.setPaymentInstrument(card); } } else if (tokenInformationField instanceof Error) { @@ -232,8 +272,8 @@ public TokenReply buildTokenReply(final Token intToken) { return tokenReply; } - private com.worldpay.service.model.token.TokenDetails transformTokenDetails(final com.worldpay.internal.model.TokenDetails tokenInformationField) { - final com.worldpay.service.model.token.TokenDetails tokenDetails = new com.worldpay.service.model.token.TokenDetails(); + private com.worldpay.data.token.TokenDetails transformTokenDetails(final com.worldpay.internal.model.TokenDetails tokenInformationField) { + final com.worldpay.data.token.TokenDetails tokenDetails = new com.worldpay.data.token.TokenDetails(); Optional.ofNullable(tokenInformationField.getTokenReason()) .map(TokenReason::getvalue) @@ -281,7 +321,7 @@ public WebformRefundReply buildWebformRefundReply(final ShopperWebformRefundDeta } private Amount transformAmount(final com.worldpay.internal.model.Amount intAmount) { - return new Amount(intAmount.getValue(), intAmount.getCurrencyCode(), intAmount.getExponent(), DebitCreditIndicator.getDebitCreditIndicator(intAmount.getDebitCreditIndicator())); + return internalAmountReverseConverter.convert(intAmount); } private void setAAVCodes(final Payment intPayment, final PaymentReply paymentReply) { @@ -307,7 +347,7 @@ private void setAAVCodes(final Payment intPayment, final PaymentReply paymentRep } } - private com.worldpay.service.model.payment.Card transformCard(final CardDetails intCardDetails) { + private com.worldpay.data.payment.Card transformCard(final CardDetails intCardDetails) { final Derived derived = intCardDetails.getDerived(); if (derived != null) { final String cvc = intCardDetails.getCvc() == null ? null : intCardDetails.getCvc().getvalue(); @@ -320,8 +360,16 @@ private com.worldpay.service.model.payment.Card transformCard(final CardDetails setCardBrand(derived); } final String cardHolderName = transformCardHolderName(intCardDetails.getCardHolderName()); - return new com.worldpay.service.model.payment.Card(PaymentType.getPaymentType(derived.getCardBrand()), - derived.getObfuscatedPAN(), cvc, expiryDate, cardHolderName, address, null, null, null, derived.getBin()); + + final com.worldpay.data.payment.Card card = new com.worldpay.data.payment.Card(); + card.setPaymentType(PaymentType.getPaymentType(derived.getCardBrand()).getMethodCode()); + card.setCardNumber(derived.getObfuscatedPAN()); + card.setCvc(cvc); + card.setExpiryDate(expiryDate); + card.setCardHolderName(cardHolderName); + card.setBin(derived.getBin()); + card.setCardAddress(address); + return card; } return null; } @@ -376,14 +424,19 @@ private void setCardBrand(final Derived derived) { } } - private com.worldpay.service.model.payment.Card transformCard(final Card intCard, final CardHolderName cardHolderName) { + private com.worldpay.data.payment.Card transformCard(final Card intCard, final CardHolderName cardHolderName) { Date transformedDate = null; final String cardHolderNameValue = transformCardHolderName(cardHolderName); if (intCard.getExpiryDate() != null) { transformedDate = transformDate(intCard.getExpiryDate().getDate()); } - return new com.worldpay.service.model.payment.Card(PaymentType.getPaymentType(intCard.getType()), - intCard.getNumber(), null, transformedDate, cardHolderNameValue, null, null, null, null, null); + + final com.worldpay.data.payment.Card card = new com.worldpay.data.payment.Card(); + card.setPaymentType(PaymentType.getPaymentType(intCard.getType()) != null ? PaymentType.getPaymentType(intCard.getType()).getMethodCode() : null); + card.setCardNumber(intCard.getNumber()); + card.setExpiryDate(transformedDate); + card.setCardHolderName(cardHolderNameValue); + return card; } private String transformCardHolderName(final CardHolderName cardHolderName) { @@ -438,7 +491,7 @@ private void setAddressFields(final List streetOrHouseNameOrHouseNumberO } private Date transformDate(final com.worldpay.internal.model.Date intDate) { - return new Date(intDate.getDayOfMonth(), intDate.getMonth(), intDate.getYear(), intDate.getHour(), intDate.getMinute(), intDate.getSecond()); + return internalDateReverseConverter.convert(intDate); } /** @@ -469,7 +522,10 @@ private void populateAccountTransactions(final Journal intJournal, final Journal Optional.ofNullable(accountTx.getAmount()) .map(this::transformAmount) .ifPresent(accountTransaction::setAmount); - journalReply.addAccountTransaction(accountTransaction); + if (journalReply.getAccountTransactions() == null) { + journalReply.setAccountTransactions(new ArrayList<>()); + } + journalReply.getAccountTransactions().add(accountTransaction); } } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/WorldpayAuthenticatedShopperIdStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/WorldpayAuthenticatedShopperIdStrategy.java deleted file mode 100644 index 3ff05b70..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/WorldpayAuthenticatedShopperIdStrategy.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.worldpay.strategy; - -import de.hybris.platform.core.model.user.UserModel; - -/** - * Exposes methods to create authenticated shopper Ids to be sent when payment is made through a tokenised card. - */ -public interface WorldpayAuthenticatedShopperIdStrategy { - - /** - * Returns a unique authenticated shopper ID. - * - * @param userModel {@link UserModel} - * @return AuthenticatedShopperId - */ - String getAuthenticatedShopperId(UserModel userModel); -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/WorldpayMerchantStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/WorldpayMerchantStrategy.java index c56d6bf1..628108d2 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/WorldpayMerchantStrategy.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/WorldpayMerchantStrategy.java @@ -1,6 +1,6 @@ package com.worldpay.strategy; -import com.worldpay.config.merchant.WorldpayMerchantConfigData; +import com.worldpay.model.WorldpayMerchantConfigurationModel; /** * Exposes methods to retrieve the configured merchants. @@ -10,14 +10,8 @@ public interface WorldpayMerchantStrategy { /** * Returns the merchant configured * - * @return + * @return {@link WorldpayMerchantConfigurationModel} */ - WorldpayMerchantConfigData getMerchant(); + WorldpayMerchantConfigurationModel getMerchant(); - /** - * Returns the merchant configured for Replenishment - * - * @return - */ - WorldpayMerchantConfigData getReplenishmentMerchant(); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/impl/DefaultWorldpayAuthenticatedShopperIdStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/impl/DefaultWorldpayAuthenticatedShopperIdStrategy.java deleted file mode 100644 index aa6355e3..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/impl/DefaultWorldpayAuthenticatedShopperIdStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.worldpay.strategy.impl; - -import com.google.common.base.Preconditions; -import com.worldpay.strategy.WorldpayAuthenticatedShopperIdStrategy; -import de.hybris.platform.core.model.user.CustomerModel; -import de.hybris.platform.core.model.user.UserModel; -import org.apache.commons.lang3.StringUtils; - -import static java.text.MessageFormat.format; - -/** - * {@inheritDoc} - */ -public class DefaultWorldpayAuthenticatedShopperIdStrategy implements WorldpayAuthenticatedShopperIdStrategy { - - /** - * {@inheritDoc} - */ - @Override - public String getAuthenticatedShopperId(final UserModel userModel) { - Preconditions.checkNotNull(userModel, "The user is null"); - if (userModel instanceof CustomerModel) { - final String customerID = ((CustomerModel) userModel).getCustomerID(); - return StringUtils.defaultIfBlank(customerID, ((CustomerModel) userModel).getOriginalUid()); - } - throw new IllegalArgumentException(format("The user {0} is not of type Customer.", userModel)); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/impl/DefaultWorldpayMerchantStrategy.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/impl/DefaultWorldpayMerchantStrategy.java index f215609d..4b8af9ec 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/impl/DefaultWorldpayMerchantStrategy.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/strategy/impl/DefaultWorldpayMerchantStrategy.java @@ -1,50 +1,34 @@ package com.worldpay.strategy.impl; -import com.worldpay.config.merchant.WorldpayMerchantConfigData; -import com.worldpay.merchant.WorldpayMerchantConfigDataService; +import com.worldpay.merchant.configuration.services.WorldpayMerchantConfigurationService; +import com.worldpay.model.WorldpayMerchantConfigurationModel; import com.worldpay.strategy.WorldpayMerchantStrategy; import de.hybris.platform.assistedserviceservices.AssistedServiceService; -import org.springframework.beans.factory.annotation.Required; - -import java.util.Map; /** * Default implementation of Worldpay merchant strategy */ public class DefaultWorldpayMerchantStrategy implements WorldpayMerchantStrategy { - private static final String WEB = "web"; - private static final String ASM_MERCHANT = "asm"; - private static final String REPLENISHMENT_MERCHANT = "replenishment"; - private WorldpayMerchantConfigDataService worldpayMerchantConfigDataService; private AssistedServiceService assistedServiceService; + private WorldpayMerchantConfigurationService worldpayMerchantConfigurationService; + + public DefaultWorldpayMerchantStrategy(final AssistedServiceService assistedServiceService, + final WorldpayMerchantConfigurationService worldpayMerchantConfigurationService) { + this.assistedServiceService = assistedServiceService; + this.worldpayMerchantConfigurationService = worldpayMerchantConfigurationService; + } @Override - public WorldpayMerchantConfigData getMerchant() { - final Map merchantConfiguration = worldpayMerchantConfigDataService.getMerchantConfiguration(); + public WorldpayMerchantConfigurationModel getMerchant() { if (isASMEnabled()) { - return merchantConfiguration.get(ASM_MERCHANT); + return worldpayMerchantConfigurationService.getCurrentAsmConfiguration(); } else { - return merchantConfiguration.get(WEB); + return worldpayMerchantConfigurationService.getCurrentWebConfiguration(); } } - @Override - public WorldpayMerchantConfigData getReplenishmentMerchant() { - return worldpayMerchantConfigDataService.getMerchantConfiguration().get(REPLENISHMENT_MERCHANT); - } - protected boolean isASMEnabled() { return assistedServiceService.getAsmSession() != null && assistedServiceService.getAsmSession().getAgent() != null; } - - @Required - public void setWorldpayMerchantConfigDataService(final WorldpayMerchantConfigDataService worldpayMerchantConfigDataService) { - this.worldpayMerchantConfigDataService = worldpayMerchantConfigDataService; - } - - @Required - public void setAssistedServiceService(final AssistedServiceService assistedServiceService) { - this.assistedServiceService = assistedServiceService; - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/support/appender/impl/WorldpayMerchantConfigurationAppender.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/support/appender/impl/WorldpayMerchantConfigurationAppender.java index 63f7b63d..023fe885 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/support/appender/impl/WorldpayMerchantConfigurationAppender.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/support/appender/impl/WorldpayMerchantConfigurationAppender.java @@ -1,12 +1,11 @@ package com.worldpay.support.appender.impl; -import com.worldpay.config.merchant.WorldpayMerchantConfigData; +import com.worldpay.merchant.configuration.services.WorldpayMerchantConfigurationService; +import com.worldpay.model.WorldpayMerchantConfigurationModel; import com.worldpay.support.appender.WorldpaySupportEmailAppender; -import de.hybris.platform.core.Registry; -import org.springframework.beans.factory.BeanFactoryUtils; -import java.util.List; -import java.util.Map; +import java.util.Collection; +import java.util.Set; import static org.apache.commons.lang.StringUtils.join; @@ -15,6 +14,12 @@ */ public class WorldpayMerchantConfigurationAppender extends WorldpaySupportEmailAppender { + protected final WorldpayMerchantConfigurationService worldpayMerchantConfigurationService; + + public WorldpayMerchantConfigurationAppender(final WorldpayMerchantConfigurationService worldpayMerchantConfigurationService) { + this.worldpayMerchantConfigurationService = worldpayMerchantConfigurationService; + } + /** * {@inheritDoc} */ @@ -22,21 +27,21 @@ public class WorldpayMerchantConfigurationAppender extends WorldpaySupportEmailA public String appendContent() { final StringBuilder merchantConfiguration = new StringBuilder(); merchantConfiguration.append(System.lineSeparator()).append("Merchant Configuration:").append(System.lineSeparator()); - final Map merchantConfigurations = getConfiguredMerchants(); - for (Map.Entry configuredMerchant : merchantConfigurations.entrySet()) { - merchantConfiguration.append(ONE_TAB).append("Configured Merchant Bean Name: ").append(configuredMerchant.getKey()).append(System.lineSeparator()); - merchantConfiguration.append(TWO_TABS).append("Merchant Code: ").append(configuredMerchant.getValue().getCode()).append(System.lineSeparator()); - merchantConfiguration.append(TWO_TABS).append("Merchant InstallationId: ").append(configuredMerchant.getValue().getInstallationId()).append(System.lineSeparator()); - merchantConfiguration.append(TWO_TABS).append("Mac Validation: ").append(configuredMerchant.getValue().getMacValidation()).append(System.lineSeparator()); + final Set allSystemActiveSiteMerchantConfigurations = worldpayMerchantConfigurationService.getAllSystemActiveSiteMerchantConfigurations(); + for (WorldpayMerchantConfigurationModel configuredMerchant : allSystemActiveSiteMerchantConfigurations) { + merchantConfiguration.append(ONE_TAB).append("Configured Merchant Id: ").append(configuredMerchant.getIdentifier()).append(System.lineSeparator()); + merchantConfiguration.append(TWO_TABS).append("Merchant Code: ").append(configuredMerchant.getCode()).append(System.lineSeparator()); + merchantConfiguration.append(TWO_TABS).append("Merchant InstallationId: ").append(configuredMerchant.getInstallationId()).append(System.lineSeparator()); + merchantConfiguration.append(TWO_TABS).append("Mac Validation: ").append(configuredMerchant.getMacValidation()).append(System.lineSeparator()); merchantConfiguration.append(TWO_TABS).append("Included payment methods: "); - final List includedPaymentTypes = configuredMerchant.getValue().getIncludedPaymentTypes(); + final Collection includedPaymentTypes = configuredMerchant.getIncludedPaymentTypes(); if (includedPaymentTypes != null) { merchantConfiguration.append(join(includedPaymentTypes, ",")); } else { merchantConfiguration.append("None"); } merchantConfiguration.append(System.lineSeparator()).append(TWO_TABS).append("Excluded payment methods: "); - final List excludedPaymentTypes = configuredMerchant.getValue().getExcludedPaymentTypes(); + final Collection excludedPaymentTypes = configuredMerchant.getExcludedPaymentTypes(); if (excludedPaymentTypes != null) { merchantConfiguration.append(join(excludedPaymentTypes, ",")).append(System.lineSeparator()); } else { @@ -45,8 +50,4 @@ public String appendContent() { } return merchantConfiguration.toString(); } - - protected Map getConfiguredMerchants() { - return BeanFactoryUtils.beansOfTypeIncludingAncestors(Registry.getApplicationContext(), WorldpayMerchantConfigData.class); - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/support/appender/impl/WorldpayPaymentTransactionTypesAppender.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/support/appender/impl/WorldpayPaymentTransactionTypesAppender.java index 602f8568..b58c4385 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/support/appender/impl/WorldpayPaymentTransactionTypesAppender.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/support/appender/impl/WorldpayPaymentTransactionTypesAppender.java @@ -4,7 +4,8 @@ import com.worldpay.support.appender.WorldpaySupportEmailAppender; import de.hybris.platform.core.Registry; import de.hybris.platform.payment.enums.PaymentTransactionType; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import java.util.Set; @@ -14,7 +15,7 @@ */ public class WorldpayPaymentTransactionTypesAppender extends WorldpaySupportEmailAppender { - private static final Logger LOG = Logger.getLogger(WorldpayPaymentTransactionTypesAppender.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayPaymentTransactionTypesAppender.class); /** * {@inheritDoc} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/WorldpayPaymentTransactionService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/WorldpayPaymentTransactionService.java index 03ec9ae7..3442faf7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/WorldpayPaymentTransactionService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/WorldpayPaymentTransactionService.java @@ -1,7 +1,7 @@ package com.worldpay.transaction; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.PaymentReply; +import com.worldpay.data.Amount; +import com.worldpay.data.PaymentReply; import com.worldpay.service.notification.OrderNotificationMessage; import de.hybris.platform.commerceservices.service.data.CommerceCheckoutParameter; import de.hybris.platform.core.model.order.AbstractOrderModel; @@ -27,7 +27,7 @@ public interface WorldpayPaymentTransactionService { * @param paymentTransactionType The payment paymentTransaction type to check {@link PaymentTransactionType} * @return true when all paymentTransactions are accepted for the type {@param paymentTransactionType} */ - boolean areAllPaymentTransactionsAcceptedForType(final OrderModel order, final PaymentTransactionType paymentTransactionType); + boolean areAllPaymentTransactionsAcceptedForType(OrderModel order, PaymentTransactionType paymentTransactionType); /** * Checks if the order contains a paymentTransaction with the flag apmOpen true, which means the asynchronous @@ -36,7 +36,7 @@ public interface WorldpayPaymentTransactionService { * @param order he current order {@link OrderModel} * @return true when there are transactions with the apmOpen flag, false otherwise. */ - boolean isAnyPaymentTransactionApmOpenForOrder(final OrderModel order); + boolean isAnyPaymentTransactionApmOpenForOrder(OrderModel order); /** * Checks if any of the PaymentTransactionEntries {@link PaymentTransactionEntryModel} in the {@param paymentTransaction} has the pending flag. @@ -45,7 +45,7 @@ public interface WorldpayPaymentTransactionService { * @param paymentTransactionType The payment paymentTransaction type to check {@link PaymentTransactionType} * @return true if any of the entries is pending. False otherwise. */ - boolean isPaymentTransactionPending(final PaymentTransactionModel paymentTransaction, final PaymentTransactionType paymentTransactionType); + boolean isPaymentTransactionPending(PaymentTransactionModel paymentTransaction, PaymentTransactionType paymentTransactionType); /** * Returns a list with the PaymentTransactionEntries {@link PaymentTransactionEntryModel} of the type {@param paymentTransactionType} {@link PaymentTransactionType} @@ -55,7 +55,7 @@ public interface WorldpayPaymentTransactionService { * @return an empty list if no PaymentTransactionEntries {@link PaymentTransactionEntryModel} of the * type {@param paymentTransactionType} are found, a list of entries of the type {@param paymentTransactionType} otherwise. */ - List filterPaymentTransactionEntriesOfType(final PaymentTransactionModel paymentTransaction, final PaymentTransactionType paymentTransactionType); + List filterPaymentTransactionEntriesOfType(PaymentTransactionModel paymentTransaction, PaymentTransactionType paymentTransactionType); /** * Returns a list with the PaymentTransactionEntries {@link PaymentTransactionEntryModel} of the type {@param paymentTransactionType} {@link PaymentTransactionType} in pending status @@ -65,7 +65,7 @@ public interface WorldpayPaymentTransactionService { * @return an empty list if no PaymentTransactionEntries {@link PaymentTransactionEntryModel} in pending status of the * type {@param paymentTransactionType} are found, a list of entries of the type {@param paymentTransactionType} in pending status otherwise. */ - List getPendingPaymentTransactionEntriesForType(final PaymentTransactionModel paymentTransactionModel, final PaymentTransactionType paymentTransactionType); + List getPendingPaymentTransactionEntriesForType(PaymentTransactionModel paymentTransactionModel, PaymentTransactionType paymentTransactionType); /** @@ -87,7 +87,7 @@ public interface WorldpayPaymentTransactionService { * @return true if the dependant paymentTransaction type is completed, false otherwise. * If the current paymentTransaction of the type {@param paymentTransactionType} has no dependencies, returns true */ - boolean isPreviousTransactionCompleted(final String worldpayOrderCode, final PaymentTransactionType paymentTransactionType, final OrderModel orderModel); + boolean isPreviousTransactionCompleted(String worldpayOrderCode, PaymentTransactionType paymentTransactionType, OrderModel orderModel); /** * Creates a new PaymentTransactionEntry of the type {@link PaymentTransactionType#CAPTURE} @@ -97,7 +97,7 @@ public interface WorldpayPaymentTransactionService { * @param orderNotificationMessage The {@link OrderNotificationMessage} to get the information from * @return the new {@link PaymentTransactionType#CAPTURE} PaymentTransactionEntry created */ - PaymentTransactionEntryModel createCapturedPaymentTransactionEntry(final PaymentTransactionModel paymentTransaction, final OrderNotificationMessage orderNotificationMessage); + PaymentTransactionEntryModel createCapturedPaymentTransactionEntry(PaymentTransactionModel paymentTransaction, OrderNotificationMessage orderNotificationMessage); /** * Creates a new PaymentTransactionEntry of the type {@link PaymentTransactionType#REFUND_FOLLOW_ON} @@ -107,7 +107,7 @@ public interface WorldpayPaymentTransactionService { * @param orderNotificationMessage The {@link OrderNotificationMessage} to get the information from * @return the new {@link PaymentTransactionType#REFUND_FOLLOW_ON} PaymentTransactionEntry created */ - PaymentTransactionEntryModel createRefundedPaymentTransactionEntry(final PaymentTransactionModel paymentTransaction, final OrderNotificationMessage orderNotificationMessage); + PaymentTransactionEntryModel createRefundedPaymentTransactionEntry(PaymentTransactionModel paymentTransaction, OrderNotificationMessage orderNotificationMessage); /** * Creates a new PaymentTransactionEntry {@link PaymentTransactionEntryModel} of the type {@link PaymentTransactionType#AUTHORIZATION} @@ -119,8 +119,8 @@ public interface WorldpayPaymentTransactionService { * @param authorisedAmount The authorisedAmount * @return the new {@link PaymentTransactionType#AUTHORIZATION} PaymentTransactionEntry created */ - PaymentTransactionEntryModel createPendingAuthorisePaymentTransactionEntry(final PaymentTransactionModel paymentTransaction, final String merchantCode, - final CartModel cartModel, final BigDecimal authorisedAmount); + PaymentTransactionEntryModel createPendingAuthorisePaymentTransactionEntry(PaymentTransactionModel paymentTransaction, String merchantCode, + CartModel cartModel, BigDecimal authorisedAmount); /** * Creates a new PaymentTransactionEntry {@link PaymentTransactionEntryModel} of the type {@link PaymentTransactionType#AUTHORIZATION} @@ -132,8 +132,8 @@ PaymentTransactionEntryModel createPendingAuthorisePaymentTransactionEntry(final * @param authorisedAmount The authorisedAmount * @return the new {@link PaymentTransactionType#AUTHORIZATION} PaymentTransactionEntry created */ - PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(final PaymentTransactionModel paymentTransaction, final String merchantCode, - final AbstractOrderModel abstractOrderModel, final BigDecimal authorisedAmount); + PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(PaymentTransactionModel paymentTransaction, String merchantCode, + AbstractOrderModel abstractOrderModel, BigDecimal authorisedAmount); /** * Creates a new PaymentTransactionEntry {@link PaymentTransactionEntryModel} of the type {@link PaymentTransactionType#AUTHORIZATION} @@ -143,7 +143,7 @@ PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(fi * @param orderNotificationMessage The {@link OrderNotificationMessage} to get the information from * @return the new {@link PaymentTransactionType#SETTLED} PaymentTransactionEntry created */ - PaymentTransactionEntryModel createNotPendingSettledPaymentTransactionEntry(final PaymentTransactionModel paymentTransactionModel, final OrderNotificationMessage orderNotificationMessage); + PaymentTransactionEntryModel createNotPendingSettledPaymentTransactionEntry(PaymentTransactionModel paymentTransactionModel, OrderNotificationMessage orderNotificationMessage); /** * Creates a new paymentTransaction in the cart once the authorization result has been received, after the HOP. @@ -153,7 +153,7 @@ PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(fi * @param commerceCheckoutParameter * @return the created {@link PaymentTransactionModel} */ - PaymentTransactionModel createPaymentTransaction(final boolean apmOpen, final String merchantCode, final CommerceCheckoutParameter commerceCheckoutParameter); + PaymentTransactionModel createPaymentTransaction(boolean apmOpen, String merchantCode, CommerceCheckoutParameter commerceCheckoutParameter); /** * Returns the PaymentTransactionModel {@link PaymentTransactionModel} corresponding to the {@param worldpayOrderCode} @@ -161,7 +161,7 @@ PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(fi * @param worldpayOrderCode The worldpayOrderCode to look for associated to a PaymentTransactionModel * @return The PaymentTransactionModel associated to the worldpayOrderCode if found, null otherwise */ - PaymentTransactionModel getPaymentTransactionFromCode(final String worldpayOrderCode); + PaymentTransactionModel getPaymentTransactionFromCode(String worldpayOrderCode); /** * Updates each one of the {@param paymentTransactionEntries} to the status {@param transactionStatus} @@ -169,7 +169,7 @@ PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(fi * @param paymentTransactionEntries * @param transactionStatus */ - void updateEntriesStatus(final List paymentTransactionEntries, final String transactionStatus); + void updateEntriesStatus(List paymentTransactionEntries, String transactionStatus); /** * Set the riskscore on a paymentTransactionEntryModel @@ -177,7 +177,7 @@ PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(fi * @param paymentTransactionModel * @param paymentReply */ - void addRiskScore(final PaymentTransactionModel paymentTransactionModel, final PaymentReply paymentReply); + void addRiskScore(PaymentTransactionModel paymentTransactionModel, PaymentReply paymentReply); /** * Set the aav fields on a paymentTransactionEntryModel @@ -185,7 +185,7 @@ PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(fi * @param paymentTransactionEntryModel * @param paymentReply */ - void addAavFields(final PaymentTransactionEntryModel paymentTransactionEntryModel, final PaymentReply paymentReply); + void addAavFields(PaymentTransactionEntryModel paymentTransactionEntryModel, PaymentReply paymentReply); /** * Updates the amount received from the OrderNotificationMessage @@ -193,7 +193,7 @@ PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(fi * @param transactionEntries transactionEntries to change the amount to. * @param amount amount to set in the transactionEntries */ - void updateEntriesAmount(final List transactionEntries, final Amount amount); + void updateEntriesAmount(List transactionEntries, Amount amount); /** * Matching order total against sum of amounts from PaymentTransactionEntries with @@ -211,5 +211,7 @@ PaymentTransactionEntryModel createNonPendingAuthorisePaymentTransactionEntry(fi * @param paymentTransactionModel The {@link PaymentTransactionModel} to associate the paymentTransactionEntry to * @return the new {@link PaymentTransactionType#SETTLED} PaymentTransactionEntry created */ - PaymentTransactionEntryModel createNotPendingCancelOrderTransactionEntry(final PaymentTransactionModel paymentTransactionModel); + PaymentTransactionEntryModel createNotPendingCancelOrderTransactionEntry(PaymentTransactionModel paymentTransactionModel); + + void addFraudSightToPaymentTransaction(PaymentTransactionModel paymentTransaction, PaymentReply paymentReply); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/WorldpayPaymentTransactionUtils.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/WorldpayPaymentTransactionUtils.java new file mode 100644 index 00000000..d135d9e0 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/WorldpayPaymentTransactionUtils.java @@ -0,0 +1,53 @@ +package com.worldpay.transaction; + +import com.worldpay.data.Amount; +import de.hybris.platform.core.model.c2l.CurrencyModel; +import de.hybris.platform.payment.enums.PaymentTransactionType; +import de.hybris.platform.payment.model.PaymentTransactionModel; + +import java.math.BigDecimal; +import java.util.Map; + +/** + * Util class for Payment transaction + */ +public interface WorldpayPaymentTransactionUtils { + + /** + * Generates payment transaction code + * + * @param paymentTransaction the payment transaction + * @return the code generated + */ + String generatePaymentTransactionCode(PaymentTransactionModel paymentTransaction); + + /** + * Gets the payment transaction dependency map from spring + * + * @return the spring map + */ + Map getPaymentTransactionDependency(); + + /** + * Gets the currency model object from the Amount + * + * @param amount the amount + * @return the {@link CurrencyModel} + */ + CurrencyModel getCurrencyFromAmount(Amount amount); + + /** + * Converts the amount to a BigDecimal object + * + * @param amount the amount to convert + * @return the big decimal value + */ + BigDecimal convertAmount(Amount amount); + + /** + * Gets the authorised amount tolerance from the configuration + * + * @return returns the configuration value + */ + double getAuthoriseAmountToleranceFromConfig(); +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionService.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionService.java index df24286c..d9ab2305 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionService.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionService.java @@ -5,13 +5,13 @@ import com.worldpay.model.WorldpayAavResponseModel; import com.worldpay.model.WorldpayBankConfigurationModel; import com.worldpay.model.WorldpayRiskScoreModel; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.RiskScore; +import com.worldpay.data.Amount; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.RiskScore; import com.worldpay.service.notification.OrderNotificationMessage; -import com.worldpay.service.payment.WorldpayOrderService; -import com.worldpay.transaction.EntryCodeStrategy; +import com.worldpay.service.payment.WorldpayFraudSightStrategy; import com.worldpay.transaction.WorldpayPaymentTransactionService; +import com.worldpay.transaction.WorldpayPaymentTransactionUtils; import de.hybris.platform.commerceservices.service.data.CommerceCheckoutParameter; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.model.order.AbstractOrderModel; @@ -22,16 +22,18 @@ import de.hybris.platform.payment.enums.PaymentTransactionType; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; -import de.hybris.platform.servicelayer.config.ConfigurationService; import de.hybris.platform.servicelayer.dto.converter.Converter; import de.hybris.platform.servicelayer.exceptions.ModelNotFoundException; -import de.hybris.platform.servicelayer.i18n.CommonI18NService; import de.hybris.platform.servicelayer.model.ModelService; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.time.Instant; -import java.util.*; +import java.util.Date; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import java.util.stream.Collectors; import static de.hybris.platform.payment.dto.TransactionStatus.ACCEPTED; @@ -47,39 +49,30 @@ @SuppressWarnings("java:S107") public class DefaultWorldpayPaymentTransactionService implements WorldpayPaymentTransactionService { - private static final Logger LOG = Logger.getLogger(DefaultWorldpayPaymentTransactionService.class); + private static final Logger LOG = LoggerFactory.getLogger(DefaultWorldpayPaymentTransactionService.class); protected final ModelService modelService; - protected final ConfigurationService configurationService; - protected final CommonI18NService commonI18NService; - protected final EntryCodeStrategy entryCodeStrategy; - protected final Map paymentTransactionDependency; protected final WorldpayPaymentTransactionDao worldpayPaymentTransactionDao; protected final Converter worldpayRiskScoreConverter; protected final Populator worldpayAavResponsePopulator; - protected final WorldpayOrderService worldpayOrderService; protected final WorldpayBankConfigurationLookupService worldpayBankConfigurationService; + protected final WorldpayPaymentTransactionUtils worldpayPaymentTransactionUtils; + protected final WorldpayFraudSightStrategy worldpayFraudSightStrategy; public DefaultWorldpayPaymentTransactionService(final ModelService modelService, - final ConfigurationService configurationService, - final CommonI18NService commonI18NService, - final EntryCodeStrategy entryCodeStrategy, - final Map paymentTransactionDependency, final WorldpayPaymentTransactionDao worldpayPaymentTransactionDao, final Converter worldpayRiskScoreConverter, final Populator worldpayAavResponsePopulator, - final WorldpayOrderService worldpayOrderService, - final WorldpayBankConfigurationLookupService worldpayBankConfigurationService) { + final WorldpayBankConfigurationLookupService worldpayBankConfigurationService, + final WorldpayPaymentTransactionUtils worldpayPaymentTransactionUtils, + final WorldpayFraudSightStrategy worldpayFraudSightStrategy) { this.modelService = modelService; - this.configurationService = configurationService; - this.commonI18NService = commonI18NService; - this.entryCodeStrategy = entryCodeStrategy; - this.paymentTransactionDependency = paymentTransactionDependency; this.worldpayPaymentTransactionDao = worldpayPaymentTransactionDao; this.worldpayRiskScoreConverter = worldpayRiskScoreConverter; this.worldpayAavResponsePopulator = worldpayAavResponsePopulator; - this.worldpayOrderService = worldpayOrderService; this.worldpayBankConfigurationService = worldpayBankConfigurationService; + this.worldpayPaymentTransactionUtils = worldpayPaymentTransactionUtils; + this.worldpayFraudSightStrategy = worldpayFraudSightStrategy; } /** @@ -107,8 +100,8 @@ public boolean areAllPaymentTransactionsAcceptedForType(final OrderModel order, @Override public boolean isAnyPaymentTransactionApmOpenForOrder(final OrderModel order) { return order.getPaymentTransactions().stream() - .filter(Objects::nonNull) - .anyMatch(PaymentTransactionModel::getApmOpen); + .filter(Objects::nonNull) + .anyMatch(PaymentTransactionModel::getApmOpen); } /** @@ -117,8 +110,8 @@ public boolean isAnyPaymentTransactionApmOpenForOrder(final OrderModel order) { @Override public boolean isPaymentTransactionPending(final PaymentTransactionModel paymentTransaction, final PaymentTransactionType paymentTransactionType) { return paymentTransaction.getEntries().stream() - .filter(paymentTransactionEntry -> paymentTransactionType.equals(paymentTransactionEntry.getType())) - .anyMatch(PaymentTransactionEntryModel::getPending); + .filter(paymentTransactionEntry -> paymentTransactionType.equals(paymentTransactionEntry.getType())) + .anyMatch(PaymentTransactionEntryModel::getPending); } /** @@ -128,8 +121,8 @@ public boolean isPaymentTransactionPending(final PaymentTransactionModel payment public List filterPaymentTransactionEntriesOfType(final PaymentTransactionModel paymentTransaction, final PaymentTransactionType paymentTransactionType) { return paymentTransaction.getEntries().stream() - .filter(entry -> entry.getType().equals(paymentTransactionType)) - .collect(Collectors.toList()); + .filter(entry -> entry.getType().equals(paymentTransactionType)) + .collect(Collectors.toList()); } /** @@ -139,8 +132,8 @@ public List filterPaymentTransactionEntriesOfType( public List getPendingPaymentTransactionEntriesForType(final PaymentTransactionModel paymentTransactionModel, final PaymentTransactionType paymentTransactionType) { return filterPaymentTransactionEntriesOfType(paymentTransactionModel, paymentTransactionType).stream() - .filter(PaymentTransactionEntryModel::getPending) - .collect(Collectors.toList()); + .filter(PaymentTransactionEntryModel::getPending) + .collect(Collectors.toList()); } /** @@ -150,8 +143,8 @@ public List getPendingPaymentTransactionEntriesFor public List getNotPendingPaymentTransactionEntriesForType(final PaymentTransactionModel paymentTransactionModel, final PaymentTransactionType paymentTransactionType) { return filterPaymentTransactionEntriesOfType(paymentTransactionModel, paymentTransactionType).stream() - .filter(entry -> !entry.getPending()) - .collect(Collectors.toList()); + .filter(entry -> !entry.getPending()) + .collect(Collectors.toList()); } /** @@ -159,14 +152,15 @@ public List getNotPendingPaymentTransactionEntries */ @Override public boolean isPreviousTransactionCompleted(final String worldpayOrderCode, final PaymentTransactionType paymentTransactionType, final OrderModel orderModel) { - final PaymentTransactionType dependingTransactionType = paymentTransactionDependency.get(paymentTransactionType); + final PaymentTransactionType dependingTransactionType = worldpayPaymentTransactionUtils.getPaymentTransactionDependency().get(paymentTransactionType); if (dependingTransactionType == null) { return true; } boolean completed = false; for (final PaymentTransactionModel paymentTransactionModel : orderModel.getPaymentTransactions()) { if (paymentTransactionModel.getRequestId().equals(worldpayOrderCode)) { - completed = !getNotPendingPaymentTransactionEntriesForType(paymentTransactionModel, dependingTransactionType).isEmpty(); + completed = !getNotPendingPaymentTransactionEntriesForType(paymentTransactionModel, dependingTransactionType).isEmpty() + || isRefundForVoidOrder(paymentTransactionType, paymentTransactionModel); } } return completed; @@ -272,7 +266,7 @@ public void updateEntriesStatus(final List payment for (final PaymentTransactionEntryModel entry : paymentTransactionEntries) { entry.setTransactionStatus(transactionStatus); entry.setPending(Boolean.FALSE); - LOG.debug(format("Setting pending flag of PaymentTransactionEntry with code [{0}] to false", entry.getCode())); + LOG.debug("Setting pending flag of PaymentTransactionEntry with code [{}] to false", entry.getCode()); } modelService.saveAll(paymentTransactionEntries); } @@ -283,12 +277,12 @@ public void updateEntriesStatus(final List payment @Override public void addRiskScore(final PaymentTransactionModel paymentTransactionModel, final PaymentReply paymentReply) { Optional.ofNullable(paymentReply.getRiskScore()) - .map(worldpayRiskScoreConverter::convert) - .map(riskScore -> { - paymentTransactionModel.setRiskScore(riskScore); - return paymentTransactionModel; - }) - .ifPresent(modelService::save); + .map(worldpayRiskScoreConverter::convert) + .map(riskScore -> { + paymentTransactionModel.setRiskScore(riskScore); + return paymentTransactionModel; + }) + .ifPresent(modelService::save); } /** @@ -309,10 +303,10 @@ public void addAavFields(final PaymentTransactionEntryModel paymentTransactionEn @Override public void updateEntriesAmount(final List transactionEntries, final Amount amount) { for (final PaymentTransactionEntryModel entry : transactionEntries) { - final BigDecimal amountValue = worldpayOrderService.convertAmount(amount); + final BigDecimal amountValue = worldpayPaymentTransactionUtils.convertAmount(amount); checkAmountChanges(entry, amountValue); entry.setAmount(amountValue); - entry.setCurrency(commonI18NService.getCurrency(amount.getCurrencyCode())); + entry.setCurrency(worldpayPaymentTransactionUtils.getCurrencyFromAmount(amount)); LOG.debug("Updating amount received value"); } modelService.saveAll(transactionEntries); @@ -337,7 +331,7 @@ public boolean isAuthorisedAmountCorrect(final OrderModel order) { } } - final double tolerance = configurationService.getConfiguration().getDouble("worldpayapi.authoriseamount.validation.tolerance"); + final double tolerance = worldpayPaymentTransactionUtils.getAuthoriseAmountToleranceFromConfig(); return Math.abs(order.getTotalPrice() - authorisedAmount.doubleValue()) <= tolerance; } @@ -350,7 +344,7 @@ public PaymentTransactionEntryModel createNotPendingCancelOrderTransactionEntry( final PaymentTransactionEntryModel paymentTransactionEntryModel = modelService.create(PaymentTransactionEntryModel.class); final AbstractOrderModel orderModel = paymentTransactionModel.getOrder(); - paymentTransactionEntryModel.setCode(entryCodeStrategy.generateCode(paymentTransactionModel)); + paymentTransactionEntryModel.setCode(worldpayPaymentTransactionUtils.generatePaymentTransactionCode(paymentTransactionModel)); paymentTransactionEntryModel.setType(CANCEL); paymentTransactionEntryModel.setPaymentTransaction(paymentTransactionModel); paymentTransactionEntryModel.setTime(Date.from(Instant.now())); @@ -366,6 +360,16 @@ public PaymentTransactionEntryModel createNotPendingCancelOrderTransactionEntry( return paymentTransactionEntryModel; } + /** + * {@inheritDoc} + */ + @Override + public void addFraudSightToPaymentTransaction(final PaymentTransactionModel paymentTransaction, final PaymentReply paymentReply) { + if (worldpayFraudSightStrategy.isFraudSightEnabled()) { + worldpayFraudSightStrategy.addFraudSight(paymentTransaction, paymentReply); + } + } + /** * {@inheritDoc} */ @@ -384,15 +388,15 @@ protected PaymentTransactionEntryModel setCommonFieldsForPaymentTransactionEntri transactionEntryModel.setRequestToken(orderNotificationMessage.getMerchantCode()); transactionEntryModel.setTransactionStatus(ACCEPTED.name()); transactionEntryModel.setTransactionStatusDetails(SUCCESFULL.name()); - transactionEntryModel.setCode(entryCodeStrategy.generateCode(paymentTransactionModel)); + transactionEntryModel.setCode(worldpayPaymentTransactionUtils.generatePaymentTransactionCode(paymentTransactionModel)); transactionEntryModel.setTime(Date.from(Instant.now())); transactionEntryModel.setPending(Boolean.FALSE); final Amount amount = orderNotificationMessage.getPaymentReply().getAmount(); - final BigDecimal amountValue = worldpayOrderService.convertAmount(amount); + final BigDecimal amountValue = worldpayPaymentTransactionUtils.convertAmount(amount); transactionEntryModel.setAmount(amountValue); - transactionEntryModel.setCurrency(commonI18NService.getCurrency(amount.getCurrencyCode())); + transactionEntryModel.setCurrency(worldpayPaymentTransactionUtils.getCurrencyFromAmount(amount)); modelService.save(transactionEntryModel); return transactionEntryModel; @@ -405,7 +409,7 @@ private void checkAmountChanges(final PaymentTransactionEntryModel entry, final } protected void logAmountChanged(final PaymentTransactionEntryModel entry, final BigDecimal amountValue) { - LOG.warn(format("The amount for the transaction entry [{0}] has changed from [{1}] to [{2}] during [{3}]", entry.getCode(), entry.getAmount(), amountValue, entry.getType())); + LOG.warn("The amount for the transaction entry [{}] has changed from [{}] to [{}] during [{}]", entry.getCode(), entry.getAmount(), amountValue, entry.getType()); } private PaymentTransactionEntryModel createAuthorizationPaymentTransactionEntryModel(final PaymentTransactionModel paymentTransaction, @@ -418,7 +422,7 @@ private PaymentTransactionEntryModel createAuthorizationPaymentTransactionEntryM transactionEntryModel.setPaymentTransaction(paymentTransaction); transactionEntryModel.setRequestId(abstractOrderModel.getWorldpayOrderCode()); transactionEntryModel.setRequestToken(merchantCode); - transactionEntryModel.setCode(entryCodeStrategy.generateCode(paymentTransaction)); + transactionEntryModel.setCode(worldpayPaymentTransactionUtils.generatePaymentTransactionCode(paymentTransaction)); transactionEntryModel.setTime(Date.from(Instant.now())); transactionEntryModel.setTransactionStatus(ACCEPTED.name()); transactionEntryModel.setTransactionStatusDetails(SUCCESFULL.name()); @@ -426,4 +430,9 @@ private PaymentTransactionEntryModel createAuthorizationPaymentTransactionEntryM transactionEntryModel.setCurrency(abstractOrderModel.getCurrency()); return transactionEntryModel; } + + private boolean isRefundForVoidOrder(final PaymentTransactionType paymentTransactionType, final PaymentTransactionModel paymentTransactionModel) { + final List pendingCancelPaymentTransactionEntries = getPendingPaymentTransactionEntriesForType(paymentTransactionModel, CANCEL); + return REFUND_FOLLOW_ON.equals(paymentTransactionType) && !pendingCancelPaymentTransactionEntries.isEmpty(); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionUtils.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionUtils.java new file mode 100644 index 00000000..eb87d020 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionUtils.java @@ -0,0 +1,76 @@ +package com.worldpay.transaction.impl; + +import com.worldpay.data.Amount; +import com.worldpay.service.payment.WorldpayOrderService; +import com.worldpay.transaction.EntryCodeStrategy; +import com.worldpay.transaction.WorldpayPaymentTransactionUtils; +import de.hybris.platform.core.model.c2l.CurrencyModel; +import de.hybris.platform.payment.enums.PaymentTransactionType; +import de.hybris.platform.payment.model.PaymentTransactionModel; +import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.i18n.CommonI18NService; + +import java.math.BigDecimal; +import java.util.Map; + +public class DefaultWorldpayPaymentTransactionUtils implements WorldpayPaymentTransactionUtils { + + protected final EntryCodeStrategy entryCodeStrategy; + protected final CommonI18NService commonI18NService; + protected final Map paymentTransactionDependency; + protected final WorldpayOrderService worldpayOrderService; + protected final ConfigurationService configurationService; + + public DefaultWorldpayPaymentTransactionUtils(final EntryCodeStrategy entryCodeStrategy, + final CommonI18NService commonI18NService, + final Map paymentTransactionDependency, + final WorldpayOrderService worldpayOrderService, + final ConfigurationService configurationService) { + this.entryCodeStrategy = entryCodeStrategy; + this.commonI18NService = commonI18NService; + this.paymentTransactionDependency = paymentTransactionDependency; + this.worldpayOrderService = worldpayOrderService; + this.configurationService = configurationService; + } + + /** + * {@inheritDoc} + */ + @Override + public String generatePaymentTransactionCode(final PaymentTransactionModel paymentTransaction) { + return entryCodeStrategy.generateCode(paymentTransaction); + } + + /** + * {@inheritDoc} + */ + @Override + public Map getPaymentTransactionDependency() { + return paymentTransactionDependency; + } + + /** + * {@inheritDoc} + */ + @Override + public CurrencyModel getCurrencyFromAmount(final Amount amount) { + return commonI18NService.getCurrency(amount.getCurrencyCode()); + } + + /** + * {@inheritDoc} + */ + @Override + public BigDecimal convertAmount(final Amount amount) { + return worldpayOrderService.convertAmount(amount); + } + + /** + * {@inheritDoc} + */ + @Override + public double getAuthoriseAmountToleranceFromConfig() { + return configurationService.getConfiguration().getDouble("worldpayapi.authoriseamount.validation.tolerance"); + } + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayConstants.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayConstants.java index 26208ef1..ca0ec074 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayConstants.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayConstants.java @@ -1,6 +1,7 @@ package com.worldpay.util; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; @@ -10,7 +11,7 @@ */ public class WorldpayConstants { - private static final Logger LOG = Logger.getLogger(WorldpayConstants.class); + private static final Logger LOG = LoggerFactory.getLogger(WorldpayConstants.class); private WorldpayConstants() { } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayInternalModelTransformerUtil.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayInternalModelTransformerUtil.java new file mode 100644 index 00000000..7c874744 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayInternalModelTransformerUtil.java @@ -0,0 +1,92 @@ +package com.worldpay.util; + +import com.worldpay.data.Date; +import com.worldpay.data.PaymentDetails; +import com.worldpay.data.klarna.KlarnaMerchantUrls; +import com.worldpay.data.klarna.KlarnaPayment; +import com.worldpay.data.klarna.KlarnaRedirectURLs; +import com.worldpay.data.payment.AlternativePayment; +import com.worldpay.data.payment.AlternativeShopperBankCodePayment; +import com.worldpay.service.model.payment.PaymentType; +import com.worldpay.service.request.AuthoriseRequestParameters; + +import java.time.LocalDateTime; + +import static com.worldpay.service.model.payment.PaymentType.KLARNASSL; + +public class WorldpayInternalModelTransformerUtil { + + private WorldpayInternalModelTransformerUtil() { + } + + public static Date newDateFromLocalDateTime(final LocalDateTime localDateTime) { + final Date date = new Date(); + date.setDayOfMonth(String.valueOf(localDateTime.getDayOfMonth())); + date.setMonth(String.valueOf(localDateTime.getMonth().getValue())); + date.setYear(String.valueOf(localDateTime.getYear())); + date.setHour(String.valueOf(localDateTime.getHour())); + date.setMinute(String.valueOf(localDateTime.getMinute())); + date.setSecond(String.valueOf(localDateTime.getSecond())); + + return date; + } + + public static AlternativePayment createAlternativePayment(final PaymentType paymentType, final String successURL, final String failureURL, final String cancelURL, final String pendingUrl, final String shopperCountryCode) { + return setAlternativePaymentData(paymentType, successURL, failureURL, cancelURL, pendingUrl, new AlternativePayment(), shopperCountryCode); + } + + public static AlternativeShopperBankCodePayment createAlternativeShopperBankCodePayment(final PaymentType paymentType, final String shopperBankCode, final String successURL, final String failureURL, final String cancelURL, final String pendingUrl, final String shopperCountryCode) { + final AlternativeShopperBankCodePayment alternativeShopperBankCodePayment = new AlternativeShopperBankCodePayment(); + setAlternativePaymentData(paymentType, successURL, failureURL, cancelURL, pendingUrl, alternativeShopperBankCodePayment, shopperCountryCode); + alternativeShopperBankCodePayment.setShopperBankCode(shopperBankCode); + + return alternativeShopperBankCodePayment; + } + + private static AlternativePayment setAlternativePaymentData(final PaymentType paymentType, final String successURL, final String failureURL, final String cancelURL, final String pendingUrl, final AlternativePayment alternativePayment, final String shopperCountryCode) { + alternativePayment.setPaymentType(paymentType.getMethodCode()); + alternativePayment.setSuccessURL(successURL); + alternativePayment.setFailureURL(failureURL); + alternativePayment.setCancelURL(cancelURL); + alternativePayment.setPendingURL(pendingUrl); + alternativePayment.setShopperCountryCode(shopperCountryCode); + + return alternativePayment; + } + + public static PaymentDetails createPaymentDetailsFromRequestParameters(final AuthoriseRequestParameters requestParameters) { + final PaymentDetails paymentDetails = new PaymentDetails(); + paymentDetails.setPayment(requestParameters.getPayment()); + paymentDetails.setSession(requestParameters.getShopper() != null ? requestParameters.getShopper().getSession() : null); + paymentDetails.setStoredCredentials(requestParameters.getStoredCredentials()); + paymentDetails.setAction(requestParameters.getAction()); + + return paymentDetails; + } + + public static KlarnaPayment createKlarnaPayment(final String purchaseCountry, final String shopperLocale, final KlarnaMerchantUrls merchantUrls, final String extraMerchantData) { + final KlarnaPayment klarnaPayment = new KlarnaPayment(); + klarnaPayment.setPaymentType(KLARNASSL.getMethodCode()); + klarnaPayment.setPurchaseCountry(purchaseCountry); + klarnaPayment.setShopperLocale(shopperLocale); + klarnaPayment.setMerchantUrls(merchantUrls); + klarnaPayment.setExtraMerchantData(extraMerchantData); + + return klarnaPayment; + } + + public static KlarnaPayment createKlarnaPayment(final String shopperCountryCode, final String shopperLocale, final String extraMerchantData, + final String klarnaPaymentMethod, final KlarnaRedirectURLs klarnaRedirectURLs) { + final KlarnaPayment klarnaPayment = new KlarnaPayment(); + klarnaPayment.setPaymentType(klarnaPaymentMethod); + klarnaPayment.setShopperCountryCode(shopperCountryCode); + klarnaPayment.setLocale(shopperLocale); + klarnaPayment.setSuccessURL(klarnaRedirectURLs.getSuccessURL()); + klarnaPayment.setPendingURL(klarnaRedirectURLs.getPendingURL()); + klarnaPayment.setFailureURL(klarnaRedirectURLs.getFailureURL()); + klarnaPayment.setCancelURL(klarnaRedirectURLs.getCancelURL()); + klarnaPayment.setExtraMerchantData(extraMerchantData); + + return klarnaPayment; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayUtil.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayUtil.java index 52bd7d2e..b256ce32 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayUtil.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/src/com/worldpay/util/WorldpayUtil.java @@ -4,7 +4,7 @@ import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.SerializationUtils; -import java.time.LocalDate; +import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; @@ -20,6 +20,7 @@ private WorldpayUtil() { /** * Serialize the worldpayAdditionalInfo object so that it can be passed into the commands without adjusting the * method structure all the way through + * * @param additionalInfo info to be serialized * @return String representation of the object encoded using Base 64 encoding */ @@ -30,6 +31,7 @@ public static String serializeWorldpayAdditionalInfo(final WorldpayAdditionalInf /** * Deserialize a serialized worldpayAdditionalInfo object + * * @param serializedObject Object to be deserialized * @return worldpayAdditionalInfo object */ @@ -42,10 +44,11 @@ public static WorldpayAdditionalInfoData deserializeWorldpayAdditionalInfo(final /** * Used to created a date in the past. + * * @param days specifies how many days to minus from new date. * @return */ public static Date createDateInPast(final int days) { - return Date.from(LocalDate.now().minusDays(days).atStartOfDay(ZoneId.systemDefault()).toInstant()); + return Date.from(LocalDateTime.now().minusDays(days).atZone(ZoneId.systemDefault()).toInstant()); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/attributehandlers/WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandlerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/attributehandlers/WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandlerTest.java index 40fa2d6d..dcf70c6f 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/attributehandlers/WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandlerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/attributehandlers/WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandlerTest.java @@ -1,6 +1,6 @@ package com.worldpay.attributehandlers; -import com.worldpay.klarna.WorldpayKlarnaUtils; +import com.worldpay.service.payment.WorldpayKlarnaService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.order.payment.WorldpayAPMPaymentInfoModel; import org.junit.Test; @@ -29,41 +29,40 @@ public class WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandle private WorldpayAPMPaymentInfoIsKlarnaPaymentTypeCodeDynamicAttributeHandler testObj; @Mock - private WorldpayKlarnaUtils worldpayKlarnaUtilsMock; - + private WorldpayKlarnaService worldpayKlarnaServiceMock; @Mock(answer = Answers.RETURNS_DEEP_STUBS) private WorldpayAPMPaymentInfoModel paymentInfoModelMock; @Test public void get_shouldReturnTrueWhenKlarnaUtilsMockReturnsTrue() { when(paymentInfoModelMock.getApmConfiguration().getCode()).thenReturn(KLARNA_1); - when(worldpayKlarnaUtilsMock.isKlarnaPaymentType(KLARNA_1)).thenReturn(true); + when(worldpayKlarnaServiceMock.isKlarnaPaymentType(KLARNA_1)).thenReturn(true); final Boolean result = testObj.get(paymentInfoModelMock); - verify(worldpayKlarnaUtilsMock).isKlarnaPaymentType(KLARNA_1); + verify(worldpayKlarnaServiceMock).isKlarnaPaymentType(KLARNA_1); assertThat(result).isTrue(); } @Test public void get_shouldReturnFalseWhenKlarnaUtilsMockReturnsFalse() { when(paymentInfoModelMock.getApmConfiguration().getCode()).thenReturn(NON_KLARNA); - when(worldpayKlarnaUtilsMock.isKlarnaPaymentType(NON_KLARNA)).thenReturn(false); + when(worldpayKlarnaServiceMock.isKlarnaPaymentType(NON_KLARNA)).thenReturn(false); final Boolean result = testObj.get(paymentInfoModelMock); - verify(worldpayKlarnaUtilsMock).isKlarnaPaymentType(NON_KLARNA); + verify(worldpayKlarnaServiceMock).isKlarnaPaymentType(NON_KLARNA); assertThat(result).isFalse(); } @Test public void get_shouldReturnFalseWhenCodeIsNull() { when(paymentInfoModelMock.getApmConfiguration().getCode()).thenReturn(null); - when(worldpayKlarnaUtilsMock.isKlarnaPaymentType(null)).thenReturn(false); + when(worldpayKlarnaServiceMock.isKlarnaPaymentType(null)).thenReturn(false); final Boolean result = testObj.get(paymentInfoModelMock); - verify(worldpayKlarnaUtilsMock).isKlarnaPaymentType(null); + verify(worldpayKlarnaServiceMock).isKlarnaPaymentType(null); assertThat(result).isFalse(); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayCaptureCommandTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayCaptureCommandTest.java index 2430a995..5e0f0916 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayCaptureCommandTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayCaptureCommandTest.java @@ -4,8 +4,8 @@ import com.worldpay.exception.WorldpayException; import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.request.CaptureServiceRequest; import com.worldpay.service.response.CaptureServiceResponse; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayFollowOnRefundCommandTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayFollowOnRefundCommandTest.java index 54985333..df80ff44 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayFollowOnRefundCommandTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayFollowOnRefundCommandTest.java @@ -4,8 +4,8 @@ import com.worldpay.exception.WorldpayException; import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.request.RefundServiceRequest; import com.worldpay.service.response.RefundServiceResponse; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayTokenisedAuthorizationCommandTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayTokenisedAuthorizationCommandTest.java index 8cd354d2..cef00dc0 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayTokenisedAuthorizationCommandTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayTokenisedAuthorizationCommandTest.java @@ -7,8 +7,8 @@ import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.*; -import com.worldpay.service.model.token.Token; +import com.worldpay.data.*; +import com.worldpay.data.token.Token; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.payment.request.WorldpayRequestService; import com.worldpay.service.request.DirectAuthoriseServiceRequest; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayVoidCommandTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayVoidCommandTest.java index 5af31e09..fa545fa8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayVoidCommandTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/DefaultWorldpayVoidCommandTest.java @@ -1,12 +1,14 @@ package com.worldpay.commands.impl; -import com.worldpay.exception.WorldpayConfigurationException; +import com.worldpay.core.services.WorldpayPrimeRoutingService; import com.worldpay.exception.WorldpayException; import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.CancelServiceRequest; +import com.worldpay.service.request.VoidSaleServiceRequest; import com.worldpay.service.response.CancelServiceResponse; +import com.worldpay.service.response.VoidSaleServiceResponse; import com.worldpay.transaction.WorldpayPaymentTransactionService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.payment.commands.request.VoidRequest; @@ -24,12 +26,12 @@ import static org.mockito.Mockito.*; @UnitTest -@RunWith (MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class DefaultWorldpayVoidCommandTest { - public static final String MERCHANT_CODE = "merchantCode"; - public static final String WORLDPAY_ORDER_CODE = "worldpayOrderCode"; - public static final String EXCEPTION_MESSAGE = "exceptionMessage"; + private static final String MERCHANT_CODE = "merchantCode"; + private static final String WORLDPAY_ORDER_CODE = "worldpayOrderCode"; + private static final String EXCEPTION_MESSAGE = "exceptionMessage"; @InjectMocks private DefaultWorldpayVoidCommand testObj; @@ -37,6 +39,8 @@ public class DefaultWorldpayVoidCommandTest { @Mock private Converter voidServiceResponseConverterMock; @Mock + private WorldpayPrimeRoutingService worldpayPrimeRoutingServiceMock; + @Mock private VoidRequest voidRequestMock; @Mock private WorldpayServiceGateway worldpayGatewayMock; @@ -52,19 +56,23 @@ public class DefaultWorldpayVoidCommandTest { private WorldpayPaymentTransactionService worldpayPaymentTransactionServiceMock; @Mock private PaymentTransactionModel paymentTransactionModelMock; + @Mock + private VoidSaleServiceResponse voidResponseMock; @Before - public void setUp() throws WorldpayConfigurationException { + public void setUp() throws WorldpayException { when(worldpayMerchantInfoServiceMock.getMerchantInfoFromTransaction(paymentTransactionModelMock)).thenReturn(merchantInfoMock); when(merchantInfoMock.getMerchantCode()).thenReturn(MERCHANT_CODE); when(voidServiceResponseConverterMock.convert(cancelResponseMock)).thenReturn(voidResultMock); when(worldpayPaymentTransactionServiceMock.getPaymentTransactionFromCode(WORLDPAY_ORDER_CODE)).thenReturn(paymentTransactionModelMock); when(voidRequestMock.getRequestToken()).thenReturn(MERCHANT_CODE); when(voidRequestMock.getRequestId()).thenReturn(WORLDPAY_ORDER_CODE); + when(voidServiceResponseConverterMock.convert(voidResponseMock)).thenReturn(voidResultMock); + when(worldpayGatewayMock.voidSale(any(VoidSaleServiceRequest.class))).thenReturn(voidResponseMock); } @Test - public void testPerformShouldReturnASuccessfulVoidResponse() throws Exception { + public void perform_ShouldReturnASuccessfulVoidResponse() throws Exception { when(worldpayGatewayMock.cancel(any(CancelServiceRequest.class))).thenReturn(cancelResponseMock); testObj.perform(voidRequestMock); @@ -73,7 +81,7 @@ public void testPerformShouldReturnASuccessfulVoidResponse() throws Exception { } @Test - public void testPerformShouldReturnAFailingVoidResponseWhenAnExceptionOccurredInvokingTheGateway() throws Exception { + public void perform_WhenAnExceptionOccurredInvokingTheGateway_ShouldReturnAFailingVoidResponse() throws Exception { doThrow(new WorldpayException(EXCEPTION_MESSAGE)).when(worldpayGatewayMock).cancel(any(CancelServiceRequest.class)); testObj.perform(voidRequestMock); @@ -83,7 +91,7 @@ public void testPerformShouldReturnAFailingVoidResponseWhenAnExceptionOccurredIn } @Test - public void testPerformShouldReturnAFailingVoidResponseWhenResponseFromGatewayIsNull() throws Exception { + public void perform_WhenResponseFromGatewayIsNull_ShouldReturnAFailingVoidResponse() throws Exception { when(worldpayGatewayMock.cancel(any(CancelServiceRequest.class))).thenReturn(null); testObj.perform(voidRequestMock); @@ -91,4 +99,36 @@ public void testPerformShouldReturnAFailingVoidResponseWhenResponseFromGatewayIs verify(worldpayGatewayMock).cancel(any(CancelServiceRequest.class)); verify(voidServiceResponseConverterMock, never()).convert(any(CancelServiceResponse.class)); } + + @Test + public void perform_WhenOrderAuthorisedWithPrimeRouting_ShouldVoidSaleAndNotCallCancel() throws Exception { + when(worldpayPrimeRoutingServiceMock.isOrderAuthorisedWithPrimeRouting(WORLDPAY_ORDER_CODE)).thenReturn(true); + + testObj.perform(voidRequestMock); + + verify(worldpayGatewayMock).voidSale(any(VoidSaleServiceRequest.class)); + verify(worldpayGatewayMock, never()).cancel(any(CancelServiceRequest.class)); + } + + @Test + public void perform_WhenAnExceptionOccurredInvokingTheGatewayVoid_ShouldReturnAFailingVoidResponse() throws Exception { + when(worldpayPrimeRoutingServiceMock.isOrderAuthorisedWithPrimeRouting(WORLDPAY_ORDER_CODE)).thenReturn(true); + doThrow(new WorldpayException(EXCEPTION_MESSAGE)).when(worldpayGatewayMock).voidSale(any(VoidSaleServiceRequest.class)); + + testObj.perform(voidRequestMock); + + verify(worldpayGatewayMock).voidSale(any(VoidSaleServiceRequest.class)); + verify(voidServiceResponseConverterMock, never()).convert(any(VoidSaleServiceResponse.class)); + } + + @Test + public void perform_WhenResponseFromVoidGatewayIsNull_ShouldReturnAFailingVoidResponse() throws Exception { + when(worldpayPrimeRoutingServiceMock.isOrderAuthorisedWithPrimeRouting(WORLDPAY_ORDER_CODE)).thenReturn(true); + when(worldpayGatewayMock.voidSale(any(VoidSaleServiceRequest.class))).thenReturn(null); + + testObj.perform(voidRequestMock); + + verify(worldpayGatewayMock).voidSale(any(VoidSaleServiceRequest.class)); + verify(voidServiceResponseConverterMock, never()).convert(any(VoidSaleServiceResponse.class)); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/WorldpayCommandTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/WorldpayCommandTest.java index 2bf25c55..732ca1e5 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/WorldpayCommandTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/commands/impl/WorldpayCommandTest.java @@ -2,7 +2,7 @@ import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.merchant.WorldpayMerchantInfoService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.transaction.WorldpayPaymentTransactionService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.payment.model.PaymentTransactionModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/OrderModificationRequestConverterTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/OrderModificationRequestConverterTest.java index 669244c2..cb561382 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/OrderModificationRequestConverterTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/OrderModificationRequestConverterTest.java @@ -1,10 +1,10 @@ package com.worldpay.converters; import com.worldpay.internal.model.*; -import com.worldpay.service.model.JournalReply; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.WebformRefundReply; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.data.JournalReply; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.WebformRefundReply; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.notification.OrderNotificationMessage; import com.worldpay.service.response.transform.ServiceResponseTransformerHelper; import de.hybris.bootstrap.annotations.UnitTest; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayAbstractServiceResponseConverterTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayAbstractServiceResponseConverterTest.java index f8572a96..0faf2bf6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayAbstractServiceResponseConverterTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayAbstractServiceResponseConverterTest.java @@ -1,7 +1,7 @@ package com.worldpay.converters; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.ErrorDetail; +import com.worldpay.data.Amount; +import com.worldpay.data.ErrorDetail; import com.worldpay.service.payment.WorldpayOrderService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.payment.dto.TransactionStatusDetails; @@ -23,6 +23,7 @@ @RunWith(MockitoJUnitRunner.class) public class WorldpayAbstractServiceResponseConverterTest { + private static final String ERROR = "error"; private WorldpayAbstractServiceResponseConverter testObj; @Mock @@ -52,98 +53,154 @@ public void getTotalAmount_ShouldGetTheConvertedAmount() { @Test public void getTransactionStatusDetails_WhenErrorCode1_ShouldReturnERROR_INTERNAL() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("1", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("1"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_INTERNAL); } @Test public void getTransactionStatusDetails_WhenErrorCode2_ShouldReturnERROR_PARSE() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("2", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("2"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_PARSE); } @Test public void getTransactionStatusDetails_WhenErrorCode3_ShouldReturnERROR_ORDER_AMOUNT() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("3", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("3"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_ORDER_AMOUNT); } @Test public void getTransactionStatusDetails_WhenErrorCode4_ShouldReturnERROR_SECURITY() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("4", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("4"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_SECURITY); } @Test public void getTransactionStatusDetails_WhenErrorCode5_ShouldReturnERROR_INVALID_REQUEST() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("5", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("5"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_INVALID_REQUEST); } @Test public void getTransactionStatusDetails_WhenErrorCode6_ShouldReturnERROR_INVALID_CONTENT() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("6", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("6"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_INVALID_CONTENT); } @Test public void getTransactionStatusDetails_WhenErrorCode7_ShouldReturnERROR_PAYMENT_DETAILS() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("7", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("7"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_PAYMENT_DETAILS); } @Test public void getTransactionStatusDetails_WhenErrorCode8_ShouldReturnERROR_NOT_AVAILABLE() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("8", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("8"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_NOT_AVAILABLE); } @Test public void getTransactionStatusDetails_WhenErrorCode9_ShouldReturnERROR_IDEMPOTENCY_SERVICE() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("9", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("9"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_IDEMPOTENCY_SERVICE); } @Test public void getTransactionStatusDetails_WhenErrorCode10_ShouldReturnERROR_PRIME_ROUTING() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("10", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("10"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_PRIME_ROUTING); } @Test public void getTransactionStatusDetails_WhenErrorCode11_ShouldReturnERROR_L2_L3_DATA() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("11", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("11"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_L2_L3_DATA); } @Test public void getTransactionStatusDetails_WhenErrorCode12_ShouldReturnERROR_LODGING_DATA() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("12", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("12"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_LODGING_DATA); } @Test public void getTransactionStatusDetails_WhenErrorCode13_ShouldReturnERROR_SPLIT_AUTH() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("13", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("13"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(ERROR_SPLIT_AUTH); } @Test public void getTransactionStatusDetails_WhenErrorCode14_ShouldReturnTheDefaultValue() { - final TransactionStatusDetails result = testObj.getTransactionStatusDetails(new ErrorDetail("14", "error")); + final ErrorDetail error = new ErrorDetail(); + error.setCode("14"); + error.setMessage(ERROR); + + final TransactionStatusDetails result = testObj.getTransactionStatusDetails(error); assertThat(result).isEqualTo(UNKNOWN_CODE); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayCaptureServiceResponseConverterTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayCaptureServiceResponseConverterTest.java index 9a4a527d..6d918010 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayCaptureServiceResponseConverterTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayCaptureServiceResponseConverterTest.java @@ -1,6 +1,6 @@ package com.worldpay.converters; -import com.worldpay.service.model.Amount; +import com.worldpay.data.Amount; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.response.CaptureServiceResponse; import de.hybris.bootstrap.annotations.UnitTest; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayRefundServiceResponseConverterTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayRefundServiceResponseConverterTest.java index 5b0d90e1..8e1cf442 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayRefundServiceResponseConverterTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayRefundServiceResponseConverterTest.java @@ -1,6 +1,6 @@ package com.worldpay.converters; -import com.worldpay.service.model.Amount; +import com.worldpay.data.Amount; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.response.RefundServiceResponse; import de.hybris.bootstrap.annotations.UnitTest; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayRiskScoreConverterTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayRiskScoreConverterTest.java index 200139b7..6465e046 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayRiskScoreConverterTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/WorldpayRiskScoreConverterTest.java @@ -1,6 +1,6 @@ package com.worldpay.converters; -import com.worldpay.service.model.RiskScore; +import com.worldpay.data.RiskScore; import com.worldpay.model.WorldpayRiskScoreModel; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.model.ModelService; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/internal/model/payment/impl/DefaultPaymentConverterStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/internal/model/payment/impl/DefaultPaymentConverterStrategyTest.java new file mode 100644 index 00000000..0847d09c --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/internal/model/payment/impl/DefaultPaymentConverterStrategyTest.java @@ -0,0 +1,66 @@ +package com.worldpay.converters.internal.model.payment.impl; + +import com.worldpay.data.payment.Payment; +import com.worldpay.internal.model.IDEALSSL; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Map; + +import static com.worldpay.service.model.payment.PaymentType.IDEAL; +import static com.worldpay.service.model.payment.PaymentType.VISA; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultPaymentConverterStrategyTest { + + @InjectMocks + private DefaultPaymentConverterStrategy testObj; + + @Mock + private Map> paymentMapConvertersMock; + + @Mock + private Converter idealConverterMock; + @Mock + private Payment idealPaymentMock; + @Mock + private IDEALSSL idealsslMock; + + @Before + public void setUp() { + paymentMapConvertersMock.put(IDEAL.getMethodCode(), idealConverterMock); + } + + @Test(expected = IllegalArgumentException.class) + public void convertPayment_WhenPaymentIsNull_ShouldThrowAnException() { + testObj.convertPayment(null); + } + + @Test(expected = IllegalArgumentException.class) + public void convertPayment_WhenMapHasNotKey_ShouldThrowAnException() { + when(idealPaymentMock.getPaymentType()).thenReturn(VISA.getMethodCode()); + + testObj.convertPayment(idealPaymentMock); + } + + @Test + public void convertPayment_WhenMapHasKey_ShouldConvertPayment() { + when(idealPaymentMock.getPaymentType()).thenReturn(IDEAL.getMethodCode()); + when(paymentMapConvertersMock.containsKey(IDEAL)).thenReturn(Boolean.TRUE); + when(paymentMapConvertersMock.get(IDEAL)).thenReturn(idealConverterMock); + when(idealConverterMock.convert(idealPaymentMock)).thenReturn(idealsslMock); + + final Object result = testObj.convertPayment(idealPaymentMock); + + assertThat(result).isEqualTo(idealsslMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAPMComponentPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAPMComponentPopulatorTest.java new file mode 100644 index 00000000..12bfb5d2 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAPMComponentPopulatorTest.java @@ -0,0 +1,85 @@ +package com.worldpay.converters.populators; + +import com.worldpay.data.apm.WorldpayAPMConfigurationData; +import com.worldpay.data.cms.WorldpayAPMComponentData; +import com.worldpay.model.WorldpayAPMComponentModel; +import com.worldpay.model.WorldpayAPMConfigurationModel; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.cmsfacades.data.MediaData; +import de.hybris.platform.core.model.media.MediaModel; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class WorldpayAPMComponentPopulatorTest { + + @InjectMocks + private WorldpayAPMComponentPopulator testObj; + + @Mock + private Converter mediaModelConverterMock; + @Mock + private Converter worldpayAPMConfigurationConverterMock; + + @Mock + private WorldpayAPMComponentModel sourceMock; + @Mock + private MediaModel mediaModelMock; + @Mock + private MediaData mediaDataMock; + @Mock + private WorldpayAPMConfigurationModel worldpayAPMConfigurationModelMock; + @Mock + private WorldpayAPMConfigurationData worldpayAPMConfigurationDataMock; + + @Before + public void setUp() { + testObj = new WorldpayAPMComponentPopulator(worldpayAPMConfigurationConverterMock, mediaModelConverterMock); + } + + @Test + public void populate_WhenSourceIsNotNullAndTargetIsNotNullAndMediaIsNotNull_ShouldPopulateAllFields() { + when(sourceMock.getApmConfiguration()).thenReturn(worldpayAPMConfigurationModelMock); + when(worldpayAPMConfigurationConverterMock.convert(worldpayAPMConfigurationModelMock)).thenReturn(worldpayAPMConfigurationDataMock); + when(sourceMock.getMedia()).thenReturn(mediaModelMock); + when(mediaModelConverterMock.convert(mediaModelMock)).thenReturn(mediaDataMock); + final WorldpayAPMComponentData target = new WorldpayAPMComponentData(); + + testObj.populate(sourceMock, target); + + assertThat(target.getApmConfiguration()).isEqualTo(worldpayAPMConfigurationDataMock); + assertThat(target.getMedia()).isEqualTo(mediaDataMock); + } + + @Test + public void populate_WhenSourceIsNotNullAndTargetIsNotNullAndMediaIsNull_ShouldOnlyPopulateApmConfig() { + when(sourceMock.getApmConfiguration()).thenReturn(worldpayAPMConfigurationModelMock); + when(worldpayAPMConfigurationConverterMock.convert(worldpayAPMConfigurationModelMock)).thenReturn(worldpayAPMConfigurationDataMock); + when(sourceMock.getMedia()).thenReturn(null); + final WorldpayAPMComponentData target = new WorldpayAPMComponentData(); + + testObj.populate(sourceMock, target); + + assertThat(target.getApmConfiguration()).isEqualTo(worldpayAPMConfigurationDataMock); + assertThat(target.getMedia()).isNull(); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new WorldpayAPMComponentData()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAPMConfigurationPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAPMConfigurationPopulatorTest.java new file mode 100644 index 00000000..d2ff7e01 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAPMConfigurationPopulatorTest.java @@ -0,0 +1,78 @@ +package com.worldpay.converters.populators; + +import com.worldpay.data.apm.WorldpayAPMConfigurationData; +import com.worldpay.facades.BankConfigurationData; +import com.worldpay.facades.WorldpayBankConfigurationFacade; +import com.worldpay.model.WorldpayAPMConfigurationModel; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.List; + +import static java.lang.Boolean.FALSE; +import static java.lang.Boolean.TRUE; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class WorldpayAPMConfigurationPopulatorTest { + + private static final String APM_CODE = "code"; + private static final String APM_NAME = "name"; + private static final String APM_DESCRIPTION = "description"; + + @InjectMocks + private WorldpayAPMConfigurationPopulator testObj; + + @Mock + private WorldpayBankConfigurationFacade worldpayBankConfigurationFacadeMock; + + @Mock + private WorldpayAPMConfigurationModel sourceMock; + @Mock + private BankConfigurationData bankConfigurationData1Mock, bankConfigurationData2Mock; + + @Before + public void setUp() throws Exception { + when(sourceMock.getCode()).thenReturn(APM_CODE); + when(sourceMock.getName()).thenReturn(APM_NAME); + when(sourceMock.getDescription()).thenReturn(APM_DESCRIPTION); + when(sourceMock.getAutoCancelPendingTimeoutInMinutes()).thenReturn(1); + when(sourceMock.getBank()).thenReturn(TRUE); + when(sourceMock.getAutomaticRefunds()).thenReturn(FALSE); + when(sourceMock.getBankTransferRefunds()).thenReturn(TRUE); + when(worldpayBankConfigurationFacadeMock.getBankConfigurationForAPMCode(APM_CODE)).thenReturn(List.of(bankConfigurationData1Mock, bankConfigurationData2Mock)); + } + + @Test + public void populate_ShouldPopulateApmData() { + final WorldpayAPMConfigurationData target = new WorldpayAPMConfigurationData(); + + testObj.populate(sourceMock, target); + + assertThat(target.getCode()).isEqualTo(APM_CODE); + assertThat(target.getName()).isEqualTo(APM_NAME); + assertThat(target.getDescription()).isEqualTo(APM_DESCRIPTION); + assertThat(target.getAutoCancelPendingTimeoutInMinutes()).isEqualTo(1); + assertThat(target.getBank()).isEqualTo(TRUE); + assertThat(target.getAutomaticRefunds()).isEqualTo(FALSE); + assertThat(target.getBankTransferRefunds()).isEqualTo(TRUE); + assertThat(target.getBankConfigurations()).isEqualTo(List.of(bankConfigurationData1Mock, bankConfigurationData2Mock)); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new WorldpayAPMConfigurationData()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAavResponsePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAavResponsePopulatorTest.java index c3b50cc0..e52c8bfe 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAavResponsePopulatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAavResponsePopulatorTest.java @@ -1,7 +1,7 @@ package com.worldpay.converters.populators; import com.worldpay.model.WorldpayAavResponseModel; -import com.worldpay.service.model.PaymentReply; +import com.worldpay.data.PaymentReply; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Before; import org.junit.Test; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAddressPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAddressPopulatorTest.java index 3a9eda52..0ab47d9b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAddressPopulatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAddressPopulatorTest.java @@ -1,6 +1,6 @@ package com.worldpay.converters.populators; -import com.worldpay.service.model.Address; +import com.worldpay.data.Address; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.user.AddressModel; import org.apache.commons.lang.StringEscapeUtils; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAuthorizationResultPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAuthorizationResultPopulatorTest.java index 69fce17d..6ea8ea9d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAuthorizationResultPopulatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayAuthorizationResultPopulatorTest.java @@ -1,8 +1,8 @@ package com.worldpay.converters.populators; import com.worldpay.service.WorldpayAuthorisationResultService; -import com.worldpay.service.model.ErrorDetail; -import com.worldpay.service.model.PaymentReply; +import com.worldpay.data.ErrorDetail; +import com.worldpay.data.PaymentReply; import com.worldpay.service.response.DirectAuthoriseServiceResponse; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.payment.commands.result.AuthorizationResult; @@ -27,7 +27,7 @@ public class WorldpayAuthorizationResultPopulatorTest { private static final String ERROR_MESSAGE = "errorMessage"; @InjectMocks - private WorldpayAuthorizationResultPopulator testObj = new WorldpayAuthorizationResultPopulator(); + private WorldpayAuthorizationResultPopulator testObj; @Mock private WorldpayAuthorisationResultService worldpayAuthorisationResultServiceMock; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayBillingInfoAddressPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayBillingInfoAddressPopulatorTest.java index 614b8a7b..dc0de13a 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayBillingInfoAddressPopulatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayBillingInfoAddressPopulatorTest.java @@ -1,6 +1,6 @@ package com.worldpay.converters.populators; -import com.worldpay.service.model.Address; +import com.worldpay.data.Address; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.payment.dto.BillingInfo; import org.junit.Before; @@ -109,4 +109,4 @@ public void populateShouldAddPhoneNumberOnAddressInformation() { assertEquals(PHONE_NUMBER, address.getTelephoneNumber()); } -} \ No newline at end of file +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayFraudSightResponsePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayFraudSightResponsePopulatorTest.java new file mode 100644 index 00000000..950865c4 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpayFraudSightResponsePopulatorTest.java @@ -0,0 +1,52 @@ +package com.worldpay.converters.populators; + +import com.worldpay.data.FraudSightResponse; +import com.worldpay.model.WorldpayFraudSightModel; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.List; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class WorldpayFraudSightResponsePopulatorTest { + + private static final String FS_ID = "fs_id"; + private static final String REASON_1 = "High risk email"; + private static final String REASON_2 = "Card unfamiliarity"; + private static final String REVIEW = "REVIEW"; + + @InjectMocks + private WorldpayFraudSightResponsePopulator testObj; + + @Mock + private FraudSightResponse fraudSightResponseMock; + @Mock + private WorldpayFraudSightModel worldpayFraudSightMock; + + @Before + public void setUp() { + when(fraudSightResponseMock.getId()).thenReturn(FS_ID); + when(fraudSightResponseMock.getMessage()).thenReturn(REVIEW); + when(fraudSightResponseMock.getScore()).thenReturn(100d); + when(fraudSightResponseMock.getReasonCodes()).thenReturn(List.of(REASON_1, REASON_2)); + } + + @Test + public void populate_ShouldPopulateTheWorldpayFraudSightModel() { + testObj.populate(fraudSightResponseMock, worldpayFraudSightMock); + + verify(worldpayFraudSightMock).setId(FS_ID); + verify(worldpayFraudSightMock).setMessage(REVIEW); + verify(worldpayFraudSightMock).setScore(100d); + verify(worldpayFraudSightMock).setReasonCodes(List.of(REASON_1, REASON_2)); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpaySubscriptionAuthoriseResultPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpaySubscriptionAuthoriseResultPopulatorTest.java index 8d03ca2c..516a763e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpaySubscriptionAuthoriseResultPopulatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/WorldpaySubscriptionAuthoriseResultPopulatorTest.java @@ -2,9 +2,9 @@ import com.worldpay.commands.WorldpaySubscriptionAuthorizeResult; import com.worldpay.service.WorldpayAuthorisationResultService; -import com.worldpay.service.model.ErrorDetail; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.RedirectReference; +import com.worldpay.data.ErrorDetail; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.RedirectReference; import com.worldpay.service.response.DirectAuthoriseServiceResponse; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Before; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/AddressPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/AddressPopulatorTest.java new file mode 100644 index 00000000..a9f6ae9c --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/AddressPopulatorTest.java @@ -0,0 +1,105 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Address; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class AddressPopulatorTest { + + private static final String FIRST_NAME = "firstName"; + private static final String LAST_NAME = "lastName"; + private static final String POSTAL_CODE = "postalCode"; + private static final String CITY = "city"; + private static final String STATE = "state"; + private static final String COUNTRY_CODE = "countryCode"; + private static final String TELEPHONE_NUMBER = "telephoneNumber"; + private static final String STREET = "street"; + private static final String HOUSE_NAME = "houseName"; + private static final String HOUSE_NUMBER = "houseNumber"; + private static final String HOUSE_NUMBER_EXTENSION = "houseNumberExtension"; + private static final String ADDRESS_1 = "address1"; + private static final String ADDRESS_2 = "address2"; + private static final String ADDRESS_3 = "address3"; + public static final int TOTAL_OF_FIELDS = 7; + + @InjectMocks + private AddressPopulator testObj; + + @Mock + private Address sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Address()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenSourceHasNullFields_ShouldNotPopulateStreetOrHouseNameOrHouseNumberOrHouseNumberExtensionOrAddress1OrAddress2OrAddress3() { + when(sourceMock.getStreet()).thenReturn(null); + when(sourceMock.getHouseName()).thenReturn(null); + when(sourceMock.getHouseNumber()).thenReturn(null); + when(sourceMock.getHouseNumberExtension()).thenReturn(null); + when(sourceMock.getAddress1()).thenReturn(null); + when(sourceMock.getAddress2()).thenReturn(null); + when(sourceMock.getAddress3()).thenReturn(null); + + final com.worldpay.internal.model.Address target = new com.worldpay.internal.model.Address(); + testObj.populate(sourceMock, target); + + assertThat(target.getStreetOrHouseNameOrHouseNumberOrHouseNumberExtensionOrAddress1OrAddress2OrAddress3()).isEmpty(); + } + + @Test + public void populate_WhenTelephoneNumberIsNull_ShouldNotPopulateTelephoneNumber() { + when(sourceMock.getTelephoneNumber()).thenReturn(null); + + final com.worldpay.internal.model.Address target = new com.worldpay.internal.model.Address(); + testObj.populate(sourceMock, target); + + assertThat(target.getTelephoneNumber()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getFirstName()).thenReturn(FIRST_NAME); + when(sourceMock.getLastName()).thenReturn(LAST_NAME); + when(sourceMock.getPostalCode()).thenReturn(POSTAL_CODE); + when(sourceMock.getCity()).thenReturn(CITY); + when(sourceMock.getState()).thenReturn(STATE); + when(sourceMock.getCountryCode()).thenReturn(COUNTRY_CODE); + when(sourceMock.getStreet()).thenReturn(STREET); + when(sourceMock.getHouseName()).thenReturn(HOUSE_NAME); + when(sourceMock.getHouseNumber()).thenReturn(HOUSE_NUMBER); + when(sourceMock.getHouseNumberExtension()).thenReturn(HOUSE_NUMBER_EXTENSION); + when(sourceMock.getAddress1()).thenReturn(ADDRESS_1); + when(sourceMock.getAddress2()).thenReturn(ADDRESS_2); + when(sourceMock.getAddress3()).thenReturn(ADDRESS_3); + when(sourceMock.getTelephoneNumber()).thenReturn(TELEPHONE_NUMBER); + + final com.worldpay.internal.model.Address target = new com.worldpay.internal.model.Address(); + testObj.populate(sourceMock, target); + + assertThat(target.getFirstName()).isEqualTo(FIRST_NAME); + assertThat(target.getLastName()).isEqualTo(LAST_NAME); + assertThat(target.getPostalCode()).isEqualTo(POSTAL_CODE); + assertThat(target.getCity()).isEqualTo(CITY); + assertThat(target.getState()).isEqualTo(STATE); + assertThat(target.getCountryCode()).isEqualTo(COUNTRY_CODE); + assertThat(target.getStreetOrHouseNameOrHouseNumberOrHouseNumberExtensionOrAddress1OrAddress2OrAddress3().size()).isEqualTo(TOTAL_OF_FIELDS); + assertThat(target.getTelephoneNumber()).isEqualTo(TELEPHONE_NUMBER); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/AmountPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/AmountPopulatorTest.java new file mode 100644 index 00000000..2f437abf --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/AmountPopulatorTest.java @@ -0,0 +1,65 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Amount; +import com.worldpay.enums.DebitCreditIndicator; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class AmountPopulatorTest { + + private static final String CREDIT = "credit"; + private static final String VALUE = "value"; + private static final String CURRENCY_CODE = "currencyCode"; + private static final String EXPONENT = "exponent"; + + @InjectMocks + private AmountPopulator testObj; + + @Mock + private Amount sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Amount()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenDebitCreditIndicatorIsNull_ShouldNotPopulateDebitCreditIndicator() { + when(sourceMock.getDebitCreditIndicator()).thenReturn(null); + + final com.worldpay.internal.model.Amount target = new com.worldpay.internal.model.Amount(); + testObj.populate(sourceMock, target); + + assertThat(target.getDebitCreditIndicator()).isEqualTo(CREDIT); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getValue()).thenReturn(VALUE); + when(sourceMock.getCurrencyCode()).thenReturn(CURRENCY_CODE); + when(sourceMock.getExponent()).thenReturn(EXPONENT); + when(sourceMock.getDebitCreditIndicator()).thenReturn(DebitCreditIndicator.CREDIT); + + final com.worldpay.internal.model.Amount target = new com.worldpay.internal.model.Amount(); + testObj.populate(sourceMock, target); + + assertThat(target.getValue()).isEqualTo(VALUE); + assertThat(target.getCurrencyCode()).isEqualTo(CURRENCY_CODE); + assertThat(target.getExponent()).isEqualTo(EXPONENT); + assertThat(target.getDebitCreditIndicator()).isEqualTo(DebitCreditIndicator.CREDIT.getCode()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/BranchSpecificExtensionPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/BranchSpecificExtensionPopulatorTest.java new file mode 100644 index 00000000..98cdb24b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/BranchSpecificExtensionPopulatorTest.java @@ -0,0 +1,65 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.BranchSpecificExtension; +import com.worldpay.data.Purchase; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class BranchSpecificExtensionPopulatorTest { + + @InjectMocks + private BranchSpecificExtensionPopulator testObj; + + @Mock + private Converter internalPurchaseConverterMock; + + @Mock + private BranchSpecificExtension sourceMock; + @Mock + private Purchase purchaseMock; + @Mock + private com.worldpay.internal.model.Purchase intPurchaseMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.BranchSpecificExtension()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetPurchaseIsNull_ShouldNotPopulateAirlineOrPurchaseOrHotelOrLodging() { + when(sourceMock.getPurchase()).thenReturn(null); + + final com.worldpay.internal.model.BranchSpecificExtension target = new com.worldpay.internal.model.BranchSpecificExtension(); + testObj.populate(sourceMock, target); + + assertThat(target.getAirlineOrPurchaseOrHotelOrLodging()).isEmpty(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getPurchase()).thenReturn(List.of(purchaseMock)); + when(internalPurchaseConverterMock.convertAll(List.of(purchaseMock))).thenReturn(List.of(intPurchaseMock)); + + final com.worldpay.internal.model.BranchSpecificExtension target = new com.worldpay.internal.model.BranchSpecificExtension(); + testObj.populate(sourceMock, target); + + assertThat(target.getAirlineOrPurchaseOrHotelOrLodging()).isEqualTo(List.of(intPurchaseMock)); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/BrowserPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/BrowserPopulatorTest.java new file mode 100644 index 00000000..f2c5dd55 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/BrowserPopulatorTest.java @@ -0,0 +1,57 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Browser; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class BrowserPopulatorTest { + + private static final String ACCEPTER_HEADER = "accepterHeader"; + private static final String DEVICE_OS = "deviceOS"; + private static final String HTTP_ACCEPT_LANGUAGE = "httpAcceptLanguage"; + private static final String HTTP_REFERER = "httpReferer"; + private static final String USER_AGENT_HEADER = "userAgentHeader"; + + @InjectMocks + BrowserPopulator testObj; + + @Mock + private Browser sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Browser()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateBrowser() { + when(sourceMock.getAcceptHeader()).thenReturn(ACCEPTER_HEADER); + when(sourceMock.getDeviceOS()).thenReturn(DEVICE_OS); + when(sourceMock.getHttpAcceptLanguage()).thenReturn(HTTP_ACCEPT_LANGUAGE); + when(sourceMock.getHttpReferer()).thenReturn(HTTP_REFERER); + when(sourceMock.getUserAgentHeader()).thenReturn(USER_AGENT_HEADER); + + final com.worldpay.internal.model.Browser targetMock = new com.worldpay.internal.model.Browser(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAcceptHeader()).isEqualTo(ACCEPTER_HEADER); + assertThat(targetMock.getDeviceOS()).isEqualTo(DEVICE_OS); + assertThat(targetMock.getHttpAcceptLanguage()).isEqualTo(HTTP_ACCEPT_LANGUAGE); + assertThat(targetMock.getHttpReferer()).isEqualTo(HTTP_REFERER); + assertThat(targetMock.getUserAgentHeader()).isEqualTo(USER_AGENT_HEADER); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/CustomNumericFieldsPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/CustomNumericFieldsPopulatorTest.java new file mode 100644 index 00000000..cf4a4285 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/CustomNumericFieldsPopulatorTest.java @@ -0,0 +1,161 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.CustomNumericFields; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class CustomNumericFieldsPopulatorTest { + + @InjectMocks + private CustomNumericFieldsPopulator testObj; + + @Mock + private CustomNumericFields sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.CustomNumericFields()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetCustomNumericField1IsNull_ShouldNotPopulateCustomNumericField1() { + when(sourceMock.getCustomNumericField1()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField1()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericField2IsNull_ShouldNotPopulateCustomNumericField2() { + when(sourceMock.getCustomNumericField2()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField2()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericField3IsNull_ShouldNotPopulateCustomNumericField3() { + when(sourceMock.getCustomNumericField3()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField3()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericField4IsNull_ShouldNotPopulateCustomNumericField4() { + when(sourceMock.getCustomNumericField4()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField4()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericField5IsNull_ShouldNotPopulateCustomNumericField5() { + when(sourceMock.getCustomNumericField5()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField5()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericField6IsNull_ShouldNotPopulateCustomNumericField6() { + when(sourceMock.getCustomNumericField6()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField6()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericField7IsNull_ShouldNotPopulateCustomNumericField7() { + when(sourceMock.getCustomNumericField7()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField7()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericField8IsNull_ShouldNotPopulateCustomNumericField8() { + when(sourceMock.getCustomNumericField8()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField8()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericField9IsNull_ShouldNotPopulateCustomNumericField9() { + when(sourceMock.getCustomNumericField9()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField9()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericField10IsNull_ShouldNotPopulateCustomNumericField10() { + when(sourceMock.getCustomNumericField10()).thenReturn(null); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField10()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getCustomNumericField1()).thenReturn(1); + when(sourceMock.getCustomNumericField2()).thenReturn(2); + when(sourceMock.getCustomNumericField3()).thenReturn(3); + when(sourceMock.getCustomNumericField4()).thenReturn(4); + when(sourceMock.getCustomNumericField5()).thenReturn(5); + when(sourceMock.getCustomNumericField6()).thenReturn(6); + when(sourceMock.getCustomNumericField7()).thenReturn(7); + when(sourceMock.getCustomNumericField8()).thenReturn(8); + when(sourceMock.getCustomNumericField9()).thenReturn(9); + when(sourceMock.getCustomNumericField10()).thenReturn(10); + + final com.worldpay.internal.model.CustomNumericFields target = new com.worldpay.internal.model.CustomNumericFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericField1()).isEqualTo("1"); + assertThat(target.getCustomNumericField2()).isEqualTo("2"); + assertThat(target.getCustomNumericField3()).isEqualTo("3"); + assertThat(target.getCustomNumericField4()).isEqualTo("4"); + assertThat(target.getCustomNumericField5()).isEqualTo("5"); + assertThat(target.getCustomNumericField6()).isEqualTo("6"); + assertThat(target.getCustomNumericField7()).isEqualTo("7"); + assertThat(target.getCustomNumericField8()).isEqualTo("8"); + assertThat(target.getCustomNumericField9()).isEqualTo("9"); + assertThat(target.getCustomNumericField10()).isEqualTo("10"); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/CustomStringFieldsPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/CustomStringFieldsPopulatorTest.java new file mode 100644 index 00000000..bc968d65 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/CustomStringFieldsPopulatorTest.java @@ -0,0 +1,73 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.CustomStringFields; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class CustomStringFieldsPopulatorTest { + + private static final String CUSTOMER_STRING_FIELD_1 = "customerStringField1"; + private static final String CUSTOMER_STRING_FIELD_2 = "customerStringField2"; + private static final String CUSTOMER_STRING_FIELD_3 = "customerStringField3"; + private static final String CUSTOMER_STRING_FIELD_4 = "customerStringField4"; + private static final String CUSTOMER_STRING_FIELD_5 = "customerStringField5"; + private static final String CUSTOMER_STRING_FIELD_6 = "customerStringField6"; + private static final String CUSTOMER_STRING_FIELD_7 = "customerStringField7"; + private static final String CUSTOMER_STRING_FIELD_8 = "customerStringField8"; + private static final String CUSTOMER_STRING_FIELD_9 = "customerStringField9"; + private static final String CUSTOMER_STRING_FIELD_10 = "customerStringField10"; + + @InjectMocks + private CustomStringFieldsPopulator testObj; + + @Mock + private CustomStringFields sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhensourceMockIsNull_ShouldThrowException() { + testObj.populate(null, new com.worldpay.internal.model.CustomStringFields()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhentargetMockIsNull_ShouldThrowException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateBrowser() { + when(sourceMock.getCustomStringField1()).thenReturn(CUSTOMER_STRING_FIELD_1); + when(sourceMock.getCustomStringField2()).thenReturn(CUSTOMER_STRING_FIELD_2); + when(sourceMock.getCustomStringField3()).thenReturn(CUSTOMER_STRING_FIELD_3); + when(sourceMock.getCustomStringField4()).thenReturn(CUSTOMER_STRING_FIELD_4); + when(sourceMock.getCustomStringField5()).thenReturn(CUSTOMER_STRING_FIELD_5); + when(sourceMock.getCustomStringField6()).thenReturn(CUSTOMER_STRING_FIELD_6); + when(sourceMock.getCustomStringField7()).thenReturn(CUSTOMER_STRING_FIELD_7); + when(sourceMock.getCustomStringField8()).thenReturn(CUSTOMER_STRING_FIELD_8); + when(sourceMock.getCustomStringField9()).thenReturn(CUSTOMER_STRING_FIELD_9); + when(sourceMock.getCustomStringField10()).thenReturn(CUSTOMER_STRING_FIELD_10); + + final com.worldpay.internal.model.CustomStringFields targetMock = new com.worldpay.internal.model.CustomStringFields(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getCustomStringField1()).isEqualTo(CUSTOMER_STRING_FIELD_1); + assertThat(targetMock.getCustomStringField2()).isEqualTo(CUSTOMER_STRING_FIELD_2); + assertThat(targetMock.getCustomStringField3()).isEqualTo(CUSTOMER_STRING_FIELD_3); + assertThat(targetMock.getCustomStringField4()).isEqualTo(CUSTOMER_STRING_FIELD_4); + assertThat(targetMock.getCustomStringField5()).isEqualTo(CUSTOMER_STRING_FIELD_5); + assertThat(targetMock.getCustomStringField6()).isEqualTo(CUSTOMER_STRING_FIELD_6); + assertThat(targetMock.getCustomStringField7()).isEqualTo(CUSTOMER_STRING_FIELD_7); + assertThat(targetMock.getCustomStringField8()).isEqualTo(CUSTOMER_STRING_FIELD_8); + assertThat(targetMock.getCustomStringField9()).isEqualTo(CUSTOMER_STRING_FIELD_9); + assertThat(targetMock.getCustomStringField10()).isEqualTo(CUSTOMER_STRING_FIELD_10); + + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/DatePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/DatePopulatorTest.java new file mode 100644 index 00000000..01179944 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/DatePopulatorTest.java @@ -0,0 +1,60 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Date; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DatePopulatorTest { + + private static final String YEAR = "year"; + private static final String MONTH = "month"; + private static final String DAY_OF_MONTH = "dayOfMonth"; + private static final String HOUR = "hour"; + private static final String MINUTE = "minute"; + private static final String SECOND = "second"; + + @InjectMocks + private DatePopulator testObj; + + @Mock + private Date sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Date()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNull_ShouldPopulate() { + when(sourceMock.getYear()).thenReturn(YEAR); + when(sourceMock.getMonth()).thenReturn(MONTH); + when(sourceMock.getDayOfMonth()).thenReturn(DAY_OF_MONTH); + when(sourceMock.getHour()).thenReturn(HOUR); + when(sourceMock.getMinute()).thenReturn(MINUTE); + when(sourceMock.getSecond()).thenReturn(SECOND); + + final com.worldpay.internal.model.Date target = new com.worldpay.internal.model.Date(); + testObj.populate(sourceMock, target); + + assertThat(target.getYear()).isEqualTo(YEAR); + assertThat(target.getMonth()).isEqualTo(MONTH); + assertThat(target.getDayOfMonth()).isEqualTo(DAY_OF_MONTH); + assertThat(target.getHour()).isEqualTo(HOUR); + assertThat(target.getMinute()).isEqualTo(MINUTE); + assertThat(target.getSecond()).isEqualTo(SECOND); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/FraudSightDataPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/FraudSightDataPopulatorTest.java new file mode 100644 index 00000000..9e6b583b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/FraudSightDataPopulatorTest.java @@ -0,0 +1,109 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.CustomNumericFields; +import com.worldpay.data.CustomStringFields; +import com.worldpay.data.FraudSightData; +import com.worldpay.data.ShopperFields; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class FraudSightDataPopulatorTest { + + @InjectMocks + private FraudSightDataPopulator testObj; + + @Mock + private Converter internalShopperFieldsConverterMock; + @Mock + private Converter internalCustomNumericFieldsConverterMock; + @Mock + private Converter internalCustomStringFieldsConverterMock; + + @Mock + private FraudSightData sourceMock; + @Mock + private ShopperFields shopperFieldsMock; + @Mock + private com.worldpay.internal.model.ShopperFields intShopperFieldsMock; + @Mock + private CustomNumericFields customNumericFieldsMock; + @Mock + private com.worldpay.internal.model.CustomNumericFields intCustomNumericFieldsMock; + @Mock + private CustomStringFields customStringFieldsMock; + @Mock + private com.worldpay.internal.model.CustomStringFields intCustomStringFieldsMock; + + @Before + public void setUp() { + testObj = new FraudSightDataPopulator(internalShopperFieldsConverterMock, internalCustomNumericFieldsConverterMock, internalCustomStringFieldsConverterMock); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.FraudSightData()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetShopperFieldsIsNull_ShouldNotPopulateShopperFields() { + when(sourceMock.getShopperFields()).thenReturn(null); + + final com.worldpay.internal.model.FraudSightData target = new com.worldpay.internal.model.FraudSightData(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperFields()).isNull(); + } + + @Test + public void populate_WhenGetCustomNumericFieldsIsNull_ShouldNotPopulateCustomNumericFields() { + when(sourceMock.getCustomNumericFields()).thenReturn(null); + + final com.worldpay.internal.model.FraudSightData target = new com.worldpay.internal.model.FraudSightData(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericFields()).isNull(); + } + + @Test + public void populate_WhenGetCustomStringFieldsIsNull_ShouldNotPopulateCustomStringFields() { + when(sourceMock.getCustomStringFields()).thenReturn(null); + + final com.worldpay.internal.model.FraudSightData target = new com.worldpay.internal.model.FraudSightData(); + testObj.populate(sourceMock, target); + + assertThat(target.getCustomNumericFields()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getShopperFields()).thenReturn(shopperFieldsMock); + when(sourceMock.getCustomNumericFields()).thenReturn(customNumericFieldsMock); + when(sourceMock.getCustomStringFields()).thenReturn(customStringFieldsMock); + when(internalShopperFieldsConverterMock.convert(shopperFieldsMock)).thenReturn(intShopperFieldsMock); + when(internalCustomNumericFieldsConverterMock.convert(customNumericFieldsMock)).thenReturn(intCustomNumericFieldsMock); + when(internalCustomStringFieldsConverterMock.convert(customStringFieldsMock)).thenReturn(intCustomStringFieldsMock); + + final com.worldpay.internal.model.FraudSightData target = new com.worldpay.internal.model.FraudSightData(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperFields()).isEqualTo(intShopperFieldsMock); + assertThat(target.getCustomNumericFields()).isEqualTo(intCustomNumericFieldsMock); + assertThat(target.getCustomStringFields()).isEqualTo(intCustomStringFieldsMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ItemPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ItemPopulatorTest.java new file mode 100644 index 00000000..b1a55c51 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ItemPopulatorTest.java @@ -0,0 +1,141 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Amount; +import com.worldpay.data.Item; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class ItemPopulatorTest { + + private static final String PRODUCT_CODE = "productCode"; + private static final String COMMODITY_CODE = "commodityCode"; + private static final String QUANTITY = "quantity"; + private static final String UNIT_OF_MEASURE = "unitOfMeasure"; + private static final String DESCRIPTION = "description"; + + @InjectMocks + private ItemPopulator testObj; + + @Mock + private Converter internalAmountConverterMock; + + @Mock + private Item sourceMock; + @Mock + private Amount unitCostMock, itemTotalMock, itemTotalWithTaxMock, itemDiscountAmountMock, taxAmountMock; + @Mock + private com.worldpay.internal.model.Amount intUnitCostMock, intItemTotalMock, intItemTotalWithTaxMock, intItemDiscountAmountMock, intTaxAmountMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Item()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenDescriptionIsNull_ShouldNotPopulateDescription() { + when(sourceMock.getDescription()).thenReturn(null); + + final com.worldpay.internal.model.Item target = new com.worldpay.internal.model.Item(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescription()).isNull(); + } + + @Test + public void populate_WhenUnitCostIsNull_ShouldNotPopulateUnitCost() { + when(sourceMock.getUnitCost()).thenReturn(null); + + final com.worldpay.internal.model.Item target = new com.worldpay.internal.model.Item(); + testObj.populate(sourceMock, target); + + assertThat(target.getUnitCost()).isNull(); + } + + @Test + public void populate_WhenItemTotalIsNull_ShouldNotPopulateItemTotal() { + when(sourceMock.getItemTotal()).thenReturn(null); + + final com.worldpay.internal.model.Item target = new com.worldpay.internal.model.Item(); + testObj.populate(sourceMock, target); + + assertThat(target.getItemTotal()).isNull(); + } + + @Test + public void populate_WhenItemTotalWithTaxIsNull_ShouldNotPopulateItemTotalWithTax() { + when(sourceMock.getItemTotalWithTax()).thenReturn(null); + + final com.worldpay.internal.model.Item target = new com.worldpay.internal.model.Item(); + testObj.populate(sourceMock, target); + + assertThat(target.getItemTotalWithTax()).isNull(); + } + + @Test + public void populate_WhenItemDiscountAmountIsNull_ShouldNotPopulateItemDiscountAmount() { + when(sourceMock.getItemDiscountAmount()).thenReturn(null); + + final com.worldpay.internal.model.Item target = new com.worldpay.internal.model.Item(); + testObj.populate(sourceMock, target); + + assertThat(target.getItemDiscountAmount()).isNull(); + } + + @Test + public void populate_WhenTaxAmountNull_ShouldNotPopulateTaxAmount() { + when(sourceMock.getTaxAmount()).thenReturn(null); + + final com.worldpay.internal.model.Item target = new com.worldpay.internal.model.Item(); + testObj.populate(sourceMock, target); + + assertThat(target.getTaxAmount()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(internalAmountConverterMock.convert(unitCostMock)).thenReturn(intUnitCostMock); + when(internalAmountConverterMock.convert(itemTotalMock)).thenReturn(intItemTotalMock); + when(internalAmountConverterMock.convert(itemTotalWithTaxMock)).thenReturn(intItemTotalWithTaxMock); + when(internalAmountConverterMock.convert(itemDiscountAmountMock)).thenReturn(intItemDiscountAmountMock); + when(internalAmountConverterMock.convert(taxAmountMock)).thenReturn(intTaxAmountMock); + when(sourceMock.getProductCode()).thenReturn(PRODUCT_CODE); + when(sourceMock.getCommodityCode()).thenReturn(COMMODITY_CODE); + when(sourceMock.getQuantity()).thenReturn(QUANTITY); + when(sourceMock.getUnitOfMeasure()).thenReturn(UNIT_OF_MEASURE); + when(sourceMock.getDescription()).thenReturn(DESCRIPTION); + when(sourceMock.getUnitCost()).thenReturn(unitCostMock); + when(sourceMock.getItemTotal()).thenReturn(itemTotalMock); + when(sourceMock.getItemTotalWithTax()).thenReturn(itemTotalWithTaxMock); + when(sourceMock.getItemDiscountAmount()).thenReturn(itemDiscountAmountMock); + when(sourceMock.getTaxAmount()).thenReturn(taxAmountMock); + + final com.worldpay.internal.model.Item target = new com.worldpay.internal.model.Item(); + testObj.populate(sourceMock, target); + + assertThat(target.getProductCode()).isEqualTo(PRODUCT_CODE); + assertThat(target.getCommodityCode()).isEqualTo(COMMODITY_CODE); + assertThat(target.getQuantity()).isEqualTo(QUANTITY); + assertThat(target.getUnitOfMeasure()).isEqualTo(UNIT_OF_MEASURE); + assertThat(target.getDescription().getvalue()).isEqualTo(DESCRIPTION); + assertThat(target.getUnitCost().getAmount()).isEqualTo(intUnitCostMock); + assertThat(target.getItemTotal().getAmount()).isEqualTo(intItemTotalMock); + assertThat(target.getItemTotalWithTax().getAmount()).isEqualTo(intItemTotalWithTaxMock); + assertThat(target.getItemDiscountAmount().getAmount()).isEqualTo(intItemDiscountAmountMock); + assertThat(target.getTaxAmount().getAmount()).isEqualTo(intTaxAmountMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/LineItemPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/LineItemPopulatorTest.java new file mode 100644 index 00000000..86c08969 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/LineItemPopulatorTest.java @@ -0,0 +1,99 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.LineItem; +import com.worldpay.data.LineItemReference; +import com.worldpay.enums.lineItem.LineItemType; +import com.worldpay.internal.model.Reference; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class LineItemPopulatorTest { + + private static final String NAME = "name"; + private static final String QUANTITY = "quantity"; + private static final String QUANTITY_UNIT = "quantityUnit"; + private static final String TAX_RATE = "taxRate"; + private static final String TOTAL_AMOUNT = "totalAmount"; + private static final String TOTAL_DISCOUNT_AMOUNT = "totalDiscountAmount"; + private static final String TOTAL_TAX_AMOUNT = "totalTaxAmount"; + + @InjectMocks + private LineItemPopulator testObj; + + @Mock + private Converter internalReferencePopulator; + + @Mock + private LineItem sourceMock; + @Mock + private Reference intReferenceMock; + @Mock + private LineItemReference lineItemReferenceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowException() { + testObj.populate(null, new com.worldpay.internal.model.LineItem()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenLineItemReferenceIsNull_ShouldNotPopulate() { + when(sourceMock.getLineItemReference()).thenReturn(null); + + final com.worldpay.internal.model.LineItem targetMock = new com.worldpay.internal.model.LineItem(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getReference()).isNull(); + } + + @Test + public void populate_WhenLineItemTypeIsNull_ShouldNotPopulate() { + when(sourceMock.getLineItemType()).thenReturn(null); + + final com.worldpay.internal.model.LineItem targetMock = new com.worldpay.internal.model.LineItem(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock. + getPhysicalOrDiscountOrShippingFeeOrDigitalOrGiftCardOrSalesTaxTypeOrStoreCreditOrSurcharge()) + .isEmpty(); + } + + @Test + public void populator_ShouldPopulateLineItem() { + when(sourceMock.getName()).thenReturn(NAME); + when(sourceMock.getQuantity()).thenReturn(QUANTITY); + when(sourceMock.getQuantityUnit()).thenReturn(QUANTITY_UNIT); + when(sourceMock.getTaxRate()).thenReturn(TAX_RATE); + when(sourceMock.getTotalAmount()).thenReturn(TOTAL_AMOUNT); + when(sourceMock.getTotalDiscountAmount()).thenReturn(TOTAL_DISCOUNT_AMOUNT); + when(sourceMock.getTotalTaxAmount()).thenReturn(TOTAL_TAX_AMOUNT); + when(sourceMock.getLineItemReference()).thenReturn(lineItemReferenceMock); + when(internalReferencePopulator.convert(sourceMock.getLineItemReference())).thenReturn(intReferenceMock); + when(sourceMock.getLineItemType()).thenReturn(LineItemType.DISCOUNT); + + final com.worldpay.internal.model.LineItem targetMock = new com.worldpay.internal.model.LineItem(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getName()).isEqualTo(NAME); + assertThat(targetMock.getQuantity()).isEqualTo(QUANTITY); + assertThat(targetMock.getQuantityUnit()).isEqualTo(QUANTITY_UNIT); + assertThat(targetMock.getTaxRate()).isEqualTo(TAX_RATE); + assertThat(targetMock.getTotalAmount()).isEqualTo(TOTAL_AMOUNT); + assertThat(targetMock.getTotalDiscountAmount()).isEqualTo(TOTAL_DISCOUNT_AMOUNT); + assertThat(targetMock.getTotalTaxAmount()).isEqualTo(TOTAL_TAX_AMOUNT); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/OrderLinesPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/OrderLinesPopulatorTest.java new file mode 100644 index 00000000..45b4f078 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/OrderLinesPopulatorTest.java @@ -0,0 +1,74 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.LineItem; +import com.worldpay.data.OrderLines; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class OrderLinesPopulatorTest { + + private static final String ORDER_TAX_AMOUNT = "orderTaxAmount"; + private static final String TERMS_URL = "termsURL"; + + @InjectMocks + private OrderLinesPopulator testObj; + + @Mock + private Converter internalLineItemConverter; + + @Mock + private OrderLines sourceMock; + @Mock + private LineItem lineItemsMock; + @Mock + private com.worldpay.internal.model.LineItem internalLineItemMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowException() { + testObj.populate(null, new com.worldpay.internal.model.OrderLines()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenLineItemsIsNull_ShouldNotPopulate() { + when(sourceMock.getLineItems()).thenReturn(Collections.emptyList()); + + final com.worldpay.internal.model.OrderLines targetMock = new com.worldpay.internal.model.OrderLines(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getLineItem()).isEmpty(); + } + + + @Test + public void populate_ShouldPopulateOrderLines() { + when(sourceMock.getOrderTaxAmount()).thenReturn(ORDER_TAX_AMOUNT); + when(sourceMock.getTermsURL()).thenReturn(TERMS_URL); + when(sourceMock.getLineItems()).thenReturn(List.of(lineItemsMock)); + when(internalLineItemConverter.convertAll(sourceMock.getLineItems())).thenReturn(List.of(internalLineItemMock)); + + final com.worldpay.internal.model.OrderLines targetMock = new com.worldpay.internal.model.OrderLines(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getOrderTaxAmount()).isEqualTo(ORDER_TAX_AMOUNT); + assertThat(targetMock.getTermsURL()).isEqualTo(TERMS_URL); + assertThat(targetMock.getLineItem()).isNotEmpty(); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/OrderPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/OrderPopulatorTest.java new file mode 100644 index 00000000..a8460b27 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/OrderPopulatorTest.java @@ -0,0 +1,548 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.*; +import com.worldpay.data.payment.PayAsOrder; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.enums.order.DynamicInteractionType; +import com.worldpay.internal.model.BillingAddress; +import com.worldpay.internal.model.CreateToken; +import com.worldpay.internal.model.Mandate; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.apache.logging.log4j.util.Strings; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class OrderPopulatorTest { + + private static final String ORDER_CODE = "orderCode"; + private static final String DESCRIPTION = "DESCRIPTION"; + private static final String INSTALLATION_ID = "installationId"; + private static final String ORDER_CONTENT = "orderContent"; + private static final String STATEMENT_NARRATIVE = "statementNarrative"; + private static final String ECHO_DATA = "echoData"; + private static final String PA_RESPONSE = "paResponse"; + private static final String DEVICE_SESSION = "deviceSession"; + private static final String MANDATE_TYPE = "mandateType"; + + @InjectMocks + private OrderPopulator testObj; + + @Mock + private Converter internalBranchSpecificExtensionConverterMock; + @Mock + private Converter internalTokenRequestConverterMock; + @Mock + private Converter internalOrderLinesConverterMock; + @Mock + private Converter internalFraudSightDataConverterMock; + @Mock + private PaymentOrderConvertersWrapper paymentOrderConvertersWrapperMock; + @Mock + private ThreeDS2OrderConvertersWrapper threeDS2OrderConvertersWrapperMock; + @Mock + private BasicOrderConvertersWrapper basicOrderConvertersWrapperMock; + + @Mock + private Converter internalAmountConverterMock; + @Mock + private Converter internalShopperConverterMock; + @Mock + private Converter internalAddressConverterMock; + @Mock + private Converter internalPaymentMethodAttributeConverterMock; + @Mock + private Converter internalSessionConverterMock; + @Mock + private Converter internalRiskDataConverterMock; + @Mock + private Converter internalAdditional3DSDataConverter; + + @Mock + private Order sourceMock; + @Mock + private PaymentMethodAttribute paymentMethodAttribute1Mock, paymentMethodAttribute2Mock; + @Mock + private com.worldpay.internal.model.PaymentMethodAttribute intPaymentMethodAttribute1Mock, intPaymentMethodAttribute2Mock; + @Mock + private Amount amountMock; + @Mock + private com.worldpay.internal.model.Amount intAmountMock; + @Mock + private PaymentMethodMask paymentMethodMaskMock; + @Mock + private com.worldpay.internal.model.PaymentMethodMask intPaymentMethodMaskMock; + @Mock + private PaymentDetails paymentDetailsMock; + @Mock + private com.worldpay.internal.model.PaymentDetails intPaymentDetailsMock; + @Mock + private PayAsOrder payAsOrderMock; + @Mock + private com.worldpay.internal.model.PayAsOrder intPayAsOrderMock; + @Mock + private Shopper shopperMock; + @Mock + private com.worldpay.internal.model.Shopper intShopperMock; + @Mock + private Address addressMock; + @Mock + private com.worldpay.internal.model.Address intAddressMock; + @Mock + private BranchSpecificExtension branchSpecificExtensionMock; + @Mock + private com.worldpay.internal.model.BranchSpecificExtension intBranchSpecificExtensionMock; + @Mock + private TokenRequest tokenRequestMock; + @Mock + private com.worldpay.internal.model.CreateToken createTokenMock; + @Mock + private Session sessionMock; + @Mock + private com.worldpay.internal.model.Session intSessionMock; + @Mock + private OrderLines orderLinesMock; + @Mock + private com.worldpay.internal.model.OrderLines intOrderLinesMock; + @Mock + private RiskData riskDataMock; + @Mock + private com.worldpay.internal.model.RiskData intRiskDataMock; + @Mock + private Additional3DSData additional3DSDataMock; + @Mock + private com.worldpay.internal.model.Additional3DSData intAdditional3DSDataMock; + @Mock + private FraudSightData fraudSightDataMock; + @Mock + private com.worldpay.internal.model.FraudSightData intFraudSightDataMock; + @Mock + private Converter internalPaymentMethodMaskConverterMock; + @Mock + private Converter internalPaymentDetailsConverterMock; + @Mock + private Converter internalPayAsOrderConverterMock; + + @Before + public void setUp() { + paymentOrderConvertersWrapperMock = new PaymentOrderConvertersWrapper(internalPaymentMethodMaskConverterMock, internalPaymentDetailsConverterMock, internalPayAsOrderConverterMock, internalPaymentMethodAttributeConverterMock); + threeDS2OrderConvertersWrapperMock = new ThreeDS2OrderConvertersWrapper(internalRiskDataConverterMock, internalAdditional3DSDataConverter); + basicOrderConvertersWrapperMock = new BasicOrderConvertersWrapper(internalAmountConverterMock, internalShopperConverterMock, internalAddressConverterMock, internalSessionConverterMock); + + testObj = new OrderPopulator(internalBranchSpecificExtensionConverterMock, internalTokenRequestConverterMock, internalOrderLinesConverterMock, + internalFraudSightDataConverterMock, paymentOrderConvertersWrapperMock, threeDS2OrderConvertersWrapperMock, basicOrderConvertersWrapperMock); + + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Order()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetOrderCodeIsNull_ShouldNotPopulateOrderCode() { + when(sourceMock.getOrderCode()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getOrderCode()).isNull(); + } + + @Test + public void populate_WhenGetDescriptionIsNull_ShouldNotPopulateDescription() { + when(sourceMock.getDescription()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetAmountIsNull_ShouldNotPopulateAmount() { + when(sourceMock.getAmount()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetInstallationIdIsNull_ShouldNotPopulateInstallationId() { + when(sourceMock.getInstallationId()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getInstallationId()).isNull(); + } + + @Test + public void populate_WhenGetOrderContentIsNull_ShouldNotPopulateOrderContent() { + when(sourceMock.getOrderContent()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetPaymentMethodMaskIsNull_ShouldNotPopulatePaymentMethodMask() { + when(sourceMock.getPaymentMethodMask()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetPaymentDetailsIsNull_ShouldNotPopulatePaymentDetails() { + when(sourceMock.getPaymentDetails()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetPayAsOrderIsNull_ShouldNotPopulatePayAsOrder() { + when(sourceMock.getPayAsOrder()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenAllPaymentRequestAreNotNull_ShouldPopulatePaymentMethodMask() { + when(sourceMock.getPaymentMethodMask()).thenReturn(paymentMethodMaskMock); + when(internalPaymentMethodMaskConverterMock.convert(paymentMethodMaskMock)).thenReturn(intPaymentMethodMaskMock); + when(sourceMock.getPaymentDetails()).thenReturn(paymentDetailsMock); + when(internalPaymentDetailsConverterMock.convert(paymentDetailsMock)).thenReturn(intPaymentDetailsMock); + when(sourceMock.getPayAsOrder()).thenReturn(payAsOrderMock); + when(internalPayAsOrderConverterMock.convert(payAsOrderMock)).thenReturn(intPayAsOrderMock); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession() + .get(0)).isEqualTo(intPaymentMethodMaskMock); + } + + @Test + public void populate_WhenPaymentDetailsAndPayAsOrderAreNotNull_ShouldPopulatePaymentDetails() { + when(sourceMock.getPaymentDetails()).thenReturn(paymentDetailsMock); + when(internalPaymentDetailsConverterMock.convert(paymentDetailsMock)).thenReturn(intPaymentDetailsMock); + when(sourceMock.getPayAsOrder()).thenReturn(payAsOrderMock); + when(internalPayAsOrderConverterMock.convert(payAsOrderMock)).thenReturn(intPayAsOrderMock); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession() + .get(0)).isEqualTo(intPaymentDetailsMock); + } + + @Test + public void populate_WhenGetShopperIsNull_ShouldNotPopulateShopper() { + when(sourceMock.getShopper()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetShippingAddressIsNull_ShouldNotPopulateShippingAddress() { + when(sourceMock.getShippingAddress()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetBillingAddressIsNull_ShouldNotPopulateBillingAddress() { + when(sourceMock.getBillingAddress()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetMandateTypeIsNull_ShouldNotPopulateMandate() { + when(sourceMock.getMandateType()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetBranchSpecificExtensionIsNull_ShouldNotPopulateBranchSpecificExtension() { + when(sourceMock.getBranchSpecificExtension()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetPaymentMethodAttributesIsNull_ShouldNotPopulatePaymentMethodAttributes() { + when(sourceMock.getPaymentMethodAttributes()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetPaymentMethodAttributesIsEmpty_ShouldNotPopulatePaymentMethodAttributes() { + when(sourceMock.getPaymentMethodAttributes()).thenReturn(Collections.emptyList()); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetPaymentMethodAttributesHasOneItem_ShouldPopulateOneItem() { + final List paymentMethodAttributes = List.of(paymentMethodAttribute1Mock); + when(sourceMock.getPaymentMethodAttributes()).thenReturn(paymentMethodAttributes); + when(internalPaymentMethodAttributeConverterMock.convert(paymentMethodAttribute1Mock)).thenReturn(intPaymentMethodAttribute1Mock); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isEqualTo(paymentMethodAttributes.size()); + } + + @Test + public void populate_WhenGetPaymentMethodAttributesHasMoreThanOneItem_ShouldPopulateAllTheItems() { + final List paymentMethodAttributes = List.of(paymentMethodAttribute1Mock, paymentMethodAttribute2Mock); + when(sourceMock.getPaymentMethodAttributes()).thenReturn(paymentMethodAttributes); + when(internalPaymentMethodAttributeConverterMock.convert(paymentMethodAttribute1Mock)).thenReturn(intPaymentMethodAttribute1Mock); + when(internalPaymentMethodAttributeConverterMock.convert(paymentMethodAttribute2Mock)).thenReturn(intPaymentMethodAttribute2Mock); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isEqualTo(paymentMethodAttributes.size()); + } + + @Test + public void populate_WhenGetStatementNarrativeIsNull_ShouldNotPopulateStatementNarrative() { + when(sourceMock.getStatementNarrative()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetEchoDataIsNull_ShouldNotPopulateEchoData() { + when(sourceMock.getEchoData()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetTokenRequestIsNull_ShouldNotPopulateTokenRequest() { + when(sourceMock.getTokenRequest()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetPaResponseIsNull_ShouldNotPopulatePaResponse() { + when(sourceMock.getPaResponse()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetSessionIsNull_ShouldNotPopulateSession() { + when(sourceMock.getSession()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetOrderLinesIsNull_ShouldNotPopulateOrderLines() { + when(sourceMock.getOrderLines()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetDynamicInteractionTypeIsNull_ShouldNotPopulateDynamicInteractionType() { + when(sourceMock.getDynamicInteractionType()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetRiskDataIsNull_ShouldNotPopulateRiskData() { + when(sourceMock.getRiskData()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetAdditional3DSDataIsNull_ShouldNotPopulateAdditional3DSData() { + when(sourceMock.getAdditional3DSData()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetFraudSightDataIsNull_ShouldNotPopulateFraudSightData() { + when(sourceMock.getFraudSightData()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetDeviceSessionIsNull_ShouldNotPopulateDeviceSession() { + when(sourceMock.getDeviceSession()).thenReturn(null); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenGetDeviceSessionIsBlank_ShouldNotPopulateDeviceSession() { + when(sourceMock.getDeviceSession()).thenReturn(Strings.EMPTY); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().size()).isZero(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getOrderCode()).thenReturn(ORDER_CODE); + when(sourceMock.getDescription()).thenReturn(DESCRIPTION); + when(sourceMock.getAmount()).thenReturn(amountMock); + when(internalAmountConverterMock.convert(amountMock)).thenReturn(intAmountMock); + when(sourceMock.getInstallationId()).thenReturn(INSTALLATION_ID); + when(sourceMock.getOrderContent()).thenReturn(ORDER_CONTENT); + when(sourceMock.getPayAsOrder()).thenReturn(payAsOrderMock); + when(internalPayAsOrderConverterMock.convert(payAsOrderMock)).thenReturn(intPayAsOrderMock); + when(sourceMock.getShopper()).thenReturn(shopperMock); + when(internalShopperConverterMock.convert(shopperMock)).thenReturn(intShopperMock); + when(sourceMock.getShippingAddress()).thenReturn(addressMock); + when(sourceMock.getBillingAddress()).thenReturn(addressMock); + when(internalAddressConverterMock.convert(addressMock)).thenReturn(intAddressMock); + when(sourceMock.getMandateType()).thenReturn(MANDATE_TYPE); + when(sourceMock.getBranchSpecificExtension()).thenReturn(branchSpecificExtensionMock); + when(internalBranchSpecificExtensionConverterMock.convert(branchSpecificExtensionMock)).thenReturn(intBranchSpecificExtensionMock); + final List paymentMethodAttributes = List.of(paymentMethodAttribute1Mock, paymentMethodAttribute2Mock); + when(sourceMock.getPaymentMethodAttributes()).thenReturn(paymentMethodAttributes); + when(internalPaymentMethodAttributeConverterMock.convert(paymentMethodAttribute1Mock)).thenReturn(intPaymentMethodAttribute1Mock); + when(internalPaymentMethodAttributeConverterMock.convert(paymentMethodAttribute2Mock)).thenReturn(intPaymentMethodAttribute2Mock); + when(sourceMock.getStatementNarrative()).thenReturn(STATEMENT_NARRATIVE); + when(sourceMock.getEchoData()).thenReturn(ECHO_DATA); + when(sourceMock.getTokenRequest()).thenReturn(tokenRequestMock); + when(internalTokenRequestConverterMock.convert(tokenRequestMock)).thenReturn(createTokenMock); + when(sourceMock.getPaResponse()).thenReturn(PA_RESPONSE); + when(sourceMock.getSession()).thenReturn(sessionMock); + when(internalSessionConverterMock.convert(sessionMock)).thenReturn(intSessionMock); + when(sourceMock.getOrderLines()).thenReturn(orderLinesMock); + when(internalOrderLinesConverterMock.convert(orderLinesMock)).thenReturn(intOrderLinesMock); + when(sourceMock.getDynamicInteractionType()).thenReturn(DynamicInteractionType.PRESENT); + when(sourceMock.getRiskData()).thenReturn(riskDataMock); + when(internalRiskDataConverterMock.convert(riskDataMock)).thenReturn(intRiskDataMock); + when(sourceMock.getAdditional3DSData()).thenReturn(additional3DSDataMock); + when(internalAdditional3DSDataConverter.convert(additional3DSDataMock)).thenReturn(intAdditional3DSDataMock); + when(sourceMock.getFraudSightData()).thenReturn(fraudSightDataMock); + when(internalFraudSightDataConverterMock.convert(fraudSightDataMock)).thenReturn(intFraudSightDataMock); + when(sourceMock.getDeviceSession()).thenReturn(DEVICE_SESSION); + + final com.worldpay.internal.model.Order target = new com.worldpay.internal.model.Order(); + testObj.populate(sourceMock, target); + + assertThat(target.getOrderCode()).isEqualTo(ORDER_CODE); + assertThat(target.getInstallationId()).isEqualTo(INSTALLATION_ID); + + final List objectList = target.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession(); + final BillingAddress intBillingAddress = objectList.stream() + .filter(BillingAddress.class::isInstance) + .map(BillingAddress.class::cast) + .findFirst() + .orElse(null); + final Mandate intMandate = objectList.stream() + .filter(Mandate.class::isInstance) + .map(Mandate.class::cast) + .findFirst() + .orElse(null); + + assertThat(objectList) + .hasSize(22) + .containsSequence(intBillingAddress, intMandate, intBranchSpecificExtensionMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PaymentDetailsPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PaymentDetailsPopulatorTest.java new file mode 100644 index 00000000..6484be03 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PaymentDetailsPopulatorTest.java @@ -0,0 +1,142 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.converters.internal.model.payment.PaymentConverterStrategy; +import com.worldpay.enums.PaymentAction; +import com.worldpay.internal.model.PaResponse; +import com.worldpay.data.PaymentDetails; +import com.worldpay.data.Session; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class PaymentDetailsPopulatorTest { + + private static final String AUTHORISE = "AUTHORISE"; + private static final String PA_RESPONSE = "paResponse"; + + @InjectMocks + private PaymentDetailsPopulator testObj; + + @Mock + private Converter internalSessionConverterMock; + @Mock + private Converter internalStoredCredentialsConverterMock; + @Mock + private PaymentConverterStrategy internalPaymentConverterStrategyMock; + + @Mock + private PaymentDetails sourceMock; + @Mock + private Payment paymentMock; + @Mock + private Object intPaymentMock; + @Mock + private Session sessionMock; + @Mock + private com.worldpay.internal.model.Session intSessionMock; + @Mock + private StoredCredentials storedCredentialsMock; + @Mock + private com.worldpay.internal.model.StoredCredentials intStoredCredentials; + + @Before + public void setUp() { + testObj = new PaymentDetailsPopulator(internalSessionConverterMock, internalStoredCredentialsConverterMock, internalPaymentConverterStrategyMock); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.PaymentDetails()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetPaymentIsNull_ShouldNotPopulatePayment() { + when(sourceMock.getPayment()).thenReturn(null); + + final com.worldpay.internal.model.PaymentDetails target = new com.worldpay.internal.model.PaymentDetails(); + testObj.populate(sourceMock, target); + + assertThat(target.getVISASSLOrECMCSSLOrBHSSSLOrNEWDAYSSLOrIKEASSLOrAMEXSSLOrELVSSLOrSEPADIRECTDEBITSSLOrDINERSSSLOrCBSSLOrAIRPLUSSSLOrUATPSSLOrCARTEBLEUESSLOrSOLOGBSSLOrLASERSSLOrDANKORTSSLOrDISCOVERSSLOrJCBSSLOrAURORESSLOrGECAPITALSSLOrHIPERCARDSSLOrSOROCREDSSLOrELOSSLOrCARNETSSLOrARGENCARDSSLOrCABALSSLOrCENCOSUDSSLOrCOOPEPLUSSSLOrCREDIMASSSLOrITALCREDSSLOrNARANJASSLOrNATIVASSLOrNEVADASSLOrNEXOSSLOrTARJETASHOPPINGSSLOrPERMANENTSIGNEDDDNLFAXOrPERMANENTSIGNEDDDGBSSLOrPERMANENTUNSIGNEDDDGBSSLOrPAYOUTBANKOrVISACHECKOUTSSLOrMASTERPASSSSLOrPAYPALEXPRESSOrGIROPAYSSLOrMAESTROSSLOrSWITCHSSLOrNCPB2BSSLOrNCPSEASONSSLOrNCPGMMSSLOrIDEALSSLOrACHSSLOrACHDIRECTDEBITSSLOrCARDSSLOrABAQOOSSSLOrAGMOSSLOrALIPAYSSLOrALIPAYMOBILESSLOrBALOTOSSLOrBANKAXESSSSLOrBANKLINKNORDEASSLOrBILLDESKSSLOrBILLINGPARTNERSSLOrCASHUSSLOrDINEROMAIL7ELEVENSSLOrDINEROMAILOXXOSSLOrDINEROMAILONLINEBTSSLOrDINEROMAILSERVIPAGSSLOrEKONTOSSLOrEPAYSSLOrEUTELLERSSLOrEWIREDKSSLOrEWIRENOSSLOrEWIRESESSLOrHALCASHSSLOrINSTADEBITSSLOrKONBINISSLOrLOBANETARSSLOrLOBANETBRSSLOrLOBANETCLSSLOrLOBANETMXSSLOrLOBANETPESSLOrLOBANETUYSSLOrMISTERCASHSSLOrMULTIBANCOSSLOrNEOSURFSSLOrPAGASSLOrPAGAVERVESSLOrPAYSAFECARDSSLOrPAYUSSLOrPLUSPAYSSLOrPOLISSLOrPOLINZSSLOrPOSTEPAYSSLOrPRZELEWYSSLOrQIWISSLOrSAFETYPAYSSLOrSIDSSLOrSKRILLSSLOrSOFORTSSLOrSOFORTCHSSLOrSPEEDCARDSSLOrSPOROPAYSSLOrSWIFFSSLOrTELEINGRESOSSLOrTICKETSURFSSLOrTRUSTLYSSLOrTRUSTPAYCZSSLOrTRUSTPAYEESSLOrTRUSTPAYSKSSLOrWEBMONEYSSLOrYANDEXMONEYSSLOrASTROPAYCARDSSLOrBANCOSANTANDERSSLOrBOLETOSSLOrBOLETOHTMLOrMONETASSLOrTODITOCARDSSLOrONLINETRANSFERBRSSLOrONLINETRANSFERMYSSLOrONLINETRANSFERTHSSLOrONLINETRANSFERVNSSLOrOPENBANKINGSSLOrSEVENELEVENMYSSLOrPETRONASSSLOrENETSSGSSLOrCASHTHSSLOrATMIDSSLOrTOKENSSLOrENETSSSLOrCHINAUNIONPAYSSLOrENVOYTRANSFERAUDBANKOrENVOYTRANSFERCADBANKOrENVOYTRANSFERCHFBANKOrENVOYTRANSFERCZKBANKOrENVOYTRANSFERDKKBANKOrENVOYTRANSFEREURBANKOrENVOYTRANSFERGBPBANKOrENVOYTRANSFERHKDBANKOrENVOYTRANSFERHUFBANKOrENVOYTRANSFERJPYBANKOrENVOYTRANSFERNOKBANKOrENVOYTRANSFERNZDBANKOrENVOYTRANSFERPLNBANKOrENVOYTRANSFERRUBBANKOrENVOYTRANSFERSEKBANKOrENVOYTRANSFERSGDBANKOrENVOYTRANSFERTHBBANKOrENVOYTRANSFERTRYBANKOrENVOYTRANSFERUSDBANKOrENVOYTRANSFERZARBANKOrTRANSFERATBANKOrTRANSFERBEBANKOrTRANSFERCHBANKOrTRANSFERDEBANKOrTRANSFERDKBANKOrTRANSFERESBANKOrTRANSFERFIBANKOrTRANSFERFRBANKOrTRANSFERGBBANKOrTRANSFERGRBANKOrTRANSFERITBANKOrTRANSFERJPBANKOrTRANSFERLUBANKOrTRANSFERNLBANKOrTRANSFERNOBANKOrTRANSFERPLBANKOrTRANSFERSEBANKOrTRANSFERUSBANKOrEMVCOTOKENSSLOrAPPLEPAYSSLOrANDROIDPAYSSLOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrKLARNASSLOrKLARNAPAYLATERSSLOrKLARNAPAYNOWSSLOrKLARNASLICEITSSLOrKLARNAV2SSLOrWECHATPAYSSLOrBILLKEYSSLOrINIPAYSSLOrWEBPAYSSLOrPBBASSLOrGPPSSLOrMERCADOPAGOSSLOrPAYPALSSLOrSVSGIFTCARDSSLOrTROYSSLOrUPISSLOrUPEXSSLOrFFDISBURSESSLOrFFMONEYTRANSFERSSLOrEPSENVSSLOrCardNumberOrExpiryDateOrCardHolderNameOrCvcOrIssueNumberOrStartDateOrPOSRequestOrCardSwipeOrCSEDATA()).isEmpty(); + } + + @Test + public void populate_WhenGetSessionIsNull_ShouldNotPopulateSession() { + when(sourceMock.getSession()).thenReturn(null); + + final com.worldpay.internal.model.PaymentDetails target = new com.worldpay.internal.model.PaymentDetails(); + testObj.populate(sourceMock, target); + + assertThat(target.getSession()).isNull(); + } + + @Test + public void populate_WhenGetPaResponseIsNull_ShouldNotPopulateInfo3DSecure() { + when(sourceMock.getPaResponse()).thenReturn(null); + + final com.worldpay.internal.model.PaymentDetails target = new com.worldpay.internal.model.PaymentDetails(); + testObj.populate(sourceMock, target); + + assertThat(target.getInfo3DSecure()).isNull(); + } + + @Test + public void populate_WhenGetStoredCredentialsIsNull_ShouldNotPopulateStoredCredentials() { + when(sourceMock.getStoredCredentials()).thenReturn(null); + + final com.worldpay.internal.model.PaymentDetails target = new com.worldpay.internal.model.PaymentDetails(); + testObj.populate(sourceMock, target); + + assertThat(target.getStoredCredentials()).isNull(); + } + + @Test + public void populate_WhenGetActionIsNull_ShouldNotPopulateAction() { + when(sourceMock.getAction()).thenReturn(null); + + final com.worldpay.internal.model.PaymentDetails target = new com.worldpay.internal.model.PaymentDetails(); + testObj.populate(sourceMock, target); + + assertThat(target.getAction()).isEqualTo(AUTHORISE); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getPayment()).thenReturn(paymentMock); + when(sourceMock.getSession()).thenReturn(sessionMock); + when(sourceMock.getPaResponse()).thenReturn(PA_RESPONSE); + when(sourceMock.getStoredCredentials()).thenReturn(storedCredentialsMock); + when(sourceMock.getAction()).thenReturn(PaymentAction.AUTHORISE); + + when(internalPaymentConverterStrategyMock.convertPayment(paymentMock)).thenReturn(intPaymentMock); + when(internalSessionConverterMock.convert(sessionMock)).thenReturn(intSessionMock); + when(internalStoredCredentialsConverterMock.convert(storedCredentialsMock)).thenReturn(intStoredCredentials); + + final com.worldpay.internal.model.PaymentDetails target = new com.worldpay.internal.model.PaymentDetails(); + testObj.populate(sourceMock, target); + + assertThat(target.getVISASSLOrECMCSSLOrBHSSSLOrNEWDAYSSLOrIKEASSLOrAMEXSSLOrELVSSLOrSEPADIRECTDEBITSSLOrDINERSSSLOrCBSSLOrAIRPLUSSSLOrUATPSSLOrCARTEBLEUESSLOrSOLOGBSSLOrLASERSSLOrDANKORTSSLOrDISCOVERSSLOrJCBSSLOrAURORESSLOrGECAPITALSSLOrHIPERCARDSSLOrSOROCREDSSLOrELOSSLOrCARNETSSLOrARGENCARDSSLOrCABALSSLOrCENCOSUDSSLOrCOOPEPLUSSSLOrCREDIMASSSLOrITALCREDSSLOrNARANJASSLOrNATIVASSLOrNEVADASSLOrNEXOSSLOrTARJETASHOPPINGSSLOrPERMANENTSIGNEDDDNLFAXOrPERMANENTSIGNEDDDGBSSLOrPERMANENTUNSIGNEDDDGBSSLOrPAYOUTBANKOrVISACHECKOUTSSLOrMASTERPASSSSLOrPAYPALEXPRESSOrGIROPAYSSLOrMAESTROSSLOrSWITCHSSLOrNCPB2BSSLOrNCPSEASONSSLOrNCPGMMSSLOrIDEALSSLOrACHSSLOrACHDIRECTDEBITSSLOrCARDSSLOrABAQOOSSSLOrAGMOSSLOrALIPAYSSLOrALIPAYMOBILESSLOrBALOTOSSLOrBANKAXESSSSLOrBANKLINKNORDEASSLOrBILLDESKSSLOrBILLINGPARTNERSSLOrCASHUSSLOrDINEROMAIL7ELEVENSSLOrDINEROMAILOXXOSSLOrDINEROMAILONLINEBTSSLOrDINEROMAILSERVIPAGSSLOrEKONTOSSLOrEPAYSSLOrEUTELLERSSLOrEWIREDKSSLOrEWIRENOSSLOrEWIRESESSLOrHALCASHSSLOrINSTADEBITSSLOrKONBINISSLOrLOBANETARSSLOrLOBANETBRSSLOrLOBANETCLSSLOrLOBANETMXSSLOrLOBANETPESSLOrLOBANETUYSSLOrMISTERCASHSSLOrMULTIBANCOSSLOrNEOSURFSSLOrPAGASSLOrPAGAVERVESSLOrPAYSAFECARDSSLOrPAYUSSLOrPLUSPAYSSLOrPOLISSLOrPOLINZSSLOrPOSTEPAYSSLOrPRZELEWYSSLOrQIWISSLOrSAFETYPAYSSLOrSIDSSLOrSKRILLSSLOrSOFORTSSLOrSOFORTCHSSLOrSPEEDCARDSSLOrSPOROPAYSSLOrSWIFFSSLOrTELEINGRESOSSLOrTICKETSURFSSLOrTRUSTLYSSLOrTRUSTPAYCZSSLOrTRUSTPAYEESSLOrTRUSTPAYSKSSLOrWEBMONEYSSLOrYANDEXMONEYSSLOrASTROPAYCARDSSLOrBANCOSANTANDERSSLOrBOLETOSSLOrBOLETOHTMLOrMONETASSLOrTODITOCARDSSLOrONLINETRANSFERBRSSLOrONLINETRANSFERMYSSLOrONLINETRANSFERTHSSLOrONLINETRANSFERVNSSLOrOPENBANKINGSSLOrSEVENELEVENMYSSLOrPETRONASSSLOrENETSSGSSLOrCASHTHSSLOrATMIDSSLOrTOKENSSLOrENETSSSLOrCHINAUNIONPAYSSLOrENVOYTRANSFERAUDBANKOrENVOYTRANSFERCADBANKOrENVOYTRANSFERCHFBANKOrENVOYTRANSFERCZKBANKOrENVOYTRANSFERDKKBANKOrENVOYTRANSFEREURBANKOrENVOYTRANSFERGBPBANKOrENVOYTRANSFERHKDBANKOrENVOYTRANSFERHUFBANKOrENVOYTRANSFERJPYBANKOrENVOYTRANSFERNOKBANKOrENVOYTRANSFERNZDBANKOrENVOYTRANSFERPLNBANKOrENVOYTRANSFERRUBBANKOrENVOYTRANSFERSEKBANKOrENVOYTRANSFERSGDBANKOrENVOYTRANSFERTHBBANKOrENVOYTRANSFERTRYBANKOrENVOYTRANSFERUSDBANKOrENVOYTRANSFERZARBANKOrTRANSFERATBANKOrTRANSFERBEBANKOrTRANSFERCHBANKOrTRANSFERDEBANKOrTRANSFERDKBANKOrTRANSFERESBANKOrTRANSFERFIBANKOrTRANSFERFRBANKOrTRANSFERGBBANKOrTRANSFERGRBANKOrTRANSFERITBANKOrTRANSFERJPBANKOrTRANSFERLUBANKOrTRANSFERNLBANKOrTRANSFERNOBANKOrTRANSFERPLBANKOrTRANSFERSEBANKOrTRANSFERUSBANKOrEMVCOTOKENSSLOrAPPLEPAYSSLOrANDROIDPAYSSLOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrKLARNASSLOrKLARNAPAYLATERSSLOrKLARNAPAYNOWSSLOrKLARNASLICEITSSLOrKLARNAV2SSLOrWECHATPAYSSLOrBILLKEYSSLOrINIPAYSSLOrWEBPAYSSLOrPBBASSLOrGPPSSLOrMERCADOPAGOSSLOrPAYPALSSLOrSVSGIFTCARDSSLOrTROYSSLOrUPISSLOrUPEXSSLOrFFDISBURSESSLOrFFMONEYTRANSFERSSLOrEPSENVSSLOrCardNumberOrExpiryDateOrCardHolderNameOrCvcOrIssueNumberOrStartDateOrPOSRequestOrCardSwipeOrCSEDATA().get(0)) + .isEqualTo(intPaymentMock); + assertThat(target.getSession()).isEqualTo(intSessionMock); + assertThat(((PaResponse) target.getInfo3DSecure().getPaResponseOrMpiProviderOrMpiResponseOrAttemptedAuthenticationOrCompletedAuthenticationOrThreeDSVersionOrMerchantNameOrXidOrDsTransactionIdOrCavvOrEci().get(0)).getvalue()) + .isEqualTo(PA_RESPONSE); + assertThat(target.getStoredCredentials()).isEqualTo(intStoredCredentials); + assertThat(target.getAction()).isEqualTo(PaymentAction.AUTHORISE.name()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PaymentMethodAttributePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PaymentMethodAttributePopulatorTest.java new file mode 100644 index 00000000..fe7afed7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PaymentMethodAttributePopulatorTest.java @@ -0,0 +1,51 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.PaymentMethodAttribute; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class PaymentMethodAttributePopulatorTest { + + private static final String ATTR_NAME = "attrName"; + private static final String ATTR_VALUE = "attrValue"; + private static final String PAYMENT_METHOD = "paymentMethod"; + + @InjectMocks + private PaymentMethodAttributePopulator testObj; + + @Mock + private PaymentMethodAttribute sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowException() { + testObj.populate(null, new com.worldpay.internal.model.PaymentMethodAttribute()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulatePaymentMethodAttribute() { + when(sourceMock.getAttrName()).thenReturn(ATTR_NAME); + when(sourceMock.getAttrValue()).thenReturn(ATTR_VALUE); + when(sourceMock.getPaymentMethod()).thenReturn(PAYMENT_METHOD); + + final com.worldpay.internal.model.PaymentMethodAttribute targetMock = new com.worldpay.internal.model.PaymentMethodAttribute(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAttrName()).isEqualTo(ATTR_NAME); + assertThat(targetMock.getAttrValue()).isEqualTo(ATTR_VALUE); + assertThat(targetMock.getPaymentMethod()).isEqualTo(PAYMENT_METHOD); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PaymentMethodMaskPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PaymentMethodMaskPopulatorTest.java new file mode 100644 index 00000000..0f52a6a1 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PaymentMethodMaskPopulatorTest.java @@ -0,0 +1,88 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.PaymentMethodMask; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.service.model.payment.PaymentType; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class PaymentMethodMaskPopulatorTest { + + @InjectMocks + private PaymentMethodMaskPopulator testObj; + + @Mock + private Converter internalStoredCredentialsConverterMock; + + @Mock + private PaymentMethodMask sourceMock; + @Mock + private StoredCredentials storedCredentialsMock; + @Mock + private com.worldpay.internal.model.StoredCredentials intStoredCredentialsMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.PaymentMethodMask()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetStoredCredentialsIsNull_ShouldNotPopulateStoredCredentials() { + when(sourceMock.getStoredCredentials()).thenReturn(null); + + final com.worldpay.internal.model.PaymentMethodMask target = new com.worldpay.internal.model.PaymentMethodMask(); + testObj.populate(sourceMock, target); + + assertThat(target.getStoredCredentialsOrIncludeOrExclude()).isEmpty(); + } + + @Test + public void populate_WhenGetExcludesIsNull_ShouldNotPopulateExcludes() { + when(sourceMock.getExcludes()).thenReturn(null); + + final com.worldpay.internal.model.PaymentMethodMask target = new com.worldpay.internal.model.PaymentMethodMask(); + testObj.populate(sourceMock, target); + + assertThat(target.getStoredCredentialsOrIncludeOrExclude()).isEmpty(); + } + + @Test + public void populate_WhenGetIncludesIsNull_ShouldNotPopulateIncludes() { + when(sourceMock.getIncludes()).thenReturn(null); + + final com.worldpay.internal.model.PaymentMethodMask target = new com.worldpay.internal.model.PaymentMethodMask(); + testObj.populate(sourceMock, target); + + assertThat(target.getStoredCredentialsOrIncludeOrExclude()).isEmpty(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getStoredCredentials()).thenReturn(storedCredentialsMock); + when(internalStoredCredentialsConverterMock.convert(storedCredentialsMock)).thenReturn(intStoredCredentialsMock); + when(sourceMock.getExcludes()).thenReturn(List.of(PaymentType.ONLINE.getMethodCode(), PaymentType.EWIRESE.getMethodCode())); + when(sourceMock.getIncludes()).thenReturn(List.of(PaymentType.ALIPAY.getMethodCode(), PaymentType.LOBANET_PE.getMethodCode())); + + final com.worldpay.internal.model.PaymentMethodMask target = new com.worldpay.internal.model.PaymentMethodMask(); + testObj.populate(sourceMock, target); + + assertThat(target.getStoredCredentialsOrIncludeOrExclude()).hasSize(5); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PurchasePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PurchasePopulatorTest.java new file mode 100644 index 00000000..38eb4372 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/PurchasePopulatorTest.java @@ -0,0 +1,168 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Amount; +import com.worldpay.data.Date; +import com.worldpay.data.Item; +import com.worldpay.data.Purchase; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class PurchasePopulatorTest { + + private static final String INVOICE_REFERENCE_NUMBER = "invoiceReferenceNumber"; + private static final String CUSTOMER_REFERENCE = "customerReference"; + private static final String CARD_ACCEPTOR_TAX_ID = "cardAcceptorTaxId"; + private static final String COUNTRY_CODE = "countryCode"; + private static final String POSTAL_CODE = "postalCode"; + + @InjectMocks + private PurchasePopulator testObj; + + @Mock + private Converter internalItemConverterMock; + @Mock + private Converter internalDateConverterMock; + @Mock + private Converter internalAmountConverterMock; + + @Mock + private Purchase sourceMock; + @Mock + private Item itemMock; + @Mock + private com.worldpay.internal.model.Item intItemMock; + @Mock + private Date dateMock; + @Mock + private com.worldpay.internal.model.Date intDateMock; + @Mock + private Amount salesTaxMock, discountAmountMock, shippingAmountMock, dutyAmountMock; + @Mock + private com.worldpay.internal.model.Amount intSalesTaxMock, intDiscountAmountMock, intShippingAmountMock, intDutyAmountMock; + + @Before + public void setUp() { + testObj = new PurchasePopulator(internalItemConverterMock, internalDateConverterMock, internalAmountConverterMock); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Purchase()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenOrderDateIsNull_ShouldNotPopulateOrderDate() { + when(sourceMock.getOrderDate()).thenReturn(null); + + final com.worldpay.internal.model.Purchase target = new com.worldpay.internal.model.Purchase(); + testObj.populate(sourceMock, target); + + assertThat(target.getOrderDate()).isNull(); + } + + @Test + public void populate_WhenSalesTaxIsNull_ShouldNotPopulateSalesTax() { + when(sourceMock.getSalesTax()).thenReturn(null); + + final com.worldpay.internal.model.Purchase target = new com.worldpay.internal.model.Purchase(); + testObj.populate(sourceMock, target); + + assertThat(target.getSalesTax()).isNull(); + } + + @Test + public void populate_WhenDiscountAmountIsNull_ShouldNotPopulateDiscountAmount() { + when(sourceMock.getDiscountAmount()).thenReturn(null); + + final com.worldpay.internal.model.Purchase target = new com.worldpay.internal.model.Purchase(); + testObj.populate(sourceMock, target); + + assertThat(target.getDiscountAmount()).isNull(); + } + + @Test + public void populate_WhenShippingAmountIsNull_ShouldNotPopulateShippingAmount() { + when(sourceMock.getShippingAmount()).thenReturn(null); + + final com.worldpay.internal.model.Purchase target = new com.worldpay.internal.model.Purchase(); + testObj.populate(sourceMock, target); + + assertThat(target.getShippingAmount()).isNull(); + } + + @Test + public void populate_WhenDutyAmountIsNull_ShouldNotPopulateDutyAmount() { + when(sourceMock.getDutyAmount()).thenReturn(null); + + final com.worldpay.internal.model.Purchase target = new com.worldpay.internal.model.Purchase(); + testObj.populate(sourceMock, target); + + assertThat(target.getDutyAmount()).isNull(); + } + + @Test + public void populate_WhenGetItemIsNull_ShouldNotPopulateItem() { + when(sourceMock.getItem()).thenReturn(null); + + final com.worldpay.internal.model.Purchase target = new com.worldpay.internal.model.Purchase(); + testObj.populate(sourceMock, target); + + assertThat(target.getItem()).isEmpty(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(internalItemConverterMock.convertAll(List.of(itemMock))).thenReturn(List.of(intItemMock)); + when(internalDateConverterMock.convert(dateMock)).thenReturn(intDateMock); + when(internalAmountConverterMock.convert(salesTaxMock)).thenReturn(intSalesTaxMock); + when(internalAmountConverterMock.convert(discountAmountMock)).thenReturn(intDiscountAmountMock); + when(internalAmountConverterMock.convert(shippingAmountMock)).thenReturn(intShippingAmountMock); + when(internalAmountConverterMock.convert(dutyAmountMock)).thenReturn(intDutyAmountMock); + when(sourceMock.getInvoiceReferenceNumber()).thenReturn(INVOICE_REFERENCE_NUMBER); + when(sourceMock.getCustomerReference()).thenReturn(CUSTOMER_REFERENCE); + when(sourceMock.getCardAcceptorTaxId()).thenReturn(CARD_ACCEPTOR_TAX_ID); + when(sourceMock.getDestinationCountryCode()).thenReturn(COUNTRY_CODE); + when(sourceMock.getDestinationPostalCode()).thenReturn(POSTAL_CODE); + when(sourceMock.isTaxExempt()).thenReturn(Boolean.TRUE); + when(sourceMock.getItem()).thenReturn(List.of(itemMock)); + when(sourceMock.getOrderDate()).thenReturn(dateMock); + when(sourceMock.getSalesTax()).thenReturn(salesTaxMock); + when(sourceMock.getDiscountAmount()).thenReturn(discountAmountMock); + when(sourceMock.getShippingAmount()).thenReturn(shippingAmountMock); + when(sourceMock.getDutyAmount()).thenReturn(dutyAmountMock); + + final com.worldpay.internal.model.Purchase target = new com.worldpay.internal.model.Purchase(); + testObj.populate(sourceMock, target); + + assertThat(target.getInvoiceReferenceNumber()).isEqualTo(INVOICE_REFERENCE_NUMBER); + assertThat(target.getCustomerReference()).isEqualTo(CUSTOMER_REFERENCE); + assertThat(target.getCardAcceptorTaxId()).isEqualTo(CARD_ACCEPTOR_TAX_ID); + assertThat(target.getDestinationCountryCode()).isEqualTo(COUNTRY_CODE); + assertThat(target.getDestinationPostalCode()).isEqualTo(POSTAL_CODE); + assertThat(target.getTaxExempt()).isEqualTo(Boolean.TRUE.toString()); + assertThat(target.getItem()).isEqualTo(List.of(intItemMock)); + assertThat(target.getOrderDate().getDate()).isEqualTo(intDateMock); + assertThat(target.getSalesTax().getAmount()).isEqualTo(intSalesTaxMock); + assertThat(target.getDiscountAmount().getAmount()).isEqualTo(intDiscountAmountMock); + assertThat(target.getShippingAmount().getAmount()).isEqualTo(intShippingAmountMock); + assertThat(target.getDutyAmount().getAmount()).isEqualTo(intDutyAmountMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ReferencePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ReferencePopulatorTest.java new file mode 100644 index 00000000..0ad8e973 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ReferencePopulatorTest.java @@ -0,0 +1,50 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.internal.model.Reference; +import com.worldpay.data.LineItemReference; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class ReferencePopulatorTest { + + private static final String ID = "id"; + private static final String VALUE = "value"; + + @InjectMocks + private ReferencePopulator testObj; + + @Mock + private LineItemReference sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowException() { + testObj.populate(null, new Reference()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populator_ShouldPopulateReference() { + when(sourceMock.getId()).thenReturn(ID); + when(sourceMock.getValue()).thenReturn(VALUE); + + final Reference targetMock = new Reference(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getId()).isEqualTo(ID); + assertThat(targetMock.getvalue()).isEqualTo(VALUE); + } +} + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/SessionPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/SessionPopulatorTest.java new file mode 100644 index 00000000..82127aa4 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/SessionPopulatorTest.java @@ -0,0 +1,68 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Session; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class SessionPopulatorTest { + + private static final String SHOPPER_IP_ADDRESS = "shopperIPAddress"; + private static final String ID = "ID"; + + @InjectMocks + private SessionPopulator testObj; + + @Mock + private Session sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Session()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetShopperIPAddressIsNull_ShouldNotPopulateShopperIPAddress() { + when(sourceMock.getShopperIPAddress()).thenReturn(null); + + final com.worldpay.internal.model.Session target = new com.worldpay.internal.model.Session(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperIPAddress()).isNull(); + } + + @Test + public void populate_WhenGetIdIsNull_ShouldNotPopulateId() { + when(sourceMock.getId()).thenReturn(null); + + final com.worldpay.internal.model.Session target = new com.worldpay.internal.model.Session(); + testObj.populate(sourceMock, target); + + assertThat(target.getId()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getShopperIPAddress()).thenReturn(SHOPPER_IP_ADDRESS); + when(sourceMock.getId()).thenReturn(ID); + + final com.worldpay.internal.model.Session target = new com.worldpay.internal.model.Session(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperIPAddress()).isEqualTo(SHOPPER_IP_ADDRESS); + assertThat(target.getId()).isEqualTo(ID); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ShopperFieldsPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ShopperFieldsPopulatorTest.java new file mode 100644 index 00000000..d13ab402 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ShopperFieldsPopulatorTest.java @@ -0,0 +1,96 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Address; +import com.worldpay.data.Date; +import com.worldpay.data.ShopperFields; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class ShopperFieldsPopulatorTest { + + private static final String SHOPPER_NAME = "shopperName"; + private static final String SHOPPER_ID = "shopperID"; + + @InjectMocks + private ShopperFieldsPopulator testObj; + + @Mock + private Converter dateConverterMock; + @Mock + private Converter addressConverterMock; + + @Mock + private ShopperFields sourceMock; + @Mock + private Address addressMock; + @Mock + private com.worldpay.internal.model.Address intAddressMock; + @Mock + private Date dateMock; + @Mock + private com.worldpay.internal.model.Date intDateMock; + + @Before + public void setUp() { + testObj = new ShopperFieldsPopulator(dateConverterMock, addressConverterMock); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.ShopperFields()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenBirthDateIsNull_ShouldNotPopulateBirthDate() { + when(sourceMock.getBirthDate()).thenReturn(null); + + final com.worldpay.internal.model.ShopperFields target = new com.worldpay.internal.model.ShopperFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getBirthDate()).isNull(); + } + + @Test + public void populate_WhenShopperAddressIsNull_ShouldNotPopulateShopperAddress() { + when(sourceMock.getShopperAddress()).thenReturn(null); + + final com.worldpay.internal.model.ShopperFields target = new com.worldpay.internal.model.ShopperFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperAddress()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getShopperName()).thenReturn(SHOPPER_NAME); + when(sourceMock.getShopperId()).thenReturn(SHOPPER_ID); + when(sourceMock.getBirthDate()).thenReturn(dateMock); + when(dateConverterMock.convert(dateMock)).thenReturn(intDateMock); + when(sourceMock.getShopperAddress()).thenReturn(addressMock); + when(addressConverterMock.convert(addressMock)).thenReturn(intAddressMock); + + final com.worldpay.internal.model.ShopperFields target = new com.worldpay.internal.model.ShopperFields(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperName()).isEqualTo(SHOPPER_NAME); + assertThat(target.getShopperId()).isEqualTo(SHOPPER_ID); + assertThat(target.getBirthDate().getDate()).isEqualTo(intDateMock); + assertThat(target.getShopperAddress().getAddress()).isEqualTo(intAddressMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ShopperPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ShopperPopulatorTest.java new file mode 100644 index 00000000..3d8d58c1 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/ShopperPopulatorTest.java @@ -0,0 +1,116 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.data.Browser; +import com.worldpay.data.Session; +import com.worldpay.data.Shopper; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class ShopperPopulatorTest { + + private static final String EMAIL = "email"; + private static final String AUTHENTICATED_SHOPPER_ID = "authenticatedShopperID"; + + @InjectMocks + private ShopperPopulator testObj; + + @Mock + private Converter internalBrowserConverterMock; + @Mock + private Converter internalSessionConverterMock; + + @Mock + private Shopper sourceMock; + @Mock + private Browser browserMock; + @Mock + private com.worldpay.internal.model.Browser intBrowserMock; + @Mock + private Session sessionMock; + @Mock + private com.worldpay.internal.model.Session intSessionMock; + + @Before + public void setUp() { + testObj = new ShopperPopulator(internalBrowserConverterMock, internalSessionConverterMock); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Shopper()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetShopperEmailAddressIsNull_ShouldNotPopulateShopperEmailAddress() { + when(sourceMock.getShopperEmailAddress()).thenReturn(null); + + final com.worldpay.internal.model.Shopper target = new com.worldpay.internal.model.Shopper(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperEmailAddress()).isNull(); + } + + @Test + public void populate_WhenGetAuthenticatedShopperIDIsNull_ShouldNotPopulateAuthenticatedShopperID() { + when(sourceMock.getAuthenticatedShopperID()).thenReturn(null); + + final com.worldpay.internal.model.Shopper target = new com.worldpay.internal.model.Shopper(); + testObj.populate(sourceMock, target); + + assertThat(target.getAuthenticatedShopperID()).isNull(); + } + + @Test + public void populate_WhenGetBrowserIsNull_ShouldNotPopulateBrowser() { + when(sourceMock.getBrowser()).thenReturn(null); + + final com.worldpay.internal.model.Shopper target = new com.worldpay.internal.model.Shopper(); + testObj.populate(sourceMock, target); + + assertThat(target.getBrowser()).isNull(); + } + + @Test + public void populate_WhenGetSessionIsNull_ShouldNotPopulateSession() { + when(sourceMock.getSession()).thenReturn(null); + + final com.worldpay.internal.model.Shopper target = new com.worldpay.internal.model.Shopper(); + testObj.populate(sourceMock, target); + + assertThat(target.getSession()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getShopperEmailAddress()).thenReturn(EMAIL); + when(sourceMock.getAuthenticatedShopperID()).thenReturn(AUTHENTICATED_SHOPPER_ID); + when(sourceMock.getBrowser()).thenReturn(browserMock); + when(internalBrowserConverterMock.convert(browserMock)).thenReturn(intBrowserMock); + when(sourceMock.getSession()).thenReturn(sessionMock); + when(internalSessionConverterMock.convert(sessionMock)).thenReturn(intSessionMock); + + final com.worldpay.internal.model.Shopper target = new com.worldpay.internal.model.Shopper(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperEmailAddress()).isEqualTo(EMAIL); + assertThat(target.getAuthenticatedShopperID().getvalue()).isEqualTo(AUTHENTICATED_SHOPPER_ID); + assertThat(target.getBrowser()).isEqualTo(intBrowserMock); + assertThat(target.getSession()).isEqualTo(intSessionMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/StoredCredentialsPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/StoredCredentialsPopulatorTest.java new file mode 100644 index 00000000..f1fec67f --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/StoredCredentialsPopulatorTest.java @@ -0,0 +1,61 @@ +package com.worldpay.converters.populators.internal.model; + +import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; +import com.worldpay.enums.payment.storedCredentials.Usage; +import com.worldpay.data.payment.StoredCredentials; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class StoredCredentialsPopulatorTest { + + private static final String SCHEME_TRANSACTION_ID = "SchemeTransactionId"; + + @InjectMocks + private StoredCredentialsPopulator testObj; + + @Mock + private StoredCredentials sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.StoredCredentials()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetUsageIsNull_ShouldNotPopulateUsage() { + when(sourceMock.getUsage()).thenReturn(null); + + final com.worldpay.internal.model.StoredCredentials target = new com.worldpay.internal.model.StoredCredentials(); + testObj.populate(sourceMock, target); + + assertThat(target.getUsage()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getMerchantInitiatedReason()).thenReturn(MerchantInitiatedReason.DELAYED); + when(sourceMock.getUsage()).thenReturn(Usage.FIRST); + when(sourceMock.getSchemeTransactionIdentifier()).thenReturn(SCHEME_TRANSACTION_ID); + + final com.worldpay.internal.model.StoredCredentials target = new com.worldpay.internal.model.StoredCredentials(); + testObj.populate(sourceMock, target); + + assertThat(target.getMerchantInitiatedReason()).isEqualTo(MerchantInitiatedReason.DELAYED.name()); + assertThat(target.getUsage()).isEqualTo(Usage.FIRST.name()); + assertThat(target.getSchemeTransactionIdentifier()).isEqualTo(SCHEME_TRANSACTION_ID); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/applepay/ApplePayPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/applepay/ApplePayPopulatorTest.java new file mode 100644 index 00000000..f172a67a --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/applepay/ApplePayPopulatorTest.java @@ -0,0 +1,78 @@ +package com.worldpay.converters.populators.internal.model.applepay; + +import com.worldpay.internal.model.APPLEPAYSSL; +import com.worldpay.data.applepay.ApplePay; +import com.worldpay.data.applepay.Header; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class ApplePayPopulatorTest { + + private static final String DATA = "data"; + private static final String SIGNATURE = "signature"; + private static final String TOKEN_REQUESTOR_ID = "tokenRequestorID"; + private static final String VERSION = "version"; + + @InjectMocks + private ApplePayPopulator testObj; + + @Mock + private Converter internalHeaderConverter; + + @Mock + private ApplePay sourceMock; + @Mock + private Header headerMock; + @Mock + private com.worldpay.internal.model.Header internalHeaderMock; + + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new APPLEPAYSSL()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenHeaderIsNull_ShouldNotPopulateInternalHeader() { + when(sourceMock.getHeader()).thenReturn(null); + + final APPLEPAYSSL targetMock = new APPLEPAYSSL(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getHeader()).isNull(); + } + + @Test + public void populate_ShouldPopulateApplePay() { + when(sourceMock.getHeader()).thenReturn(headerMock); + when(sourceMock.getData()).thenReturn(DATA); + when(sourceMock.getSignature()).thenReturn(SIGNATURE); + when(sourceMock.getTokenRequestorID()).thenReturn(TOKEN_REQUESTOR_ID); + when(sourceMock.getVersion()).thenReturn(VERSION); + when(internalHeaderConverter.convert(headerMock)).thenReturn(internalHeaderMock); + + final APPLEPAYSSL targetMock = new APPLEPAYSSL(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getHeader()).isEqualTo(internalHeaderMock); + assertThat(targetMock.getData()).isEqualTo(DATA); + assertThat(targetMock.getSignature()).isEqualTo(SIGNATURE); + assertThat(targetMock.getTokenRequestorID()).isEqualTo(TOKEN_REQUESTOR_ID); + assertThat(targetMock.getVersion()).isEqualTo(VERSION); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/applepay/HeaderPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/applepay/HeaderPopulatorTest.java new file mode 100644 index 00000000..406f9e44 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/applepay/HeaderPopulatorTest.java @@ -0,0 +1,54 @@ +package com.worldpay.converters.populators.internal.model.applepay; + +import com.worldpay.data.applepay.Header; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class HeaderPopulatorTest { + + private static final String APPLICATION_DATA = "applicationData"; + private static final String EPHEMERAL_PUBLIC_KEY = "EphemeralPublicKey"; + private static final String PUBLIC_KEY_HASH = "publicKeyHash"; + private static final String TRANSACTION_ID = "transactionId"; + + @InjectMocks + private HeaderPopulator testObj; + + @Mock + private Header sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Header()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateHeader() { + when(sourceMock.getApplicationData()).thenReturn(APPLICATION_DATA); + when(sourceMock.getEphemeralPublicKey()).thenReturn(EPHEMERAL_PUBLIC_KEY); + when(sourceMock.getPublicKeyHash()).thenReturn(PUBLIC_KEY_HASH); + when(sourceMock.getTransactionId()).thenReturn(TRANSACTION_ID); + + final com.worldpay.internal.model.Header targetMock = new com.worldpay.internal.model.Header(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getApplicationData()).isEqualTo(APPLICATION_DATA); + assertThat(targetMock.getEphemeralPublicKey()).isEqualTo(EPHEMERAL_PUBLIC_KEY); + assertThat(targetMock.getPublicKeyHash()).isEqualTo(PUBLIC_KEY_HASH); + assertThat(targetMock.getTransactionId()).isEqualTo(TRANSACTION_ID); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayLaterPaymentPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayLaterPaymentPopulatorTest.java new file mode 100644 index 00000000..651ac483 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayLaterPaymentPopulatorTest.java @@ -0,0 +1,61 @@ +package com.worldpay.converters.populators.internal.model.klarna; + +import com.worldpay.internal.model.KLARNAPAYLATERSSL; +import com.worldpay.data.klarna.KlarnaPayment; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class KlarnaPayLaterPaymentPopulatorTest { + + private static final String SHOPPER_COUNTRY_CODE = "shopperCountryCode"; + private static final String LOCALE = "locale"; + private static final String SUCCESS_URL = "SuccessURL"; + private static final String PENDING_URL = "pendingURL"; + private static final String FAILURE_URL = "FailureURL"; + private static final String CANCEL_URL = "cancelURL"; + + @InjectMocks + private KlarnaPayLaterPaymentPopulator testObj; + + @Mock + private KlarnaPayment sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new KLARNAPAYLATERSSL()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateKlarnaPayment() { + when(sourceMock.getShopperCountryCode()).thenReturn(SHOPPER_COUNTRY_CODE); + when(sourceMock.getLocale()).thenReturn(LOCALE); + when(sourceMock.getSuccessURL()).thenReturn(SUCCESS_URL); + when(sourceMock.getPendingURL()).thenReturn(PENDING_URL); + when(sourceMock.getFailureURL()).thenReturn(FAILURE_URL); + when(sourceMock.getCancelURL()).thenReturn(CANCEL_URL); + + final KLARNAPAYLATERSSL targetMock = new KLARNAPAYLATERSSL(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getShopperCountryCode()).isEqualTo(SHOPPER_COUNTRY_CODE); + assertThat(targetMock.getLocale()).isEqualTo(LOCALE); + assertThat(targetMock.getSuccessURL()).isEqualTo(SUCCESS_URL); + assertThat(targetMock.getFailureURL()).isEqualTo(FAILURE_URL); + assertThat(targetMock.getCancelURL()).isEqualTo(CANCEL_URL); + assertThat(targetMock.getPendingURL()).isEqualTo(PENDING_URL); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayNowPaymentPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayNowPaymentPopulatorTest.java new file mode 100644 index 00000000..0c409f33 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaPayNowPaymentPopulatorTest.java @@ -0,0 +1,61 @@ +package com.worldpay.converters.populators.internal.model.klarna; + +import com.worldpay.internal.model.KLARNAPAYNOWSSL; +import com.worldpay.data.klarna.KlarnaPayment; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class KlarnaPayNowPaymentPopulatorTest { + + private static final String SHOPPER_COUNTRY_CODE = "shopperCountryCode"; + private static final String LOCALE = "locale"; + private static final String SUCCESS_URL = "SuccessURL"; + private static final String PENDING_URL = "pendingURL"; + private static final String FAILURE_URL = "FailureURL"; + private static final String CANCEL_URL = "cancelURL"; + + @InjectMocks + private KlarnaPayNowPaymentPopulator testObj; + + @Mock + private KlarnaPayment sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new KLARNAPAYNOWSSL()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateKlarnaPayment() { + when(sourceMock.getShopperCountryCode()).thenReturn(SHOPPER_COUNTRY_CODE); + when(sourceMock.getLocale()).thenReturn(LOCALE); + when(sourceMock.getSuccessURL()).thenReturn(SUCCESS_URL); + when(sourceMock.getPendingURL()).thenReturn(PENDING_URL); + when(sourceMock.getFailureURL()).thenReturn(FAILURE_URL); + when(sourceMock.getCancelURL()).thenReturn(CANCEL_URL); + + final KLARNAPAYNOWSSL targetMock = new KLARNAPAYNOWSSL(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getShopperCountryCode()).isEqualTo(SHOPPER_COUNTRY_CODE); + assertThat(targetMock.getLocale()).isEqualTo(LOCALE); + assertThat(targetMock.getSuccessURL()).isEqualTo(SUCCESS_URL); + assertThat(targetMock.getFailureURL()).isEqualTo(FAILURE_URL); + assertThat(targetMock.getCancelURL()).isEqualTo(CANCEL_URL); + assertThat(targetMock.getPendingURL()).isEqualTo(PENDING_URL); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaPaymentPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaPaymentPopulatorTest.java new file mode 100644 index 00000000..805eaabf --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaPaymentPopulatorTest.java @@ -0,0 +1,68 @@ +package com.worldpay.converters.populators.internal.model.klarna; + +import com.worldpay.internal.model.KLARNASSL; +import com.worldpay.data.klarna.KlarnaMerchantUrls; +import com.worldpay.data.klarna.KlarnaPayment; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class KlarnaPaymentPopulatorTest { + + private static final String EXTRA_MERCHANT_DATA = "extraMerchantData"; + private static final String PURCHASE_COUNTRY = "purchaseCountry"; + private static final String SHOPPER_LOCALE = "shopperLocale"; + + @InjectMocks + private KlarnaPaymentPopulator testObj; + + @Mock + private KlarnaPayment sourceMock; + @Mock + private KlarnaMerchantUrls klarnaMerchantUrlsMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNullA_ShouldThrowAnException() { + testObj.populate(null, new KLARNASSL()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenKlarnaMerchantUrlsIsNull_ShouldNotPopulateMerchantUrls() { + when(sourceMock.getMerchantUrls()).thenReturn(null); + + final KLARNASSL targetMock = new KLARNASSL(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getMerchantUrls()).isNull(); + } + + @Test + public void populate_ShouldPopulateKlarnaPayment() { + when(sourceMock.getPurchaseCountry()).thenReturn(PURCHASE_COUNTRY); + when(sourceMock.getShopperLocale()).thenReturn(SHOPPER_LOCALE); + when(sourceMock.getExtraMerchantData()).thenReturn(EXTRA_MERCHANT_DATA); + when(sourceMock.getMerchantUrls()).thenReturn(klarnaMerchantUrlsMock); + + final KLARNASSL targetMock = new KLARNASSL(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getExtraMerchantData()).isEqualTo(EXTRA_MERCHANT_DATA); + assertThat(targetMock.getPurchaseCountry()).isEqualTo(PURCHASE_COUNTRY); + assertThat(targetMock.getShopperLocale()).isEqualTo(SHOPPER_LOCALE); + assertThat(targetMock.getMerchantUrls().getCheckoutURL()).isEqualTo(klarnaMerchantUrlsMock.getCheckoutURL()); + assertThat(targetMock.getMerchantUrls().getConfirmationURL()).isEqualTo(klarnaMerchantUrlsMock.getConfirmationURL()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaSliceItPaymentPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaSliceItPaymentPopulatorTest.java new file mode 100644 index 00000000..4d2017c0 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/klarna/KlarnaSliceItPaymentPopulatorTest.java @@ -0,0 +1,61 @@ +package com.worldpay.converters.populators.internal.model.klarna; + +import com.worldpay.internal.model.KLARNASLICEITSSL; +import com.worldpay.data.klarna.KlarnaPayment; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class KlarnaSliceItPaymentPopulatorTest { + + private static final String SHOPPER_COUNTRY_CODE = "shopperCountryCode"; + private static final String LOCALE = "locale"; + private static final String SUCCESS_URL = "SuccessURL"; + private static final String PENDING_URL = "pendingURL"; + private static final String FAILURE_URL = "FailureURL"; + private static final String CANCEL_URL = "cancelURL"; + + @InjectMocks + private KlarnaSliceItPaymentPopulator testObj; + + @Mock + private KlarnaPayment sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new KLARNASLICEITSSL()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateKlarnaPayment() { + when(sourceMock.getShopperCountryCode()).thenReturn(SHOPPER_COUNTRY_CODE); + when(sourceMock.getLocale()).thenReturn(LOCALE); + when(sourceMock.getSuccessURL()).thenReturn(SUCCESS_URL); + when(sourceMock.getPendingURL()).thenReturn(PENDING_URL); + when(sourceMock.getFailureURL()).thenReturn(FAILURE_URL); + when(sourceMock.getCancelURL()).thenReturn(CANCEL_URL); + + final KLARNASLICEITSSL targetMock = new KLARNASLICEITSSL(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getShopperCountryCode()).isEqualTo(SHOPPER_COUNTRY_CODE); + assertThat(targetMock.getLocale()).isEqualTo(LOCALE); + assertThat(targetMock.getSuccessURL()).isEqualTo(SUCCESS_URL); + assertThat(targetMock.getFailureURL()).isEqualTo(FAILURE_URL); + assertThat(targetMock.getCancelURL()).isEqualTo(CANCEL_URL); + assertThat(targetMock.getPendingURL()).isEqualTo(PENDING_URL); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/CsePaymentPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/CsePaymentPopulatorTest.java new file mode 100644 index 00000000..d860027f --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/CsePaymentPopulatorTest.java @@ -0,0 +1,68 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.internal.model.CSEDATA; +import com.worldpay.data.Address; +import com.worldpay.data.payment.Cse; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class CsePaymentPopulatorTest { + + private static final String ENCRYPTED_DATA = "encryptedData"; + + @InjectMocks + private CsePaymentPopulator testObj; + + @Mock + private Converter internalAddressConverterMock; + + @Mock + private Cse sourceMock; + @Mock + private Address addressMock; + @Mock + private com.worldpay.internal.model.Address internalAddressMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new CSEDATA()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenAddressIsNull_ShouldNotPopulateCardAddress() { + when(sourceMock.getAddress()).thenReturn(null); + + final CSEDATA targetMock = new CSEDATA(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getCardAddress()).isNull(); + } + + @Test + public void populate_ShouldPopulateCsePayment() { + when(sourceMock.getAddress()).thenReturn(addressMock); + when(sourceMock.getEncryptedData()).thenReturn(ENCRYPTED_DATA); + when(internalAddressConverterMock.convert(addressMock)).thenReturn(internalAddressMock); + + final CSEDATA targetMock = new CSEDATA(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getCardAddress().getAddress()).isEqualTo(internalAddressMock); + assertThat(targetMock.getEncryptedData().getvalue()).isEqualTo(ENCRYPTED_DATA); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/GooglePaymentPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/GooglePaymentPopulatorTest.java new file mode 100644 index 00000000..f27ffbb1 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/GooglePaymentPopulatorTest.java @@ -0,0 +1,82 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.internal.model.PAYWITHGOOGLESSL; +import com.worldpay.data.payment.PayWithGoogleSSL; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class GooglePaymentPopulatorTest { + + private static final String PROTOCOL_VERSION = "protocolVersion"; + private static final String SIGNATURE = "signature"; + private static final String SIGNED_MESSAGE = "signedMessage"; + + @InjectMocks + private GooglePaymentPopulator testObj; + + @Mock + private PayWithGoogleSSL sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.PAYWITHGOOGLESSL()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetProtocolVersionIsNull_ShouldNotPopulateProtocolVersion() { + when(sourceMock.getProtocolVersion()).thenReturn(null); + + final PAYWITHGOOGLESSL target = new PAYWITHGOOGLESSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getProtocolVersion()).isNull(); + } + + @Test + public void populate_WhenGetSignatureIsNull_ShouldNotPopulateSignature() { + when(sourceMock.getSignature()).thenReturn(null); + + final PAYWITHGOOGLESSL target = new PAYWITHGOOGLESSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getSignature()).isNull(); + } + + @Test + public void populate_WhenGetSignedMessageIsNull_ShouldNotPopulateSignedMessage() { + when(sourceMock.getSignedMessage()).thenReturn(null); + + final PAYWITHGOOGLESSL target = new PAYWITHGOOGLESSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getSignedMessage()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getProtocolVersion()).thenReturn(PROTOCOL_VERSION); + when(sourceMock.getSignature()).thenReturn(SIGNATURE); + when(sourceMock.getSignedMessage()).thenReturn(SIGNED_MESSAGE); + + final PAYWITHGOOGLESSL target = new PAYWITHGOOGLESSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getProtocolVersion()).isEqualTo(PROTOCOL_VERSION); + assertThat(target.getSignature()).isEqualTo(SIGNATURE); + assertThat(target.getSignedMessage()).isEqualTo(SIGNED_MESSAGE); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/IdealPaymentPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/IdealPaymentPopulatorTest.java new file mode 100644 index 00000000..8a9fa022 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/IdealPaymentPopulatorTest.java @@ -0,0 +1,108 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.internal.model.IDEALSSL; +import com.worldpay.data.payment.AlternativeShopperBankCodePayment; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class IdealPaymentPopulatorTest { + + private static final String SHOPPER_BANK = "shopperBank"; + private static final String SUCCESS_URL = "successURL"; + private static final String FAILURE_URL = "failureURL"; + private static final String CANCEL_URL = "cancelURL"; + private static final String PENDING_URL = "pendingURL"; + + @InjectMocks + private IdealPaymentPopulator testObj; + + @Mock + private AlternativeShopperBankCodePayment sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.IDEALSSL()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetShopperBankCodeIsNull_ShouldNotPopulateShopperBankCode() { + when(sourceMock.getShopperBankCode()).thenReturn(null); + + final IDEALSSL target = new IDEALSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperBankCode()).isNull(); + } + + @Test + public void populate_WhenGetSuccessURLIsNull_ShouldNotPopulateSuccessURL() { + when(sourceMock.getSuccessURL()).thenReturn(null); + + final IDEALSSL target = new IDEALSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getSuccessURL()).isNull(); + } + + @Test + public void populate_WhenGetFailureURLIsNull_ShouldNotPopulateFailureURL() { + when(sourceMock.getFailureURL()).thenReturn(null); + + final IDEALSSL target = new IDEALSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getFailureURL()).isNull(); + } + + @Test + public void populate_WhenGetCancelURLIsNull_ShouldNotPopulateCancelURL() { + when(sourceMock.getCancelURL()).thenReturn(null); + + final IDEALSSL target = new IDEALSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getCancelURL()).isNull(); + } + + @Test + public void populate_WhenGetPendingURLIsNull_ShouldNotPopulatePendingURL() { + when(sourceMock.getPendingURL()).thenReturn(null); + + final IDEALSSL target = new IDEALSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getPendingURL()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getShopperBankCode()).thenReturn(SHOPPER_BANK); + when(sourceMock.getSuccessURL()).thenReturn(SUCCESS_URL); + when(sourceMock.getFailureURL()).thenReturn(FAILURE_URL); + when(sourceMock.getCancelURL()).thenReturn(CANCEL_URL); + when(sourceMock.getPendingURL()).thenReturn(PENDING_URL); + + final IDEALSSL target = new IDEALSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getShopperBankCode()).isEqualTo(SHOPPER_BANK); + assertThat(target.getSuccessURL()).isEqualTo(SUCCESS_URL); + assertThat(target.getFailureURL()).isEqualTo(FAILURE_URL); + assertThat(target.getCancelURL()).isEqualTo(CANCEL_URL); + assertThat(target.getPendingURL()).isEqualTo(PENDING_URL); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/PayAsOrderPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/PayAsOrderPopulatorTest.java new file mode 100644 index 00000000..b86e7330 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/PayAsOrderPopulatorTest.java @@ -0,0 +1,103 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.data.Amount; +import com.worldpay.data.payment.PayAsOrder; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class PayAsOrderPopulatorTest { + + private static final String MERCHANT_CODE = "merchantCode"; + private static final String ORDER_CODE = "orderCode"; + private static final String CVC = "cvc"; + + @InjectMocks + private PayAsOrderPopulator testObj; + + @Mock + private Converter internalAmountConverterMock; + + @Mock + private PayAsOrder sourceMock; + @Mock + private Amount amountMock; + @Mock + private com.worldpay.internal.model.Amount intAmountMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.PayAsOrder()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetOriginalMerchantCodeIsNull_ShouldNotPopulateMerchantCode() { + when(sourceMock.getOriginalMerchantCode()).thenReturn(null); + + final com.worldpay.internal.model.PayAsOrder targetMock = new com.worldpay.internal.model.PayAsOrder(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getMerchantCode()).isNull(); + } + + @Test + public void populate_WhenGetOriginalOrderCodeIsNull_ShouldNotPopulateOrderCode() { + when(sourceMock.getOriginalOrderCode()).thenReturn(null); + + final com.worldpay.internal.model.PayAsOrder targetMock = new com.worldpay.internal.model.PayAsOrder(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getOrderCode()).isNull(); + } + + @Test + public void populate_WhenGetAmountIsNull_ShouldNotPopulateAmount() { + when(sourceMock.getAmount()).thenReturn(null); + + final com.worldpay.internal.model.PayAsOrder targetMock = new com.worldpay.internal.model.PayAsOrder(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAmount()).isNull(); + } + + @Test + public void populate_WhenGetCvcIsNull_ShouldNotPopulateCvc() { + when(sourceMock.getCvc()).thenReturn(null); + + final com.worldpay.internal.model.PayAsOrder targetMock = new com.worldpay.internal.model.PayAsOrder(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getCvc()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getOriginalMerchantCode()).thenReturn(MERCHANT_CODE); + when(sourceMock.getOriginalOrderCode()).thenReturn(ORDER_CODE); + when(sourceMock.getAmount()).thenReturn(amountMock); + when(internalAmountConverterMock.convert(amountMock)).thenReturn(intAmountMock); + when(sourceMock.getCvc()).thenReturn(CVC); + + final com.worldpay.internal.model.PayAsOrder targetMock = new com.worldpay.internal.model.PayAsOrder(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getMerchantCode()).isEqualTo(MERCHANT_CODE); + assertThat(targetMock.getOrderCode()).isEqualTo(ORDER_CODE); + assertThat(targetMock.getAmount()).isEqualTo(intAmountMock); + assertThat(targetMock.getCvc()).isEqualTo(CVC); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/StoredCredentialsPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/StoredCredentialsPopulatorTest.java new file mode 100644 index 00000000..265c5eda --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/payment/StoredCredentialsPopulatorTest.java @@ -0,0 +1,61 @@ +package com.worldpay.converters.populators.internal.model.payment; + +import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; +import com.worldpay.enums.payment.storedCredentials.Usage; +import com.worldpay.data.payment.StoredCredentials; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class StoredCredentialsPopulatorTest { + + private static final String SCHEME_TRANSACTION_ID = "SchemeTransactionId"; + + @InjectMocks + private StoredCredentialsPopulator testObj; + + @Mock + private StoredCredentials sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.StoredCredentials()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetUsageIsNull_ShouldNotPopulateUsage() { + when(sourceMock.getUsage()).thenReturn(null); + + final com.worldpay.internal.model.StoredCredentials target = new com.worldpay.internal.model.StoredCredentials(); + testObj.populate(sourceMock, target); + + assertThat(target.getUsage()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getMerchantInitiatedReason()).thenReturn(MerchantInitiatedReason.DELAYED); + when(sourceMock.getUsage()).thenReturn(Usage.FIRST); + when(sourceMock.getSchemeTransactionIdentifier()).thenReturn(SCHEME_TRANSACTION_ID); + + final com.worldpay.internal.model.StoredCredentials target = new com.worldpay.internal.model.StoredCredentials(); + testObj.populate(sourceMock, target); + + assertThat(target.getMerchantInitiatedReason()).isEqualTo(MerchantInitiatedReason.DELAYED.name()); + assertThat(target.getUsage()).isEqualTo(Usage.FIRST.name()); + assertThat(target.getSchemeTransactionIdentifier()).isEqualTo(SCHEME_TRANSACTION_ID); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/Additional3DSDataPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/Additional3DSDataPopulatorTest.java new file mode 100644 index 00000000..9b646663 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/Additional3DSDataPopulatorTest.java @@ -0,0 +1,54 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.threedsecureflexenums.ChallengePreferenceEnum; +import com.worldpay.threedsecureflexenums.ChallengeWindowSizeEnum; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class Additional3DSDataPopulatorTest { + + private static final String DF_REFERENCE_ID = "dfReferenceId"; + private static final String CHALLENGE_MANDATED = "challengeMandated"; + private static final String FULL_PAGE = "fullPage"; + + @InjectMocks + private Additional3DSDataPopulator testObj; + + @Mock + private Additional3DSData sourceMock; + + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.Additional3DSData()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateAdditional3DSData() { + when(sourceMock.getChallengePreference()).thenReturn(CHALLENGE_MANDATED); + when(sourceMock.getChallengeWindowSize()).thenReturn(FULL_PAGE); + when(sourceMock.getDfReferenceId()).thenReturn(DF_REFERENCE_ID); + + final com.worldpay.internal.model.Additional3DSData targetMock = new com.worldpay.internal.model.Additional3DSData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getChallengePreference()).isEqualTo(ChallengePreferenceEnum.CHALLENGE_MANDATED.toString()); + assertThat(targetMock.getChallengeWindowSize()).isEqualTo(ChallengeWindowSizeEnum.FULL_PAGE.toString()); + assertThat(targetMock.getDfReferenceId()).isEqualTo(DF_REFERENCE_ID); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/AuthenticationRiskDataPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/AuthenticationRiskDataPopulatorTest.java new file mode 100644 index 00000000..cc64779b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/AuthenticationRiskDataPopulatorTest.java @@ -0,0 +1,69 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.data.Date; +import com.worldpay.data.threeds2.AuthenticationRiskData; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class AuthenticationRiskDataPopulatorTest { + + private static final String AUTHENTICATION_METHOD = "authenticationMethod"; + + @InjectMocks + private AuthenticationRiskDataPopulator testObj; + + @Mock + private Converter internalDateConverterMock; + + @Mock + private AuthenticationRiskData sourceMock; + @Mock + private Date authenticationTimestampMock; + @Mock + private com.worldpay.internal.model.Date internalDateMock; + + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.AuthenticationRiskData()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateAuthenticationRiskData() { + when(sourceMock.getAuthenticationMethod()).thenReturn(AUTHENTICATION_METHOD); + when(sourceMock.getAuthenticationTimestamp()).thenReturn(authenticationTimestampMock); + when(internalDateConverterMock.convert(authenticationTimestampMock)).thenReturn(internalDateMock); + + final com.worldpay.internal.model.AuthenticationRiskData targetMock = new com.worldpay.internal.model.AuthenticationRiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAuthenticationMethod()).isEqualTo(AUTHENTICATION_METHOD); + assertThat(targetMock.getAuthenticationTimestamp().getDate()).isEqualTo(internalDateMock); + } + + @Test + public void populate_WhenDateIsNull_ShouldNotPopulateInternalDate() { + when(sourceMock.getAuthenticationTimestamp()).thenReturn(null); + when(internalDateConverterMock.convert(sourceMock.getAuthenticationTimestamp())).thenReturn(internalDateMock); + + final com.worldpay.internal.model.AuthenticationRiskData targetMock = new com.worldpay.internal.model.AuthenticationRiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAuthenticationTimestamp()).isNull(); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/RiskDataPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/RiskDataPopulatorTest.java new file mode 100644 index 00000000..879ac815 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/RiskDataPopulatorTest.java @@ -0,0 +1,113 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.data.threeds2.AuthenticationRiskData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.threeds2.ShopperAccountRiskData; +import com.worldpay.data.threeds2.TransactionRiskData; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.*; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class RiskDataPopulatorTest { + + @Spy + @InjectMocks + private RiskDataPopulator testObj; + + @Mock + private Converter internalAuthenticationRiskDataConverterMock; + @Mock + private Converter internalShopperAccountRiskDataConverterMock; + @Mock + private Converter internalTransactionRiskDataConverterMock; + + @Mock + private RiskData sourceMock; + @Mock + private com.worldpay.internal.model.AuthenticationRiskData internalAuthenticationRiskDataMock; + @Mock + private com.worldpay.internal.model.ShopperAccountRiskData internalShopperAccountRiskDataMock; + @Mock + private com.worldpay.internal.model.TransactionRiskData internalTransactionRiskDataMock; + @Mock + private AuthenticationRiskData authenticationRiskDataMock; + @Mock + private ShopperAccountRiskData shopperAccountRiskData; + @Mock + private TransactionRiskData transactionRiskData; + + @Before + public void setup() { + testObj = new RiskDataPopulator(internalAuthenticationRiskDataConverterMock, internalShopperAccountRiskDataConverterMock, internalTransactionRiskDataConverterMock); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.RiskData()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenAuthenticationRiskDataIsNull_ShouldNotPopulate() { + when(sourceMock.getAuthenticationRiskData()).thenReturn(null); + when(internalAuthenticationRiskDataConverterMock.convert(sourceMock.getAuthenticationRiskData())).thenReturn(null); + + final com.worldpay.internal.model.RiskData targetMock = new com.worldpay.internal.model.RiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAuthenticationRiskData()).isNull(); + } + + @Test + public void populate_WhenAuthenticationShopperAccountRiskDataIsNull_ShouldNotPopulate() { + when(sourceMock.getShopperAccountRiskData()).thenReturn(null); + when(internalShopperAccountRiskDataConverterMock.convert(sourceMock.getShopperAccountRiskData())).thenReturn(null); + + final com.worldpay.internal.model.RiskData targetMock = new com.worldpay.internal.model.RiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getShopperAccountRiskData()).isNull(); + } + + @Test + public void populate_WhenAuthenticationTransactionRiskDataIsNull_ShouldNotPopulate() { + when(sourceMock.getTransactionRiskData()).thenReturn(null); + when(internalTransactionRiskDataConverterMock.convert(sourceMock.getTransactionRiskData())).thenReturn(null); + + final com.worldpay.internal.model.RiskData targetMock = new com.worldpay.internal.model.RiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getTransactionRiskData()).isNull(); + } + + @Test + public void populate_ShouldPopulatRiskData() { + when(sourceMock.getAuthenticationRiskData()).thenReturn(authenticationRiskDataMock); + when(sourceMock.getShopperAccountRiskData()).thenReturn(shopperAccountRiskData); + when(sourceMock.getTransactionRiskData()).thenReturn(transactionRiskData); + given(internalAuthenticationRiskDataConverterMock.convert(authenticationRiskDataMock)).willReturn(internalAuthenticationRiskDataMock); + given(internalShopperAccountRiskDataConverterMock.convert(shopperAccountRiskData)).willReturn(internalShopperAccountRiskDataMock); + given(internalTransactionRiskDataConverterMock.convert(transactionRiskData)).willReturn(internalTransactionRiskDataMock); + + final com.worldpay.internal.model.RiskData targetMock = new com.worldpay.internal.model.RiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAuthenticationRiskData()).isEqualTo(internalAuthenticationRiskDataMock); + assertThat(targetMock.getShopperAccountRiskData()).isEqualTo(internalShopperAccountRiskDataMock); + assertThat(targetMock.getTransactionRiskData()).isEqualTo(internalTransactionRiskDataMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/ShopperAccountRiskDataPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/ShopperAccountRiskDataPopulatorTest.java new file mode 100644 index 00000000..a3bca992 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/ShopperAccountRiskDataPopulatorTest.java @@ -0,0 +1,110 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.data.Date; +import com.worldpay.data.threeds2.ShopperAccountRiskData; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class ShopperAccountRiskDataPopulatorTest { + + private static final String TRANSACTIONS_ATTEMPTED_LAST_DAY = "transactionsAttemptedLastDay"; + private static final String TRANSACTIONS_ATTEMPTED_LAST_YEAR = "transactionsAttemptedLastYear"; + private static final String PREVIOUS_SUSPICIOUS_ACTIVITY = "previousSuspiciousActivity"; + private static final String ADD_CARD_ATTEMPTS_LAST_DAY = "addCardAttemptsLastDay"; + private static final String SHIPPING_NAME_MATCHES_ACCOUNT_NAME = "shippingNameMatchesAccountName"; + private static final String SHOPPER_ACCOUNT_AGE_INDICATOR = "shopperAccountAgeIndicator"; + private static final String SHOPPER_ACCOUNT_CHANGE_INDICATOR = "shopperAccountChangeIndicator"; + private static final String SHOPPER_ACCOUNT_PASSWORD_CHANGE_INDICATOR = "shopperAccountPasswordChangeIndicator"; + private static final String SHOPPER_ACCOUNT_SHIPPING_ADDRESS_USAGE_INDICATOR = "shopperAccountShippingAddressUsageIndicator"; + private static final String SHOPPER_ACCOUNT_PAYMENT_ACCOUNT_INDICATOR = "shopperAccountPaymentAccountIndicator"; + + @InjectMocks + private ShopperAccountRiskDataPopulator testObj; + + @Mock + private Converter internalDateConverterMock; + + @Mock + private ShopperAccountRiskData sourceMock; + @Mock + private Date date1Mock, date2Mock, date3Mock, date4Mock, date5Mock; + @Mock + private com.worldpay.internal.model.Date internalDate1Mock, internalDate2Mock, internalDate3Mock, internalDate4Mock, internalDate5Mock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.ShopperAccountRiskData()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateShopperAccountRiskData() { + when(sourceMock.getTransactionsAttemptedLastDay()).thenReturn(TRANSACTIONS_ATTEMPTED_LAST_DAY); + when(sourceMock.getTransactionsAttemptedLastYear()).thenReturn(TRANSACTIONS_ATTEMPTED_LAST_YEAR); + when(sourceMock.getPreviousSuspiciousActivity()).thenReturn(PREVIOUS_SUSPICIOUS_ACTIVITY); + when(sourceMock.getAddCardAttemptsLastDay()).thenReturn(ADD_CARD_ATTEMPTS_LAST_DAY); + when(sourceMock.getShippingNameMatchesAccountName()).thenReturn(SHIPPING_NAME_MATCHES_ACCOUNT_NAME); + when(sourceMock.getShopperAccountAgeIndicator()).thenReturn(SHOPPER_ACCOUNT_AGE_INDICATOR); + when(sourceMock.getShopperAccountChangeIndicator()).thenReturn(SHOPPER_ACCOUNT_CHANGE_INDICATOR); + when(sourceMock.getShopperAccountPasswordChangeIndicator()).thenReturn(SHOPPER_ACCOUNT_PASSWORD_CHANGE_INDICATOR); + when(sourceMock.getShopperAccountShippingAddressUsageIndicator()).thenReturn(SHOPPER_ACCOUNT_SHIPPING_ADDRESS_USAGE_INDICATOR); + when(sourceMock.getShopperAccountPaymentAccountIndicator()).thenReturn(SHOPPER_ACCOUNT_PAYMENT_ACCOUNT_INDICATOR); + + when(sourceMock.getShopperAccountCreationDate()).thenReturn(date1Mock); + when(sourceMock.getShopperAccountShippingAddressFirstUseDate()).thenReturn(date2Mock); + when(sourceMock.getShopperAccountModificationDate()).thenReturn(date3Mock); + when(sourceMock.getShopperAccountPaymentAccountFirstUseDate()).thenReturn(date4Mock); + when(sourceMock.getShopperAccountPasswordChangeDate()).thenReturn(date5Mock); + + when(internalDateConverterMock.convert(date1Mock)).thenReturn(internalDate1Mock); + when(internalDateConverterMock.convert(date2Mock)).thenReturn(internalDate2Mock); + when(internalDateConverterMock.convert(date3Mock)).thenReturn(internalDate3Mock); + when(internalDateConverterMock.convert(date4Mock)).thenReturn(internalDate4Mock); + when(internalDateConverterMock.convert(date5Mock)).thenReturn(internalDate5Mock); + + final com.worldpay.internal.model.ShopperAccountRiskData targetMock = new com.worldpay.internal.model.ShopperAccountRiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getTransactionsAttemptedLastDay()).isEqualTo(TRANSACTIONS_ATTEMPTED_LAST_DAY); + assertThat(targetMock.getTransactionsAttemptedLastYear()).isEqualTo(TRANSACTIONS_ATTEMPTED_LAST_YEAR); + assertThat(targetMock.getPreviousSuspiciousActivity()).isEqualTo(PREVIOUS_SUSPICIOUS_ACTIVITY); + assertThat(targetMock.getAddCardAttemptsLastDay()).isEqualTo(ADD_CARD_ATTEMPTS_LAST_DAY); + assertThat(targetMock.getShippingNameMatchesAccountName()).isEqualTo(SHIPPING_NAME_MATCHES_ACCOUNT_NAME); + assertThat(targetMock.getShopperAccountAgeIndicator()).isEqualTo(SHOPPER_ACCOUNT_AGE_INDICATOR); + assertThat(targetMock.getShopperAccountChangeIndicator()).isEqualTo(SHOPPER_ACCOUNT_CHANGE_INDICATOR); + assertThat(targetMock.getShopperAccountPasswordChangeIndicator()).isEqualTo(SHOPPER_ACCOUNT_PASSWORD_CHANGE_INDICATOR); + assertThat(targetMock.getShopperAccountShippingAddressUsageIndicator()).isEqualTo(SHOPPER_ACCOUNT_SHIPPING_ADDRESS_USAGE_INDICATOR); + assertThat(targetMock.getShopperAccountPaymentAccountIndicator()).isEqualTo(SHOPPER_ACCOUNT_PAYMENT_ACCOUNT_INDICATOR); + + assertThat(targetMock.getShopperAccountCreationDate().getDate()).isEqualTo(internalDate1Mock); + assertThat(targetMock.getShopperAccountShippingAddressFirstUseDate().getDate()).isEqualTo(internalDate2Mock); + assertThat(targetMock.getShopperAccountModificationDate().getDate()).isEqualTo(internalDate3Mock); + assertThat(targetMock.getShopperAccountPaymentAccountFirstUseDate().getDate()).isEqualTo(internalDate4Mock); + assertThat(targetMock.getShopperAccountPasswordChangeDate().getDate()).isEqualTo(internalDate5Mock); + } + + @Test + public void populate_WhenDateIsNull_ShouldNotPopulateInternalDate() { + when(sourceMock.getShopperAccountCreationDate()).thenReturn(null); + when(internalDateConverterMock.convert(date1Mock)).thenReturn(internalDate1Mock); + + final com.worldpay.internal.model.ShopperAccountRiskData targetMock = new com.worldpay.internal.model.ShopperAccountRiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getShopperAccountCreationDate()).isNull(); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataGiftCardAmountPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataGiftCardAmountPopulatorTest.java new file mode 100644 index 00000000..8e84456f --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataGiftCardAmountPopulatorTest.java @@ -0,0 +1,64 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.data.Amount; +import com.worldpay.data.threeds2.TransactionRiskDataGiftCardAmount; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class TransactionRiskDataGiftCardAmountPopulatorTest { + + @InjectMocks + private TransactionRiskDataGiftCardAmountPopulator testObj; + + @Mock + private Converter internalAmountConverterMock; + + @Mock + private TransactionRiskDataGiftCardAmount sourceMock; + @Mock + private Amount amountMock; + @Mock + private com.worldpay.internal.model.Amount internalAmountMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.TransactionRiskDataGiftCardAmount()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateTransactionRiskDataGiftCardAmount() { + when(sourceMock.getAmount()).thenReturn(amountMock); + when(internalAmountConverterMock.convert(amountMock)).thenReturn(internalAmountMock); + + final com.worldpay.internal.model.TransactionRiskDataGiftCardAmount targetMock = new com.worldpay.internal.model.TransactionRiskDataGiftCardAmount(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAmount()).isEqualTo(internalAmountMock); + } + + @Test + public void populate_WhenAmountIsNull_ShouldNotPopulateAmount() { + when(sourceMock.getAmount()).thenReturn(null); + when(internalAmountConverterMock.convert(sourceMock.getAmount())).thenReturn(internalAmountMock); + + final com.worldpay.internal.model.TransactionRiskDataGiftCardAmount targetMock = new com.worldpay.internal.model.TransactionRiskDataGiftCardAmount(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAmount()).isNull(); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataPopulatorTest.java new file mode 100644 index 00000000..3896409a --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/threeds2/TransactionRiskDataPopulatorTest.java @@ -0,0 +1,111 @@ +package com.worldpay.converters.populators.internal.model.threeds2; + +import com.worldpay.data.Date; +import com.worldpay.data.threeds2.TransactionRiskData; +import com.worldpay.data.threeds2.TransactionRiskDataGiftCardAmount; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class TransactionRiskDataPopulatorTest { + + private static final String DELIVERY_EMAIL_ADDRESS = "deliveryEmailAddress"; + private static final String DELIVERY_TIMEFRAME = "deliveryTimeframe"; + private static final String GIFT_CARD_COUNT = "giftCardCount"; + private static final String PRE_ORDER_PURCHASE = "preOrderPurchase"; + private static final String REORDERING_PREVIOUS_PURCHASES = "reorderingPreviousPurchases"; + private static final String SHIPPING_METHOD = "shippingMethod"; + + @InjectMocks + private TransactionRiskDataPopulator testObj; + + @Mock + private Converter internalDateConverterMock; + @Mock + private Converter internalTransactionRiskDataGiftCardAmountConverterMock; + + @Mock + private TransactionRiskData sourceMock; + @Mock + private Date dateMock; + @Mock + private com.worldpay.internal.model.Date internalDateMock; + @Mock + private TransactionRiskDataGiftCardAmount amountMock; + @Mock + private com.worldpay.internal.model.TransactionRiskDataGiftCardAmount internalAmountMock; + + @Before + public void setup() { + testObj = new TransactionRiskDataPopulator(internalDateConverterMock, internalTransactionRiskDataGiftCardAmountConverterMock); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.TransactionRiskData()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenDateIsNull_ShouldNotPopulateInternalDate() { + when(sourceMock.getTransactionRiskDataPreOrderDate()).thenReturn(null); + when(internalDateConverterMock.convert(sourceMock.getTransactionRiskDataPreOrderDate())).thenReturn(internalDateMock); + + final com.worldpay.internal.model.TransactionRiskData targetMock = new com.worldpay.internal.model.TransactionRiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getTransactionRiskDataPreOrderDate()).isNull(); + } + + @Test + public void populate_WhenAmountIsNull_ShouldNotPopulateAmount() { + when(sourceMock.getTransactionRiskDataGiftCardAmount()).thenReturn(null); + when(internalTransactionRiskDataGiftCardAmountConverterMock.convert(sourceMock.getTransactionRiskDataGiftCardAmount())).thenReturn(internalAmountMock); + + final com.worldpay.internal.model.TransactionRiskData targetMock = new com.worldpay.internal.model.TransactionRiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getTransactionRiskDataGiftCardAmount()).isNull(); + } + + @Test + public void populate_ShouldPopulateTransactionRiskData() { + when(sourceMock.getDeliveryEmailAddress()).thenReturn(DELIVERY_EMAIL_ADDRESS); + when(sourceMock.getDeliveryTimeframe()).thenReturn(DELIVERY_TIMEFRAME); + when(sourceMock.getGiftCardCount()).thenReturn(GIFT_CARD_COUNT); + when(sourceMock.getPreOrderPurchase()).thenReturn(PRE_ORDER_PURCHASE); + when(sourceMock.getReorderingPreviousPurchases()).thenReturn(REORDERING_PREVIOUS_PURCHASES); + when(sourceMock.getShippingMethod()).thenReturn(SHIPPING_METHOD); + when(sourceMock.getTransactionRiskDataPreOrderDate()).thenReturn(dateMock); + when(sourceMock.getTransactionRiskDataGiftCardAmount()).thenReturn(amountMock); + + when(internalDateConverterMock.convert(dateMock)).thenReturn(internalDateMock); + when(internalTransactionRiskDataGiftCardAmountConverterMock.convert(amountMock)).thenReturn(internalAmountMock); + + final com.worldpay.internal.model.TransactionRiskData targetMock = new com.worldpay.internal.model.TransactionRiskData(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getDeliveryEmailAddress()).isEqualTo(DELIVERY_EMAIL_ADDRESS); + assertThat(targetMock.getDeliveryTimeframe()).isEqualTo(DELIVERY_TIMEFRAME); + assertThat(targetMock.getGiftCardCount()).isEqualTo(GIFT_CARD_COUNT); + assertThat(targetMock.getPreOrderPurchase()).isEqualTo(PRE_ORDER_PURCHASE); + assertThat(targetMock.getReorderingPreviousPurchases()).isEqualTo(REORDERING_PREVIOUS_PURCHASES); + assertThat(targetMock.getShippingMethod()).isEqualTo(SHIPPING_METHOD); + assertThat(targetMock.getTransactionRiskDataPreOrderDate().getDate()).isEqualTo(internalDateMock); + assertThat(targetMock.getTransactionRiskDataGiftCardAmount()).isEqualTo(internalAmountMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/CardDetailsPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/CardDetailsPopulatorTest.java new file mode 100644 index 00000000..3d6448a2 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/CardDetailsPopulatorTest.java @@ -0,0 +1,108 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.data.Address; +import com.worldpay.data.Date; +import com.worldpay.data.token.CardDetails; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class CardDetailsPopulatorTest { + + private static final String CARD_BRAND = "cardBrand"; + private static final String CARD_HOLDER_NAME = "cardHolderName"; + private static final String CARD_NUMBER = "cardNumber"; + private static final String CARD_SUB_BRAND = "cardSubBrand"; + private static final String CVC_NUMBER = "cvcNumber"; + private static final String ISSUER_COUNTRY_CODE = "issuerCountryCode"; + + @InjectMocks + private CardDetailsPopulator testObj; + + @Mock + private Converter internalAddressConverterMock; + @Mock + private Converter internalDateConverterMock; + + @Mock + private CardDetails sourceMock; + @Mock + private Address cardAddresMock; + @Mock + private Date expiryDateMock; + @Mock + private com.worldpay.internal.model.Address internalAddresMock; + @Mock + private com.worldpay.internal.model.Date internalDateMock; + + @Before + public void setup() { + testObj = new CardDetailsPopulator(internalAddressConverterMock, internalDateConverterMock); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.CardDetails()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenDateIsNull_ShouldNotPopulateInternalDate() { + when(sourceMock.getExpiryDate()).thenReturn(null); + when(internalDateConverterMock.convert(sourceMock.getExpiryDate())).thenReturn(internalDateMock); + + final com.worldpay.internal.model.CardDetails targetMock = new com.worldpay.internal.model.CardDetails(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getExpiryDate()).isNull(); + } + + @Test + public void populate_WhenAddressIsNull_ShouldNotPopulateInternalAddress() { + when(sourceMock.getCardAddress()).thenReturn(null); + when(internalAddressConverterMock.convert(sourceMock.getCardAddress())).thenReturn(internalAddresMock); + + final com.worldpay.internal.model.CardDetails targetMock = new com.worldpay.internal.model.CardDetails(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getCardAddress()).isNull(); + } + + @Test + public void populate_ShouldPopulateCardDetails() { + when(sourceMock.getCardAddress()).thenReturn(cardAddresMock); + when(sourceMock.getCardBrand()).thenReturn(CARD_BRAND); + when(sourceMock.getCardHolderName()).thenReturn(CARD_HOLDER_NAME); + when(sourceMock.getCardNumber()).thenReturn(CARD_NUMBER); + when(sourceMock.getCardSubBrand()).thenReturn(CARD_SUB_BRAND); + when(sourceMock.getCvcNumber()).thenReturn(CVC_NUMBER); + when(sourceMock.getExpiryDate()).thenReturn(expiryDateMock); + when(sourceMock.getIssuerCountryCode()).thenReturn(ISSUER_COUNTRY_CODE); + + when(internalAddressConverterMock.convert(cardAddresMock)).thenReturn(internalAddresMock); + when(internalDateConverterMock.convert(expiryDateMock)).thenReturn(internalDateMock); + + final com.worldpay.internal.model.CardDetails targetMock = new com.worldpay.internal.model.CardDetails(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getCardAddress().getAddress()).isEqualTo(internalAddresMock); + assertThat(targetMock.getCardHolderName().getvalue()).isEqualTo(CARD_HOLDER_NAME); + assertThat(targetMock.getCvc().getvalue()).isEqualTo(CVC_NUMBER); + assertThat(targetMock.getDerived().getObfuscatedPAN()).isEqualTo(CARD_NUMBER); + assertThat(targetMock.getExpiryDate().getDate()).isEqualTo(internalDateMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/PaymentTokenCreatePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/PaymentTokenCreatePopulatorTest.java new file mode 100644 index 00000000..739cd5dc --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/PaymentTokenCreatePopulatorTest.java @@ -0,0 +1,126 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.converters.internal.model.payment.PaymentConverterStrategy; +import com.worldpay.internal.model.CreateToken; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.token.CardTokenRequest; +import com.worldpay.data.token.TokenRequest; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class PaymentTokenCreatePopulatorTest { + + private static final String SHOPPER_ID = "shopperId"; + + @InjectMocks + private PaymentTokenCreatePopulator testObj; + + @Mock + private Converter internalTokenRequestConverter; + @Mock + private Converter internalStoredCredentialsConverter; + @Mock + private PaymentConverterStrategy internalPaymentConverterStrategy; + + @Mock + private CardTokenRequest sourceMock; + @Mock + private StoredCredentials storeCredentialsMock; + @Mock + private com.worldpay.internal.model.StoredCredentials intStoreCredentialsMock; + @Mock + private TokenRequest tokenRequestMock; + @Mock + private CreateToken createTokenMock; + @Mock + private Payment paymentMock; + @Mock + private Object intPaymentMock; + + @Before + public void setup() { + testObj = new PaymentTokenCreatePopulator(internalTokenRequestConverter, internalStoredCredentialsConverter, internalPaymentConverterStrategy); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.PaymentTokenCreate()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetAuthenticatedShopperIdIsNull_ShouldNotPopulateAuthenticatedShopperId() { + when(sourceMock.getAuthenticatedShopperId()).thenReturn(null); + + final com.worldpay.internal.model.PaymentTokenCreate targetMock = new com.worldpay.internal.model.PaymentTokenCreate(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAuthenticatedShopperID()).isNull(); + } + + @Test + public void populate_WhenGetTokenRequestIsNull_ShouldNotPopulateTokenRequest() { + when(sourceMock.getTokenRequest()).thenReturn(null); + + final com.worldpay.internal.model.PaymentTokenCreate targetMock = new com.worldpay.internal.model.PaymentTokenCreate(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getCreateToken()).isNull(); + } + + @Test + public void populate_WhenGetStoredCredentialsIsNull_ShouldNotPopulateStoredCredentials() { + when(sourceMock.getStoredCredentials()).thenReturn(null); + + final com.worldpay.internal.model.PaymentTokenCreate targetMock = new com.worldpay.internal.model.PaymentTokenCreate(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getStoredCredentials()).isNull(); + } + + @Test + public void populate_WhenGetPaymentIsNull_ShouldNotPopulatePaymentInstrumentOrCSEDATA() { + when(sourceMock.getPayment()).thenReturn(null); + + final com.worldpay.internal.model.PaymentTokenCreate targetMock = new com.worldpay.internal.model.PaymentTokenCreate(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getPaymentInstrumentOrCSEDATA()).isEmpty(); + } + + @Test + public void populate_ShouldPopulatePaymentTokenCreate() { + when(sourceMock.getAuthenticatedShopperId()).thenReturn(SHOPPER_ID); + when(sourceMock.getStoredCredentials()).thenReturn(storeCredentialsMock); + when(sourceMock.getTokenRequest()).thenReturn(tokenRequestMock); + when(sourceMock.getPayment()).thenReturn(paymentMock); + + when(internalTokenRequestConverter.convert(tokenRequestMock)).thenReturn(createTokenMock); + when(internalStoredCredentialsConverter.convert(storeCredentialsMock)).thenReturn(intStoreCredentialsMock); + when(internalPaymentConverterStrategy.convertPayment(paymentMock)).thenReturn(intPaymentMock); + + final com.worldpay.internal.model.PaymentTokenCreate targetMock = new com.worldpay.internal.model.PaymentTokenCreate(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAuthenticatedShopperID().getvalue()).isEqualTo(SHOPPER_ID); + assertThat(targetMock.getCreateToken()).isEqualTo(createTokenMock); + assertThat(targetMock.getStoredCredentials()).isEqualTo(intStoreCredentialsMock); + assertThat(targetMock.getPaymentInstrumentOrCSEDATA().get(0)).isEqualTo(intPaymentMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/PaymentTokenDeletePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/PaymentTokenDeletePopulatorTest.java new file mode 100644 index 00000000..7442d490 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/PaymentTokenDeletePopulatorTest.java @@ -0,0 +1,54 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.data.token.DeleteTokenRequest; +import com.worldpay.data.token.TokenRequest; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class PaymentTokenDeletePopulatorTest { + + private static final String SHOPPER_ID = "shopperId"; + private static final String TOKEN_ID = "tokenId"; + + @InjectMocks + private PaymentTokenDeletePopulator testObj; + + @Mock + private DeleteTokenRequest sourceMock; + @Mock + private TokenRequest tokenRequestMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.PaymentTokenDelete()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulatePaymentTokenDelete() { + when(sourceMock.getTokenRequest()).thenReturn(tokenRequestMock); + when(sourceMock.getAuthenticatedShopperId()).thenReturn(SHOPPER_ID); + when(sourceMock.getPaymentTokenId()).thenReturn(TOKEN_ID); + + final com.worldpay.internal.model.PaymentTokenDelete targetMock = new com.worldpay.internal.model.PaymentTokenDelete(); + testObj.populate(sourceMock, targetMock); + + assertThat(targetMock.getAuthenticatedShopperID().getvalue()).isEqualTo(SHOPPER_ID); + assertThat(targetMock.getPaymentTokenID().getvalue()).isEqualTo(TOKEN_ID); + assertThat(targetMock.getTokenEventReference()).isEqualTo(tokenRequestMock.getTokenEventReference()); + assertThat(targetMock.getTokenReason().getvalue()).isEqualTo(tokenRequestMock.getTokenReason()); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/PaymentTokenUpdatePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/PaymentTokenUpdatePopulatorTest.java new file mode 100644 index 00000000..61031a38 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/PaymentTokenUpdatePopulatorTest.java @@ -0,0 +1,140 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.internal.model.PaymentTokenUpdate; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.data.token.UpdateTokenRequest; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class PaymentTokenUpdatePopulatorTest { + + private static final String MERCHANT = "merchant"; + private static final String SHOPPER_ID = "shopperId"; + private static final String SHOPPER = "shopper"; + private static final String PAYMENT_TOKEN_ID = "paymentTokenId"; + private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; + private static final String TOKEN_REASON = "tokenReason"; + + @InjectMocks + private PaymentTokenUpdatePopulator testObj; + + @Mock + private Converter internalCardDetailsConverterMock; + + @Mock + private UpdateTokenRequest sourceMock; + @Mock + private TokenRequest tokenRequestMock; + @Mock + private CardDetails cardDetailsMock; + @Mock + private com.worldpay.internal.model.CardDetails intCardDetailsMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.PaymentTokenUpdate()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenIsMerchantToken_ShouldPopulateTokenScopeAndNotPopulateAuthenticatedShopperID() { + when(sourceMock.isMerchantToken()).thenReturn(Boolean.TRUE); + + final PaymentTokenUpdate target = new PaymentTokenUpdate(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenScope()).isEqualTo(MERCHANT); + assertThat(target.getAuthenticatedShopperID()).isNull(); + } + + @Test + public void populate_WhenIsNotMerchantTokenAndAuthenticatedShopperIDIsNull_ShouldNotPopulateAuthenticatedShopperID() { + when(sourceMock.isMerchantToken()).thenReturn(Boolean.FALSE); + when(sourceMock.getAuthenticatedShopperID()).thenReturn(null); + + final PaymentTokenUpdate target = new PaymentTokenUpdate(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenScope()).isEqualTo(SHOPPER); + assertThat(target.getAuthenticatedShopperID()).isNull(); + } + + @Test + public void populate_WhenIsNotMerchantTokenAndAuthenticatedShopperIDIsNotNull_ShouldPopulateAuthenticatedShopperID() { + when(sourceMock.isMerchantToken()).thenReturn(Boolean.FALSE); + when(sourceMock.getAuthenticatedShopperID()).thenReturn(SHOPPER_ID); + + final PaymentTokenUpdate target = new PaymentTokenUpdate(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenScope()).isEqualTo(SHOPPER); + assertThat(target.getAuthenticatedShopperID().getvalue()).isEqualTo(SHOPPER_ID); + } + + @Test + public void populate_WhenGetTokenRequestIsNull_ShouldNotPopulateTokenEventReference() { + when(sourceMock.getTokenRequest()).thenReturn(null); + + final PaymentTokenUpdate target = new PaymentTokenUpdate(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenEventReference()).isNull(); + } + + @Test + public void populate_WhenGetCardDetailsIsNull_ShouldNotPopulatePaymentInstrument() { + when(sourceMock.getCardDetails()).thenReturn(null); + + final PaymentTokenUpdate target = new PaymentTokenUpdate(); + testObj.populate(sourceMock, target); + + assertThat(target.getPaymentInstrument()).isNull(); + } + + @Test + public void populate_WhenGetTokenRequestIsNull_ShouldNotPopulateTokenReason() { + when(sourceMock.getTokenRequest()).thenReturn(null); + + final PaymentTokenUpdate target = new PaymentTokenUpdate(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenReason()).isNull(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.isMerchantToken()).thenReturn(Boolean.FALSE); + when(sourceMock.getAuthenticatedShopperID()).thenReturn(SHOPPER_ID); + when(sourceMock.getPaymentTokenId()).thenReturn(PAYMENT_TOKEN_ID); + when(sourceMock.getTokenRequest()).thenReturn(tokenRequestMock); + when(tokenRequestMock.getTokenEventReference()).thenReturn(TOKEN_EVENT_REFERENCE); + when(tokenRequestMock.getTokenReason()).thenReturn(TOKEN_REASON); + when(sourceMock.getCardDetails()).thenReturn(cardDetailsMock); + when(internalCardDetailsConverterMock.convert(cardDetailsMock)).thenReturn(intCardDetailsMock); + + final PaymentTokenUpdate target = new PaymentTokenUpdate(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenScope()).isEqualTo(SHOPPER); + assertThat(target.getAuthenticatedShopperID().getvalue()).isEqualTo(SHOPPER_ID); + assertThat(target.getPaymentTokenID().getvalue()).isEqualTo(PAYMENT_TOKEN_ID); + assertThat(target.getTokenEventReference()).isEqualTo(TOKEN_EVENT_REFERENCE); + assertThat(target.getPaymentInstrument().getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().get(0)).isEqualTo(intCardDetailsMock); + assertThat(target.getTokenReason().getvalue()).isEqualTo(TOKEN_REASON); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/TokenPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/TokenPopulatorTest.java new file mode 100644 index 00000000..d5d4dbbe --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/TokenPopulatorTest.java @@ -0,0 +1,102 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.internal.model.TOKENSSL; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.Token; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class TokenPopulatorTest { + + private static final String MERCHANT = "merchant"; + private static final String SHOPPER = "shopper"; + private static final String PAYMENT_TOKEN_ID = "paymentTokenId"; + + @InjectMocks + private TokenPopulator testObj; + + @Mock + private Converter internalCardDetailsConverterMock; + + @Mock + private Token sourceMock; + @Mock + private CardDetails cardDetailsMock; + @Mock + private com.worldpay.internal.model.CardDetails intCardDetailsMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.TOKENSSL()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenIsMerchantToken_ShouldPopulateMerchant() { + when(sourceMock.isMerchantToken()).thenReturn(Boolean.TRUE); + + final TOKENSSL target = new TOKENSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenScope()).isEqualTo(MERCHANT); + } + + @Test + public void populate_WhenIsNotMerchantToken_ShouldPopulateShopper() { + when(sourceMock.isMerchantToken()).thenReturn(Boolean.FALSE); + + final TOKENSSL target = new TOKENSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenScope()).isEqualTo(SHOPPER); + } + + @Test + public void populate_WhenGetPaymentTokenIDIsNull_ShouldNotPopulatePaymentTokenID() { + when(sourceMock.getPaymentTokenID()).thenReturn(null); + + final TOKENSSL target = new TOKENSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getPaymentTokenIDOrPaymentInstrumentOrCvcOrSession()).isEmpty(); + } + + @Test + public void populate_WhenGetPaymentInstrumentIsNull_ShouldNotPopulatePaymentInstrument() { + when(sourceMock.getPaymentInstrument()).thenReturn(null); + + final TOKENSSL target = new TOKENSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getPaymentTokenIDOrPaymentInstrumentOrCvcOrSession()).isEmpty(); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.isMerchantToken()).thenReturn(Boolean.TRUE); + when(sourceMock.getPaymentTokenID()).thenReturn(PAYMENT_TOKEN_ID); + when(sourceMock.getPaymentInstrument()).thenReturn(cardDetailsMock); + + when(internalCardDetailsConverterMock.convert(cardDetailsMock)).thenReturn(intCardDetailsMock); + + final TOKENSSL target = new TOKENSSL(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenScope()).isEqualTo(MERCHANT); + assertThat(target.getPaymentTokenIDOrPaymentInstrumentOrCvcOrSession().size()).isEqualTo(2); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/TokenRequestPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/TokenRequestPopulatorTest.java new file mode 100644 index 00000000..f9bf2239 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/internal/model/token/TokenRequestPopulatorTest.java @@ -0,0 +1,82 @@ +package com.worldpay.converters.populators.internal.model.token; + +import com.worldpay.data.token.TokenRequest; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class TokenRequestPopulatorTest { + + private static final String MERCHANT = "merchant"; + private static final String SHOPPER = "shopper"; + private static final String TOKEN_REASON = "tokenReason"; + private static final String TOKEN_REFERENCE = "tokenReference"; + + @InjectMocks + private TokenRequestPopulator testObj; + + @Mock + private TokenRequest sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.internal.model.CreateToken()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_WhenGetTokenReasonIsNull_ShouldNotPopulateTokenReason() { + when(sourceMock.getTokenReason()).thenReturn(null); + + final com.worldpay.internal.model.CreateToken target = new com.worldpay.internal.model.CreateToken(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenReason()).isNull(); + } + + @Test + public void populate_WhenIsMerchantToken_ShouldPopulateMerchantTokenReference() { + when(sourceMock.isMerchantToken()).thenReturn(Boolean.TRUE); + + final com.worldpay.internal.model.CreateToken target = new com.worldpay.internal.model.CreateToken(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenScope()).isEqualTo(MERCHANT); + } + + @Test + public void populate_WhenIsNotMerchantToken_ShouldPopulateShopperTokenReference() { + when(sourceMock.isMerchantToken()).thenReturn(Boolean.FALSE); + + final com.worldpay.internal.model.CreateToken target = new com.worldpay.internal.model.CreateToken(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenScope()).isEqualTo(SHOPPER); + } + + @Test + public void populate_WhenSourceAndTargetAreNotNullAndAllTheFieldsAreNotNull_ShouldPopulate() { + when(sourceMock.getTokenReason()).thenReturn(TOKEN_REASON); + when(sourceMock.getTokenEventReference()).thenReturn(TOKEN_REFERENCE); + when(sourceMock.isMerchantToken()).thenReturn(Boolean.TRUE); + + final com.worldpay.internal.model.CreateToken target = new com.worldpay.internal.model.CreateToken(); + testObj.populate(sourceMock, target); + + assertThat(target.getTokenReason().getvalue()).isEqualTo(TOKEN_REASON); + assertThat(target.getTokenEventReference()).isEqualTo(TOKEN_REFERENCE); + assertThat(target.getTokenScope()).isEqualTo(MERCHANT); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/reverse/internal/model/AmountReversePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/reverse/internal/model/AmountReversePopulatorTest.java new file mode 100644 index 00000000..a7ee646f --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/reverse/internal/model/AmountReversePopulatorTest.java @@ -0,0 +1,52 @@ +package com.worldpay.converters.populators.reverse.internal.model; + +import com.worldpay.enums.DebitCreditIndicator; +import com.worldpay.internal.model.Amount; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class AmountReversePopulatorTest { + + @InjectMocks + private AmountReversePopulator testObj; + + @Mock + private Amount sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.data.Amount()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateAmount() { + when(sourceMock.getCurrencyCode()).thenReturn("EUR"); + when(sourceMock.getExponent()).thenReturn("2"); + when(sourceMock.getValue()).thenReturn("100"); + when(sourceMock.getDebitCreditIndicator()).thenReturn("CREDIT"); + + final com.worldpay.data.Amount target = new com.worldpay.data.Amount(); + testObj.populate(sourceMock, target); + + assertThat(target.getCurrencyCode()).isEqualTo("EUR"); + assertThat(target.getExponent()).isEqualTo("2"); + assertThat(target.getValue()).isEqualTo("100"); + assertThat(target.getDebitCreditIndicator()).isEqualTo(DebitCreditIndicator.CREDIT); + } + + +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/reverse/internal/model/DateReversePopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/reverse/internal/model/DateReversePopulatorTest.java new file mode 100644 index 00000000..b22fd979 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/converters/populators/reverse/internal/model/DateReversePopulatorTest.java @@ -0,0 +1,54 @@ +package com.worldpay.converters.populators.reverse.internal.model; + + +import com.worldpay.internal.model.Date; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DateReversePopulatorTest { + + @InjectMocks + private DateReversePopulator testObj; + + @Mock + private Date sourceMock; + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenSourceIsNull_ShouldThrowAnException() { + testObj.populate(null, new com.worldpay.data.Date()); + } + + @Test(expected = IllegalArgumentException.class) + public void populate_WhenTargetIsNull_ShouldThrowAnException() { + testObj.populate(sourceMock, null); + } + + @Test + public void populate_ShouldPopulateDate() { + when(sourceMock.getDayOfMonth()).thenReturn("01"); + when(sourceMock.getMonth()).thenReturn("01"); + when(sourceMock.getYear()).thenReturn("2021"); + when(sourceMock.getHour()).thenReturn("01"); + when(sourceMock.getMinute()).thenReturn("01"); + when(sourceMock.getSecond()).thenReturn("01"); + + final com.worldpay.data.Date target = new com.worldpay.data.Date(); + testObj.populate(sourceMock, target); + + assertThat(target.getDayOfMonth()).isEqualTo("01"); + assertThat(target.getHour()).isEqualTo("01"); + assertThat(target.getMinute()).isEqualTo("01"); + assertThat(target.getMonth()).isEqualTo("01"); + assertThat(target.getSecond()).isEqualTo("01"); + assertThat(target.getYear()).isEqualTo("2021"); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/checkout/impl/DefaultWorldpayCheckoutServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/checkout/impl/DefaultWorldpayCheckoutServiceTest.java index 81c1fa6e..a79e9448 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/checkout/impl/DefaultWorldpayCheckoutServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/checkout/impl/DefaultWorldpayCheckoutServiceTest.java @@ -4,13 +4,16 @@ import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.user.AddressModel; import de.hybris.platform.servicelayer.model.ModelService; +import de.hybris.platform.servicelayer.user.AddressService; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; -import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @UnitTest @RunWith(MockitoJUnitRunner.class) @@ -18,20 +21,37 @@ public class DefaultWorldpayCheckoutServiceTest { @InjectMocks private DefaultWorldpayCheckoutService testObj; + @Mock - private CartModel cartModelMock; + private ModelService modelServiceMock; @Mock - private AddressModel addressModelMock; + private AddressService addressServiceMock; @Mock - private ModelService modelServiceMock; + private CartModel cartModelMock; + @Mock + private AddressModel addressModelMock, clonedAddressMock; @Test - public void testSetPaymentAddress() throws Exception { + public void setPaymentAddress_ShouldSetPaymentAddressAndSaveCart() { testObj.setPaymentAddress(cartModelMock, addressModelMock); - verify(modelServiceMock).save(cartModelMock); - verify(modelServiceMock).refresh(cartModelMock); - verify(cartModelMock).setPaymentAddress(addressModelMock); + final InOrder inOrder = Mockito.inOrder(cartModelMock, modelServiceMock); + inOrder.verify(cartModelMock).setPaymentAddress(addressModelMock); + inOrder.verify(modelServiceMock).save(cartModelMock); + inOrder.verify(modelServiceMock).refresh(cartModelMock); + } + + @Test + public void setShippingAndPaymentAddress_ShouldSetShippingAndPaymentAddressAndSaveCart() { + when(addressServiceMock.cloneAddress(addressModelMock)).thenReturn(clonedAddressMock); + + testObj.setShippingAndPaymentAddress(cartModelMock, addressModelMock); + + final InOrder inOrder = Mockito.inOrder(cartModelMock, modelServiceMock); + inOrder.verify(cartModelMock).setDeliveryAddress(addressModelMock); + inOrder.verify(cartModelMock).setPaymentAddress(clonedAddressMock); + inOrder.verify(modelServiceMock).saveAll(clonedAddressMock, cartModelMock); + inOrder.verify(modelServiceMock).refresh(cartModelMock); } -} \ No newline at end of file +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/dao/impl/DefaultWorldpayAPMComponentDaoIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/dao/impl/DefaultWorldpayAPMComponentDaoIntegrationTest.java new file mode 100644 index 00000000..86e74cf0 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/dao/impl/DefaultWorldpayAPMComponentDaoIntegrationTest.java @@ -0,0 +1,53 @@ +package com.worldpay.core.dao.impl; + +import com.worldpay.core.dao.WorldpayAPMComponentDao; +import com.worldpay.model.WorldpayAPMComponentModel; +import de.hybris.bootstrap.annotations.IntegrationTest; +import de.hybris.platform.catalog.CatalogVersionService; +import de.hybris.platform.catalog.model.CatalogVersionModel; +import de.hybris.platform.impex.jalo.ImpExException; +import de.hybris.platform.servicelayer.ServicelayerTransactionalTest; +import org.junit.Before; +import org.junit.Test; + +import javax.annotation.Resource; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@IntegrationTest +public class DefaultWorldpayAPMComponentDaoIntegrationTest extends ServicelayerTransactionalTest { + + private static final String CATALOG_WITH_COMPONENTS = "testCatalog1"; + private static final String CATALOG_WITHOUT_COMPONENTS = "testCatalog2"; + private static final String CATALOG_VERSION = "Online"; + + @Resource(name = "worldpayAPMComponentDao") + private WorldpayAPMComponentDao testObj; + + @Resource(name = "catalogVersionService") + private CatalogVersionService catalogVersionService; + + @Before + public void setUp() throws ImpExException { + importCsv("/test/integration/worldpayAPMComponentTest.impex", "utf-8"); + } + + @Test + public void findAllApmComponents_WhenComponentsAreInTheListOfCatalogs_ShouldReturnComponents() { + final CatalogVersionModel catalogVersionModel = catalogVersionService.getCatalogVersion(CATALOG_WITH_COMPONENTS, CATALOG_VERSION); + + final List result = testObj.findAllApmComponents(List.of(catalogVersionModel)); + + assertThat(result.size()).isEqualTo(2); + } + + @Test + public void findAllApmComponents_WhenComponentsAreNotInTheListOfCatalogs_ShouldNotReturnComponents() { + final CatalogVersionModel catalogVersionModel = catalogVersionService.getCatalogVersion(CATALOG_WITHOUT_COMPONENTS, "Online"); + + final List result = testObj.findAllApmComponents(List.of(catalogVersionModel)); + + assertThat(result).isEmpty(); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/dao/impl/DefaultWorldpayAPMComponentDaoTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/dao/impl/DefaultWorldpayAPMComponentDaoTest.java new file mode 100644 index 00000000..b08b0af7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/dao/impl/DefaultWorldpayAPMComponentDaoTest.java @@ -0,0 +1,80 @@ +package com.worldpay.core.dao.impl; + +import com.worldpay.model.WorldpayAPMComponentModel; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.catalog.model.CatalogVersionModel; +import de.hybris.platform.cms2.model.contents.CMSItemModel; +import de.hybris.platform.core.model.ItemModel; +import de.hybris.platform.servicelayer.search.FlexibleSearchService; +import de.hybris.platform.servicelayer.search.SearchResult; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayAPMComponentDaoTest { + + private static final String QUERY = "SELECT {wc." + ItemModel.PK + "} " + + "FROM {" + WorldpayAPMComponentModel._TYPECODE + " AS wc} " + + "WHERE {wc." + CMSItemModel.CATALOGVERSION + "} IN (?catalogVersions)"; + private static final String CATALOG_VERSIONS_KEY = "catalogVersions"; + + @InjectMocks + private DefaultWorldpayAPMComponentDao testObj; + + @Mock + private FlexibleSearchService flexibleSearchServiceMock; + @Mock + private SearchResult searchResultMock; + + @Mock + private WorldpayAPMComponentModel apmComponentModel1Mock, apmComponentModel2Mock; + @Mock + private CatalogVersionModel catalogVersionModel1Mock, catalogVersionModel2Mock; + + @Captor + private ArgumentCaptor stringArgumentCaptor; + @Captor + private ArgumentCaptor> mapArgumentCaptor; + + @Before + public void setUp() { + when(flexibleSearchServiceMock.search(stringArgumentCaptor.capture(), mapArgumentCaptor.capture())).thenReturn(searchResultMock); + } + + @Test + public void findAllAvailableApmComponents_WhenThereAreComponentsForTheGivenCatalogs_ShouldReturnAListOfComponents() { + when(searchResultMock.getResult()).thenReturn(List.of(apmComponentModel1Mock, apmComponentModel2Mock)); + + final List result = testObj.findAllApmComponents(List.of(catalogVersionModel1Mock, catalogVersionModel2Mock)); + + assertThat(result).isEqualTo(List.of(apmComponentModel1Mock, apmComponentModel2Mock)); + assertThat(stringArgumentCaptor.getValue()).isEqualTo(QUERY); + assertThat(mapArgumentCaptor.getValue()).containsEntry(CATALOG_VERSIONS_KEY, List.of(catalogVersionModel1Mock, catalogVersionModel2Mock)); + } + + @Test + public void findAllAvailableApmComponents_WhenThereAreNotComponentsForTheGivenCatalogs_ShouldReturnAnEmptyList() { + when(searchResultMock.getResult()).thenReturn(Collections.emptyList()); + + final List result = testObj.findAllApmComponents(List.of(catalogVersionModel1Mock, catalogVersionModel2Mock)); + + assertThat(result).isEmpty(); + assertThat(stringArgumentCaptor.getValue()).isEqualTo(QUERY); + assertThat(mapArgumentCaptor.getValue()).containsEntry(CATALOG_VERSIONS_KEY, List.of(catalogVersionModel1Mock, catalogVersionModel2Mock)); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultAPMConfigurationLookupServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultAPMConfigurationLookupServiceTest.java index cf7aad6f..34c21ec5 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultAPMConfigurationLookupServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultAPMConfigurationLookupServiceTest.java @@ -26,7 +26,7 @@ public class DefaultAPMConfigurationLookupServiceTest { private static final String PAYMENT_APM_NAME = "paymentAPMName"; @InjectMocks - private DefaultAPMConfigurationLookupService testObj = new DefaultAPMConfigurationLookupService(); + private DefaultAPMConfigurationLookupService testObj; @Mock private WorldpayAPMConfigurationDao worldpayAPMConfigurationDaoMock; @@ -90,4 +90,4 @@ public void getAllApmPaymentTypeCodesReturns() { assertTrue(result.isEmpty()); } -} \ No newline at end of file +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultOrderInquiryServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultOrderInquiryServiceTest.java index 873e7a1b..497cfa54 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultOrderInquiryServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultOrderInquiryServiceTest.java @@ -2,13 +2,13 @@ import com.evanlennick.retry4j.config.RetryConfig; import com.worldpay.core.services.WorldpayPaymentInfoService; +import com.worldpay.data.ErrorDetail; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.PaymentReply; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.exception.WorldpayException; import com.worldpay.model.WorldpayAPMConfigurationModel; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.ErrorDetail; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.PaymentReply; import com.worldpay.service.request.KlarnaOrderInquiryServiceRequest; import com.worldpay.service.request.OrderInquiryServiceRequest; import com.worldpay.service.response.OrderInquiryServiceResponse; @@ -45,6 +45,8 @@ public class DefaultOrderInquiryServiceTest { private static final String WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES = "worldpayapi.inquiry.delay.between.retries"; private static final int DELAY_BETWEEN_RETRIES = 1; private static final int MAX_NUMBER_RETRIES = 3; + private static final String ERROR_CODE = "5"; + private static final String ERROR_MESSAGE_DETAIL = "Some Error Detail"; @Rule @@ -175,13 +177,16 @@ public void shouldInquiryPaymentDetailsOfAnOrderUsingOrderCode() throws Exceptio @Test public void shouldRetryInquiryPaymentDetailsWhenThereIsAnError() throws Exception { when(worldpayServiceGatewayMock.orderInquiry(orderInquiryServiceRequestMock)) - .thenReturn(orderInquiryServiceResponseMock) - .thenReturn(orderInquiryServiceResponseMock1) - .thenReturn(orderInquiryServiceResponseMock2); + .thenReturn(orderInquiryServiceResponseMock) + .thenReturn(orderInquiryServiceResponseMock1) + .thenReturn(orderInquiryServiceResponseMock2); when(orderInquiryServiceResponseMock2.getPaymentReply()).thenReturn(paymentReplyMock); - final ErrorDetail errorDetail = new ErrorDetail("5", "Some Error Detail"); + final ErrorDetail errorDetail = new ErrorDetail(); + errorDetail.setCode(ERROR_CODE); + errorDetail.setMessage(ERROR_MESSAGE_DETAIL); + when(orderInquiryServiceResponseMock.getErrorDetail()).thenReturn(errorDetail); when(orderInquiryServiceResponseMock1.getErrorDetail()).thenReturn(errorDetail); when(orderInquiryServiceResponseMock2.getErrorDetail()).thenReturn(null); @@ -212,11 +217,14 @@ public void shouldCreateConfigurationUsingConfigurationServiceValues() throws Ex @Test(expected = WorldpayException.class) public void shouldRetryInquiryPaymentDetailsWhenThereIsAnErrorAndFailWhenRetriesNumberAreExhausted() throws Exception { when(worldpayServiceGatewayMock.orderInquiry(orderInquiryServiceRequestMock)) - .thenReturn(orderInquiryServiceResponseMock) - .thenReturn(orderInquiryServiceResponseMock1) - .thenReturn(orderInquiryServiceResponseMock2); + .thenReturn(orderInquiryServiceResponseMock) + .thenReturn(orderInquiryServiceResponseMock1) + .thenReturn(orderInquiryServiceResponseMock2); + + final ErrorDetail errorDetail = new ErrorDetail(); + errorDetail.setCode(ERROR_CODE); + errorDetail.setMessage(ERROR_MESSAGE_DETAIL); - final ErrorDetail errorDetail = new ErrorDetail("5", "Some Error Detail"); when(orderInquiryServiceResponseMock.getErrorDetail()).thenReturn(errorDetail); when(orderInquiryServiceResponseMock1.getErrorDetail()).thenReturn(errorDetail); when(orderInquiryServiceResponseMock2.getErrorDetail()).thenReturn(errorDetail); @@ -256,13 +264,16 @@ public void shouldCreateRetryConfigurationUsingConfigurationServiceValuesForKlar public void shouldRetryKlarnaInquiryPaymentDetailsWhenThereIsAnErrorAndFailWhenRetriesNumberAreExhausted() throws Exception { doReturn(klarnaOrderInquiryServiceRequestMock).when(testObj).createKlarnaOrderInquiryServiceRequest(merchantInfoMock, WORLDPAY_ORDER_CODE); - final ErrorDetail errorDetail = new ErrorDetail("5", "Some Error Detail"); + final ErrorDetail errorDetail = new ErrorDetail(); + errorDetail.setCode(ERROR_CODE); + errorDetail.setMessage(ERROR_MESSAGE_DETAIL); + when(orderInquiryServiceResponseMock.getErrorDetail()).thenReturn(errorDetail); when(worldpayServiceGatewayMock.orderInquiry(klarnaOrderInquiryServiceRequestMock)) - .thenReturn(orderInquiryServiceResponseMock) - .thenReturn(orderInquiryServiceResponseMock) - .thenReturn(orderInquiryServiceResponseMock); + .thenReturn(orderInquiryServiceResponseMock) + .thenReturn(orderInquiryServiceResponseMock) + .thenReturn(orderInquiryServiceResponseMock); testObj.inquiryKlarnaOrder(merchantInfoMock, WORLDPAY_ORDER_CODE); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayAPMComponentServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayAPMComponentServiceTest.java new file mode 100644 index 00000000..17de0d61 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayAPMComponentServiceTest.java @@ -0,0 +1,93 @@ +package com.worldpay.core.services.impl; + +import com.worldpay.core.dao.WorldpayAPMComponentDao; +import com.worldpay.model.WorldpayAPMComponentModel; +import com.worldpay.model.WorldpayAPMConfigurationModel; +import com.worldpay.service.apm.APMAvailabilityService; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.catalog.CatalogVersionService; +import de.hybris.platform.catalog.model.CatalogVersionModel; +import de.hybris.platform.core.model.order.CartModel; +import de.hybris.platform.order.CartService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayAPMComponentServiceTest { + + @InjectMocks + private DefaultWorldpayAPMComponentService testObj; + + @Mock + private CartService cartServiceMock; + @Mock + private CatalogVersionService catalogVersionServiceMock; + @Mock + private APMAvailabilityService apmAvailabilityServiceMock; + @Mock + private WorldpayAPMComponentDao worldpayAPMComponentDaoMock; + + @Mock + private CartModel cartModelMock; + @Mock + private CatalogVersionModel catalogVersionModelMock; + @Mock + private WorldpayAPMComponentModel worldpayAPMComponentModelMock; + @Mock + private WorldpayAPMConfigurationModel worldpayAPMConfigurationModelMock; + + @Before + public void setUp() { + when(catalogVersionServiceMock.getSessionCatalogVersions()).thenReturn(List.of(catalogVersionModelMock)); + when(worldpayAPMComponentDaoMock.findAllApmComponents(List.of(catalogVersionModelMock))).thenReturn(List.of(worldpayAPMComponentModelMock)); + when(worldpayAPMComponentModelMock.getApmConfiguration()).thenReturn(worldpayAPMConfigurationModelMock); + when(cartServiceMock.getSessionCart()).thenReturn(cartModelMock); + } + + @Test + public void getAllAvailableWorldpayAPMComponents_WhenDaoDoesNotFindAnyComponent_ShouldReturnAnEmptyList() { + when(worldpayAPMComponentDaoMock.findAllApmComponents(List.of(catalogVersionModelMock))).thenReturn(Collections.emptyList()); + + final List result = testObj.getAllAvailableWorldpayAPMComponents(); + + assertThat(result).isEmpty(); + } + + @Test + public void getAllAvailableWorldpayAPMComponents_WhenApmConfigIsNull_ShouldReturnAnEmptyList() { + when(worldpayAPMComponentModelMock.getApmConfiguration()).thenReturn(null); + + final List result = testObj.getAllAvailableWorldpayAPMComponents(); + + assertThat(result).isEmpty(); + } + + @Test + public void getAllAvailableWorldpayAPMComponents_WhenApmIsNotAvailable_ShouldReturnAnEmptyList() { + when(apmAvailabilityServiceMock.isAvailable(worldpayAPMConfigurationModelMock, cartModelMock)).thenReturn(Boolean.FALSE); + + final List result = testObj.getAllAvailableWorldpayAPMComponents(); + + assertThat(result).isEmpty(); + } + + @Test + public void getAllAvailableWorldpayAPMComponents_WhenDaoFindComponentsAndApmConfigIsNotNullAndApmIsAvailable_ShouldReturnAListOfComponents() { + when(apmAvailabilityServiceMock.isAvailable(worldpayAPMConfigurationModelMock, cartModelMock)).thenReturn(Boolean.TRUE); + + final List result = testObj.getAllAvailableWorldpayAPMComponents(); + + assertThat(result).isEqualTo(List.of(worldpayAPMComponentModelMock)); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayBankConfigurationLookupServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayBankConfigurationLookupServiceTest.java index 882fedb7..5cd00c43 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayBankConfigurationLookupServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayBankConfigurationLookupServiceTest.java @@ -32,7 +32,7 @@ public class DefaultWorldpayBankConfigurationLookupServiceTest { private static final String APM_CODE = "apmCode"; private static final String BANK_CODE = "ING"; @InjectMocks - private DefaultWorldpayBankConfigurationLookupService testObj = new DefaultWorldpayBankConfigurationLookupService(); + private DefaultWorldpayBankConfigurationLookupService testObj; @Mock private APMConfigurationLookupService apmConfigurationLookupService; @@ -78,5 +78,5 @@ public void shouldReturnBankConfigurationIfBankCodeNotNull() { } } - + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayCartServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayCartServiceTest.java index a7722846..95281cb0 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayCartServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayCartServiceTest.java @@ -1,11 +1,19 @@ package com.worldpay.core.services.impl; import com.worldpay.core.dao.WorldpayCartDao; +import com.worldpay.data.AdditionalAuthInfo; +import com.worldpay.data.Address; import com.worldpay.service.payment.impl.DefaultWorldpaySessionService; import com.worldpay.service.payment.impl.OccWorldpaySessionService; +import com.worldpay.strategy.WorldpayDeliveryAddressStrategy; import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.commerceservices.customer.CustomerEmailResolutionService; import de.hybris.platform.core.model.order.CartModel; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.core.model.user.CustomerModel; +import de.hybris.platform.core.model.user.UserModel; import de.hybris.platform.order.CartService; +import de.hybris.platform.servicelayer.dto.converter.Converter; import de.hybris.platform.servicelayer.exceptions.AmbiguousIdentifierException; import de.hybris.platform.servicelayer.exceptions.ModelNotFoundException; import org.junit.Before; @@ -16,6 +24,7 @@ import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; @@ -26,6 +35,8 @@ public class DefaultWorldpayCartServiceTest { private static final String WORLDPAY_ORDER_CODE = "orderCode"; private static final String DECLINE_CODE = "A19"; private static final String BANK_CODE = "bankCode"; + private static final String CUSTOMER_ID = "customerId"; + private static final String ORIGINAL_UID = "originalUid"; @InjectMocks private DefaultWorldpayCartService testObj; @@ -33,21 +44,38 @@ public class DefaultWorldpayCartServiceTest { @Mock private WorldpayCartDao worldpayCartDaoMock; @Mock - private CartModel cartModelMock; + private WorldpayDeliveryAddressStrategy worldpayDeliveryAddressStrategyMock; @Mock - private CartModel cartModelMock2; + private CustomerEmailResolutionService customerEmailResolutionServiceMock; @Mock private CartService cartServiceMock; @Mock private OccWorldpaySessionService occWorldpaySessionServiceMock; @Mock private DefaultWorldpaySessionService worldpaySessionServiceMock; + @Mock + private Converter worldpayAddressConverterMock; + + @Mock + private CartModel cartModelMock, cartModelMock2; + @Mock + private CustomerModel customerModelMock; + @Mock + private UserModel userModelMock; + @Mock + private Address addressMock; + @Mock + private AddressModel deliveryAddressMock, paymentAddressMock; + @Mock + private AdditionalAuthInfo additionalAuthInfoMock; @Before - public void setUp() throws Exception { - Whitebox.setInternalState(testObj, "worldpaySessionService", worldpaySessionServiceMock); + public void setUp() { when(worldpayCartDaoMock.findCartByWorldpayOrderCode(WORLDPAY_ORDER_CODE)).thenReturn(cartModelMock); when(cartServiceMock.getSessionCart()).thenReturn(cartModelMock); + when(cartModelMock.getUser()).thenReturn(customerModelMock); + when(worldpayAddressConverterMock.convert(deliveryAddressMock)).thenReturn(addressMock); + when(worldpayAddressConverterMock.convert(paymentAddressMock)).thenReturn(addressMock); } @Test @@ -128,4 +156,91 @@ public void setSessionId_whenInstanceOfOccWorldpay_shouldDoNothig() { verify(occWorldpaySessionServiceMock).setSessionIdFor3dSecure("sessionId"); } + + @Test + public void getAuthenticatedShopperId_ShouldReturnCustomerId() { + when(customerModelMock.getCustomerID()).thenReturn(CUSTOMER_ID); + + final String result = testObj.getAuthenticatedShopperId(cartModelMock); + + assertEquals(CUSTOMER_ID, result); + } + + @Test + public void getAuthenticatedShopperId_WhenCustomerIdNotPresesnt_ShouldReturnOriginalUID() { + when(customerModelMock.getCustomerID()).thenReturn(""); + when(customerModelMock.getOriginalUid()).thenReturn(ORIGINAL_UID); + + final String result = testObj.getAuthenticatedShopperId(cartModelMock); + + assertEquals(ORIGINAL_UID, result); + } + + @Test(expected = IllegalArgumentException.class) + public void getAuthenticatedShopperId_WhenNotInstanceOfCustomer_ShouldThrowIllegalArgumentException() { + when(cartModelMock.getUser()).thenReturn(userModelMock); + + testObj.getAuthenticatedShopperId(cartModelMock); + } + + @Test(expected = NullPointerException.class) + public void getAuthenticatedShopperId_WhenCartIsNull_ShouldThrowException() { + testObj.getAuthenticatedShopperId(null); + } + + @Test + public void getEmailForCustomer_ShouldReturnCustomerEmail() { + testObj.getEmailForCustomer(cartModelMock); + + verify(customerEmailResolutionServiceMock).getEmailForCustomer(customerModelMock); + } + + @Test + public void getAddressFromCart_WhenIsDeliveryAddressTrue_ShouldReturnDeliveryAddress() { + when(worldpayDeliveryAddressStrategyMock.getDeliveryAddress(cartModelMock)).thenReturn(deliveryAddressMock); + + final Address result = testObj.getAddressFromCart(cartModelMock, true); + + assertThat(result).isEqualTo(addressMock); + } + + @Test + public void getAddressFromCart_WhenIsDeliveryAddressFalse_ShouldReturnPaymentAddress() { + when(cartModelMock.getPaymentAddress()).thenReturn(paymentAddressMock); + + final Address result = testObj.getAddressFromCart(cartModelMock, false); + + assertThat(result).isEqualTo(addressMock); + } + + @Test + public void getBillingAddress_WhenUsingShippingAsBilling_ShouldReturnBillingAddress() { + when(cartModelMock.getDeliveryAddress()).thenReturn(deliveryAddressMock); + when(additionalAuthInfoMock.getUsingShippingAsBilling()).thenReturn(Boolean.TRUE); + + final Address result = testObj.getBillingAddress(cartModelMock, additionalAuthInfoMock); + + assertThat(result).isEqualTo(addressMock); + } + + @Test + public void getBillingAddress_WhenUsingShippingAsBillingFalse_ShouldReturnPaymentAddress() { + when(cartModelMock.getDeliveryAddress()).thenReturn(deliveryAddressMock); + when(cartModelMock.getPaymentAddress()).thenReturn(paymentAddressMock); + when(additionalAuthInfoMock.getUsingShippingAsBilling()).thenReturn(Boolean.FALSE); + + final Address result = testObj.getBillingAddress(cartModelMock, additionalAuthInfoMock); + + assertThat(result).isEqualTo(addressMock); + } + + @Test + public void getBillingAddress_WhenNoPaymentOrDeliveryAddress_ShouldReturnNull() { + when(cartModelMock.getDeliveryAddress()).thenReturn(null); + when(cartModelMock.getPaymentAddress()).thenReturn(null); + + final Address result = testObj.getBillingAddress(cartModelMock, additionalAuthInfoMock); + + assertThat(result).isNull(); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoServiceCreditCardTypeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoServiceCreditCardTypeTest.java index 017c692f..1fb1d915 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoServiceCreditCardTypeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoServiceCreditCardTypeTest.java @@ -1,6 +1,6 @@ package com.worldpay.core.services.impl; -import com.worldpay.service.model.PaymentReply; +import com.worldpay.data.PaymentReply; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.enums.CreditCardType; import de.hybris.platform.core.model.order.payment.CreditCardPaymentInfoModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoServiceTest.java index 2ae29af6..1b55d1a0 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPaymentInfoServiceTest.java @@ -9,12 +9,12 @@ import com.worldpay.model.ApplePayPaymentInfoModel; import com.worldpay.model.GooglePayPaymentInfoModel; import com.worldpay.model.WorldpayAPMConfigurationModel; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.payment.Card; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.payment.Card; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.TokenReply; import com.worldpay.service.notification.OrderNotificationMessage; import com.worldpay.service.request.UpdateTokenServiceRequest; import com.worldpay.service.response.CreateTokenResponse; @@ -147,7 +147,7 @@ public class DefaultWorldpayPaymentInfoServiceTest { @Mock(answer = RETURNS_DEEP_STUBS) private Card cardMock; @Mock - private com.worldpay.service.model.Date dateMock; + private com.worldpay.data.Date dateMock; @Mock private CurrencyModel currencyModelMock; @Mock @@ -515,7 +515,7 @@ public void createCreditCardPaymentInfo_ShouldCreateAndPopulateCreditCardPayment doReturn(CC_PAYMENT_INFO_MODEL_CODE).when(testObj).generateCcPaymentInfoCode(cartModelMock); when(createTokenResponseMock.getToken()).thenReturn(tokenReplyMock); when(tokenReplyMock.getTokenDetails().getTokenEvent()).thenReturn(NEW); - when(tokenReplyMock.getPaymentInstrument().getPaymentType()).thenReturn(PaymentType.VISA); + when(tokenReplyMock.getPaymentInstrument().getPaymentType()).thenReturn(PaymentType.VISA.getMethodCode()); when(tokenReplyMock.getPaymentInstrument().getBin()).thenReturn(BIN); when(cartModelMock.getPaymentAddress()).thenReturn(paymentAddressModelMock); doReturn(clonedAddressMock).when(testObj).cloneAndSetBillingAddressFromCart(cartModelMock, creditCardPaymentInfoModelMock); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPrimeRoutingServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPrimeRoutingServiceTest.java new file mode 100644 index 00000000..da596eaa --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/core/services/impl/DefaultWorldpayPrimeRoutingServiceTest.java @@ -0,0 +1,102 @@ +package com.worldpay.core.services.impl; + +import com.worldpay.core.services.WorldpayHybrisOrderService; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.core.model.order.CartModel; +import de.hybris.platform.core.model.order.OrderModel; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.order.CartService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Answers; +import org.mockito.InOrder; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayPrimeRoutingServiceTest { + + private static final String WORLDPAY_ORDER_CODE = "worldpayOrderCode"; + private static final String US_COUNTRY_ISO_CODE = "US"; + + @InjectMocks + private DefaultWorldpayPrimeRoutingService testObj; + + @Mock + private CartService cartService; + @Mock + private WorldpayHybrisOrderService worldpayHybrisOrderServiceMock; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private CartModel cartMock; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private AddressModel addressMock; + @Mock + private OrderModel orderMock; + + @Before + public void setUp() { + when(cartMock.getSite().getEnablePR()).thenReturn(true); + when(cartMock.getPaymentAddress()).thenReturn(addressMock); + when(addressMock.getCountry().getIsocode()).thenReturn(US_COUNTRY_ISO_CODE); + } + + @Test + public void isPrimeRoutingEnabled_WhenPrimeRoutingEnabledAndUSBillingAddress_ShouldReturnTrue() { + boolean result = testObj.isPrimeRoutingEnabled(cartMock); + + assertThat(result).isTrue(); + } + + @Test + public void isPrimeRoutingEnabled_WhenPrimeRoutingEnabledAndNotUSBillingAddress_ShouldReturnFalse() { + when(addressMock.getCountry().getIsocode()).thenReturn("UK"); + + boolean result = testObj.isPrimeRoutingEnabled(cartMock); + + assertThat(result).isFalse(); + } + + @Test + public void isPrimeRoutingEnabled_WhenPrimeRoutingDisabled_ShouldReturnFalse() { + when(cartMock.getSite().getEnablePR()).thenReturn(false); + + boolean result = testObj.isPrimeRoutingEnabled(cartMock); + + assertThat(result).isFalse(); + } + + @Test + public void isPrimeRoutingEnabled_WhenPrimeRoutingEnabledAndBillingAddressIsNull_ShouldReturnFalse() { + when(cartMock.getPaymentAddress()).thenReturn(null); + + boolean result = testObj.isPrimeRoutingEnabled(cartMock); + + assertThat(result).isFalse(); + } + + @Test + public void setAuthorisedWithPrimeRoutingOnCart_ShouldSetFlagOnCart() { + testObj.setAuthorisedWithPrimeRoutingOnCart(cartMock); + + final InOrder inOrder = inOrder(cartMock, cartService); + inOrder.verify(cartMock).setIsPrimeRouteAuth(Boolean.TRUE); + inOrder.verify(cartService).saveOrder(cartMock); + } + + @Test + public void isOrderAuthorisedWithPrimeRouting_WhenOrderAuthorisedWithPrimeRouting_ShouldReturnTrue() { + when(worldpayHybrisOrderServiceMock.findOrderByWorldpayOrderCode(WORLDPAY_ORDER_CODE)).thenReturn(orderMock); + when(orderMock.getIsPrimeRouteAuth()).thenReturn(Boolean.TRUE); + + boolean result = testObj.isOrderAuthorisedWithPrimeRouting(WORLDPAY_ORDER_CODE); + + assertThat(result).isTrue(); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/customer/impl/DefaultWorldpayCustomerAccountServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/customer/impl/DefaultWorldpayCustomerAccountServiceTest.java index d6d91585..e24e87c1 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/customer/impl/DefaultWorldpayCustomerAccountServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/customer/impl/DefaultWorldpayCustomerAccountServiceTest.java @@ -3,7 +3,7 @@ import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.exception.WorldpayException; import com.worldpay.merchant.WorldpayMerchantInfoService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayDirectOrderService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.order.payment.CreditCardPaymentInfoModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/impl/DefaultWorldpayAPMComponentFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/impl/DefaultWorldpayAPMComponentFacadeTest.java new file mode 100644 index 00000000..296db1c0 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/impl/DefaultWorldpayAPMComponentFacadeTest.java @@ -0,0 +1,56 @@ +package com.worldpay.facades.impl; + +import com.worldpay.core.services.WorldpayAPMComponentService; +import com.worldpay.data.cms.WorldpayAPMComponentData; +import com.worldpay.model.WorldpayAPMComponentModel; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayAPMComponentFacadeTest { + + @InjectMocks + private DefaultWorldpayAPMComponentFacade testObj; + + @Mock + private WorldpayAPMComponentService worldpayAPMComponentServiceMock; + @Mock + private Converter worldpayAPMComponentConverterMock; + + @Mock + private WorldpayAPMComponentData worldpayAPMComponentData1Mock, worldpayAPMComponentData2Mock; + @Mock + private WorldpayAPMComponentModel worldpayAPMComponentModel1Mock, worldpayAPMComponentModel2Mock; + + @Test + public void getAllAvailableWorldpayAPMComponents_WhenThereAreAvailableComponents_ShouldReturnAListOfComponentData() { + when(worldpayAPMComponentServiceMock.getAllAvailableWorldpayAPMComponents()).thenReturn(List.of(worldpayAPMComponentModel1Mock, worldpayAPMComponentModel2Mock)); + when(worldpayAPMComponentConverterMock.convertAll(List.of(worldpayAPMComponentModel1Mock, worldpayAPMComponentModel2Mock))).thenReturn(List.of(worldpayAPMComponentData1Mock, worldpayAPMComponentData2Mock)); + + final List result = testObj.getAllAvailableWorldpayAPMComponents(); + + assertThat(result).isEqualTo(List.of(worldpayAPMComponentData1Mock, worldpayAPMComponentData2Mock)); + } + + @Test + public void getAllAvailableWorldpayAPMComponents_WhenThereAreNotAvailableComponents_ShouldReturnAnEmptyList() { + when(worldpayAPMComponentServiceMock.getAllAvailableWorldpayAPMComponents()).thenReturn(Collections.emptyList()); + when(worldpayAPMComponentConverterMock.convertAll(Collections.emptyList())).thenReturn(Collections.emptyList()); + + final List result = testObj.getAllAvailableWorldpayAPMComponents(); + + assertThat(result).isEmpty(); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/impl/DefaultWorldpayCartFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/impl/DefaultWorldpayCartFacadeTest.java index 1d4162f0..7d646da6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/impl/DefaultWorldpayCartFacadeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/impl/DefaultWorldpayCartFacadeTest.java @@ -24,6 +24,7 @@ public class DefaultWorldpayCartFacadeTest { @InjectMocks private DefaultWorldpayCartFacade testObj; + @Mock private WorldpayCartService worldpayCartServiceMock; @Mock diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/order/impl/DefaultWorldpayKlarnaPaymentCheckoutFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/order/impl/DefaultWorldpayKlarnaPaymentCheckoutFacadeTest.java index c0d4a55a..3529fc65 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/order/impl/DefaultWorldpayKlarnaPaymentCheckoutFacadeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/order/impl/DefaultWorldpayKlarnaPaymentCheckoutFacadeTest.java @@ -6,8 +6,8 @@ import com.worldpay.hostedorderpage.data.KlarnaRedirectAuthoriseResult; import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.request.KlarnaOrderInquiryServiceRequest; import com.worldpay.service.response.OrderInquiryServiceResponse; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/order/impl/DefaultWorldpayPaymentCheckoutFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/order/impl/DefaultWorldpayPaymentCheckoutFacadeTest.java index c309515d..30ae75a8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/order/impl/DefaultWorldpayPaymentCheckoutFacadeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/order/impl/DefaultWorldpayPaymentCheckoutFacadeTest.java @@ -1,6 +1,7 @@ package com.worldpay.facades.order.impl; import com.worldpay.core.checkout.WorldpayCheckoutService; +import com.worldpay.service.payment.WorldpayFraudSightStrategy; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.commercefacades.order.CheckoutFacade; import de.hybris.platform.commercefacades.user.data.AddressData; @@ -16,6 +17,7 @@ import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; @@ -37,6 +39,8 @@ public class DefaultWorldpayPaymentCheckoutFacadeTest { private CartService cartServiceMock; @Mock private CustomerAccountService customerAccountServiceMock; + @Mock + private WorldpayFraudSightStrategy worldpayFraudSightStrategyMock; @Mock private AddressData addressDataMock; @@ -55,21 +59,19 @@ public void setUp() { when(cartServiceMock.getSessionCart()).thenReturn(cartModelMock); when(cartModelMock.getUser()).thenReturn(customerModelMock); when(customerAccountServiceMock.getAddressForCode(customerModelMock, ADDRESS_DATA_ID)).thenReturn(addressModelMock); + when(addressDataMock.getId()).thenReturn(ADDRESS_DATA_ID); + when(worldpayFraudSightStrategyMock.isFraudSightEnabled()).thenReturn(true); } @Test - public void setBillingDetailsSetsPaymentAddressWhenPkMatchesAddressDataId() { - when(addressDataMock.getId()).thenReturn(ADDRESS_DATA_ID); - when(customerAccountServiceMock.getAddressForCode(customerModelMock, ADDRESS_DATA_ID)).thenReturn(addressModelMock); - + public void setBillingDetails_WhenPkMatchesAddressDataId_ShouldSetPaymentAddress() { testObj.setBillingDetails(addressDataMock); verify(worldpayCheckoutServiceMock).setPaymentAddress(cartModelMock, addressModelMock); } @Test - public void setBillingDetailsDoesNotSetPaymentAddressWhenPkDoesNotMatchesAddressDataId() { - when(addressDataMock.getId()).thenReturn(ADDRESS_DATA_ID); + public void setBillingDetails_WhenPkDoesNotMatchesAddressDataId_ShouldNotSetPaymentAddress() { when(customerAccountServiceMock.getAddressForCode(customerModelMock, ADDRESS_DATA_ID)).thenReturn(null); testObj.setBillingDetails(addressDataMock); @@ -78,8 +80,7 @@ public void setBillingDetailsDoesNotSetPaymentAddressWhenPkDoesNotMatchesAddress } @Test - public void setBillingDetailsDoesNotSetPaymentAddressWhenNoDeliveryAddressesReturned() { - when(addressDataMock.getId()).thenReturn(ADDRESS_DATA_ID); + public void setBillingDetails_WhenNoDeliveryAddressesReturned_ShouldNotSetPaymentAddress() { when(customerAccountServiceMock.getAddressForCode(customerModelMock, ADDRESS_DATA_ID)).thenReturn(null); testObj.setBillingDetails(addressDataMock); @@ -88,23 +89,70 @@ public void setBillingDetailsDoesNotSetPaymentAddressWhenNoDeliveryAddressesRetu } @Test - public void hasBillingDetailsReturnsFalseWhenCartIsNull() { + public void hasBillingDetails_WhenCartIsNull_ShouldReturnFalse() { when(cartServiceMock.getSessionCart()).thenReturn(null); + final boolean result = testObj.hasBillingDetails(); + assertFalse(result); } @Test - public void hasBillingDetailsReturnsFalseWhenPaymentAddressIsNull() { + public void hasBillingDetails_WhenPaymentAddressIsNull_ShouldReturnFalse() { when(cartModelMock.getPaymentAddress()).thenReturn(null); + final boolean result = testObj.hasBillingDetails(); + assertFalse(result); } @Test - public void hasBillingDetailsReturnsTrueWhenCartModelAndPaymentAddressAreNotNull() { + public void hasBillingDetails_WhenCartModelAndPaymentAddressAreNotNull_ShouldReturnTrue() { when(cartModelMock.getPaymentAddress()).thenReturn(paymentAddressMock); + final boolean result = testObj.hasBillingDetails(); + assertTrue(result); } + + @Test + public void isFSEnabled_WhenFSIsEnabled_ShouldReturnTrue() { + final boolean result = testObj.isFSEnabled(); + + assertThat(result).isTrue(); + } + + @Test + public void isFSEnabled_WhenFSIsDisabled_ShouldReturnFalse() { + when(worldpayFraudSightStrategyMock.isFraudSightEnabled()).thenReturn(false); + + final boolean result = testObj.isFSEnabled(); + + assertThat(result).isFalse(); + } + + @Test + public void setShippingAndBillingDetails_WhenPkMatchesAddressDataId_ShouldSetPaymentAddress() { + testObj.setShippingAndBillingDetails(addressDataMock); + + verify(worldpayCheckoutServiceMock).setShippingAndPaymentAddress(cartModelMock, addressModelMock); + } + + @Test + public void setShippingAndBillingDetails_WhenPkDoesNotMatchesAddressDataId_ShouldNotSetPaymentAddress() { + when(customerAccountServiceMock.getAddressForCode(customerModelMock, ADDRESS_DATA_ID)).thenReturn(null); + + testObj.setShippingAndBillingDetails(addressDataMock); + + verify(worldpayCheckoutServiceMock, never()).setShippingAndPaymentAddress(cartModelMock, addressModelMock); + } + + @Test + public void setShippingAndBillingDetails_WhenNoDeliveryAddressesReturned_ShouldNotSetPaymentAddress() { + when(customerAccountServiceMock.getAddressForCode(customerModelMock, ADDRESS_DATA_ID)).thenReturn(null); + + testObj.setBillingDetails(addressDataMock); + + verify(worldpayCheckoutServiceMock, never()).setShippingAndPaymentAddress(cartModelMock, addressModelMock); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/direct/impl/DefaultWorldpayDirectOrderFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/direct/impl/DefaultWorldpayDirectOrderFacadeTest.java index e560f46a..19f3f7cb 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/direct/impl/DefaultWorldpayDirectOrderFacadeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/direct/impl/DefaultWorldpayDirectOrderFacadeTest.java @@ -1,21 +1,19 @@ package com.worldpay.facades.payment.direct.impl; +import com.worldpay.core.services.WorldpayCartService; import com.worldpay.core.services.WorldpayPaymentInfoService; import com.worldpay.data.*; +import com.worldpay.data.payment.Card; +import com.worldpay.data.token.TokenDetails; +import com.worldpay.data.token.TokenReply; import com.worldpay.enums.order.AuthorisedStatus; import com.worldpay.exception.WorldpayException; -import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.model.GooglePayPaymentInfoModel; import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.payment.DirectResponseData; import com.worldpay.payment.TransactionStatus; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Card; -import com.worldpay.service.model.token.TokenDetails; -import com.worldpay.service.model.token.TokenReply; import com.worldpay.service.payment.WorldpayDirectOrderService; import com.worldpay.service.response.DirectAuthoriseServiceResponse; -import com.worldpay.strategy.WorldpayAuthenticatedShopperIdStrategy; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.acceleratorfacades.order.AcceleratorCheckoutFacade; import de.hybris.platform.commercefacades.order.data.CCPaymentInfoData; @@ -66,8 +64,10 @@ public class DefaultWorldpayDirectOrderFacadeTest { private static final String TRANSACTION_ID_3DS = "transactionId3Ds"; private static final String PAYMENT_TOKEN_ID = "paymentTokenId"; private static final String CARD_NUMBER = "cardNumber"; + private static final String MONTH = "01"; + private static final String YEAR = "2025"; - final Date expiryDate = new Date("01", "2025"); + Date expiryDate; @Rule @SuppressWarnings("PMD.MemberScope") @@ -86,14 +86,12 @@ public class DefaultWorldpayDirectOrderFacadeTest { @Mock private WorldpayDirectOrderService worldpayDirectOrderServiceMock; @Mock - private WorldpayAuthenticatedShopperIdStrategy worldpayAuthenticatedShopperIdStrategyMock; + private WorldpayCartService worldpayCartServiceMock; @Mock private WorldpayPaymentInfoService worldpayPaymentInfoServiceMock; @Mock private AcceleratorCheckoutFacade acceleratorCheckoutFacadeMock; @Mock - private WorldpayMerchantInfoService worldpayMerchantInfoServiceMock; - @Mock private Populator apmPaymentInfoPopulatorMock; @Mock @@ -146,8 +144,12 @@ public void setUp() throws Exception { when(directAuthoriseServiceResponseMock.getPaymentReply()).thenReturn(paymentReplyMock); when(directAuthoriseServiceResponse3dSecureMock.getPaymentReply()).thenReturn(paymentReplyMock); when(paymentReplyMock.getAuthStatus()).thenReturn(AuthorisedStatus.AUTHORISED); - when(worldpayAuthenticatedShopperIdStrategyMock.getAuthenticatedShopperId(userModelMock)).thenReturn(AUTHENTICATED_SHOPPER_ID); + when(worldpayCartServiceMock.getAuthenticatedShopperId(cartModelMock)).thenReturn(AUTHENTICATED_SHOPPER_ID); when(worldpayDirectOrderServiceMock.createTokenAndAuthorise(cartModelMock, worldpayAdditionalInfoDataMock, cseAdditionalAuthInfoMock)).thenReturn(directAuthoriseServiceResponseMock); + final Date date = new Date(); + date.setMonth(MONTH); + date.setYear(YEAR); + this.expiryDate = date; } @Test @@ -696,7 +698,6 @@ public void executeFirstPaymentAuthorisation3DSecure_shouldAuthorizeRecurringPay testObj.executeFirstPaymentAuthorisation3DSecure(cseAdditionalAuthInfoMock, worldpayAdditionalInfoDataMock); // then - verify(worldpayMerchantInfoServiceMock).getCurrentSiteMerchant(); verify(worldpayDirectOrderServiceMock).authoriseRecurringPayment(cartModelMock, worldpayAdditionalInfoDataMock); verify(worldpayDirectOrderServiceMock).completeAuthorise(directAuthoriseServiceResponseMock, cartModelMock); verifyNoMoreInteractions(worldpayDirectOrderServiceMock); @@ -759,4 +760,5 @@ public void populateApmAttributes_ShouldPopulateApmAttributes() { verify(apmPaymentInfoPopulatorMock).populate(googlePayPaymentInfoMock, ccPaymentInfoData); } + } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayAfterRedirectValidationFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayAfterRedirectValidationFacadeTest.java index 874f15b4..27e53c61 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayAfterRedirectValidationFacadeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayAfterRedirectValidationFacadeTest.java @@ -2,7 +2,7 @@ import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.merchant.WorldpayMerchantInfoService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayAfterRedirectValidationService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.session.SessionService; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayHostedOrderFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayHostedOrderFacadeTest.java index 72f25406..3355bf78 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayHostedOrderFacadeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/hosted/impl/DefaultWorldpayHostedOrderFacadeTest.java @@ -9,7 +9,7 @@ import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.merchant.strategies.WorldpayOrderInfoStrategy; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayRedirectOrderService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.order.CartModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/merchant/converters/populators/WorldPayMerchantConfigDataPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/merchant/converters/populators/WorldPayMerchantConfigDataPopulatorTest.java new file mode 100644 index 00000000..cb8d9b30 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/merchant/converters/populators/WorldPayMerchantConfigDataPopulatorTest.java @@ -0,0 +1,149 @@ +package com.worldpay.facades.payment.merchant.converters.populators; + +import com.worldpay.config.merchant.WorldpayMerchantConfigData; +import com.worldpay.enums.*; +import com.worldpay.model.WorldpayApplePayConfigurationModel; +import com.worldpay.model.WorldpayGooglePayConfigurationModel; +import com.worldpay.model.WorldpayMerchantConfigurationModel; +import com.worldpay.model.WorldpayThreeDS2JsonWebTokenConfigurationModel; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Set; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class WorldPayMerchantConfigDataPopulatorTest { + + private static final String CARD_TYPE = "CARD"; + private static final String MERCHANT_CODE = "merchantCode"; + private static final String MAC_SECRET = "macSecret"; + private static final String MERCHANT_PASSWORD = "password"; + private static final String CSE_PUBLIC_KEY_VALUE = "csePublicKeyValue"; + private static final String INSTALLATION_ID = "installationId"; + private static final String STATEMENT_NARRATIVE_TEXT = "STATEMENT NARRATIVE TEXT"; + private static final String ORDER_CONTENT = "orderContent"; + private static final String CHALLENGE_PREFERENCE = "challengePreference"; + private static final String COUNTRY_CODE = "countryCode"; + private static final String MERCHANT_ID = "merchantId"; + private static final String MERCHANT_NAME = "Merchant name"; + private static final String MERCHANT_NAME_VALUE = "merchant_name"; + private static final String MERCHANT_ID_VALUE = "merchant_id"; + private static final String GATEWAY_MERCHANT_ID_VALUE = "Gateway merchant id"; + private static final String ISS_VALUE = "5bd9e0e4444dce153428c940"; + private static final String JWT_MAC_KEY_VALUE = "fa2daee2-1fbb-45ff-4444-52805d5cd9e0"; + private static final String ORG_UNIT_ID_VALUE = "5bd9b55e4444761ac0af1c80"; + private static final String ALG_VALUE = "alg"; + private static final String EVENT_ORIGIN_DOMAIN = "EVENT_ORIGIN_DOMAIN"; + private static final String ISSUER_URL_VALUE = "acsURLValue"; + private static final String RETURN_URL_VALUE = "ReturnURLValue"; + + @InjectMocks + private WorldPayMerchantConfigDataPopulator testObj; + + @Mock + private WorldpayMerchantConfigurationModel worldpayMerchantConfigurationMock; + @Mock + private WorldpayThreeDS2JsonWebTokenConfigurationModel threeDSFlexJsonWebTokenSettingsMock; + @Mock + private WorldpayGooglePayConfigurationModel googlePayConfigurationMock; + @Mock + private WorldpayApplePayConfigurationModel applePayConfigurationMock; + + private WorldpayMerchantConfigData targetData = new WorldpayMerchantConfigData(); + + @Before + public void setUp() { + when(worldpayMerchantConfigurationMock.getCode()).thenReturn(MERCHANT_CODE); + when(worldpayMerchantConfigurationMock.getPassword()).thenReturn(MERCHANT_PASSWORD); + when(worldpayMerchantConfigurationMock.getMacSecret()).thenReturn(MAC_SECRET); + when(worldpayMerchantConfigurationMock.getMacValidation()).thenReturn(true); + when(worldpayMerchantConfigurationMock.getCsePublicKey()).thenReturn(CSE_PUBLIC_KEY_VALUE); + when(worldpayMerchantConfigurationMock.getInstallationId()).thenReturn(INSTALLATION_ID); + when(worldpayMerchantConfigurationMock.getStatementNarrative()).thenReturn(STATEMENT_NARRATIVE_TEXT); + when(worldpayMerchantConfigurationMock.getOrderContent()).thenReturn(ORDER_CONTENT); + when(worldpayMerchantConfigurationMock.getThreeDSFlexChallengePreference()).thenReturn(ChallengePreference.NOPREFERENCE); + + mockApplePayConfiguration(); + mockGooglePayConfiguration(); + mockThreeDSFlexJsonWebTokenSettings(); + } + + @Test + public void populate_shouldPopulateTheMerchantData() { + testObj.populate(worldpayMerchantConfigurationMock, targetData); + + assertEquals(MERCHANT_CODE, targetData.getCode()); + assertEquals(MERCHANT_PASSWORD, targetData.getPassword()); + assertEquals(MAC_SECRET, targetData.getMacSecret()); + assertEquals(true, targetData.getMacValidation()); + assertEquals(CSE_PUBLIC_KEY_VALUE, targetData.getCsePublicKey()); + assertEquals(INSTALLATION_ID, targetData.getInstallationId()); + assertEquals(STATEMENT_NARRATIVE_TEXT, targetData.getStatementNarrative()); + assertEquals(ORDER_CONTENT, targetData.getOrderContent()); + assertEquals(ChallengePreference.NOPREFERENCE.getCode(), targetData.getThreeDSFlexChallengePreference()); + + assertNotNull(targetData.getApplePaySettings()); + assertEquals(COUNTRY_CODE, targetData.getApplePaySettings().getCountryCode()); + assertEquals(MERCHANT_ID, targetData.getApplePaySettings().getMerchantId()); + assertEquals(MERCHANT_NAME, targetData.getApplePaySettings().getMerchantName()); + assertTrue(targetData.getApplePaySettings().getMerchantCapabilities().contains(ApplePayMerchantCapabilities.SUPPORTS3DS.getCode())); + assertTrue(targetData.getApplePaySettings().getSupportedNetworks().contains(ApplePaySupportedNetworks.CARTESBANCAIRES.getCode())); + + assertNotNull(targetData.getGooglePaySettings()); + assertEquals(GATEWAY_MERCHANT_ID_VALUE, targetData.getGooglePaySettings().getGatewayMerchantId()); + assertEquals(MERCHANT_ID_VALUE, targetData.getGooglePaySettings().getMerchantId()); + assertEquals(MERCHANT_NAME_VALUE, targetData.getGooglePaySettings().getMerchantName()); + assertEquals(EnvironmentType.TEST.getCode(), targetData.getGooglePaySettings().getEnvironment()); + assertTrue(targetData.getGooglePaySettings().getAllowedAuthMethods().contains(GooglePayCardAuthMethods.PAN_ONLY.getCode())); + assertTrue(targetData.getGooglePaySettings().getAllowedCardNetworks().contains(GooglePayCardNetworks.AMEX.getCode())); + + assertNotNull(targetData.getThreeDSFlexJsonWebTokenSettings()); + assertEquals(ALG_VALUE, targetData.getThreeDSFlexJsonWebTokenSettings().getAlg()); + assertEquals(ISS_VALUE, targetData.getThreeDSFlexJsonWebTokenSettings().getIss()); + assertEquals(ORG_UNIT_ID_VALUE, targetData.getThreeDSFlexJsonWebTokenSettings().getOrgUnitId()); + assertEquals(JWT_MAC_KEY_VALUE, targetData.getThreeDSFlexJsonWebTokenSettings().getJwtMacKey()); + assertEquals(EVENT_ORIGIN_DOMAIN, targetData.getThreeDSFlexJsonWebTokenSettings().getEventOriginDomain()); + assertEquals(ISSUER_URL_VALUE, targetData.getThreeDSFlexJsonWebTokenSettings().getChallengeUrl()); + assertEquals(RETURN_URL_VALUE, targetData.getThreeDSFlexJsonWebTokenSettings().getDdcUrl()); + } + + private void mockThreeDSFlexJsonWebTokenSettings() { + when(threeDSFlexJsonWebTokenSettingsMock.getAlg()).thenReturn(ALG_VALUE); + when(threeDSFlexJsonWebTokenSettingsMock.getIss()).thenReturn(ISS_VALUE); + when(threeDSFlexJsonWebTokenSettingsMock.getOrgUnitId()).thenReturn(ORG_UNIT_ID_VALUE); + when(threeDSFlexJsonWebTokenSettingsMock.getJwtMacKey()).thenReturn(JWT_MAC_KEY_VALUE); + when(threeDSFlexJsonWebTokenSettingsMock.getEventOriginDomain()).thenReturn(EVENT_ORIGIN_DOMAIN); + when(threeDSFlexJsonWebTokenSettingsMock.getChallengeUrl()).thenReturn(ISSUER_URL_VALUE); + when(threeDSFlexJsonWebTokenSettingsMock.getDdcUrl()).thenReturn(RETURN_URL_VALUE); + when(worldpayMerchantConfigurationMock.getThreeDSFlexJsonWebTokenSettings()).thenReturn(threeDSFlexJsonWebTokenSettingsMock); + } + + private void mockGooglePayConfiguration() { + when(googlePayConfigurationMock.getMerchantId()).thenReturn(MERCHANT_ID_VALUE); + when(googlePayConfigurationMock.getMerchantName()).thenReturn(MERCHANT_NAME_VALUE); + when(googlePayConfigurationMock.getCardType()).thenReturn(CARD_TYPE); + when(googlePayConfigurationMock.getEnvironment()).thenReturn(EnvironmentType.TEST); + when(googlePayConfigurationMock.getGatewayMerchantId()).thenReturn(GATEWAY_MERCHANT_ID_VALUE); + when(googlePayConfigurationMock.getAllowedAuthMethods()).thenReturn(Set.of(GooglePayCardAuthMethods.PAN_ONLY, GooglePayCardAuthMethods.CRYPTOGRAM_3DS)); + when(googlePayConfigurationMock.getAllowedCardNetworks()).thenReturn(Set.of(GooglePayCardNetworks.AMEX, GooglePayCardNetworks.DISCOVER)); + when(worldpayMerchantConfigurationMock.getGooglePayConfiguration()).thenReturn(googlePayConfigurationMock); + } + + private void mockApplePayConfiguration() { + when(applePayConfigurationMock.getCountryCode()).thenReturn(COUNTRY_CODE); + when(applePayConfigurationMock.getMerchantId()).thenReturn(MERCHANT_ID); + when(applePayConfigurationMock.getMerchantName()).thenReturn(MERCHANT_NAME); + when(applePayConfigurationMock.getMerchantCapabilities()).thenReturn(Set.of(ApplePayMerchantCapabilities.SUPPORTS3DS, ApplePayMerchantCapabilities.SUPPORTSCREDIT)); + when(applePayConfigurationMock.getSupportedNetworks()).thenReturn(Set.of(ApplePaySupportedNetworks.MADA, ApplePaySupportedNetworks.CARTESBANCAIRES)); + when(worldpayMerchantConfigurationMock.getApplePayConfiguration()).thenReturn(applePayConfigurationMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/merchant/impl/DefaultWorldpayMerchantConfigDataFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/merchant/impl/DefaultWorldpayMerchantConfigDataFacadeTest.java index 2d18346f..0e8f784b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/merchant/impl/DefaultWorldpayMerchantConfigDataFacadeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/facades/payment/merchant/impl/DefaultWorldpayMerchantConfigDataFacadeTest.java @@ -1,8 +1,10 @@ package com.worldpay.facades.payment.merchant.impl; import com.worldpay.config.merchant.WorldpayMerchantConfigData; +import com.worldpay.model.WorldpayMerchantConfigurationModel; import com.worldpay.strategy.WorldpayMerchantStrategy; import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,23 +16,28 @@ import static org.mockito.Mockito.when; @UnitTest -@RunWith (MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class DefaultWorldpayMerchantConfigDataFacadeTest { @InjectMocks private DefaultWorldpayMerchantConfigDataFacade testObj; @Mock - private WorldpayMerchantConfigData worldpayMerchantConfigDataMock; + private WorldpayMerchantConfigurationModel worldpayMerchantConfigMock; @Mock private WorldpayMerchantStrategy worldpayMerchantStrategyMock; + @Mock + private Converter worldPayMerchantConfigDataConverter; + @Mock + private WorldpayMerchantConfigData worldpayMerchantConfigDataMock; @Before public void setUp() { - when(worldpayMerchantStrategyMock.getMerchant()).thenReturn(worldpayMerchantConfigDataMock); + when(worldpayMerchantStrategyMock.getMerchant()).thenReturn(worldpayMerchantConfigMock); + when(worldPayMerchantConfigDataConverter.convert(worldpayMerchantConfigMock)).thenReturn(worldpayMerchantConfigDataMock); } @Test - public void shouldReturnWebSiteMerchantConfigData() throws Exception { + public void shouldReturnWebSiteMerchantConfigData() { final WorldpayMerchantConfigData result = testObj.getCurrentSiteMerchantConfigData(); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/fulfilmentprocess/actions/order/WorldpayTakePaymentActionTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/fulfilmentprocess/actions/order/WorldpayTakePaymentActionTest.java index c05834e4..f56165ea 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/fulfilmentprocess/actions/order/WorldpayTakePaymentActionTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/fulfilmentprocess/actions/order/WorldpayTakePaymentActionTest.java @@ -73,7 +73,7 @@ public void setUp() { } @Test - public void execute_WhenExistingPendingCaptureEntry_ShouldReturnWAIT(){ + public void execute_WhenExistingPendingCaptureEntry_ShouldReturnWAIT() { when(worldpayPaymentTransactionServiceMock.areAllPaymentTransactionsAcceptedForType(orderMock, CAPTURE)).thenReturn(true); when(worldpayPaymentTransactionServiceMock.isPaymentTransactionPending(paymentTransactionMock, CAPTURE)).thenReturn(true); @@ -122,7 +122,7 @@ public void execute_WhenThereIsNotCapture_ShouldReturnWAITAndUpdatesOrderStatus( @Test public void execute_WhenThereIsMoreThanOneTransactionEntry_ShouldReturnNOK() { when(worldpayPaymentTransactionServiceMock.filterPaymentTransactionEntriesOfType(paymentTransactionMock, CAPTURE)). - thenReturn(Arrays.asList(paymentTransactionEntryModelMock, paymentTransactionEntryModelMock2)); + thenReturn(Arrays.asList(paymentTransactionEntryModelMock, paymentTransactionEntryModelMock2)); when(paymentServiceMock.capture(paymentTransactionMock)).thenReturn(paymentTransactionEntryModelMock); when(paymentTransactionEntryModelMock.getTransactionStatus()).thenReturn(TransactionStatus.ACCEPTED.name()); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/hostedorderpage/converters/RedirectAuthoriseResultPopulatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/hostedorderpage/converters/RedirectAuthoriseResultPopulatorTest.java index fb29736d..2aa7ddd3 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/hostedorderpage/converters/RedirectAuthoriseResultPopulatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/hostedorderpage/converters/RedirectAuthoriseResultPopulatorTest.java @@ -2,7 +2,7 @@ import com.worldpay.enums.order.AuthorisedStatus; import com.worldpay.hostedorderpage.data.RedirectAuthoriseResult; -import com.worldpay.service.model.Amount; +import com.worldpay.data.Amount; import com.worldpay.service.payment.WorldpayOrderService; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Test; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/interceptors/WorldpayPaymentInfoRemoveInterceptorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/interceptors/WorldpayPaymentInfoRemoveInterceptorTest.java index ece96c6a..1320bc81 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/interceptors/WorldpayPaymentInfoRemoveInterceptorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/interceptors/WorldpayPaymentInfoRemoveInterceptorTest.java @@ -1,7 +1,7 @@ package com.worldpay.interceptors; import com.worldpay.merchant.WorldpayMerchantInfoService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayDirectOrderService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.order.payment.CreditCardPaymentInfoModel; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/jalo/WorldpayapiTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/jalo/WorldpayapiTest.java deleted file mode 100644 index c196752a..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/jalo/WorldpayapiTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * [y] hybris Platform - * - * Copyright (c) 2000-2013 hybris AG - * All rights reserved. - * - * This software is the confidential and proprietary information of hybris - * ("Confidential Information"). You shall not disclose such Confidential - * Information and shall use it only in accordance with the terms of the - * license agreement you entered into with hybris. - * - * - */ -package com.worldpay.jalo; - -import static org.junit.Assert.assertTrue; - -import de.hybris.platform.testframework.HybrisJUnit4TransactionalTest; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - - -/** - * JUnit Tests for the Worldpayapi extension - */ -public class WorldpayapiTest extends HybrisJUnit4TransactionalTest -{ - /** Edit the local|project.properties to change logging behaviour (properties log4j.*). */ - @SuppressWarnings("unused") - private static final Logger LOG = Logger.getLogger(WorldpayapiTest.class.getName()); - - @Before - public void setUp() - { - // implement here code executed before each test - } - - @After - public void tearDown() - { - // implement here code executed after each test - } - - /** - * This is a sample test method. - */ - @Test - public void testWorldpayapi() - { - final boolean testTrue = true; - assertTrue("true is not true", testTrue); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/klarna/impl/DefaultWorldpayKlarnaUtilsTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/klarna/impl/DefaultWorldpayKlarnaUtilsTest.java deleted file mode 100644 index 11e097a9..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/klarna/impl/DefaultWorldpayKlarnaUtilsTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.worldpay.klarna.impl; - -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; - -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class DefaultWorldpayKlarnaUtilsTest { - - private static final String KLARNA_1 = "klarna1"; - private static final String KLARNA_2 = " klarna2"; - private static final String KLARNA_3 = "klarna3"; - private static final String NON_KLARNA = "nonKlarna"; - - private DefaultWorldpayKlarnaUtils testObj; - - private final List klarnaPaymentMethods = List.of(KLARNA_1, KLARNA_2, KLARNA_3); - - @Before - public void setUp() throws Exception { - testObj = new DefaultWorldpayKlarnaUtils(klarnaPaymentMethods); - } - - @Test - public void isKlarnaPaymentType_shouldReturnTrueWhenCodeIsInKlarnaPaymentMethodsList() { - final boolean result = testObj.isKlarnaPaymentType(KLARNA_2); - - assertThat(result).isTrue(); - } - - @Test - public void isKlarnaPaymentType_shouldReturnFalseWhenCodeIsNotInKlarnaPaymentMethodsList() { - final boolean result = testObj.isKlarnaPaymentType(NON_KLARNA); - - assertThat(result).isFalse(); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/configuration/services/impl/DefaultWorldpayMerchantConfigurationServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/configuration/services/impl/DefaultWorldpayMerchantConfigurationServiceTest.java new file mode 100644 index 00000000..6c5dc4b7 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/configuration/services/impl/DefaultWorldpayMerchantConfigurationServiceTest.java @@ -0,0 +1,112 @@ +package com.worldpay.merchant.configuration.services.impl; + +import com.worldpay.model.WorldpayMerchantConfigurationModel; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.cms2.model.site.CMSSiteModel; +import de.hybris.platform.site.BaseSiteService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Set; + +import static java.util.Arrays.asList; +import static org.junit.Assert.*; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayMerchantConfigurationServiceTest { + + private static final String BASE_SITE_ID = "base-site-id"; + + @InjectMocks + private DefaultWorldpayMerchantConfigurationService testObj; + + @Mock + private BaseSiteService baseSiteServiceMock; + @Mock + private CMSSiteModel siteMock1, siteMock2, siteMock3; + @Mock + private WorldpayMerchantConfigurationModel webMerchantConfigurationMock, asmMerchantConfigurationMock, replenishmentMerchantConfigurationMock; + + @Before + public void setUp() { + when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(siteMock1); + when(baseSiteServiceMock.getBaseSiteForUID(BASE_SITE_ID)).thenReturn(siteMock1); + } + + @Test + public void getCurrentWebConfiguration_ShouldReturnTheValueAsExpected() { + when(siteMock1.getWebMerchantConfiguration()).thenReturn(webMerchantConfigurationMock); + + final WorldpayMerchantConfigurationModel result = testObj.getCurrentWebConfiguration(); + + assertSame(webMerchantConfigurationMock, result); + } + + @Test(expected = IllegalArgumentException.class) + public void getCurrentWebConfiguration_WhenSiteNull_ShouldThrowException() { + when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(null); + + testObj.getCurrentWebConfiguration(); + } + + @Test + public void getCurrentAsmConfiguration_ShouldReturnTheValueAsExpected() { + when(siteMock1.getAsmMerchantConfiguration()).thenReturn(asmMerchantConfigurationMock); + + final WorldpayMerchantConfigurationModel result = testObj.getCurrentAsmConfiguration(); + + assertSame(asmMerchantConfigurationMock, result); + } + + @Test(expected = IllegalArgumentException.class) + public void getCurrentAsmConfiguration_WhenSiteNull_ShouldThrowException() { + when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(null); + + testObj.getCurrentAsmConfiguration(); + } + + @Test + public void getAllCurrentSiteMerchantConfigurations_ShouldReturnAllTheCurrentSiteMerchantConfig() { + when(siteMock1.getWebMerchantConfiguration()).thenReturn(webMerchantConfigurationMock); + when(siteMock1.getAsmMerchantConfiguration()).thenReturn(asmMerchantConfigurationMock); + when(siteMock1.getReplenishmentMerchantConfiguration()).thenReturn(replenishmentMerchantConfigurationMock); + + final Set result = testObj.getAllCurrentSiteMerchantConfigurations(); + + assertEquals(3, result.size()); + assertTrue(result.contains(webMerchantConfigurationMock)); + assertTrue(result.contains(asmMerchantConfigurationMock)); + assertTrue(result.contains(replenishmentMerchantConfigurationMock)); + } + + @Test(expected = IllegalArgumentException.class) + public void getAllCurrentSiteMerchantConfigurations_WhenSiteNull_ShouldThrowException() { + when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(null); + + testObj.getAllCurrentSiteMerchantConfigurations(); + } + + @Test + public void getAllSystemActiveSiteMerchantConfigurations_ShouldGetAllTheSystemMerchantConfigForActiveSites() { + when(baseSiteServiceMock.getAllBaseSites()).thenReturn(asList(siteMock1, siteMock2, siteMock3)); + when(siteMock1.getWebMerchantConfiguration()).thenReturn(webMerchantConfigurationMock); + when(siteMock1.getAsmMerchantConfiguration()).thenReturn(asmMerchantConfigurationMock); + when(siteMock1.getActive()).thenReturn(true); + when(siteMock2.getAsmMerchantConfiguration()).thenReturn(null); + when(siteMock2.getActive()).thenReturn(true); + when(siteMock3.getReplenishmentMerchantConfiguration()).thenReturn(replenishmentMerchantConfigurationMock); + when(siteMock3.getActive()).thenReturn(false); + + final Set result = testObj.getAllSystemActiveSiteMerchantConfigurations(); + + assertEquals(2, result.size()); + assertTrue(result.contains(webMerchantConfigurationMock)); + assertTrue(result.contains(asmMerchantConfigurationMock)); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/impl/DefaultWorldpayMerchantConfigDataServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/impl/DefaultWorldpayMerchantConfigDataServiceTest.java deleted file mode 100644 index 63f20d18..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/impl/DefaultWorldpayMerchantConfigDataServiceTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.worldpay.merchant.impl; - -import com.worldpay.config.merchant.WorldpayMerchantConfigData; -import de.hybris.bootstrap.annotations.UnitTest; -import de.hybris.platform.acceleratorservices.config.SiteConfigService; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.springframework.context.ApplicationContext; - -import java.util.Map; - -import static com.worldpay.merchant.impl.DefaultWorldpayMerchantConfigDataService.WORLDPAY_MERCHANT_CONFIG; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith (MockitoJUnitRunner.class) -public class DefaultWorldpayMerchantConfigDataServiceTest { - - private static final String MERCHANT_CONFIG_BEAN_NAME = "merchantConfigBeanName"; - - @InjectMocks - private DefaultWorldpayMerchantConfigDataService testObj; - - @Mock - private SiteConfigService siteConfigServiceMock; - @Mock - private ApplicationContext applicationContextMock; - @Mock - private Map worldpayMerchantConfigurationMock; - - @Before - public void setUp() { - when(siteConfigServiceMock.getProperty(WORLDPAY_MERCHANT_CONFIG)).thenReturn(MERCHANT_CONFIG_BEAN_NAME); - when(applicationContextMock.getBean(MERCHANT_CONFIG_BEAN_NAME)).thenReturn(worldpayMerchantConfigurationMock); - } - - @Test - public void testGetMerchantConfigurationWhenNotInAThreadContext() throws Exception { - - testObj.getMerchantConfiguration(); - - verify(siteConfigServiceMock).getProperty(WORLDPAY_MERCHANT_CONFIG); - verify(applicationContextMock).getBean(MERCHANT_CONFIG_BEAN_NAME); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/impl/DefaultWorldpayMerchantInfoServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/impl/DefaultWorldpayMerchantInfoServiceTest.java index 6359a211..70d27ad7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/impl/DefaultWorldpayMerchantInfoServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/merchant/impl/DefaultWorldpayMerchantInfoServiceTest.java @@ -2,9 +2,12 @@ import com.worldpay.config.merchant.WorldpayMerchantConfigData; import com.worldpay.exception.WorldpayConfigurationException; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.merchant.configuration.services.WorldpayMerchantConfigurationService; +import com.worldpay.model.WorldpayMerchantConfigurationModel; +import com.worldpay.data.MerchantInfo; import com.worldpay.strategy.WorldpayMerchantStrategy; import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.cms2.model.site.CMSSiteModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import org.junit.Before; import org.junit.Test; @@ -15,10 +18,9 @@ import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; -import java.util.Arrays; +import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; @@ -41,31 +43,45 @@ public class DefaultWorldpayMerchantInfoServiceTest { @Mock private WorldpayMerchantStrategy worldpayMerchantStrategyMock; @Mock - private WorldpayMerchantConfigData merchantConfigDataMock; + private WorldpayMerchantConfigurationService worldpayMerchantConfigurationServiceMock; @Mock private MerchantInfo merchantInfo; + @Mock + private WorldpayMerchantConfigurationModel worldpayMerchantConfigurationMock; + @Mock + private CMSSiteModel cmsSiteMock; @Before public void setUp() { when(worldpayMerchantConfigDataMock.getCode()).thenReturn(KNOWN_MERCHANT_CODE); when(anotherWorldpayMerchantConfigDataMock.getCode()).thenReturn(MERCHANT_CODE); - testObj.setConfiguredMerchants(Arrays.asList(worldpayMerchantConfigDataMock, anotherWorldpayMerchantConfigDataMock)); + when(worldpayMerchantConfigurationServiceMock.getAllSystemActiveSiteMerchantConfigurations()).thenReturn(Set.of(worldpayMerchantConfigurationMock)); } @Test - public void shouldCreateMerchantInfoFromReplenishmentMerchantConfigData() { - when(worldpayMerchantStrategyMock.getReplenishmentMerchant()).thenReturn(merchantConfigDataMock); - doReturn(merchantInfo).when(testObj).createMerchantInfo(merchantConfigDataMock); + public void getReplenishmentMerchant_whenSiteAndConfigNotNull_shouldCreateMerchantInfoFromReplenishmentMerchantConfigData() { + when(cmsSiteMock.getReplenishmentMerchantConfiguration()).thenReturn(worldpayMerchantConfigurationMock); + doReturn(merchantInfo).when(testObj).createMerchantInfo(worldpayMerchantConfigurationMock); - final MerchantInfo result = testObj.getReplenishmentMerchant(); + final MerchantInfo result = testObj.getReplenishmentMerchant(cmsSiteMock); assertEquals(merchantInfo, result); } + @Test(expected = IllegalArgumentException.class) + public void getReplenishmentMerchant_whenSiteNull_shouldCreateMerchantInfoFromReplenishmentMerchantConfigData() { + testObj.getReplenishmentMerchant(null); + } + + @Test(expected = IllegalArgumentException.class) + public void getReplenishmentMerchant_whenSiteDoesNotHaveReplenishmentConfig_shouldCreateMerchantInfoFromReplenishmentMerchantConfigData() { + testObj.getReplenishmentMerchant(cmsSiteMock); + } + @Test - public void shouldCreateMerchantInfoFromWebSiteMerchantConfigData() { - when(worldpayMerchantStrategyMock.getMerchant()).thenReturn(merchantConfigDataMock); - doReturn(merchantInfo).when(testObj).createMerchantInfo(merchantConfigDataMock); + public void getCurrentSiteMerchant_shouldCreateMerchantInfoFromWebSiteMerchantConfigData() { + when(worldpayMerchantStrategyMock.getMerchant()).thenReturn(worldpayMerchantConfigurationMock); + doReturn(merchantInfo).when(testObj).createMerchantInfo(worldpayMerchantConfigurationMock); final MerchantInfo result = testObj.getCurrentSiteMerchant(); @@ -73,19 +89,24 @@ public void shouldCreateMerchantInfoFromWebSiteMerchantConfigData() { } @Test - public void getMerchantConfigShouldReturnAlreadyKnownMerchantCode() throws WorldpayConfigurationException { + public void getMerchantInfoByCode_shouldReturnAlreadyKnownMerchantCode() throws WorldpayConfigurationException { + when(worldpayMerchantConfigurationMock.getCode()).thenReturn(KNOWN_MERCHANT_CODE); + final MerchantInfo result = testObj.getMerchantInfoByCode(KNOWN_MERCHANT_CODE); assertEquals(KNOWN_MERCHANT_CODE, result.getMerchantCode()); } @Test(expected = WorldpayConfigurationException.class) - public void getKnownMerchantShouldReturnExceptionWhenMerchantIsNotFound() throws WorldpayConfigurationException { + public void getMerchantInfoByCode_shouldReturnExceptionWhenMerchantIsNotFound() throws WorldpayConfigurationException { + when(worldpayMerchantConfigurationMock.getCode()).thenReturn(KNOWN_MERCHANT_CODE); + testObj.getMerchantInfoByCode("mumbo jumbo"); } @Test - public void testGetMerchantInfoFromTransaction() throws WorldpayConfigurationException { + public void getMerchantInfoFromTransaction_shouldGetMerchantInfoFromTransaction() throws WorldpayConfigurationException { + when(worldpayMerchantConfigurationMock.getCode()).thenReturn(MERCHANT_CODE); when(paymentTransactionMock.getRequestToken()).thenReturn(MERCHANT_CODE); final MerchantInfo result = testObj.getMerchantInfoFromTransaction(paymentTransactionMock); @@ -94,32 +115,32 @@ public void testGetMerchantInfoFromTransaction() throws WorldpayConfigurationExc } @Test - public void shouldCreateMerchantInfoUsingMacValidation() { - when(merchantConfigDataMock.getCode()).thenReturn(MERCHANT_CODE); - when(merchantConfigDataMock.getPassword()).thenReturn(MERCHANT_PASSWORD); - when(merchantConfigDataMock.getMacSecret()).thenReturn(MAC_SECRET); - when(merchantConfigDataMock.getMacValidation()).thenReturn(true); + public void createMerchantInfo_shouldCreateMerchantInfoUsingMacValidation() { + when(worldpayMerchantConfigurationMock.getCode()).thenReturn(MERCHANT_CODE); + when(worldpayMerchantConfigurationMock.getPassword()).thenReturn(MERCHANT_PASSWORD); + when(worldpayMerchantConfigurationMock.getMacSecret()).thenReturn(MAC_SECRET); + when(worldpayMerchantConfigurationMock.getMacValidation()).thenReturn(true); - final MerchantInfo result = testObj.createMerchantInfo(merchantConfigDataMock); + final MerchantInfo result = testObj.createMerchantInfo(worldpayMerchantConfigurationMock); assertEquals(MAC_SECRET, result.getMacSecret()); assertEquals(MERCHANT_CODE, result.getMerchantCode()); assertEquals(MERCHANT_PASSWORD, result.getMerchantPassword()); - assertEquals(true, result.isUsingMacValidation()); + assertTrue(result.isUsingMacValidation()); } @Test - public void shouldCreateMerchantInfoNotUsingMacValidation() { - when(merchantConfigDataMock.getCode()).thenReturn(MERCHANT_CODE); - when(merchantConfigDataMock.getPassword()).thenReturn(MERCHANT_PASSWORD); - when(merchantConfigDataMock.getMacSecret()).thenReturn(MAC_SECRET); - when(merchantConfigDataMock.getMacValidation()).thenReturn(false); + public void createMerchantInfo_shouldCreateMerchantInfoNotUsingMacValidation() { + when(worldpayMerchantConfigurationMock.getCode()).thenReturn(MERCHANT_CODE); + when(worldpayMerchantConfigurationMock.getPassword()).thenReturn(MERCHANT_PASSWORD); + when(worldpayMerchantConfigurationMock.getMacSecret()).thenReturn(MAC_SECRET); + when(worldpayMerchantConfigurationMock.getMacValidation()).thenReturn(false); - final MerchantInfo result = testObj.createMerchantInfo(merchantConfigDataMock); + final MerchantInfo result = testObj.createMerchantInfo(worldpayMerchantConfigurationMock); assertEquals(MERCHANT_CODE, result.getMerchantCode()); assertEquals(MERCHANT_PASSWORD, result.getMerchantPassword()); assertNull(result.getMacSecret()); - assertEquals(false, result.isUsingMacValidation()); + assertFalse(result.isUsingMacValidation()); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/orderprocess/strategies/cancel/impl/DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/orderprocess/strategies/cancel/impl/DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategyTest.java index 6d7b3e1d..bb914e81 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/orderprocess/strategies/cancel/impl/DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategyTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/orderprocess/strategies/cancel/impl/DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategyTest.java @@ -45,10 +45,11 @@ public class DefaultWorldpayCancelWholeOrderDueToCancelNotificationStrategyTest @Before public void setUp() { when(orderProcessModelMock.getOrder()).thenReturn(orderModelMock); + when(orderModelMock.getStatus()).thenReturn(OrderStatus.PAYMENT_CAPTURED); when(orderModelMock.getWorldpayOrderCode()).thenReturn(WORLDPAY_ORDER_CODE); when(orderModelMock.getPaymentTransactions()).thenReturn(List.of(paymentTransactionModelMock)); when(worldpayPaymentTransactionServiceMock.createNotPendingCancelOrderTransactionEntry(paymentTransactionModelMock)) - .thenReturn(paymentTransactionEntryMock); + .thenReturn(paymentTransactionEntryMock); when(paymentTransactionModelMock.getEntries()).thenReturn(Collections.emptyList()); } @@ -65,7 +66,7 @@ public void cancelOrder_ShouldSetTheOrderStatusToCancelled() { } @Test - public void cancelOrder_ShouldSetTheOrderStatusToProcessingError_WhenNoPaymentTransactionFound() { + public void cancelOrder_WhenNoPaymentTransactionFound_ShouldSetTheOrderStatusToProcessingError() { when(orderModelMock.getPaymentTransactions()).thenReturn(Collections.emptyList()); testObj.cancelOrder(orderProcessModelMock); @@ -74,4 +75,14 @@ public void cancelOrder_ShouldSetTheOrderStatusToProcessingError_WhenNoPaymentTr verify(paymentTransactionEntryMock, never()).setPaymentTransaction(paymentTransactionModelMock); verify(modelServiceMock).save(orderModelMock); } + + @Test + public void cancelOrder_WhenOrderIsAlreadyCancelled_ShouldNotCreateTransaction() { + when(orderModelMock.getStatus()).thenReturn(OrderStatus.CANCELLED); + + testObj.cancelOrder(orderProcessModelMock); + + verifyZeroInteractions(worldpayPaymentTransactionServiceMock); + verifyZeroInteractions(modelServiceMock); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AddBackOfficeCodeServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AddBackOfficeCodeServiceRequestIntegrationTest.java index 0c59c03e..e5b09ccd 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AddBackOfficeCodeServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AddBackOfficeCodeServiceRequestIntegrationTest.java @@ -1,11 +1,12 @@ package com.worldpay.service; +import com.worldpay.data.MerchantInfo; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.MerchantInfo; import com.worldpay.service.request.AddBackOfficeCodeServiceRequest; import com.worldpay.service.response.AddBackOfficeCodeServiceResponse; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.servicelayer.ServicelayerBaseTest; +import org.junit.Before; import org.junit.Test; import javax.annotation.Resource; @@ -20,11 +21,20 @@ public class AddBackOfficeCodeServiceRequestIntegrationTest extends Servicelayer private static final String ORDER_CODE = String.valueOf(new Date().getTime()); private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo merchantInfo = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); + + private MerchantInfo merchantInfo; @Resource(name = "worldpayServiceGateway") private WorldpayServiceGateway gateway; + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + } + @Test public void testAddBackOfficeCode() throws WorldpayException { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AddBackOfficeCodeServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AddBackOfficeCodeServiceRequestTest.java index c22af322..ac162e3e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AddBackOfficeCodeServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AddBackOfficeCodeServiceRequestTest.java @@ -1,8 +1,9 @@ package com.worldpay.service; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.AddBackOfficeCodeServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -15,19 +16,28 @@ public class AddBackOfficeCodeServiceRequestTest { private static final String BACK_OFFICE_CODE = "BOC-1234567890"; private static final String MERCHANT1ECOM = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo(MERCHANT1ECOM, MERCHANT_PASSWORD); private static final String ORDER_CODE = "orderCode"; + private MerchantInfo merchantInfo; + @Rule @SuppressWarnings("PMD.MemberScope") public ExpectedException expectedException = ExpectedException.none(); + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT1ECOM); + this.merchantInfo = merchantInfo; + } + @Test public void createAddBackOfficeCodeRequestShouldContainBackOfficeCodeAndWorldpayConfigAndMerchantInfoAndOrderCode() { - final AddBackOfficeCodeServiceRequest request = AddBackOfficeCodeServiceRequest.createAddBackOfficeCodeRequest(MERCHANT_INFO, ORDER_CODE, BACK_OFFICE_CODE); + final AddBackOfficeCodeServiceRequest request = AddBackOfficeCodeServiceRequest.createAddBackOfficeCodeRequest(merchantInfo, ORDER_CODE, BACK_OFFICE_CODE); assertEquals(BACK_OFFICE_CODE, request.getBackOfficeCode()); - assertEquals(MERCHANT_INFO, request.getMerchantInfo()); + assertEquals(merchantInfo, request.getMerchantInfo()); assertEquals(ORDER_CODE, request.getOrderCode()); } @@ -42,13 +52,13 @@ public void createAddBackOfficeCodeRequestShouldRaiseIllegalArgumentExceptionWhe public void createAddBackOfficeCodeRequestShouldRaiseIllegalArgumentExceptionWhenOrderCodeIsNull() { expectedException.expect(IllegalArgumentException.class); - AddBackOfficeCodeServiceRequest.createAddBackOfficeCodeRequest(MERCHANT_INFO, null, BACK_OFFICE_CODE); + AddBackOfficeCodeServiceRequest.createAddBackOfficeCodeRequest(merchantInfo, null, BACK_OFFICE_CODE); } @Test public void createAddBackOfficeCodeRequestShouldRaiseIllegalArgumentExceptionWhenBackOfficeCodeIsNull() { expectedException.expect(IllegalArgumentException.class); - AddBackOfficeCodeServiceRequest.createAddBackOfficeCodeRequest(MERCHANT_INFO, ORDER_CODE, null); + AddBackOfficeCodeServiceRequest.createAddBackOfficeCodeRequest(merchantInfo, ORDER_CODE, null); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AuthorisationCodeServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AuthorisationCodeServiceRequestIntegrationTest.java index 528fa258..0d014254 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AuthorisationCodeServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AuthorisationCodeServiceRequestIntegrationTest.java @@ -1,11 +1,12 @@ package com.worldpay.service; +import com.worldpay.data.MerchantInfo; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.MerchantInfo; import com.worldpay.service.request.AuthorisationCodeServiceRequest; import com.worldpay.service.response.AuthorisationCodeServiceResponse; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.servicelayer.ServicelayerBaseTest; +import org.junit.Before; import org.junit.Test; import javax.annotation.Resource; @@ -19,12 +20,21 @@ public class AuthorisationCodeServiceRequestIntegrationTest extends Servicelayer private static final String AUTHORISATION_CODE = "AC-1234567890"; private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo merchantInfo = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String orderCode = String.valueOf(new Date().getTime()); + private MerchantInfo merchantInfo; + @Resource(name = "worldpayServiceGateway") private WorldpayServiceGateway gateway; + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + } + /** * Test method for {@link WorldpayServiceGateway#authorisationCode(AuthorisationCodeServiceRequest)}. */ diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AuthorisationCodeServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AuthorisationCodeServiceRequestTest.java index cdc682f6..96f830c8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AuthorisationCodeServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/AuthorisationCodeServiceRequestTest.java @@ -1,9 +1,10 @@ package com.worldpay.service; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.AuthorisationCodeServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -16,14 +17,23 @@ public class AuthorisationCodeServiceRequestTest { private static final String AUTHORISATION_CODE = "AC-1234567890"; private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo merchantInfo = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String ORDER_CODE = "orderCode"; + private MerchantInfo merchantInfo; + @SuppressWarnings("PMD.MemberScope") @Rule public ExpectedException expectedException = ExpectedException.none(); + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + } + @Test public void testAuthorisationCode() throws WorldpayException { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CancelServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CancelServiceRequestIntegrationTest.java index 913d0e67..cf4ba136 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CancelServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CancelServiceRequestIntegrationTest.java @@ -1,11 +1,12 @@ package com.worldpay.service; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.CancelServiceRequest; import com.worldpay.service.response.CancelServiceResponse; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.servicelayer.ServicelayerBaseTest; +import org.junit.Before; import org.junit.Test; import javax.annotation.Resource; @@ -19,21 +20,30 @@ public class CancelServiceRequestIntegrationTest extends ServicelayerBaseTest { private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String ORDER_CODE = String.valueOf(new Date().getTime()); + private MerchantInfo merchantInfo; + @Resource(name = "worldpayServiceGateway") private WorldpayServiceGateway gateway; + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + } + /** * Test method for {@link WorldpayServiceGateway#cancel(CancelServiceRequest)}. */ @Test public void testCancel() throws WorldpayException { - WPSGTestHelper.directAuthorise(gateway, MERCHANT_INFO, ORDER_CODE); + WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); - final CancelServiceRequest request = CancelServiceRequest.createCancelRequest(MERCHANT_INFO, ORDER_CODE); + final CancelServiceRequest request = CancelServiceRequest.createCancelRequest(merchantInfo, ORDER_CODE); final CancelServiceResponse cancel = gateway.cancel(request); assertNotNull("Cancel response is null!", cancel); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CancelServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CancelServiceRequestTest.java index d7bc526b..5836ea8c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CancelServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CancelServiceRequestTest.java @@ -1,9 +1,10 @@ package com.worldpay.service; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.CancelServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -15,19 +16,28 @@ public class CancelServiceRequestTest { private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String ORDER_CODE = "orderCode"; + private MerchantInfo merchantInfo; + @Rule @SuppressWarnings("PMD.MemberScope") public ExpectedException expectedException = ExpectedException.none(); + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + } + @Test public void testCancel() throws WorldpayException { - final CancelServiceRequest request = CancelServiceRequest.createCancelRequest(MERCHANT_INFO, ORDER_CODE); + final CancelServiceRequest request = CancelServiceRequest.createCancelRequest(merchantInfo, ORDER_CODE); - assertEquals(MERCHANT_INFO, request.getMerchantInfo()); + assertEquals(merchantInfo, request.getMerchantInfo()); assertEquals(ORDER_CODE, request.getOrderCode()); } @@ -42,6 +52,6 @@ public void createCancelRequestShouldRaiseIllegalArgumentExceptionWhenMerchantIn public void createCancelRequestShouldRaiseIllegalArgumentExceptionWhenOrderCodeIsNull() { expectedException.expect(IllegalArgumentException.class); - CancelServiceRequest.createCancelRequest(MERCHANT_INFO, null); + CancelServiceRequest.createCancelRequest(merchantInfo, null); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CaptureServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CaptureServiceRequestIntegrationTest.java index ad34081a..b1d43465 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CaptureServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CaptureServiceRequestIntegrationTest.java @@ -1,12 +1,13 @@ package com.worldpay.service; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.MerchantInfo; import com.worldpay.service.request.CaptureServiceRequest; import com.worldpay.service.response.CaptureServiceResponse; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.servicelayer.ServicelayerBaseTest; +import org.junit.Before; import org.junit.Test; import javax.annotation.Resource; @@ -22,41 +23,59 @@ public class CaptureServiceRequestIntegrationTest extends ServicelayerBaseTest { private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; private static final String TRACKING_ID1 = "trackingId1"; private static final String TRACKING_ID2 = "trackingId2"; + private static final String EXPONENT = "2"; + private static final String EUR = "EUR"; - private static final MerchantInfo merchantInfo = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); + private MerchantInfo merchantInfo; private static final String ORDER_CODE = Instant.now().toString(); @Resource(name = "worldpayServiceGateway") private WorldpayServiceGateway gateway; + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + } + @Test public void capture_ShouldResponseWithNoErrorsAFullAmount_WhenThereIsACaptureServiceRequestWithoutTrackingIds() throws WorldpayException { WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); - final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, ORDER_CODE, new Amount("100", "EUR", "2"), null, null); + final Amount amount = new Amount(); + amount.setExponent(EXPONENT); + amount.setCurrencyCode(EUR); + amount.setValue("100"); + final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, ORDER_CODE, amount, null, null); final CaptureServiceResponse capture = gateway.capture(request); assertNotNull("Capture response is null!", capture); assertFalse("Errors returned from capture request", capture.isError()); assertEquals("Order code returned is incorrect", ORDER_CODE, capture.getOrderCode()); - final Amount amount = capture.getAmount(); - assertNotNull("Amount in the capture is null!", amount); - assertEquals("Incorrect amount captured", "100", amount.getValue()); + final Amount amountCapture = capture.getAmount(); + assertNotNull("Amount in the capture is null!", amountCapture); + assertEquals("Incorrect amount captured", "100", amountCapture.getValue()); } @Test public void capture_ShouldResponseWithNoErrors_WhenThereIsAFullAmountCaptureServiceRequestWithTrackingIds() throws WorldpayException { WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); - final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, ORDER_CODE, new Amount("100", "EUR", "2"), null, List.of(TRACKING_ID1, TRACKING_ID2)); + final Amount amount = new Amount(); + amount.setExponent(EXPONENT); + amount.setCurrencyCode(EUR); + amount.setValue("100"); + final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, ORDER_CODE, amount, null, List.of(TRACKING_ID1, TRACKING_ID2)); final CaptureServiceResponse capture = gateway.capture(request); assertNotNull("Capture response is null!", capture); assertFalse("Errors returned from capture request", capture.isError()); assertEquals("Order code returned is incorrect", ORDER_CODE, capture.getOrderCode()); - final Amount amount = capture.getAmount(); - assertNotNull("Amount in the capture is null!", amount); - assertEquals("Incorrect amount captured", "100", amount.getValue()); + final Amount amountCapture = capture.getAmount(); + assertNotNull("Amount in the capture is null!", amountCapture); + assertEquals("Incorrect amount captured", "100", amountCapture.getValue()); } @Test @@ -64,22 +83,30 @@ public void capture_ShouldResponseWithNoErrors_WhenThereIsACorrectPartialAmountC WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); - final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, ORDER_CODE, new Amount("70", "EUR", "2"), null, null); + final Amount amount = new Amount(); + amount.setExponent(EXPONENT); + amount.setCurrencyCode(EUR); + amount.setValue("70"); + final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, ORDER_CODE, amount, null, null); final CaptureServiceResponse capture = gateway.capture(request); assertNotNull("Capture response is null!", capture); assertFalse("Errors returned from capture request", capture.isError()); assertEquals("Order code returned is incorrect", ORDER_CODE, capture.getOrderCode()); - final Amount amount = capture.getAmount(); - assertNotNull("Amount in the capture is null!", amount); - assertEquals("Incorrect amount captured", "70", amount.getValue()); + final Amount amountCapture = capture.getAmount(); + assertNotNull("Amount in the capture is null!", amountCapture); + assertEquals("Incorrect amount captured", "70", amountCapture.getValue()); } @Test public void capture_ShouldNotAllowToCaptureMoreThanAuthorised_WhenExceedingAmountCaptureServiceRequest() throws WorldpayException { WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); - final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, ORDER_CODE, new Amount("140", "EUR", "2"), null, null); + final Amount amount = new Amount(); + amount.setExponent(EXPONENT); + amount.setCurrencyCode(EUR); + amount.setValue("140"); + final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, ORDER_CODE, amount, null, null); final CaptureServiceResponse capture = gateway.capture(request); assertNotNull("Capture response is null!", capture); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CaptureServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CaptureServiceRequestTest.java index c3bf522d..d65900d6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CaptureServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CaptureServiceRequestTest.java @@ -1,9 +1,11 @@ package com.worldpay.service; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.CaptureServiceRequest; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -19,50 +21,64 @@ public class CaptureServiceRequestTest { private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String ORDER_CODE = "orderCode"; - private static final Amount AMOUNT = new Amount("100", "EUR", "2"); private static final List TRACKING_IDS = List.of("trackingId1", "trackingId2"); + private MerchantInfo merchantInfo; + private Amount amount; + @Rule public ExpectedException expectedException = ExpectedException.none(); + @Before + public void setUp() throws Exception { + final Amount amount = new Amount(); + amount.setExponent("2"); + amount.setCurrencyCode("EUR"); + amount.setValue("100"); + this.amount = amount; + + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantCode(MERCHANT_CODE); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + this.merchantInfo = merchantInfo; + } + @Test public void createCaptureRequest_ShouldCreateWithNoErrorsAnCaptureServiceRequest_WhenUsingMandatoryFieldsAndTrackingIds() { - final com.worldpay.service.model.Date date = new com.worldpay.service.model.Date(LocalDateTime.now()); - final CaptureServiceRequest request = createCaptureRequest(MERCHANT_INFO, ORDER_CODE, AMOUNT, date, TRACKING_IDS); + final com.worldpay.data.Date date = WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(LocalDateTime.now()); + final CaptureServiceRequest request = createCaptureRequest(merchantInfo, ORDER_CODE, amount, date, TRACKING_IDS); - assertEquals(MERCHANT_INFO, request.getMerchantInfo()); + assertEquals(merchantInfo, request.getMerchantInfo()); assertEquals(ORDER_CODE, request.getOrderCode()); assertEquals(date, request.getDate()); - assertEquals(AMOUNT, request.getAmount()); + assertEquals(amount, request.getAmount()); assertEquals(TRACKING_IDS, request.getTrackingIds()); } @Test public void createCaptureRequest_ShouldCreateWithNoErrorsAnCaptureServiceRequest_WhenUsingMandatoryFieldsAndNoTrackingIds() { - final com.worldpay.service.model.Date date = new com.worldpay.service.model.Date(LocalDateTime.now()); - final CaptureServiceRequest request = createCaptureRequest(MERCHANT_INFO, ORDER_CODE, AMOUNT, date, null); + final com.worldpay.data.Date date = WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(LocalDateTime.now()); + final CaptureServiceRequest request = createCaptureRequest(merchantInfo, ORDER_CODE, amount, date, null); - assertEquals(MERCHANT_INFO, request.getMerchantInfo()); + assertEquals(merchantInfo, request.getMerchantInfo()); assertEquals(ORDER_CODE, request.getOrderCode()); assertEquals(date, request.getDate()); - assertEquals(AMOUNT, request.getAmount()); + assertEquals(amount, request.getAmount()); } @Test(expected = IllegalArgumentException.class) public void createCaptureRequest_ShouldRaiseIllegalArgumentException_WhenMerchantInfoIsNull() { - createCaptureRequest(null, ORDER_CODE, AMOUNT, null, null); + createCaptureRequest(null, ORDER_CODE, amount, null, null); } @Test(expected = IllegalArgumentException.class) public void createCaptureRequest_ShouldRaiseIllegalArgumentException_WhenTheOrderCodeIsNull() { - createCaptureRequest(MERCHANT_INFO, null, AMOUNT, null, null); + createCaptureRequest(merchantInfo, null, amount, null, null); } @Test(expected = IllegalArgumentException.class) public void createCaptureRequest_ShouldRaiseIllegalArgumentException_WhenAmountIsNull() { - createCaptureRequest(MERCHANT_INFO, ORDER_CODE, null, null, null); + createCaptureRequest(merchantInfo, ORDER_CODE, null, null, null); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CreateTokenServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CreateTokenServiceRequestIntegrationTest.java index b9a6f632..e8cc05e5 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CreateTokenServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CreateTokenServiceRequestIntegrationTest.java @@ -1,8 +1,8 @@ package com.worldpay.service; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.token.TokenRequest; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.token.TokenRequest; import com.worldpay.service.response.CreateTokenResponse; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.servicelayer.ServicelayerBaseTest; @@ -19,7 +19,6 @@ public class CreateTokenServiceRequestIntegrationTest extends ServicelayerBaseTe private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo merchantInfo = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String TOKEN_REASON = "tokenReason"; private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; @@ -28,7 +27,14 @@ public class CreateTokenServiceRequestIntegrationTest extends ServicelayerBaseTe @Test public void testCreateTokenWithoutOrder() throws WorldpayException { - final TokenRequest tokenRequest = new TokenRequest(TOKEN_EVENT_REFERENCE, TOKEN_REASON); + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantCode(MERCHANT_CODE); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setTokenEventReference(TOKEN_EVENT_REFERENCE); + tokenRequest.setMerchantToken(false); final String authenticatedShopperId = UUID.randomUUID().toString(); final CreateTokenResponse createTokenResponse = WPSGTestHelper.createShopperToken(gateway, merchantInfo, tokenRequest, authenticatedShopperId); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CreateTokenServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CreateTokenServiceRequestTest.java index ba5b8b0b..9a76a6f8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CreateTokenServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/CreateTokenServiceRequestTest.java @@ -1,18 +1,20 @@ package com.worldpay.service; -import com.worldpay.service.model.Address; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.payment.PaymentBuilder; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.data.Address; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.payment.Cse; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.service.model.payment.PaymentType; import com.worldpay.service.request.CreateTokenServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static com.worldpay.service.request.CreateTokenServiceRequest.createTokenRequestForShopperToken; import static com.worldpay.service.request.CreateTokenServiceRequest.createTokenRequestForMerchantToken; +import static com.worldpay.service.request.CreateTokenServiceRequest.createTokenRequestForShopperToken; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -22,22 +24,62 @@ public class CreateTokenServiceRequestTest { private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; private static final String TOKEN_REASON = "tokenReason"; private static final String AUTHENTICATED_SHOPPER_ID = "authenticatedShopperId"; - private static final Address BILLING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo("MERCHANT1ECOM", "3l3ph4nt_&_c4st!3"); - private static final TokenRequest TOKEN_REQUEST = new TokenRequest(TOKEN_EVENT_REFERENCE, TOKEN_REASON); + private static final String MERCHANT_CODE = "MERCHANT1ECOM"; + private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; private static final String ENCRYPTED_DATA = "encryptedData"; - private static final Payment PAYMENT = PaymentBuilder.createCSE(ENCRYPTED_DATA, BILLING_ADDRESS); + private static final String CITY = "city"; + private static final String GB = "GB"; + private static final String NAME = "John"; + private static final String SHOPPER = "Shopper"; + private static final String SHOPPER_ADDRESS_1 = "Shopper Address1"; + private static final String SHOPPER_ADDRESS_2 = "Shopper Address2"; + private static final String SHOPPER_ADDRESS_3 = "Shopper Address3"; + private static final String POSTAL_CODE = "Postal code"; + + private Payment payment; + private MerchantInfo merchantInfo; + private TokenRequest tokenRequest; @Rule @SuppressWarnings("PMD.MemberScope") public ExpectedException thrown = ExpectedException.none(); + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setTokenEventReference(TOKEN_EVENT_REFERENCE); + tokenRequest.setMerchantToken(false); + this.tokenRequest = tokenRequest; + + final Address billingAddress = new Address(); + billingAddress.setFirstName(NAME); + billingAddress.setLastName(SHOPPER); + billingAddress.setAddress1(SHOPPER_ADDRESS_1); + billingAddress.setAddress2(SHOPPER_ADDRESS_2); + billingAddress.setAddress3(SHOPPER_ADDRESS_3); + billingAddress.setPostalCode(POSTAL_CODE); + billingAddress.setCity(CITY); + billingAddress.setCountryCode(GB); + + final Cse cse = new Cse(); + cse.setEncryptedData(ENCRYPTED_DATA); + cse.setAddress(billingAddress); + cse.setPaymentType(PaymentType.CSEDATA.getMethodCode()); + this.payment = cse; + } + @Test public void createTokenRequestForShopperWillRaiseIllegalArgumentExceptionWhenMerchantIsNull() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Required parameter to create CreateTokenServiceRequest cannot be null"); final MerchantInfo merchant = null; - createTokenRequestForShopperToken(merchant, AUTHENTICATED_SHOPPER_ID, PAYMENT, TOKEN_REQUEST); + createTokenRequestForShopperToken(merchant, AUTHENTICATED_SHOPPER_ID, payment, tokenRequest); } @Test @@ -45,16 +87,16 @@ public void createTokenRequestForShopperWillRaiseIllegalArgumentExceptionWhenPay thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Required parameter to create CreateTokenServiceRequest cannot be null"); final Payment payment = null; - createTokenRequestForShopperToken(MERCHANT_INFO, AUTHENTICATED_SHOPPER_ID, payment, TOKEN_REQUEST); + createTokenRequestForShopperToken(merchantInfo, AUTHENTICATED_SHOPPER_ID, payment, tokenRequest); } @Test public void createTokenRequestForShopperShouldBuildRequest() { - final CreateTokenServiceRequest result = createTokenRequestForShopperToken(MERCHANT_INFO, AUTHENTICATED_SHOPPER_ID, PAYMENT, TOKEN_REQUEST); - assertEquals(MERCHANT_INFO, result.getMerchantInfo()); + final CreateTokenServiceRequest result = createTokenRequestForShopperToken(merchantInfo, AUTHENTICATED_SHOPPER_ID, payment, tokenRequest); + assertEquals(merchantInfo, result.getMerchantInfo()); assertEquals(AUTHENTICATED_SHOPPER_ID, result.getCardTokenRequest().getAuthenticatedShopperId()); - assertEquals(PAYMENT, result.getCardTokenRequest().getPayment()); - assertEquals(TOKEN_REQUEST, result.getCardTokenRequest().getTokenRequest()); + assertEquals(payment, result.getCardTokenRequest().getPayment()); + assertEquals(tokenRequest, result.getCardTokenRequest().getTokenRequest()); } @Test @@ -62,7 +104,7 @@ public void createTokenRequestForMerchantWillRaiseIllegalArgumentExceptionWhenMe thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Required parameter to create CreateTokenServiceRequest cannot be null"); final MerchantInfo merchant = null; - createTokenRequestForMerchantToken(merchant, PAYMENT, TOKEN_REQUEST); + createTokenRequestForMerchantToken(merchant, payment, tokenRequest); } @Test @@ -70,15 +112,15 @@ public void createTokenRequestForMerchantWillRaiseIllegalArgumentExceptionWhenPa thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Required parameter to create CreateTokenServiceRequest cannot be null"); final Payment payment = null; - createTokenRequestForMerchantToken(MERCHANT_INFO, payment, TOKEN_REQUEST); + createTokenRequestForMerchantToken(merchantInfo, payment, tokenRequest); } @Test public void createTokenRequestForMerchantShouldBuildRequest() { - final CreateTokenServiceRequest result = createTokenRequestForMerchantToken(MERCHANT_INFO, PAYMENT, TOKEN_REQUEST); - assertEquals(MERCHANT_INFO, result.getMerchantInfo()); + final CreateTokenServiceRequest result = createTokenRequestForMerchantToken(merchantInfo, payment, tokenRequest); + assertEquals(merchantInfo, result.getMerchantInfo()); assertNull(result.getCardTokenRequest().getAuthenticatedShopperId()); - assertEquals(PAYMENT, result.getCardTokenRequest().getPayment()); - assertEquals(TOKEN_REQUEST, result.getCardTokenRequest().getTokenRequest()); + assertEquals(payment, result.getCardTokenRequest().getPayment()); + assertEquals(tokenRequest, result.getCardTokenRequest().getTokenRequest()); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DefaultWorldpayServiceGatewayTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DefaultWorldpayServiceGatewayTest.java index 3cb61643..194ef80c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DefaultWorldpayServiceGatewayTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DefaultWorldpayServiceGatewayTest.java @@ -1,17 +1,23 @@ package com.worldpay.service; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.worldpay.exception.WorldpayException; import com.worldpay.internal.model.PaymentService; +import com.worldpay.model.PayloadModel; import com.worldpay.service.http.ServiceReply; import com.worldpay.service.http.WorldpayConnector; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.SecondThreeDSecurePaymentRequest; import com.worldpay.service.request.transform.ServiceRequestTransformer; import com.worldpay.service.request.validation.WorldpayXMLValidator; import com.worldpay.service.response.ServiceResponse; import com.worldpay.service.response.transform.ServiceResponseTransformer; import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.internal.dao.GenericDao; +import de.hybris.platform.servicelayer.model.ModelService; import org.apache.commons.configuration.Configuration; import org.junit.Before; import org.junit.Test; @@ -23,17 +29,22 @@ import java.util.HashMap; import java.util.Map; +import static com.worldpay.config.Environment.PROD; import static com.worldpay.config.Environment.TEST; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; @UnitTest @RunWith(MockitoJUnitRunner.class) public class DefaultWorldpayServiceGatewayTest { + private static final String ORDER_CODE = "orderCode"; + private static final String PAYMENT_REQUEST_PAYLOAD = "paymentRequestString"; + private static final String PAYMENT_RESPONSE_PAYLOAD = "paymentResponseString"; private static final String WORLDPAY_CONFIG_ENVIRONMENT = "worldpay.config.environment"; private static final String COOKIE = "Cookie"; + @Spy @InjectMocks private DefaultWorldpayServiceGateway testObj; @@ -45,6 +56,11 @@ public class DefaultWorldpayServiceGatewayTest { private SecondThreeDSecurePaymentRequest serviceRequestMock; @Mock private ConfigurationService configurationServiceMock; + @Mock + private GenericDao abstractOrderGenericDaoMock; + @Mock + private ModelService modelServiceMock; + @Mock private Configuration configurationMock; @Mock @@ -52,13 +68,17 @@ public class DefaultWorldpayServiceGatewayTest { @Mock private ServiceResponseTransformer directAuthoriseResponseTransformerMock; @Mock - private PaymentService paymentRequestMock, paymentResponseService; + private PaymentService paymentRequestMock, paymentResponseServiceMock; @Mock - private ServiceReply paymentResponseServiceMock; + private ServiceReply paymentResponseServiceReplyMock; @Mock private ServiceResponse paymentResponseMock; @Mock private MerchantInfo merchantInfoMock; + @Mock + private AbstractOrderModel orderMock; + @Mock + private PayloadModel requestPayloadMock, responsePayloadMock; private Map requestTransformerStrategyMap = new HashMap<>(); private Map responseTransformerStrategyMap = new HashMap<>(); @@ -72,11 +92,15 @@ public void setUp() throws Exception { requestTransformerStrategyMap.put(serviceRequestMock.getClass().getName(), directAuthoriseRequestTransformerMock); responseTransformerStrategyMap.put(serviceRequestMock.getClass().getName(), directAuthoriseResponseTransformerMock); when(directAuthoriseRequestTransformerMock.transform(serviceRequestMock)).thenReturn(paymentRequestMock); - when(directAuthoriseResponseTransformerMock.transform(paymentResponseServiceMock)).thenReturn(paymentResponseMock); - when(paymentResponseServiceMock.getPaymentService()).thenReturn(paymentResponseService); + when(directAuthoriseResponseTransformerMock.transform(paymentResponseServiceReplyMock)).thenReturn(paymentResponseMock); + when(paymentResponseServiceReplyMock.getPaymentService()).thenReturn(paymentResponseServiceMock); when(serviceRequestMock.getMerchantInfo()).thenReturn(merchantInfoMock); when(serviceRequestMock.getCookie()).thenReturn(COOKIE); - when(worldpayConnectorMock.send(paymentRequestMock, merchantInfoMock, COOKIE)).thenReturn(paymentResponseServiceMock); + when(worldpayConnectorMock.send(paymentRequestMock, merchantInfoMock, COOKIE)).thenReturn(paymentResponseServiceReplyMock); + when(serviceRequestMock.getOrderCode()).thenReturn(ORDER_CODE); + when(abstractOrderGenericDaoMock.find(ImmutableMap.of(AbstractOrderModel.WORLDPAYORDERCODE, ORDER_CODE))).thenReturn(ImmutableList.of(orderMock)); + doReturn(requestPayloadMock).when(testObj).createPayloadModel(PAYMENT_REQUEST_PAYLOAD); + doReturn(responsePayloadMock).when(testObj).createPayloadModel(PAYMENT_RESPONSE_PAYLOAD); } @Test @@ -87,7 +111,41 @@ public void service_WhenPayloadValid_ShouldSendTheTransformedRequestToWorlpayAnd inOrder.verify(worldpayConnectorMock).logXMLOut(paymentRequestMock); inOrder.verify(worldpayXMLValidatorMock).validate(paymentRequestMock); inOrder.verify(worldpayConnectorMock).send(paymentRequestMock, merchantInfoMock, COOKIE); - inOrder.verify(worldpayConnectorMock).logXMLOut(paymentResponseService); + inOrder.verify(worldpayConnectorMock).logXMLOut(paymentResponseServiceMock); assertThat(result).isEqualTo(paymentResponseMock); } + + @Test + public void service_WhenPayloadValid_ShouldSetPayloadToOrder() throws WorldpayException { + when(worldpayConnectorMock.logXMLOut(paymentRequestMock)).thenReturn(PAYMENT_REQUEST_PAYLOAD); + when(worldpayConnectorMock.logXMLOut(paymentResponseServiceMock)).thenReturn(PAYMENT_RESPONSE_PAYLOAD); + + testObj.service(serviceRequestMock); + + verify(orderMock).setRequestsPayload(ImmutableList.of(requestPayloadMock)); + verify(orderMock).setResponsesPayload(ImmutableList.of(responsePayloadMock)); + verify(modelServiceMock).save(orderMock); + } + + @Test + public void service_WhenProdEnvironment_ShouldNotSetPayloadToOrder() throws WorldpayException { + when(configurationMock.getString(WORLDPAY_CONFIG_ENVIRONMENT)).thenReturn(PROD.name()); + + testObj.service(serviceRequestMock); + + verify(orderMock, never()).setRequestsPayload(ImmutableList.of(requestPayloadMock)); + verify(orderMock, never()).setResponsesPayload(ImmutableList.of(responsePayloadMock)); + verify(worldpayConnectorMock, never()).logXMLOut(any()); + } + + @Test + public void service_WhenNoOrderFound_ShouldNotSetPayloadToOrder() throws WorldpayException { + when(abstractOrderGenericDaoMock.find(ImmutableMap.of(AbstractOrderModel.WORLDPAYORDERCODE, ORDER_CODE))).thenReturn(ImmutableList.of()); + + testObj.service(serviceRequestMock); + + verify(orderMock, never()).setRequestsPayload(any()); + verify(orderMock, never()).setResponsesPayload(any()); + verify(modelServiceMock, never()).save(orderMock); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DeleteTokenServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DeleteTokenServiceRequestIntegrationTest.java index 0be0da19..b4a24e2e 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DeleteTokenServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DeleteTokenServiceRequestIntegrationTest.java @@ -1,8 +1,8 @@ package com.worldpay.service; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.token.TokenRequest; import com.worldpay.service.response.CreateTokenResponse; import com.worldpay.service.response.DeleteTokenResponse; import de.hybris.bootstrap.annotations.IntegrationTest; @@ -20,7 +20,6 @@ public class DeleteTokenServiceRequestIntegrationTest extends ServicelayerBaseTe private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo merchantInfo = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String TOKEN_REASON = "tokenReason"; private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; @@ -29,7 +28,15 @@ public class DeleteTokenServiceRequestIntegrationTest extends ServicelayerBaseTe @Test public void testDeleteCreatedToken() throws WorldpayException { - final TokenRequest tokenRequest = new TokenRequest(TOKEN_EVENT_REFERENCE, TOKEN_REASON); + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setTokenEventReference(TOKEN_EVENT_REFERENCE); + tokenRequest.setMerchantToken(false); + final String authenticatedShopperId = UUID.randomUUID().toString(); final CreateTokenResponse createTokenResponse = WPSGTestHelper.createShopperToken(gateway, merchantInfo, tokenRequest, authenticatedShopperId); final String paymentTokenId = createTokenResponse.getToken().getTokenDetails().getPaymentTokenID(); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DeleteTokenServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DeleteTokenServiceRequestTest.java index 85f4ad89..863eac93 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DeleteTokenServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DeleteTokenServiceRequestTest.java @@ -1,7 +1,7 @@ package com.worldpay.service; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.token.TokenRequest; import com.worldpay.service.request.DeleteTokenServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Test; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DirectAuthoriseServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DirectAuthoriseServiceRequestIntegrationTest.java index e88f1211..2e4e176c 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DirectAuthoriseServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DirectAuthoriseServiceRequestIntegrationTest.java @@ -1,60 +1,36 @@ package com.worldpay.service; -import com.worldpay.enums.order.AuthorisedStatus; +import com.worldpay.data.MerchantInfo; import com.worldpay.enums.order.DynamicInteractionType; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.payment.PaymentBuilder; import com.worldpay.service.request.AuthoriseRequestParameters; import com.worldpay.service.request.DirectAuthoriseServiceRequest; -import com.worldpay.service.response.DirectAuthoriseServiceResponse; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.servicelayer.ServicelayerBaseTest; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import javax.annotation.Resource; -import java.time.LocalDateTime; - -import static com.worldpay.enums.order.AuthorisedStatus.AUTHORISED; -import static com.worldpay.enums.order.AuthorisedStatus.REFUSED; -import static org.junit.Assert.*; @IntegrationTest public class DirectAuthoriseServiceRequestIntegrationTest extends ServicelayerBaseTest { - private static final String SHOPPER_EMAIL = "jshopper@myprovider.com"; - private static final String STATEMENT_NARRATIVE = "STATEMENT NARRATIVE TEXT"; - private static final String FAKED_PA_RESPONSE = "fakedPaResponse"; - - private static final Address SHIPPING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final com.worldpay.service.model.Date EXPIRY_DATE = new com.worldpay.service.model.Date(LocalDateTime.now().plusYears(1)); - private static final Session SESSION = new Session("192.168.1.1", "sessionId1234"); - private static final Browser BROWSER = new Browser("text/html,application/xhtml+xml,application/xml;q=0. 9,*/*;q=0.8", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)", "0"); - private static final Address BILLING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final Shopper SHOPPER = new Shopper(SHOPPER_EMAIL, null, BROWSER, SESSION); + private static final String MERCHANT_CODE = "MERCHANT1ECOM"; + private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; @Rule @SuppressWarnings("PMD.MemberScope") public ExpectedException thrown = ExpectedException.none(); - private String orderCode; - private MerchantInfo merchantInfo; - private BasicOrderInfo basicOrderInfo; @Resource(name = "worldpayServiceGateway") private WorldpayServiceGateway testObj; - @Before - public void setUp() { - merchantInfo = new MerchantInfo("MERCHANT1ECOM", "3l3ph4nt_&_c4st!3"); - orderCode = String.valueOf(new java.util.Date().getTime()); - basicOrderInfo = new BasicOrderInfo(orderCode, "Your Order & Order desc", new Amount("100", "EUR", "2")); - } - @Test public void createDirectAuthoriseRequestShouldRaiseWorldpayValidationExceptionWithMinimumValues() throws WorldpayException { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + thrown.expect(IllegalArgumentException.class); final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() @@ -71,255 +47,4 @@ public void createDirectAuthoriseRequestShouldRaiseWorldpayValidationExceptionWi testObj.directAuthorise(request); } - - @Test - public void createDirectAuthoriseRequestShouldReturnAnAuthorisedPaymentReply() throws WorldpayException { - final Payment payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, "J. Shopper", "123", BILLING_ADDRESS); - - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE).build(); - - final DirectAuthoriseServiceRequest request = DirectAuthoriseServiceRequest.createDirectAuthoriseRequest(requestParameters); - - final Order requestOrder = request.getOrder(); - assertNull(requestOrder.getTokenRequest()); - assertEquals(BILLING_ADDRESS, requestOrder.getBillingAddress()); - assertEquals(SHIPPING_ADDRESS, requestOrder.getShippingAddress()); - - final DirectAuthoriseServiceResponse directAuthorise = testObj.directAuthorise(request); - - assertNotNull("Authorise response is null!", directAuthorise); - assertFalse("Errors returned from authorise request", directAuthorise.isError()); - assertEquals("Order code returned is incorrect", orderCode, directAuthorise.getOrderCode()); - final PaymentReply paymentReply = directAuthorise.getPaymentReply(); - assertNotNull("Payment reply is null!", paymentReply); - final AuthorisedStatus authStatus = paymentReply.getAuthStatus(); - assertEquals("Authorised status is not correct", AUTHORISED, authStatus); - } - - @Test - public void testDirectAuthoriseRefusedWithCardPayment() throws WorldpayException { - final Payment payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, "REFUSED", "123", BILLING_ADDRESS); - - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE).build(); - - final DirectAuthoriseServiceRequest request = DirectAuthoriseServiceRequest.createDirectAuthoriseRequest(requestParameters); - - final Order requestOrder = request.getOrder(); - assertNull(requestOrder.getTokenRequest()); - assertEquals(BILLING_ADDRESS, requestOrder.getBillingAddress()); - assertEquals(SHIPPING_ADDRESS, requestOrder.getShippingAddress()); - - final DirectAuthoriseServiceResponse directAuthorise = testObj.directAuthorise(request); - - assertNotNull("Authorise response is null!", directAuthorise); - assertFalse("Errors returned from authorise request", directAuthorise.isError()); - assertEquals("Order code returned is incorrect", orderCode, directAuthorise.getOrderCode()); - final PaymentReply paymentReply = directAuthorise.getPaymentReply(); - assertNotNull("Payment reply is null!", paymentReply); - final AuthorisedStatus authStatus = paymentReply.getAuthStatus(); - assertEquals("Authorised status is not correct", REFUSED, authStatus); - } - - @Test - public void createDirectAuthoriseRequestShouldReturnReferredPaymentReply() throws WorldpayException { - final Payment payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, "REFERRED", "123", BILLING_ADDRESS); - - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE).build(); - - final DirectAuthoriseServiceRequest request = DirectAuthoriseServiceRequest.createDirectAuthoriseRequest(requestParameters); - - final Order requestOrder = request.getOrder(); - assertNull(requestOrder.getTokenRequest()); - assertEquals(BILLING_ADDRESS, requestOrder.getBillingAddress()); - assertEquals(SHIPPING_ADDRESS, requestOrder.getShippingAddress()); - - final DirectAuthoriseServiceResponse directAuthorise = testObj.directAuthorise(request); - - assertNotNull("Authorise response is null!", directAuthorise); - assertFalse("Errors returned from authorise request", directAuthorise.isError()); - assertEquals("Order code returned is incorrect", orderCode, directAuthorise.getOrderCode()); - final PaymentReply paymentReply = directAuthorise.getPaymentReply(); - assertNotNull("Payment reply is null!", paymentReply); - final AuthorisedStatus authStatus = paymentReply.getAuthStatus(); - assertEquals("Authorised status is not correct", AUTHORISED, authStatus); - } - - @Test - public void createDirectAuthoriseRequestShouldReturnFraudPaymentReply() throws WorldpayException { - final Payment payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, "FRAUD", "123", BILLING_ADDRESS); - - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE).build(); - - final DirectAuthoriseServiceRequest request = DirectAuthoriseServiceRequest.createDirectAuthoriseRequest(requestParameters); - - final Order requestOrder = request.getOrder(); - assertNull(requestOrder.getTokenRequest()); - assertEquals(BILLING_ADDRESS, requestOrder.getBillingAddress()); - assertEquals(SHIPPING_ADDRESS, requestOrder.getShippingAddress()); - - final DirectAuthoriseServiceResponse directAuthorise = testObj.directAuthorise(request); - - assertNotNull("Authorise response is null!", directAuthorise); - assertFalse("Errors returned from authorise request", directAuthorise.isError()); - assertEquals("Order code returned is incorrect", orderCode, directAuthorise.getOrderCode()); - final PaymentReply paymentReply = directAuthorise.getPaymentReply(); - assertNotNull("Payment reply is null!", paymentReply); - final AuthorisedStatus authStatus = paymentReply.getAuthStatus(); - assertEquals("Authorised status is not correct", AUTHORISED, authStatus); - } - - @Test - public void createDirectAuthoriseRequestWithERRORMagicValue() throws WorldpayException { - final Payment payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, "ERROR", "123", BILLING_ADDRESS); - - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE).build(); - - final DirectAuthoriseServiceRequest request = DirectAuthoriseServiceRequest.createDirectAuthoriseRequest(requestParameters); - - final Order requestOrder = request.getOrder(); - assertNull(requestOrder.getTokenRequest()); - assertEquals(BILLING_ADDRESS, requestOrder.getBillingAddress()); - assertEquals(SHIPPING_ADDRESS, requestOrder.getShippingAddress()); - - final DirectAuthoriseServiceResponse directAuthorise = testObj.directAuthorise(request); - - assertNotNull("Authorise response is null!", directAuthorise); - assertTrue("No Errors returned from authorise request", directAuthorise.isError()); - } - - @Test - public void testDirectAuthoriseGoingTo3DUsingHelperMethodAndAdds3DDetails() throws WorldpayException { - final Payment payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, "3D", "123", BILLING_ADDRESS); - - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE).build(); - - final DirectAuthoriseServiceRequest request = DirectAuthoriseServiceRequest.createDirectAuthoriseRequest(requestParameters); - - final Order requestOrder = request.getOrder(); - assertNull(requestOrder.getTokenRequest()); - assertEquals(BILLING_ADDRESS, requestOrder.getBillingAddress()); - assertEquals(SHIPPING_ADDRESS, requestOrder.getShippingAddress()); - - final DirectAuthoriseServiceResponse directAuthorise = testObj.directAuthorise(request); - - assertNotNull("Authorise response is null!", directAuthorise); - assertFalse("Errors returned from authorise request", directAuthorise.isError()); - assertEquals("Order code returned is incorrect", orderCode, directAuthorise.getOrderCode()); - final PaymentReply paymentReply = directAuthorise.getPaymentReply(); - assertNull("Payment reply is not null!", paymentReply); - final Request3DInfo request3dInfo = directAuthorise.getRequest3DInfo(); - assertNotNull("Request 3D info is null", request3dInfo); - final String issuerUrl = request3dInfo.getIssuerUrl(); - assertNotNull("Issuer URL cannot be null", issuerUrl); - final String paRequest = request3dInfo.getPaRequest(); - assertNotNull("paRequest cannot be null", paRequest); - final String echoData = directAuthorise.getEchoData(); - assertNotNull("echoData cannot be null", echoData); - } - - @Test - public void createDirectAuthoriseRequestWith3DSecureGetsResponseWithRequest3DInfo() throws WorldpayException { - final Payment payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, "3D", "123", BILLING_ADDRESS); - - final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) - .build(); - - final DirectAuthoriseServiceRequest request = DirectAuthoriseServiceRequest.createDirectAuthoriseRequest(requestParameters); - - final Order requestOrder = request.getOrder(); - assertNull(requestOrder.getTokenRequest()); - assertEquals(BILLING_ADDRESS, requestOrder.getBillingAddress()); - assertEquals(SHIPPING_ADDRESS, requestOrder.getShippingAddress()); - - final DirectAuthoriseServiceResponse directAuthorise = testObj.directAuthorise(request); - - assertNotNull("Authorise response is null!", directAuthorise); - assertFalse("Errors returned from authorise request", directAuthorise.isError()); - assertEquals("Order code returned is incorrect", orderCode, directAuthorise.getOrderCode()); - final PaymentReply paymentReply = directAuthorise.getPaymentReply(); - assertNull("Payment reply is not null!", paymentReply); - final Request3DInfo request3dInfo = directAuthorise.getRequest3DInfo(); - assertNotNull("Request 3D info is null", request3dInfo); - final String issuerUrl = request3dInfo.getIssuerUrl(); - assertNotNull("Issuer URL cannot be null", issuerUrl); - final String paRequest = request3dInfo.getPaRequest(); - assertNotNull("paRequest cannot be null", paRequest); - - final AuthoriseRequestParameters requestParameters3D = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withPayment(null) - .withShopper(SHOPPER) - .withShippingAddress(null) - .withBillingAddress(null) - .withStatementNarrative(null) - .withDynamicInteractionType(null) - .withPaRes(FAKED_PA_RESPONSE) - .build(); - - final DirectAuthoriseServiceRequest direct3DAuthoriseRequest = DirectAuthoriseServiceRequest.createDirect3DAuthoriseRequest(requestParameters3D); - - final DirectAuthoriseServiceResponse directAuthoriseServiceResponse = testObj.directAuthorise(direct3DAuthoriseRequest); - - assertNotNull("Authorise response is null!", directAuthoriseServiceResponse); - // We have to assert that this response actually has errors, as 3d secure hasn't actually been checked (redirect) - assertTrue("Expect errors returned", directAuthoriseServiceResponse.isError()); - assertEquals("Expect error code 7, verification of PaRes failed", "7", directAuthoriseServiceResponse.getErrorDetail().getCode()); - } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DirectAuthoriseServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DirectAuthoriseServiceRequestTest.java index 3c1c2da5..f796d135 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DirectAuthoriseServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/DirectAuthoriseServiceRequestTest.java @@ -1,20 +1,23 @@ package com.worldpay.service; +import com.google.common.collect.ImmutableList; +import com.worldpay.data.*; +import com.worldpay.data.applepay.ApplePay; +import com.worldpay.data.applepay.Header; +import com.worldpay.data.klarna.KlarnaMerchantUrls; +import com.worldpay.data.payment.Card; +import com.worldpay.data.payment.PayWithGoogleSSL; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.token.Token; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.enums.lineItem.LineItemType; import com.worldpay.enums.order.DynamicInteractionType; -import com.worldpay.service.model.*; -import com.worldpay.service.model.applepay.ApplePay; -import com.worldpay.service.model.applepay.Header; -import com.worldpay.service.model.klarna.KlarnaMerchantUrls; -import com.worldpay.service.model.payment.PayWithGoogleSSL; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.payment.PaymentBuilder; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.threeds2.RiskData; -import com.worldpay.service.model.token.Token; -import com.worldpay.service.model.token.TokenRequest; import com.worldpay.service.request.AuthoriseRequestParameters; import com.worldpay.service.request.DirectAuthoriseServiceRequest; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Before; import org.junit.Rule; @@ -33,49 +36,160 @@ public class DirectAuthoriseServiceRequestTest { private static final String TOKEN_ID = "tokenId"; private static final String MERCHANT1ECOM = "MERCHANT1ECOM"; + private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; private static final String DESCRIPTION = "Your Order & Order desc"; - private static final Amount AMOUNT = new Amount("100", "EUR", "2"); private static final String PA_RES = "paRes"; private static final String SHOPPER_NAME = "J. Shopper"; private static final String EXTRA_MERCHANT_DATA = "extraMerchantData"; private static final String SHOPPER_LOCALE = "en-GB"; private static final String LINE_ITEM_REFERENCE_ID = "id"; private static final String LINE_ITEM_REFERENCE_VALUE = "value"; - + private static final String CITY = "city"; + private static final String GB = "GB"; + private static final String NAME = "John"; + private static final String LAST_NAME = "Shopper"; + private static final String SHOPPER_ADDRESS_1 = "Shopper Address1"; + private static final String SHOPPER_ADDRESS_2 = "Shopper Address2"; + private static final String SHOPPER_ADDRESS_3 = "Shopper Address3"; + private static final String POSTAL_CODE = "Postal code"; private static final String AUTHENTICATED_SHOPPER_ID = "authenticatedShopperId"; private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; private static final String TOKEN_REASON = "tokenReason"; private static final String SHOPPER_EMAIL = "jshopper@myprovider.com"; private static final String STATEMENT_NARRATIVE = "STATEMENT NARRATIVE TEXT"; private static final String ORDER_CODE = "orderCode"; - - private static final TokenRequest TOKEN_REQUEST = new TokenRequest(TOKEN_EVENT_REFERENCE, TOKEN_REASON); private static final String COUNTRY_CODE = "GB"; - private static final Address SHIPPING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", COUNTRY_CODE); - private static final com.worldpay.service.model.Date EXPIRY_DATE = new com.worldpay.service.model.Date(LocalDateTime.now().plusYears(1)); - private static final Session SESSION = new Session("192.168.1.1", "sessionId1234"); - private static final Browser BROWSER = new Browser("text/html,application/xhtml+xml,application/xml;q=0. 9,*/*;q=0.8", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)", "0"); - private static final Address BILLING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", COUNTRY_CODE); - private static final Shopper SHOPPER = new Shopper(SHOPPER_EMAIL, null, BROWSER, SESSION); - private static final Shopper SHOPPER_WITHOUT_BROWSER_NOR_SESSION = new Shopper(SHOPPER_EMAIL, null, null, null); - private static final Shopper SHOPPER_WITH_SHOPPER_ID = new Shopper(SHOPPER_EMAIL, AUTHENTICATED_SHOPPER_ID, BROWSER, SESSION); + private static final String IP = "192.168.1.1"; + private static final String SESSION_ID = "sessionId1234"; + private static final String ACCEPT_HEADER = "text/html,application/xhtml+xml,application/xml;q=0. 9,*/*;q=0.8"; + private static final String USER_AGENT_HEADER = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)"; + private static final String DEVICE_TYPE = "0"; + private static final String CONFIRMATION_URL = "confirmationURL"; + private static final String CHECKOUT_URL = "checkoutURL"; + private static final String ORDER_TAX_AMOUNT = "orderTaxAmount"; + private static final String TERMS_URL = "termsURL"; private static final String REFERENCE_ID = "referenceId"; + private static final String DEVICE_SESSION_ID = "device_session_id"; @SuppressWarnings("PMD.MemberScope") @Rule public ExpectedException thrown = ExpectedException.none(); + private ShopperFields shopperFields = new ShopperFields(); + private CustomNumericFields customNumericFields = new CustomNumericFields(); + private CustomStringFields customStringFields = new CustomStringFields(); + private Purchase purchase = new Purchase(); private MerchantInfo merchantInfo; private BasicOrderInfo basicOrderInfo; private Payment payment; private Additional3DSData additional3DSData; private RiskData riskData; + private FraudSightData fraudSightData; + private BranchSpecificExtension branchSpecificExtension; + private TokenRequest tokenRequest; + private Amount amount; + private Address shippingAddress; + private Address billingAddress; + private Session session; + private Browser browser; + private Card visa; + private Date expiryDate; + private Shopper shopper; + private Shopper shopperWithoutBrowserNorSession; + private Shopper shopperWithShopperID; @Before public void setUp() { - merchantInfo = new MerchantInfo(MERCHANT1ECOM, "3l3ph4nt_&_c4st!3"); - basicOrderInfo = new BasicOrderInfo(ORDER_CODE, DESCRIPTION, AMOUNT); - additional3DSData = new Additional3DSData(REFERENCE_ID); + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT1ECOM); + this.merchantInfo = merchantInfo; + + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setTokenEventReference(TOKEN_EVENT_REFERENCE); + tokenRequest.setMerchantToken(false); + this.tokenRequest = tokenRequest; + + final Amount amount = new Amount(); + amount.setExponent("2"); + amount.setCurrencyCode("EUR"); + amount.setValue("100"); + this.amount = amount; + + final BasicOrderInfo basicOrderInfo = new BasicOrderInfo(); + basicOrderInfo.setOrderCode(ORDER_CODE); + basicOrderInfo.setDescription(DESCRIPTION); + basicOrderInfo.setAmount(amount); + this.basicOrderInfo = basicOrderInfo; + + final Additional3DSData additional3DSData = new Additional3DSData(); + additional3DSData.setDfReferenceId(REFERENCE_ID); + this.additional3DSData = additional3DSData; + riskData = new RiskData(); + + final FraudSightData fraudSightData = new FraudSightData(); + fraudSightData.setShopperFields(shopperFields); + fraudSightData.setCustomStringFields(customStringFields); + fraudSightData.setCustomNumericFields(customNumericFields); + this.fraudSightData = fraudSightData; + + final BranchSpecificExtension branchSpecificExtension = new BranchSpecificExtension(); + branchSpecificExtension.setPurchase(ImmutableList.of(purchase)); + this.branchSpecificExtension = branchSpecificExtension; + + final Session session = new Session(); + session.setId(SESSION_ID); + session.setShopperIPAddress(IP); + this.session = session; + + final Browser browser = new Browser(); + browser.setUserAgentHeader(USER_AGENT_HEADER); + browser.setAcceptHeader(ACCEPT_HEADER); + browser.setDeviceType(DEVICE_TYPE); + this.browser = browser; + + final Address address = new Address(); + address.setFirstName(NAME); + address.setLastName(LAST_NAME); + address.setAddress1(SHOPPER_ADDRESS_1); + address.setAddress2(SHOPPER_ADDRESS_2); + address.setAddress3(SHOPPER_ADDRESS_3); + address.setPostalCode(POSTAL_CODE); + address.setCity(CITY); + address.setCountryCode(GB); + + this.shippingAddress = address; + this.billingAddress = address; + + expiryDate = WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(LocalDateTime.now().plusYears(1)); + + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(SHOPPER_EMAIL); + shopper.setSession(this.session); + shopper.setBrowser(this.browser); + this.shopper = shopper; + + final Shopper shopperWithoutBrowserNorSession = new Shopper(); + shopperWithoutBrowserNorSession.setShopperEmailAddress(SHOPPER_EMAIL); + this.shopperWithoutBrowserNorSession = shopperWithoutBrowserNorSession; + + final Shopper shopperWithShopperID = new Shopper(); + shopperWithShopperID.setShopperEmailAddress(SHOPPER_EMAIL); + shopperWithShopperID.setAuthenticatedShopperID(AUTHENTICATED_SHOPPER_ID); + shopperWithShopperID.setSession(this.session); + shopperWithShopperID.setBrowser(this.browser); + this.shopperWithShopperID = shopperWithShopperID; + + final Card visa = new Card(); + visa.setPaymentType(PaymentType.VISA.getMethodCode()); + visa.setCardNumber("4444333322221111"); + visa.setCvc("123"); + visa.setExpiryDate(expiryDate); + visa.setCardAddress(billingAddress); + visa.setCardHolderName(SHOPPER_NAME); + this.visa = visa; + } @Test @@ -98,15 +212,15 @@ public void createDirectAuthoriseRequestWillRaiseIllegalArgumentExceptionWhenPar @Test public void createDirectAuthoriseRequestShouldNotRequestTokenAndHaveAllTheInformation() { - payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, SHOPPER_NAME, "123", BILLING_ADDRESS); + payment = visa; final AuthoriseRequestParameters requestParameters3D = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) + .withShopper(shopper) + .withShippingAddress(shippingAddress) + .withBillingAddress(billingAddress) .withStatementNarrative(STATEMENT_NARRATIVE) .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) .build(); @@ -115,32 +229,39 @@ public void createDirectAuthoriseRequestShouldNotRequestTokenAndHaveAllTheInform final Order requestOrder = result.getOrder(); assertNull(requestOrder.getTokenRequest()); - assertEquals(BILLING_ADDRESS, result.getOrder().getBillingAddress()); - assertEquals(SHOPPER, result.getOrder().getShopper()); + assertEquals(billingAddress, result.getOrder().getBillingAddress()); + assertEquals(shopper, result.getOrder().getShopper()); assertEquals(payment, result.getOrder().getPaymentDetails().getPayment()); assertCommonOrderRequestData(result); } @Test public void shouldContainOrderLinesForKlarnaDirectAuthorize() { - final KlarnaMerchantUrls merchantUrls = new KlarnaMerchantUrls("checkoutURL", "confirmationURL"); - payment = PaymentBuilder.createKlarnaPayment(COUNTRY_CODE, SHOPPER_LOCALE, merchantUrls, EXTRA_MERCHANT_DATA); + final KlarnaMerchantUrls merchantUrls = new KlarnaMerchantUrls(); + merchantUrls.setConfirmationURL(CONFIRMATION_URL); + merchantUrls.setCheckoutURL(CHECKOUT_URL); + payment = WorldpayInternalModelTransformerUtil.createKlarnaPayment(COUNTRY_CODE, SHOPPER_LOCALE, merchantUrls, EXTRA_MERCHANT_DATA); final LineItem lineItem = new LineItem(); - lineItem.setLineItemType(LineItem.LINE_ITEM_TYPE.SHIPPING_FEE); + lineItem.setLineItemType(LineItemType.SHIPPING_FEE); - final LineItemReference lineItemReference = new LineItemReference(LINE_ITEM_REFERENCE_ID, LINE_ITEM_REFERENCE_VALUE); + final LineItemReference lineItemReference = new LineItemReference(); + lineItemReference.setValue(LINE_ITEM_REFERENCE_VALUE); + lineItemReference.setId(LINE_ITEM_REFERENCE_ID); lineItem.setLineItemReference(lineItemReference); - final OrderLines orderLines = new OrderLines("orderTaxAmount", "termsURL", singletonList(lineItem)); + final OrderLines orderLines = new OrderLines(); + orderLines.setLineItems(singletonList(lineItem)); + orderLines.setOrderTaxAmount(ORDER_TAX_AMOUNT); + orderLines.setTermsURL(TERMS_URL); final AuthoriseRequestParameters requestParameters3D = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) .withPayment(payment) - .withShopper(SHOPPER_WITH_SHOPPER_ID) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) + .withShopper(shopperWithShopperID) + .withShippingAddress(shippingAddress) + .withBillingAddress(billingAddress) .withStatementNarrative(STATEMENT_NARRATIVE) .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) .withOrderLines(orderLines) @@ -149,8 +270,8 @@ public void shouldContainOrderLinesForKlarnaDirectAuthorize() { final DirectAuthoriseServiceRequest result = DirectAuthoriseServiceRequest.createKlarnaDirectAuthoriseRequest(requestParameters3D); final Order requestOrder = result.getOrder(); - assertEquals(BILLING_ADDRESS, result.getOrder().getBillingAddress()); - assertEquals(SHOPPER_WITH_SHOPPER_ID, result.getOrder().getShopper()); + assertEquals(billingAddress, result.getOrder().getBillingAddress()); + assertEquals(shopperWithShopperID, result.getOrder().getShopper()); assertThat(requestOrder.getOrderLines().getLineItems()).hasSize(1); assertThat(requestOrder.getOrderLines().getLineItems().get(0).getLineItemReference().getId()).isEqualTo(LINE_ITEM_REFERENCE_ID); assertThat(requestOrder.getOrderLines().getLineItems().get(0).getLineItemReference().getValue()).isEqualTo(LINE_ITEM_REFERENCE_VALUE); @@ -163,66 +284,90 @@ public void createTokenisedDirectAuthoriseRequestShouldRaiseIllegalArgumentExcep thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Payment type needs to be a type of Token"); - payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, SHOPPER_NAME, "123", BILLING_ADDRESS); - - basicOrderInfo = new BasicOrderInfo(ORDER_CODE, "Your Order & Order desc with token", new Amount("1000", "EUR", "2")); - final AuthoriseRequestParameters requestParameters3D = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) - .withPayment(payment) - .withShopper(SHOPPER_WITH_SHOPPER_ID) - .withShippingAddress(SHIPPING_ADDRESS) + .withPayment(visa) + .withShopper(shopperWithShopperID) + .withShippingAddress(shippingAddress) .withBillingAddress(null) .withStatementNarrative(STATEMENT_NARRATIVE) .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) .withAdditional3DSData(additional3DSData) + .withFraudSightData(fraudSightData) + .withDeviceSession(DEVICE_SESSION_ID) .build(); DirectAuthoriseServiceRequest.createTokenisedDirectAuthoriseRequest(requestParameters3D); } @Test - public void createTokenisedDirectAuthoriseRequestShouldCreateAnOrderRequestWithToken() { - payment = new Token(TOKEN_ID, false); + public void createTokenisedDirectAuthoriseRequest_ShouldCreateAnOrderRequestWithToken() { + final Token token = new Token(); + token.setPaymentType(PaymentType.TOKENSSL.getMethodCode()); + token.setPaymentTokenID(TOKEN_ID); + token.setMerchantToken(false); + payment = token; final AuthoriseRequestParameters requestParameters3D = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) .withPayment(payment) - .withShopper(SHOPPER_WITH_SHOPPER_ID) - .withShippingAddress(SHIPPING_ADDRESS) + .withShopper(shopperWithShopperID) + .withShippingAddress(shippingAddress) .withBillingAddress(null) .withStatementNarrative(STATEMENT_NARRATIVE) .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) .withAdditional3DSData(additional3DSData) + .withFraudSightData(fraudSightData) + .withDeviceSession(DEVICE_SESSION_ID) + .withLevel23Data(branchSpecificExtension) .build(); + final DirectAuthoriseServiceRequest result = DirectAuthoriseServiceRequest.createTokenisedDirectAuthoriseRequest(requestParameters3D); - assertEquals("TOKEN-SSL", result.getOrder().getPaymentDetails().getPayment().getPaymentType().getMethodCode()); + assertEquals("TOKEN-SSL", result.getOrder().getPaymentDetails().getPayment().getPaymentType()); assertEquals(TOKEN_ID, ((Token) result.getOrder().getPaymentDetails().getPayment()).getPaymentTokenID()); - assertEquals(SHOPPER_WITH_SHOPPER_ID, result.getOrder().getShopper()); + assertEquals(shopperWithShopperID, result.getOrder().getShopper()); assertEquals(REFERENCE_ID, result.getOrder().getAdditional3DSData().getDfReferenceId()); + assertEquals(fraudSightData, result.getOrder().getFraudSightData()); + assertEquals(shopperFields, result.getOrder().getFraudSightData().getShopperFields()); + assertEquals(DEVICE_SESSION_ID, result.getOrder().getDeviceSession()); + assertEquals(branchSpecificExtension, result.getOrder().getBranchSpecificExtension()); assertCommonOrderRequestData(result); } @Test public void createApplePayDirectAuthoriseRequestShouldCreateAnOrderRequestWithApplePayAsPaymentMethod() { - payment = new ApplePay(new Header("ephKey", "keyHash", "transactionId", "applicationData"), "signature", "version", "data", "tokenRequestorID"); + final Header header = new Header(); + header.setTransactionId("transactionId"); + header.setApplicationData("applicationData"); + header.setPublicKeyHash("keyHash"); + header.setEphemeralPublicKey("ephKey"); + + final ApplePay applePay = new ApplePay(); + applePay.setHeader(header); + applePay.setSignature("signature"); + applePay.setVersion("version"); + applePay.setData("data"); + applePay.setTokenRequestorID("tokenRequestorID"); + applePay.setPaymentType(PaymentType.APPLEPAYSSL.getMethodCode()); + + payment = applePay; final AuthoriseRequestParameters requestParameters3D = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) .withPayment(payment) - .withShopper(SHOPPER_WITH_SHOPPER_ID) - .withShippingAddress(SHIPPING_ADDRESS) + .withShopper(shopperWithShopperID) + .withShippingAddress(shippingAddress) .withBillingAddress(null) .withStatementNarrative(null) .withDynamicInteractionType(null).build(); final DirectAuthoriseServiceRequest result = DirectAuthoriseServiceRequest.createApplePayDirectAuthoriseRequest(requestParameters3D); - assertEquals("APPLEPAY-SSL", result.getOrder().getPaymentDetails().getPayment().getPaymentType().getMethodCode()); + assertEquals("APPLEPAY-SSL", result.getOrder().getPaymentDetails().getPayment().getPaymentType()); assertEquals("data", ((ApplePay) result.getOrder().getPaymentDetails().getPayment()).getData()); - assertEquals(SHOPPER_WITH_SHOPPER_ID, result.getOrder().getShopper()); + assertEquals(shopperWithShopperID, result.getOrder().getShopper()); } @Test @@ -232,7 +377,7 @@ public void createDirect3DAuthoriseRequestShouldContainPaResponse() { .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) .withPayment(null) - .withShopper(SHOPPER_WITH_SHOPPER_ID) + .withShopper(shopperWithShopperID) .withShippingAddress(null) .withBillingAddress(null) .withStatementNarrative(null) @@ -246,23 +391,23 @@ public void createDirect3DAuthoriseRequestShouldContainPaResponse() { assertEquals(ORDER_CODE, result.getOrderCode()); assertEquals(ORDER_CODE, result.getOrder().getOrderCode()); assertEquals(PA_RES, result.getOrder().getPaResponse()); - assertEquals(SESSION, result.getOrder().getSession()); + assertEquals(session, result.getOrder().getSession()); } @Test public void createDirectAuthorisedWithoutMerchantShouldRaiseIllegalArgumentExceptionException() { thrown.expect(IllegalArgumentException.class); - merchantInfo = new MerchantInfo(null, null); - final Payment payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, "J. Shopper", "123", BILLING_ADDRESS); + merchantInfo.setMerchantPassword(null); + merchantInfo.setMerchantCode(null); final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) - .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) + .withPayment(visa) + .withShopper(shopper) + .withShippingAddress(shippingAddress) + .withBillingAddress(billingAddress) .withStatementNarrative(STATEMENT_NARRATIVE) .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) .build(); @@ -272,35 +417,44 @@ public void createDirectAuthorisedWithoutMerchantShouldRaiseIllegalArgumentExcep @Test public void shouldCreateGooglePayDirectAuthorisationRequest() { - final PayWithGoogleSSL payment = new PayWithGoogleSSL("protocolVersion", "signature", "signedMessage"); + final PayWithGoogleSSL payment = new PayWithGoogleSSL(); + payment.setProtocolVersion("protocolVersion"); + payment.setSignature("signature"); + payment.setSignedMessage("signedMessage"); + payment.setPaymentType(PaymentType.PAYWITHGOOGLESSL.getMethodCode()); + final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) .withPayment(payment) - .withShopper(SHOPPER_WITHOUT_BROWSER_NOR_SESSION) - .withShippingAddress(SHIPPING_ADDRESS) + .withShopper(shopperWithoutBrowserNorSession) + .withShippingAddress(shippingAddress) .withBillingAddress(null) .withStatementNarrative(null) - .withTokenRequest(null) + .withTokenRequest(null) .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) .build(); final DirectAuthoriseServiceRequest result = DirectAuthoriseServiceRequest.createGooglePayDirectAuthoriseRequest(requestParameters); - assertThat(result.getOrder().getPaymentDetails().getPayment().getPaymentType().getMethodCode()).isEqualTo(PaymentType.PAYWITHGOOGLESSL.getMethodCode()); + assertThat(result.getOrder().getPaymentDetails().getPayment().getPaymentType()).isEqualTo(PaymentType.PAYWITHGOOGLESSL.getMethodCode()); } @Test public void shouldRaiseIllegalArgumentExceptionWhenPaymentIsNotPayWithGoogleSSL() { thrown.expect(IllegalArgumentException.class); - final Token payment = new Token(TOKEN_EVENT_REFERENCE, false); + final Token token = new Token(); + token.setPaymentType(PaymentType.TOKENSSL.getMethodCode()); + token.setPaymentTokenID(TOKEN_EVENT_REFERENCE); + token.setMerchantToken(false); + payment = token; final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) .withPayment(payment) - .withShopper(SHOPPER_WITHOUT_BROWSER_NOR_SESSION) - .withShippingAddress(SHIPPING_ADDRESS) + .withShopper(shopperWithoutBrowserNorSession) + .withShippingAddress(shippingAddress) .withBillingAddress(null) .withStatementNarrative(null) .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) @@ -320,11 +474,15 @@ public void createDirectTokenAndAuthoriseRequest_ShouldReturnADirectAuthoriseSer assertEquals(merchantInfo, result.getMerchantInfo()); assertEquals(ORDER_CODE, result.getOrderCode()); - assertEquals(resultOrder.getBillingAddress(), BILLING_ADDRESS); - assertEquals(resultOrder.getShippingAddress(), SHIPPING_ADDRESS); - assertEquals(resultOrder.getStatementNarrative(), STATEMENT_NARRATIVE); - assertEquals(resultOrder.getDynamicInteractionType(), DynamicInteractionType.ECOMMERCE); - assertEquals(resultOrder.getTokenRequest(), TOKEN_REQUEST); + assertEquals(billingAddress, resultOrder.getBillingAddress()); + assertEquals(shippingAddress, resultOrder.getShippingAddress()); + assertEquals(STATEMENT_NARRATIVE, resultOrder.getStatementNarrative()); + assertEquals(DynamicInteractionType.ECOMMERCE, resultOrder.getDynamicInteractionType()); + assertEquals(tokenRequest, resultOrder.getTokenRequest()); + assertEquals(fraudSightData, result.getOrder().getFraudSightData()); + assertEquals(shopperFields, result.getOrder().getFraudSightData().getShopperFields()); + assertEquals(DEVICE_SESSION_ID, result.getOrder().getDeviceSession()); + assertEquals(branchSpecificExtension, result.getOrder().getBranchSpecificExtension()); assert3DSInfoOrderRequestData(result); } @@ -333,14 +491,17 @@ protected AuthoriseRequestParameters getAuthoriseRequestParametersMock() { .withMerchantInfo(merchantInfo) .withOrderInfo(basicOrderInfo) .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) + .withShopper(shopper) + .withShippingAddress(shippingAddress) + .withBillingAddress(billingAddress) .withStatementNarrative(STATEMENT_NARRATIVE) .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE) - .withTokenRequest(TOKEN_REQUEST) + .withTokenRequest(tokenRequest) .withAdditional3DSData(additional3DSData) .withRiskData(riskData) + .withFraudSightData(fraudSightData) + .withDeviceSession(DEVICE_SESSION_ID) + .withLevel23Data(branchSpecificExtension) .build(); } @@ -349,11 +510,11 @@ private void assertCommonOrderRequestData(final DirectAuthoriseServiceRequest re assertEquals(ORDER_CODE, result.getOrderCode()); assertEquals(ORDER_CODE, result.getOrder().getOrderCode()); assertEquals(DESCRIPTION, result.getOrder().getDescription()); - assertEquals(AMOUNT, result.getOrder().getAmount()); - assertEquals(SHIPPING_ADDRESS, result.getOrder().getShippingAddress()); + assertEquals(amount, result.getOrder().getAmount()); + assertEquals(shippingAddress, result.getOrder().getShippingAddress()); assertEquals(STATEMENT_NARRATIVE, result.getOrder().getStatementNarrative()); assertEquals(payment, result.getOrder().getPaymentDetails().getPayment()); - assertEquals(SESSION, result.getOrder().getPaymentDetails().getSession()); + assertEquals(session, result.getOrder().getPaymentDetails().getSession()); } private void assert3DSInfoOrderRequestData(final DirectAuthoriseServiceRequest result) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/OrderInquiryServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/OrderInquiryServiceRequestIntegrationTest.java index 44db28c4..e48a84fe 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/OrderInquiryServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/OrderInquiryServiceRequestIntegrationTest.java @@ -6,10 +6,10 @@ import com.evanlennick.retry4j.config.RetryConfigBuilder; import com.evanlennick.retry4j.exception.RetriesExhaustedException; import com.evanlennick.retry4j.exception.UnexpectedException; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.PaymentReply; import com.worldpay.enums.order.AuthorisedStatus; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.PaymentReply; import com.worldpay.service.request.AbstractServiceRequest; import com.worldpay.service.request.OrderInquiryServiceRequest; import com.worldpay.service.response.OrderInquiryServiceResponse; @@ -32,7 +32,6 @@ public class OrderInquiryServiceRequestIntegrationTest extends ServicelayerBaseT private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASS = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASS); private static final String ORDER_CODE = String.valueOf(new Date().getTime()); private static final String WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES = "worldpayapi.inquiry.max.number.of.retries"; @@ -49,15 +48,21 @@ public class OrderInquiryServiceRequestIntegrationTest extends ServicelayerBaseT public void setUp() throws Exception { configurationService.getConfiguration().setProperty(WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES_VALUE.toString()); configurationService.getConfiguration().setProperty(WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES_VALUE.toString()); + + } @Test @Ignore("Ignored because taking to much time to pass") public void testOrderInquiry() throws WorldpayException { - WPSGTestHelper.directAuthorise(gateway, MERCHANT_INFO, ORDER_CODE); + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASS); + merchantInfo.setMerchantCode(MERCHANT_CODE); + + WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); - final OrderInquiryServiceRequest request = OrderInquiryServiceRequest.createOrderInquiryRequest(MERCHANT_INFO, ORDER_CODE); + final OrderInquiryServiceRequest request = OrderInquiryServiceRequest.createOrderInquiryRequest(merchantInfo, ORDER_CODE); final Callable callable = getOrderInquiryServiceResponseCallable(request); final RetryConfig config = buildRetryConfig(); @@ -79,11 +84,11 @@ public void testOrderInquiry() throws WorldpayException { private RetryConfig buildRetryConfig() { return new RetryConfigBuilder() - .retryOnSpecificExceptions(WorldpayException.class) - .withMaxNumberOfTries(configurationService.getConfiguration().getInt(WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES_VALUE)) - .withDelayBetweenTries(configurationService.getConfiguration().getInt(WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES_VALUE), ChronoUnit.SECONDS) - .withFixedBackoff() - .build(); + .retryOnSpecificExceptions(WorldpayException.class) + .withMaxNumberOfTries(configurationService.getConfiguration().getInt(WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_MAX_NUMBER_OF_RETRIES_VALUE)) + .withDelayBetweenTries(configurationService.getConfiguration().getInt(WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES, DEFAULT_WORLDPAYAPI_INQUIRY_DELAY_BETWEEN_RETRIES_VALUE), ChronoUnit.SECONDS) + .withFixedBackoff() + .build(); } private Status executeInquiryCallable(final Callable callable, final RetryConfig config) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/OrderInquiryServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/OrderInquiryServiceRequestTest.java index cf6d7802..38801ca4 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/OrderInquiryServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/OrderInquiryServiceRequestTest.java @@ -1,8 +1,9 @@ package com.worldpay.service; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.OrderInquiryServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -14,18 +15,27 @@ public class OrderInquiryServiceRequestTest { private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String ORDER_CODE = "orderCode"; + private MerchantInfo merchantInfo; + @Rule public ExpectedException expectedException = ExpectedException.none(); + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + } + @Test public void testOrderInquiry() { - final OrderInquiryServiceRequest request = OrderInquiryServiceRequest.createOrderInquiryRequest(MERCHANT_INFO, ORDER_CODE); + final OrderInquiryServiceRequest request = OrderInquiryServiceRequest.createOrderInquiryRequest(merchantInfo, ORDER_CODE); - assertEquals(MERCHANT_INFO, request.getMerchantInfo()); + assertEquals(merchantInfo, request.getMerchantInfo()); assertEquals(ORDER_CODE, request.getOrderCode()); } @@ -40,6 +50,6 @@ public void createOrderInquiryRequestShouldRaiseIllegalArgumentExceptionWhenMerc public void createOrderInquiryRequestShouldRaiseIllegalArgumentExceptionWhenOrderCodeIsNull() { expectedException.expect(IllegalArgumentException.class); - OrderInquiryServiceRequest.createOrderInquiryRequest(MERCHANT_INFO, null); + OrderInquiryServiceRequest.createOrderInquiryRequest(merchantInfo, null); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RedirectAuthoriseServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RedirectAuthoriseServiceRequestIntegrationTest.java index 66b362c0..3c5c1864 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RedirectAuthoriseServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RedirectAuthoriseServiceRequestIntegrationTest.java @@ -1,13 +1,13 @@ package com.worldpay.service; +import com.worldpay.data.*; +import com.worldpay.data.payment.Cse; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.token.TokenRequest; import com.worldpay.enums.payment.storedCredentials.Usage; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Cse; -import com.worldpay.service.model.payment.Payment; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.model.token.TokenRequest; import com.worldpay.service.request.AuthoriseRequestParameters; import com.worldpay.service.request.RedirectAuthoriseServiceRequest; import com.worldpay.service.response.RedirectAuthoriseServiceResponse; @@ -36,16 +36,32 @@ public class RedirectAuthoriseServiceRequestIntegrationTest extends Servicelayer private static final String ENCRYPTED_DATA = "encryptedData"; private static final String SESSION_ID = "sessionId"; private static final String SHOPPER_IP_ADDRESS = "shopperIPAddress"; - - private static final Address SHIPPING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final TokenRequest TOKEN_REQUEST = new TokenRequest("tokenEventReferenceNumber", "tokenReason"); - private static final Address ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final List includedPaymentMethods = singletonList(ONLINE); - private static final Address BILLING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final Payment PAYMENT = new Cse(ENCRYPTED_DATA, SHIPPING_ADDRESS); - private static final Session SESSION = new Session(SHOPPER_IP_ADDRESS, SESSION_ID); - private static final Shopper SHOPPER = new Shopper(EMAIL_ADDRESS, null, null, SESSION); - private static final StoredCredentials STORED_CREDENTIALS = new StoredCredentials(null,null, Usage.FIRST); + private static final String MERCHANT_CODE = "MERCHANT1ECOM"; + private static final String MERCHANT_PASS = "3l3ph4nt_&_c4st!3"; + private static final String VALUE = "100"; + private static final String EUR = "EUR"; + private static final String EXPONENT = "2"; + private static final String YOUR_ORDER_ORDER_DESC = "Your Order & Order desc"; + private static final String NAME = "John"; + private static final String SHOPPER = "Shopper"; + private static final String SHOPPER_ADDRESS_1 = "Shopper Address1"; + private static final String SHOPPER_ADDRESS_2 = "Shopper Address2"; + private static final String SHOPPER_ADDRESS_3 = "Shopper Address3"; + private static final String POSTAL_CODE = "postalCode"; + private static final String CITY = "city"; + private static final String GB = "GB"; + private static final String TOKEN_EVENT_REFERENCE_NUMBER = "tokenEventReferenceNumber"; + private static final String TOKEN_REASON = "tokenReason"; + + private Address shippingAddress; + private TokenRequest tokenRequest; + private Address address; + private List includedPaymentMethods = singletonList(ONLINE); + private Address billingAddress; + private Payment payment; + private Session session; + private Shopper shopper; + private StoredCredentials storedCredentials; private String orderCode; private MerchantInfo merchantInfo; private BasicOrderInfo basicOrderInfo; @@ -60,25 +76,98 @@ public class RedirectAuthoriseServiceRequestIntegrationTest extends Servicelayer @Before public void setUp() { orderCode = String.valueOf(new Date().getTime()); - merchantInfo = new MerchantInfo("MERCHANT1ECOM", "3l3ph4nt_&_c4st!3"); - basicOrderInfo = new BasicOrderInfo(orderCode, "Your Order & Order desc", new Amount("100", "EUR", "2")); + + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantCode(MERCHANT_CODE); + merchantInfo.setMerchantPassword(MERCHANT_PASS); + merchantInfo.setUsingMacValidation(false); + this.merchantInfo = merchantInfo; + + final Amount amount = new Amount(); + amount.setValue(VALUE); + amount.setCurrencyCode(EUR); + amount.setExponent(EXPONENT); + + final BasicOrderInfo basicOrderInfo = new BasicOrderInfo(); + basicOrderInfo.setOrderCode(orderCode); + basicOrderInfo.setDescription(YOUR_ORDER_ORDER_DESC); + basicOrderInfo.setAmount(amount); + this.basicOrderInfo = basicOrderInfo; + + final Address shippingAddress = new Address(); + shippingAddress.setFirstName(NAME); + shippingAddress.setLastName(SHOPPER); + shippingAddress.setAddress1(SHOPPER_ADDRESS_1); + shippingAddress.setAddress2(SHOPPER_ADDRESS_2); + shippingAddress.setAddress3(SHOPPER_ADDRESS_3); + shippingAddress.setPostalCode(POSTAL_CODE); + shippingAddress.setCity(CITY); + shippingAddress.setCountryCode(GB); + this.shippingAddress = shippingAddress; + + final TokenRequest tokenRequestData = new TokenRequest(); + tokenRequestData.setTokenEventReference(TOKEN_EVENT_REFERENCE_NUMBER); + tokenRequestData.setTokenReason(TOKEN_REASON); + tokenRequestData.setMerchantToken(false); + tokenRequest = tokenRequestData; + + final Address address = new Address(); + address.setFirstName(NAME); + address.setLastName(SHOPPER); + address.setAddress1(SHOPPER_ADDRESS_1); + address.setAddress2(SHOPPER_ADDRESS_2); + address.setAddress3(SHOPPER_ADDRESS_3); + address.setPostalCode(POSTAL_CODE); + address.setCity(CITY); + address.setCountryCode(GB); + this.address = address; + + final Address billingAddress = new Address(); + billingAddress.setFirstName(NAME); + billingAddress.setLastName(SHOPPER); + billingAddress.setAddress1(SHOPPER_ADDRESS_1); + billingAddress.setAddress2(SHOPPER_ADDRESS_2); + billingAddress.setAddress3(SHOPPER_ADDRESS_3); + billingAddress.setPostalCode(POSTAL_CODE); + billingAddress.setCity(CITY); + billingAddress.setCountryCode(GB); + this.billingAddress = billingAddress; + + final Cse payment = new Cse(); + payment.setEncryptedData(ENCRYPTED_DATA); + payment.setAddress(this.shippingAddress); + this.payment = payment; + + final Session session = new Session(); + session.setShopperIPAddress(SHOPPER_IP_ADDRESS); + session.setId(SESSION_ID); + this.session = session; + + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(EMAIL_ADDRESS); + shopper.setSession(this.session); + this.shopper = shopper; + + final StoredCredentials storedCredentials = new StoredCredentials(); + storedCredentials.setUsage(Usage.FIRST); + this.storedCredentials = storedCredentials; } protected AuthoriseRequestParameters getAuthoriseRequestParameters() { return AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .build(); + .withMerchantInfo(merchantInfo) + .build(); } @Test public void createRedirectAuthoriseRequestShouldReturnErrorWhenThereAreMissingFields() throws WorldpayException { final AuthoriseRequestParameters authoriseRequestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withPayment(PAYMENT) - .withShopper(SHOPPER) - .withStoredCredentials(STORED_CREDENTIALS) - .build(); + .withMerchantInfo(merchantInfo) + .withOrderInfo(basicOrderInfo) + .withPayment(payment) + .withShopper(shopper) + .withStoredCredentials(storedCredentials) + .build(); final RedirectAuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); RedirectAuthoriseServiceResponse response = gateway.redirectAuthorise(request); @@ -88,13 +177,13 @@ public void createRedirectAuthoriseRequestShouldReturnErrorWhenThereAreMissingFi @Test public void createTokenAndRedirectAuthoriseRequestShouldReturnErrorWhenThereAreMissingFields() throws WorldpayException { final AuthoriseRequestParameters authoriseRequestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withTokenRequest(TOKEN_REQUEST) - .withPayment(PAYMENT) - .withShopper(SHOPPER) - .withStoredCredentials(STORED_CREDENTIALS) - .build(); + .withMerchantInfo(merchantInfo) + .withOrderInfo(basicOrderInfo) + .withTokenRequest(tokenRequest) + .withPayment(payment) + .withShopper(shopper) + .withStoredCredentials(storedCredentials) + .build(); final RedirectAuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); RedirectAuthoriseServiceResponse response = gateway.redirectAuthorise(request); @@ -103,17 +192,18 @@ public void createTokenAndRedirectAuthoriseRequestShouldReturnErrorWhenThereAreM @Test public void createRedirectAuthoriseRequestShouldGetRedirectReference() throws WorldpayException { - final Shopper shopper = new Shopper(EMAIL_ADDRESS, null, null, null); + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(EMAIL_ADDRESS); final AuthoriseRequestParameters authoriseRequestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withOrderContent(ORDER_CONTENT) - .withIncludedPTs(includedPaymentMethods) - .withShippingAddress(ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withShopper(shopper) - .build(); + .withMerchantInfo(merchantInfo) + .withOrderInfo(basicOrderInfo) + .withOrderContent(ORDER_CONTENT) + .withIncludedPTs(includedPaymentMethods) + .withShippingAddress(address) + .withBillingAddress(billingAddress) + .withStatementNarrative(STATEMENT_NARRATIVE) + .withShopper(shopper) + .build(); final RedirectAuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); assertNull(request.getOrder().getTokenRequest()); @@ -131,21 +221,23 @@ public void createRedirectAuthoriseRequestShouldGetRedirectReference() throws Wo @Test public void createTokenAndRedirectAuthoriseRequestShouldGetRedirectReferenceAndRequestTokenCreation() throws WorldpayException { - final Shopper shopper = new Shopper(EMAIL_ADDRESS, AUTH_SHOPPER_ID, null, null); + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(EMAIL_ADDRESS); + shopper.setAuthenticatedShopperID(AUTH_SHOPPER_ID); final AuthoriseRequestParameters authoriseRequestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withOrderContent(ORDER_CONTENT) - .withIncludedPTs(includedPaymentMethods) - .withShopper(shopper) - .withShippingAddress(ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withTokenRequest(TOKEN_REQUEST) - .build(); + .withMerchantInfo(merchantInfo) + .withOrderInfo(basicOrderInfo) + .withOrderContent(ORDER_CONTENT) + .withIncludedPTs(includedPaymentMethods) + .withShopper(shopper) + .withShippingAddress(address) + .withBillingAddress(billingAddress) + .withStatementNarrative(STATEMENT_NARRATIVE) + .withTokenRequest(tokenRequest) + .build(); final RedirectAuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); - assertEquals(TOKEN_REQUEST, request.getOrder().getTokenRequest()); + assertEquals(tokenRequest, request.getOrder().getTokenRequest()); final RedirectAuthoriseServiceResponse redirectAuthorise = gateway.redirectAuthorise(request); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RedirectAuthoriseServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RedirectAuthoriseServiceRequestTest.java index 3348a90f..063878da 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RedirectAuthoriseServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RedirectAuthoriseServiceRequestTest.java @@ -1,18 +1,21 @@ package com.worldpay.service; +import com.google.common.collect.ImmutableList; +import com.worldpay.data.*; +import com.worldpay.data.payment.Cse; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.threeds2.AuthenticationRiskData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.threeds2.ShopperAccountRiskData; +import com.worldpay.data.threeds2.TransactionRiskData; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.enums.lineItem.LineItemType; import com.worldpay.enums.order.DynamicInteractionType; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Cse; -import com.worldpay.service.model.payment.Payment; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.model.threeds2.AuthenticationRiskData; -import com.worldpay.service.model.threeds2.RiskData; -import com.worldpay.service.model.threeds2.ShopperAccountRiskData; -import com.worldpay.service.model.threeds2.TransactionRiskData; -import com.worldpay.service.model.token.TokenRequest; import com.worldpay.service.request.AuthoriseRequestParameters; import com.worldpay.service.request.RedirectAuthoriseServiceRequest; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Before; import org.junit.Test; @@ -37,35 +40,127 @@ public class RedirectAuthoriseServiceRequestTest { private static final String ENCRYPTED_DATA = "encryptedData"; private static final String TAX_AMOUNT = "taxtAmount"; private static final String TERMS_URL = "termsUrl"; - private static final List INCLUDED_PAYMENT_TYPES = singletonList(ONLINE); - private static final List EXCLUDED_PAYMENT_TYPES = singletonList(VISA); - - private static final TokenRequest TOKEN_REQUEST = new TokenRequest("tokenEventReferenceNumber", "tokenReason"); - private static final Address SHIPPING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final Address BILLING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); + private static final String TOKEN_EVENT_REFERENCE = "tokenEventReferenceNumber"; + private static final String TOKEN_REASON = "tokenReason"; private static final String SESSION_ID = "sessionId"; private static final String SHOPPER_IP_ADDRESS = "shopperIPAddress"; - private static final Session SESSION = new Session(SHOPPER_IP_ADDRESS, SESSION_ID); - private static final Shopper SHOPPER = new Shopper(EMAIL_ADDRESS, null, null, SESSION); - private static final Amount AMOUNT = new Amount("100", "EUR", "2"); - private static final Payment PAYMENT = new Cse(ENCRYPTED_DATA, SHIPPING_ADDRESS); - private static final StoredCredentials STORED_CREDENTIALS = new StoredCredentials(); - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo("MERCHANT1ECOM", "3l3ph4nt_&_c4st!3"); + private static final String MERCHANT_CODE = "MERCHANT1ECOM"; + private static final String MERCHANT_PASS = "3l3ph4nt_&_c4st!3"; private static final String ORDER_DESC = "Your Order & Order desc"; - private static final BasicOrderInfo BASIC_ORDER_INFO = new BasicOrderInfo(ORDER_CODE, ORDER_DESC, AMOUNT); + private static final String CITY = "city"; + private static final String GB = "GB"; + private static final String NAME = "John"; + private static final String LAST_NAME = "Shopper"; + private static final String SHOPPER_ADDRESS_1 = "Shopper Address1"; + private static final String SHOPPER_ADDRESS_2 = "Shopper Address2"; + private static final String SHOPPER_ADDRESS_3 = "Shopper Address3"; + private static final String POSTAL_CODE = "Postal code"; + private static final List INCLUDED_PAYMENT_TYPES = singletonList(ONLINE); + private static final List EXCLUDED_PAYMENT_TYPES = singletonList(VISA); + private static final List INCLUDED_PAYMENT_TYPES_METHOD = singletonList(ONLINE.getMethodCode()); + private static final List EXCLUDED_PAYMENT_TYPES_METHOD = singletonList(VISA.getMethodCode()); + private static final StoredCredentials STORED_CREDENTIALS = new StoredCredentials(); private static final DynamicInteractionType DYNAMIC_INTERACTION_TYPE = DynamicInteractionType.ECOMMERCE; private static final List PAYMENT_METHOD_ATTRIBUTE = List.of(new PaymentMethodAttribute()); + private static final String USD = "USD"; + private static final String EXPONENT = "2"; + private static final String MANDATE_TYPE = "mandateType"; + + private TokenRequest tokenRequest; + private Address shippingAddress; + private Address billingAddress; + private Payment payment; + private BasicOrderInfo basicOrderInfo; + private Session session; + private Shopper shopper; + private Amount amount; + private MerchantInfo merchantInfo; + private ShopperFields shopperFields = new ShopperFields(); + private CustomNumericFields customNumericFields = new CustomNumericFields(); + private CustomStringFields customStringFields = new CustomStringFields(); + private Purchase purchase; private RiskData riskData; private LineItem lineItemOne; private LineItem lineItemTwo; private OrderLines orderLines; + private FraudSightData fraudSightData; + private BranchSpecificExtension branchSpecificExtension; @Before public void setUp() throws Exception { - lineItemOne = createLineItem("id", "value", LineItem.LINE_ITEM_TYPE.PHYSICAL, "name", "200", "PCS", "taxRate", "20", "0", 20D, "0.5"); - lineItemTwo = createLineItem("id2", "value2", LineItem.LINE_ITEM_TYPE.PHYSICAL, "name2", "2000", "PCS2", "taxRate2", "200", "00", 0D, "0.5"); - orderLines = new OrderLines(TAX_AMOUNT, TERMS_URL, List.of(lineItemOne, lineItemTwo)); + lineItemOne = createLineItem("id", "value", LineItemType.PHYSICAL, "name", "200", "PCS", "taxRate", "20", "0", 20D, "0.5"); + lineItemTwo = createLineItem("id2", "value2", LineItemType.PHYSICAL, "name2", "2000", "PCS2", "taxRate2", "200", "00", 0D, "0.5"); + final OrderLines orderLines = new OrderLines(); + orderLines.setOrderTaxAmount(TAX_AMOUNT); + orderLines.setTermsURL(TERMS_URL); + orderLines.setLineItems(List.of(lineItemOne, lineItemTwo)); + this.orderLines = orderLines; riskData = createRiskData(); + purchase = createPurchaseItem(); + + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASS); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setTokenEventReference(TOKEN_EVENT_REFERENCE); + tokenRequest.setMerchantToken(false); + this.tokenRequest = tokenRequest; + + final Amount amount = new Amount(); + amount.setExponent(EXPONENT); + amount.setCurrencyCode("EUR"); + amount.setValue("100"); + this.amount = amount; + + final BasicOrderInfo basicOrderInfo = new BasicOrderInfo(); + basicOrderInfo.setOrderCode(ORDER_CODE); + basicOrderInfo.setDescription(ORDER_DESC); + basicOrderInfo.setAmount(amount); + this.basicOrderInfo = basicOrderInfo; + + riskData = new RiskData(); + + final FraudSightData fraudSightData = new FraudSightData(); + fraudSightData.setShopperFields(shopperFields); + fraudSightData.setCustomStringFields(customStringFields); + fraudSightData.setCustomNumericFields(customNumericFields); + this.fraudSightData = fraudSightData; + + final BranchSpecificExtension branchSpecificExtension = new BranchSpecificExtension(); + branchSpecificExtension.setPurchase(ImmutableList.of(purchase)); + this.branchSpecificExtension = branchSpecificExtension; + + final Session session = new Session(); + session.setId(SESSION_ID); + session.setShopperIPAddress(SHOPPER_IP_ADDRESS); + this.session = session; + + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(EMAIL_ADDRESS); + shopper.setSession(this.session); + this.shopper = shopper; + + final Address address = new Address(); + address.setFirstName(NAME); + address.setLastName(LAST_NAME); + address.setAddress1(SHOPPER_ADDRESS_1); + address.setAddress2(SHOPPER_ADDRESS_2); + address.setAddress3(SHOPPER_ADDRESS_3); + address.setPostalCode(POSTAL_CODE); + address.setCity(CITY); + address.setCountryCode(GB); + + this.shippingAddress = address; + this.billingAddress = address; + + final Cse cse = new Cse(); + cse.setPaymentType(PaymentType.CSEDATA.getMethodCode()); + cse.setAddress(this.shippingAddress); + cse.setEncryptedData(ENCRYPTED_DATA); + payment = cse; } @Test @@ -79,61 +174,70 @@ private void verifyOrder(final RedirectAuthoriseServiceRequest request) { final Order order = request.getOrder(); assertEquals(ORDER_CODE, order.getOrderCode()); assertEquals(ORDER_DESC, order.getDescription()); - assertEquals(AMOUNT, order.getAmount()); - assertEquals(MERCHANT_INFO, request.getMerchantInfo()); + assertEquals(amount, order.getAmount()); + assertEquals(merchantInfo, request.getMerchantInfo()); assertNotNull(order.getPaymentDetails()); - assertEquals(PAYMENT, order.getPaymentDetails().getPayment()); - assertEquals(SESSION, order.getPaymentDetails().getSession()); + assertEquals(payment, order.getPaymentDetails().getPayment()); + assertEquals(session, order.getPaymentDetails().getSession()); assertEquals(STORED_CREDENTIALS, order.getPaymentDetails().getStoredCredentials()); assertEquals(INSTALLATION_ID, order.getInstallationId()); - assertEquals(INCLUDED_PAYMENT_TYPES, order.getPaymentMethodMask().getIncludes()); - assertEquals(EXCLUDED_PAYMENT_TYPES, order.getPaymentMethodMask().getExcludes()); + assertEquals(INCLUDED_PAYMENT_TYPES_METHOD, order.getPaymentMethodMask().getIncludes()); + assertEquals(EXCLUDED_PAYMENT_TYPES_METHOD, order.getPaymentMethodMask().getExcludes()); assertEquals(ORDER_CONTENT, order.getOrderContent()); - assertEquals(SHOPPER, order.getShopper()); - assertEquals(TOKEN_REQUEST, order.getTokenRequest()); - assertEquals(SHIPPING_ADDRESS, order.getShippingAddress()); - assertEquals(BILLING_ADDRESS, order.getBillingAddress()); + assertEquals(shopper, order.getShopper()); + assertEquals(tokenRequest, order.getTokenRequest()); + assertEquals(shippingAddress, order.getShippingAddress()); + assertEquals(billingAddress, order.getBillingAddress()); assertEquals(STATEMENT_NARRATIVE, order.getStatementNarrative()); assertEquals(DYNAMIC_INTERACTION_TYPE, order.getDynamicInteractionType()); assertEquals(PAYMENT_METHOD_ATTRIBUTE, order.getPaymentMethodAttributes()); assertEquals(riskData, order.getRiskData()); assertEquals(orderLines, order.getOrderLines()); + assertEquals(fraudSightData, order.getFraudSightData()); + assertEquals(branchSpecificExtension, order.getBranchSpecificExtension()); + assertEquals(MANDATE_TYPE, order.getMandateType()); } private AuthoriseRequestParameters createRequestParameters() { return AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(MERCHANT_INFO) - .withOrderInfo(BASIC_ORDER_INFO) - .withPayment(PAYMENT) - .withShopper(SHOPPER) + .withMerchantInfo(merchantInfo) + .withOrderInfo(basicOrderInfo) + .withPayment(payment) + .withShopper(shopper) .withStoredCredentials(STORED_CREDENTIALS) .withInstallationId(INSTALLATION_ID) .withIncludedPTs(INCLUDED_PAYMENT_TYPES) .withExcludedPTs(EXCLUDED_PAYMENT_TYPES) .withOrderContent(ORDER_CONTENT) - .withTokenRequest(TOKEN_REQUEST) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) + .withTokenRequest(tokenRequest) + .withShippingAddress(shippingAddress) + .withBillingAddress(billingAddress) .withStatementNarrative(STATEMENT_NARRATIVE) .withDynamicInteractionType(DYNAMIC_INTERACTION_TYPE) .withPaymentMethodAttributes(PAYMENT_METHOD_ATTRIBUTE) .withOrderLines(orderLines) .withRiskData(riskData) + .withFraudSightData(fraudSightData) + .withLevel23Data(branchSpecificExtension) + .withMandateType(MANDATE_TYPE) .build(); } - private LineItem createLineItem(final String id, final String value, final LineItem.LINE_ITEM_TYPE physical, final String name, final String s, final String pcs, final String taxRate, final String totalAmount, final String totalDiscountAmount, final double totalTaxAmountValue, final String unitPrice) { + private LineItem createLineItem(final String id, final String value, final LineItemType physical, final String name, final String qunatity, final String quantityUnit, final String taxRate, final String totalAmount, final String totalDiscountAmount, final double totalTaxAmountValue, final String unitPrice) { final LineItem lineItem = new LineItem(); - lineItem.setLineItemReference(new LineItemReference("id", "value")); - lineItem.setLineItemType(LineItem.LINE_ITEM_TYPE.DISCOUNT); - lineItem.setName("name"); - lineItem.setQuantity("200"); - lineItem.setQuantityUnit("PCS"); - lineItem.setTaxRate("taxRate"); - lineItem.setTotalAmount("20"); - lineItem.setTotalDiscountAmount("0"); - lineItem.setTotalTaxAmountValue(20D); - lineItem.setUnitPrice("1"); + final LineItemReference lineItemReference = new LineItemReference(); + lineItemReference.setId(id); + lineItemReference.setValue(value); + lineItem.setLineItemReference(lineItemReference); + lineItem.setLineItemType(physical); + lineItem.setName(name); + lineItem.setQuantity(qunatity); + lineItem.setQuantityUnit(quantityUnit); + lineItem.setTaxRate(taxRate); + lineItem.setTotalAmount(totalAmount); + lineItem.setTotalDiscountAmount(totalDiscountAmount); + lineItem.setTotalTaxAmountValue(totalTaxAmountValue); + lineItem.setUnitPrice(unitPrice); return lineItem; } @@ -143,7 +247,7 @@ private RiskData createRiskData() { final AuthenticationRiskData authenticationRiskData = new AuthenticationRiskData(); authenticationRiskData.setAuthenticationMethod("authenticationMethod"); - authenticationRiskData.setAuthenticationTimestamp(new Date(LocalDateTime.now())); + authenticationRiskData.setAuthenticationTimestamp(WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(LocalDateTime.now())); riskData.setAuthenticationRiskData(authenticationRiskData); final ShopperAccountRiskData shopperAccountRiskData = new ShopperAccountRiskData(); @@ -153,8 +257,8 @@ private RiskData createRiskData() { shopperAccountRiskData.setShippingNameMatchesAccountName("shippingNameMatchesAccountName"); shopperAccountRiskData.setShopperAccountAgeIndicator("shopperAccountAgeIndicator"); shopperAccountRiskData.setShopperAccountChangeIndicator("shopperAccountAgeIndicator"); - shopperAccountRiskData.setShopperAccountCreationDate(new Date(LocalDateTime.now())); - shopperAccountRiskData.setShopperAccountModificationDate(new Date(LocalDateTime.now())); + shopperAccountRiskData.setShopperAccountCreationDate(WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(LocalDateTime.now())); + shopperAccountRiskData.setShopperAccountModificationDate(WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(LocalDateTime.now())); riskData.setShopperAccountRiskData(shopperAccountRiskData); final TransactionRiskData transactionRiskData = new TransactionRiskData(); @@ -167,4 +271,40 @@ private RiskData createRiskData() { return riskData; } + + private Purchase createPurchaseItem() { + purchase = new Purchase(); + purchase.setInvoiceReferenceNumber("invoiceNumber"); + purchase.setCustomerReference("customerReference"); + purchase.setCardAcceptorTaxId("cardAcceptorId"); + + final Amount salesTaxAmount = new Amount(); + salesTaxAmount.setExponent(EXPONENT); + salesTaxAmount.setCurrencyCode(USD); + salesTaxAmount.setValue("10000"); + + final Amount discontAmount = new Amount(); + discontAmount.setExponent(EXPONENT); + discontAmount.setCurrencyCode(USD); + discontAmount.setValue("1000"); + + final Amount shippingAmount = new Amount(); + shippingAmount.setExponent(EXPONENT); + shippingAmount.setCurrencyCode(USD); + shippingAmount.setValue("0"); + + final Amount dutyAmount = new Amount(); + dutyAmount.setExponent(EXPONENT); + dutyAmount.setCurrencyCode(USD); + dutyAmount.setValue("0"); + + purchase.setSalesTax(salesTaxAmount); + purchase.setDiscountAmount(discontAmount); + purchase.setShippingAmount(shippingAmount); + purchase.setDutyAmount(dutyAmount); + purchase.setDestinationPostalCode("10200"); + purchase.setDestinationCountryCode("US"); + + return purchase; + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RefundServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RefundServiceRequestIntegrationTest.java index 16654b22..01086458 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RefundServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RefundServiceRequestIntegrationTest.java @@ -1,12 +1,13 @@ package com.worldpay.service; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.RefundServiceRequest; import com.worldpay.service.response.RefundServiceResponse; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.servicelayer.ServicelayerBaseTest; +import org.junit.Before; import org.junit.Test; import javax.annotation.Resource; @@ -20,18 +21,34 @@ public class RefundServiceRequestIntegrationTest extends ServicelayerBaseTest { private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; private static final String ORDER_CODE = String.valueOf(new Date().getTime()); - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String REFERENCE = "reference"; + private static final String EUR = "EUR"; + private static final String EXPONENT = "2"; + + private MerchantInfo merchantInfo; @Resource(name = "worldpayServiceGateway") private WorldpayServiceGateway gateway; + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + } + @Test public void testRefundFullAmount() throws WorldpayException { - WPSGTestHelper.directAuthorise(gateway, MERCHANT_INFO, ORDER_CODE); - WPSGTestHelper.capture(gateway, MERCHANT_INFO, ORDER_CODE); + WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); + WPSGTestHelper.capture(gateway, merchantInfo, ORDER_CODE); - final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(MERCHANT_INFO, ORDER_CODE, new Amount("100", "EUR", "2"), REFERENCE, Boolean.FALSE); + final Amount amountMock = new Amount(); + amountMock.setExponent(EXPONENT); + amountMock.setCurrencyCode(EUR); + amountMock.setValue("100"); + + final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(merchantInfo, ORDER_CODE, amountMock, REFERENCE, Boolean.FALSE); final RefundServiceResponse refund = gateway.refund(request); assertNotNull("Refund response is null!", refund); @@ -44,10 +61,15 @@ public void testRefundFullAmount() throws WorldpayException { @Test public void testRefundPartialAmount() throws WorldpayException { - WPSGTestHelper.directAuthorise(gateway, MERCHANT_INFO, ORDER_CODE); - WPSGTestHelper.capture(gateway, MERCHANT_INFO, ORDER_CODE); + WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); + WPSGTestHelper.capture(gateway, merchantInfo, ORDER_CODE); + + final Amount amountMock = new Amount(); + amountMock.setExponent(EXPONENT); + amountMock.setCurrencyCode(EUR); + amountMock.setValue("70"); - final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(MERCHANT_INFO, ORDER_CODE, new Amount("70", "EUR", "2"), REFERENCE, Boolean.FALSE); + final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(merchantInfo, ORDER_CODE, amountMock, REFERENCE, Boolean.FALSE); final RefundServiceResponse refund = gateway.refund(request); assertNotNull("Refund response is null!", refund); @@ -61,10 +83,16 @@ public void testRefundPartialAmount() throws WorldpayException { @Test public void testRefundMultiple() throws WorldpayException { - WPSGTestHelper.directAuthorise(gateway, MERCHANT_INFO, ORDER_CODE); - WPSGTestHelper.capture(gateway, MERCHANT_INFO, ORDER_CODE); + WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); + WPSGTestHelper.capture(gateway, merchantInfo, ORDER_CODE); - final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(MERCHANT_INFO, ORDER_CODE, new Amount("70", "EUR", "2"), REFERENCE, Boolean.FALSE); + final Amount amountMock = new Amount(); + amountMock.setExponent(EXPONENT); + amountMock.setCurrencyCode(EUR); + amountMock.setValue("70"); + + + final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(merchantInfo, ORDER_CODE, amountMock, REFERENCE, Boolean.FALSE); final RefundServiceResponse refund = gateway.refund(request); assertNotNull("Refund response is null!", refund); @@ -74,7 +102,12 @@ public void testRefundMultiple() throws WorldpayException { assertNotNull("Ampount in the refund is null!", amount); assertEquals("Incorrect amount refunded", "70", amount.getValue()); - final RefundServiceRequest request2 = RefundServiceRequest.createRefundRequest(MERCHANT_INFO, ORDER_CODE, new Amount("30", "EUR", "2"), REFERENCE, Boolean.FALSE); + final Amount amountMock2 = new Amount(); + amountMock2.setExponent(EXPONENT); + amountMock2.setCurrencyCode(EUR); + amountMock2.setValue("30"); + + final RefundServiceRequest request2 = RefundServiceRequest.createRefundRequest(merchantInfo, ORDER_CODE,amountMock2, REFERENCE, Boolean.FALSE); final RefundServiceResponse refund2 = gateway.refund(request2); assertNotNull("Refund response is null!", refund2); @@ -87,10 +120,15 @@ public void testRefundMultiple() throws WorldpayException { @Test public void testRefundAmountMoreThanCaptured() throws WorldpayException { - WPSGTestHelper.directAuthorise(gateway, MERCHANT_INFO, ORDER_CODE); - WPSGTestHelper.capture(gateway, MERCHANT_INFO, ORDER_CODE); + WPSGTestHelper.directAuthorise(gateway, merchantInfo, ORDER_CODE); + WPSGTestHelper.capture(gateway, merchantInfo, ORDER_CODE); + + final Amount amountMock = new Amount(); + amountMock.setExponent(EXPONENT); + amountMock.setCurrencyCode(EUR); + amountMock.setValue("140"); - final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(MERCHANT_INFO, ORDER_CODE, new Amount("140", "EUR", "2"), REFERENCE, Boolean.FALSE); + final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(merchantInfo, ORDER_CODE, amountMock, REFERENCE, Boolean.FALSE); final RefundServiceResponse refund = gateway.refund(request); assertNotNull("Refund response is null!", refund); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RefundServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RefundServiceRequestTest.java index 8d987e43..39c014ec 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RefundServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/RefundServiceRequestTest.java @@ -1,10 +1,11 @@ package com.worldpay.service; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.MerchantInfo; import com.worldpay.service.request.RefundServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -18,21 +19,38 @@ public class RefundServiceRequestTest { private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; private static final String ORDER_CODE = "orderCode"; - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); - private static final Amount AMOUNT = new Amount("100", "EUR", "2"); private static final String REFERENCE = "reference"; + private static final String EUR = "EUR"; + private static final String EXPONENT = "2"; + + private Amount amount; + private MerchantInfo merchantInfo; @Rule @SuppressWarnings("PMD.MemberScope") public ExpectedException expectedException = ExpectedException.none(); + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + + final Amount amount = new Amount(); + amount.setExponent(EXPONENT); + amount.setCurrencyCode(EUR); + amount.setValue("100"); + this.amount = amount; + } + @Test - public void testRefundFullAmount() throws WorldpayException { + public void testRefundFullAmount() { - final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(MERCHANT_INFO, ORDER_CODE, AMOUNT, REFERENCE, Boolean.FALSE); + final RefundServiceRequest request = RefundServiceRequest.createRefundRequest(merchantInfo, ORDER_CODE, amount, REFERENCE, Boolean.FALSE); - assertEquals(AMOUNT, request.getAmount()); - assertEquals(MERCHANT_INFO, request.getMerchantInfo()); + assertEquals(amount, request.getAmount()); + assertEquals(merchantInfo, request.getMerchantInfo()); assertEquals(ORDER_CODE, request.getOrderCode()); assertEquals(REFERENCE, request.getReference()); assertFalse(request.getShopperWebformRefund()); @@ -42,20 +60,20 @@ public void testRefundFullAmount() throws WorldpayException { public void createRefundRequestShouldRaiseIllegalArgumentExceptionWhenMerchantInfoIsNull() { expectedException.expect(IllegalArgumentException.class); - RefundServiceRequest.createRefundRequest(null, ORDER_CODE, AMOUNT, REFERENCE, Boolean.FALSE); + RefundServiceRequest.createRefundRequest(null, ORDER_CODE, amount, REFERENCE, Boolean.FALSE); } @Test public void createRefundRequestShouldRaiseIllegalArgumentExceptionWhenOrderCodeIsNull() { expectedException.expect(IllegalArgumentException.class); - RefundServiceRequest.createRefundRequest(MERCHANT_INFO, null, AMOUNT, REFERENCE, Boolean.FALSE); + RefundServiceRequest.createRefundRequest(merchantInfo, null, amount, REFERENCE, Boolean.FALSE); } @Test public void createRefundRequestShouldRaiseIllegalArgumentExceptionWhenAmountIsNull() { expectedException.expect(IllegalArgumentException.class); - RefundServiceRequest.createRefundRequest(MERCHANT_INFO, ORDER_CODE, null, REFERENCE, Boolean.FALSE); + RefundServiceRequest.createRefundRequest(merchantInfo, ORDER_CODE, null, REFERENCE, Boolean.FALSE); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/UpdateTokenServiceRequestIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/UpdateTokenServiceRequestIntegrationTest.java index 50061c2d..5637f66b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/UpdateTokenServiceRequestIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/UpdateTokenServiceRequestIntegrationTest.java @@ -1,14 +1,16 @@ package com.worldpay.service; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.Date; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.data.Date; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.TokenRequest; import com.worldpay.service.response.CreateTokenResponse; import com.worldpay.service.response.UpdateTokenResponse; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.servicelayer.ServicelayerBaseTest; +import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -25,16 +27,29 @@ public class UpdateTokenServiceRequestIntegrationTest extends ServicelayerBaseTe private static final String MERCHANT_CODE = "MERCHANT1ECOM"; private static final String MERCHANT_PASSWORD = "3l3ph4nt_&_c4st!3"; - private static final MerchantInfo merchantInfo = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); private static final String TOKEN_REASON = "tokenReason"; private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; + private MerchantInfo merchantInfo; + @Resource(name = "worldpayServiceGateway") private WorldpayServiceGateway gateway; + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + } + @Test public void testUpdateTokenWithoutOrderWithShopperScope() throws WorldpayException { - final TokenRequest tokenRequest = new TokenRequest(TOKEN_EVENT_REFERENCE, TOKEN_REASON); + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setMerchantToken(false); + tokenRequest.setTokenEventReference(TOKEN_EVENT_REFERENCE); + tokenRequest.setTokenReason(TOKEN_REASON); + final String authenticatedShopperId = UUID.randomUUID().toString(); final CreateTokenResponse createTokenResponse = WPSGTestHelper.createShopperToken(gateway, merchantInfo, tokenRequest, authenticatedShopperId); final String paymentTokenId = createTokenResponse.getToken().getTokenDetails().getPaymentTokenID(); @@ -54,7 +69,10 @@ public void testUpdateTokenWithoutOrderWithShopperScope() throws WorldpayExcepti @Test @Ignore("ignored because its unstable") public void testUpdateTokenWithoutOrderWithMerchantScope() throws WorldpayException { - final TokenRequest tokenRequest = new TokenRequest(TOKEN_EVENT_REFERENCE, TOKEN_REASON, true); + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setMerchantToken(true); + tokenRequest.setTokenEventReference(TOKEN_EVENT_REFERENCE); + tokenRequest.setTokenReason(TOKEN_REASON); final CreateTokenResponse createTokenResponse = WPSGTestHelper.createMerchantToken(gateway, merchantInfo, tokenRequest); final String paymentTokenId = createTokenResponse.getToken().getTokenDetails().getPaymentTokenID(); final CardDetails cardDetails = createCardDetailsWithExpirationDate6YearsFromNow(); @@ -71,7 +89,7 @@ public void testUpdateTokenWithoutOrderWithMerchantScope() throws WorldpayExcept private CardDetails createCardDetailsWithExpirationDate6YearsFromNow() { final CardDetails cardDetails = new CardDetails(); - cardDetails.setExpiryDate(new Date(LocalDateTime.now().plusYears(6))); + cardDetails.setExpiryDate(WorldpayInternalModelTransformerUtil.newDateFromLocalDateTime(LocalDateTime.now().plusYears(6))); cardDetails.setCardHolderName("new name"); return cardDetails; } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/UpdateTokenServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/UpdateTokenServiceRequestTest.java index 5a08f58d..633d5a47 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/UpdateTokenServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/UpdateTokenServiceRequestTest.java @@ -1,8 +1,8 @@ package com.worldpay.service; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.TokenRequest; import com.worldpay.service.request.UpdateTokenServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Test; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/WPSGTestHelper.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/WPSGTestHelper.java index 2f26a635..a3ef1f0f 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/WPSGTestHelper.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/WPSGTestHelper.java @@ -1,16 +1,17 @@ package com.worldpay.service; +import com.worldpay.data.payment.Cse; import com.worldpay.enums.order.DynamicInteractionType; import com.worldpay.exception.WorldpayException; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.payment.PaymentBuilder; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.data.*; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.TokenRequest; +import com.worldpay.service.model.payment.PaymentType; import com.worldpay.service.request.*; import com.worldpay.service.response.*; - -import java.time.LocalDateTime; +import com.worldpay.util.WorldpayInternalModelTransformerUtil; +import org.apache.commons.lang.StringUtils; public class WPSGTestHelper { @@ -19,26 +20,62 @@ public class WPSGTestHelper { private static final String STATEMENT_NARRATIVE = "STATEMENT NARRATIVE TEXT"; private static final String SHOPPER_EMAIL = "jshopper@myprovider.com"; - private static final Date EXPIRY_DATE = new com.worldpay.service.model.Date(LocalDateTime.now().plusYears(1)); - private static final Session SESSION = new Session("192.168.1.1", "sessionId1234"); - private static final Browser BROWSER = new Browser("text/html,application/xhtml+xml,application/xml;q=0. 9,*/*;q=0.8", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)", "0"); - private static final Address ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final Shopper SHOPPER = new Shopper(SHOPPER_EMAIL, null, BROWSER, SESSION); - private static final Address BILLING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); + private static final String SESSION_IP = "192.168.1.1"; + private static final String SESSION_ID = "sessionId1234"; + private static final String ORDER_DESCRIPTION = "Your Order & Order desc"; + private static final String HEADER = "text/html,application/xhtml+xml,application/xml;q=0. 9,*/*;q=0.8"; + private static final String USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)"; + private static final String DEVICE_TYPE = "0"; + private static final String CITY = "city"; + private static final String GB = "GB"; + private static final String NAME = "John"; + private static final String SHOPPER = "Shopper"; + private static final String SHOPPER_ADDRESS_1 = "Shopper Address1"; + private static final String SHOPPER_ADDRESS_2 = "Shopper Address2"; + private static final String SHOPPER_ADDRESS_3 = "Shopper Address3"; + private static final String POSTAL_CODE = "Postal code"; + private static final Address ADDRESS = createAddress(); + private static final Address BILLING_ADDRESS = createAddress(); + private static final String EUR = "EUR"; + private static final String EXPONENT = "2"; public static DirectAuthoriseServiceResponse directAuthorise(final WorldpayServiceGateway gateway, final MerchantInfo merchantInfo, final String orderCode) throws WorldpayException { - final BasicOrderInfo orderInfo = new BasicOrderInfo(orderCode, "Your Order & Order desc", new Amount("100", "EUR", "2")); - final Payment payment = PaymentBuilder.createVISASSL("4444333322221111", EXPIRY_DATE, "J. Shopper", "123", ADDRESS); + final Amount amount = new Amount(); + amount.setExponent(EXPONENT); + amount.setCurrencyCode(EUR); + amount.setValue("100"); + + final BasicOrderInfo orderInfo = new BasicOrderInfo(); + orderInfo.setOrderCode(orderCode); + orderInfo.setDescription(ORDER_DESCRIPTION); + orderInfo.setAmount(amount); + + final Payment payment = WorldpayInternalModelTransformerUtil + .createAlternativeShopperBankCodePayment(PaymentType.IDEAL, "ASN", "successURL", "failureURL", "cancelURL", StringUtils.EMPTY, StringUtils.EMPTY); + + final Session session = new Session(); + session.setShopperIPAddress(SESSION_IP); + session.setId(SESSION_ID); + + final Browser browser = new Browser(); + browser.setDeviceType(DEVICE_TYPE); + browser.setAcceptHeader(HEADER); + browser.setUserAgentHeader(USER_AGENT); + + final Shopper shopper = new Shopper(); + shopper.setSession(session); + shopper.setShopperEmailAddress(SHOPPER_EMAIL); + shopper.setBrowser(browser); final AuthoriseRequestParameters requestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(orderInfo) - .withPayment(payment) - .withShopper(SHOPPER) - .withShippingAddress(ADDRESS) - .withBillingAddress(BILLING_ADDRESS) - .withStatementNarrative(STATEMENT_NARRATIVE) - .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE).build(); + .withMerchantInfo(merchantInfo) + .withOrderInfo(orderInfo) + .withPayment(payment) + .withShopper(shopper) + .withShippingAddress(ADDRESS) + .withBillingAddress(BILLING_ADDRESS) + .withStatementNarrative(STATEMENT_NARRATIVE) + .withDynamicInteractionType(DynamicInteractionType.ECOMMERCE).build(); final DirectAuthoriseServiceRequest request = DirectAuthoriseServiceRequest.createDirectAuthoriseRequest(requestParameters); return gateway.directAuthorise(request); @@ -46,15 +83,21 @@ public static DirectAuthoriseServiceResponse directAuthorise(final WorldpayServi public static CreateTokenResponse createShopperToken(final WorldpayServiceGateway gateway, final MerchantInfo merchantInfo, final TokenRequest tokenRequest, final String authenticatedShopperId) throws WorldpayException { - final Payment payment = PaymentBuilder.createCSE(ENCRYPTED_DATA, ADDRESS); - final CreateTokenServiceRequest request = CreateTokenServiceRequest.createTokenRequestForShopperToken(merchantInfo, authenticatedShopperId, payment, tokenRequest); + final Cse cse = new Cse(); + cse.setEncryptedData(ENCRYPTED_DATA); + cse.setAddress(ADDRESS); + cse.setPaymentType(PaymentType.CSEDATA.getMethodCode()); + final CreateTokenServiceRequest request = CreateTokenServiceRequest.createTokenRequestForShopperToken(merchantInfo, authenticatedShopperId, cse, tokenRequest); return gateway.createToken(request); } public static CreateTokenResponse createMerchantToken(final WorldpayServiceGateway gateway, final MerchantInfo merchantInfo, final TokenRequest tokenRequest) throws WorldpayException { - final Payment payment = PaymentBuilder.createCSE(ENCRYPTED_DATA, ADDRESS); - final CreateTokenServiceRequest request = CreateTokenServiceRequest.createTokenRequestForMerchantToken(merchantInfo, payment, tokenRequest); + final Cse cse = new Cse(); + cse.setEncryptedData(ENCRYPTED_DATA); + cse.setAddress(ADDRESS); + cse.setPaymentType(PaymentType.CSEDATA.getMethodCode()); + final CreateTokenServiceRequest request = CreateTokenServiceRequest.createTokenRequestForMerchantToken(merchantInfo, cse, tokenRequest); return gateway.createToken(request); } @@ -77,8 +120,26 @@ public static DeleteTokenResponse deleteToken(final WorldpayServiceGateway gatew } public static CaptureServiceResponse capture(final WorldpayServiceGateway gateway, final MerchantInfo merchantInfo, final String orderCode) throws WorldpayException { - final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, orderCode, new Amount("100", "EUR", "2"), null, null); + final Amount amount = new Amount(); + amount.setValue("100"); + amount.setCurrencyCode(EUR); + amount.setExponent(EXPONENT); + final CaptureServiceRequest request = CaptureServiceRequest.createCaptureRequest(merchantInfo, orderCode, amount, null, null); return gateway.capture(request); } + + private static Address createAddress() { + final Address address = new Address(); + address.setFirstName(NAME); + address.setLastName(SHOPPER); + address.setAddress1(SHOPPER_ADDRESS_1); + address.setAddress2(SHOPPER_ADDRESS_2); + address.setAddress3(SHOPPER_ADDRESS_3); + address.setPostalCode(POSTAL_CODE); + address.setCity(CITY); + address.setCountryCode(GB); + + return address; + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/hop/impl/DefaultWorldpayHOPServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/hop/impl/DefaultWorldpayHOPServiceTest.java index 54e22647..6631c23d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/hop/impl/DefaultWorldpayHOPServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/hop/impl/DefaultWorldpayHOPServiceTest.java @@ -6,9 +6,9 @@ import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.service.WorldpayServiceGateway; import com.worldpay.service.WorldpayUrlService; -import com.worldpay.service.model.ErrorDetail; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.RedirectReference; +import com.worldpay.data.ErrorDetail; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.RedirectReference; import com.worldpay.service.payment.request.WorldpayRequestFactory; import com.worldpay.service.request.RedirectAuthoriseServiceRequest; import com.worldpay.service.response.RedirectAuthoriseServiceResponse; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/http/impl/DefaultWorldpayConnectorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/http/impl/DefaultWorldpayConnectorTest.java index e39be33e..a0477af5 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/http/impl/DefaultWorldpayConnectorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/http/impl/DefaultWorldpayConnectorTest.java @@ -4,7 +4,7 @@ import com.worldpay.exception.WorldpayException; import com.worldpay.internal.model.PaymentService; import com.worldpay.service.marshalling.PaymentServiceMarshaller; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.config.ConfigurationService; import org.apache.commons.io.IOUtils; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/impl/DefaultWorldpayAuthorisationResultServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/impl/DefaultWorldpayAuthorisationResultServiceTest.java index a9a1cc54..d23cc443 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/impl/DefaultWorldpayAuthorisationResultServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/impl/DefaultWorldpayAuthorisationResultServiceTest.java @@ -1,7 +1,7 @@ package com.worldpay.service.impl; import com.worldpay.commands.WorldpaySubscriptionAuthorizeResult; -import com.worldpay.service.model.RedirectReference; +import com.worldpay.data.RedirectReference; import com.worldpay.service.response.DirectAuthoriseServiceResponse; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.payment.commands.result.AbstractResult; @@ -81,5 +81,5 @@ public void testSetAuthorizeResultForAPM() { verify(worldpaySubscriptionAuthorizeResultMock).setPaymentRedirectUrl(REDIRECT_REFERENCE); } } - + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/impl/DefaultWorldpayUrlServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/impl/DefaultWorldpayUrlServiceTest.java index 4ba0159f..08f608c7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/impl/DefaultWorldpayUrlServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/impl/DefaultWorldpayUrlServiceTest.java @@ -1,17 +1,21 @@ package com.worldpay.service.impl; import com.worldpay.exception.WorldpayConfigurationException; +import com.worldpay.model.WorldpayThreeDS2JsonWebTokenConfigurationModel; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.acceleratorservices.urlresolver.SiteBaseUrlResolutionService; import de.hybris.platform.basecommerce.model.site.BaseSiteModel; import de.hybris.platform.site.BaseSiteService; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; @@ -34,22 +38,29 @@ public class DefaultWorldpayUrlServiceTest { private BaseSiteService baseSiteServiceMock; @Mock private SiteBaseUrlResolutionService siteBaseUrlResolutionServiceMock; - @Mock + @Mock(answer = Answers.RETURNS_DEEP_STUBS) private BaseSiteModel currentBaseSiteMock; + @Mock + private WorldpayThreeDS2JsonWebTokenConfigurationModel threeDSFlexSettingsMock; - @Test - public void testGetFullUrlSecure() throws Exception { + @Before + public void setUp() { when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(currentBaseSiteMock); when(siteBaseUrlResolutionServiceMock.getWebsiteUrlForSite(currentBaseSiteMock, true, URL)).thenReturn(FULL_SITE_URL); + when(currentBaseSiteMock.getWebMerchantConfiguration().getThreeDSFlexJsonWebTokenSettings()).thenReturn(threeDSFlexSettingsMock); + when(threeDSFlexSettingsMock.getAuthSubmit()).thenReturn(AUTOSUBMIT_URL); + when(threeDSFlexSettingsMock.getFlowReturnUrl()).thenReturn("threeDFlexPath"); + } + @Test + public void getFullUrl_WhenSecure_ShouldReturnSecureFullSiteURL() throws Exception { final String result = testObj.getFullUrl(URL, true); assertEquals(FULL_SITE_URL, result); } @Test - public void testGetFullUrlUnSecure() throws Exception { - when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(currentBaseSiteMock); + public void getFullUrl_WhenUnSecure_ShouldReturnUnSecureFullSiteURL() throws Exception { when(siteBaseUrlResolutionServiceMock.getWebsiteUrlForSite(currentBaseSiteMock, false, URL)).thenReturn(FULL_SITE_URL); final String result = testObj.getFullUrl(URL, false); @@ -58,8 +69,7 @@ public void testGetFullUrlUnSecure() throws Exception { } @Test - public void shouldReturnBaseURLForCurrentSite() throws Exception { - when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(currentBaseSiteMock); + public void getBaseWebsiteUrlForSite_ShouldReturnBaseURLForCurrentSite() throws Exception { when(siteBaseUrlResolutionServiceMock.getWebsiteUrlForSite(currentBaseSiteMock, true, EMPTY_URL)).thenReturn(FULL_SITE_URL); final String result = testObj.getBaseWebsiteUrlForSite(); @@ -68,8 +78,7 @@ public void shouldReturnBaseURLForCurrentSite() throws Exception { } @Test - public void shouldReturnFullTermsUrl() throws Exception { - when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(currentBaseSiteMock); + public void getFullTermsUrl_ShouldReturnFullTermsUrl() throws Exception { doReturn(TERMS_URL).when(testObj).getTermsPath(); when(siteBaseUrlResolutionServiceMock.getWebsiteUrlForSite(currentBaseSiteMock, true, TERMS_URL)).thenReturn(FULL_SITE_URL); @@ -79,16 +88,14 @@ public void shouldReturnFullTermsUrl() throws Exception { } @Test(expected = WorldpayConfigurationException.class) - public void testGetFullUrlShouldRaiseExceptionWhenServiceReturnsNull() throws Exception { - when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(currentBaseSiteMock); + public void getFullUrl_WhenServiceReturnsNull_ShouldThrowException() throws Exception { when(siteBaseUrlResolutionServiceMock.getWebsiteUrlForSite(currentBaseSiteMock, true, URL)).thenReturn(null); testObj.getFullUrl(URL, true); } @Test - public void testSetOfAddresses() throws WorldpayConfigurationException { - when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(currentBaseSiteMock); + public void getFullCancelURL_ShouldReturnCorrectURLs() throws WorldpayConfigurationException { // Returns the 3rd argument of the invocation, the Url passed in the getFullUrl invocation when(siteBaseUrlResolutionServiceMock.getWebsiteUrlForSite(eq(currentBaseSiteMock), eq(true), anyString())).thenAnswer(invocationOnMOck -> { final Object[] args = invocationOnMOck.getArguments(); @@ -115,22 +122,22 @@ public void testSetOfAddresses() throws WorldpayConfigurationException { testObj.getFullThreeDSecureTermURL(); verify(testObj).getFullUrl("threeDPath", true); - doReturn("threeDFlexPath").when(testObj).getThreeDSecureFlexFlowReturnUrl(); - final String result = testObj.getFullThreeDSecureFlexFlowReturnUrl(); + testObj.getFullThreeDSecureFlexFlowReturnUrl(); verify(testObj).getFullUrl("threeDFlexPath", true); } @Test - public void testReturnCurrentBaseSiteDomain() { - when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(currentBaseSiteMock); + public void getWebsiteUrlForCurrentSite_ShuldReturnSiteURL() { when(siteBaseUrlResolutionServiceMock.getWebsiteUrlForSite(currentBaseSiteMock, true, null)).thenReturn(URL); - testObj.getWebsiteUrlForCurrentSite(); + + final String result = testObj.getWebsiteUrlForCurrentSite(); + + assertThat(result).isEqualTo(URL); } @Test - public void testGetFullThreeDSecureFlexFlowReturnUrl() throws Exception { - when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(currentBaseSiteMock); - doReturn(THREED_SECURE_FLEX_URL).when(testObj).getThreeDSecureFlexFlowReturnUrl(); + public void getFullThreeDSecureFlexFlowReturnUrl_ShouldReturnFullFlexFlowURL() throws Exception { + when(threeDSFlexSettingsMock.getFlowReturnUrl()).thenReturn(THREED_SECURE_FLEX_URL); when(siteBaseUrlResolutionServiceMock.getWebsiteUrlForSite(currentBaseSiteMock, true, THREED_SECURE_FLEX_URL)).thenReturn(FULL_SITE_URL + THREED_SECURE_FLEX_URL); final String result = testObj.getFullThreeDSecureFlexFlowReturnUrl(); @@ -139,9 +146,7 @@ public void testGetFullThreeDSecureFlexFlowReturnUrl() throws Exception { } @Test - public void testGetFullThreeDSecureFlexAutosubmitUrl() throws Exception { - when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(currentBaseSiteMock); - doReturn(AUTOSUBMIT_URL).when(testObj).getThreeDSecureFlexAuthSubmit(); + public void getFullThreeDSecureFlexAutosubmitUrl_ShouldReturnFullFlexAutoSubmitURL() throws Exception { when(siteBaseUrlResolutionServiceMock.getWebsiteUrlForSite(currentBaseSiteMock, true, AUTOSUBMIT_URL)).thenReturn(FULL_SITE_URL + AUTOSUBMIT_URL); final String result = testObj.getFullThreeDSecureFlexAutosubmitUrl(); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/AddressTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/AddressTest.java deleted file mode 100644 index db11391f..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/AddressTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.internal.model.*; -import de.hybris.bootstrap.annotations.UnitTest; -import org.hamcrest.CoreMatchers; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; -import static org.hamcrest.core.IsCollectionContaining.hasItems; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; - -@UnitTest -public class AddressTest { - - private static final String STATE = "State"; - private static final String FIRST_NAME = "FirstName"; - private static final String LAST_NAME = "LastName"; - private static final String STREET = "Street"; - private static final String HOUSE_NAME = "HouseName"; - private static final String HOUSE_NUMBER_EXTENSION = "HouseNumberExtension"; - private static final String ADDRESS_1 = "Address1"; - private static final String ADDRESS_2 = "Address2"; - private static final String ADDRESS_3 = "Address3"; - private static final String POSTAL_CODE = "PostalCode"; - private static final String CITY = "City"; - private static final String COUNTRY_CODE = "CountryCode"; - private static final String TELEPHONE_NUMBER = "TelephoneNumber"; - private static final String VALUE = "value"; - private static final String HOUSE_NUMBER = "houseNumber"; - private Address testObj = new Address(); - - @Test - public void testTransformToInternalModel() throws Exception { - testObj.setState(STATE); - testObj.setFirstName(FIRST_NAME); - testObj.setLastName(LAST_NAME); - testObj.setStreet(STREET); - testObj.setHouseName(HOUSE_NAME); - testObj.setHouseNumberExtension(HOUSE_NUMBER_EXTENSION); - testObj.setAddress1(ADDRESS_1); - testObj.setAddress2(ADDRESS_2); - testObj.setAddress3(ADDRESS_3); - testObj.setPostalCode(POSTAL_CODE); - testObj.setCity(CITY); - testObj.setCountryCode(COUNTRY_CODE); - testObj.setTelephoneNumber(TELEPHONE_NUMBER); - testObj.setHouseNumber(HOUSE_NUMBER); - - final com.worldpay.internal.model.Address result = (com.worldpay.internal.model.Address) testObj.transformToInternalModel(); - - assertEquals(STATE, result.getState()); - assertEquals(FIRST_NAME, result.getFirstName()); - assertEquals(LAST_NAME, result.getLastName()); - final List addressDetails = result.getStreetOrHouseNameOrHouseNumberOrHouseNumberExtensionOrAddress1OrAddress2OrAddress3(); - - assertThat(addressDetails, hasItems(instanceOf(Street.class), instanceOf(HouseName.class), CoreMatchers.instanceOf(HouseNumber.class), instanceOf(HouseNumberExtension.class), instanceOf(Address1.class), instanceOf(Address2.class), instanceOf(Address3.class))); - assertThat(addressDetails, hasItems(hasProperty(VALUE, is(STREET)), hasProperty(VALUE, is(HOUSE_NAME)), hasProperty(VALUE,is(HOUSE_NUMBER)), hasProperty(VALUE, is(HOUSE_NUMBER_EXTENSION)), hasProperty(VALUE, is(ADDRESS_1)), hasProperty(VALUE, is(ADDRESS_2)), hasProperty(VALUE, is(ADDRESS_3)))); - - assertEquals(POSTAL_CODE, result.getPostalCode()); - assertEquals(CITY, result.getCity()); - assertEquals(COUNTRY_CODE, result.getCountryCode()); - assertEquals(TELEPHONE_NUMBER, result.getTelephoneNumber()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/AmountTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/AmountTest.java deleted file mode 100644 index 81a83d38..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/AmountTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.internal.helper.InternalModelObject; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@UnitTest -public class AmountTest { - - private static final String VALUE = "value"; - private static final String CURRENCY_CODE = "currencyCode"; - private static final String EXPONENT = "exponent"; - private static final DebitCreditIndicator DEBIT_CREDIT_INDICATOR = DebitCreditIndicator.DEBIT; - - @Test - public void shouldReturnAnAmount() { - final Amount amount = new Amount(null, null, null); - - final InternalModelObject result = amount.transformToInternalModel(); - - assertTrue(result instanceof com.worldpay.internal.model.Amount); - } - - @Test - public void shouldSetValueOnAmount() { - final Amount amount = new Amount(VALUE, null, null); - - final com.worldpay.internal.model.Amount result = (com.worldpay.internal.model.Amount) amount.transformToInternalModel(); - - assertEquals(VALUE, result.getValue()); - } - - @Test - public void shouldSetCurrencyCodeOnAmount() { - final Amount amount = new Amount(null, CURRENCY_CODE, null); - - final com.worldpay.internal.model.Amount result = (com.worldpay.internal.model.Amount) amount.transformToInternalModel(); - - assertEquals(CURRENCY_CODE, result.getCurrencyCode()); - } - - @Test - public void shouldSetExponentOnAmount() { - final Amount amount = new Amount(null, null, EXPONENT); - - final com.worldpay.internal.model.Amount result = (com.worldpay.internal.model.Amount) amount.transformToInternalModel(); - - assertEquals(EXPONENT, result.getExponent()); - } - - @Test - public void shouldSetCreditOnAmountIfDebitCreditIndicatorIsNotSupplied() { - final Amount amount = new Amount(null, null, null); - - final com.worldpay.internal.model.Amount result = (com.worldpay.internal.model.Amount) amount.transformToInternalModel(); - - assertEquals(DebitCreditIndicator.CREDIT.getCode(), result.getDebitCreditIndicator()); - } - - @Test - public void shouldSetDebitCreditIndicatorOnAmount() { - final Amount amount = new Amount(null, null, null, DEBIT_CREDIT_INDICATOR); - - final com.worldpay.internal.model.Amount result = (com.worldpay.internal.model.Amount) amount.transformToInternalModel(); - - assertEquals(DEBIT_CREDIT_INDICATOR.getCode(), result.getDebitCreditIndicator()); - } - - @Test - public void shouldSetCreditOnAmountIfDebitCreditIndicatorIsNull() { - final Amount amount = new Amount(null, null, null, null); - - final com.worldpay.internal.model.Amount result = (com.worldpay.internal.model.Amount) amount.transformToInternalModel(); - - // We're actually testing, that the getter of debitCreditIndicator defaults to CREDIT... - assertEquals(DebitCreditIndicator.CREDIT.getCode(), result.getDebitCreditIndicator()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/BrowserTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/BrowserTest.java deleted file mode 100644 index 0bf123ba..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/BrowserTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.exception.WorldpayModelTransformationException; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@UnitTest -public class BrowserTest { - - private static final String HEADER = "header"; - private static final String USER_AGENT_HEADER = "user_agent_header"; - private static final String DEVICE_TYPE = "deviceType"; - private static final String DEVICE_OS = "deviceOS"; - private static final String HTTP_REFERER = "httpReferer"; - private static final String HTTP_ACCEPT_LANGUAGE = "httpAcceptLanguage"; - - @Test - public void shouldReturnAnInternalBrowser() throws WorldpayModelTransformationException { - final Browser testObj = new Browser(null, null, null, null, null, null); - - final com.worldpay.internal.model.Browser result = (com.worldpay.internal.model.Browser) testObj.transformToInternalModel(); - - assertTrue(result instanceof com.worldpay.internal.model.Browser); - } - - @Test - public void shouldSetAcceptHeaderOnInternalBrowser() throws WorldpayModelTransformationException { - final Browser testObj = new Browser(HEADER, null, null, null, null, null); - - final com.worldpay.internal.model.Browser result = (com.worldpay.internal.model.Browser) testObj.transformToInternalModel(); - - assertEquals(HEADER, result.getAcceptHeader()); - } - - - @Test - public void shouldSetUserAgentHeaderOnInternalBrowser() throws WorldpayModelTransformationException { - final Browser testObj = new Browser(null, USER_AGENT_HEADER, null, null, null, null); - - final com.worldpay.internal.model.Browser result = (com.worldpay.internal.model.Browser) testObj.transformToInternalModel(); - - assertEquals(USER_AGENT_HEADER, result.getUserAgentHeader()); - } - - @Test - public void shouldSetDeviceTypeOnInternalBrowser() throws WorldpayModelTransformationException { - final Browser testObj = new Browser(null, null, DEVICE_TYPE, null, null, null); - - final com.worldpay.internal.model.Browser result = (com.worldpay.internal.model.Browser) testObj.transformToInternalModel(); - - assertEquals(DEVICE_TYPE, result.getDeviceType()); - } - - @Test - public void shouldSetDeviceOsOnInternalBrowser() throws WorldpayModelTransformationException { - final Browser testObj = new Browser(null, null, null, DEVICE_OS, null, null); - - final com.worldpay.internal.model.Browser result = (com.worldpay.internal.model.Browser) testObj.transformToInternalModel(); - - assertEquals(DEVICE_OS, result.getDeviceOS()); - } - - @Test - public void shouldSetHttpAcceptLanguageOnInternalBrowser() throws WorldpayModelTransformationException { - final Browser testObj = new Browser(null, null, null, null, HTTP_ACCEPT_LANGUAGE, null); - - final com.worldpay.internal.model.Browser result = (com.worldpay.internal.model.Browser) testObj.transformToInternalModel(); - - assertEquals(HTTP_ACCEPT_LANGUAGE, result.getHttpAcceptLanguage()); - } - - @Test - public void shouldSetHttpRefererOnInternalBrowser() throws WorldpayModelTransformationException { - final Browser testObj = new Browser(null, null, null, null, null, HTTP_REFERER); - - final com.worldpay.internal.model.Browser result = (com.worldpay.internal.model.Browser) testObj.transformToInternalModel(); - - assertEquals(HTTP_REFERER, result.getHttpReferer()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/DateTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/DateTest.java deleted file mode 100644 index b2b7df32..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/DateTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.worldpay.service.model; - -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; - -import java.time.LocalDateTime; - -import static org.assertj.core.api.Assertions.assertThat; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class DateTest { - - private Date testObj; - - @Test - public void transformToInternalModel_ShouldReturnInternalDate_WhenUsingFullMembersConstructor() { - testObj = new Date("15", "5", "2020", "12", "30", "35"); - - final com.worldpay.internal.model.Date result = testObj.transformToInternalModel(); - - assertThat(result.getDayOfMonth()).isEqualTo("15"); - assertThat(result.getMonth()).isEqualTo("5"); - assertThat(result.getYear()).isEqualTo("2020"); - assertThat(result.getHour()).isEqualTo("12"); - assertThat(result.getMinute()).isEqualTo("30"); - assertThat(result.getSecond()).isEqualTo("35"); - } - - @Test - public void transformToInternalModel_ShouldReturnInternalDate_WhenLocalDateTimeConstructor() { - testObj = new Date(LocalDateTime.of(2020, 5, 15, 12, 30, 35)); - - final com.worldpay.internal.model.Date result = testObj.transformToInternalModel(); - - assertThat(result.getDayOfMonth()).isEqualTo("15"); - assertThat(result.getMonth()).isEqualTo("5"); - assertThat(result.getYear()).isEqualTo("2020"); - assertThat(result.getHour()).isEqualTo("12"); - assertThat(result.getMinute()).isEqualTo("30"); - assertThat(result.getSecond()).isEqualTo("35"); - } - - @Test - public void transformToInternalModel_ShouldReturnInternalDate_WhenUsingMonthAndYearConstructor() { - testObj = new Date("5", "2020"); - - final com.worldpay.internal.model.Date result = testObj.transformToInternalModel(); - - assertThat(result.getDayOfMonth()).isNullOrEmpty(); - assertThat(result.getMonth()).isEqualTo("5"); - assertThat(result.getYear()).isEqualTo("2020"); - assertThat(result.getHour()).isNullOrEmpty(); - assertThat(result.getMinute()).isNullOrEmpty(); - assertThat(result.getSecond()).isNullOrEmpty(); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/OrderTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/OrderTest.java deleted file mode 100644 index 7047fbbc..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/OrderTest.java +++ /dev/null @@ -1,507 +0,0 @@ -package com.worldpay.service.model; - -import com.worldpay.enums.order.DynamicInteractionType; -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.Description; -import com.worldpay.internal.model.Info3DSecure; -import com.worldpay.internal.model.PaResponse; -import com.worldpay.service.model.payment.PayAsOrder; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.threeds2.RiskData; -import com.worldpay.service.model.threeds2.TransactionRiskData; -import com.worldpay.service.model.threeds2.TransactionRiskDataGiftCardAmount; -import com.worldpay.service.model.token.TokenRequest; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class OrderTest { - - private Order order; - - @Mock - private Shopper shopperMock; - @Mock - private Amount amountMock; - @Mock - private com.worldpay.internal.model.Shopper intShopperMock; - @Mock - private Address shippingAddressMock, billingAddressMock; - @Mock - private com.worldpay.internal.model.Address intShippingAddressMock, intBillingAddressMock; - @Mock - private PaymentMethodAttribute paymentMethodAttributeMock1, paymentMethodAttributeMock2; - @Mock - private com.worldpay.internal.model.PaymentMethodAttribute intPaymentMethodAttributeMock1, intPaymentMethodAttributeMock2; - @Mock - private TokenRequest tokenRequestMock; - @Mock - private com.worldpay.internal.model.CreateToken createTokenMock; - @Mock - private Session sessionMock; - @Mock - private com.worldpay.internal.model.Session intSessionMock; - @Mock - private OrderLines orderLinesMock; - @Mock - private com.worldpay.internal.model.OrderLines intOrderLinesMock; - @Mock - private PaymentMethodMask paymentMethodMaskMock; - @Mock - private com.worldpay.internal.model.PaymentMethodMask intPaymentMethodMaskMock; - @Mock - private PaymentDetails paymentDetailsMock; - @Mock - private com.worldpay.internal.model.PaymentDetails intPaymentDetailsMock; - @Mock - private PayAsOrder payAsOrderMock; - @Mock - private com.worldpay.internal.model.PayAsOrder intPayAsOrderMock; - @Mock - private Additional3DSData additional3DSDataMock; - @Mock - private RiskData riskDataMock; - @Mock - private TransactionRiskData transactionRiskDataMock; - @Mock - private TransactionRiskDataGiftCardAmount transactionRiskDataGiftCardAmountMock; - @Mock - private com.worldpay.internal.model.Amount intAmountMock; - @Mock - private com.worldpay.internal.model.Additional3DSData intAdditional3DSDataMock; - - @Before - public void setUp() throws Exception { - order = new Order("orderCode", "description", amountMock); - - when(amountMock.transformToInternalModel()).thenReturn(intAmountMock); - when(shopperMock.transformToInternalModel()).thenReturn(intShopperMock); - when(shippingAddressMock.transformToInternalModel()).thenReturn(intShippingAddressMock); - when(billingAddressMock.transformToInternalModel()).thenReturn(intBillingAddressMock); - when(paymentMethodAttributeMock1.transformToInternalModel()).thenReturn(intPaymentMethodAttributeMock1); - when(paymentMethodAttributeMock2.transformToInternalModel()).thenReturn(intPaymentMethodAttributeMock2); - when(tokenRequestMock.transformToInternalModel()).thenReturn(createTokenMock); - when(sessionMock.transformToInternalModel()).thenReturn(intSessionMock); - when(orderLinesMock.transformToInternalModel()).thenReturn(intOrderLinesMock); - when(paymentMethodMaskMock.transformToInternalModel()).thenReturn(intPaymentMethodMaskMock); - when(paymentDetailsMock.transformToInternalModel()).thenReturn(intPaymentDetailsMock); - when(payAsOrderMock.transformToInternalModel()).thenReturn(intPayAsOrderMock); - when(additional3DSDataMock.transformToInternalModel()).thenReturn(intAdditional3DSDataMock); - } - - @Test - public void transformToInternalModel_shouldSetOrderCodeDescriptionAndAmount() throws WorldpayModelTransformationException { - final var result = order.transformToInternalModel(); - - assertThat(result.getOrderCode()).isEqualTo("orderCode"); - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - - final Description intDescription = orderChildElements.stream().filter(Description.class::isInstance).map(Description.class::cast).findAny().orElseThrow(); - assertThat(intDescription.getvalue()).isEqualTo("description"); - - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.Amount.class::isInstance).map(com.worldpay.internal.model.Amount.class::cast).collect(Collectors.toList())).hasSize(1); - final var intAmount = orderChildElements.stream().filter(com.worldpay.internal.model.Amount.class::isInstance).map(com.worldpay.internal.model.Amount.class::cast).findAny().orElseThrow(); - assertThat(intAmount).isEqualTo(intAmountMock); - } - - @Test - public void transformToInternalModel_shouldSetInstallationId() throws WorldpayModelTransformationException { - order.setInstallationId("installationId"); - final var result = order.transformToInternalModel(); - - assertThat(result.getInstallationId()).isEqualToIgnoringCase("installationId"); - } - - @Test - public void transformToInternalModel_shouldNotSetInstallationId_WhenEmpty() throws WorldpayModelTransformationException { - order.setInstallationId(null); - - final var result = order.transformToInternalModel(); - - assertThat(result.getInstallationId()).isNullOrEmpty(); - } - - @Test - public void transformToInternalModel_shouldSetOrderContent() throws WorldpayModelTransformationException { - order.setOrderContent("orderContent"); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.OrderContent.class::isInstance).map(com.worldpay.internal.model.OrderContent.class::cast).collect(Collectors.toList())).hasSize(1); - final var intOrderContent = orderChildElements.stream().filter(com.worldpay.internal.model.OrderContent.class::isInstance).map(com.worldpay.internal.model.OrderContent.class::cast).findAny().orElseThrow(); - assertThat(intOrderContent.getvalue()).isEqualToIgnoringCase("orderContent"); - } - - @Test - public void transformToInternalModel_shouldNotSetOrderContent_WhenEmpty() throws WorldpayModelTransformationException { - order.setOrderContent(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyOrderContent = orderChildElements.stream().noneMatch(com.worldpay.internal.model.OrderContent.class::isInstance); - assertThat(emptyOrderContent).isTrue(); - } - - @Test - public void transformToInternalModel_shouldSetShopper() throws WorldpayModelTransformationException { - order.setShopper(shopperMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.Shopper.class::isInstance).map(com.worldpay.internal.model.Shopper.class::cast).collect(Collectors.toList())).hasSize(1); - final var intShopper = orderChildElements.stream().filter(com.worldpay.internal.model.Shopper.class::isInstance).map(com.worldpay.internal.model.Shopper.class::cast).findAny().orElseThrow(); - assertThat(intShopper).isEqualTo(intShopperMock); - } - - @Test - public void transformToInternalModel_shouldNotSetShopper_WhenEmpty() throws WorldpayModelTransformationException { - order.setShopper(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyShopper = orderChildElements.stream().noneMatch(com.worldpay.internal.model.Shopper.class::isInstance); - assertThat(emptyShopper).isTrue(); - } - - @Test - public void transformToInternalModel_shouldSetShippingAddress() throws WorldpayModelTransformationException { - order.setShippingAddress(shippingAddressMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.ShippingAddress.class::isInstance).map(com.worldpay.internal.model.ShippingAddress.class::cast).collect(Collectors.toList())).hasSize(1); - final var intShippingAddress = orderChildElements.stream().filter(com.worldpay.internal.model.ShippingAddress.class::isInstance).map(com.worldpay.internal.model.ShippingAddress.class::cast).findAny().orElseThrow(); - assertThat(intShippingAddress.getAddress()).isEqualTo(intShippingAddressMock); - } - - - @Test - public void transformToInternalModel_shouldNotSetShippingAddress_WhenEmpty() throws WorldpayModelTransformationException { - order.setShippingAddress(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyShippingAddress = orderChildElements.stream().noneMatch(com.worldpay.internal.model.ShippingAddress.class::isInstance); - assertThat(emptyShippingAddress).isTrue(); - } - - @Test - public void transformToInternalModel_shouldSetBillingAddress() throws WorldpayModelTransformationException { - order.setBillingAddress(billingAddressMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.BillingAddress.class::isInstance).map(com.worldpay.internal.model.BillingAddress.class::cast).collect(Collectors.toList())).hasSize(1); - final var intBillingAddress = orderChildElements.stream().filter(com.worldpay.internal.model.BillingAddress.class::isInstance).map(com.worldpay.internal.model.BillingAddress.class::cast).findAny().orElseThrow(); - assertThat(intBillingAddress.getAddress()).isEqualTo(intBillingAddressMock); - } - - @Test - public void transformToInternalModel_shouldNotSetBillingAddress_WhenEmpty() throws WorldpayModelTransformationException { - order.setBillingAddress(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyBillingAddress = orderChildElements.stream().noneMatch(com.worldpay.internal.model.BillingAddress.class::isInstance); - assertThat(emptyBillingAddress).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddPaymentMethodAttributes() throws WorldpayModelTransformationException { - order.setPaymentMethodAttributes(List.of(paymentMethodAttributeMock1, paymentMethodAttributeMock2)); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.PaymentMethodAttribute.class::isInstance).map(com.worldpay.internal.model.PaymentMethodAttribute.class::cast).collect(Collectors.toList())).hasSize(2); - final var intPaymentMethodAttributes = orderChildElements.stream().filter(com.worldpay.internal.model.PaymentMethodAttribute.class::isInstance).map(com.worldpay.internal.model.PaymentMethodAttribute.class::cast).collect(Collectors.toList()); - assertThat(intPaymentMethodAttributes).containsOnly(intPaymentMethodAttributeMock1, intPaymentMethodAttributeMock2); - } - - @Test - public void transformToInternalModel_shouldNotPaymentMethodAttributes_WhenEmpty() throws WorldpayModelTransformationException { - order.setPaymentMethodAttributes(Collections.emptyList()); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyPaymentMethodAttributes = orderChildElements.stream().noneMatch(com.worldpay.internal.model.PaymentMethodAttribute.class::isInstance); - assertThat(emptyPaymentMethodAttributes).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddStatementNarrative() throws WorldpayModelTransformationException { - order.setStatementNarrative("statementNarrative"); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.StatementNarrative.class::isInstance).map(com.worldpay.internal.model.StatementNarrative.class::cast).collect(Collectors.toList())).hasSize(1); - final var intStatementNarrative = orderChildElements.stream().filter(com.worldpay.internal.model.StatementNarrative.class::isInstance).map(com.worldpay.internal.model.StatementNarrative.class::cast).findAny().orElseThrow(); - assertThat(intStatementNarrative.getvalue()).isEqualToIgnoringCase("statementNarrative"); - } - - @Test - public void transformToInternalModel_shouldNotAddStatementNarrative_WhenEmpty() throws WorldpayModelTransformationException { - order.setStatementNarrative(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyStatementNarrative = orderChildElements.stream().noneMatch(com.worldpay.internal.model.StatementNarrative.class::isInstance); - assertThat(emptyStatementNarrative).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddEchoData() throws WorldpayModelTransformationException { - order.setEchoData("echoData"); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.EchoData.class::isInstance).map(com.worldpay.internal.model.EchoData.class::cast).collect(Collectors.toList())).hasSize(1); - final var intEchoData = orderChildElements.stream().filter(com.worldpay.internal.model.EchoData.class::isInstance).map(com.worldpay.internal.model.EchoData.class::cast).findAny().orElseThrow(); - assertThat(intEchoData.getvalue()).isEqualToIgnoringCase("echoData"); - } - - @Test - public void transformToInternalModel_shouldNotAddEchoData_WhenEmpty() throws WorldpayModelTransformationException { - order.setEchoData(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emtpyEchoData = orderChildElements.stream().noneMatch(com.worldpay.internal.model.EchoData.class::isInstance); - assertThat(emtpyEchoData).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddCreateTokenRequest() throws WorldpayModelTransformationException { - order.setTokenRequest(tokenRequestMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.CreateToken.class::isInstance).map(com.worldpay.internal.model.CreateToken.class::cast).collect(Collectors.toList())).hasSize(1); - final var intCreateToken = orderChildElements.stream().filter(com.worldpay.internal.model.CreateToken.class::isInstance).map(com.worldpay.internal.model.CreateToken.class::cast).findAny().orElseThrow(); - assertThat(intCreateToken).isEqualTo(createTokenMock); - } - - @Test - public void transformToInternalModel_shouldNotAddCreateTokenRequest_WhenEmpty() throws WorldpayModelTransformationException { - order.setTokenRequest(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyCreateToken = orderChildElements.stream().noneMatch(com.worldpay.internal.model.CreateToken.class::isInstance); - assertThat(emptyCreateToken).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddPaResponseInsideInfo3dSecure() throws WorldpayModelTransformationException { - order.setPaResponse("paResponse"); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.Info3DSecure.class::isInstance).map(com.worldpay.internal.model.Info3DSecure.class::cast).collect(Collectors.toList())).hasSize(1); - final var intInfo3DSecure = orderChildElements.stream().filter(com.worldpay.internal.model.Info3DSecure.class::isInstance).map(com.worldpay.internal.model.Info3DSecure.class::cast).findAny().orElseThrow(); - final var threeDSecureInfoChildElements = intInfo3DSecure.getPaResponseOrMpiProviderOrMpiResponseOrAttemptedAuthenticationOrCompletedAuthenticationOrThreeDSVersionOrMerchantNameOrXidOrDsTransactionIdOrCavvOrEci(); - assertThat(threeDSecureInfoChildElements.stream().filter(com.worldpay.internal.model.PaResponse.class::isInstance).map(com.worldpay.internal.model.PaResponse.class::cast).collect(Collectors.toList())).hasSize(1); - final PaResponse paResponse = threeDSecureInfoChildElements.stream().filter(PaResponse.class::isInstance).map(PaResponse.class::cast).findAny().orElseThrow(); - assertThat(paResponse.getvalue()).isEqualTo("paResponse"); - } - - @Test - public void transformToInternalModel_shouldNotAddPaResponseInsideInfo3dSecure_WhenEmpty() throws WorldpayModelTransformationException { - order.setPaResponse(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyInfo3DSecure = orderChildElements.stream().noneMatch(Info3DSecure.class::isInstance); - assertThat(emptyInfo3DSecure).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddSession() throws WorldpayModelTransformationException { - order.setSession(sessionMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.Session.class::isInstance).map(com.worldpay.internal.model.Session.class::cast).collect(Collectors.toList())).hasSize(1); - final var intSession = orderChildElements.stream().filter(com.worldpay.internal.model.Session.class::isInstance).map(com.worldpay.internal.model.Session.class::cast).findAny().orElseThrow(); - assertThat(intSession).isEqualTo(intSessionMock); - } - - @Test - public void transformToInternalModel_shouldNotAddSession_WhenEmpty() throws WorldpayModelTransformationException { - order.setSession(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptySession = orderChildElements.stream().noneMatch(com.worldpay.internal.model.Session.class::isInstance); - assertThat(emptySession).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddOrderLines() throws WorldpayModelTransformationException { - order.setOrderLines(orderLinesMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.OrderLines.class::isInstance).map(com.worldpay.internal.model.OrderLines.class::cast).collect(Collectors.toList())).hasSize(1); - final var intOrderLines = orderChildElements.stream().filter(com.worldpay.internal.model.OrderLines.class::isInstance).map(com.worldpay.internal.model.OrderLines.class::cast).findAny().orElseThrow(); - assertThat(intOrderLines).isEqualTo(intOrderLinesMock); - } - - @Test - public void transformToInternalModel_shouldNotAddOrderLines_WhenEmpty() throws WorldpayModelTransformationException { - order.setOrderLines(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyOrderLines = orderChildElements.stream().noneMatch(com.worldpay.internal.model.OrderLines.class::isInstance); - assertThat(emptyOrderLines).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddDynamicInteractionType() throws WorldpayModelTransformationException { - order.setDynamicInteractionType(DynamicInteractionType.ECOMMERCE); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.DynamicInteractionType.class::isInstance).map(com.worldpay.internal.model.DynamicInteractionType.class::cast).collect(Collectors.toList())).hasSize(1); - final var dynamicInteractionType = orderChildElements.stream().filter(com.worldpay.internal.model.DynamicInteractionType.class::isInstance).map(com.worldpay.internal.model.DynamicInteractionType.class::cast).findAny().orElseThrow(); - assertThat(dynamicInteractionType.getType()).isEqualTo(DynamicInteractionType.ECOMMERCE.name()); - } - - @Test - public void transformToInternalModel_shouldNotAddDynamicInteractionType_WhenEmpty() throws WorldpayModelTransformationException { - order.setDynamicInteractionType(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyDynamicInteractionType = orderChildElements.stream().noneMatch(com.worldpay.internal.model.DynamicInteractionType.class::isInstance); - assertThat(emptyDynamicInteractionType).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddPaymentMethodMask() throws WorldpayModelTransformationException { - order.setPaymentMethodMask(paymentMethodMaskMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.PaymentMethodMask.class::isInstance).map(com.worldpay.internal.model.PaymentMethodMask.class::cast).collect(Collectors.toList())).hasSize(1); - final var intPaymentMethodMask = orderChildElements.stream().filter(com.worldpay.internal.model.PaymentMethodMask.class::isInstance).map(com.worldpay.internal.model.PaymentMethodMask.class::cast).findAny().orElseThrow(); - assertThat(intPaymentMethodMask).isEqualTo(intPaymentMethodMaskMock); - } - - @Test - public void transformToInternalModel_shouldNotAddPaymentMethodMask_WhenEmpty() throws WorldpayModelTransformationException { - order.setPaymentMethodMask(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyPaymentMethodMask = orderChildElements.stream().noneMatch(com.worldpay.internal.model.PaymentMethodMask.class::isInstance); - assertThat(emptyPaymentMethodMask).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddPaymentDetails() throws WorldpayModelTransformationException { - order.setPaymentDetails(paymentDetailsMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.PaymentDetails.class::isInstance).map(com.worldpay.internal.model.PaymentDetails.class::cast).collect(Collectors.toList())).hasSize(1); - final var intPaymentDetails = orderChildElements.stream().filter(com.worldpay.internal.model.PaymentDetails.class::isInstance).map(com.worldpay.internal.model.PaymentDetails.class::cast).findAny().orElseThrow(); - assertThat(intPaymentDetails).isEqualTo(intPaymentDetailsMock); - } - - @Test - public void transformToInternalModel_shouldNotAddPaymentDetails_WhenEmpty() throws WorldpayModelTransformationException { - order.setPaymentDetails(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyPaymentDetails = orderChildElements.stream().noneMatch(com.worldpay.internal.model.PaymentDetails.class::isInstance); - assertThat(emptyPaymentDetails).isTrue(); - } - - @Test - public void transformToInternalModel_shouldAddPayAsOrder() throws WorldpayModelTransformationException { - order.setPayAsOrder(payAsOrderMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.PayAsOrder.class::isInstance).map(com.worldpay.internal.model.PayAsOrder.class::cast).collect(Collectors.toList())).hasSize(1); - final var intPaymentDetails = orderChildElements.stream().filter(com.worldpay.internal.model.PayAsOrder.class::isInstance).map(com.worldpay.internal.model.PayAsOrder.class::cast).findAny().orElseThrow(); - assertThat(intPaymentDetails).isEqualTo(intPayAsOrderMock); - } - - @Test - public void transformToInternalModel_shouldNotAddPayAsOrder_WhenEmpty() throws WorldpayModelTransformationException { - order.setPayAsOrder(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyPayAsOrder = orderChildElements.stream().noneMatch(com.worldpay.internal.model.PayAsOrder.class::isInstance); - assertThat(emptyPayAsOrder).isTrue(); - } - - @Test - public void transformToInternalModel_shouldPopulateAdditional3DSData() throws WorldpayModelTransformationException { - order.setAdditional3DSData(additional3DSDataMock); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - assertThat(orderChildElements.stream().filter(com.worldpay.internal.model.Additional3DSData.class::isInstance).map(com.worldpay.internal.model.Additional3DSData.class::cast).collect(Collectors.toList())).hasSize(1); - final var intAdditional3DSData = orderChildElements.stream().filter(com.worldpay.internal.model.Additional3DSData.class::isInstance).map(com.worldpay.internal.model.Additional3DSData.class::cast).findAny().orElseThrow(); - assertThat(intAdditional3DSData).isEqualTo(intAdditional3DSDataMock); - } - - @Test - public void transformToInternalModel_shouldNotAddAdditional3DSData_WhenEmpty() throws WorldpayModelTransformationException { - order.setAdditional3DSData(null); - - final var result = order.transformToInternalModel(); - - final var orderChildElements = result.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final boolean emptyAdditional3DSData = orderChildElements.stream().noneMatch(com.worldpay.internal.model.Additional3DSData.class::isInstance); - assertThat(emptyAdditional3DSData).isTrue(); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/PaymentMethodAttributeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/PaymentMethodAttributeTest.java deleted file mode 100644 index 656a220b..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/PaymentMethodAttributeTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.worldpay.service.model; - -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class PaymentMethodAttributeTest { - - private static final String ATTR_NAME = "attrName"; - private static final String ATTR_VALUE = "attrValue"; - private static final String PAYMENT_METHOD = "paymentMethod"; - - @Test - public void populate_shouldSettAttrNameAttrValueAndPaymentMethodName() { - final com.worldpay.service.model.PaymentMethodAttribute paymentMethodAttribute = new com.worldpay.service.model.PaymentMethodAttribute(); - paymentMethodAttribute.setAttrName(ATTR_NAME); - paymentMethodAttribute.setAttrValue(ATTR_VALUE); - paymentMethodAttribute.setPaymentMethod(PAYMENT_METHOD); - - final com.worldpay.internal.model.PaymentMethodAttribute intPaymentMethodAttribute = (com.worldpay.internal.model.PaymentMethodAttribute) paymentMethodAttribute.transformToInternalModel(); - - assertThat(intPaymentMethodAttribute.getAttrName()).isEqualTo(ATTR_NAME); - assertThat(intPaymentMethodAttribute.getAttrValue()).isEqualTo(ATTR_VALUE); - assertThat(intPaymentMethodAttribute.getPaymentMethod()).isEqualTo(PAYMENT_METHOD); - } -} - diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/applepay/ApplePayTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/applepay/ApplePayTest.java deleted file mode 100644 index 83096aab..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/applepay/ApplePayTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.worldpay.service.model.applepay; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.APPLEPAYSSL; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - - -@UnitTest -public class ApplePayTest { - - private static final String VERSION = "version"; - private static final String TOKEN_REQUESTOR_ID = "tokenRequestorID"; - private static final String SIGNATURE = "signature"; - private static final String DATA = "data"; - private static final String EPHEMERAL_PUBLIC_KEY = "ephemeralPublicKey"; - private static final String PUBLIC_KEY_HASH = "publicKeyHash"; - private static final String TRANSACTION_ID = "transactionId"; - private static final String APPLICATION_DATA = "applicationData"; - private static final Header HEADER = new Header(EPHEMERAL_PUBLIC_KEY, PUBLIC_KEY_HASH, TRANSACTION_ID, APPLICATION_DATA); - private ApplePay testObj = new ApplePay(HEADER, SIGNATURE, VERSION, DATA, TOKEN_REQUESTOR_ID); - - @Test - public void shouldSetValuesOnInternalObject() throws WorldpayModelTransformationException { - - final APPLEPAYSSL result = (APPLEPAYSSL) testObj.transformToInternalModel(); - - assertThat(result.getData()).isEqualTo(DATA); - assertThat(result.getHeader().getTransactionId()).isEqualTo(TRANSACTION_ID); - assertThat(result.getHeader().getPublicKeyHash()).isEqualTo(PUBLIC_KEY_HASH); - assertThat(result.getHeader().getEphemeralPublicKey()).isEqualTo(EPHEMERAL_PUBLIC_KEY); - assertThat(result.getHeader().getApplicationData()).isEqualTo(APPLICATION_DATA); - assertThat(result.getSignature()).isEqualTo(SIGNATURE); - assertThat(result.getTokenRequestorID()).isEqualTo(TOKEN_REQUESTOR_ID); - assertThat(result.getVersion()).isEqualTo(VERSION); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/applepay/HeaderTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/applepay/HeaderTest.java deleted file mode 100644 index 32abc4dd..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/applepay/HeaderTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.worldpay.service.model.applepay; - -import com.worldpay.exception.WorldpayModelTransformationException; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -@UnitTest -public class HeaderTest { - - private static final String EPHEMERAL_PUBLIC_KEY = "ephemeralPublicKey"; - private static final String APPLICATION_DATA = "applicationData"; - private static final String TRANSACTION_ID = "transactionId"; - private static final String PUBLIC_KEY_HASH = "publicKeyHash"; - private Header testObj = new Header(EPHEMERAL_PUBLIC_KEY, PUBLIC_KEY_HASH, TRANSACTION_ID, APPLICATION_DATA); - - @Test - public void shouldTransformToInternalModel() throws WorldpayModelTransformationException { - - final com.worldpay.internal.model.Header result = (com.worldpay.internal.model.Header) testObj.transformToInternalModel(); - - assertThat(result.getApplicationData()).isEqualTo(APPLICATION_DATA); - assertThat(result.getEphemeralPublicKey()).isEqualTo(EPHEMERAL_PUBLIC_KEY); - assertThat(result.getPublicKeyHash()).isEqualTo(PUBLIC_KEY_HASH); - assertThat(result.getTransactionId()).isEqualTo(TRANSACTION_ID); - - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/payment/PayWithGoogleSSLTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/payment/PayWithGoogleSSLTest.java deleted file mode 100644 index db0140aa..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/payment/PayWithGoogleSSLTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.PAYWITHGOOGLESSL; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class PayWithGoogleSSLTest { - - private PayWithGoogleSSL testObj = new PayWithGoogleSSL("protocolVersion", "signature", "signedMessage"); - - @Test - public void shouldReturnAPAYWITHGOOGLESSLObjectWithCorrectValuesInMembers() throws WorldpayModelTransformationException { - final PAYWITHGOOGLESSL result = (PAYWITHGOOGLESSL) testObj.transformToInternalModel(); - - assertThat(result.getProtocolVersion()).isEqualTo("protocolVersion"); - assertThat(result.getSignature()).isEqualTo("signature"); - assertThat(result.getSignedMessage()).isEqualTo("signedMessage"); - - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/payment/TokenTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/payment/TokenTest.java deleted file mode 100644 index 1461bc67..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/payment/TokenTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.worldpay.service.model.payment; - -import com.worldpay.internal.model.PaymentInstrument; -import com.worldpay.internal.model.PaymentTokenID; -import com.worldpay.internal.model.TOKENSSL; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.Token; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; - -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; - -@UnitTest -public class TokenTest { - - private static final String PAYMENT_TOKEN_ID = "paymentTokenId"; - private static final String CARD_NUMBER = "cardNumber"; - private static final String SHOPPER = "shopper"; - private static final String MERCHANT = "merchant"; - - @Test - public void shouldReturnTokenSSLWithPaymentTokenIDWithMerchantScope() { - final Token token = new Token(PAYMENT_TOKEN_ID, true); - - final TOKENSSL result = (TOKENSSL) token.transformToInternalModel(); - - final List tokenElements = result.getPaymentTokenIDOrPaymentInstrumentOrCvcOrSession(); - assertThat(tokenElements).hasSize(1); - assertThat(tokenElements.get(0)).isInstanceOf(PaymentTokenID.class); - assertThat(((PaymentTokenID) tokenElements.get(0)).getvalue()).isEqualTo(PAYMENT_TOKEN_ID); - assertEquals(MERCHANT, result.getTokenScope()); - } - - @Test - public void shouldReturnTokenSSLWithPaymentTokenIDWithShopperScope() { - final Token token = new Token(PAYMENT_TOKEN_ID, false); - - final TOKENSSL result = (TOKENSSL) token.transformToInternalModel(); - - final List tokenElements = result.getPaymentTokenIDOrPaymentInstrumentOrCvcOrSession(); - assertThat(tokenElements).hasSize(1); - assertThat(tokenElements.get(0)).isInstanceOf(PaymentTokenID.class); - assertThat(((PaymentTokenID) tokenElements.get(0)).getvalue()).isEqualTo(PAYMENT_TOKEN_ID); - assertEquals(SHOPPER, result.getTokenScope()); - } - - @Test - public void shouldReturnTokenSSLWithPaymentTokenIDAndPaymentInstrumentWithMerchantScope() { - final CardDetails paymentInstrument = new CardDetails(); - paymentInstrument.setCardNumber(CARD_NUMBER); - - final Token token = new Token(PAYMENT_TOKEN_ID, paymentInstrument, true); - - final TOKENSSL result = (TOKENSSL) token.transformToInternalModel(); - - final List tokenElements = result.getPaymentTokenIDOrPaymentInstrumentOrCvcOrSession(); - assertThat(tokenElements).hasSize(2); - assertThat(tokenElements.get(0)).isInstanceOf(PaymentTokenID.class); - assertThat(((PaymentTokenID) tokenElements.get(0)).getvalue()).isEqualTo(PAYMENT_TOKEN_ID); - assertThat(tokenElements.get(1)).isInstanceOf(PaymentInstrument.class); - assertThat((((com.worldpay.internal.model.CardDetails) ((PaymentInstrument) tokenElements.get(1)).getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().get(0))).getDerived().getObfuscatedPAN()).isEqualTo(CARD_NUMBER); - assertEquals(MERCHANT, result.getTokenScope()); - } - - @Test - public void shouldReturnTokenSSLWithPaymentTokenIDAndPaymentInstrumentWithShopperScope() { - final CardDetails paymentInstrument = new CardDetails(); - paymentInstrument.setCardNumber(CARD_NUMBER); - - final Token token = new Token(PAYMENT_TOKEN_ID, paymentInstrument, false); - - final TOKENSSL result = (TOKENSSL) token.transformToInternalModel(); - - final List tokenElements = result.getPaymentTokenIDOrPaymentInstrumentOrCvcOrSession(); - assertThat(tokenElements).hasSize(2); - assertThat(tokenElements.get(0)).isInstanceOf(PaymentTokenID.class); - assertThat(((PaymentTokenID) tokenElements.get(0)).getvalue()).isEqualTo(PAYMENT_TOKEN_ID); - assertThat(tokenElements.get(1)).isInstanceOf(PaymentInstrument.class); - assertThat((((com.worldpay.internal.model.CardDetails) ((PaymentInstrument) tokenElements.get(1)).getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().get(0))).getDerived().getObfuscatedPAN()).isEqualTo(CARD_NUMBER); - assertEquals(SHOPPER, result.getTokenScope()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/Additional3DSDataTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/Additional3DSDataTest.java deleted file mode 100644 index 4eb0cec5..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/Additional3DSDataTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.threedsecureflexenums.ChallengePreferenceEnum; -import com.worldpay.threedsecureflexenums.ChallengeWindowSizeEnum; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class Additional3DSDataTest { - - @Test - public void transformToInternalModelDefaultNoPreferenceAnd390x400() { - final Additional3DSData testObj = new Additional3DSData(); - testObj.setDfReferenceId("referenceId"); - - final var result = (com.worldpay.internal.model.Additional3DSData) testObj.transformToInternalModel(); - - assertThat(result.getDfReferenceId()).isEqualTo("referenceId"); - assertThat(result.getChallengePreference()).isEqualTo(ChallengePreferenceEnum.NO_PREFERENCE.toString()); - assertThat(result.getChallengeWindowSize()).isEqualTo(ChallengeWindowSizeEnum.R_390_400.toString()); - } - - @Test - public void transformToInternalModelWithNoDefaultValues() { - final Additional3DSData testObj = new Additional3DSData(); - testObj.setDfReferenceId("referenceId"); - testObj.setChallengePreference(ChallengePreferenceEnum.CHALLENGE_MANDATED); - testObj.setChallengeWindowSize(ChallengeWindowSizeEnum.R_250_400); - - final var result = (com.worldpay.internal.model.Additional3DSData) testObj.transformToInternalModel(); - - assertThat(result.getDfReferenceId()).isEqualTo("referenceId"); - assertThat(result.getChallengePreference()).isEqualTo(ChallengePreferenceEnum.CHALLENGE_MANDATED.toString()); - assertThat(result.getChallengeWindowSize()).isEqualTo(ChallengeWindowSizeEnum.R_250_400.toString()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/AuthenticationRiskDataTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/AuthenticationRiskDataTest.java deleted file mode 100644 index 5b504abc..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/AuthenticationRiskDataTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.service.model.Date; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class AuthenticationRiskDataTest { - - private static final String AUTHENTICATION_METHOD = "authenticationMethod"; - - @InjectMocks - private AuthenticationRiskData testObj; - - @Mock - private Date dateMock; - @Mock - private com.worldpay.internal.model.Date transformedDate; - - @Before - public void setUp() { - testObj.setAuthenticationMethod(AUTHENTICATION_METHOD); - testObj.setAuthenticationTimestamp(dateMock); - - when(dateMock.transformToInternalModel()).thenReturn(transformedDate); - } - - @Test - public void transformToInternalModel_ShouldTransformDataIntoInternalModel() { - final com.worldpay.internal.model.AuthenticationRiskData result = testObj.transformToInternalModel(); - - assertThat(result.getAuthenticationMethod()).isEqualTo(AUTHENTICATION_METHOD); - assertThat(result.getAuthenticationTimestamp().getDate()).isEqualTo(transformedDate); - } - - @Test - public void transformToInternalModel_ShouldNotPopulateAuthenticationTimestamp_WhenNull() { - testObj.setAuthenticationTimestamp(null); - - final com.worldpay.internal.model.AuthenticationRiskData result = testObj.transformToInternalModel(); - - assertThat(result.getAuthenticationMethod()).isEqualTo(AUTHENTICATION_METHOD); - assertThat(result.getAuthenticationTimestamp()).isNull(); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/RiskDataTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/RiskDataTest.java deleted file mode 100644 index 8d077eab..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/RiskDataTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.exception.WorldpayModelTransformationException; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class RiskDataTest { - - @InjectMocks - private RiskData testObj; - - @Mock - private TransactionRiskData transactionRiskDataMock; - @Mock - private ShopperAccountRiskData shopperAccountRiskDataMock; - @Mock - private AuthenticationRiskData authenticationRiskDataMock; - - @Mock - private com.worldpay.internal.model.TransactionRiskData intTransactionRiskDataMock; - @Mock - private com.worldpay.internal.model.ShopperAccountRiskData intShopperAccountRiskDataMock; - @Mock - private com.worldpay.internal.model.AuthenticationRiskData intAuthenticationRiskDataMock; - - @Before - public void setUp() throws Exception { - when(transactionRiskDataMock.transformToInternalModel()).thenReturn(intTransactionRiskDataMock); - when(shopperAccountRiskDataMock.transformToInternalModel()).thenReturn(intShopperAccountRiskDataMock); - when(authenticationRiskDataMock.transformToInternalModel()).thenReturn(intAuthenticationRiskDataMock); - } - - @Test - public void transformToInternalModel_ShouldSetAllMembersOfRiskData() throws WorldpayModelTransformationException { - final var result = testObj.transformToInternalModel(); - - assertThat(result.getAuthenticationRiskData()).isEqualTo(intAuthenticationRiskDataMock); - assertThat(result.getShopperAccountRiskData()).isEqualTo(intShopperAccountRiskDataMock); - assertThat(result.getTransactionRiskData()).isEqualTo(intTransactionRiskDataMock); - } - - @Test - public void transformToInternalModel_ShouldNotAddTransactionRiskData_WhenNull() throws WorldpayModelTransformationException { - testObj.setTransactionRiskData(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getTransactionRiskData()).isEqualTo(null); - } - - @Test - public void transformToInternalModel_ShouldNotAddShopperAccountRiskData_WhenNull() throws WorldpayModelTransformationException { - testObj.setShopperAccountRiskData(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getShopperAccountRiskData()).isEqualTo(null); - } - - @Test - public void transformToInternalModel_ShouldNotAddAuthenticationRiskData_WhenNull() throws WorldpayModelTransformationException { - testObj.setAuthenticationRiskData(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getAuthenticationRiskData()).isEqualTo(null); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/ShopperAccountRiskDataTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/ShopperAccountRiskDataTest.java deleted file mode 100644 index decad2fb..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/ShopperAccountRiskDataTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.service.model.Date; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class ShopperAccountRiskDataTest { - - @InjectMocks - private ShopperAccountRiskData testObj; - - @Mock(name = "shopperAccountCreationDate") - private Date shopperAccountCreationDateMock; - @Mock(name = "shopperAccountShippingAddressFirstUseDate") - private Date shopperAccountShippingAddressFirstUseDateMock; - @Mock(name = "shopperAccountModificationDate") - private Date shopperAccountModificationDateMock; - @Mock(name = "shopperAccountPaymentAccountFirstUseDate") - private Date shopperAccountPaymentAccountFirstUseDateMock; - @Mock(name = "shopperAccountPasswordChangeDate") - private Date shopperAccountPasswordChangeDateMock; - - @Mock - private com.worldpay.internal.model.Date intShopperAccountCreationDateMock; - @Mock - private com.worldpay.internal.model.Date intShopperAccountShippingAddressFirstUseDateMock; - @Mock - private com.worldpay.internal.model.Date intShopperAccountModificationDateMock; - @Mock - private com.worldpay.internal.model.Date intShopperAccountPaymentAccountFirstUseDateMock; - @Mock - private com.worldpay.internal.model.Date intShopperAccountPasswordChangeDateMock; - - @Before - public void setUp() throws Exception { - when(shopperAccountCreationDateMock.transformToInternalModel()).thenReturn(intShopperAccountCreationDateMock); - when(shopperAccountShippingAddressFirstUseDateMock.transformToInternalModel()).thenReturn(intShopperAccountShippingAddressFirstUseDateMock); - when(shopperAccountModificationDateMock.transformToInternalModel()).thenReturn(intShopperAccountModificationDateMock); - when(shopperAccountPaymentAccountFirstUseDateMock.transformToInternalModel()).thenReturn(intShopperAccountPaymentAccountFirstUseDateMock); - when(shopperAccountPasswordChangeDateMock.transformToInternalModel()).thenReturn(intShopperAccountPasswordChangeDateMock); - } - - @Test - public void transformToInternalModel_ShouldAddAllMembersOfTheInternalObject_WhenTheyExist() { - testObj.setShopperAccountAgeIndicator("shopperAccountAgeIndicator"); - testObj.setTransactionsAttemptedLastDay("transactionsAttemptedLastDay"); - testObj.setShopperAccountPaymentAccountIndicator("shopperAccountPaymentAccountIndicator"); - testObj.setShopperAccountChangeIndicator("shopperAccountChangeIndicator"); - testObj.setShopperAccountPasswordChangeIndicator("shopperAccountPasswordChangeIndicator"); - testObj.setPreviousSuspiciousActivity("previousSuspiciousActivity"); - testObj.setAddCardAttemptsLastDay("addCardAttemptsLastDay"); - testObj.setTransactionsAttemptedLastYear("transactionsAttemptedLastYear"); - testObj.setPurchasesCompletedLastSixMonths("purchasesCompletedLastSixMonths"); - testObj.setShopperAccountShippingAddressUsageIndicator("shopperAccountShippingAddressUsageIndicator"); - testObj.setShippingNameMatchesAccountName("shippingNameMatchesAccountName"); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getShopperAccountAgeIndicator()).isEqualTo("shopperAccountAgeIndicator"); - assertThat(result.getTransactionsAttemptedLastDay()).isEqualTo("transactionsAttemptedLastDay"); - assertThat(result.getShopperAccountPaymentAccountIndicator()).isEqualTo("shopperAccountPaymentAccountIndicator"); - assertThat(result.getShopperAccountChangeIndicator()).isEqualTo("shopperAccountChangeIndicator"); - assertThat(result.getShopperAccountPasswordChangeIndicator()).isEqualTo("shopperAccountPasswordChangeIndicator"); - assertThat(result.getPreviousSuspiciousActivity()).isEqualTo("previousSuspiciousActivity"); - assertThat(result.getAddCardAttemptsLastDay()).isEqualTo("addCardAttemptsLastDay"); - assertThat(result.getTransactionsAttemptedLastYear()).isEqualTo("transactionsAttemptedLastYear"); - assertThat(result.getPurchasesCompletedLastSixMonths()).isEqualTo("purchasesCompletedLastSixMonths"); - assertThat(result.getShopperAccountShippingAddressUsageIndicator()).isEqualTo("shopperAccountShippingAddressUsageIndicator"); - assertThat(result.getShippingNameMatchesAccountName()).isEqualTo("shippingNameMatchesAccountName"); - - assertThat(result.getShopperAccountCreationDate().getDate()).isEqualTo(intShopperAccountCreationDateMock); - assertThat(result.getShopperAccountModificationDate().getDate()).isEqualTo(intShopperAccountModificationDateMock); - assertThat(result.getShopperAccountPasswordChangeDate().getDate()).isEqualTo(intShopperAccountPasswordChangeDateMock); - assertThat(result.getShopperAccountShippingAddressFirstUseDate().getDate()).isEqualTo(intShopperAccountShippingAddressFirstUseDateMock); - assertThat(result.getShopperAccountPaymentAccountFirstUseDate().getDate()).isEqualTo(intShopperAccountPaymentAccountFirstUseDateMock); - } - - @Test - public void transformToInternalModel_ShouldNotAddShopperAccountCreationDate() { - testObj.setShopperAccountCreationDate(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getShopperAccountCreationDate()).isNull(); - } - - @Test - public void transformToInternalModel_ShouldNotAddShopperAccountShippingAddressFirstUseDate() { - testObj.setShopperAccountShippingAddressFirstUseDate(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getShopperAccountShippingAddressFirstUseDate()).isNull(); - } - - @Test - public void transformToInternalModel_ShouldNotAddShopperAccountModificationDate() { - testObj.setShopperAccountModificationDate(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getShopperAccountModificationDate()).isNull(); - } - - @Test - public void transformToInternalModel_ShouldNotAddShopperAccountPaymentAccountFirstUseDate() { - testObj.setShopperAccountPaymentAccountFirstUseDate(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getShopperAccountPaymentAccountFirstUseDate()).isNull(); - } - - @Test - public void transformToInternalModel_ShouldNotAddShopperAccountPasswordChangeDate() { - testObj.setShopperAccountPasswordChangeDate(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getShopperAccountPasswordChangeDate()).isNull(); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/TransactionRiskDataGiftCardAmountTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/TransactionRiskDataGiftCardAmountTest.java deleted file mode 100644 index bd50e97d..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/TransactionRiskDataGiftCardAmountTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.service.model.Amount; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class TransactionRiskDataGiftCardAmountTest { - - @InjectMocks - private TransactionRiskDataGiftCardAmount testObj; - - @Mock - private Amount amountMock; - @Mock - private com.worldpay.internal.model.Amount intAmountMock; - - @Test - public void transformToInternalModel_ShouldReturnInternalTransactionRiskDataGiftCardAmount() { - when(amountMock.transformToInternalModel()).thenReturn(intAmountMock); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getAmount()).isEqualTo(intAmountMock); - - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/TransactionRiskDataTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/TransactionRiskDataTest.java deleted file mode 100644 index 697e8b0f..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/threeds2/TransactionRiskDataTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.worldpay.service.model.threeds2; - -import com.worldpay.service.model.Date; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class TransactionRiskDataTest { - - @InjectMocks - private TransactionRiskData testObj; - - @Mock - private Date transactionRiskDataPreOrderDateMock; - @Mock - private TransactionRiskDataGiftCardAmount transactionRiskDataGiftCardAmountMock; - - @Mock - private com.worldpay.internal.model.Date intTransactionRiskDataPreOrderDateMock; - @Mock - private com.worldpay.internal.model.TransactionRiskDataGiftCardAmount intTransactionRiskDataGiftCardAmountMock; - - @Before - public void setUp() throws Exception { - when(transactionRiskDataPreOrderDateMock.transformToInternalModel()).thenReturn(intTransactionRiskDataPreOrderDateMock); - when(transactionRiskDataGiftCardAmountMock.transformToInternalModel()).thenReturn(intTransactionRiskDataGiftCardAmountMock); - } - - @Test - public void transformToInternalModel_ShouldAddAllMembersOfTransactionRiskData() { - testObj.setDeliveryEmailAddress("deliveryEmailAddress"); - testObj.setDeliveryTimeframe("deliveryTimeframe"); - testObj.setGiftCardCount("giftCardCount"); - testObj.setPreOrderPurchase("preOrderPurchase"); - testObj.setReorderingPreviousPurchases("reorderingPreviousPurchases"); - testObj.setShippingMethod("shippingMethod"); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getDeliveryEmailAddress()).isEqualTo("deliveryEmailAddress"); - assertThat(result.getDeliveryTimeframe()).isEqualTo("deliveryTimeframe"); - assertThat(result.getGiftCardCount()).isEqualTo("giftCardCount"); - assertThat(result.getPreOrderPurchase()).isEqualTo("preOrderPurchase"); - assertThat(result.getReorderingPreviousPurchases()).isEqualTo("reorderingPreviousPurchases"); - assertThat(result.getShippingMethod()).isEqualTo("shippingMethod"); - - assertThat(result.getTransactionRiskDataPreOrderDate().getDate()).isEqualTo(intTransactionRiskDataPreOrderDateMock); - assertThat(result.getTransactionRiskDataGiftCardAmount()).isEqualTo(intTransactionRiskDataGiftCardAmountMock); - } - - @Test - public void transformToInternalModel_ShouldNotAddPreorderDate_WhenEmpty() { - testObj.setTransactionRiskDataPreOrderDate(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getTransactionRiskDataPreOrderDate()).isNull(); - } - - @Test - public void transformToInternalModel_ShouldNotAddGiftCardAmount_WhenEmpty() { - testObj.setTransactionRiskDataGiftCardAmount(null); - - final var result = testObj.transformToInternalModel(); - - assertThat(result.getTransactionRiskDataGiftCardAmount()).isNull(); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/CardDetailsTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/CardDetailsTest.java deleted file mode 100644 index 08bd2976..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/CardDetailsTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.service.model.Address; -import com.worldpay.service.model.Date; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; - -import java.time.LocalDateTime; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@UnitTest -public class CardDetailsTest { - - private static final String ISSUER_COUNTRY_CODE = "issuerContryCode"; - private static final String CARD_SUB_BRAND = "cardSubBrand"; - private static final String CARD_BRAND = "cardBrand"; - private static final String FIRST_NAME = "JJJJ"; - private static final String CARD_HOLDER_NAME = "cardHolderName"; - private static final String CVC_NUMBER = "123"; - private static final String CARD_NUMBER = "cardNumber"; - - @Test - public void shouldTransformToInternalCardDetails() { - final CardDetails cardDetails = new CardDetails(); - cardDetails.setIssuerCountryCode(ISSUER_COUNTRY_CODE); - cardDetails.setCardSubBrand(CARD_SUB_BRAND); - cardDetails.setCardBrand(CARD_BRAND); - final Address cardAddress = new Address(); - cardAddress.setFirstName(FIRST_NAME); - cardDetails.setCardAddress(cardAddress); - cardDetails.setCardHolderName(CARD_HOLDER_NAME); - cardDetails.setCvcNumber(CVC_NUMBER); - cardDetails.setCardNumber(CARD_NUMBER); - final Date expiryDate = new Date(LocalDateTime.now().plusYears(2)); - cardDetails.setExpiryDate(expiryDate); - - final com.worldpay.internal.model.CardDetails result = (com.worldpay.internal.model.CardDetails) cardDetails.transformToInternalModel(); - - assertEquals(ISSUER_COUNTRY_CODE, result.getDerived().getIssuerCountryCode()); - assertEquals(CARD_SUB_BRAND, result.getDerived().getCardSubBrand()); - assertEquals(CARD_BRAND, result.getDerived().getCardBrand()); - assertEquals(FIRST_NAME, result.getCardAddress().getAddress().getFirstName()); - assertEquals(CARD_HOLDER_NAME, result.getCardHolderName().getvalue()); - assertEquals(CVC_NUMBER, result.getCvc().getvalue()); - assertEquals(CARD_NUMBER, result.getDerived().getObfuscatedPAN()); - assertEquals(expiryDate.getMonth(), result.getExpiryDate().getDate().getMonth()); - assertEquals(expiryDate.getYear(), result.getExpiryDate().getDate().getYear()); - } - - @Test - public void shouldNotTransformEmptyFieldsToInternalCardDetails() { - final CardDetails cardDetails = new CardDetails(); - - final com.worldpay.internal.model.CardDetails result = (com.worldpay.internal.model.CardDetails) cardDetails.transformToInternalModel(); - - assertNull(result.getDerived()); - assertNull(result.getCardAddress()); - assertNull(result.getCardHolderName()); - assertNull(result.getCvc()); - assertNull(result.getDerived()); - assertNull(result.getExpiryDate()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/CardTokenRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/CardTokenRequestTest.java deleted file mode 100644 index d6870c60..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/CardTokenRequestTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; -import com.worldpay.enums.payment.storedCredentials.Usage; -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.*; -import com.worldpay.service.model.Address; -import com.worldpay.service.model.payment.Cse; -import com.worldpay.service.model.payment.PaymentBuilder; -import com.worldpay.service.model.payment.StoredCredentials; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; - -import static org.junit.Assert.*; - -@UnitTest -public class CardTokenRequestTest { - - private static final String AUTHENTICATED_SHOPPER_ID = "authenticatedShopperId"; - private static final String TOKEN_REASON = "tokenReason"; - private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; - private static final TokenRequest TOKEN_REQUEST = new TokenRequest(TOKEN_EVENT_REFERENCE, TOKEN_REASON); - private static final Address BILLING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final Cse PAYMENT = PaymentBuilder.createCSE("encryptedData", BILLING_ADDRESS); - private static final String SCHEME_TRANSACTION_IDENTIFIER = "schemeTransactionIdentifier"; - - @Test - public void paymentTokenCreateShouldContainAnAuthenticatedShopperIdIfProvided() throws WorldpayModelTransformationException { - final CardTokenRequest cardTokenRequest = new CardTokenRequest(TOKEN_REQUEST, AUTHENTICATED_SHOPPER_ID, PAYMENT); - final PaymentTokenCreate result = (PaymentTokenCreate) cardTokenRequest.transformToInternalModel(); - assertEquals(AUTHENTICATED_SHOPPER_ID, result.getAuthenticatedShopperID().getvalue()); - } - - @Test - public void paymentTokenCreateShouldNotContainAnAuthenticatedShopperIdIfNotProvided() throws WorldpayModelTransformationException { - final CardTokenRequest cardTokenRequest = new CardTokenRequest(TOKEN_REQUEST, null, PAYMENT); - final PaymentTokenCreate result = (PaymentTokenCreate) cardTokenRequest.transformToInternalModel(); - assertNull(result.getAuthenticatedShopperID()); - } - - @Test - public void paymentTokenCreateShouldContainTokenRequestIfProvided() throws WorldpayModelTransformationException { - final CardTokenRequest cardTokenRequest = new CardTokenRequest(TOKEN_REQUEST, AUTHENTICATED_SHOPPER_ID, PAYMENT); - final PaymentTokenCreate result = (PaymentTokenCreate) cardTokenRequest.transformToInternalModel(); - assertEquals(TOKEN_REASON, result.getCreateToken().getTokenReason().getvalue()); - assertEquals(TOKEN_EVENT_REFERENCE, result.getCreateToken().getTokenEventReference()); - } - - @Test - public void paymentTokenCreateShouldNotContainTokenRequestIfNotProvided() throws WorldpayModelTransformationException { - final CardTokenRequest cardTokenRequest = new CardTokenRequest(null, AUTHENTICATED_SHOPPER_ID, PAYMENT); - final PaymentTokenCreate result = (PaymentTokenCreate) cardTokenRequest.transformToInternalModel(); - assertNull(result.getCreateToken()); - } - - @Test - public void paymentTokenCreateShouldContainPayment() throws WorldpayModelTransformationException { - final CardTokenRequest cardTokenRequest = new CardTokenRequest(TOKEN_REQUEST, AUTHENTICATED_SHOPPER_ID, PAYMENT); - final PaymentTokenCreate result = (PaymentTokenCreate) cardTokenRequest.transformToInternalModel(); - final CSEDATA csePayment = (CSEDATA) result.getPaymentInstrumentOrCSEDATA().get(0); - final com.worldpay.internal.model.Address address = csePayment.getCardAddress().getAddress(); - - assertEquals(PAYMENT.getEncryptedData(), csePayment.getEncryptedData()); - assertEquals(BILLING_ADDRESS.getFirstName(), address.getFirstName()); - assertEquals(BILLING_ADDRESS.getLastName(), address.getLastName()); - for (final Object addressLine : address.getStreetOrHouseNameOrHouseNumberOrHouseNumberExtensionOrAddress1OrAddress2OrAddress3()) { - if (addressLine instanceof Address1) { - assertEquals(BILLING_ADDRESS.getAddress1(), ((Address1) addressLine).getvalue()); - } else if (addressLine instanceof Address2) { - assertEquals(BILLING_ADDRESS.getAddress2(), ((Address2) addressLine).getvalue()); - } else { - assertEquals(BILLING_ADDRESS.getAddress3(), ((Address3) addressLine).getvalue()); - } - } - assertEquals(BILLING_ADDRESS.getPostalCode(), address.getPostalCode()); - assertEquals(BILLING_ADDRESS.getCity(), address.getCity()); - assertEquals(BILLING_ADDRESS.getCountryCode(), address.getCountryCode()); - } - - @Test - public void transformToInternalModel_ShouldSetStoredCredentialAttribute_WhenCardTokenRequestHasStoredCredentialsNotNull() throws WorldpayModelTransformationException { - final StoredCredentials storedCredentials = new StoredCredentials(MerchantInitiatedReason.UNSCHEDULED, SCHEME_TRANSACTION_IDENTIFIER, Usage.FIRST); - final CardTokenRequest cardTokenRequest = new CardTokenRequest(TOKEN_REQUEST, AUTHENTICATED_SHOPPER_ID, PAYMENT, storedCredentials); - - final PaymentTokenCreate result = (PaymentTokenCreate) cardTokenRequest.transformToInternalModel(); - final com.worldpay.internal.model.StoredCredentials intStoredCredentials = result.getStoredCredentials(); - - assertNotNull(intStoredCredentials); - } - - @Test - public void transformToInternalModel_ShouldNotSetStoredCredentialAttribute_WhenCardTokenRequestHasNotStoredCredentialsNotNull() throws WorldpayModelTransformationException { - final CardTokenRequest cardTokenRequest = new CardTokenRequest( TOKEN_REQUEST, AUTHENTICATED_SHOPPER_ID, PAYMENT); - - final PaymentTokenCreate result = (PaymentTokenCreate) cardTokenRequest.transformToInternalModel(); - final com.worldpay.internal.model.StoredCredentials intStoredCredentials = result.getStoredCredentials(); - - assertNull(intStoredCredentials); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/DeleteTokenRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/DeleteTokenRequestTest.java deleted file mode 100644 index 990ed3a9..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/DeleteTokenRequestTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.PaymentTokenDelete; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class DeleteTokenRequestTest { - - private static final String PAYMENT_TOKEN_ID = "paymentTokenId"; - private static final String AUTHENTICATED_SHOPPER_ID = "authenticatedShopperId"; - private static final String TOKEN_REASON = "tokenReason"; - private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; - - private DeleteTokenRequest testObj; - - @Mock - private TokenRequest tokenRequestMock; - - @Before - public void setUp(){ - testObj = new DeleteTokenRequest(PAYMENT_TOKEN_ID, AUTHENTICATED_SHOPPER_ID, tokenRequestMock); - when(tokenRequestMock.getTokenReason()).thenReturn(TOKEN_REASON); - when(tokenRequestMock.getTokenEventReference()).thenReturn(TOKEN_EVENT_REFERENCE); - } - - @Test - public void shouldTransformToAPaymentTokenDeleteWithShopperScope() { - final InternalModelObject result = testObj.transformToInternalModel(); - - assertTrue(result instanceof PaymentTokenDelete); - final PaymentTokenDelete paymentTokenDelete = (PaymentTokenDelete) result; - assertEquals(PAYMENT_TOKEN_ID, paymentTokenDelete.getPaymentTokenID().getvalue()); - assertEquals(AUTHENTICATED_SHOPPER_ID, paymentTokenDelete.getAuthenticatedShopperID().getvalue()); - assertEquals(TOKEN_REASON, paymentTokenDelete.getTokenReason().getvalue()); - assertEquals(TOKEN_EVENT_REFERENCE, paymentTokenDelete.getTokenEventReference()); - assertEquals("shopper", paymentTokenDelete.getTokenScope()); - } - - @Test - public void shouldTransformToAPaymentTokenDeleteWithMerchantScope() { - when(tokenRequestMock.isMerchantToken()).thenReturn(true); - - final InternalModelObject result = testObj.transformToInternalModel(); - - assertTrue(result instanceof PaymentTokenDelete); - final PaymentTokenDelete paymentTokenDelete = (PaymentTokenDelete) result; - assertEquals(PAYMENT_TOKEN_ID, paymentTokenDelete.getPaymentTokenID().getvalue()); - assertEquals(AUTHENTICATED_SHOPPER_ID, paymentTokenDelete.getAuthenticatedShopperID().getvalue()); - assertEquals(TOKEN_REASON, paymentTokenDelete.getTokenReason().getvalue()); - assertEquals(TOKEN_EVENT_REFERENCE, paymentTokenDelete.getTokenEventReference()); - assertEquals("merchant", paymentTokenDelete.getTokenScope()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/TokenRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/TokenRequestTest.java deleted file mode 100644 index 6865f512..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/TokenRequestTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.CreateToken; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@UnitTest -public class TokenRequestTest { - - private static final String TOKEN_REASON = "tokenReason"; - private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; - private static final String SHOPPER = "shopper"; - - @Test - public void shouldTransformToInternalCreateTokenWithScopeMerchant() throws WorldpayModelTransformationException { - final TokenRequest tokenRequest = new TokenRequest(TOKEN_EVENT_REFERENCE, TOKEN_REASON, true); - - final CreateToken result = (CreateToken) tokenRequest.transformToInternalModel(); - - assertEquals(TOKEN_EVENT_REFERENCE, result.getTokenEventReference()); - assertEquals(TOKEN_REASON, result.getTokenReason().getvalue()); - assertEquals("merchant", result.getTokenScope()); - } - - @Test - public void shouldTransformToInternalCreateTokenWithScopeShopper() throws WorldpayModelTransformationException { - final TokenRequest tokenRequest = new TokenRequest(TOKEN_EVENT_REFERENCE, TOKEN_REASON, false); - - final CreateToken result = (CreateToken) tokenRequest.transformToInternalModel(); - - assertEquals(TOKEN_EVENT_REFERENCE, result.getTokenEventReference()); - assertEquals(TOKEN_REASON, result.getTokenReason().getvalue()); - assertEquals(SHOPPER, result.getTokenScope()); - } - - @Test - public void shouldTransformToInternalCreateTokenWithoutTokenReason() throws WorldpayModelTransformationException { - final TokenRequest tokenRequest = new TokenRequest(TOKEN_EVENT_REFERENCE, null, false); - - final CreateToken result = (CreateToken) tokenRequest.transformToInternalModel(); - - assertEquals(TOKEN_EVENT_REFERENCE, result.getTokenEventReference()); - assertNull(result.getTokenReason()); - assertEquals(SHOPPER, result.getTokenScope()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/UpdateTokenRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/UpdateTokenRequestTest.java deleted file mode 100644 index 736d6816..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/model/token/UpdateTokenRequestTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.worldpay.service.model.token; - -import com.worldpay.internal.helper.InternalModelObject; -import com.worldpay.internal.model.PaymentTokenUpdate; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class UpdateTokenRequestTest { - - private static final String PAYMENT_TOKEN_ID = "paymentTokenId"; - private static final String AUTHENTICATED_SHOPPER_ID = "authenticatedShopperId"; - private static final String TOKEN_REASON = "tokenReason"; - private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; - - private UpdateTokenRequest testObj; - - @Mock - private CardDetails cardDetailsMock; - @Mock - private TokenRequest tokenRequestMock; - @Mock - private com.worldpay.internal.model.CardDetails intCardDetailsMock; - - @Before - public void setUp() { - when(cardDetailsMock.transformToInternalModel()).thenReturn(intCardDetailsMock); - when(tokenRequestMock.getTokenReason()).thenReturn(TOKEN_REASON); - when(tokenRequestMock.getTokenEventReference()).thenReturn(TOKEN_EVENT_REFERENCE); - } - - @Test - public void shouldTransformToAPaymentTokenUpdateWithMerchantScope() { - testObj = new UpdateTokenRequest(PAYMENT_TOKEN_ID, AUTHENTICATED_SHOPPER_ID, cardDetailsMock, tokenRequestMock, true); - - final InternalModelObject result = testObj.transformToInternalModel(); - - assertTrue(result instanceof PaymentTokenUpdate); - final PaymentTokenUpdate paymentTokenUpdate = (PaymentTokenUpdate) result; - assertEquals(PAYMENT_TOKEN_ID, paymentTokenUpdate.getPaymentTokenID().getvalue()); - assertNull(paymentTokenUpdate.getAuthenticatedShopperID()); - assertEquals(intCardDetailsMock, paymentTokenUpdate.getPaymentInstrument().getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().get(0)); - assertEquals(TOKEN_REASON, paymentTokenUpdate.getTokenReason().getvalue()); - assertEquals(TOKEN_EVENT_REFERENCE, paymentTokenUpdate.getTokenEventReference()); - assertEquals("merchant", paymentTokenUpdate.getTokenScope()); - } - - @Test - public void shouldTransformToAPaymentTokenUpdateWithShopperScope() { - testObj = new UpdateTokenRequest(PAYMENT_TOKEN_ID, AUTHENTICATED_SHOPPER_ID, cardDetailsMock, tokenRequestMock, false); - - final InternalModelObject result = testObj.transformToInternalModel(); - - assertTrue(result instanceof PaymentTokenUpdate); - final PaymentTokenUpdate paymentTokenUpdate = (PaymentTokenUpdate) result; - assertEquals(PAYMENT_TOKEN_ID, paymentTokenUpdate.getPaymentTokenID().getvalue()); - assertEquals(AUTHENTICATED_SHOPPER_ID, paymentTokenUpdate.getAuthenticatedShopperID().getvalue()); - assertEquals(intCardDetailsMock, paymentTokenUpdate.getPaymentInstrument().getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().get(0)); - assertEquals(TOKEN_REASON, paymentTokenUpdate.getTokenReason().getvalue()); - assertEquals(TOKEN_EVENT_REFERENCE, paymentTokenUpdate.getTokenEventReference()); - assertEquals("shopper", paymentTokenUpdate.getTokenScope()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultTestWorldpayFraudSightStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultTestWorldpayFraudSightStrategyTest.java new file mode 100644 index 00000000..86b6d5e3 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultTestWorldpayFraudSightStrategyTest.java @@ -0,0 +1,69 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.data.Address; +import com.worldpay.data.CustomNumericFields; +import com.worldpay.data.CustomStringFields; +import com.worldpay.data.ShopperFields; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.core.model.order.CartModel; +import de.hybris.platform.core.model.user.AddressModel; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultTestWorldpayFraudSightStrategyTest { + + private static final String ADDRESS_LINE_2 = "Address Line 2"; + + @Spy + @InjectMocks + private DefaultTestWorldpayFraudSightStrategy testObj; + + @Mock + private ShopperFields shopperFieldsMock; + @Mock + private CartModel cartMock; + @Mock + private WorldpayAdditionalInfoData worldpayAdditionalInfoDataMock; + @Mock + private AddressModel addressMock; + @Mock + private Address convertedAddressMock; + + @Test + public void createShopperFields_ShouldAddTheAddressLine3() { + doReturn(shopperFieldsMock).when(testObj).callSuperCreateShopperFields(cartMock, worldpayAdditionalInfoDataMock); + when(shopperFieldsMock.getShopperAddress()).thenReturn(convertedAddressMock); + when(cartMock.getPaymentAddress()).thenReturn(addressMock); + when(addressMock.getLine2()).thenReturn(ADDRESS_LINE_2); + + testObj.createShopperFields(cartMock, worldpayAdditionalInfoDataMock); + + verify(convertedAddressMock).setAddress3(ADDRESS_LINE_2); + } + + @Test + public void createCustomNumericFields_ShouldCreateCustomNumericFields() { + final CustomNumericFields result = testObj.createCustomNumericFields(); + + assertThat(result).isNotNull(); + assertThat(result.getCustomNumericField1()).isEqualTo(123); + } + + @Test + public void createCustomStringFields_ShouldCreateCustomStringFields() { + final CustomStringFields result = testObj.createCustomStringFields(); + + assertThat(result).isNotNull(); + assertThat(result.getCustomStringField1()).isEqualTo("abc"); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultTestWorldpayLevel23StrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultTestWorldpayLevel23StrategyTest.java new file mode 100644 index 00000000..929dc62d --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultTestWorldpayLevel23StrategyTest.java @@ -0,0 +1,87 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.data.Amount; +import com.worldpay.data.Item; +import com.worldpay.data.Purchase; +import com.worldpay.service.payment.WorldpayOrderService; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.core.model.c2l.CurrencyModel; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.product.ProductModel; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultTestWorldpayLevel23StrategyTest { + + private static final String VALID_PRODUCT_NAME = "valid product name"; + + @InjectMocks + private DefaultTestWorldpayLevel23Strategy testObj; + + @Mock + private WorldpayOrderService worldpayOrderServiceMock; + + @Mock + private AbstractOrderModel orderMock; + @Mock + private ProductModel productMock; + @Mock + private CurrencyModel currencyMock; + @Mock + private Amount amountMock; + + private Purchase purchase; + + @Before + public void setUp() { + purchase = new Purchase(); + when(orderMock.getCurrency()).thenReturn(currencyMock); + when(worldpayOrderServiceMock.createAmount(currencyMock, 0)).thenReturn(amountMock); + when(productMock.getName()).thenReturn(VALID_PRODUCT_NAME); + } + + @Test + public void setCustomerReference_ShouldSetRandomStringLength17() { + testObj.setCustomerReference(orderMock, purchase); + + assertThat(purchase.getCustomerReference()).isNotEmpty(); + assertThat(purchase.getCustomerReference().length()).isEqualTo(17); + } + + @Test + public void setProductDescription_WhenProductNameLessThen26Char_ShouldSetProductName() { + final Item item = new Item(); + + testObj.setProductDescription(productMock, item); + + assertThat(item.getDescription()).isNotEmpty(); + assertThat(item.getDescription()).isEqualTo(VALID_PRODUCT_NAME); + } + + @Test + public void setProductDescription_WhenProductNameMoreThen26Char_ShouldTrimProductName() { + when(productMock.getName()).thenReturn("Product name that exceeds the maximum limit of 26 characters"); + final Item item = new Item(); + + testObj.setProductDescription(productMock, item); + + assertThat(item.getDescription().length()).isEqualTo(26); + assertThat(item.getDescription()).isEqualTo("Product name that exceeds "); + } + + @Test + public void setDutyAmount_ShouldCreateAmountWithZeroValue() { + testObj.setDutyAmount(orderMock, purchase); + + assertThat(purchase.getDutyAmount()).isEqualTo(amountMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayAdditionalRequestDataServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayAdditionalRequestDataServiceTest.java new file mode 100644 index 00000000..39861f0c --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayAdditionalRequestDataServiceTest.java @@ -0,0 +1,54 @@ +package com.worldpay.service.payment.impl; + +import com.google.common.collect.ImmutableList; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.payment.WorldpayAdditionalDataRequestStrategy; +import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.mockito.Mockito.*; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayAdditionalRequestDataServiceTest { + + private DefaultWorldpayAdditionalRequestDataService testObj; + + @Mock + private WorldpayAdditionalDataRequestStrategy primeRoutingStrategyMock, level23StrategyMock, fraudSightStrategyMock; + @Mock + private AbstractOrderModel cartMock; + @Mock + private WorldpayAdditionalInfoData worldpayAdditionalInfoDataMock; + @Mock + private AuthoriseRequestParametersCreator authoriseRequestParametersCreatorMock; + + @Before + public void setUp() { + testObj = new DefaultWorldpayAdditionalRequestDataService(ImmutableList.of(primeRoutingStrategyMock, level23StrategyMock, fraudSightStrategyMock), ImmutableList.of(level23StrategyMock, fraudSightStrategyMock)); + } + + @Test + public void populateDirectRequestAdditionalData_ShouldCallTheDirectStrategies() { + testObj.populateDirectRequestAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verify(primeRoutingStrategyMock).populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + verify(level23StrategyMock).populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + verify(fraudSightStrategyMock).populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + } + + @Test + public void populateDirectRequestAdditionalData_ShouldCallTheRedirectStrategies() { + testObj.populateRedirectRequestAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verify(primeRoutingStrategyMock, never()).populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + verify(level23StrategyMock).populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + verify(fraudSightStrategyMock).populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayAfterRedirectValidationServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayAfterRedirectValidationServiceTest.java index a6c2ffca..008144f6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayAfterRedirectValidationServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayAfterRedirectValidationServiceTest.java @@ -2,7 +2,7 @@ import com.worldpay.exception.WorldpayMacValidationException; import com.worldpay.service.mac.MacValidator; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Before; import org.junit.Test; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayDirectOrderServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayDirectOrderServiceTest.java index e2331f48..2c0c6eaa 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayDirectOrderServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayDirectOrderServiceTest.java @@ -2,6 +2,9 @@ import com.worldpay.core.services.WorldpayPaymentInfoService; import com.worldpay.data.*; +import com.worldpay.data.payment.Card; +import com.worldpay.data.token.TokenDetails; +import com.worldpay.data.token.TokenReply; import com.worldpay.enums.order.ThreeDSecureFlowEnum; import com.worldpay.enums.token.TokenEvent; import com.worldpay.exception.WorldpayConfigurationException; @@ -9,11 +12,7 @@ import com.worldpay.merchant.WorldpayMerchantInfoService; import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.service.WorldpayServiceGateway; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Card; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.token.TokenDetails; -import com.worldpay.service.model.token.TokenReply; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.payment.WorldpaySessionService; import com.worldpay.service.payment.request.WorldpayRequestFactory; @@ -201,7 +200,7 @@ public void setUp() throws WorldpayException { when(aditional3DSInfoMock.getChallengeWindowSize()).thenReturn(WINDOW_SIZE); when(createTokenResponseMock.getToken()).thenReturn(tokenReplyMock); when(tokenReplyMock.getPaymentInstrument()).thenReturn(cardMock); - when(cardMock.getPaymentType()).thenReturn(PaymentType.VISA); + when(cardMock.getPaymentType()).thenReturn(PaymentType.VISA.getMethodCode()); when(tokenReplyMock.getTokenDetails()).thenReturn(tokenDetailsMock); when(tokenDetailsMock.getTokenEvent()).thenReturn(TokenEvent.CONFLICT.name()); when(worldpayMerchantInfoService.getCurrentSiteMerchant()).thenReturn(merchantInfoMock); @@ -551,7 +550,7 @@ public void completeAuthoriseGooglePay_ShouldDoNothing_WhenOrderModel() { testObj.completeAuthoriseGooglePay(directAuthoriseServiceResponseMock, orderMock, MERCHANT_CODE); - verifyZeroInteractions(worldpayPaymentTransactionServiceMock); - verifyZeroInteractions(worldpayPaymentInfoServiceMock); + verifyZeroInteractions(worldpayPaymentTransactionServiceMock); + verifyZeroInteractions(worldpayPaymentInfoServiceMock); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayFraudSightStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayFraudSightStrategyTest.java new file mode 100644 index 00000000..7c7980ef --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayFraudSightStrategyTest.java @@ -0,0 +1,226 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.core.services.WorldpayCartService; +import com.worldpay.model.WorldpayFraudSightModel; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.data.Address; +import com.worldpay.data.FraudSightData; +import com.worldpay.data.FraudSightResponse; +import com.worldpay.data.PaymentReply; +import com.worldpay.service.request.AuthoriseRequestParameters; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.cms2.model.site.CMSSiteModel; +import de.hybris.platform.core.model.order.CartModel; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.core.model.user.CustomerModel; +import de.hybris.platform.payment.model.PaymentTransactionModel; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import de.hybris.platform.servicelayer.model.ModelService; +import de.hybris.platform.site.BaseSiteService; +import org.apache.commons.lang3.NotImplementedException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.internal.util.reflection.Whitebox; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Calendar; +import java.util.Date; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayFraudSightStrategyTest { + + private static final String ADDRESS_LINE_2 = "Address Line 2"; + private static final String SHOPPER_ID = "shopper_id"; + private static final String CUSTOMER_NAME = "Customer Name"; + private static final Date BIRTHDAY_DATE = new Date(1990, Calendar.MAY, 17); + private static final String DEVICE_SESSION = "deviceSession"; + + @Spy + @InjectMocks + private DefaultWorldpayFraudSightStrategy testObj; + + @Mock + private ModelService modelServiceMock; + @Mock + private WorldpayCartService worldpayCartServiceMock; + @Mock + private Converter worldpayAddressConverterMock; + @Mock + private Converter worldpayFraudSightResponseConverterMock; + @Mock + private CartModel cartMock; + @Mock + private CMSSiteModel siteMock; + @Mock + private WorldpayAdditionalInfoData worldpayAdditionalInfoDataMock; + @Mock + private CustomerModel customerMock; + @Mock + private BaseSiteService baseSiteServiceMock; + @Mock + private AddressModel addressMock; + @Mock + private Address convertedAddressMock; + @Mock + private PaymentReply paymentReplyMock; + @Mock + private PaymentTransactionModel paymentTransactionModelMock; + @Mock + private FraudSightResponse fraudSightMock; + @Mock + private WorldpayFraudSightModel worldpayFrauSightMock; + @Mock + private FraudSightData fraudSightDataMock; + @Mock + private AuthoriseRequestParameters.AuthoriseRequestParametersCreator authoriseRequestParametersCreatorMock; + + @Before + public void setUp() { + Whitebox.setInternalState(testObj, "worldpayAddressConverter", worldpayAddressConverterMock); + Whitebox.setInternalState(testObj, "worldpayFraudSightResponseConverter", worldpayFraudSightResponseConverterMock); + + when(baseSiteServiceMock.getCurrentBaseSite()).thenReturn(siteMock); + when(worldpayFraudSightResponseConverterMock.convert(fraudSightMock)).thenReturn(worldpayFrauSightMock); + } + + @Test + public void isFraudSightEnabled_WhenFSIsEnabledForSite_ShouldReturnTrue() { + when(siteMock.getEnableFS()).thenReturn(true); + + final boolean result = testObj.isFraudSightEnabled(); + + assertThat(result).isTrue(); + } + + @Test + public void isFraudSightEnabled_WhenFSIsDisabledForSite_ShouldReturnFalse() { + when(siteMock.getEnableFS()).thenReturn(false); + + final boolean result = testObj.isFraudSightEnabled(); + + assertThat(result).isFalse(); + } + + @Test + public void isFraudSightEnabled_WhenFSIsEnabledForGivenSite_ShouldReturnTrue() { + when(siteMock.getEnableFS()).thenReturn(true); + + final boolean result = testObj.isFraudSightEnabled(siteMock); + + assertThat(result).isTrue(); + } + + @Test + public void isFraudSightEnabled_WhenFSIsDisabledForGivenSite_ShouldReturnFalse() { + when(siteMock.getEnableFS()).thenReturn(false); + + final boolean result = testObj.isFraudSightEnabled(siteMock); + + assertThat(result).isFalse(); + } + + @Test(expected = IllegalArgumentException.class) + public void createFraudSightData_WhenCartIsNull_ShouldThrowException() { + testObj.createFraudSightData(null, worldpayAdditionalInfoDataMock); + } + + @Test(expected = IllegalArgumentException.class) + public void createFraudSightData_WhenUserIsNull_ShouldThrowException() { + testObj.createFraudSightData(cartMock, worldpayAdditionalInfoDataMock); + } + + @Test + public void createFraudSightData_ShouldPopulateTheFraudSightData() { + doReturn(null).when(testObj).createCustomNumericFields(); + doReturn(null).when(testObj).createCustomStringFields(); + when(cartMock.getUser()).thenReturn(customerMock); + when(cartMock.getPaymentAddress()).thenReturn(addressMock); + when(customerMock.getName()).thenReturn(CUSTOMER_NAME); + when(addressMock.getLine2()).thenReturn(ADDRESS_LINE_2); + when(worldpayAdditionalInfoDataMock.getDateOfBirth()).thenReturn(BIRTHDAY_DATE); + when(worldpayCartServiceMock.getAuthenticatedShopperId(cartMock)).thenReturn(SHOPPER_ID); + when(worldpayAddressConverterMock.convert(addressMock)).thenReturn(convertedAddressMock); + + final FraudSightData result = testObj.createFraudSightData(cartMock, worldpayAdditionalInfoDataMock); + + assertThat(result).isNotNull(); + assertThat(result.getShopperFields()).isNotNull(); + assertThat(result.getShopperFields().getShopperId()).isEqualTo(SHOPPER_ID); + assertThat(result.getShopperFields().getShopperName()).isEqualTo(CUSTOMER_NAME); + assertThat(result.getShopperFields().getBirthDate()).isNotNull(); + assertThat(result.getShopperFields().getBirthDate().getMonth()).isEqualTo("5"); + assertThat(result.getShopperFields().getBirthDate().getDayOfMonth()).isEqualTo("17"); + assertThat(result.getShopperFields().getShopperAddress()).isEqualTo(convertedAddressMock); + } + + @Test(expected = NotImplementedException.class) + public void createCustomStringFields_ShouldThrowException() { + testObj.createCustomStringFields(); + } + + @Test(expected = NotImplementedException.class) + public void createCustomNumericFields_ShouldThrowException() { + testObj.createCustomNumericFields(); + } + + @Test + public void addFraudSight_WhenFraudSightIsNull_ShouldDoNothing() { + when(paymentReplyMock.getFraudSight()).thenReturn(null); + + testObj.addFraudSight(paymentTransactionModelMock, paymentReplyMock); + + verify(paymentTransactionModelMock, never()).setFraudSight(any()); + } + + @Test + public void addFraudSight_WhenFraudSightIsPresent_ShouldSaveFraudSightOnTransaction() { + when(paymentReplyMock.getFraudSight()).thenReturn(fraudSightMock); + + testObj.addFraudSight(paymentTransactionModelMock, paymentReplyMock); + + verify(paymentTransactionModelMock).setFraudSight(worldpayFrauSightMock); + verify(modelServiceMock).save(paymentTransactionModelMock); + } + + @Test + public void populateRequestWithAdditionalData_WhenFraudSightIsEnabledAndDeviceIsNotNull_ShouldAddFraudSightAndDeviceData() { + doReturn(fraudSightDataMock).when(testObj).createFraudSightData(cartMock, worldpayAdditionalInfoDataMock); + doReturn(Boolean.TRUE).when(testObj).isFraudSightEnabled(); + when(worldpayAdditionalInfoDataMock.getDeviceSession()).thenReturn(DEVICE_SESSION); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verify(authoriseRequestParametersCreatorMock).withFraudSightData(fraudSightDataMock); + verify(authoriseRequestParametersCreatorMock).withDeviceSession(DEVICE_SESSION); + } + + @Test + public void populateRequestWithAdditionalData_WhenFraudSightIsEnabledAndDeviceIsNull_ShouldAddFraudSight() { + doReturn(fraudSightDataMock).when(testObj).createFraudSightData(cartMock, worldpayAdditionalInfoDataMock); + when(worldpayAdditionalInfoDataMock.getDeviceSession()).thenReturn(null); + doReturn(Boolean.TRUE).when(testObj).isFraudSightEnabled(); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verify(authoriseRequestParametersCreatorMock).withFraudSightData(fraudSightDataMock); + verify(authoriseRequestParametersCreatorMock, never()).withDeviceSession(DEVICE_SESSION); + } + + @Test + public void populateRequestWithAdditionalData_WhenFraudSightIsDisabled_ShouldDoNothing() { + doReturn(Boolean.FALSE).when(testObj).isFraudSightEnabled(); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verifyZeroInteractions(authoriseRequestParametersCreatorMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaServiceTest.java similarity index 93% rename from hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaStrategyTest.java rename to hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaServiceTest.java index f3c726fa..8b211339 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaStrategyTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayKlarnaServiceTest.java @@ -1,9 +1,10 @@ package com.worldpay.service.payment.impl; +import com.worldpay.enums.lineItem.LineItemType; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.service.WorldpayUrlService; -import com.worldpay.service.model.LineItem; -import com.worldpay.service.model.OrderLines; +import com.worldpay.data.LineItem; +import com.worldpay.data.OrderLines; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.CoreAlgorithms; import de.hybris.platform.core.model.order.CartEntryModel; @@ -18,11 +19,13 @@ import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; +import java.util.List; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; @@ -33,7 +36,7 @@ @UnitTest @RunWith(MockitoJUnitRunner.class) -public class DefaultWorldpayKlarnaStrategyTest { +public class DefaultWorldpayKlarnaServiceTest { private static final String TERMS_URL = "termsURL"; private static final String SHIPPING_LINE_ITEM_REFERENCE = "SHIPPING_LINE_ITEM_REFERENCE"; @@ -50,9 +53,15 @@ public class DefaultWorldpayKlarnaStrategyTest { private static final String DELIVERY_MODE_NAME = "deliveryModeName"; private static final String PRODUCT_NAME = "productName"; private static final String UK_VAT_FULL = "uk-vat-full"; + private static final String KLARNA_1 = "klarna1"; + private static final String KLARNA_2 = " klarna2"; + private static final String KLARNA_3 = "klarna3"; + private static final String NON_KLARNA = "nonKlarna"; + + private final List klarnaPaymentMethods = List.of(KLARNA_1, KLARNA_2, KLARNA_3); @InjectMocks - private DefaultWorldpayKlarnaStrategy testObj; + private DefaultWorldpayKlarnaService testObj; @Mock private CommonI18NService commonI18NServiceMock; @@ -68,6 +77,7 @@ public class DefaultWorldpayKlarnaStrategyTest { @Before public void setUp() throws WorldpayConfigurationException { + Whitebox.setInternalState(testObj, "klarnaPayments", klarnaPaymentMethods); when(worldpayUrlServiceMock.getFullTermsUrl()).thenReturn(TERMS_URL); } @@ -98,7 +108,7 @@ public void shouldPopulateOrderLines() throws WorldpayConfigurationException { assertThat(lineItem.getTaxRate()).isEqualToIgnoringCase(EXPECTED_2000); assertThat(lineItem.getTotalTaxAmount()).isEqualToIgnoringCase("1416"); assertThat(lineItem.getTotalDiscountAmount()).isEqualToIgnoringCase("0"); - assertThat(lineItem.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.PHYSICAL); + assertThat(lineItem.getLineItemType()).isEqualTo(LineItemType.PHYSICAL); } @Test @@ -129,7 +139,7 @@ public void shouldPopulateOrderLinesAndEscapeThemForXML() throws WorldpayConfigu assertThat(lineItem.getTaxRate()).isEqualToIgnoringCase(EXPECTED_2000); assertThat(lineItem.getTotalTaxAmount()).isEqualToIgnoringCase("1416"); assertThat(lineItem.getTotalDiscountAmount()).isEqualToIgnoringCase("0"); - assertThat(lineItem.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.PHYSICAL); + assertThat(lineItem.getLineItemType()).isEqualTo(LineItemType.PHYSICAL); } @Test @@ -162,7 +172,7 @@ public void shouldPopulateOrderLinesFixedDiscountWithoutDelivery() throws Worldp assertThat(result.getOrderTaxAmount()).isEqualToIgnoringCase("966"); final LineItem lineItem = result.getLineItems().get(0); - assertThat(lineItem.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.PHYSICAL); + assertThat(lineItem.getLineItemType()).isEqualTo(LineItemType.PHYSICAL); assertThat(lineItem.getLineItemReference().getValue()).isEqualToIgnoringCase("1"); assertThat(lineItem.getName()).isEqualToIgnoringCase(PRODUCT_NAME); assertThat(lineItem.getQuantity()).isEqualToIgnoringCase("1"); @@ -173,7 +183,7 @@ public void shouldPopulateOrderLinesFixedDiscountWithoutDelivery() throws Worldp assertThat(lineItem.getTotalDiscountAmount()).isEqualToIgnoringCase("0"); final LineItem lineItemDiscount = result.getLineItems().get(1); - assertThat(lineItemDiscount.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.DISCOUNT); + assertThat(lineItemDiscount.getLineItemType()).isEqualTo(LineItemType.DISCOUNT); assertThat(lineItemDiscount.getLineItemReference().getValue()).isEqualToIgnoringCase(DISCOUNT_LINE_ITEM_REFERENCE); assertThat(lineItemDiscount.getName()).isEqualToIgnoringCase(ORDER_DISCOUNT); assertThat(lineItemDiscount.getQuantity()).isEqualToIgnoringCase("1"); @@ -194,8 +204,8 @@ public void shouldPopulateOrderLinesFixedAndPercentageDiscountDelivery() throws when(cartModelMock.getTotalTaxValues()).thenReturn(singletonList(new TaxValue(UK_VAT_FULL, 20, false, 9.66D, "GBP"))); when(cartModelMock.getTotalDiscounts()).thenReturn(10D); when(cartModelMock.getGlobalDiscountValues()).thenReturn(Arrays.asList( - new DiscountValue("dv", 10D, true, 10D, "GBP"), - new DiscountValue("dv2", 10D, false, "GBP")) + new DiscountValue("dv", 10D, true, 10D, "GBP"), + new DiscountValue("dv2", 10D, false, "GBP")) ); when(cartEntryModelMock.getOrder()).thenReturn(cartModelMock); @@ -230,7 +240,7 @@ public void shouldPopulateOrderLinesFixedAndPercentageDiscountDelivery() throws assertThat(result.getOrderTaxAmount()).isEqualToIgnoringCase("2785"); final LineItem lineItem = result.getLineItems().get(0); - assertThat(lineItem.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.PHYSICAL); + assertThat(lineItem.getLineItemType()).isEqualTo(LineItemType.PHYSICAL); assertThat(lineItem.getLineItemReference().getValue()).isEqualToIgnoringCase("0"); assertThat(lineItem.getName()).isEqualToIgnoringCase(PRODUCT_NAME_B); assertThat(lineItem.getQuantity()).isEqualToIgnoringCase("2"); @@ -241,7 +251,7 @@ public void shouldPopulateOrderLinesFixedAndPercentageDiscountDelivery() throws assertThat(lineItem.getTotalDiscountAmount()).isEqualToIgnoringCase("1699"); final LineItem lineItem2 = result.getLineItems().get(1); - assertThat(lineItem2.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.PHYSICAL); + assertThat(lineItem2.getLineItemType()).isEqualTo(LineItemType.PHYSICAL); assertThat(lineItem2.getLineItemReference().getValue()).isEqualToIgnoringCase("1"); assertThat(lineItem2.getName()).isEqualToIgnoringCase(PRODUCT_NAME_A); assertThat(lineItem2.getQuantity()).isEqualToIgnoringCase("1"); @@ -252,7 +262,7 @@ public void shouldPopulateOrderLinesFixedAndPercentageDiscountDelivery() throws assertThat(lineItem2.getTotalDiscountAmount()).isEqualToIgnoringCase("202"); final LineItem lineItemShipping = result.getLineItems().get(2); - assertThat(lineItemShipping.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.SHIPPING_FEE); + assertThat(lineItemShipping.getLineItemType()).isEqualTo(LineItemType.SHIPPING_FEE); assertThat(lineItemShipping.getLineItemReference().getValue()).isEqualToIgnoringCase(SHIPPING_LINE_ITEM_REFERENCE); assertThat(lineItemShipping.getQuantity()).isEqualToIgnoringCase("1"); assertThat(lineItemShipping.getQuantityUnit()).isEqualToIgnoringCase(SHIPPING); @@ -263,7 +273,7 @@ public void shouldPopulateOrderLinesFixedAndPercentageDiscountDelivery() throws assertThat(lineItemShipping.getTotalDiscountAmount()).isEqualToIgnoringCase("0"); final LineItem lineItemDiscount = result.getLineItems().get(3); - assertThat(lineItemDiscount.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.DISCOUNT); + assertThat(lineItemDiscount.getLineItemType()).isEqualTo(LineItemType.DISCOUNT); assertThat(lineItemDiscount.getLineItemReference().getValue()).isEqualToIgnoringCase(DISCOUNT_LINE_ITEM_REFERENCE); assertThat(lineItemDiscount.getName()).isEqualToIgnoringCase(ORDER_DISCOUNT); assertThat(lineItemDiscount.getQuantity()).isEqualToIgnoringCase("1"); @@ -303,7 +313,7 @@ public void shouldPopulateOrderLinesWithDeliveryCost() throws WorldpayConfigurat assertThat(result.getOrderTaxAmount()).isEqualToIgnoringCase("1232"); final LineItem lineItem = result.getLineItems().get(0); - assertThat(lineItem.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.PHYSICAL); + assertThat(lineItem.getLineItemType()).isEqualTo(LineItemType.PHYSICAL); assertThat(lineItem.getLineItemReference().getValue()).isEqualToIgnoringCase("0"); assertThat(lineItem.getName()).isEqualToIgnoringCase("Helmet Women TSG Lotus Graphic Designs wms Butterfly LXL"); assertThat(lineItem.getQuantity()).isEqualToIgnoringCase("1"); @@ -314,7 +324,7 @@ public void shouldPopulateOrderLinesWithDeliveryCost() throws WorldpayConfigurat assertThat(lineItem.getTotalDiscountAmount()).isEqualToIgnoringCase("0"); final LineItem lineItemShipping = result.getLineItems().get(1); - assertThat(lineItemShipping.getLineItemType()).isEqualTo(LineItem.LINE_ITEM_TYPE.SHIPPING_FEE); + assertThat(lineItemShipping.getLineItemType()).isEqualTo(LineItemType.SHIPPING_FEE); assertThat(lineItemShipping.getLineItemReference().getValue()).isEqualToIgnoringCase(SHIPPING_LINE_ITEM_REFERENCE); assertThat(lineItemShipping.getQuantity()).isEqualToIgnoringCase("1"); assertThat(lineItemShipping.getQuantityUnit()).isEqualToIgnoringCase(SHIPPING); @@ -324,4 +334,18 @@ public void shouldPopulateOrderLinesWithDeliveryCost() throws WorldpayConfigurat assertThat(lineItemShipping.getTotalTaxAmount()).isEqualToIgnoringCase("99"); assertThat(lineItemShipping.getTotalDiscountAmount()).isEqualToIgnoringCase("0"); } + + @Test + public void isKlarnaPaymentType_shouldReturnTrueWhenCodeIsInKlarnaPaymentMethodsList() { + final boolean result = testObj.isKlarnaPaymentType(KLARNA_2); + + assertThat(result).isTrue(); + } + + @Test + public void isKlarnaPaymentType_shouldReturnFalseWhenCodeIsNotInKlarnaPaymentMethodsList() { + final boolean result = testObj.isKlarnaPaymentType(NON_KLARNA); + + assertThat(result).isFalse(); + } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayLevel23DataValidatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayLevel23DataValidatorTest.java new file mode 100644 index 00000000..9d1a0e3d --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayLevel23DataValidatorTest.java @@ -0,0 +1,193 @@ +package com.worldpay.service.payment.impl; + +import com.google.common.collect.ImmutableList; +import com.worldpay.data.Amount; +import com.worldpay.data.Date; +import com.worldpay.data.Item; +import com.worldpay.data.Purchase; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayLevel23DataValidatorTest { + + private static final String INVOICE_REFERENCE_NUMBER = "invoiceReference"; + private static final String CUSTOMER_REFERENCE = "customerReference"; + private static final String CARD_ACCEPTOR_TAX_ID = "123456789"; + private static final String US_COUNTRY_CODE = "US"; + private static final String DESTINATION_POSTAL_CODE = "120125"; + private static final String PRODUCT_DESCRIPRION = "product descriprion"; + private static final String PRODUCT_CODE = "productCode"; + private static final String COMMODITY_CODE = "1234567"; + private static final String UNIT_OF_MEASURE = "pieces"; + + @InjectMocks + private DefaultWorldpayLevel23DataValidator testObj; + + @Mock + private Date orderDateMock; + @Mock + private Amount hundredAmountMock, ninetyAmountMock, tenAmountMock, dutyAmountMock, totalAmountMock, taxAmountMock; + + private Purchase purchase; + private Item item; + + @Before + public void setUp() { + item = createItem(); + purchase = createPurchase(); + } + + @Test + public void isValidLevel3Data_WhenAllFieldsAreValid_ShouldReturnTrue() { + boolean result = testObj.isValidLevel3Data(ImmutableList.of(purchase)); + + assertThat(result).isTrue(); + } + + @Test + public void isValidLevel3Data_WhenOneOfTheFieldsIsInvalid_ShouldReturnFalse() { + purchase.setCustomerReference("longCustomerReference"); + + boolean result = testObj.isValidLevel3Data(ImmutableList.of(purchase)); + + assertThat(result).isFalse(); + } + + @Test + public void isValidLevel3Data_WhenItemIsNull_ShouldReturnFalse() { + purchase.setItem(null); + + boolean result = testObj.isValidLevel3Data(ImmutableList.of(purchase)); + + assertThat(result).isFalse(); + } + + @Test + public void isValidLevel3Data_WhenItemIsInvalid_ShouldReturnFalse() { + item.setProductCode("longProductCode"); + + boolean result = testObj.isValidLevel3Data(ImmutableList.of(purchase)); + + assertThat(result).isFalse(); + } + + @Test + public void isValidLevel2Data_WhenItemIsNull_ShouldReturnTrue() { + purchase.setItem(null); + + boolean result = testObj.isValidLevel2Data(ImmutableList.of(purchase)); + + assertThat(result).isTrue(); + } + + @Test + public void isValidLevel2Data_WhenItemIsEmptyList_ShouldReturnTrue() { + purchase.setItem(Collections.emptyList()); + + boolean result = testObj.isValidLevel2Data(ImmutableList.of(purchase)); + + assertThat(result).isTrue(); + } + + @Test + public void isValidLevel2Data_WhenProductCodeInvalid_ShouldSetValueToNullAndReturnTrue() { + item.setProductCode("longProductCode"); + + boolean result = testObj.isValidLevel2Data(ImmutableList.of(purchase)); + + assertThat(result).isTrue(); + assertThat(item.getProductCode()).isNull(); + } + + @Test + public void isValidLevel2Data_WhenCommodityCodeInvalid_ShouldSetValueToNullAndReturnTrue() { + item.setCommodityCode("longCommodityCode"); + + boolean result = testObj.isValidLevel2Data(ImmutableList.of(purchase)); + + assertThat(result).isTrue(); + assertThat(item.getCommodityCode()).isNull(); + } + + @Test + public void isValidLevel2Data_WhenUnitOfMeasureInvalid_ShouldSetValueToNullAndReturnTrue() { + item.setUnitOfMeasure("longUnitOfMeasure"); + + boolean result = testObj.isValidLevel2Data(ImmutableList.of(purchase)); + + assertThat(result).isTrue(); + assertThat(item.getUnitOfMeasure()).isNull(); + } + + @Test + public void isValidLevel2Data_WhenDescriptionInvalid_ShouldReturnFalse() { + item.setDescription("reallyLongProductDescription"); + + boolean result = testObj.isValidLevel2Data(ImmutableList.of(purchase)); + + assertThat(result).isFalse(); + } + + @Test + public void isValidLevel2Data_WhenMandatoryFieldInvalid_ShouldReturnFalse() { + purchase.setCustomerReference("longCustomerReference"); + + boolean result = testObj.isValidLevel2Data(ImmutableList.of(purchase)); + + assertThat(result).isFalse(); + } + + @Test + public void isValidLevel2Data_WhenDestinationPostcodeInvalid_ShouldSetValueToNullAndReturnTrue() { + purchase.setDestinationPostalCode("longPostalCode"); + + boolean result = testObj.isValidLevel2Data(ImmutableList.of(purchase)); + + assertThat(result).isTrue(); + assertThat(purchase.getDestinationPostalCode()).isNull(); + } + + private Item createItem() { + final Item item = new Item(); + item.setDescription(PRODUCT_DESCRIPRION); + item.setProductCode(PRODUCT_CODE); + item.setQuantity("1"); + item.setCommodityCode(COMMODITY_CODE); + item.setUnitOfMeasure(UNIT_OF_MEASURE); + item.setItemTotal(hundredAmountMock); + item.setItemTotalWithTax(totalAmountMock); + item.setItemDiscountAmount(tenAmountMock); + item.setTaxAmount(taxAmountMock); + + return item; + } + + private Purchase createPurchase() { + final Purchase purchase = new Purchase(); + purchase.setInvoiceReferenceNumber(INVOICE_REFERENCE_NUMBER); + purchase.setCustomerReference(CUSTOMER_REFERENCE); + purchase.setCardAcceptorTaxId(CARD_ACCEPTOR_TAX_ID); + purchase.setDestinationCountryCode(US_COUNTRY_CODE); + purchase.setDestinationPostalCode(DESTINATION_POSTAL_CODE); + purchase.setTaxExempt(false); + purchase.setSalesTax(hundredAmountMock); + purchase.setDiscountAmount(tenAmountMock); + purchase.setShippingAmount(ninetyAmountMock); + purchase.setDutyAmount(dutyAmountMock); + purchase.setOrderDate(orderDateMock); + purchase.setItem(ImmutableList.of(item)); + + return purchase; + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayLevel23StrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayLevel23StrategyTest.java new file mode 100644 index 00000000..4ec877cc --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayLevel23StrategyTest.java @@ -0,0 +1,296 @@ +package com.worldpay.service.payment.impl; + +import com.google.common.collect.ImmutableList; +import com.worldpay.model.WorldpayMerchantConfigurationModel; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.data.*; +import com.worldpay.service.payment.WorldpayLevel23DataValidator; +import com.worldpay.service.payment.WorldpayOrderService; +import com.worldpay.service.request.AuthoriseRequestParameters; +import com.worldpay.strategy.WorldpayMerchantStrategy; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.basecommerce.model.site.BaseSiteModel; +import de.hybris.platform.core.model.c2l.CurrencyModel; +import de.hybris.platform.core.model.order.AbstractOrderEntryModel; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.product.ProductModel; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.util.DiscountValue; +import de.hybris.platform.util.TaxValue; +import org.apache.commons.lang3.NotImplementedException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Answers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Calendar; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayLevel23StrategyTest { + + private static final double TEN_DOUBLE_VALUE = 10d; + private static final double HUNDRED_DOUBLE_VALUE = 100d; + private static final String CARD_ACCEPTOR_TAX_ID = "123456789"; + private static final String US_COUNTRY_CODE = "US"; + private static final String DESTINATION_POSTAL_CODE = "120125"; + private static final String PRODUCT_CODE = "productCode"; + private static final String COMMODITY_CODE = "1234567"; + private static final String UNIT_OF_MEASURE = "pieces"; + private static final java.util.Date ORDER_DATE_VALUE = new java.util.Date(1990, Calendar.MAY, 17); + + @Spy + @InjectMocks + private DefaultWorldpayLevel23Strategy testObj; + + @Mock + private WorldpayMerchantStrategy worldpayMerchantStrategyMock; + @Mock + private WorldpayLevel23DataValidator worldpayLevel23DataValidatorMock; + @Mock + private WorldpayOrderService worldpayOrderService; + + @Mock + private AbstractOrderModel cartMock; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private AddressModel addressMock; + @Mock + private BaseSiteModel baseSiteMock; + @Mock + private ProductModel productMock; + @Mock + private Amount hundredAmountMock, ninetyAmountMock, tenAmountMock; + @Mock + private WorldpayMerchantConfigurationModel merchantMock; + @Mock + private CurrencyModel currencyMock; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private AbstractOrderEntryModel entryMock; + @Mock + private TaxValue taxValueMock; + @Mock + private DiscountValue discountValueMock; + @Mock + private AuthoriseRequestParameters.AuthoriseRequestParametersCreator authoriseRequestParametersCreatorMock; + @Mock + private WorldpayAdditionalInfoData worldpayAdditionalInfoDataMock; + @Mock + private BranchSpecificExtension level23DataMock; + @Mock + private Purchase purchaseMock; + + private List purchaseList; + + @Before + public void setUp() { + purchaseList = ImmutableList.of(purchaseMock); + + setUpCart(); + setUpCartEntry(); + + when(level23DataMock.getPurchase()).thenReturn(purchaseList); + when(cartMock.getSite()).thenReturn(baseSiteMock); + when(baseSiteMock.getEnableLevel2()).thenReturn(true); + when(baseSiteMock.getEnableLevel3()).thenReturn(true); + when(worldpayMerchantStrategyMock.getMerchant()).thenReturn(merchantMock); + when(merchantMock.getCardAcceptorTaxID()).thenReturn(CARD_ACCEPTOR_TAX_ID); + + when(worldpayOrderService.createAmount(currencyMock, HUNDRED_DOUBLE_VALUE)).thenReturn(hundredAmountMock); + when(worldpayOrderService.createAmount(currencyMock, TEN_DOUBLE_VALUE)).thenReturn(tenAmountMock); + when(worldpayOrderService.createAmount(currencyMock, 0d)).thenReturn(ninetyAmountMock); + when(worldpayOrderService.createAmount(currencyMock, 90d)).thenReturn(ninetyAmountMock); + } + + @Test + public void populateRequestWithAdditionalData_WhenLevel23Disabled_ShouldDoNothing() { + doNothing().when(testObj).setCustomerReference(any(), any()); + doNothing().when(testObj).setProductDescription(any(), any()); + doNothing().when(testObj).setDutyAmount(any(), any()); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verify(worldpayLevel23DataValidatorMock, never()).isValidLevel3Data(purchaseList); + verify(worldpayLevel23DataValidatorMock, never()).isValidLevel2Data(purchaseList); + verify(authoriseRequestParametersCreatorMock, never()).withLevel23Data(level23DataMock); + } + + @Test + public void populateRequestWithAdditionalData_WhenLevel3EnabledAndValidData_ShouldSetLevel3Data() { + doReturn(true).when(testObj).isLevel2Enabled(cartMock); + doReturn(level23DataMock).when(testObj).createLevel23Data(cartMock); + + doNothing().when(testObj).setCustomerReference(any(), any()); + doNothing().when(testObj).setProductDescription(any(), any()); + doNothing().when(testObj).setDutyAmount(any(), any()); + when(worldpayLevel23DataValidatorMock.isValidLevel3Data(purchaseList)).thenReturn(true); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verify(worldpayLevel23DataValidatorMock, never()).isValidLevel2Data(purchaseList); + verify(authoriseRequestParametersCreatorMock).withLevel23Data(level23DataMock); + } + + @Test + public void populateRequestWithAdditionalData_WhenLevel3EnabledAndInValidData_ShouldSetLevel2Data() { + doReturn(true).when(testObj).isLevel3Enabled(cartMock); + doReturn(level23DataMock).when(testObj).createLevel23Data(cartMock); + + doNothing().when(testObj).setCustomerReference(any(), any()); + doNothing().when(testObj).setProductDescription(any(), any()); + doNothing().when(testObj).setDutyAmount(any(), any()); + when(worldpayLevel23DataValidatorMock.isValidLevel3Data(purchaseList)).thenReturn(false); + when(worldpayLevel23DataValidatorMock.isValidLevel2Data(purchaseList)).thenReturn(true); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verify(authoriseRequestParametersCreatorMock).withLevel23Data(level23DataMock); + } + + @Test + public void isLevel2Enabled_WhenFlagIsSetToFalse_ShouldReturnFalse() { + when(baseSiteMock.getEnableLevel2()).thenReturn(false); + + boolean result = testObj.isLevel2Enabled(cartMock); + + assertThat(result).isFalse(); + } + + @Test + public void isLevel2Enabled_WhenFlagIsSetToTrueAndAddressIsNotUSorCA_ShouldReturnFalse() { + when(addressMock.getCountry().getIsocode()).thenReturn("UK"); + + boolean result = testObj.isLevel2Enabled(cartMock); + + assertThat(result).isFalse(); + } + + @Test + public void isLevel2Enabled_WhenAddressIsNull_ShouldReturnFalse() { + when(cartMock.getPaymentAddress()).thenReturn(null); + + boolean result = testObj.isLevel2Enabled(cartMock); + + assertThat(result).isFalse(); + } + + + @Test + public void isLevel2Enabled_WhenFlagIsSetToTrueAndAddressUS_ShouldReturnTrue() { + boolean result = testObj.isLevel2Enabled(cartMock); + + assertThat(result).isTrue(); + } + + @Test + public void isLevel3Enabled_WhenFlagIsSetToFalse_ShouldReturnFalse() { + when(baseSiteMock.getEnableLevel3()).thenReturn(false); + + boolean result = testObj.isLevel3Enabled(cartMock); + + assertThat(result).isFalse(); + } + + @Test + public void isLevel3Enabled_WhenFlagIsSetToTrueAndAddressIsNotUSorCA_ShouldReturnFalse() { + when(addressMock.getCountry().getIsocode()).thenReturn("UK"); + + boolean result = testObj.isLevel3Enabled(cartMock); + + assertThat(result).isFalse(); + } + + @Test + public void isLevel3Enabled_WhenFlagIsSetToTrueAndAddressUS_ShouldReturnTrue() { + boolean result = testObj.isLevel3Enabled(cartMock); + + assertThat(result).isTrue(); + } + + @Test(expected = NotImplementedException.class) + public void setCustomerReference_ShouldThrowException() { + testObj.setCustomerReference(eq(cartMock), any(Purchase.class)); + } + + @Test(expected = NotImplementedException.class) + public void setDutyAmount_ShouldThrowException() { + testObj.setDutyAmount(eq(cartMock), any(Purchase.class)); + } + + @Test(expected = NotImplementedException.class) + public void setProductDescription_ShouldThrowException() { + testObj.setProductDescription(eq(productMock), any(Item.class)); + } + + @Test(expected = IllegalArgumentException.class) + public void createLevel23Data_WhenCartIsNull_ShouldThrowException() { + testObj.createLevel23Data(null); + } + + @Test + public void createLevel23Data_WhenCartIsNotNull_ShouldCreateBranchSpecific() { + doNothing().when(testObj).setCustomerReference(any(), any()); + doNothing().when(testObj).setProductDescription(any(), any()); + doNothing().when(testObj).setDutyAmount(any(), any()); + + final BranchSpecificExtension result = testObj.createLevel23Data(cartMock); + + assertThat(result.getPurchase().size()).isEqualTo(1); + final Purchase purchase = result.getPurchase().get(0); + assertThat(purchase.getSalesTax()).isEqualTo(hundredAmountMock); + assertThat(purchase.getDiscountAmount()).isEqualTo(tenAmountMock); + assertThat(purchase.getShippingAmount()).isEqualTo(ninetyAmountMock); + assertThat(purchase.getCardAcceptorTaxId()).isEqualTo(CARD_ACCEPTOR_TAX_ID); + assertThat(purchase.getDestinationPostalCode()).isEqualTo(DESTINATION_POSTAL_CODE); + assertThat(purchase.getDestinationCountryCode()).isEqualTo(US_COUNTRY_CODE); + + assertThat(purchase.getItem().size()).isEqualTo(1); + final Item item = purchase.getItem().get(0); + assertThat(item.getProductCode()).isEqualTo(PRODUCT_CODE); + assertThat(item.getCommodityCode()).isEqualTo(COMMODITY_CODE); + assertThat(item.getQuantity()).isEqualTo("1"); + assertThat(item.getUnitOfMeasure()).isEqualTo(UNIT_OF_MEASURE); + + assertThat(item.getUnitCost()).isEqualTo(hundredAmountMock); + assertThat(item.getItemTotalWithTax()).isEqualTo(hundredAmountMock); + assertThat(item.getTaxAmount()).isEqualTo(tenAmountMock); + assertThat(item.getItemTotal()).isEqualTo(ninetyAmountMock); + assertThat(item.getItemDiscountAmount()).isEqualTo(tenAmountMock); + } + + private void setUpCart() { + when(cartMock.getCurrency()).thenReturn(currencyMock); + when(cartMock.getTotalTax()).thenReturn(HUNDRED_DOUBLE_VALUE); + when(cartMock.getTotalDiscounts()).thenReturn(TEN_DOUBLE_VALUE); + when(cartMock.getDeliveryCost()).thenReturn(0d); + when(cartMock.getDate()).thenReturn(ORDER_DATE_VALUE); + when(cartMock.getEntries()).thenReturn(ImmutableList.of(entryMock)); + when(cartMock.getDeliveryAddress()).thenReturn(addressMock); + when(cartMock.getPaymentAddress()).thenReturn(addressMock); + when(addressMock.getCountry().getIsocode()).thenReturn(US_COUNTRY_CODE); + when(addressMock.getPostalcode()).thenReturn(DESTINATION_POSTAL_CODE); + } + + private void setUpCartEntry() { + when(entryMock.getProduct()).thenReturn(productMock); + when(productMock.getCode()).thenReturn(PRODUCT_CODE); + when(productMock.getCommodityCode()).thenReturn(COMMODITY_CODE); + when(entryMock.getQuantity()).thenReturn(1L); + when(entryMock.getBasePrice()).thenReturn(HUNDRED_DOUBLE_VALUE); + when(entryMock.getUnit().getCode()).thenReturn(UNIT_OF_MEASURE); + when(entryMock.getTotalPrice()).thenReturn(HUNDRED_DOUBLE_VALUE); + when(entryMock.getTaxValues()).thenReturn(ImmutableList.of(taxValueMock)); + when(taxValueMock.getAppliedValue()).thenReturn(TEN_DOUBLE_VALUE); + when(entryMock.getDiscountValues()).thenReturn(ImmutableList.of(discountValueMock)); + when(discountValueMock.getAppliedValue()).thenReturn(TEN_DOUBLE_VALUE); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayOrderServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayOrderServiceTest.java index c2efc771..9ea64c96 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayOrderServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayOrderServiceTest.java @@ -1,18 +1,18 @@ package com.worldpay.service.payment.impl; import com.worldpay.core.services.strategies.RecurringGenerateMerchantTransactionCodeStrategy; +import com.worldpay.data.Amount; import com.worldpay.data.ApplePayAdditionalAuthInfo; import com.worldpay.data.ApplePayHeader; +import com.worldpay.data.BasicOrderInfo; +import com.worldpay.data.applepay.ApplePay; +import com.worldpay.data.klarna.KlarnaPayment; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.Header; -import com.worldpay.klarna.WorldpayKlarnaUtils; import com.worldpay.service.WorldpayUrlService; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.BasicOrderInfo; -import com.worldpay.service.model.applepay.ApplePay; -import com.worldpay.service.model.klarna.KlarnaPayment; import com.worldpay.service.model.payment.PaymentType; +import com.worldpay.service.payment.WorldpayKlarnaService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.commerceservices.order.CommerceCheckoutService; import de.hybris.platform.commerceservices.service.data.CommerceCheckoutParameter; @@ -21,6 +21,7 @@ import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; +import de.hybris.platform.servicelayer.dto.converter.Converter; import de.hybris.platform.servicelayer.i18n.CommonI18NService; import org.junit.Before; import org.junit.Test; @@ -28,7 +29,6 @@ import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import java.math.BigDecimal; @@ -51,7 +51,7 @@ public class DefaultWorldpayOrderServiceTest { private static final String WORLDPAY_ORDER_CODE = "worldpayOrderCode"; private static final String ORDER_DESCRIPTION = "orderDescription"; private static final String GBP = "GBP"; - private static final String COUNTRY_CODE = "countryCode"; + private static final String COUNTRY_CODE = "GB"; private static final String EXTRA_DATA = "extraData"; private static final String EPHEMERAL_PUBLIC_KEY = "ephemeralPublicKey"; private static final String PUBLIC_KEY_HASH = "publicKeyHash"; @@ -72,7 +72,6 @@ public class DefaultWorldpayOrderServiceTest { private static final String PAYMENT_PROVIDER = "paymentProvider"; @InjectMocks - @Spy private DefaultWorldpayOrderService testObj; @Mock @@ -80,11 +79,13 @@ public class DefaultWorldpayOrderServiceTest { @Mock private WorldpayUrlService worldpayUrlServiceMock; @Mock - private WorldpayKlarnaUtils worldpayKlarnaPaymentsMock; + private WorldpayKlarnaService worldpayKlarnaServiceMock; @Mock private CommerceCheckoutService commerceCheckoutServiceMock; @Mock private RecurringGenerateMerchantTransactionCodeStrategy recurringGenerateMerchantTransactionCodeStrategyMock; + @Mock + Converter internalHeaderConverter; @Mock private CurrencyModel currencyModelMock; @@ -100,16 +101,15 @@ public class DefaultWorldpayOrderServiceTest { @Mock private LanguageModel languageMock; @Mock - private CommerceCheckoutParameter commerceCheckoutParameterMock; + private Header internalHeaderMock; @Before public void setUp() throws Exception { - testObj = new DefaultWorldpayOrderService(commonI18NServiceMock, worldpayUrlServiceMock, worldpayKlarnaPaymentsMock, commerceCheckoutServiceMock, recurringGenerateMerchantTransactionCodeStrategyMock); - when(worldpayKlarnaPaymentsMock.isKlarnaPaymentType(KLARNA_SSL)).thenReturn(true); - when(worldpayKlarnaPaymentsMock.isKlarnaPaymentType(KLARNA_SLICE_IT_SSL)).thenReturn(true); - when(worldpayKlarnaPaymentsMock.isKlarnaPaymentType(KLARNA_PAYNOW_SSL)).thenReturn(true); - when(worldpayKlarnaPaymentsMock.isKlarnaPaymentType(KLARNA_PAYLATER_SSL)).thenReturn(true); - when(commonI18NServiceMock.getLocaleForLanguage(languageMock)).thenReturn(Locale.UK); + when(worldpayKlarnaServiceMock.isKlarnaPaymentType(KLARNA_SSL)).thenReturn(true); + when(worldpayKlarnaServiceMock.isKlarnaPaymentType(KLARNA_SLICE_IT_SSL)).thenReturn(true); + when(worldpayKlarnaServiceMock.isKlarnaPaymentType(KLARNA_PAYNOW_SSL)).thenReturn(true); + when(worldpayKlarnaServiceMock.isKlarnaPaymentType(KLARNA_PAYLATER_SSL)).thenReturn(true); + when(commonI18NServiceMock.getLocaleForLanguage(languageMock)).thenReturn(Locale.ENGLISH); } @Test @@ -184,7 +184,7 @@ public void createKlarnaPayment_shouldCreateKlarnaPayment_WhenKlarnaPayNowPaymen final KlarnaPayment result = (KlarnaPayment) testObj.createKlarnaPayment(COUNTRY_CODE, languageMock, EXTRA_DATA, KLARNA_PAYNOW_SSL); - assertEquals(PaymentType.KLARNAPAYNOWSSL, result.getPaymentType()); + assertEquals(PaymentType.KLARNAPAYNOWSSL.getMethodCode(), result.getPaymentType()); assertEquals(EXTRA_DATA, result.getExtraMerchantData()); assertEquals(SUCCESS_URL, result.getSuccessURL()); assertEquals(PENDING_URL, result.getPendingURL()); @@ -202,7 +202,7 @@ public void createKlarnaPayment_shouldCreateKlarnaPayment_WhenKlarnaSliceITPayme final KlarnaPayment result = (KlarnaPayment) testObj.createKlarnaPayment(COUNTRY_CODE, languageMock, EXTRA_DATA, KLARNA_SLICE_IT_SSL); - assertEquals(PaymentType.KLARNASLICESSL, result.getPaymentType()); + assertEquals(PaymentType.KLARNASLICESSL.getMethodCode(), result.getPaymentType()); assertEquals(EXTRA_DATA, result.getExtraMerchantData()); assertEquals(SUCCESS_URL, result.getSuccessURL()); assertEquals(PENDING_URL, result.getPendingURL()); @@ -220,7 +220,7 @@ public void createKlarnaPayment_shouldCreateKlarnaPayment_WhenKlarnaPayLaterPaym final KlarnaPayment result = (KlarnaPayment) testObj.createKlarnaPayment(COUNTRY_CODE, languageMock, EXTRA_DATA, KLARNA_PAYLATER_SSL); - assertEquals(PaymentType.KLARNAPAYLATERSSL, result.getPaymentType()); + assertEquals(PaymentType.KLARNAPAYLATERSSL.getMethodCode(), result.getPaymentType()); assertEquals(EXTRA_DATA, result.getExtraMerchantData()); assertEquals(SUCCESS_URL, result.getSuccessURL()); assertEquals(PENDING_URL, result.getPendingURL()); @@ -238,9 +238,9 @@ public void createKlarnaPayment_shouldCreateKlarnaPayment_WhenKlarnaSSLPaymentIs final KlarnaPayment result = (KlarnaPayment) testObj.createKlarnaPayment(COUNTRY_CODE, languageMock, EXTRA_DATA, KLARNA_SSL); - assertEquals(PaymentType.KLARNASSL, result.getPaymentType()); + assertEquals(PaymentType.KLARNASSL.getMethodCode(), result.getPaymentType()); assertEquals(COUNTRY_CODE, result.getPurchaseCountry()); - assertEquals(Locale.UK.toLanguageTag(), result.getShopperLocale()); + assertEquals("en-GB", result.getShopperLocale()); assertEquals(KLARNA_CHECKOUT_URL, result.getMerchantUrls().getCheckoutURL()); assertEquals(KLARNA_CONFIRMATION_URL, result.getMerchantUrls().getConfirmationURL()); assertEquals(EXTRA_DATA, result.getExtraMerchantData()); @@ -264,6 +264,8 @@ public void createKlarnaPayment_shouldThrowWorldpayConfigurationException_WhenNU @Test public void shouldCreateApplePayPayment() throws WorldpayModelTransformationException { + + final ApplePayHeader applePayHeader = new ApplePayHeader(); applePayHeader.setEphemeralPublicKey(EPHEMERAL_PUBLIC_KEY); applePayHeader.setPublicKeyHash(PUBLIC_KEY_HASH); @@ -280,7 +282,13 @@ public void shouldCreateApplePayPayment() throws WorldpayModelTransformationExce assertThat(result.getData()).isEqualTo(DATA); assertThat(result.getSignature()).isEqualTo(SIGNATURE); assertThat(result.getVersion()).isEqualTo(VERSION); - final Header header = (Header) result.getHeader().transformToInternalModel(); + + when(internalHeaderConverter.convert(result.getHeader())).thenReturn(internalHeaderMock); + when(internalHeaderMock.getEphemeralPublicKey()).thenReturn(EPHEMERAL_PUBLIC_KEY); + when(internalHeaderMock.getPublicKeyHash()).thenReturn(PUBLIC_KEY_HASH); + when(internalHeaderMock.getTransactionId()).thenReturn(TRANSACTION_ID); + + final Header header = internalHeaderConverter.convert(result.getHeader()); assertThat(header.getEphemeralPublicKey()).isEqualTo(EPHEMERAL_PUBLIC_KEY); assertThat(header.getPublicKeyHash()).isEqualTo(PUBLIC_KEY_HASH); assertThat(header.getTransactionId()).isEqualTo(TRANSACTION_ID); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayPrimeRoutingStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayPrimeRoutingStrategyTest.java new file mode 100644 index 00000000..06e383ee --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayPrimeRoutingStrategyTest.java @@ -0,0 +1,51 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.core.services.WorldpayPrimeRoutingService; +import com.worldpay.enums.PaymentAction; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.core.model.order.CartModel; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.verify; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpayPrimeRoutingStrategyTest { + + @InjectMocks + private DefaultWorldpayPrimeRoutingStrategy testObj; + + @Mock + private WorldpayPrimeRoutingService worldpayPrimeRoutingServiceMock; + + @Mock + private CartModel cartMock; + @Mock + private AuthoriseRequestParametersCreator authoriseRequestParametersCreatorMock; + @Mock + private WorldpayAdditionalInfoData worldpayAdditionalInfoDataMock; + + @Test + public void populateRequestWithAdditionalData_WhenPrimeRoutingIsDisabled_ShouldDoNothing() { + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verifyZeroInteractions(authoriseRequestParametersCreatorMock); + verify(worldpayPrimeRoutingServiceMock, never()).setAuthorisedWithPrimeRoutingOnCart(cartMock); + } + + @Test + public void populateRequestWithAdditionalData_WhenPrimeRoutingIsEnabled_ShouldSetSaleAction() { + when(worldpayPrimeRoutingServiceMock.isPrimeRoutingEnabled(cartMock)).thenReturn(Boolean.TRUE); + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreatorMock); + + verify(authoriseRequestParametersCreatorMock).withPaymentDetailsAction(PaymentAction.SALE); + verify(worldpayPrimeRoutingServiceMock).setAuthorisedWithPrimeRoutingOnCart(cartMock); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayRedirectOrderServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayRedirectOrderServiceTest.java index cc9e9272..de1b521b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayRedirectOrderServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayRedirectOrderServiceTest.java @@ -1,5 +1,6 @@ package com.worldpay.service.payment.impl; +import com.worldpay.core.services.WorldpayCartService; import com.worldpay.core.services.WorldpayPaymentInfoService; import com.worldpay.data.AdditionalAuthInfo; import com.worldpay.enums.order.AuthorisedStatus; @@ -7,12 +8,11 @@ import com.worldpay.hostedorderpage.data.RedirectAuthoriseResult; import com.worldpay.order.data.WorldpayAdditionalInfoData; import com.worldpay.service.hop.WorldpayHOPPService; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.BasicOrderInfo; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.BasicOrderInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.payment.WorldpayOrderService; import com.worldpay.service.payment.WorldpayTokenEventReferenceCreationStrategy; -import com.worldpay.strategy.WorldpayAuthenticatedShopperIdStrategy; import com.worldpay.transaction.WorldpayPaymentTransactionService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.acceleratorservices.payment.data.PaymentData; @@ -79,7 +79,7 @@ public class DefaultWorldpayRedirectOrderServiceTest { @Mock private WorldpayPaymentInfoService worldpayPaymentInfoServiceMock; @Mock - private WorldpayAuthenticatedShopperIdStrategy worldpayAuthenticatedShopperIdStrategyMock; + private WorldpayCartService worldpayCartServiceMock; @Mock private WorldpayTokenEventReferenceCreationStrategy worldpayTokenEventReferenceCreationStrategyMock; @Mock @@ -107,7 +107,7 @@ public void setUp() throws WorldpayException { when(worldpayOrderServiceMock.createBasicOrderInfo(eq(WORLDPAY_ORDER_CODE), eq(WORLDPAY_ORDER_CODE), any(Amount.class))).thenReturn(basicOrderInfoMock); when(worldpayPaymentInfoServiceMock.createPaymentInfo(cartModelMock)).thenReturn(paymentInfoModelMock); - when(worldpayAuthenticatedShopperIdStrategyMock.getAuthenticatedShopperId(customerModelMock)).thenReturn(AUTHENTICATED_SHOPPER_ID); + when(worldpayCartServiceMock.getAuthenticatedShopperId(cartModelMock)).thenReturn(AUTHENTICATED_SHOPPER_ID); when(worldpayTokenEventReferenceCreationStrategyMock.createTokenEventReference()).thenReturn(TOKEN_EVENT_REFERENCE); when(worldpayOrderServiceMock.createCheckoutParameterAndSetPaymentInfo(paymentInfoModelMock, bigDecimalMock, cartModelMock)).thenReturn(commerceCheckoutParameterMock); when(cartModelMock.getPaymentInfo()).thenReturn(paymentInfoModelMock); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayRiskDataServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayRiskDataServiceTest.java index 9c804594..4023bc6b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayRiskDataServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpayRiskDataServiceTest.java @@ -1,7 +1,7 @@ package com.worldpay.service.payment.impl; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.threeds2.RiskData; +import com.worldpay.data.threeds2.RiskData; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.order.CartModel; import org.junit.Test; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpaySepaMandateStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpaySepaMandateStrategyTest.java new file mode 100644 index 00000000..a5fa4737 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/impl/DefaultWorldpaySepaMandateStrategyTest.java @@ -0,0 +1,86 @@ +package com.worldpay.service.payment.impl; + +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.service.model.payment.PaymentType; +import com.worldpay.service.request.AuthoriseRequestParameters; +import com.worldpay.service.request.AuthoriseRequestParameters.AuthoriseRequestParametersCreator; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class DefaultWorldpaySepaMandateStrategyTest { + + private static final String MANDATE_TYPE = "ONE-OFF"; + + @InjectMocks + private DefaultWorldpaySepaMandateStrategy testObj; + + @Mock + private AbstractOrderModel cartMock; + @Mock + private WorldpayAdditionalInfoData worldpayAdditionalInfoDataMock; + + private List listWithSEPAPayment = List.of(PaymentType.SEPA); + private List listWithoutSEPAPayment = List.of(PaymentType.SOFORT); + private List listWitNullModelClass = List.of(PaymentType.ONLINE); + + @Test + public void populateRequestWithAdditionalData_WhenGetIncludedPTsIsNull_ShouldNotPopulateMandateType() { + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + .withIncludedPTs(null); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreator); + + assertThat(authoriseRequestParametersCreator.build().getMandateType()).isNull(); + } + + @Test + public void populateRequestWithAdditionalData_WhenGetIncludedPTsIsEmpty_ShouldNotPopulateMandateType() { + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + .withIncludedPTs(List.of()); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreator); + + assertThat(authoriseRequestParametersCreator.build().getMandateType()).isNull(); + } + + @Test + public void populateRequestWithAdditionalData_WhenIsNotSEPAAPM_ShouldNotPopulateMandateType() { + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + .withIncludedPTs(listWithoutSEPAPayment); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreator); + + assertThat(authoriseRequestParametersCreator.build().getMandateType()).isNull(); + } + + @Test + public void populateRequestWithAdditionalData_WhenPaymentTypeModelClassIsNull_ShouldNotPopulateMandateType() { + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + .withIncludedPTs(listWitNullModelClass); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreator); + + assertThat(authoriseRequestParametersCreator.build().getMandateType()).isNull(); + } + + @Test + public void populateRequestWithAdditionalData_WhenIsSEPAAPM_ShouldPopulateMandateType() { + final AuthoriseRequestParametersCreator authoriseRequestParametersCreator = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + .withIncludedPTs(listWithSEPAPayment); + + testObj.populateRequestWithAdditionalData(cartMock, worldpayAdditionalInfoDataMock, authoriseRequestParametersCreator); + + assertThat(authoriseRequestParametersCreator.build().getMandateType()).isEqualTo(MANDATE_TYPE); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestFactoryTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestFactoryTest.java index 9e06dd3e..50971326 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestFactoryTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestFactoryTest.java @@ -1,32 +1,31 @@ package com.worldpay.service.payment.request.impl; +import com.worldpay.core.services.WorldpayCartService; import com.worldpay.data.*; +import com.worldpay.data.applepay.ApplePay; +import com.worldpay.data.payment.Cse; +import com.worldpay.data.payment.PayWithGoogleSSL; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.threeds2.RiskData; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.Token; +import com.worldpay.data.token.TokenRequest; import com.worldpay.enums.order.DynamicInteractionType; import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; import com.worldpay.enums.payment.storedCredentials.Usage; import com.worldpay.exception.WorldpayConfigurationException; import com.worldpay.exception.WorldpayException; -import com.worldpay.klarna.WorldpayKlarnaUtils; import com.worldpay.order.data.WorldpayAdditionalInfoData; -import com.worldpay.service.model.*; -import com.worldpay.service.model.applepay.ApplePay; -import com.worldpay.service.model.payment.*; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.threeds2.RiskData; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.Token; -import com.worldpay.service.model.token.TokenRequest; -import com.worldpay.service.payment.WorldpayKlarnaStrategy; -import com.worldpay.service.payment.WorldpayOrderService; -import com.worldpay.service.payment.WorldpayRiskDataService; -import com.worldpay.service.payment.WorldpayTokenEventReferenceCreationStrategy; +import com.worldpay.service.model.payment.PaymentType; +import com.worldpay.service.payment.*; import com.worldpay.service.payment.request.WorldpayRequestService; import com.worldpay.service.request.AuthoriseRequestParameters; import com.worldpay.service.request.DirectAuthoriseServiceRequest; import com.worldpay.service.request.RedirectAuthoriseServiceRequest; import com.worldpay.service.request.SecondThreeDSecurePaymentRequest; import com.worldpay.service.response.CreateTokenResponse; -import com.worldpay.strategy.WorldpayAuthenticatedShopperIdStrategy; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.c2l.CurrencyModel; import de.hybris.platform.core.model.c2l.LanguageModel; @@ -47,7 +46,8 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; @@ -81,6 +81,7 @@ public class DefaultWorldpayRequestFactoryTest { private static final String TRANSACTION_IDENTIFIER = "transactionIdentifier"; private static final String INSTALLATION_ID = "installationId"; private static final String KLARNA_SSL = "KLARNA-SSL"; + private static final String DEVICE_SESSION_ID = "device_session_id"; @Spy @InjectMocks @@ -91,15 +92,15 @@ public class DefaultWorldpayRequestFactoryTest { @Mock private WorldpayOrderService worldpayOrderServiceMock; @Mock - private WorldpayKlarnaStrategy worldpayKlarnaStrategyMock; + private WorldpayKlarnaService worldpayKlarnaServiceMock; @Mock private WorldpayRiskDataService worldpayRiskDataServiceMock; @Mock - private WorldpayAuthenticatedShopperIdStrategy worldpayAuthenticatedShopperIdStrategyMock; - @Mock - private WorldpayKlarnaUtils worldpayKlarnaUtilsMock; + private WorldpayCartService worldpayCartServiceMock; @Mock private WorldpayRequestService worldpayRequestServiceMock; + @Mock + private WorldpayAdditionalRequestDataService worldpayAdditionalRequestDataServiceMock; @Mock private MerchantInfo merchantInfoMock; @@ -219,16 +220,19 @@ public void setUp() throws WorldpayException { when(worldpayRequestServiceMock.createAdditional3DSData(worldpayAdditionalInfoDataMock)).thenReturn(additional3DSDataMock); when(worldpayOrderServiceMock.createCsePayment(cseAdditionalAuthInfoMock, billingAddressMock)).thenReturn(csePaymentMock); when(worldpayRequestServiceMock.createStoredCredentials(Usage.USED, null, null)).thenReturn(storedCredentialsMock); - when(worldpayRequestServiceMock.getBillingAddress(cartModelMock, cseAdditionalAuthInfoMock)).thenReturn(billingAddressMock); - when(worldpayRequestServiceMock.getBillingAddress(cartModelMock, additionalAuthInfoMock)).thenReturn(billingAddressMock); - when(worldpayRequestServiceMock.getEmailForCustomer(customerModelMock)).thenReturn(SHOPPER_EMAIL_ADDRESS); - when(worldpayRequestServiceMock.getAddressFromCart(cartModelMock, true)).thenReturn(shippingAddressMock); - when(worldpayRequestServiceMock.getAddressFromCart(abstractOrderModelMock, true)).thenReturn(shippingAddressMock); - when(worldpayRequestServiceMock.getAddressFromCart(cartModelMock, false)).thenReturn(billingAddressMock); - when(worldpayRequestServiceMock.getAddressFromCart(abstractOrderModelMock, false)).thenReturn(billingAddressMock); + when(worldpayCartServiceMock.getBillingAddress(cartModelMock, cseAdditionalAuthInfoMock)).thenReturn(billingAddressMock); + when(worldpayCartServiceMock.getBillingAddress(cartModelMock, additionalAuthInfoMock)).thenReturn(billingAddressMock); + when(worldpayCartServiceMock.getEmailForCustomer(cartModelMock)).thenReturn(SHOPPER_EMAIL_ADDRESS); + when(worldpayCartServiceMock.getAddressFromCart(cartModelMock, true)).thenReturn(shippingAddressMock); + when(worldpayCartServiceMock.getAddressFromCart(abstractOrderModelMock, true)).thenReturn(shippingAddressMock); + when(worldpayCartServiceMock.getAddressFromCart(cartModelMock, false)).thenReturn(billingAddressMock); + when(worldpayCartServiceMock.getAddressFromCart(abstractOrderModelMock, false)).thenReturn(billingAddressMock); when(worldpayRequestServiceMock.getDynamicInteractionType(worldpayAdditionalInfoDataMock)).thenReturn(DynamicInteractionType.ECOMMERCE); when(worldpayRequestServiceMock.createCardDetails(cseAdditionalAuthInfoMock, paymentAddressModelMock)).thenReturn(cartDetailsMock); when(createTokenResponseMock.getToken().getTokenDetails().getPaymentTokenID()).thenReturn(PAYMENT_TOKEN_ID); + + doNothing().when(worldpayAdditionalRequestDataServiceMock).populateDirectRequestAdditionalData(eq(cartModelMock), any(), eq(authoriseRequestParametersCreatorMock)); + doNothing().when(worldpayAdditionalRequestDataServiceMock).populateRedirectRequestAdditionalData(eq(cartModelMock), any(), eq(authoriseRequestParametersCreatorMock)); } @Test @@ -253,7 +257,7 @@ public void shouldUseBillingAddressWhenNoShippingAddress() { // User has selecte @Test public void buildTokenRequest_ShouldUseShippingAsBilling_WhenUsingShippingAsBillingFlagIsTrue() { when(cseAdditionalAuthInfoMock.getUsingShippingAsBilling()).thenReturn(true); - when(worldpayRequestServiceMock.getBillingAddress(cartModelMock, cseAdditionalAuthInfoMock)).thenReturn(shippingAddressMock); + when(worldpayCartServiceMock.getBillingAddress(cartModelMock, cseAdditionalAuthInfoMock)).thenReturn(shippingAddressMock); doReturn(directTokenisedAuthoriseServiceRequestMock).when(testObj).createTokenisedDirectAuthoriseRequest(getAuthoriseRequestParameters()); testObj.buildTokenRequest(merchantInfoMock, cartModelMock, cseAdditionalAuthInfoMock, worldpayAdditionalInfoDataMock); @@ -262,12 +266,49 @@ public void buildTokenRequest_ShouldUseShippingAsBilling_WhenUsingShippingAsBill } @Test - public void shouldCreateTokenisedDirectAuthoriseRequest() { - doReturn(directTokenisedAuthoriseServiceRequestMock).when(testObj).createTokenisedDirectAuthoriseRequest(Mockito.any(AuthoriseRequestParameters.class)); + public void buildDirectAuthoriseRequestWithTokenForCSE_WhenItIsCalledAndCurrentSiteFsIsEnabled_ShouldCreateTokenisedDirectAuthoriseRequest() { + when(cseAdditionalAuthInfoMock.getStatementNarrative()).thenReturn(STATEMENT_NARRATIVE); + when(worldpayRequestServiceMock.createStoredCredentials(Usage.FIRST, null, null)).thenReturn(storedCredentialsMock); + when(worldpayRequestServiceMock.createAdditional3DSData(worldpayAdditionalInfoDataMock)).thenReturn(additional3DSDataMock); + when(worldpayRiskDataServiceMock.createRiskData(cartModelMock, worldpayAdditionalInfoDataMock)).thenReturn(riskDataMock); + when(cseAdditionalAuthInfoMock.getSaveCard()).thenReturn(true); + when(worldpayAdditionalInfoDataMock.getDeviceSession()).thenReturn(DEVICE_SESSION_ID); final DirectAuthoriseServiceRequest result = testObj.buildDirectAuthoriseRequestWithTokenForCSE(merchantInfoMock, cartModelMock, worldpayAdditionalInfoDataMock); - assertThat(result).isEqualTo(directTokenisedAuthoriseServiceRequestMock); + verify(testObj).createTokenisedDirectAuthoriseRequest(authoriseRequestParametersArgumentCaptor.capture()); + final AuthoriseRequestParameters requestParameters = authoriseRequestParametersArgumentCaptor.getValue(); + assertEquals(merchantInfoMock, result.getMerchantInfo()); + assertEquals(basicOrderInfoMock, requestParameters.getOrderInfo()); + assertEquals(tokenMock, requestParameters.getPayment()); + assertEquals(shopperMock, requestParameters.getShopper()); + assertEquals(shippingAddressMock, requestParameters.getShippingAddress()); + assertEquals(DynamicInteractionType.ECOMMERCE, requestParameters.getDynamicInteractionType()); + assertEquals(additional3DSDataMock, requestParameters.getAdditional3DSData()); + assertEquals(riskDataMock, requestParameters.getRiskData()); + } + + @Test + public void buildDirectAuthoriseRequestWithTokenForCSE_WhenItIsCalledAndCurrentSiteFSIsDisabled_ShouldReturnADirectAuthoriseServiceRequest() { + when(cseAdditionalAuthInfoMock.getStatementNarrative()).thenReturn(STATEMENT_NARRATIVE); + when(worldpayRequestServiceMock.createStoredCredentials(Usage.FIRST, null, null)).thenReturn(storedCredentialsMock); + when(worldpayRequestServiceMock.createAdditional3DSData(worldpayAdditionalInfoDataMock)).thenReturn(additional3DSDataMock); + when(worldpayRiskDataServiceMock.createRiskData(cartModelMock, worldpayAdditionalInfoDataMock)).thenReturn(riskDataMock); + when(cseAdditionalAuthInfoMock.getSaveCard()).thenReturn(true); + when(worldpayAdditionalInfoDataMock.getDeviceSession()).thenReturn(DEVICE_SESSION_ID); + + testObj.buildDirectAuthoriseRequestWithTokenForCSE(merchantInfoMock, cartModelMock, worldpayAdditionalInfoDataMock); + + verify(testObj).createTokenisedDirectAuthoriseRequest(authoriseRequestParametersArgumentCaptor.capture()); + final AuthoriseRequestParameters requestParameters = authoriseRequestParametersArgumentCaptor.getValue(); + assertEquals(merchantInfoMock, requestParameters.getMerchantInfo()); + assertEquals(basicOrderInfoMock, requestParameters.getOrderInfo()); + assertEquals(tokenMock, requestParameters.getPayment()); + assertEquals(shopperMock, requestParameters.getShopper()); + assertEquals(shippingAddressMock, requestParameters.getShippingAddress()); + assertEquals(DynamicInteractionType.ECOMMERCE, requestParameters.getDynamicInteractionType()); + assertEquals(additional3DSDataMock, requestParameters.getAdditional3DSData()); + assertEquals(riskDataMock, requestParameters.getRiskData()); } @Test @@ -311,7 +352,7 @@ public void shouldCreateDirectAuthoriseKlarnaRequest() throws WorldpayConfigurat when(billingAddressMock.getCountryCode()).thenReturn(COUNTRY_CODE); when(customerModelMock.getSessionLanguage()).thenReturn(languageModelMock); when(additionalAuthInfoMock.getStatementNarrative()).thenReturn(STATEMENT_NARRATIVE); - when(worldpayKlarnaStrategyMock.createOrderLines(cartModelMock)).thenReturn(orderLinesMock); + when(worldpayKlarnaServiceMock.createOrderLines(cartModelMock)).thenReturn(orderLinesMock); doReturn(directAuthoriseServiceRequestMock).when(testObj).createKlarnaDirectAuthoriseRequest(Mockito.any(AuthoriseRequestParameters.class)); @@ -395,10 +436,10 @@ public void buildTokenDeleteRequest_ShouldCreateDeleteTokenRequest() { } @Test - public void buildDirectAuthoriseRecurringPayment_shouldCreateAuthoriseRecurringPaymentRequest_WhenDynamicIntereactionTypeIsCommerce() { + public void buildDirectAuthoriseRecurringPayment_WhenDynamicIntereactionTypeIsCommerceAndFSEnabled_ShouldCreateAuthoriseRecurringPaymentRequestAndSetDeviceSession() { when(worldpayRequestServiceMock.getDynamicInteractionType(worldpayAdditionalInfoDataMock)).thenReturn(DynamicInteractionType.ECOMMERCE); - testObj.buildDirectAuthoriseRecurringPayment(merchantInfoMock, abstractOrderModelMock, worldpayAdditionalInfoDataMock); + testObj.buildDirectAuthoriseRecurringPayment(merchantInfoMock, cartModelMock, worldpayAdditionalInfoDataMock); verify(testObj).createTokenisedDirectAuthoriseRequest(authoriseRequestParametersArgumentCaptor.capture()); final AuthoriseRequestParameters requestParameters = authoriseRequestParametersArgumentCaptor.getValue(); @@ -411,13 +452,14 @@ public void buildDirectAuthoriseRecurringPayment_shouldCreateAuthoriseRecurringP assertNull(requestParameters.getStatementNarrative()); assertEquals(additional3DSDataMock, requestParameters.getAdditional3DSData()); assertEquals(storedCredentialsMock, requestParameters.getStoredCredentials()); + } @Test - public void buildDirectAuthoriseRecurringPayment_shouldCreateAuthoriseRecurringPaymentRequest_WhenDynamicIntereactionTypeIsMoto() { + public void buildDirectAuthoriseRecurringPayment_WhenDynamicIntereactionTypeIsMotoAndFSDisabled_ShouldCreateAuthoriseRecurringPaymentRequestAndNotSetDeviceSession() { when(worldpayRequestServiceMock.getDynamicInteractionType(worldpayAdditionalInfoDataMock)).thenReturn(DynamicInteractionType.MOTO); - testObj.buildDirectAuthoriseRecurringPayment(merchantInfoMock, abstractOrderModelMock, worldpayAdditionalInfoDataMock); + testObj.buildDirectAuthoriseRecurringPayment(merchantInfoMock, cartModelMock, worldpayAdditionalInfoDataMock); verify(testObj).createTokenisedDirectAuthoriseRequest(authoriseRequestParametersArgumentCaptor.capture()); final AuthoriseRequestParameters requestParameters = authoriseRequestParametersArgumentCaptor.getValue(); @@ -430,14 +472,15 @@ public void buildDirectAuthoriseRecurringPayment_shouldCreateAuthoriseRecurringP assertNull(requestParameters.getStatementNarrative()); assertEquals(additional3DSDataMock, requestParameters.getAdditional3DSData()); assertEquals(storedCredentialsMock, requestParameters.getStoredCredentials()); + assertNull(requestParameters.getAction()); } @Test - public void buildDirectAuthoriseRecurringPayment_shouldCreateAuthoriseRecurringPaymentRequest_WhenDynamicIntereactionTypeIsRecurring() { + public void buildDirectAuthoriseRecurringPayment_shouldCreateAuthoriseRecurringPaymentRequest_WhenDynamicInteractionTypeIsRecurring() { when(worldpayRequestServiceMock.getDynamicInteractionType(worldpayAdditionalInfoDataMock)).thenReturn(DynamicInteractionType.RECURRING); when(worldpayRequestServiceMock.createStoredCredentials(Usage.USED, MerchantInitiatedReason.RECURRING, TRANSACTION_IDENTIFIER)).thenReturn(storedCredentialsMock); - testObj.buildDirectAuthoriseRecurringPayment(merchantInfoMock, abstractOrderModelMock, worldpayAdditionalInfoDataMock); + testObj.buildDirectAuthoriseRecurringPayment(merchantInfoMock, cartModelMock, worldpayAdditionalInfoDataMock); verify(testObj).createTokenisedDirectAuthoriseRequest(authoriseRequestParametersArgumentCaptor.capture()); final AuthoriseRequestParameters requestParameters = authoriseRequestParametersArgumentCaptor.getValue(); @@ -450,6 +493,7 @@ public void buildDirectAuthoriseRecurringPayment_shouldCreateAuthoriseRecurringP assertNull(requestParameters.getStatementNarrative()); assertEquals(additional3DSDataMock, requestParameters.getAdditional3DSData()); assertEquals(storedCredentialsMock, requestParameters.getStoredCredentials()); + assertNull(requestParameters.getAction()); } @Test @@ -467,12 +511,13 @@ public void testBuildSecondThreeDSecurePaymentRequest() { } @Test - public void buildDirectAuthoriseRequestWithToken_ShouldReturnADirectAuthoriseServiceRequest_WhenItIsCalled() { + public void buildDirectAuthoriseRequestWithToken_WhenItIsCalledAndCurrentSite_ShouldReturnADirectAuthoriseServiceRequestAndNotSetDeviceSession() { when(cseAdditionalAuthInfoMock.getStatementNarrative()).thenReturn(STATEMENT_NARRATIVE); when(worldpayRequestServiceMock.createStoredCredentials(Usage.FIRST, null, null)).thenReturn(storedCredentialsMock); when(worldpayRequestServiceMock.createAdditional3DSData(worldpayAdditionalInfoDataMock)).thenReturn(additional3DSDataMock); when(worldpayRiskDataServiceMock.createRiskData(cartModelMock, worldpayAdditionalInfoDataMock)).thenReturn(riskDataMock); when(cseAdditionalAuthInfoMock.getSaveCard()).thenReturn(true); + when(worldpayAdditionalInfoDataMock.getDeviceSession()).thenReturn(DEVICE_SESSION_ID); testObj.buildDirectTokenAndAuthorise(merchantInfoMock, cartModelMock, worldpayAdditionalInfoDataMock, cseAdditionalAuthInfoMock); @@ -494,14 +539,14 @@ public void buildDirectAuthoriseRequestWithToken_ShouldReturnADirectAuthoriseSer } @Test - public void buildRedirectAuthoriseRequest_ShouldReturnADirectAuthoriseServiceRequestWithStoredCredentials_WhenThePaymentMethodsIsRequestedToBeSaved() throws WorldpayConfigurationException { + public void buildRedirectAuthoriseRequest_WhenThePaymentMethodsIsRequestedToBeSaved_ShouldReturnADirectAuthoriseServiceRequestWithStoredCredentials() throws WorldpayConfigurationException { doReturn(redirectAuthoriseRequestMock).when(testObj).createRedirectAuthoriseRequest(any(AuthoriseRequestParameters.class)); doReturn(includedPTsMock).when(testObj).getIncludedPaymentTypeList(additionalAuthInfoMock); when(additionalAuthInfoMock.getSaveCard()).thenReturn(Boolean.TRUE); when(additionalAuthInfoMock.getInstallationId()).thenReturn(INSTALLATION_ID); when(worldpayRequestServiceMock.createStoredCredentials(Usage.FIRST, null, null)).thenReturn(storedCredentialsMock); when(customerModelMock.getContactEmail()).thenReturn(SHOPPER_EMAIL_ADDRESS); - when(worldpayAuthenticatedShopperIdStrategyMock.getAuthenticatedShopperId(customerModelMock)).thenReturn(AUTHENTICATED_SHOPPER_ID); + when(worldpayCartServiceMock.getAuthenticatedShopperId(cartModelMock)).thenReturn(AUTHENTICATED_SHOPPER_ID); when(worldpayRequestServiceMock.createAuthenticatedShopper(SHOPPER_EMAIL_ADDRESS, AUTHENTICATED_SHOPPER_ID, null, null)).thenReturn(shopperWithoutSessionNorBrowserMock); testObj.buildRedirectAuthoriseRequest(merchantInfoMock, cartModelMock, additionalAuthInfoMock, worldpayAdditionalInfoDataMock); @@ -522,28 +567,7 @@ public void buildRedirectAuthoriseRequest_ShouldReturnADirectAuthoriseServiceReq } @Test - public void buildRedirectAuthoriseRequest_ShouldIncludePaymentAttributes_WhenPaymentMethodIsPaypalExpress() throws WorldpayConfigurationException { - doReturn(redirectAuthoriseRequestMock).when(testObj).createRedirectAuthoriseRequest(any(AuthoriseRequestParameters.class)); - doReturn(includedPTsMock).when(testObj).getIncludedPaymentTypeList(additionalAuthInfoMock); - when(additionalAuthInfoMock.getSaveCard()).thenReturn(Boolean.TRUE); - when(additionalAuthInfoMock.getInstallationId()).thenReturn(INSTALLATION_ID); - when(additionalAuthInfoMock.getPaymentMethod()).thenReturn(PaymentType.PAYPAL.getMethodCode()); - - testObj.buildRedirectAuthoriseRequest(merchantInfoMock, cartModelMock, additionalAuthInfoMock, worldpayAdditionalInfoDataMock); - - verify(testObj).createRedirectAuthoriseRequest(authoriseRequestParametersArgumentCaptor.capture()); - final AuthoriseRequestParameters requestParameters = authoriseRequestParametersArgumentCaptor.getValue(); - - assertThat(requestParameters.getPaymentMethodAttributes()).isNotEmpty(); - assertThat(requestParameters.getStoredCredentials()).isNull(); - final PaymentMethodAttribute paymentMethodAttribute = requestParameters.getPaymentMethodAttributes().get(0); - assertThat(paymentMethodAttribute.getAttrName()).isEqualTo("firstInBillingRun"); - assertThat(paymentMethodAttribute.getAttrValue()).isEqualTo("true"); - assertThat(paymentMethodAttribute.getPaymentMethod()).isEqualTo("PAYPAL-EXPRESS"); - } - - @Test - public void buildRedirectAuthoriseRequest_ShouldNotIncludePaymentAttributes_WhenPaymentMethodIsNotPaypalExpress() throws WorldpayConfigurationException { + public void buildRedirectAuthoriseRequest_WhenPaymentMethodIsNotPaypalExpressAnd_ShouldNotIncludePaymentAttributes() throws WorldpayConfigurationException { doReturn(redirectAuthoriseRequestMock).when(testObj).createRedirectAuthoriseRequest(any(AuthoriseRequestParameters.class)); doReturn(includedPTsMock).when(testObj).getIncludedPaymentTypeList(additionalAuthInfoMock); when(additionalAuthInfoMock.getSaveCard()).thenReturn(Boolean.TRUE); @@ -559,7 +583,7 @@ public void buildRedirectAuthoriseRequest_ShouldNotIncludePaymentAttributes_When } @Test - public void buildRedirectAuthoriseRequest_ShouldReturnADirectAuthoriseServiceRequestWithoutStoredCredentials_WhenThePaymentMethodsIsNotRequestedToBeSaved() throws WorldpayConfigurationException { + public void buildRedirectAuthoriseRequest_WhenThePaymentMethodsIsNotRequestedToBeSaved_ShouldReturnADirectAuthoriseServiceRequestWithoutStoredCredentials() throws WorldpayConfigurationException { doReturn(includedPTsMock).when(testObj).getIncludedPaymentTypeList(additionalAuthInfoMock); when(worldpayRequestServiceMock.createStoredCredentials(Usage.FIRST, null, null)).thenReturn(storedCredentialsMock); when(worldpayRequestServiceMock.createShopper(SHOPPER_EMAIL_ADDRESS, null, null)).thenReturn(shopperMock); @@ -610,7 +634,7 @@ public void internalGetRedirectAuthoriseServiceRequestForKlarna_ShouldReturnRedi when(billingAddressMock.getCountryCode()).thenReturn(COUNTRY_CODE); when(customerModelMock.getSessionLanguage()).thenReturn(languageModelMock); when(additionalAuthInfoMock.getStatementNarrative()).thenReturn(STATEMENT_NARRATIVE); - when(worldpayKlarnaStrategyMock.createOrderLines(cartModelMock)).thenReturn(orderLinesMock); + when(worldpayKlarnaServiceMock.createOrderLines(cartModelMock)).thenReturn(orderLinesMock); doReturn(authoriseRequestParametersCreatorMock).when(authoriseRequestParametersCreatorMock).withPayment(paymentMock); doReturn(authoriseRequestParametersCreatorMock).when(authoriseRequestParametersCreatorMock).withShopper(shopperMock); doReturn(authoriseRequestParametersCreatorMock).when(authoriseRequestParametersCreatorMock).withStatementNarrative(STATEMENT_NARRATIVE); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestServiceTest.java index 8a85daac..e9ec4aaa 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/payment/request/impl/DefaultWorldpayRequestServiceTest.java @@ -1,8 +1,15 @@ package com.worldpay.service.payment.request.impl; -import com.worldpay.data.Additional3DS2Info; -import com.worldpay.data.AdditionalAuthInfo; -import com.worldpay.data.CSEAdditionalAuthInfo; +import com.worldpay.core.services.WorldpayCartService; +import com.worldpay.data.*; +import com.worldpay.data.payment.AlternativeShopperBankCodePayment; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.threeds2.Additional3DSData; +import com.worldpay.data.token.CardDetails; +import com.worldpay.data.token.CardTokenRequest; +import com.worldpay.data.token.Token; +import com.worldpay.data.token.TokenRequest; import com.worldpay.enums.payment.storedCredentials.MerchantInitiatedReason; import com.worldpay.enums.payment.storedCredentials.Usage; import com.worldpay.exception.WorldpayConfigurationException; @@ -10,28 +17,16 @@ import com.worldpay.service.WorldpayUrlService; import com.worldpay.service.hop.WorldpayOrderCodeVerificationService; import com.worldpay.service.interaction.WorldpayDynamicInteractionResolverService; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.AlternativeShopperBankCodePayment; -import com.worldpay.service.model.payment.Payment; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.model.threeds2.Additional3DSData; -import com.worldpay.service.model.token.CardDetails; -import com.worldpay.service.model.token.CardTokenRequest; -import com.worldpay.service.model.token.Token; -import com.worldpay.service.model.token.TokenRequest; import com.worldpay.service.request.CreateTokenServiceRequest; import com.worldpay.service.request.UpdateTokenServiceRequest; -import com.worldpay.strategy.WorldpayDeliveryAddressStrategy; import com.worldpay.threedsecureflexenums.ChallengePreferenceEnum; import com.worldpay.threedsecureflexenums.ChallengeWindowSizeEnum; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.acceleratorservices.config.SiteConfigService; -import de.hybris.platform.commerceservices.customer.CustomerEmailResolutionService; import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.user.AddressModel; -import de.hybris.platform.core.model.user.CustomerModel; import org.apache.commons.beanutils.ConversionException; import org.junit.Before; import org.junit.Test; @@ -40,7 +35,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import org.springframework.core.convert.converter.Converter; import java.security.GeneralSecurityException; @@ -52,7 +46,8 @@ @RunWith(MockitoJUnitRunner.class) public class DefaultWorldpayRequestServiceTest { - private static final String ENCRYPTED_ORDER_CODE = "3X3iuAV11xoMZ4zwq3XVwnlix1azTk1quCFCXgAv11s18enqCl4="; + private static final String ENCRYPTED_ORDER_CODE = "/wLfcHcPCWk6BOmSxLh/fPlCjxTSrdDxd1dE205/D+1AyLJ9AWs="; + private static final String ENCODED_ORDER_CODE = "%2FwLfcHcPCWk6BOmSxLh%2FfPlCjxTSrdDxd1dE205%2FD%2B1AyLJ9AWs%3D"; private static final String REFERENCE_ID = "referenceId"; private static final String WINDOW_SIZE = "390x400"; private static final String NO_PREFERENCE = "noPreference"; @@ -82,15 +77,11 @@ public class DefaultWorldpayRequestServiceTest { @Mock private SiteConfigService siteConfigServiceMock; @Mock - private Converter worldpayAddressConverterMock; - @Mock - private WorldpayDeliveryAddressStrategy worldpayDeliveryAddressStrategyMock; - @Mock private WorldpayDynamicInteractionResolverService worldpayDynamicInteractionResolverServiceMock; @Mock - private CustomerEmailResolutionService customerEmailResolutionServiceMock; - @Mock private WorldpayOrderCodeVerificationService worldpayOrderCodeVerificationServiceMock; + @Mock + private WorldpayCartService worldpayCartServiceMock; @Mock private WorldpayAdditionalInfoData worldpayAdditionalInfoDataMock; @@ -103,8 +94,6 @@ public class DefaultWorldpayRequestServiceTest { @Mock private Additional3DS2Info additional3DS2InfoMock; @Mock - private AdditionalAuthInfo additionalAuthInfoMock; - @Mock private CSEAdditionalAuthInfo cseAdditionalAuthInfoMock; @Mock private Session sessionMock; @@ -113,24 +102,21 @@ public class DefaultWorldpayRequestServiceTest { @Mock(answer = Answers.RETURNS_DEEP_STUBS) private AbstractOrderModel abstractOrderModelMock; @Mock - private CustomerModel customerMock; + private CartModel cartMock; @Mock - private AddressModel deliveryAddressMock, paymentAddressMock; + private AddressModel paymentAddressMock; @Mock private Address addressMock; @Mock - private CartModel cartMock; - @Mock private Payment paymentMock; @Before public void setUp() { when(siteConfigServiceMock.getBoolean(WORLDPAY_MERCHANT_TOKEN_ENABLED, false)).thenReturn(true); - when(worldpayAddressConverterMock.convert(deliveryAddressMock)).thenReturn(addressMock); - when(worldpayAddressConverterMock.convert(paymentAddressMock)).thenReturn(addressMock); when(cseAdditionalAuthInfoMock.getExpiryMonth()).thenReturn(EXPIRY_MONTH); when(cseAdditionalAuthInfoMock.getExpiryYear()).thenReturn(EXPIRY_YEAR); when(cseAdditionalAuthInfoMock.getCardHolderName()).thenReturn(CARD_HOLDER_NAME); + when(worldpayCartServiceMock.convertAddressModelToAddress(paymentAddressMock)).thenReturn(addressMock); } @Test @@ -150,8 +136,8 @@ public void createBankPayment_shouldCreatePaymentForIdealSSL() throws WorldpayCo final AlternativeShopperBankCodePayment result = (AlternativeShopperBankCodePayment) testObj.createBankPayment(WORLDPAY_ORDER_CODE, "IDEAL-SSL", BANK_CODE); assertEquals(BANK_CODE, result.getShopperBankCode()); - assertEquals(PaymentType.IDEAL, result.getPaymentType()); - assertEquals(FULL_SUCCESS_URL + "?orderId=" + ENCRYPTED_ORDER_CODE, result.getSuccessURL()); + assertEquals(PaymentType.IDEAL.getMethodCode(), result.getPaymentType()); + assertEquals(FULL_SUCCESS_URL + "?orderId=" + ENCODED_ORDER_CODE, result.getSuccessURL()); } @Test(expected = ConversionException.class) @@ -260,7 +246,6 @@ public void shouldCreateTokenRequestWithoutTokenReasonWithShopperScope() { assertThat(result.isMerchantToken()).isFalse(); } - @Test public void shouldCreateUpdateTokenServiceRequestWithShopperScope() { when(siteConfigServiceMock.getBoolean(WORLDPAY_MERCHANT_TOKEN_ENABLED, false)).thenReturn(false); @@ -289,7 +274,6 @@ public void shouldCreateTokenForDeletionWithShopperScope() { assertThat(result.isMerchantToken()).isFalse(); } - @Test public void shouldCreateAdditional3DSData() { when(worldpayAdditionalInfoDataMock.getAdditional3DS2()).thenReturn(additional3DS2InfoMock); @@ -300,12 +284,12 @@ public void shouldCreateAdditional3DSData() { final Additional3DSData result = testObj.createAdditional3DSData(worldpayAdditionalInfoDataMock); assertThat(result.getDfReferenceId()).isEqualTo(REFERENCE_ID); - assertThat(result.getChallengeWindowSize()).isEqualTo(ChallengeWindowSizeEnum.getEnum(WINDOW_SIZE)); - assertThat(result.getChallengePreference()).isEqualTo(ChallengePreferenceEnum.getEnum(NO_PREFERENCE)); + assertThat(result.getChallengeWindowSize()).isEqualTo(ChallengeWindowSizeEnum.R_390_400.toString()); + assertThat(result.getChallengePreference()).isEqualTo(ChallengePreferenceEnum.NO_PREFERENCE.toString()); } @Test - public void shouldCreateAdditional3DSDataEvenIfWithChallengePreferenceAsEmptyBeingNoPreferenceAsDefault() { + public void shouldCreateAdditional3DSDataEvenIfWithChallengeWindowSizeAsEmptyBeing390x400AsDefault() { when(worldpayAdditionalInfoDataMock.getAdditional3DS2()).thenReturn(additional3DS2InfoMock); when(additional3DS2InfoMock.getDfReferenceId()).thenReturn(REFERENCE_ID); when(additional3DS2InfoMock.getChallengeWindowSize()).thenReturn(null); @@ -314,7 +298,7 @@ public void shouldCreateAdditional3DSDataEvenIfWithChallengePreferenceAsEmptyBei final Additional3DSData result = testObj.createAdditional3DSData(worldpayAdditionalInfoDataMock); assertThat(result.getDfReferenceId()).isEqualTo(REFERENCE_ID); - assertThat(result.getChallengeWindowSize()).isEqualTo(ChallengeWindowSizeEnum.getEnum(WINDOW_SIZE)); + assertThat(result.getChallengeWindowSize()).isEqualTo(ChallengeWindowSizeEnum.R_390_400.toString()); assertThat(result.getChallengePreference()).isNull(); } @@ -341,7 +325,7 @@ public void createStoreCredentials_ShouldCreateAStoredCredentials_WhenOnlyUsageP } @Test(expected = IllegalArgumentException.class) - public void createStoreCredentials_ShouldThrowAnIlegalArgumentException_WhenUsageArgumentIsNull() { + public void createStoreCredentials_ShouldThrowAnIllegalArgumentException_WhenUsageArgumentIsNull() { testObj.createStoredCredentials(null, null, null); } @@ -352,62 +336,6 @@ public void getDynamicInteractionType_ShouldReturnDynamicInteractionType() { verify(worldpayDynamicInteractionResolverServiceMock).resolveInteractionTypeForDirectIntegration(worldpayAdditionalInfoDataMock); } - @Test - public void getEmailForCustomer_ShouldReturnCustomerEmail() { - testObj.getEmailForCustomer(customerMock); - - verify(customerEmailResolutionServiceMock).getEmailForCustomer(customerMock); - } - - @Test - public void getAddressFromCart_WhenIsDeliveryAddressTrue_ShouldReturnDeliveryAddress() { - when(worldpayDeliveryAddressStrategyMock.getDeliveryAddress(abstractOrderModelMock)).thenReturn(deliveryAddressMock); - - final Address result = testObj.getAddressFromCart(abstractOrderModelMock, true); - - assertThat(result).isEqualTo(addressMock); - } - - @Test - public void getAddressFromCart_WhenIsDeliveryAddressFalse_ShouldReturnPaymentAddress() { - when(abstractOrderModelMock.getPaymentAddress()).thenReturn(paymentAddressMock); - - final Address result = testObj.getAddressFromCart(abstractOrderModelMock, false); - - assertThat(result).isEqualTo(addressMock); - } - - @Test - public void getBillingAddress_WhenUsingShippingAsBilling_ShouldReturnBillingAddress() { - when(cartMock.getDeliveryAddress()).thenReturn(deliveryAddressMock); - when(additionalAuthInfoMock.getUsingShippingAsBilling()).thenReturn(Boolean.TRUE); - - final Address result = testObj.getBillingAddress(cartMock, additionalAuthInfoMock); - - assertThat(result).isEqualTo(addressMock); - } - - @Test - public void getBillingAddress_WhenUsingShippingAsBillingFalse_ShouldReturnPaymentAddress() { - when(cartMock.getDeliveryAddress()).thenReturn(deliveryAddressMock); - when(cartMock.getPaymentAddress()).thenReturn(paymentAddressMock); - when(additionalAuthInfoMock.getUsingShippingAsBilling()).thenReturn(Boolean.FALSE); - - final Address result = testObj.getBillingAddress(cartMock, additionalAuthInfoMock); - - assertThat(result).isEqualTo(addressMock); - } - - @Test - public void getBillingAddress_WhenNoPaymentOrDeliveryAddress_ShouldReturnNull() { - when(cartMock.getDeliveryAddress()).thenReturn(null); - when(cartMock.getPaymentAddress()).thenReturn(null); - - final Address result = testObj.getBillingAddress(cartMock, additionalAuthInfoMock); - - assertThat(result).isNull(); - } - @Test public void createToken_ShouldReturnTokenObject() { final Token result = testObj.createToken("subscriptionId", "securityCode"); @@ -434,7 +362,6 @@ public void createCardDetails_WhenAddressIsNull() { assertThat(result.getExpiryDate().getMonth()).isEqualTo(EXPIRY_MONTH); assertThat(result.getExpiryDate().getYear()).isEqualTo(EXPIRY_YEAR); assertThat(result.getCardAddress()).isNull(); - verifyZeroInteractions(worldpayAddressConverterMock); } @Test diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/KlarnaOrderInquiryServiceRequestTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/KlarnaOrderInquiryServiceRequestTest.java index 8e121316..4132777b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/KlarnaOrderInquiryServiceRequestTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/KlarnaOrderInquiryServiceRequestTest.java @@ -1,7 +1,8 @@ package com.worldpay.service.request; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -13,19 +14,28 @@ public class KlarnaOrderInquiryServiceRequestTest { private static final String MERCHANT_CODE = "merchantCode"; private static final String MERCHANT_PASSWORD = "merchantPassword"; - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo(MERCHANT_CODE, MERCHANT_PASSWORD); + private MerchantInfo merchantInfo; private static final String ORDER_CODE = "orderCode"; @Rule @SuppressWarnings("PMD.MemberScope") public ExpectedException expectedException = ExpectedException.none(); + @Before + public void setUp() throws Exception { + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantCode(MERCHANT_CODE); + merchantInfo.setMerchantCode(MERCHANT_PASSWORD); + this.merchantInfo = merchantInfo; + } + @Test public void testOrderInquiry() { - final KlarnaOrderInquiryServiceRequest request = KlarnaOrderInquiryServiceRequest.createKlarnaOrderInquiryRequest(MERCHANT_INFO, ORDER_CODE); - assertEquals(MERCHANT_INFO, request.getMerchantInfo()); + final KlarnaOrderInquiryServiceRequest request = KlarnaOrderInquiryServiceRequest.createKlarnaOrderInquiryRequest(merchantInfo, ORDER_CODE); + + assertEquals(merchantInfo, request.getMerchantInfo()); assertEquals(ORDER_CODE, request.getOrderCode()); } @@ -40,6 +50,6 @@ public void createOrderInquiryRequestShouldRaiseIllegalArgumentExceptionWhenMerc public void createOrderInquiryRequestShouldRaiseIllegalArgumentExceptionWhenOrderCodeIsNull() { expectedException.expect(IllegalArgumentException.class); - OrderInquiryServiceRequest.createOrderInquiryRequest(MERCHANT_INFO, null); + OrderInquiryServiceRequest.createOrderInquiryRequest(merchantInfo, null); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/OrderBuilderTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/OrderBuilderTest.java index b06bfd70..79c92ffc 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/OrderBuilderTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/OrderBuilderTest.java @@ -1,15 +1,17 @@ package com.worldpay.service.request; +import com.worldpay.data.*; +import com.worldpay.data.payment.Cse; +import com.worldpay.data.payment.Payment; +import com.worldpay.data.payment.StoredCredentials; +import com.worldpay.data.token.TokenRequest; import com.worldpay.enums.order.DynamicInteractionType; -import com.worldpay.service.model.*; -import com.worldpay.service.model.payment.Cse; -import com.worldpay.service.model.payment.Payment; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.payment.StoredCredentials; -import com.worldpay.service.model.token.TokenRequest; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; @@ -32,26 +34,105 @@ public class OrderBuilderTest { private static final String ENCRYPTED_DATA = "encryptedData"; private static final List INCLUDED_PAYMENT_TYPES = singletonList(ONLINE); private static final List EXCLUDED_PAYMENT_TYPES = singletonList(VISA); - private static final TokenRequest TOKEN_REQUEST = new TokenRequest("tokenEventReferenceNumber", "tokenReason"); - private static final Address SHIPPING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - private static final Address BILLING_ADDRESS = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); + private static final List INCLUDED_PAYMENT_TYPES_METHOD = singletonList(ONLINE.getMethodCode()); + private static final List EXCLUDED_PAYMENT_TYPES_METHOD = singletonList(VISA.getMethodCode()); + private static final String TOKEN_EVENT_REFERENCE = "tokenEventReferenceNumber"; + private static final String TOKEN_REASON = "tokenReason"; + private static final String FIRST_NAME = "John"; + private static final String LAST_NAME = "Shopper"; + private static final String SHOPPER_ADDRESS_1 = "Shopper Address1"; + private static final String SHOPPER_ADDRESS_2 = "Shopper Address2"; + private static final String SHOPPER_ADDRESS_3 = "Shopper Address3"; + private static final String POSTAL_CODE = "postalCode"; + private static final String CITY = "city"; + private static final String GB = "GB"; private static final String SESSION_ID = "sessionId"; private static final String SHOPPER_IP_ADDRESS = "shopperIPAddress"; - private static final Session SESSION = new Session(SHOPPER_IP_ADDRESS, SESSION_ID); - private static final Shopper SHOPPER = new Shopper(EMAIL_ADDRESS, null, null, SESSION); - private static final Amount AMOUNT = new Amount("100", "EUR", "2"); - private static final Payment PAYMENT = new Cse(ENCRYPTED_DATA, SHIPPING_ADDRESS); + private Payment payment; private static final StoredCredentials STORED_CREDENTIALS = new StoredCredentials(); private static final String ORDER_DESC = "Your Order & Order desc"; - private static final BasicOrderInfo BASIC_ORDER_INFO = new BasicOrderInfo(ORDER_CODE, ORDER_DESC, AMOUNT); private static final DynamicInteractionType DYNAMIC_INTERACTION_TYPE = DynamicInteractionType.ECOMMERCE; - private static final PaymentDetails PAYMENT_DETAILS = new PaymentDetails(PAYMENT, SESSION, STORED_CREDENTIALS); + private PaymentDetails paymentDetails; private static final String ECHO_DATA = "echoData"; private static final LineItem LINE_ITEM = new LineItem(); private static final String ORDER_TAX_AMOUNT = "orderTaxAmount"; private static final String TERMS_URL = "termsUrl"; - private static final OrderLines ORDER_LINES = new OrderLines(ORDER_TAX_AMOUNT, TERMS_URL, List.of(LINE_ITEM)); + private OrderLines orderLines; private static final List PAYMENT_METHOD_ATTRIBUTES = List.of(new PaymentMethodAttribute()); + private TokenRequest tokenRequest; + private Address shippingAddress; + private Address billingAddress; + private Session session; + private Shopper shopper; + private Amount amount; + private BasicOrderInfo basicOrderInfo; + private static final String MANDATE_TYPE = "mandateType"; + + @Mock + private FraudSightData fraudSightDataMock; + @Mock + private BranchSpecificExtension level23DataMock; + + @Before + public void setUp() throws Exception { + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setTokenEventReference(TOKEN_EVENT_REFERENCE); + this.tokenRequest = tokenRequest; + + final Amount amount = new Amount(); + amount.setExponent("2"); + amount.setCurrencyCode("EUR"); + amount.setValue("100"); + this.amount = amount; + + final BasicOrderInfo basicOrderInfo = new BasicOrderInfo(); + basicOrderInfo.setOrderCode(ORDER_CODE); + basicOrderInfo.setDescription(ORDER_DESC); + basicOrderInfo.setAmount(amount); + this.basicOrderInfo = basicOrderInfo; + + final Address address = new Address(); + address.setFirstName(FIRST_NAME); + address.setLastName(LAST_NAME); + address.setAddress1(SHOPPER_ADDRESS_1); + address.setAddress2(SHOPPER_ADDRESS_2); + address.setAddress3(SHOPPER_ADDRESS_3); + address.setPostalCode(POSTAL_CODE); + address.setCity(CITY); + address.setCountryCode(GB); + + this.shippingAddress = address; + this.billingAddress = address; + + final Session session = new Session(); + session.setId(SESSION_ID); + session.setShopperIPAddress(SHOPPER_IP_ADDRESS); + this.session = session; + + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(EMAIL_ADDRESS); + shopper.setSession(session); + this.shopper = shopper; + + final Cse cse = new Cse(); + cse.setEncryptedData(ENCRYPTED_DATA); + cse.setAddress(shippingAddress); + cse.setPaymentType(PaymentType.CSEDATA.getMethodCode()); + payment = cse; + + final PaymentDetails paymentDetails = new PaymentDetails(); + paymentDetails.setPayment(payment); + paymentDetails.setSession(this.session); + paymentDetails.setStoredCredentials(STORED_CREDENTIALS); + this.paymentDetails = paymentDetails; + + final OrderLines orderLines = new OrderLines(); + orderLines.setLineItems(List.of(LINE_ITEM)); + orderLines.setTermsURL(TERMS_URL); + orderLines.setOrderTaxAmount(ORDER_TAX_AMOUNT); + this.orderLines = orderLines; + } @Test public void build_ShouldCreateOrderWithAllParameters_WhenAllRequestParametersAreProvided() { @@ -63,43 +144,49 @@ public void build_ShouldCreateOrderWithAllParameters_WhenAllRequestParametersAre private void verifyOrder(final Order order) { assertEquals(ORDER_CODE, order.getOrderCode()); assertEquals(ORDER_DESC, order.getDescription()); - assertEquals(AMOUNT, order.getAmount()); + assertEquals(amount, order.getAmount()); assertNotNull(order.getPaymentDetails()); - assertEquals(PAYMENT, order.getPaymentDetails().getPayment()); - assertEquals(SESSION, order.getPaymentDetails().getSession()); + assertEquals(payment, order.getPaymentDetails().getPayment()); + assertEquals(session, order.getPaymentDetails().getSession()); assertEquals(STORED_CREDENTIALS, order.getPaymentDetails().getStoredCredentials()); assertEquals(INSTALLATION_ID, order.getInstallationId()); - assertEquals(INCLUDED_PAYMENT_TYPES, order.getPaymentMethodMask().getIncludes()); - assertEquals(EXCLUDED_PAYMENT_TYPES, order.getPaymentMethodMask().getExcludes()); + assertEquals(INCLUDED_PAYMENT_TYPES_METHOD, order.getPaymentMethodMask().getIncludes()); + assertEquals(EXCLUDED_PAYMENT_TYPES_METHOD, order.getPaymentMethodMask().getExcludes()); assertEquals(ORDER_CONTENT, order.getOrderContent()); - assertEquals(SHOPPER, order.getShopper()); - assertEquals(TOKEN_REQUEST, order.getTokenRequest()); - assertEquals(SHIPPING_ADDRESS, order.getShippingAddress()); - assertEquals(BILLING_ADDRESS, order.getBillingAddress()); + assertEquals(shopper, order.getShopper()); + assertEquals(tokenRequest, order.getTokenRequest()); + assertEquals(shippingAddress, order.getShippingAddress()); + assertEquals(billingAddress, order.getBillingAddress()); assertEquals(STATEMENT_NARRATIVE, order.getStatementNarrative()); assertEquals(DYNAMIC_INTERACTION_TYPE, order.getDynamicInteractionType()); assertEquals(ECHO_DATA, order.getEchoData()); - assertEquals(ORDER_LINES, order.getOrderLines()); + assertEquals(orderLines, order.getOrderLines()); assertEquals(PAYMENT_METHOD_ATTRIBUTES, order.getPaymentMethodAttributes()); + assertEquals(fraudSightDataMock, order.getFraudSightData()); + assertEquals(level23DataMock, order.getBranchSpecificExtension()); + assertEquals(MANDATE_TYPE, order.getMandateType()); } private Order createOrder() { return new OrderBuilder() - .withOrderInfo(BASIC_ORDER_INFO) - .withShopper(SHOPPER) + .withOrderInfo(basicOrderInfo) + .withShopper(shopper) .withInstallationId(INSTALLATION_ID) .withOrderContent(ORDER_CONTENT) - .withTokenRequest(TOKEN_REQUEST) - .withShippingAddress(SHIPPING_ADDRESS) - .withBillingAddress(BILLING_ADDRESS) + .withTokenRequest(tokenRequest) + .withShippingAddress(shippingAddress) + .withBillingAddress(billingAddress) .withStatementNarrative(STATEMENT_NARRATIVE) .withExcludedPaymentMethods(EXCLUDED_PAYMENT_TYPES) .withIncludedPaymentMethods(INCLUDED_PAYMENT_TYPES) .withDynamicInteractionType(DYNAMIC_INTERACTION_TYPE) - .withPaymentDetails(PAYMENT_DETAILS) + .withPaymentDetails(paymentDetails) .withEchoData(ECHO_DATA) - .withOrderLines(ORDER_LINES) + .withOrderLines(orderLines) .withPaymentMethodAttribute(PAYMENT_METHOD_ATTRIBUTES) + .withFraudSightAttribute(fraudSightDataMock) + .withLevel23Data(level23DataMock) + .withMandateType(MANDATE_TYPE) .build(); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/model/CardTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/model/CardTest.java deleted file mode 100644 index 8a2c86ef..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/model/CardTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.worldpay.service.request.model; - -import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.VISASSL; -import com.worldpay.service.model.Address; -import com.worldpay.service.model.Date; -import com.worldpay.service.model.payment.Card; -import com.worldpay.service.model.payment.PaymentType; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -@UnitTest -public class CardTest { - - private static final String CARDHOLDER_NAME = "John Smith"; - private static final String CARD_NUMBER = "4111111111111111"; - private static final String CVC = "123"; - private static final String FIRST_NAME = "firstName"; - - /** - * Test method for {@link com.worldpay.service.model.payment.Card#transformToInternalModel()}. - */ - @Test - public void testTransformToInternalModel() throws WorldpayModelTransformationException { - final Address address = new Address(); - address.setFirstName(FIRST_NAME); - final Date expiryDate = new Date("01", "1974"); - final Card card = new Card(PaymentType.VISA, CARD_NUMBER, CVC, expiryDate, CARDHOLDER_NAME, address, null, null, null, null); - - final VISASSL result = (VISASSL) card.transformToInternalModel(); - - assertEquals(CARD_NUMBER, result.getCardNumber().getvalue()); - assertEquals(CARDHOLDER_NAME, result.getCardHolderName().getvalue()); - assertEquals(CVC, result.getCvc().getvalue()); - assertEquals(expiryDate.getMonth(), result.getExpiryDate().getDate().getMonth()); - assertEquals(expiryDate.getYear(), result.getExpiryDate().getDate().getYear()); - assertEquals(FIRST_NAME, result.getCardAddress().getAddress().getFirstName()); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/AuthoriseRequestTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/AuthoriseRequestTransformerTest.java index c6c38508..1b7de0e2 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/AuthoriseRequestTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/AuthoriseRequestTransformerTest.java @@ -1,18 +1,17 @@ package com.worldpay.service.request.transform; +import com.worldpay.data.*; +import com.worldpay.data.token.TokenRequest; import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.CreateToken; -import com.worldpay.internal.model.Description; import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.Submit; -import com.worldpay.service.model.*; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.token.TokenRequest; import com.worldpay.service.request.AuthoriseRequestParameters; import com.worldpay.service.request.AuthoriseServiceRequest; import com.worldpay.service.request.RedirectAuthoriseServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,7 +24,7 @@ import static com.worldpay.service.model.payment.PaymentType.ONLINE; import static java.util.Collections.singletonList; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @UnitTest @@ -49,114 +48,144 @@ public class AuthoriseRequestTransformerTest { private static final String AUTH_SHOPPER_ID = "authShopperID"; private static final String ORDER_CODE = "DS1347889928107_3"; private static final String DESCRIPTION = "Your Order & Order desc"; + private static final String MERCHANT_CODE = "MERCHANT_CODE"; + private static final String MERCHANT_PASSWORD = "MERCHANT_PASSWORD"; + private static final String VERSION = "1.4"; + private static final List INCLUDED_PTS = singletonList(ONLINE); + + private MerchantInfo merchantInfo; + private BasicOrderInfo basicOrderInfo; + private Address shippingAddress; + private Address billingAddress; + private TokenRequest tokenRequest; + private Shopper shopper; @InjectMocks private AuthoriseRequestTransformer testObj; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) private ConfigurationService configurationServiceMock; @Mock - private com.worldpay.internal.model.PaymentMethodAttribute intPaymentMethodAttributeMock; + private Converter internalOrderConverterMock; + @Mock - private PaymentMethodAttribute paymentMethodAttributeMock; + private com.worldpay.internal.model.Order intOrderMock; @Before public void setUp() { - when(paymentMethodAttributeMock.transformToInternalModel()).thenReturn(intPaymentMethodAttributeMock); - when(configurationServiceMock.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)).thenReturn("1.4"); + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setTokenEventReference(TOKEN_REFERENCE); + this.tokenRequest = tokenRequest; + + final Amount amount = new Amount(); + amount.setExponent("2"); + amount.setCurrencyCode("EUR"); + amount.setValue("100"); + + final BasicOrderInfo basicOrderInfo = new BasicOrderInfo(); + basicOrderInfo.setOrderCode(ORDER_CODE); + basicOrderInfo.setDescription(DESCRIPTION); + basicOrderInfo.setAmount(amount); + this.basicOrderInfo = basicOrderInfo; + + + final Address address = new Address(); + address.setFirstName(FIRST_NAME); + address.setLastName(LAST_NAME); + address.setAddress1(SHOPPER_ADDRESS_1); + address.setAddress2(SHOPPER_ADDRESS_2); + address.setAddress3(SHOPPER_ADDRESS_3); + address.setPostalCode(POSTAL_CODE); + address.setCity(CITY); + address.setCountryCode(GB); + + this.shippingAddress = address; + this.billingAddress = address; + + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(SHOPPER_EMAIL_ADDRESS); + shopper.setAuthenticatedShopperID(AUTH_SHOPPER_ID); + this.shopper = shopper; + + when(configurationServiceMock.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)).thenReturn(VERSION); } - /** - * Test method for {@link com.worldpay.service.request.transform.AuthoriseRequestTransformer#transform(com.worldpay.service.request.ServiceRequest)}. - */ - @Test - public void transform_ShouldConvertFromAuthoriseRequestToPaymentServiceWithTokenRequest() throws WorldpayModelTransformationException { - final MerchantInfo merchantInfo = new MerchantInfo("MERCHANT_CODE", "MERCHANT_PASSWORD"); - final BasicOrderInfo orderInfo = new BasicOrderInfo(ORDER_CODE, DESCRIPTION, new Amount("100", "EUR", "2")); - final Address shippingAddress = new Address(FIRST_NAME, LAST_NAME, SHOPPER_ADDRESS_1, SHOPPER_ADDRESS_2, SHOPPER_ADDRESS_3, POSTAL_CODE, CITY, GB); - final Address billingAddress = new Address(FIRST_NAME, LAST_NAME, SHOPPER_ADDRESS_1, SHOPPER_ADDRESS_2, SHOPPER_ADDRESS_3, POSTAL_CODE, CITY, GB); - final List includedPTs = singletonList(ONLINE); - final TokenRequest tokenRequest = new TokenRequest(TOKEN_REFERENCE, TOKEN_REASON); - final Shopper shopper = new Shopper(SHOPPER_EMAIL_ADDRESS, AUTH_SHOPPER_ID, null, null); + @Test(expected = WorldpayModelTransformationException.class) + public void populate_WhenRequestIsNull_ShouldThrowAnException() throws WorldpayModelTransformationException { + testObj.transform(null); + } + + @Test(expected = WorldpayModelTransformationException.class) + public void populate_WhenMerchantInfoIsNull_ShouldThrowAnException() throws WorldpayModelTransformationException { final AuthoriseRequestParameters authoriseRequestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(orderInfo) + .withMerchantInfo(null) + .withOrderInfo(basicOrderInfo) .withOrderContent(ORDER_CONTENT) - .withIncludedPTs(includedPTs) + .withIncludedPTs(INCLUDED_PTS) .withShopper(shopper) .withShippingAddress(shippingAddress) .withBillingAddress(billingAddress) .withTokenRequest(tokenRequest) .withStatementNarrative(STATEMENT_NARRATIVE_TEXT) - .withPaymentMethodAttributes(List.of(paymentMethodAttributeMock)) .build(); - final AuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); - - final PaymentService result = testObj.transform(request); - - final List submitList = result.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify(); - final Submit submit = (Submit) submitList.get(0); - final List orderList = submit.getOrderOrOrderBatchOrShopperOrFuturePayAgreementOrMakeFuturePayPaymentOrIdentifyMeRequestOrPaymentTokenCreateOrChallenge(); - final com.worldpay.internal.model.Order intOrder = (com.worldpay.internal.model.Order) orderList.get(0); - - final List orderElements = intOrder.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final String description = orderElements.stream().filter(Description.class::isInstance).map(Description.class::cast).findFirst().map(Description::getvalue).orElse(null); - assertEquals("Incorrect description", DESCRIPTION, description); - final String orderCode = intOrder.getOrderCode(); + final AuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); - final CreateToken createToken = orderElements.stream().filter(CreateToken.class::isInstance).map(CreateToken.class::cast).findFirst().orElse(null); - assertNotNull(createToken); - assertEquals(TOKEN_REFERENCE, createToken.getTokenEventReference()); - assertEquals(TOKEN_REASON, createToken.getTokenReason().getvalue()); + testObj.transform(request); + } - final com.worldpay.internal.model.Shopper intShopper = orderElements.stream().filter(com.worldpay.internal.model.Shopper.class::isInstance).map(com.worldpay.internal.model.Shopper.class::cast).findFirst().orElse(null); - assertNotNull(intShopper); - assertEquals(AUTH_SHOPPER_ID, intShopper.getAuthenticatedShopperID().getvalue()); + @Test(expected = WorldpayModelTransformationException.class) + public void populate_WhenOrderCodeIsNull_ShouldThrowAnException() throws WorldpayModelTransformationException { + basicOrderInfo.setOrderCode(null); + final AuthoriseRequestParameters authoriseRequestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + .withMerchantInfo(merchantInfo) + .withOrderInfo(basicOrderInfo) + .withOrderContent(ORDER_CONTENT) + .withIncludedPTs(INCLUDED_PTS) + .withShopper(shopper) + .withShippingAddress(shippingAddress) + .withBillingAddress(billingAddress) + .withTokenRequest(tokenRequest) + .withStatementNarrative(STATEMENT_NARRATIVE_TEXT) + .build(); - final com.worldpay.internal.model.PaymentMethodAttribute intPaymentMethodAttribute = orderElements.stream().filter(com.worldpay.internal.model.PaymentMethodAttribute.class::isInstance).map(com.worldpay.internal.model.PaymentMethodAttribute.class::cast).findFirst().orElse(null); - assertEquals(intPaymentMethodAttributeMock, intPaymentMethodAttribute); + final AuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); - assertEquals("Incorrect orderCode", ORDER_CODE, orderCode); - assertEquals(merchantInfo.getMerchantCode(), result.getMerchantCode()); + testObj.transform(request); } - /** - * Test method for {@link com.worldpay.service.request.transform.AuthoriseRequestTransformer#transform(com.worldpay.service.request.ServiceRequest)}. - */ @Test - public void transform_ShouldCreateAuthoriseRequest() throws WorldpayModelTransformationException { - final MerchantInfo merchantInfo = new MerchantInfo("MERCHANT_CODE", "MERCHANT_PASSWORD"); - final BasicOrderInfo orderInfo = new BasicOrderInfo(ORDER_CODE, DESCRIPTION, new Amount("100", "EUR", "2")); - final Address shippingAddress = new Address(FIRST_NAME, LAST_NAME, SHOPPER_ADDRESS_1, SHOPPER_ADDRESS_2, SHOPPER_ADDRESS_3, POSTAL_CODE, CITY, GB); - final Address billingAddress = new Address(FIRST_NAME, LAST_NAME, SHOPPER_ADDRESS_1, SHOPPER_ADDRESS_2, SHOPPER_ADDRESS_3, POSTAL_CODE, CITY, GB); - final List includedPTs = singletonList(ONLINE); - final Shopper shopper = new Shopper(SHOPPER_EMAIL_ADDRESS, AUTH_SHOPPER_ID, null, null); + public void transform_WhenEveryFieldIsNotEmpty_ShouldTransformRequest() throws WorldpayModelTransformationException { final AuthoriseRequestParameters authoriseRequestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() .withMerchantInfo(merchantInfo) - .withOrderInfo(orderInfo) + .withOrderInfo(basicOrderInfo) .withOrderContent(ORDER_CONTENT) - .withIncludedPTs(includedPTs) + .withIncludedPTs(INCLUDED_PTS) .withShopper(shopper) .withShippingAddress(shippingAddress) .withBillingAddress(billingAddress) + .withTokenRequest(tokenRequest) .withStatementNarrative(STATEMENT_NARRATIVE_TEXT) .build(); final AuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); + when(internalOrderConverterMock.convert(request.getOrder())).thenReturn(intOrderMock); final PaymentService result = testObj.transform(request); + assertThat(result.getMerchantCode()).isEqualTo(merchantInfo.getMerchantCode()); + assertThat(result.getVersion()).isEqualTo(VERSION); + final List submitList = result.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify(); final Submit submit = (Submit) submitList.get(0); final List orderList = submit.getOrderOrOrderBatchOrShopperOrFuturePayAgreementOrMakeFuturePayPaymentOrIdentifyMeRequestOrPaymentTokenCreateOrChallenge(); final com.worldpay.internal.model.Order intOrder = (com.worldpay.internal.model.Order) orderList.get(0); - final List orderElements = intOrder.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); - final String description = orderElements.stream().filter(Description.class::isInstance).map(Description.class::cast).findFirst().map(Description::getvalue).orElse(null); - assertEquals("Incorrect description", DESCRIPTION, description); - - final String orderCode = intOrder.getOrderCode(); - assertFalse(orderElements.stream().anyMatch(CreateToken.class::isInstance)); - assertEquals("Incorrect orderCode", ORDER_CODE, orderCode); - assertEquals(merchantInfo.getMerchantCode(), result.getMerchantCode()); + assertThat(intOrder).isEqualTo(intOrderMock); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/CaptureRequestTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/CaptureRequestTransformerTest.java index 2f3d3322..9afc6798 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/CaptureRequestTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/CaptureRequestTransformerTest.java @@ -2,12 +2,13 @@ import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.*; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.Date; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.Amount; +import com.worldpay.data.Date; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.CaptureServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -39,6 +40,10 @@ public class CaptureRequestTransformerTest { @Mock(answer = Answers.RETURNS_DEEP_STUBS) private ConfigurationService configurationServiceMock; + @Mock + private Converter internalAmountConverter; + @Mock + private Converter internalDateConverter; @Mock private CaptureServiceRequest captureRequestMock; @@ -55,13 +60,15 @@ public class CaptureRequestTransformerTest { @Before public void setUp() throws Exception { + testObj = new CaptureRequestTransformer(configurationServiceMock, internalAmountConverter, internalDateConverter); + when(captureRequestMock.getMerchantInfo()).thenReturn(merchantInfoMock); when(captureRequestMock.getOrderCode()).thenReturn(ORDER_CODE); when(captureRequestMock.getAmount()).thenReturn(amountMock); when(captureRequestMock.getDate()).thenReturn(dateMock); when(captureRequestMock.getTrackingIds()).thenReturn(List.of(TRACKING_ID_1, TRACKING_ID_2)); - when(dateMock.transformToInternalModel()).thenReturn(internalDateMock); - when(amountMock.transformToInternalModel()).thenReturn(internalAmountMock); + when(internalDateConverter.convert(dateMock)).thenReturn(internalDateMock); + when(internalAmountConverter.convert(amountMock)).thenReturn(internalAmountMock); when(merchantInfoMock.getMerchantCode()).thenReturn(MERCHANT_CODE); when(configurationServiceMock.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)).thenReturn(VERSION); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/CreateTokenRequestTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/CreateTokenRequestTransformerTest.java index a7023aed..204e3d7d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/CreateTokenRequestTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/CreateTokenRequestTransformerTest.java @@ -1,32 +1,30 @@ package com.worldpay.service.request.transform; +import com.worldpay.data.Address; +import com.worldpay.data.MerchantInfo; +import com.worldpay.data.payment.Cse; +import com.worldpay.data.token.CardTokenRequest; +import com.worldpay.data.token.TokenRequest; import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.CSEDATA; import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.PaymentTokenCreate; import com.worldpay.internal.model.Submit; -import com.worldpay.service.model.Address; -import com.worldpay.service.model.MerchantInfo; -import com.worldpay.service.model.payment.Payment; -import com.worldpay.service.model.payment.PaymentBuilder; -import com.worldpay.service.model.token.TokenRequest; +import com.worldpay.service.model.payment.PaymentType; +import com.worldpay.service.request.CreateTokenServiceRequest; import com.worldpay.service.request.ServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import static com.worldpay.service.request.CreateTokenServiceRequest.createTokenRequestForMerchantToken; import static com.worldpay.service.request.CreateTokenServiceRequest.createTokenRequestForShopperToken; -import static org.hamcrest.Matchers.samePropertyValuesAs; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @UnitTest @@ -41,69 +39,76 @@ public class CreateTokenRequestTransformerTest { private static final String GB = "GB"; private static final String TOKEN_REASON = "tokenReason"; private static final String TOKEN_REFERENCE = "tokenReference"; - private static final Address BILLING_ADDRESS = new Address(FIRST_NAME, LAST_NAME, null, null, null, POSTAL_CODE, CITY, GB); - private static final MerchantInfo MERCHANT_INFO = new MerchantInfo("MERCHANT_CODE", "MERCHANT_PASSWORD"); + + private static final String MERCHANT_CODE = "MERCHANT_CODE"; + private static final String MERCHANT_PASSWORD = "MERCHANT_PASSWORD"; private static final String AUTH_SHOPPER_ID = "authShopperID"; private static final String ENCRYPTED_DATA = "encryptedData"; - private static final Payment PAYMENT = PaymentBuilder.createCSE(ENCRYPTED_DATA, BILLING_ADDRESS); - private static final TokenRequest TOKEN_REQUEST_SHOPPER = new TokenRequest(TOKEN_REFERENCE, TOKEN_REASON); - private static final TokenRequest TOKEN_REQUEST_MERCHANT = new TokenRequest(TOKEN_REFERENCE, TOKEN_REASON, true); + private static final String VERSION = "1.4"; - @Rule - @SuppressWarnings("PMD.MemberScope") - public ExpectedException expectedException = ExpectedException.none(); + private TokenRequest tokenRequest; + private MerchantInfo merchantInfo; @InjectMocks private CreateTokenRequestTransformer testObj; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) private ConfigurationService configurationServiceMock; + @Mock + private Converter internalPaymentTokenCreateConverterMock; + + @Mock + private PaymentTokenCreate paymentTokenCreateMock; @Before public void setUp() throws Exception { - when(configurationServiceMock.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)).thenReturn("1.4"); + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + this.merchantInfo = merchantInfo; + + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setTokenEventReference(TOKEN_REFERENCE); + this.tokenRequest = tokenRequest; + + when(configurationServiceMock.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)).thenReturn(VERSION); + testObj = new CreateTokenRequestTransformer(configurationServiceMock, internalPaymentTokenCreateConverterMock); } - @Test + @Test(expected = WorldpayModelTransformationException.class) public void transformShouldRaiseErrorWhenRequestIsNull() throws WorldpayModelTransformationException { - expectedException.expect(WorldpayModelTransformationException.class); - expectedException.expectMessage("Request provided to create token is invalid."); - testObj.transform(null); } @Test - public void transformShouldCreatePaymentServiceRequestUsingShopperToken() throws WorldpayModelTransformationException { - final ServiceRequest serviceRequest = createTokenRequestForShopperToken(MERCHANT_INFO, AUTH_SHOPPER_ID, PAYMENT, TOKEN_REQUEST_SHOPPER); - final PaymentService result = testObj.transform(serviceRequest); + public void transformShouldCreatePaymentServiceRequest() throws WorldpayModelTransformationException { - final Submit submit = (Submit) result.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); - final PaymentTokenCreate paymentTokenCreate = (PaymentTokenCreate) submit.getOrderOrOrderBatchOrShopperOrFuturePayAgreementOrMakeFuturePayPaymentOrIdentifyMeRequestOrPaymentTokenCreateOrChallenge().get(0); - final CSEDATA cseData = (CSEDATA) paymentTokenCreate.getPaymentInstrumentOrCSEDATA().get(0); - - assertEquals(MERCHANT_INFO.getMerchantCode(), result.getMerchantCode()); - assertEquals(AUTH_SHOPPER_ID, paymentTokenCreate.getAuthenticatedShopperID().getvalue()); - assertEquals(TOKEN_REFERENCE, paymentTokenCreate.getCreateToken().getTokenEventReference()); - assertEquals(TOKEN_REASON, paymentTokenCreate.getCreateToken().getTokenReason().getvalue()); - assertEquals(ENCRYPTED_DATA, cseData.getEncryptedData()); - assertThat(BILLING_ADDRESS.transformToInternalModel(), samePropertyValuesAs(cseData.getCardAddress().getAddress())); - assertEquals("shopper", paymentTokenCreate.getCreateToken().getTokenScope()); - } + final Address address = new Address(); + address.setFirstName(FIRST_NAME); + address.setLastName(LAST_NAME); + address.setPostalCode(POSTAL_CODE); + address.setCity(CITY); + address.setCountryCode(GB); + + final Cse cse = new Cse(); + cse.setEncryptedData(ENCRYPTED_DATA); + cse.setAddress(address); + cse.setPaymentType(PaymentType.CSEDATA.getMethodCode()); + + final ServiceRequest serviceRequest = createTokenRequestForShopperToken(merchantInfo, AUTH_SHOPPER_ID, cse, tokenRequest); + final CreateTokenServiceRequest tokenRequest = (CreateTokenServiceRequest) serviceRequest; + + when(internalPaymentTokenCreateConverterMock.convert(tokenRequest.getCardTokenRequest())).thenReturn(paymentTokenCreateMock); - @Test - public void transformShouldCreatePaymentServiceRequestUsingMerchantToken() throws WorldpayModelTransformationException { - final ServiceRequest serviceRequest = createTokenRequestForMerchantToken(MERCHANT_INFO, PAYMENT, TOKEN_REQUEST_MERCHANT); final PaymentService result = testObj.transform(serviceRequest); final Submit submit = (Submit) result.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); final PaymentTokenCreate paymentTokenCreate = (PaymentTokenCreate) submit.getOrderOrOrderBatchOrShopperOrFuturePayAgreementOrMakeFuturePayPaymentOrIdentifyMeRequestOrPaymentTokenCreateOrChallenge().get(0); - final CSEDATA cseData = (CSEDATA) paymentTokenCreate.getPaymentInstrumentOrCSEDATA().get(0); - - assertEquals(MERCHANT_INFO.getMerchantCode(), result.getMerchantCode()); - assertNull(paymentTokenCreate.getAuthenticatedShopperID()); - assertEquals(TOKEN_REFERENCE, paymentTokenCreate.getCreateToken().getTokenEventReference()); - assertEquals(TOKEN_REASON, paymentTokenCreate.getCreateToken().getTokenReason().getvalue()); - assertEquals(ENCRYPTED_DATA, cseData.getEncryptedData()); - assertThat(BILLING_ADDRESS.transformToInternalModel(), samePropertyValuesAs(cseData.getCardAddress().getAddress())); - assertEquals("merchant", paymentTokenCreate.getCreateToken().getTokenScope()); + + assertThat(result.getMerchantCode()).isEqualTo(merchantInfo.getMerchantCode()); + assertThat(result.getVersion()).isEqualTo(VERSION); + assertThat(paymentTokenCreate).isEqualTo(paymentTokenCreateMock); } + } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/DeleteTokenRequestTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/DeleteTokenRequestTransformerTest.java index 2b3bcefb..576e40d7 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/DeleteTokenRequestTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/DeleteTokenRequestTransformerTest.java @@ -4,9 +4,11 @@ import com.worldpay.internal.model.Modify; import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.PaymentTokenDelete; +import com.worldpay.data.token.DeleteTokenRequest; import com.worldpay.service.request.DeleteTokenServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,6 +33,9 @@ public class DeleteTokenRequestTransformerTest { private DeleteTokenRequestTransformer testObj; @Mock(answer = RETURNS_DEEP_STUBS) private DeleteTokenServiceRequest serviceRequestMock; + @Mock + private Converter internalPaymentTokenDeleteConverter; + @Mock private PaymentTokenDelete paymentTokenDeleteMock; @Mock(answer = RETURNS_DEEP_STUBS) @@ -48,7 +53,7 @@ public void shouldRaiseExceptionWhenServiceRequestIsNull() throws Exception { @Test public void shouldReturnPaymentServiceWithPaymentTokenDelete() throws Exception { - when(serviceRequestMock.getDeleteTokenRequest().transformToInternalModel()).thenReturn(paymentTokenDeleteMock); + when(internalPaymentTokenDeleteConverter.convert(serviceRequestMock.getDeleteTokenRequest())).thenReturn(paymentTokenDeleteMock); when(serviceRequestMock.getMerchantInfo().getMerchantCode()).thenReturn(MERCHANT_CODE); final PaymentService result = testObj.transform(serviceRequestMock); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/OrderInquiryRequestTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/OrderInquiryRequestTransformerTest.java index a2b3094e..691b53bb 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/OrderInquiryRequestTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/OrderInquiryRequestTransformerTest.java @@ -5,7 +5,7 @@ import com.worldpay.internal.model.KlarnaConfirmationInquiry; import com.worldpay.internal.model.OrderInquiry; import com.worldpay.internal.model.PaymentService; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.KlarnaOrderInquiryServiceRequest; import com.worldpay.service.request.OrderInquiryServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/RefundRequestTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/RefundRequestTransformerTest.java new file mode 100644 index 00000000..ccd6306e --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/RefundRequestTransformerTest.java @@ -0,0 +1,104 @@ +package com.worldpay.service.request.transform; + +import com.worldpay.exception.WorldpayModelTransformationException; +import com.worldpay.internal.model.Modify; +import com.worldpay.internal.model.OrderModification; +import com.worldpay.internal.model.PaymentService; +import com.worldpay.internal.model.Refund; +import com.worldpay.data.Amount; +import com.worldpay.data.MerchantInfo; +import com.worldpay.service.request.RefundServiceRequest; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Answers.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.when; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class RefundRequestTransformerTest { + + private static final String WORLDPAY_CONFIG_VERSION = "worldpay.config.version"; + private static final String MERCHANT_CODE = "merchantCode"; + private static final String CONFIG_VERSION = "1.4"; + private static final String REFERENCE = "reference"; + private static final String ORDER_CODE = "orderCode"; + + @InjectMocks + private RefundRequestTransformer testObj; + + @Mock(answer = RETURNS_DEEP_STUBS) + private ConfigurationService configurationServiceMock; + @Mock + protected Converter internalAmountConverterMock; + + @Mock(answer = RETURNS_DEEP_STUBS) + private RefundServiceRequest requestMock; + @Mock + private com.worldpay.internal.model.Amount internalAmountMock; + @Mock + private MerchantInfo merchantInfoMock; + + @Before + public void setUp() throws Exception { + when(configurationServiceMock.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)).thenReturn(CONFIG_VERSION); + when(requestMock.getMerchantInfo()).thenReturn(merchantInfoMock); + when(requestMock.getMerchantInfo().getMerchantCode()).thenReturn(MERCHANT_CODE); + when(requestMock.getOrderCode()).thenReturn(ORDER_CODE); + } + + @Test(expected = WorldpayModelTransformationException.class) + public void transform_WhenServiceRequestIsNull_ShouldRaiseException() throws Exception { + testObj.transform(null); + } + + @Test(expected = WorldpayModelTransformationException.class) + public void transform_WhenMerchantCodeIsNull_ShouldRaiseException() throws Exception { + when(requestMock.getMerchantInfo()).thenReturn(null); + + testObj.transform(requestMock); + } + + @Test(expected = WorldpayModelTransformationException.class) + public void transform_WhenOrderCodeIsNull_ShouldRaiseException() throws Exception { + when(requestMock.getOrderCode()).thenReturn(null); + + testObj.transform(requestMock); + } + + @Test(expected = WorldpayModelTransformationException.class) + public void transform_WhenAmountIsNull_ShouldRaiseException() throws Exception { + when(requestMock.getAmount()).thenReturn(null); + + testObj.transform(requestMock); + } + + @Test + public void transform_ShouldReturnPaymentService() throws Exception { + when(internalAmountConverterMock.convert(requestMock.getAmount())).thenReturn(internalAmountMock); + when(internalAmountConverterMock.convert(requestMock.getAmount())).thenReturn(internalAmountMock); + when(requestMock.getReference()).thenReturn(REFERENCE); + when(requestMock.getShopperWebformRefund()).thenReturn(Boolean.TRUE); + + final PaymentService result = testObj.transform(requestMock); + + final Modify modify = (Modify) result.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().get(0); + final OrderModification orderModification = (OrderModification) modify.getOrderModificationOrBatchModificationOrAccountBatchModificationOrFuturePayAgreementModificationOrPaymentTokenUpdateOrPaymentTokenDelete().get(0); + final Refund refund = (Refund) orderModification.getCancelOrCaptureOrRefundOrRevokeOrAddBackOfficeCodeOrAuthoriseOrIncreaseAuthorisationOrCancelOrRefundOrDefendOrShopperWebformRefundDetailsOrExtendExpiryDateOrCancelRefundOrCancelRetryOrVoidSaleOrApprove().get(0); + + assertThat(refund.getAmount()).isEqualTo(internalAmountMock); + assertThat(refund.getReference()).isEqualTo(REFERENCE); + assertThat(refund.getShopperWebformRefund()).isEqualTo(Boolean.TRUE.toString()); + assertThat(result.getMerchantCode()).isEqualTo(MERCHANT_CODE); + assertThat(result.getVersion()).isEqualTo(CONFIG_VERSION); + assertThat(orderModification.getOrderCode()).isEqualTo(ORDER_CODE); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/SecondThreeDSecurePaymentRequestTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/SecondThreeDSecurePaymentRequestTransformerTest.java index ba177a69..b538bf37 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/SecondThreeDSecurePaymentRequestTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/SecondThreeDSecurePaymentRequestTransformerTest.java @@ -4,7 +4,7 @@ import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.Session; import com.worldpay.internal.model.Submit; -import com.worldpay.service.model.MerchantInfo; +import com.worldpay.data.MerchantInfo; import com.worldpay.service.request.SecondThreeDSecurePaymentRequest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.config.ConfigurationService; @@ -30,6 +30,8 @@ public class SecondThreeDSecurePaymentRequestTransformerTest { private static final String MERCHANT_INFO_CODE = "merchant_info_code"; private static final String ORDER_CODE = "order_code"; private static final String VERSION = "1.4"; + private static final String MERCHANT_CODE = "MERCHANT_CODE"; + private static final String MERCHANT_PASSWORD = "MERCHANT_PASSWORD"; @InjectMocks private SecondThreeDSecurePaymentRequestTransformer testObj; @@ -78,7 +80,10 @@ public void testTransformSecondThreeDSecurePaymentRequestToPaymentServiceWithBla @Test public void testTransformSecondThreeDSecurePaymentRequestToPaymentService() throws WorldpayModelTransformationException { - final MerchantInfo merchantInfo = new MerchantInfo("MERCHANT_CODE", "MERCHANT_PASSWORD"); + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + merchantInfo.setMerchantCode(MERCHANT_CODE); + when(secondThreeDSecurePaymentRequestMock.getMerchantInfo()).thenReturn(merchantInfo); when(merchantInfoMock.getMerchantCode()).thenReturn(MERCHANT_INFO_CODE); when(secondThreeDSecurePaymentRequestMock.getOrderCode()).thenReturn(ORDER_CODE); @@ -94,7 +99,7 @@ public void testTransformSecondThreeDSecurePaymentRequestToPaymentService() thro assertEquals("Incorrect orderCode", ORDER_CODE, orderCode); assertEquals(merchantInfo.getMerchantCode(), result.getMerchantCode()); assertEquals(VERSION, result.getVersion()); - final List orderElements = intOrder.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrInfo3DSecureOrSession(); + final List orderElements = intOrder.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession(); final Session session = (Session) orderElements.get(1); assertEquals(SESSION_ID, session.getId()); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/UpdateTokenRequestTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/UpdateTokenRequestTransformerTest.java index 1b50ad48..f2189711 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/UpdateTokenRequestTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/transform/UpdateTokenRequestTransformerTest.java @@ -4,9 +4,11 @@ import com.worldpay.internal.model.Modify; import com.worldpay.internal.model.PaymentService; import com.worldpay.internal.model.PaymentTokenUpdate; +import com.worldpay.data.token.UpdateTokenRequest; import com.worldpay.service.request.UpdateTokenServiceRequest; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -28,12 +30,16 @@ public class UpdateTokenRequestTransformerTest { @InjectMocks private UpdateTokenRequestTransformer testObj; + + @Mock(answer = RETURNS_DEEP_STUBS) + private ConfigurationService configurationServiceMock; + @Mock + protected Converter internalPaymentTokenUpdateConverterMock; + @Mock(answer = RETURNS_DEEP_STUBS) private UpdateTokenServiceRequest serviceRequestMock; @Mock private PaymentTokenUpdate paymentTokenUpdateMock; - @Mock(answer = RETURNS_DEEP_STUBS) - private ConfigurationService configurationServiceMock; @Before public void setUp() throws Exception { @@ -47,7 +53,7 @@ public void shouldRaiseExceptionWhenServiceRequestIsNull() throws Exception { @Test public void shouldReturnPaymentServiceWithPaymentTokenUpdate() throws Exception { - when(serviceRequestMock.getUpdateTokenRequest().transformToInternalModel()).thenReturn(paymentTokenUpdateMock); + when(internalPaymentTokenUpdateConverterMock.convert(serviceRequestMock.getUpdateTokenRequest())).thenReturn(paymentTokenUpdateMock); when(serviceRequestMock.getMerchantInfo().getMerchantCode()).thenReturn(MERCHANT_CODE); final PaymentService result = testObj.transform(serviceRequestMock); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/validation/impl/DefaultWorldpayXMLValidatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/validation/impl/DefaultWorldpayXMLValidatorTest.java index cbb781a3..369e4518 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/validation/impl/DefaultWorldpayXMLValidatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/request/validation/impl/DefaultWorldpayXMLValidatorTest.java @@ -1,11 +1,12 @@ package com.worldpay.service.request.validation.impl; +import com.worldpay.data.*; +import com.worldpay.data.token.TokenRequest; import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.exception.WorldpayValidationException; +import com.worldpay.internal.model.Description; import com.worldpay.internal.model.PaymentService; -import com.worldpay.service.model.*; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.token.TokenRequest; import com.worldpay.service.request.AuthoriseRequestParameters; import com.worldpay.service.request.AuthoriseServiceRequest; import com.worldpay.service.request.RedirectAuthoriseServiceRequest; @@ -13,6 +14,7 @@ import com.worldpay.service.request.validation.WorldpayXMLValidator; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -36,8 +38,26 @@ public class DefaultWorldpayXMLValidatorTest { private static final String EMAIL_ADDRESS = "jshopper@myprovider.com"; private static final String TOKEN_REFERENCE = "tokenReference"; private static final String TOKEN_REASON = "tokenReason"; - private static final String AUTH_SHOPPER_ID = "authShopperId"; + private static final String ORDER_CODE = "DS1347889928107_3"; + private static final String MERCHANT_CODE = "MERCHANT_CODE"; + private static final String MERCHANT_PASSWORD = "MERCHANT_PASSWORD"; + private static final String YOUR_ORDER_ORDER_DESC = "Your Order & Order desc"; + private static final String VALUE = "100"; + private static final String EUR = "EUR"; + private static final String EXPONENT = "2"; + private static final String CITY = "city"; + private static final String GB = "GB"; + private static final String NAME = "John"; + private static final String SHOPPER = "Shopper"; + private static final String SHOPPER_ADDRESS_1 = "Shopper Address1"; + private static final String SHOPPER_ADDRESS_2 = "Shopper Address2"; + private static final String SHOPPER_ADDRESS_3 = "Shopper Address3"; + private static final String POSTAL_CODE = "Postal code"; + private static final String VERSION = "1.4"; + private static final String ORDER_CONTENT = "orderContent"; + + private static final WorldpayXMLValidator VALIDATOR = new DefaultWorldpayXMLValidator(); private MerchantInfo merchantInfo; private BasicOrderInfo basicOrderInfo; @@ -49,35 +69,63 @@ public class DefaultWorldpayXMLValidatorTest { @Mock(answer = RETURNS_DEEP_STUBS) private ConfigurationService configurationServiceMock; + @Mock + private Converter internalOrderConverterMock; - private static final String ORDER_CONTENT = "orderContent"; - private static final WorldpayXMLValidator VALIDATOR = new DefaultWorldpayXMLValidator(); @Before public void setUp() { - merchantInfo = new MerchantInfo("MERCHANT_CODE", "MERCHANT_PASSWORD"); - basicOrderInfo = new BasicOrderInfo("DS1347889928107_3", "Your Order & Order desc", new Amount("100", "EUR", "2")); - shippingAddress = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - billingAddress = new Address("John", "Shopper", "Shopper Address1", "Shopper Address2", "Shopper Address3", "postalCode", "city", "GB"); - when(configurationServiceMock.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)).thenReturn("1.4"); + final MerchantInfo merchantInfo = new MerchantInfo(); + merchantInfo.setMerchantCode(MERCHANT_CODE); + merchantInfo.setMerchantPassword(MERCHANT_PASSWORD); + this.merchantInfo = merchantInfo; + + final Amount amount = new Amount(); + amount.setValue(VALUE); + amount.setCurrencyCode(EUR); + amount.setExponent(EXPONENT); + + final BasicOrderInfo basicOrderInfo = new BasicOrderInfo(); + basicOrderInfo.setAmount(amount); + basicOrderInfo.setOrderCode(ORDER_CODE); + basicOrderInfo.setDescription(YOUR_ORDER_ORDER_DESC); + this.basicOrderInfo = basicOrderInfo; + + final Address address = new Address(); + address.setFirstName(NAME); + address.setLastName(SHOPPER); + address.setAddress1(SHOPPER_ADDRESS_1); + address.setAddress2(SHOPPER_ADDRESS_2); + address.setAddress3(SHOPPER_ADDRESS_3); + address.setPostalCode(POSTAL_CODE); + address.setCity(CITY); + address.setCountryCode(GB); + shippingAddress = address; + billingAddress = address; + + when(configurationServiceMock.getConfiguration().getString(WORLDPAY_CONFIG_VERSION)).thenReturn(VERSION); } @Test public void testValidate() throws WorldpayValidationException, WorldpayModelTransformationException { final List includedPTs = singletonList(ONLINE); - final Shopper shopper = new Shopper(EMAIL_ADDRESS, AUTH_SHOPPER_ID, null, null); + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(EMAIL_ADDRESS); + shopper.setAuthenticatedShopperID(AUTH_SHOPPER_ID); final AuthoriseRequestParameters authoriseRequestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withOrderContent(ORDER_CONTENT) - .withIncludedPTs(includedPTs) - .withShopper(shopper) - .withShippingAddress(shippingAddress) - .withBillingAddress(billingAddress) - .withStatementNarrative(STATEMENT_NARRATIVE_TEXT) - .build(); + .withMerchantInfo(merchantInfo) + .withOrderInfo(basicOrderInfo) + .withOrderContent(ORDER_CONTENT) + .withIncludedPTs(includedPTs) + .withShopper(shopper) + .withShippingAddress(shippingAddress) + .withBillingAddress(billingAddress) + .withStatementNarrative(STATEMENT_NARRATIVE_TEXT) + .build(); final AuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); + when(internalOrderConverterMock.convert(request.getOrder())).thenReturn(createOrderWithMandatoryFields()); + final PaymentService paymentService = testObj.transform(request); VALIDATOR.validate(paymentService); @@ -86,11 +134,18 @@ public void testValidate() throws WorldpayValidationException, WorldpayModelTran @Test public void testValidateXMLWithCreateTokenWithShopperScope() throws WorldpayValidationException, WorldpayModelTransformationException { final List includedPTs = singletonList(ONLINE); - final Shopper shopper = new Shopper(EMAIL_ADDRESS, AUTH_SHOPPER_ID, null, null); - final TokenRequest tokenRequest = new TokenRequest(TOKEN_REFERENCE, TOKEN_REASON, false); + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(EMAIL_ADDRESS); + shopper.setAuthenticatedShopperID(AUTH_SHOPPER_ID); + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenEventReference(TOKEN_REFERENCE); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setMerchantToken(false); final AuthoriseRequestParameters authoriseRequestParameters = getAuthoriseRequestParameters(includedPTs, shopper, tokenRequest); final AuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); + when(internalOrderConverterMock.convert(request.getOrder())).thenReturn(createOrderWithMandatoryFields()); + final PaymentService paymentService = testObj.transform(request); VALIDATOR.validate(paymentService); @@ -99,11 +154,18 @@ public void testValidateXMLWithCreateTokenWithShopperScope() throws WorldpayVali @Test public void testValidateXMLWithCreateTokenWithMerchantScope() throws WorldpayValidationException, WorldpayModelTransformationException { final List includedPTs = singletonList(ONLINE); - final Shopper shopper = new Shopper(EMAIL_ADDRESS, AUTH_SHOPPER_ID, null, null); - final TokenRequest tokenRequest = new TokenRequest(TOKEN_REFERENCE, TOKEN_REASON, true); + final Shopper shopper = new Shopper(); + shopper.setShopperEmailAddress(EMAIL_ADDRESS); + shopper.setAuthenticatedShopperID(AUTH_SHOPPER_ID); + final TokenRequest tokenRequest = new TokenRequest(); + tokenRequest.setTokenEventReference(TOKEN_REFERENCE); + tokenRequest.setTokenReason(TOKEN_REASON); + tokenRequest.setMerchantToken(true); final AuthoriseRequestParameters authoriseRequestParameters = getAuthoriseRequestParameters(includedPTs, shopper, tokenRequest); final AuthoriseServiceRequest request = RedirectAuthoriseServiceRequest.createRedirectAuthoriseRequest(authoriseRequestParameters); + when(internalOrderConverterMock.convert(request.getOrder())).thenReturn(createOrderWithMandatoryFields()); + final PaymentService paymentService = testObj.transform(request); VALIDATOR.validate(paymentService); @@ -111,15 +173,24 @@ public void testValidateXMLWithCreateTokenWithMerchantScope() throws WorldpayVal protected AuthoriseRequestParameters getAuthoriseRequestParameters(final List includedPTs, final Shopper shopper, final TokenRequest tokenRequest) { return AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() - .withMerchantInfo(merchantInfo) - .withOrderInfo(basicOrderInfo) - .withOrderContent(ORDER_CONTENT) - .withIncludedPTs(includedPTs) - .withShopper(shopper) - .withShippingAddress(shippingAddress) - .withBillingAddress(billingAddress) - .withTokenRequest(tokenRequest) - .withStatementNarrative(STATEMENT_NARRATIVE_TEXT) - .build(); + .withMerchantInfo(merchantInfo) + .withOrderInfo(basicOrderInfo) + .withOrderContent(ORDER_CONTENT) + .withIncludedPTs(includedPTs) + .withShopper(shopper) + .withShippingAddress(shippingAddress) + .withBillingAddress(billingAddress) + .withTokenRequest(tokenRequest) + .withStatementNarrative(STATEMENT_NARRATIVE_TEXT) + .build(); + } + + private com.worldpay.internal.model.Order createOrderWithMandatoryFields() { + final com.worldpay.internal.model.Order intOrder = new com.worldpay.internal.model.Order(); + + intOrder.setOrderCode(ORDER_CODE); + intOrder.getDescriptionOrAmountOrRiskOrOrderContentOrPaymentMethodMaskOrPaymentDetailsOrPayAsOrderOrPaymentTokenIDOrShopperOrShippingAddressOrBillingAddressOrBranchSpecificExtensionOrExtendedOrderDetailOrRedirectPageAttributeOrPaymentMethodAttributeOrEchoDataOrStatementNarrativeOrHcgAdditionalDataOrThirdPartyDataOrResultURLOrShopperAdditionalDataOrApprovedAmountOrMandateOrAuthorisationAmountStatusOrDynamic3DSOrCreateTokenOrCreateTokenApprovalOrOrderLinesOrSubMerchantDataOrDynamicMCCOrDynamicInteractionTypeOrPrimeRoutingRequestOrRiskDataOrAdditional3DSDataOrExemptionOrShippingMethodOrProductSkuOrFraudSightDataOrDeviceSessionOrDynamicCurrencyConversionOrOverrideNarrativeOrInfo3DSecureOrSession().add(new Description()); + + return intOrder; } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/DirectAuthoriseServiceResponseTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/DirectAuthoriseServiceResponseTest.java index 7944ccce..9b7d95b4 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/DirectAuthoriseServiceResponseTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/DirectAuthoriseServiceResponseTest.java @@ -1,8 +1,8 @@ package com.worldpay.service.response; +import com.worldpay.data.Request3DInfo; import com.worldpay.enums.order.ThreeDSecureFlowEnum; import com.worldpay.enums.order.ThreeDSecureVersionEnum; -import com.worldpay.service.model.Request3DInfo; import org.junit.Test; import java.util.Optional; @@ -16,6 +16,7 @@ public class DirectAuthoriseServiceResponseTest { private static final String ISSUER_PAYLOAD = "issuerPayload"; private static final String MAJOR_3DS_VERSION1 = "1"; private static final String MAJOR_3DS_VERSION2 = "2"; + private static final String TRANSACTION_ID = "TransactionID"; @Test public void get3DSecureVersionReturnsAnEmptyOptionalIfThereIsNot3DSecureInfo() { @@ -40,7 +41,9 @@ public void get3DSecureVersionReturnsTheEnumVersionStoredInMajorVersionOfTheObje @Test public void get3DSecureFlowWithPaRequestAndIssuerUrlReturnsTheLegacyFlow() { final DirectAuthoriseServiceResponse testObj = new DirectAuthoriseServiceResponse(); - final Request3DInfo request3DInfo = new Request3DInfo(PA_REQUEST, ISSUER_URL); + final Request3DInfo request3DInfo = new Request3DInfo(); + request3DInfo.setPaRequest(PA_REQUEST); + request3DInfo.setIssuerUrl(ISSUER_URL); testObj.setRequest3DInfo(request3DInfo); @@ -52,7 +55,11 @@ public void get3DSecureFlowWithPaRequestAndIssuerUrlReturnsTheLegacyFlow() { @Test public void get3DSecureFlowWithIssuerUrlAnd3DMajorVersionAndIssuerPayloadAndTransactionIDReturns3DSecureFlexFlow() { final DirectAuthoriseServiceResponse testObj = new DirectAuthoriseServiceResponse(); - final Request3DInfo request3DInfo = new Request3DInfo(PA_REQUEST, ISSUER_URL, MAJOR_3DS_VERSION1, ISSUER_PAYLOAD); + final Request3DInfo request3DInfo = new Request3DInfo(); + request3DInfo.setIssuerUrl(ISSUER_URL); + request3DInfo.setMajor3DSVersion(MAJOR_3DS_VERSION1); + request3DInfo.setIssuerPayload(ISSUER_PAYLOAD); + request3DInfo.setTransactionId3DS(TRANSACTION_ID); testObj.setRequest3DInfo(request3DInfo); @@ -64,7 +71,8 @@ public void get3DSecureFlowWithIssuerUrlAnd3DMajorVersionAndIssuerPayloadAndTran @Test public void get3DSecureFlowWithIncompleteRequest3DInfoReturnsNull() { final DirectAuthoriseServiceResponse testObj = new DirectAuthoriseServiceResponse(); - final Request3DInfo request3DInfo = new Request3DInfo(PA_REQUEST, null); + final Request3DInfo request3DInfo = new Request3DInfo(); + request3DInfo.setPaRequest(PA_REQUEST); testObj.setRequest3DInfo(request3DInfo); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/CreateTokenResponseTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/CreateTokenResponseTransformerTest.java index a6ec704b..2d2aa5ee 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/CreateTokenResponseTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/CreateTokenResponseTransformerTest.java @@ -1,9 +1,9 @@ package com.worldpay.service.response.transform; import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.*; import com.worldpay.internal.model.Error; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.internal.model.*; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.response.CreateTokenResponse; import com.worldpay.service.response.ServiceResponse; import de.hybris.bootstrap.annotations.UnitTest; @@ -28,10 +28,6 @@ @RunWith(MockitoJUnitRunner.class) public class CreateTokenResponseTransformerTest { - @Rule - @SuppressWarnings("PMD.MemberScope") - public ExpectedException thrown = ExpectedException.none(); - private static final String AUTHENTICATED_SHOPPER = "authenticatedShopper"; private static final String TOKEN_EVENT_REFERENCE = "tokenEventReference"; private static final String TOKEN_REASON = "tokenReason"; @@ -49,6 +45,7 @@ public class CreateTokenResponseTransformerTest { private static final String ERROR_CODE = "errorCode"; private static final String ERROR_VALUE = "errorValue"; private static final String PAYPAL_TOKEN = "paypalToken"; + private static final String ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE = "Reply has no reply message or the reply type is not the expected one"; @InjectMocks private CreateTokenResponseTransformer testObj; @@ -59,11 +56,14 @@ public class CreateTokenResponseTransformerTest { private ServiceResponseTransformerHelper serviceResponseTransformerHelperMock; @Mock private TokenReply tokenReplyMock; + @Rule + @SuppressWarnings("PMD.MemberScope") + public ExpectedException thrown = ExpectedException.none(); @Test public void shouldRaiseErrorIfPaymentServiceReplyIsNull() throws WorldpayModelTransformationException { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("No reply message in Worldpay create token response"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); when(paymentServiceReplyMock.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify()).thenReturn(singletonList(null)); testObj.transform(paymentServiceReplyMock); @@ -72,7 +72,7 @@ public void shouldRaiseErrorIfPaymentServiceReplyIsNull() throws WorldpayModelTr @Test public void shouldRaiseErrorIfResponseTypeIsNotReply() throws WorldpayModelTransformationException { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("Reply type from Worldpay not the expected type"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); when(paymentServiceReplyMock.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify()).thenReturn(singletonList(new Submit())); testObj.transform(paymentServiceReplyMock); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/DeleteTokenResponseTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/DeleteTokenResponseTransformerTest.java index 5f9456fd..03e80db9 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/DeleteTokenResponseTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/DeleteTokenResponseTransformerTest.java @@ -1,9 +1,9 @@ package com.worldpay.service.response.transform; +import com.worldpay.data.token.DeleteTokenReply; import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.*; import com.worldpay.internal.model.Error; -import com.worldpay.service.model.token.DeleteTokenReply; +import com.worldpay.internal.model.*; import com.worldpay.service.response.DeleteTokenResponse; import com.worldpay.service.response.ServiceResponse; import de.hybris.bootstrap.annotations.UnitTest; @@ -30,6 +30,7 @@ public class DeleteTokenResponseTransformerTest { private static final String PAYMENT_TOKEN_ID = "paymentTokenId"; + private static final String ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE = "Reply has no reply message or the reply type is not the expected one"; @InjectMocks private DeleteTokenResponseTransformer testObj; @@ -75,7 +76,7 @@ public void shouldTransformPaymentServiceIntoDeleteTokenResponse() throws Except @Test public void shouldRaiseWorldpayModelTransformationExceptionWhenThereIsNoReplyInThePaymentService() throws Exception { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("No reply message in Worldpay delete token response"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); when(paymentServiceMock.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify()).thenReturn(singletonList(null)); testObj.transform(paymentServiceMock); @@ -84,7 +85,7 @@ public void shouldRaiseWorldpayModelTransformationExceptionWhenThereIsNoReplyInT @Test public void shouldRaiseWorldpayModelTransformationExceptionWhenResponseIsNotAReply() throws Exception { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("Reply type from Worldpay not the expected type"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); when(paymentServiceMock.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify()).thenReturn(singletonList(new Modify())); testObj.transform(paymentServiceMock); @@ -95,7 +96,7 @@ public void shouldThrowExceptionWhenResponseIsNotOk() throws Exception { thrown.expect(WorldpayModelTransformationException.class); thrown.expectMessage("DeleteTokenResponse did not contain an OK object"); when(replyMock.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken()). - thenReturn(singletonList(new Shopper())); + thenReturn(singletonList(new Shopper())); testObj.transform(paymentServiceMock); } @@ -105,7 +106,7 @@ public void shouldReturnDeleteTokenResponseWithErrorDetails() throws Exception { when(serviceResponseTransformerHelperMock.checkForError(any(DeleteTokenResponse.class), eq(replyMock))).thenReturn(true); when(replyMock.getOrderStatusOrBatchStatusOrErrorOrAddressCheckResponseOrRefundableAmountOrAccountBatchOrShopperOrOkOrFuturePayAgreementStatusOrShopperAuthenticationResultOrFuturePayPaymentResultOrPricePointOrCheckCardResponseOrPaymentOptionOrToken()) - .thenReturn(singletonList(errorMock)); + .thenReturn(singletonList(errorMock)); final ServiceResponse result = testObj.transform(paymentServiceMock); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/DirectAuthoriseResponseTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/DirectAuthoriseResponseTransformerTest.java index ceab23d0..64a5509b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/DirectAuthoriseResponseTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/DirectAuthoriseResponseTransformerTest.java @@ -1,10 +1,10 @@ package com.worldpay.service.response.transform; import com.worldpay.exception.WorldpayModelTransformationException; -import com.worldpay.internal.model.*; import com.worldpay.internal.model.Error; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.internal.model.*; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.response.DirectAuthoriseServiceResponse; import com.worldpay.service.response.ServiceResponse; import de.hybris.bootstrap.annotations.UnitTest; @@ -44,6 +44,7 @@ public class DirectAuthoriseResponseTransformerTest { private static final String TRANSACTION_ID_3DS = "transactionId3DS"; private static final String MAJOR_3DS_VERSION = "1"; private static final String ISSUER_PAYLOAD = "issuerPayload"; + private static final String ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE = "Reply has no reply message or the reply type is not the expected one"; @Rule public ExpectedException thrown = ExpectedException.none(); @@ -351,7 +352,7 @@ public void shouldThrowExceptionWhenOrderStatusTypeIsNull() throws WorldpayModel @Test public void shouldThrowExceptionWhenResponseTypeIsNull() throws WorldpayModelTransformationException { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("No reply message in Worldpay response"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); final PaymentService paymentServiceReply = new PaymentService(); @@ -363,7 +364,7 @@ public void shouldThrowExceptionWhenResponseTypeIsNull() throws WorldpayModelTra @Test public void shouldThrowExceptionWhenResponseTypeNotReply() throws WorldpayModelTransformationException { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("Reply type from Worldpay not the expected type"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); final PaymentService paymentServiceReply = new PaymentService(); paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify().add(new Notify()); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/RedirectAuthoriseResponseTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/RedirectAuthoriseResponseTransformerTest.java index f36f6c90..8b46c2d2 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/RedirectAuthoriseResponseTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/RedirectAuthoriseResponseTransformerTest.java @@ -3,7 +3,7 @@ import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.Error; import com.worldpay.internal.model.*; -import com.worldpay.service.model.token.TokenReply; +import com.worldpay.data.token.TokenReply; import com.worldpay.service.response.RedirectAuthoriseServiceResponse; import com.worldpay.service.response.ServiceResponse; import de.hybris.bootstrap.annotations.UnitTest; @@ -33,6 +33,7 @@ public class RedirectAuthoriseResponseTransformerTest { private static final String REFERENCE_VALUE = "referenceValue"; private static final String ERROR_CODE = "errorCode"; private static final String ERROR_DETAIL = "errorDetail"; + private static final String ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE = "Reply has no reply message or the reply type is not the expected one"; @Rule @SuppressWarnings("PMD.MemberScope") @@ -84,7 +85,7 @@ public void transformShouldReturnARedirectAuthoriseServiceResponse() throws Exce @Test public void shouldThrowWorldpayModelTransformationExceptionWhenResponseTypeIsNull() throws WorldpayModelTransformationException { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("No reply message in Worldpay response"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); final PaymentService paymentServiceReply = new PaymentService(); final List responseType = paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify(); responseType.add(null); @@ -95,7 +96,7 @@ public void shouldThrowWorldpayModelTransformationExceptionWhenResponseTypeIsNul @Test public void shouldThrowWorldpayModelTransformationExceptionWhenResponseTypeIsNotReply() throws WorldpayModelTransformationException { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("Reply type from Worldpay not the expected type"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); final PaymentService paymentServiceReply = new PaymentService(); final List responseType = paymentServiceReply.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify(); responseType.add(new Submit()); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/UpdateTokenResponseTransformerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/UpdateTokenResponseTransformerTest.java index 75f186d5..d872639d 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/UpdateTokenResponseTransformerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/UpdateTokenResponseTransformerTest.java @@ -3,7 +3,7 @@ import com.worldpay.exception.WorldpayModelTransformationException; import com.worldpay.internal.model.Error; import com.worldpay.internal.model.*; -import com.worldpay.service.model.token.UpdateTokenReply; +import com.worldpay.data.token.UpdateTokenReply; import com.worldpay.service.response.ServiceResponse; import com.worldpay.service.response.UpdateTokenResponse; import de.hybris.bootstrap.annotations.UnitTest; @@ -30,6 +30,7 @@ public class UpdateTokenResponseTransformerTest { private static final String PAYMENT_TOKEN_ID = "paymentTokenId"; private static final String ERROR_CODE = "errorCode"; private static final String ERROR_VALUE = "errorValue"; + private static final String ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE = "Update Token Response has no reply message or the reply type is not the expected one"; @InjectMocks private UpdateTokenResponseTransformer testObj; @@ -74,7 +75,7 @@ public void shouldTransformPaymentServiceIntoUpdateTokenResponse() throws Except @Test public void shouldRaiseWorldpayModelTransformationExceptionWhenThereIsNoReplyInThePaymentService() throws Exception { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("No reply message in Worldpay update token response"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); when(paymentServiceMock.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify()).thenReturn(singletonList(null)); testObj.transform(paymentServiceMock); @@ -83,7 +84,7 @@ public void shouldRaiseWorldpayModelTransformationExceptionWhenThereIsNoReplyInT @Test public void shouldRaiseWorldpayModelTransformationExceptionWhenResponseIsNotAReply() throws Exception { thrown.expect(WorldpayModelTransformationException.class); - thrown.expectMessage("Reply type from Worldpay not the expected type"); + thrown.expectMessage(ERROR_MSG_NO_REPLY_OR_NOT_EXPECTED_TYPE); when(paymentServiceMock.getSubmitOrModifyOrInquiryOrReplyOrNotifyOrVerify()).thenReturn(singletonList(new Modify())); testObj.transform(paymentServiceMock); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/impl/DefaultServiceResponseTransformerHelperTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/impl/DefaultServiceResponseTransformerHelperTest.java index 616b2a6c..820624de 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/impl/DefaultServiceResponseTransformerHelperTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/service/response/transform/impl/DefaultServiceResponseTransformerHelperTest.java @@ -1,15 +1,17 @@ package com.worldpay.service.response.transform.impl; +import com.worldpay.data.JournalReply; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.WebformRefundReply; +import com.worldpay.data.token.DeleteTokenReply; +import com.worldpay.data.token.TokenReply; +import com.worldpay.data.token.UpdateTokenReply; +import com.worldpay.enums.DebitCreditIndicator; import com.worldpay.internal.model.Error; import com.worldpay.internal.model.*; -import com.worldpay.service.model.JournalReply; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.WebformRefundReply; import com.worldpay.service.model.payment.PaymentType; -import com.worldpay.service.model.token.DeleteTokenReply; -import com.worldpay.service.model.token.TokenReply; -import com.worldpay.service.model.token.UpdateTokenReply; import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.servicelayer.dto.converter.Converter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -17,6 +19,7 @@ import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; +import java.util.Arrays; import java.util.List; import static com.worldpay.enums.order.AuthorisedStatus.AUTHORISED; @@ -29,6 +32,8 @@ @RunWith(MockitoJUnitRunner.class) public class DefaultServiceResponseTransformerHelperTest { + public static final String REASEON_CODE_1 = "Card Unfamiliarity"; + public static final String REASEON_CODE_2 = "High Risk Email"; private static final String RESPONSE_CODE = "responseCode"; private static final String ACTION_CODE = "action code"; private static final String TRANSACTION_ID = "transaction id"; @@ -106,9 +111,18 @@ public class DefaultServiceResponseTransformerHelperTest { private static final String BATCH_1 = "batch 1"; private static final String BATCH_2 = "batch 2"; private static final String TOKEN_ID = "token_id"; + private static final String FRAUD_SIGHT_ID = "188a9ae6-21c4-4fd9-87cd-8df4c719aaf1"; + private static final String SCORE = "0.5"; + private static final String LOW_RISK_LEVEL = "low-risk"; + @InjectMocks private DefaultServiceResponseTransformerHelper testObj; + @Mock + private Converter internalAmountReverseConverterMock; + @Mock + private Converter internalDateReverseConverterMock; + private Amount amount; private CVCResultCode cvcResultCode; private Balance balance; @@ -123,6 +137,7 @@ public class DefaultServiceResponseTransformerHelperTest { private AAVTelephoneResultCode aavTelephoneResultCode; private AuthorisationId authorisationId; private SchemeResponse schemeResponse; + private FraudSight fraudSightResponse; @Mock private UpdateTokenReceived updateTokenReceivedMock; @@ -134,11 +149,44 @@ public class DefaultServiceResponseTransformerHelperTest { private AccountTx accountTx1Mock, accountTx2Mock; @Mock private DeleteTokenReceived deletedTokenReceivedMock; + @Mock + private ReasonCodes reasonCodesMock; + @Mock + private Amount internalAmountMock; + @Mock + private com.worldpay.data.Amount amountMock, balanceAmountMock; + @Mock + private Date internalDateMock; + @Mock + private com.worldpay.data.Date dateMock, reportingDateMock; @Before public void setUp() { + testObj = new DefaultServiceResponseTransformerHelper(internalAmountReverseConverterMock, internalDateReverseConverterMock); + cardHolderName = new CardHolderName(); cardHolderName.setvalue(CARD_HOLDER_NAME); + + when(amountMock.getValue()).thenReturn(AMOUNT_VALUE); + when(amountMock.getCurrencyCode()).thenReturn(AMOUNT_CURRENCY_CODE); + when(amountMock.getDebitCreditIndicator()).thenReturn(DebitCreditIndicator.DEBIT); + when(amountMock.getExponent()).thenReturn(AMOUNT_EXPONENT); + when(balanceAmountMock.getValue()).thenReturn(BALANCE_AMOUNT_VALUE); + when(balanceAmountMock.getCurrencyCode()).thenReturn(BALANCE_AMOUNT_CURRENCY_CODE); + when(balanceAmountMock.getDebitCreditIndicator()).thenReturn(DebitCreditIndicator.DEBIT); + when(balanceAmountMock.getExponent()).thenReturn(BALANCE_AMOUNT_EXPONENT); + when(dateMock.getYear()).thenReturn(EXPIRY_YEAR); + when(dateMock.getMonth()).thenReturn(EXPIRY_MONTH); + when(dateMock.getDayOfMonth()).thenReturn(DAY_OF_MONTH); + when(dateMock.getHour()).thenReturn(HOUR); + when(dateMock.getMinute()).thenReturn(MINUTE); + when(dateMock.getSecond()).thenReturn(SECOND); + when(reportingDateMock.getYear()).thenReturn(REPORTING_EXPIRY_YEAR); + when(reportingDateMock.getMonth()).thenReturn(REPORTING_EXPIRY_MONTH); + when(reportingDateMock.getDayOfMonth()).thenReturn(REPORTING_DAY_OF_MONTH); + when(reportingDateMock.getHour()).thenReturn(REPORTING_HOUR); + when(reportingDateMock.getMinute()).thenReturn(REPORTING_MINUTE); + when(reportingDateMock.getSecond()).thenReturn(REPORTING_SECOND); when(journalMock.getJournalType()).thenReturn(AUTHORISED.name()); when(journalMock.getBookingDate()).thenReturn(bookingDateMock); when(bookingDateMock.getDate()).thenReturn(createDate()); @@ -149,6 +197,10 @@ public void setUp() { when(accountTx2Mock.getAccountType()).thenReturn(BUSSINESS_ACCOUNT); when(accountTx2Mock.getBatchId()).thenReturn(BATCH_2); when(deletedTokenReceivedMock.getPaymentTokenID()).thenReturn(TOKEN_ID); + when(internalAmountReverseConverterMock.convert(internalAmountMock)).thenReturn(amountMock); + when(internalAmountReverseConverterMock.convert(internalAmountMock)).thenReturn(balanceAmountMock); + when(internalDateReverseConverterMock.convert(internalDateMock)).thenReturn(dateMock); + when(internalDateReverseConverterMock.convert(internalDateMock)).thenReturn(reportingDateMock); } @Test @@ -161,6 +213,7 @@ public void testBuildPaymentReply() { createBalance(); createIso8583ReturnCode(); createRiskScore(); + createFraudSight(); createAavAddressResultCode(); createAavCardholderNameResultCode(); createAavEmailResultCode(); @@ -178,6 +231,7 @@ public void testBuildPaymentReply() { payment.getBalance().add(balance); payment.setISO8583ReturnCode(iso8583ReturnCode); payment.setRiskScore(riskScore); + payment.setFraudSight(fraudSightResponse); payment.setCardHolderName(cardHolderName); payment.setAAVAddressResultCode(aavAddressResultCode); payment.setAAVCardholderNameResultCode(aavCardholderNameResultCode); @@ -188,6 +242,10 @@ public void testBuildPaymentReply() { payment.setAuthorisationId(authorisationId); payment.setSchemeResponse(schemeResponse); + when(internalDateReverseConverterMock.convert(payment.getPaymentMethodDetail().getCard().getExpiryDate().getDate())).thenReturn(dateMock); + when(internalAmountReverseConverterMock.convert(payment.getBalance().get(0).getAmount())).thenReturn(balanceAmountMock); + when(internalAmountReverseConverterMock.convert(payment.getAmount())).thenReturn(amountMock); + final PaymentReply paymentReply = testObj.buildPaymentReply(payment); assertEquals(PAYMENT_METHOD, paymentReply.getPaymentMethodCode()); @@ -195,7 +253,7 @@ public void testBuildPaymentReply() { assertEquals(EXPIRY_YEAR, paymentReply.getCardDetails().getExpiryDate().getYear()); assertEquals(CARD_HOLDER_NAME, paymentReply.getCardDetails().getCardHolderName()); assertEquals(CARD_NUMBER, paymentReply.getCardDetails().getCardNumber()); - assertEquals(PaymentType.VISA, paymentReply.getCardDetails().getPaymentType()); + assertEquals(PaymentType.VISA.getMethodCode(), paymentReply.getCardDetails().getPaymentType()); assertEquals(AUTHORISED, paymentReply.getAuthStatus()); assertEquals(CVC_RESULT_CODE_DESCRIPTION, paymentReply.getCvcResultDescription()); assertEquals(ISO8583_RETURN_CODE_CODE, paymentReply.getReturnCode()); @@ -222,6 +280,26 @@ public void testBuildPaymentReply() { assertEquals(RESPONSE_CODE, paymentReply.getSchemeResponse().getResponseCode()); assertEquals(SCHEMA_NAME, paymentReply.getSchemeResponse().getSchemeName()); assertEquals(TRANSACTION_ID, paymentReply.getSchemeResponse().getTransactionIdentifier()); + + assertThat(paymentReply.getFraudSight().getId()).isEqualTo(FRAUD_SIGHT_ID); + assertThat(paymentReply.getFraudSight().getScore()).isEqualTo(0.5); + assertThat(paymentReply.getFraudSight().getMessage()).isEqualTo(LOW_RISK_LEVEL); + assertThat(paymentReply.getFraudSight().getReasonCodes()).hasSize(2); + assertThat(paymentReply.getFraudSight().getReasonCodes().get(0)).isEqualTo(REASEON_CODE_1); + assertThat(paymentReply.getFraudSight().getReasonCodes().get(1)).isEqualTo(REASEON_CODE_2); + } + + private void createFraudSight() { + fraudSightResponse = new FraudSight(); + fraudSightResponse.setId(FRAUD_SIGHT_ID); + fraudSightResponse.setScore(SCORE); + fraudSightResponse.setMessage(LOW_RISK_LEVEL); + final ReasonCode reasonCode1 = new ReasonCode(); + reasonCode1.setvalue(REASEON_CODE_1); + final ReasonCode reasonCode2 = new ReasonCode(); + reasonCode2.setvalue(REASEON_CODE_2); + when(reasonCodesMock.getReasonCode()).thenReturn(Arrays.asList(reasonCode1, reasonCode2)); + fraudSightResponse.setReasonCodes(reasonCodesMock); } private void createScheme() { @@ -307,6 +385,10 @@ public void buildPaymentReplyWithoutRiskScoreShouldNotSetRiskScoreOnPaymentReply payment.setRefundReference(REFUND_REFERENCE); payment.setAuthorisationId(authorisationId); + when(internalDateReverseConverterMock.convert(payment.getPaymentMethodDetail().getCard().getExpiryDate().getDate())).thenReturn(dateMock); + when(internalAmountReverseConverterMock.convert(payment.getBalance().get(0).getAmount())).thenReturn(balanceAmountMock); + when(internalAmountReverseConverterMock.convert(payment.getAmount())).thenReturn(amountMock); + final PaymentReply paymentReply = testObj.buildPaymentReply(payment); assertEquals(PAYMENT_METHOD, paymentReply.getPaymentMethodCode()); @@ -314,11 +396,11 @@ public void buildPaymentReplyWithoutRiskScoreShouldNotSetRiskScoreOnPaymentReply assertEquals(EXPIRY_YEAR, paymentReply.getCardDetails().getExpiryDate().getYear()); assertEquals(CARD_HOLDER_NAME, paymentReply.getCardDetails().getCardHolderName()); assertEquals(CARD_NUMBER, paymentReply.getCardDetails().getCardNumber()); - assertEquals(PaymentType.VISA, paymentReply.getCardDetails().getPaymentType()); + assertEquals(PaymentType.VISA.getMethodCode(), paymentReply.getCardDetails().getPaymentType()); assertEquals(AUTHORISED, paymentReply.getAuthStatus()); assertEquals(CVC_RESULT_CODE_DESCRIPTION, paymentReply.getCvcResultDescription()); assertEquals(ISO8583_RETURN_CODE_CODE, paymentReply.getReturnCode()); - assertThat(paymentReply.getRiskScore()).isEqualTo(null); + assertThat(paymentReply.getRiskScore()).isNull(); assertEquals(AAV_ADDRESS_RESULT_CODE_DESCRIPTION, paymentReply.getAavAddressResultCode()); assertEquals(AAV_CARDHOLDER_NAME_RESULT_CODE_DESCRIPTION, paymentReply.getAavCardholderNameResultCode()); assertEquals(AAV_EMAIL_RESULT_CODE_DESCRIPTION, paymentReply.getAavEmailResultCode()); @@ -381,6 +463,9 @@ public void shouldBuildTokenReply() { paymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().add(createCardDetails("VISA", null)); tokenElements.add(paymentInstrument); + final Date date = ((CardDetails) paymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().get(0)).getExpiryDate().getDate(); + when(internalDateReverseConverterMock.convert(date)).thenReturn(dateMock); + final Error error = new Error(); error.setCode(ERROR_CODE); error.setvalue(ERROR_MESSAGE); @@ -435,7 +520,7 @@ public void shouldBuildTokenReplyWithCartebleueVisa() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.CARTE_BLEUE); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.CARTE_BLEUE.getMethodCode()); } @Test @@ -449,7 +534,7 @@ public void shouldBuildTokenReplyWithCarteBancaireMasterCard() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.CARTE_BANCAIRE); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.CARTE_BANCAIRE.getMethodCode()); } @Test @@ -463,7 +548,7 @@ public void shouldBuildTokenReplyWithVisa() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.VISA); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.VISA.getMethodCode()); } @Test @@ -477,7 +562,7 @@ public void shouldBuildTokenReplyWithAirplus() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.AIRPLUS); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.AIRPLUS.getMethodCode()); } @Test @@ -491,7 +576,7 @@ public void shouldBuildTokenReplyWithAMEX() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.AMERICAN_EXPRESS); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.AMERICAN_EXPRESS.getMethodCode()); } @Test @@ -505,7 +590,7 @@ public void shouldBuildTokenReplyWithDankort() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.DANKORT); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.DANKORT.getMethodCode()); } @Test @@ -519,7 +604,7 @@ public void shouldBuildTokenReplyWithDiners() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.DINERS); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.DINERS.getMethodCode()); } @Test @@ -533,7 +618,7 @@ public void shouldBuildTokenReplyWithDiscover() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.DISCOVER); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.DISCOVER.getMethodCode()); } @Test @@ -547,7 +632,7 @@ public void shouldBuildTokenReplyWithJCB() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.JCB); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.JCB.getMethodCode()); } @Test @@ -561,7 +646,7 @@ public void shouldBuildTokenReplyWithMaestro() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.MAESTRO); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.MAESTRO.getMethodCode()); } @Test @@ -575,7 +660,7 @@ public void shouldBuildTokenReplyWithUATP() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.UATP); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.UATP.getMethodCode()); } @Test @@ -589,7 +674,7 @@ public void shouldBuildTokenReplyWithUnknownBrand() { final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.CARD_SSL); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.CARD_SSL.getMethodCode()); } @Test @@ -626,6 +711,9 @@ public void shouldBuildTokenReplyWithoutCardHolderNameInPaymentInstrument() { paymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().add(createCardDetailsWithoutCardHolderName()); tokenElements.add(paymentInstrument); + final Date date = ((CardDetails) paymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().get(0)).getExpiryDate().getDate(); + when(internalDateReverseConverterMock.convert(date)).thenReturn(dateMock); + final Error error = new Error(); error.setCode(ERROR_CODE); error.setvalue(ERROR_MESSAGE); @@ -707,6 +795,9 @@ public void shouldBuildTokenReplyWithoutCardAddress() { error.setvalue(ERROR_MESSAGE); tokenElements.add(error); + final Date date = ((CardDetails) paymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().get(0)).getExpiryDate().getDate(); + when(internalDateReverseConverterMock.convert(date)).thenReturn(dateMock); + final TokenReply tokenReply = testObj.buildTokenReply(token); assertEquals(AUTHENTICATED_SHOPPER_ID, tokenReply.getAuthenticatedShopperID()); @@ -760,6 +851,8 @@ public void shouldBuildTokenReplyWithoutExpiryDate() { tokenDetail.setReportingTokenExpiry(reportingTokenExpiry); tokenElements.add(tokenDetail); + when(internalDateReverseConverterMock.convert(reportingTokenExpiry.getDate())).thenReturn(reportingDateMock); + final PaymentInstrument paymentInstrument = new PaymentInstrument(); paymentInstrument.getCardDetailsOrPaypalOrSepaOrEmvcoTokenDetailsOrSAMSUNGPAYSSLOrPAYWITHGOOGLESSLOrAPPLEPAYSSLOrEMVCOTOKENSSL().add(createCardDetailsWithoutExpiryDate()); tokenElements.add(paymentInstrument); @@ -865,6 +958,8 @@ public void shouldBuildWebformRefundReply() { shopperWebformRefundDetails.setRefundId(REFUND_ID); shopperWebformRefundDetails.setAmount(amount); + when(internalAmountReverseConverterMock.convert(shopperWebformRefundDetails.getAmount())).thenReturn(amountMock); + final WebformRefundReply result = testObj.buildWebformRefundReply(shopperWebformRefundDetails); assertEquals(WEBFORM_URL, result.getWebformURL()); @@ -873,7 +968,7 @@ public void shouldBuildWebformRefundReply() { assertEquals(PAYMENT_ID, result.getPaymentId()); assertEquals(REASON, result.getReason()); assertEquals(REFUND_ID, result.getRefundId()); - final com.worldpay.service.model.Amount amountResult = result.getAmount(); + final com.worldpay.data.Amount amountResult = result.getAmount(); assertEquals(amount.getValue(), amountResult.getValue()); } @@ -897,7 +992,7 @@ public void buildTokenReply_shouldBuildTokenReplyWithCardContainingAnExistingPay final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.MASTERCARD); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.MASTERCARD.getMethodCode()); } @Test @@ -911,7 +1006,7 @@ public void buildTokenReply_shouldBuildTokenReplyWithCardContainingAnExistingPay final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.MASTERCARD); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.MASTERCARD.getMethodCode()); } @Test @@ -925,11 +1020,13 @@ public void buildTokenReply_shouldBuildTokenReplyWithCardContainingAnExistingPay final TokenReply tokenReply = testObj.buildTokenReply(token); - assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.CARD_SSL); + assertThat(tokenReply.getPaymentInstrument().getPaymentType()).isEqualTo(PaymentType.CARD_SSL.getMethodCode()); } @Test public void buildJournalReply_ShouldBuildTheJournal() { + when(internalDateReverseConverterMock.convert(journalMock.getBookingDate().getDate())).thenReturn(dateMock); + final JournalReply result = testObj.buildJournalReply(journalMock); assertThat(result).isNotNull(); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/strategy/impl/DefaultWorldpayAuthenticatedShopperIdStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/strategy/impl/DefaultWorldpayAuthenticatedShopperIdStrategyTest.java deleted file mode 100644 index 73e1ca6d..00000000 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/strategy/impl/DefaultWorldpayAuthenticatedShopperIdStrategyTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.worldpay.strategy.impl; - -import de.hybris.bootstrap.annotations.UnitTest; -import de.hybris.platform.core.model.user.CustomerModel; -import de.hybris.platform.core.model.user.UserModel; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static java.text.MessageFormat.format; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith (MockitoJUnitRunner.class) -public class DefaultWorldpayAuthenticatedShopperIdStrategyTest { - - private static final String CUSTOMER_ID = "customerId"; - private static final String ORIGINAL_UID = "originalUid"; - - @InjectMocks - private DefaultWorldpayAuthenticatedShopperIdStrategy testObj; - - @Mock - private CustomerModel customerModelMock; - - @Mock - private UserModel userModelMock; - - @Rule - @SuppressWarnings("PMD.MemberScope") - public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void shouldReturnCustomerIdAsAuthenticatedShopperId() throws Exception { - when(customerModelMock.getCustomerID()).thenReturn(CUSTOMER_ID); - - final String result = testObj.getAuthenticatedShopperId(customerModelMock); - - assertEquals(CUSTOMER_ID, result); - } - - @Test - public void shouldReturnOriginalUIDIfCustomerIdIsNotSet() throws Exception { - when(customerModelMock.getCustomerID()).thenReturn(""); - when(customerModelMock.getOriginalUid()).thenReturn(ORIGINAL_UID); - - final String result = testObj.getAuthenticatedShopperId(customerModelMock); - - assertEquals(ORIGINAL_UID, result); - } - - @Test - public void shouldThrowExceptionIfNotCustomer() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("The user {0} is not of type Customer.", userModelMock)); - - testObj.getAuthenticatedShopperId(userModelMock); - } - @Test - public void shouldRaiseErrorIfUserIsNull() throws Exception { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("The user is null"); - - testObj.getAuthenticatedShopperId(null); - } -} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/strategy/impl/DefaultWorldpayMerchantStrategyTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/strategy/impl/DefaultWorldpayMerchantStrategyTest.java index ec4a9d59..e3451b3f 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/strategy/impl/DefaultWorldpayMerchantStrategyTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/strategy/impl/DefaultWorldpayMerchantStrategyTest.java @@ -1,7 +1,7 @@ package com.worldpay.strategy.impl; -import com.worldpay.config.merchant.WorldpayMerchantConfigData; -import com.worldpay.merchant.WorldpayMerchantConfigDataService; +import com.worldpay.merchant.configuration.services.WorldpayMerchantConfigurationService; +import com.worldpay.model.WorldpayMerchantConfigurationModel; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.assistedserviceservices.AssistedServiceService; import de.hybris.platform.assistedserviceservices.utils.AssistedServiceSession; @@ -14,8 +14,6 @@ import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import java.util.Map; - import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; @@ -23,21 +21,15 @@ @RunWith(MockitoJUnitRunner.class) public class DefaultWorldpayMerchantStrategyTest { - private static final String WEB = "web"; - private static final String ASM_MERCHANT = "asm"; - private static final String REPLENISHMENT_MERCHANT = "replenishment"; - @InjectMocks private DefaultWorldpayMerchantStrategy testObj; @Mock private AssistedServiceService assistedServiceServiceMock; @Mock - private WorldpayMerchantConfigDataService worldpayMerchantConfigDataServiceMock; + private WorldpayMerchantConfigurationService worldpayMerchantConfigurationServiceMock; @Mock - private WorldpayMerchantConfigData websiteMerchantConfigDataMock, asmMerchantConfigDataMock, replenishmentMerchantConfigDataMock; - @Mock - private Map merchantConfigDataMapMock; + private WorldpayMerchantConfigurationModel websiteMerchantConfigMock, asmMerchantConfigMock; @Mock(answer = Answers.RETURNS_DEEP_STUBS) private AssistedServiceSession asmSessionMock; @Mock @@ -45,35 +37,26 @@ public class DefaultWorldpayMerchantStrategyTest { @Before public void setUp() throws Exception { - when(worldpayMerchantConfigDataServiceMock.getMerchantConfiguration()).thenReturn(merchantConfigDataMapMock); - when(merchantConfigDataMapMock.get(WEB)).thenReturn(websiteMerchantConfigDataMock); - when(merchantConfigDataMapMock.get(ASM_MERCHANT)).thenReturn(asmMerchantConfigDataMock); - when(merchantConfigDataMapMock.get(REPLENISHMENT_MERCHANT)).thenReturn(replenishmentMerchantConfigDataMock); + when(worldpayMerchantConfigurationServiceMock.getCurrentWebConfiguration()).thenReturn(websiteMerchantConfigMock); + when(worldpayMerchantConfigurationServiceMock.getCurrentAsmConfiguration()).thenReturn(asmMerchantConfigMock); } @Test - public void shouldReturnWebMerchant() throws Exception { + public void getMerchant_whenIsNotAsmSession_shouldReturnWebMerchant() { when(assistedServiceServiceMock.getAsmSession()).thenReturn(null); - final WorldpayMerchantConfigData result = testObj.getMerchant(); + final WorldpayMerchantConfigurationModel result = testObj.getMerchant(); - assertEquals(websiteMerchantConfigDataMock, result); + assertEquals(websiteMerchantConfigMock, result); } @Test - public void shouldReturnAsmMerchant() throws Exception { + public void getMerchant_whenIsAsmSession_shouldReturnAsmMerchant() { when(assistedServiceServiceMock.getAsmSession()).thenReturn(asmSessionMock); when(assistedServiceServiceMock.getAsmSession().getAgent()).thenReturn(userModelMock); - final WorldpayMerchantConfigData result = testObj.getMerchant(); - - assertEquals(asmMerchantConfigDataMock, result); - } - - @Test - public void shouldReturnReplenishmentMerchant() throws Exception { - final WorldpayMerchantConfigData result = testObj.getReplenishmentMerchant(); + final WorldpayMerchantConfigurationModel result = testObj.getMerchant(); - assertEquals(replenishmentMerchantConfigDataMock, result); + assertEquals(asmMerchantConfigMock, result); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/support/appender/impl/WorldpayMerchantConfigurationAppenderTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/support/appender/impl/WorldpayMerchantConfigurationAppenderTest.java index f494e247..f17ff4b8 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/support/appender/impl/WorldpayMerchantConfigurationAppenderTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/support/appender/impl/WorldpayMerchantConfigurationAppenderTest.java @@ -1,7 +1,7 @@ package com.worldpay.support.appender.impl; -import com.google.common.collect.ImmutableMap; -import com.worldpay.config.merchant.WorldpayMerchantConfigData; +import com.worldpay.merchant.configuration.services.WorldpayMerchantConfigurationService; +import com.worldpay.model.WorldpayMerchantConfigurationModel; import de.hybris.bootstrap.annotations.UnitTest; import org.apache.commons.lang.StringUtils; import org.junit.Test; @@ -12,11 +12,11 @@ import org.mockito.runners.MockitoJUnitRunner; import java.util.List; +import java.util.Set; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; @UnitTest @@ -30,41 +30,43 @@ public class WorldpayMerchantConfigurationAppenderTest { private static final String PAYMENT_METHOD_2 = "paymentMethod2"; private static final String PAYMENT_METHOD_3 = "paymentMethod3"; private static final String PAYMENT_METHOD_4 = "paymentMethod4"; - private static final String WEB_BEAN_ID = "webBeanId"; - private static final String MOBILE_BEAN_ID = "mobileBeanId"; + private static final String WEB_MERCHANT_ID = "webMerchantId"; + private static final String MOBILE_MERCHANT_ID = "mobileMerchantId"; @Spy @InjectMocks private WorldpayMerchantConfigurationAppender testObj; @Mock - private WorldpayMerchantConfigData webWorldpayMerchantConfigDataMock, mobileWorldpayMerchantConfigDataMock; + private WorldpayMerchantConfigurationService worldpayMerchantConfigurationServiceMock; + @Mock + private WorldpayMerchantConfigurationModel webWorldpayMerchantConfigurationMock, mobileWorldpayMerchantConfigurationMock; @Test public void appendContent_ShouldAppendMerchantConfiguration() { - final ImmutableMap configuredMerchants = ImmutableMap.of(WEB_BEAN_ID, webWorldpayMerchantConfigDataMock, MOBILE_BEAN_ID, mobileWorldpayMerchantConfigDataMock); - doReturn(configuredMerchants).when(testObj).getConfiguredMerchants(); - + when(worldpayMerchantConfigurationServiceMock.getAllSystemActiveSiteMerchantConfigurations()).thenReturn(Set.of(webWorldpayMerchantConfigurationMock, mobileWorldpayMerchantConfigurationMock)); final List includedPaymentMethods = asList(PAYMENT_METHOD_1, PAYMENT_METHOD_2); final List excludedPaymentMethods = asList(PAYMENT_METHOD_3, PAYMENT_METHOD_4); - when(webWorldpayMerchantConfigDataMock.getIncludedPaymentTypes()).thenReturn(includedPaymentMethods); - when(webWorldpayMerchantConfigDataMock.getExcludedPaymentTypes()).thenReturn(excludedPaymentMethods); - when(webWorldpayMerchantConfigDataMock.getMacValidation()).thenReturn(MAC_VALIDATION); - when(webWorldpayMerchantConfigDataMock.getCode()).thenReturn(MERCHANT_CODE); - when(webWorldpayMerchantConfigDataMock.getInstallationId()).thenReturn(INSTALLATION_ID); + when(webWorldpayMerchantConfigurationMock.getIncludedPaymentTypes()).thenReturn(includedPaymentMethods); + when(webWorldpayMerchantConfigurationMock.getExcludedPaymentTypes()).thenReturn(excludedPaymentMethods); + when(webWorldpayMerchantConfigurationMock.getMacValidation()).thenReturn(MAC_VALIDATION); + when(webWorldpayMerchantConfigurationMock.getCode()).thenReturn(MERCHANT_CODE); + when(webWorldpayMerchantConfigurationMock.getIdentifier()).thenReturn(WEB_MERCHANT_ID); + when(webWorldpayMerchantConfigurationMock.getInstallationId()).thenReturn(INSTALLATION_ID); - when(mobileWorldpayMerchantConfigDataMock.getIncludedPaymentTypes()).thenReturn(includedPaymentMethods); - when(mobileWorldpayMerchantConfigDataMock.getExcludedPaymentTypes()).thenReturn(excludedPaymentMethods); - when(mobileWorldpayMerchantConfigDataMock.getMacValidation()).thenReturn(MAC_VALIDATION); - when(mobileWorldpayMerchantConfigDataMock.getCode()).thenReturn(MERCHANT_CODE); - when(mobileWorldpayMerchantConfigDataMock.getInstallationId()).thenReturn(INSTALLATION_ID); + when(mobileWorldpayMerchantConfigurationMock.getIncludedPaymentTypes()).thenReturn(includedPaymentMethods); + when(mobileWorldpayMerchantConfigurationMock.getExcludedPaymentTypes()).thenReturn(excludedPaymentMethods); + when(mobileWorldpayMerchantConfigurationMock.getMacValidation()).thenReturn(MAC_VALIDATION); + when(mobileWorldpayMerchantConfigurationMock.getCode()).thenReturn(MERCHANT_CODE); + when(mobileWorldpayMerchantConfigurationMock.getIdentifier()).thenReturn(MOBILE_MERCHANT_ID); + when(mobileWorldpayMerchantConfigurationMock.getInstallationId()).thenReturn(INSTALLATION_ID); final String result = testObj.appendContent(); assertTrue(result.contains("Merchant Configuration")); - assertTrue(result.contains(WEB_BEAN_ID)); - assertTrue(result.contains(MOBILE_BEAN_ID)); + assertTrue(result.contains(WEB_MERCHANT_ID)); + assertTrue(result.contains(MOBILE_MERCHANT_ID)); assertEquals(2, StringUtils.countMatches(result, MERCHANT_CODE)); assertEquals(2, StringUtils.countMatches(result, INSTALLATION_ID)); @@ -79,5 +81,4 @@ public void appendContent_ShouldAppendMerchantConfiguration() { assertEquals(2, StringUtils.countMatches(result, PAYMENT_METHOD_4)); } } - diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/support/impl/DefaultWorldpaySupportEmailServiceIntegrationTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/support/impl/DefaultWorldpaySupportEmailServiceIntegrationTest.java index 9a07c2eb..3e328261 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/support/impl/DefaultWorldpaySupportEmailServiceIntegrationTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/support/impl/DefaultWorldpaySupportEmailServiceIntegrationTest.java @@ -19,7 +19,6 @@ public class DefaultWorldpaySupportEmailServiceIntegrationTest extends Servicela private static final String TIME = "Time:"; private static final String USER = "User:"; private static final String MERCHANT_CONFIGURATION = "Merchant Configuration:"; - private static final String CONFIGURED_MERCHANT_BEAN_NAME = "Configured Merchant Bean Name:"; private static final String ACTIVE_PAYMENT_FLOW = "Active Payment Flow:"; private static final String PAYMENT_TRANSACTION_TYPES = "Payment Transaction Types:"; private static final String EXTENSIONS = "Extensions:"; @@ -46,7 +45,6 @@ public void shouldCreateContent() { assertTrue(emailBody.contains(TIME)); assertTrue(emailBody.contains(USER)); assertTrue(emailBody.contains(MERCHANT_CONFIGURATION)); - assertTrue(emailBody.contains(CONFIGURED_MERCHANT_BEAN_NAME)); assertTrue(emailBody.contains(ACTIVE_PAYMENT_FLOW)); assertTrue(emailBody.contains(PAYMENT_TRANSACTION_TYPES)); assertTrue(emailBody.contains(EXTENSIONS)); @@ -54,9 +52,9 @@ public void shouldCreateContent() { } @After - public void tearDown(){ + public void tearDown() { configurationService.getConfiguration().clearProperty("worldpay.addon.version"); } } - + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionServiceTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionServiceTest.java index e80c1f04..ed2d8fd2 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionServiceTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionServiceTest.java @@ -6,12 +6,12 @@ import com.worldpay.model.WorldpayAavResponseModel; import com.worldpay.model.WorldpayBankConfigurationModel; import com.worldpay.model.WorldpayRiskScoreModel; -import com.worldpay.service.model.Amount; -import com.worldpay.service.model.PaymentReply; -import com.worldpay.service.model.RiskScore; +import com.worldpay.data.Amount; +import com.worldpay.data.PaymentReply; +import com.worldpay.data.RiskScore; import com.worldpay.service.notification.OrderNotificationMessage; -import com.worldpay.service.payment.WorldpayOrderService; -import com.worldpay.transaction.EntryCodeStrategy; +import com.worldpay.service.payment.WorldpayFraudSightStrategy; +import com.worldpay.transaction.WorldpayPaymentTransactionUtils; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.commerceservices.service.data.CommerceCheckoutParameter; import de.hybris.platform.converters.Populator; @@ -23,12 +23,9 @@ import de.hybris.platform.payment.enums.PaymentTransactionType; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; -import de.hybris.platform.servicelayer.config.ConfigurationService; import de.hybris.platform.servicelayer.dto.converter.Converter; import de.hybris.platform.servicelayer.exceptions.ModelNotFoundException; -import de.hybris.platform.servicelayer.i18n.CommonI18NService; import de.hybris.platform.servicelayer.model.ModelService; -import org.apache.commons.configuration.Configuration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -75,17 +72,26 @@ public class DefaultWorldpayPaymentTransactionServiceTest { private DefaultWorldpayPaymentTransactionService testObj; @Mock - private PaymentTransactionModel paymentTransactionModelMock; + private ModelService modelServiceMock; @Mock - private PaymentTransactionEntryModel authorisedAndAcceptedAndNotPendingEntryMock, authorisedAndAcceptedAndPendingEntryMock, authorisedAndRejectedAndPendingEntryMock, pendingCaptureEntryMock; + private WorldpayPaymentTransactionDao worldpayPaymentTransactionDaoMock; @Mock - private PaymentTransactionEntryModel capturedEntryMock; + private Converter worldpayRiskScoreConverterMock; @Mock - private OrderModel orderModelMock; + private Populator worldpayAavResponsePopulatorMock; @Mock - private ModelService modelServiceMock; + private WorldpayPaymentTransactionUtils worldpayPaymentTransactionUtilsMock; + @Mock + private WorldpayFraudSightStrategy worldpayFraudSightStrategyMock; + @Mock + private WorldpayBankConfigurationLookupService worldpayBankConfigurationServiceMock; + + @Mock + private PaymentTransactionEntryModel authorisedAndAcceptedAndNotPendingEntryMock, authorisedAndAcceptedAndPendingEntryMock, authorisedAndRejectedAndPendingEntryMock, pendingCaptureEntryMock, pendingCancelEntryMock; + @Mock + private PaymentTransactionEntryModel capturedEntryMock; @Mock - private CommonI18NService commonI18NServiceMock; + private OrderModel orderModelMock; @Mock private CurrencyModel currencyModelMock; @Mock(answer = Answers.RETURNS_DEEP_STUBS) @@ -97,11 +103,7 @@ public class DefaultWorldpayPaymentTransactionServiceTest { @Mock private PaymentInfoModel paymentInfoModelMock; @Mock - private EntryCodeStrategy entryCodeStrategyMock; - @Mock - private WorldpayPaymentTransactionDao worldpayPaymentTransactionDaoMock; - @Mock - private PaymentTransactionModel notApmOpenPaymentTransactionModelMock, apmOpenPaymentTransactionModelMock; + private PaymentTransactionModel notApmOpenPaymentTransactionModelMock, apmOpenPaymentTransactionModelMock, paymentTransactionModelMock; @Mock private RedirectAuthoriseResult redirectAuthoriseResultMock; @Mock @@ -109,38 +111,23 @@ public class DefaultWorldpayPaymentTransactionServiceTest { @Mock private RiskScore riskScoreMock; @Mock - private Converter worldpayRiskScoreConverterMock; - @Mock private WorldpayRiskScoreModel worldpayRiskScoreModelMock; @Mock private WorldpayAavResponseModel worldpayAavResponseModelMock; @Mock - private Populator worldpayAavResponsePopulatorMock; - @Mock private PaymentTransactionEntryModel paymentTransactionEntryModelMock; @Mock private CommerceCheckoutParameter commerceCheckoutParameterMock; @Mock private BigDecimal bigDecimalMock; @Mock - private ConfigurationService configurationServiceMock; - @Mock - private Configuration configurationMock; - @Mock - private WorldpayBankConfigurationLookupService worldpayBankConfigurationServiceMock; - @Mock private WorldpayBankConfigurationModel worldpayBankConfigurationMock; @Mock private AbstractOrderModel abstractOrderMock; - @Mock - private WorldpayOrderService worldpayOrderServiceMock; @Before public void setUp() { - Whitebox.setInternalState(testObj, "paymentTransactionDependency", Map.of( - CAPTURE, AUTHORIZATION, - SETTLED, CAPTURE - )); + Whitebox.setInternalState(testObj, "worldpayRiskScoreConverter", worldpayRiskScoreConverterMock); when(authorisedAndAcceptedAndNotPendingEntryMock.getType()).thenReturn(AUTHORIZATION); when(authorisedAndAcceptedAndNotPendingEntryMock.getTransactionStatus()).thenReturn(ACCEPTED.name()); when(authorisedAndAcceptedAndNotPendingEntryMock.getPending()).thenReturn(Boolean.FALSE); @@ -153,13 +140,13 @@ public void setUp() { when(authorisedAndRejectedAndPendingEntryMock.getTransactionStatus()).thenReturn(REJECTED.name()); when(authorisedAndRejectedAndPendingEntryMock.getPending()).thenReturn(Boolean.FALSE); + when(pendingCancelEntryMock.getType()).thenReturn(CANCEL); + when(pendingCancelEntryMock.getPending()).thenReturn(Boolean.TRUE); + when(capturedEntryMock.getType()).thenReturn(CAPTURE); when(capturedEntryMock.getTransactionStatus()).thenReturn(ACCEPTED.name()); when(capturedEntryMock.getPending()).thenReturn(Boolean.FALSE); when(orderModelMock.getPaymentTransactions()).thenReturn(Collections.singletonList(paymentTransactionModelMock)); - - when(entryCodeStrategyMock.generateCode(paymentTransactionModelMock)).thenReturn(TRANSACTION_ENTRY_CODE); - when(modelServiceMock.create(PaymentTransactionEntryModel.class)).thenReturn(authorisedAndAcceptedAndPendingEntryMock); when(modelServiceMock.create(PaymentTransactionModel.class)).thenReturn(paymentTransactionModelMock); @@ -170,7 +157,6 @@ public void setUp() { when(apmOpenPaymentTransactionModelMock.getApmOpen()).thenReturn(Boolean.TRUE); when(cartModelMock.getWorldpayOrderCode()).thenReturn(WORLDPAY_ORDER_CODE); - when(worldpayOrderServiceMock.convertAmount(amountMock)).thenReturn(BigDecimal.TEN); when(amountMock.getCurrencyCode()).thenReturn(currency.getCurrencyCode()); when(capturedEntryMock.getAmount()).thenReturn(BigDecimal.TEN); @@ -179,7 +165,6 @@ public void setUp() { when(orderNotificationMessageMock.getOrderCode()).thenReturn(REQUEST_ID); when(orderNotificationMessageMock.getMerchantCode()).thenReturn(REQUEST_TOKEN); - when(commonI18NServiceMock.getCurrency(currency.getCurrencyCode())).thenReturn(currencyModelMock); when(commerceCheckoutParameterMock.getAuthorizationAmount()).thenReturn(BigDecimal.TEN); when(commerceCheckoutParameterMock.getCart()).thenReturn(cartModelMock); @@ -190,10 +175,18 @@ public void setUp() { when(paymentTransactionModelMock.getEntries()).thenReturn(Collections.singletonList(authorisedAndAcceptedAndNotPendingEntryMock)); when(authorisedAndAcceptedAndNotPendingEntryMock.getType()).thenReturn(AUTHORIZATION); when(authorisedAndAcceptedAndNotPendingEntryMock.getAmount()).thenReturn(new BigDecimal(50)); - when(configurationServiceMock.getConfiguration()).thenReturn(configurationMock); - when(configurationMock.getDouble("worldpayapi.authoriseamount.validation.tolerance")).thenReturn(0.01); + when(cartModelMock.getShopperBankCode()).thenReturn(BANK_CODE); when(worldpayBankConfigurationServiceMock.getBankConfigurationForBankCode(BANK_CODE)).thenReturn(worldpayBankConfigurationMock); + + when(worldpayPaymentTransactionUtilsMock.generatePaymentTransactionCode(paymentTransactionModelMock)).thenReturn(TRANSACTION_ENTRY_CODE); + when(worldpayPaymentTransactionUtilsMock.convertAmount(amountMock)).thenReturn(BigDecimal.TEN); + when(worldpayPaymentTransactionUtilsMock.getCurrencyFromAmount(amountMock)).thenReturn(currencyModelMock); + when(worldpayPaymentTransactionUtilsMock.getAuthoriseAmountToleranceFromConfig()).thenReturn(0.01); + when(worldpayPaymentTransactionUtilsMock.getPaymentTransactionDependency()).thenReturn(Map.of( + CAPTURE, AUTHORIZATION, + SETTLED, CAPTURE + )); } @Test @@ -300,6 +293,16 @@ public void isPreviousTransactionCompleted_WhenTransactionIsNonDependantOnAPrevi assertTrue(result); } + @Test + public void isPreviousTransactionCompleted_WhenTransactionRefundForVoidOrder_ShouldReturnTrue() { + when(paymentTransactionModelMock.getRequestId()).thenReturn(WORLDPAY_ORDER_CODE); + when(paymentTransactionModelMock.getEntries()).thenReturn(Collections.singletonList(pendingCancelEntryMock)); + + final boolean result = testObj.isPreviousTransactionCompleted(WORLDPAY_ORDER_CODE, AUTHORIZATION, orderModelMock); + + assertTrue(result); + } + @Test public void createPendingAuthorisePaymentTransactionEntry_ShouldCreatePendingAuthorizationPaymentTransactionEntry() { when(paymentTransactionModelMock.getCode()).thenReturn(TRANSACTION_ENTRY_CODE); @@ -565,7 +568,7 @@ public void isAuthorisedAmountCorrect_WhenCorrectAuthorisedAmountDiffEqualToTole @Test public void isAuthorisedAmountCorrect_WhenZeroToleranceAndDiffAboveZero_ShouldReturnFalse() { - when(configurationMock.getDouble("worldpayapi.authoriseamount.validation.tolerance")).thenReturn(0.00); + when(worldpayPaymentTransactionUtilsMock.getAuthoriseAmountToleranceFromConfig()).thenReturn(0.00); when(orderModelMock.getTotalPrice()).thenReturn(50.01); boolean result = testObj.isAuthorisedAmountCorrect(orderModelMock); @@ -575,7 +578,7 @@ public void isAuthorisedAmountCorrect_WhenZeroToleranceAndDiffAboveZero_ShouldRe @Test public void isAuthorisedAmountCorrect_WhenZeroToleranceAndZeroDiff_ShouldReturnTrue() { - when(configurationMock.getDouble("worldpayapi.authoriseamount.validation.tolerance")).thenReturn(0.00); + when(worldpayPaymentTransactionUtilsMock.getAuthoriseAmountToleranceFromConfig()).thenReturn(0.00); when(orderModelMock.getTotalPrice()).thenReturn(50.00); boolean result = testObj.isAuthorisedAmountCorrect(orderModelMock); @@ -609,6 +612,22 @@ public void createNotPendingCancelOrderTransactionEntry_ShouldCreateCancelTransa verify(modelServiceMock).save(result); } + @Test + public void addFraudSightToPaymentTransaction_WhenFraudSightEnabled_ShouldAddFraudSightToTransaction() { + when(worldpayFraudSightStrategyMock.isFraudSightEnabled()).thenReturn(true); + + testObj.addFraudSightToPaymentTransaction(paymentTransactionModelMock, paymentReplyMock); + + verify(worldpayFraudSightStrategyMock).addFraudSight(paymentTransactionModelMock, paymentReplyMock); + } + + @Test + public void addFraudSightToPaymentTransaction_WhenFraudSightIsNotEnabled_ShouldNotAddFraudSightToTransaction() { + testObj.addFraudSightToPaymentTransaction(paymentTransactionModelMock, paymentReplyMock); + + verify(worldpayFraudSightStrategyMock, never()).addFraudSight(paymentTransactionModelMock, paymentReplyMock); + } + protected void verifyPaymentTransactionEntry(final PaymentTransactionEntryModel result, final PaymentTransactionType transactionType, final Boolean pendingFlag) { verify(result).setType(transactionType); verify(result).setRequestId(REQUEST_ID); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionUtilsTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionUtilsTest.java new file mode 100644 index 00000000..124701b1 --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/DefaultWorldpayPaymentTransactionUtilsTest.java @@ -0,0 +1,94 @@ +package com.worldpay.transaction.impl; + +import com.worldpay.data.Amount; +import com.worldpay.service.payment.WorldpayOrderService; +import com.worldpay.transaction.EntryCodeStrategy; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.core.model.c2l.CurrencyModel; +import de.hybris.platform.payment.enums.PaymentTransactionType; +import de.hybris.platform.payment.model.PaymentTransactionModel; +import de.hybris.platform.servicelayer.config.ConfigurationService; +import de.hybris.platform.servicelayer.i18n.CommonI18NService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Answers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.internal.util.reflection.Whitebox; +import org.mockito.runners.MockitoJUnitRunner; + +import java.math.BigDecimal; +import java.util.Map; + +import static de.hybris.platform.payment.enums.PaymentTransactionType.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +@UnitTest +public class DefaultWorldpayPaymentTransactionUtilsTest { + + private static final String TRANSACTION_CODE = "transactionEntryCode"; + private static final String CURRENCY_CODE = "currencyCode"; + + @InjectMocks + private DefaultWorldpayPaymentTransactionUtils testObj; + + @Mock + private EntryCodeStrategy entryCodeStrategyMock; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private ConfigurationService configurationServiceMock; + @Mock + private WorldpayOrderService worldpayOrderServiceMock; + @Mock + private CommonI18NService commonI18NServiceMock; + @Mock + private CurrencyModel currencyModelMock; + + @Mock + private Amount amountMock; + @Mock + private PaymentTransactionModel paymentTransactionModelMock; + + @Before + public void setUp() { + Whitebox.setInternalState(testObj, "paymentTransactionDependency", Map.of( + CAPTURE, AUTHORIZATION, + SETTLED, CAPTURE + )); + when(entryCodeStrategyMock.generateCode(paymentTransactionModelMock)).thenReturn(TRANSACTION_CODE); + when(worldpayOrderServiceMock.convertAmount(amountMock)).thenReturn(BigDecimal.TEN); + when(amountMock.getCurrencyCode()).thenReturn(CURRENCY_CODE); + when(commonI18NServiceMock.getCurrency(CURRENCY_CODE)).thenReturn(currencyModelMock); + when(configurationServiceMock.getConfiguration().getDouble("worldpayapi.authoriseamount.validation.tolerance")).thenReturn(0.01); + } + + @Test + public void generatePaymentTransactionCode_ShouldReturnTheGeneratedCode() { + final String result = testObj.generatePaymentTransactionCode(paymentTransactionModelMock); + + assertThat(result).isEqualTo(TRANSACTION_CODE); + } + + @Test + public void getPaymentTransactionDependency_ShouldReturnTheMap() { + Map result = testObj.getPaymentTransactionDependency(); + assertThat(result).containsKeys(CAPTURE, SETTLED); + assertThat(result).containsValues(AUTHORIZATION, CAPTURE); + } + + @Test + public void getCurrencyFromAmount_ShouldreturnTheCurrency() { + final CurrencyModel result = testObj.getCurrencyFromAmount(amountMock); + + assertThat(result).isEqualTo(currencyModelMock); + } + + @Test + public void getAuthoriseAmountToleranceFromConfig_ShouldReturnConfigValue() { + final double result = testObj.getAuthoriseAmountToleranceFromConfig(); + + assertThat(result).isEqualTo(0.01); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/WorldpayEntryCodeStrategyImplTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/WorldpayEntryCodeStrategyImplTest.java index 07f8cb30..d375a2ec 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/WorldpayEntryCodeStrategyImplTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/transaction/impl/WorldpayEntryCodeStrategyImplTest.java @@ -16,10 +16,11 @@ import static org.mockito.Mockito.when; @UnitTest -@RunWith (MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class WorldpayEntryCodeStrategyImplTest { - public static final String PAYMENT_TRANSACTION_CODE = "paymentTransactionCode"; + private static final String PAYMENT_TRANSACTION_CODE = "paymentTransactionCode"; + @InjectMocks private EntryCodeStrategy testObj = new WorldpayEntryCodeStrategyImpl(); @@ -29,7 +30,7 @@ public class WorldpayEntryCodeStrategyImplTest { private PaymentTransactionEntryModel transactionEntry1Mock; @Test - public void generateNewEntryCodeShouldReturnCodeEndingInEntriesSizePlusOne() throws Exception { + public void generateCode_WhenNewEntryCode_ShouldReturnCodeEndingInEntriesSizePlusOne() { when(paymentTransactionModelMock.getEntries()).thenReturn(Collections.singletonList(transactionEntry1Mock)); when(paymentTransactionModelMock.getCode()).thenReturn(PAYMENT_TRANSACTION_CODE); @@ -39,7 +40,7 @@ public void generateNewEntryCodeShouldReturnCodeEndingInEntriesSizePlusOne() thr } @Test - public void generateNewEntryCodeShouldReturnCodeEndingIn1WhenEntriesIsNull() throws Exception { + public void generateCode_WhenNoEntries_ShouldReturnCodeEndingIn1WhenEntriesIsNull() { when(paymentTransactionModelMock.getEntries()).thenReturn(null); when(paymentTransactionModelMock.getCode()).thenReturn(PAYMENT_TRANSACTION_CODE); @@ -47,4 +48,4 @@ public void generateNewEntryCodeShouldReturnCodeEndingIn1WhenEntriesIsNull() thr assertEquals(PAYMENT_TRANSACTION_CODE + "-1", result); } -} \ No newline at end of file +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/util/WorldpayInternalModelTransformerUtilTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/util/WorldpayInternalModelTransformerUtilTest.java new file mode 100644 index 00000000..b7585ebc --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/testsrc/com/worldpay/util/WorldpayInternalModelTransformerUtilTest.java @@ -0,0 +1,136 @@ +package com.worldpay.util; + +import com.worldpay.data.Date; +import com.worldpay.data.PaymentDetails; +import com.worldpay.data.Session; +import com.worldpay.data.Shopper; +import com.worldpay.data.klarna.KlarnaMerchantUrls; +import com.worldpay.data.klarna.KlarnaPayment; +import com.worldpay.data.klarna.KlarnaRedirectURLs; +import com.worldpay.data.payment.*; +import com.worldpay.enums.PaymentAction; +import com.worldpay.service.model.payment.PaymentType; +import com.worldpay.service.request.AuthoriseRequestParameters; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.runners.MockitoJUnitRunner; + +import java.time.LocalDateTime; + +import static org.assertj.core.api.Assertions.assertThat; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class WorldpayInternalModelTransformerUtilTest { + + private static final String CHECKOUT_URL = "checkoutURL"; + private static final String CONFIRMATION_URL = "confirmationURL"; + private static final String COUNTRY_CODE = "ES"; + private static final String SHOPPER_LOCALE = "shopperLocale"; + private static final String EXTRA_MERCHANT_DATA = "extraMerchantData"; + private static final String SHOPPER_BANK_CODE = "shopperBankCode"; + private static final String SUCCESS_URL = "successURL"; + private static final String FAILURE_URL = "failureURL"; + private static final String PENDING_URL = "pendingURL"; + private static final String CANCEL_URL = "cancelURL"; + @InjectMocks + private WorldpayInternalModelTransformerUtil testObj; + + + private Payment payment = new Cse(); + private Shopper shopper = new Shopper(); + private StoredCredentials storedCredentials = new StoredCredentials(); + private PaymentAction action = PaymentAction.AUTHORISE; + + @Test + public void newDateFromLocalDateTime_ShouldReturnDate() { + final LocalDateTime sourceMock = LocalDateTime.of(2021, 1, 1, 1, 1, 1); + + final Date result = testObj.newDateFromLocalDateTime(sourceMock); + + assertThat(result.getDayOfMonth()).isEqualTo("1"); + assertThat(result.getYear()).isEqualTo("2021"); + assertThat(result.getSecond()).isEqualTo("1"); + assertThat(result.getMonth()).isEqualTo("1"); + assertThat(result.getMinute()).isEqualTo("1"); + assertThat(result.getHour()).isEqualTo("1"); + + } + + @Test + public void createAlternativePayment_ShouldReturnAlternativePayment() { + + final AlternativePayment result = testObj.createAlternativePayment(PaymentType.IDEAL, SUCCESS_URL, FAILURE_URL, CANCEL_URL, PENDING_URL, COUNTRY_CODE); + + assertThat(result.getCancelURL()).isEqualTo(CANCEL_URL); + assertThat(result.getPendingURL()).isEqualTo(PENDING_URL); + assertThat(result.getFailureURL()).isEqualTo(FAILURE_URL); + assertThat(result.getSuccessURL()).isEqualTo(SUCCESS_URL); + assertThat(result.getShopperCountryCode()).isEqualTo(COUNTRY_CODE); + assertThat(result.getPaymentType()).isEqualTo(PaymentType.IDEAL.getMethodCode()); + } + + @Test + public void createAlternativeShopperBankCodePayment() { + final AlternativeShopperBankCodePayment result = testObj.createAlternativeShopperBankCodePayment(PaymentType.IDEAL, SHOPPER_BANK_CODE, SUCCESS_URL, FAILURE_URL, CANCEL_URL, PENDING_URL, COUNTRY_CODE); + + assertThat(result.getCancelURL()).isEqualTo(CANCEL_URL); + assertThat(result.getPendingURL()).isEqualTo(PENDING_URL); + assertThat(result.getFailureURL()).isEqualTo(FAILURE_URL); + assertThat(result.getSuccessURL()).isEqualTo(SUCCESS_URL); + assertThat(result.getShopperCountryCode()).isEqualTo(COUNTRY_CODE); + assertThat(result.getShopperBankCode()).isEqualTo(SHOPPER_BANK_CODE); + assertThat(result.getPaymentType()).isEqualTo(PaymentType.IDEAL.getMethodCode()); + } + + @Test + public void createPaymentDetailsFromRequestParameters_ShouldReturnPaymentDetails() { + shopper.setSession(new Session()); + final AuthoriseRequestParameters authoriseRequestParameters = AuthoriseRequestParameters.AuthoriseRequestParametersBuilder.getInstance() + .withPayment(payment) + .withShopper(shopper) + .withStoredCredentials(storedCredentials) + .withPaymentDetailsAction(action) + .build(); + + final PaymentDetails result = testObj.createPaymentDetailsFromRequestParameters(authoriseRequestParameters); + + assertThat(result.getAction()).isEqualTo(PaymentAction.AUTHORISE); + assertThat(result.getPayment()).isEqualTo(payment); + assertThat(result.getSession()).isEqualTo(shopper.getSession()); + assertThat(result.getStoredCredentials()).isEqualTo(storedCredentials); + } + + @Test + public void createKlarnaPayment_ShouldRetunrKLARNASSL() { + final KlarnaMerchantUrls merchantUrls = new KlarnaMerchantUrls(); + merchantUrls.setCheckoutURL(CHECKOUT_URL); + merchantUrls.setConfirmationURL(CONFIRMATION_URL); + + final KlarnaPayment result = testObj.createKlarnaPayment(COUNTRY_CODE, SHOPPER_LOCALE, merchantUrls, EXTRA_MERCHANT_DATA); + + assertThat(result.getPurchaseCountry()).isEqualTo(COUNTRY_CODE); + assertThat(result.getMerchantUrls().getCheckoutURL()).isEqualTo(merchantUrls.getCheckoutURL()); + assertThat(result.getExtraMerchantData()).isEqualTo(EXTRA_MERCHANT_DATA); + assertThat(result.getShopperLocale()).isEqualTo(SHOPPER_LOCALE); + } + + @Test + public void createKlarnaPayment_ShouldRetunrKLARNAPAYNOWSSL() { + final KlarnaRedirectURLs klarnaRedirectURLs = new KlarnaRedirectURLs(); + klarnaRedirectURLs.setSuccessURL(SUCCESS_URL); + klarnaRedirectURLs.setCancelURL(CANCEL_URL); + klarnaRedirectURLs.setPendingURL(PENDING_URL); + klarnaRedirectURLs.setFailureURL(FAILURE_URL); + + final KlarnaPayment result = testObj.createKlarnaPayment(COUNTRY_CODE, SHOPPER_LOCALE, EXTRA_MERCHANT_DATA, PaymentType.KLARNAPAYNOWSSL.getMethodCode(), klarnaRedirectURLs); + + assertThat(result.getShopperCountryCode()).isEqualTo(COUNTRY_CODE); + assertThat(result.getExtraMerchantData()).isEqualTo(EXTRA_MERCHANT_DATA); + assertThat(result.getLocale()).isEqualTo(SHOPPER_LOCALE); + assertThat(result.getPaymentType()).isEqualTo(PaymentType.KLARNAPAYNOWSSL.getMethodCode()); + assertThat(result.getSuccessURL()).isEqualTo(SUCCESS_URL); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayapi/unmanaged-dependencies.txt b/hybris/bin/y-ext/ext-worldpay/worldpayapi/unmanaged-dependencies.txt index aaece98e..cc63ef54 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayapi/unmanaged-dependencies.txt +++ b/hybris/bin/y-ext/ext-worldpay/worldpayapi/unmanaged-dependencies.txt @@ -1 +1 @@ -worldpay-core-*.jar +dtd-conversion/*.jar diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepController.java b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepController.java index d3862c9f..4fddfdd9 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepController.java @@ -13,12 +13,14 @@ import de.hybris.platform.acceleratorstorefrontcommons.annotations.RequireHardLogIn; import de.hybris.platform.acceleratorstorefrontcommons.controllers.util.GlobalMessages; import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @@ -26,8 +28,8 @@ import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; -import static org.springframework.web.bind.annotation.RequestMethod.GET; -import static org.springframework.web.bind.annotation.RequestMethod.POST; +import java.text.SimpleDateFormat; +import java.util.Date; /** * Worldpay controller to handle CSE @@ -36,7 +38,7 @@ @RequestMapping(value = "/checkout/multi/worldpay/cse") public class WorldpayCseCheckoutStepController extends AbstractWorldpayDirectCheckoutStepController { - private static final Logger LOGGER = Logger.getLogger(WorldpayCseCheckoutStepController.class); + private static final Logger LOGGER = LoggerFactory.getLogger(WorldpayCseCheckoutStepController.class); protected static final String CSE_PUBLIC_KEY = "csePublicKey"; protected static final String B2B_CSE_PAYMENT_FORM = "b2bCSEPaymentForm"; @@ -66,7 +68,7 @@ public class WorldpayCseCheckoutStepController extends AbstractWorldpayDirectChe * @return * @throws CMSItemNotFoundException */ - @RequestMapping(value = {"/cse-data", "/tokenize"}, method = GET) + @GetMapping(value = {"/cse-data", "/tokenize"}) @RequireHardLogIn public String getCseDataPage(final Model model) throws CMSItemNotFoundException { if (getCheckoutFacade().hasCheckoutCart()) { @@ -87,10 +89,10 @@ public String getCseDataPage(final Model model) throws CMSItemNotFoundException * @return The view to redirect to. * @throws CMSItemNotFoundException */ - @RequestMapping(value = "/add-payment-address", method = POST) + @PostMapping(value = "/add-payment-address") @RequireHardLogIn public String addPaymentAddress(final Model model, @Valid final PaymentDetailsForm paymentDetailsForm, final BindingResult bindingResult, final RedirectAttributes redirectAttrs) - throws CMSItemNotFoundException { + throws CMSItemNotFoundException { csePaymentDetailsFormValidator.validate(paymentDetailsForm, bindingResult); if (addGlobalErrors(model, bindingResult)) { @@ -119,10 +121,11 @@ public String addPaymentAddress(final Model model, @Valid final PaymentDetailsFo * @return * @throws CMSItemNotFoundException */ - @RequestMapping(value = "/tokenize", method = POST) + @PostMapping(value = "/tokenize") @RequireHardLogIn - public String addCseData(final HttpServletRequest request, final Model model, @Valid final B2BCSEPaymentForm b2bCSEPaymentForm, final BindingResult bindingResult) - throws CMSItemNotFoundException { + public String addCseData(final HttpServletRequest request, final Model model, @Valid final B2BCSEPaymentForm b2bCSEPaymentForm, + final BindingResult bindingResult, final RedirectAttributes redirectAttributes) + throws CMSItemNotFoundException { cseFormValidator.validate(b2bCSEPaymentForm, bindingResult); getSessionService().setAttribute(SAVED_CARD_SELECTED_ATTRIBUTE, Boolean.FALSE); @@ -132,13 +135,17 @@ public String addCseData(final HttpServletRequest request, final Model model, @V } final CSEAdditionalAuthInfo cseAdditionalAuthInfo = createCSEAdditionalAuthInfo(b2bCSEPaymentForm); - final WorldpayAdditionalInfoData worldpayAdditionalInfoData = createWorldpayAdditionalInfo(request, b2bCSEPaymentForm.getCvc(), cseAdditionalAuthInfo); - return handleResponse(model, cseAdditionalAuthInfo, worldpayAdditionalInfoData); + final WorldpayAdditionalInfoData worldpayAdditionalInfoData = createWorldpayAdditionalInfo(request, b2bCSEPaymentForm, cseAdditionalAuthInfo); + return handleResponse(model, cseAdditionalAuthInfo, worldpayAdditionalInfoData, redirectAttributes); } - private String handleResponse(final Model model, final CSEAdditionalAuthInfo cseAdditionalAuthInfo, final WorldpayAdditionalInfoData worldpayAdditionalInfoData) throws CMSItemNotFoundException { + private String handleResponse(final Model model, final CSEAdditionalAuthInfo cseAdditionalAuthInfo, final WorldpayAdditionalInfoData worldpayAdditionalInfoData, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException { try { worldpayDirectOrderFacade.tokenize(cseAdditionalAuthInfo, worldpayAdditionalInfoData); + if (worldpayPaymentCheckoutFacade.isFSEnabled()) { + redirectAttributes.addFlashAttribute(BIRTHDAY_DATE, worldpayAdditionalInfoData.getDateOfBirth()); + redirectAttributes.addFlashAttribute(DEVICE_SESSION, worldpayAdditionalInfoData.getDeviceSession()); + } return REDIRECT_TO_SUMMARY_PAGE; } catch (WorldpayException e) { GlobalMessages.addErrorMessage(model, CHECKOUT_ERROR_PAYMENTETHOD_FORMENTRY_INVALID); @@ -173,9 +180,12 @@ public String getChallengeIframeContent(final Model model) { return worldpayAddonEndpointService.getChallengeIframe3dSecureFlex(); } - protected WorldpayAdditionalInfoData createWorldpayAdditionalInfo(final HttpServletRequest request, final String cvc, final CSEAdditionalAuthInfo cseAdditionalAuthInfo) { + protected WorldpayAdditionalInfoData createWorldpayAdditionalInfo(final HttpServletRequest request, final B2BCSEPaymentForm b2BCSEPaymentForm, final CSEAdditionalAuthInfo cseAdditionalAuthInfo) { final WorldpayAdditionalInfoData worldpayAdditionalInfo = worldpayAdditionalInfoFacade.createWorldpayAdditionalInfoData(request); - worldpayAdditionalInfo.setSecurityCode(cvc); + worldpayAdditionalInfo.setSecurityCode(b2BCSEPaymentForm.getSecurityCode()); + worldpayAdditionalInfo.setDateOfBirth(b2BCSEPaymentForm.getDateOfBirth()); + worldpayAdditionalInfo.setDeviceSession(b2BCSEPaymentForm.getDeviceSession()); + if (cseAdditionalAuthInfo.getAdditional3DS2() != null) { worldpayAdditionalInfo.setAdditional3DS2(cseAdditionalAuthInfo.getAdditional3DS2()); } @@ -189,6 +199,9 @@ protected WorldpayAdditionalInfoData createWorldpayAdditionalInfo(final HttpServ protected void setupAddPaymentPage(final Model model) throws CMSItemNotFoundException { super.setupAddPaymentPage(model); model.addAttribute(B2B_CSE_PAYMENT_FORM, new B2BCSEPaymentForm()); + model.addAttribute(IS_FS_ENABLED, worldpayPaymentCheckoutFacade.isFSEnabled()); + final SimpleDateFormat dateFormat = new SimpleDateFormat(BIRTH_DAY_DATE_FORMAT); + model.addAttribute(CURRENT_DATE, dateFormat.format(new Date())); model.addAttribute(CSE_PUBLIC_KEY, worldpayMerchantConfigDataFacade.getCurrentSiteMerchantConfigData().getCsePublicKey()); model.addAttribute(THREEDSFLEX_EVENT_ORIGIN_DOMAIN, worldpayDDCFacade.getEventOriginDomainForDDC()); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayResponseController.java b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayResponseController.java index e5b08947..4bb291f6 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayResponseController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayResponseController.java @@ -4,8 +4,8 @@ import com.worldpay.service.WorldpayAddonEndpointService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Resource; @@ -30,7 +30,7 @@ public class WorldpayResponseController extends WorldpayChoosePaymentMethodCheck * @param model * @return */ - @RequestMapping(value = "/billingaddressform", method = RequestMethod.GET) + @GetMapping(value = "/billingaddressform") public String getCountryAddressForm(@RequestParam("countryIsoCode") final String countryIsoCode, @RequestParam("useDeliveryAddress") final boolean useDeliveryAddress, final Model model) { model.addAttribute("supportedCountries", getCountries()); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpaySummaryCheckoutStepController.java b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpaySummaryCheckoutStepController.java index d0dadeef..c1eeb72b 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpaySummaryCheckoutStepController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpaySummaryCheckoutStepController.java @@ -55,7 +55,7 @@ @RequestMapping(value = "/checkout/multi/worldpay/summary") public class WorldpaySummaryCheckoutStepController extends AbstractWorldpayDirectCheckoutStepController { - protected static final Logger LOG = LogManager.getLogger(WorldpaySummaryCheckoutStepController.class); + private static final Logger LOG = LogManager.getLogger(WorldpaySummaryCheckoutStepController.class); private static final String SUMMARY = "summary"; private static final String CART_SUFFIX = "/cart"; @@ -119,6 +119,10 @@ public String enterStep(final Model model, final RedirectAttributes redirectAttr final List daysOfWeek = new ArrayList<>(); daysOfWeek.add(DayOfWeek.MONDAY); b2bCSEPaymentForm.setnDaysOfWeek(daysOfWeek); + if (worldpayPaymentCheckoutFacade.isFSEnabled()) { + b2bCSEPaymentForm.setDateOfBirth((Date) model.asMap().get(BIRTHDAY_DATE)); + b2bCSEPaymentForm.setDeviceSession((String) model.asMap().get(DEVICE_SESSION)); + } model.addAttribute(B2B_CSE_PAYMENT_FORM, b2bCSEPaymentForm); storeCmsPageInModel(model, getContentPageForLabelOrId(MULTI_CHECKOUT_SUMMARY_CMS_PAGE_LABEL)); @@ -130,7 +134,9 @@ public String enterStep(final Model model, final RedirectAttributes redirectAttr final String subscriptionId = cartData.getPaymentInfo() != null ? cartData.getPaymentInfo().getSubscriptionId() : null; model.addAttribute(SUBSCRIPTION_ID, subscriptionId); - model.addAttribute(BIN, cartData.getPaymentInfo().getBin()); + + Optional.ofNullable(cartData.getPaymentInfo()).ifPresent(bin -> model.addAttribute(BIN, bin)); + return worldpayAddonEndpointService.getCheckoutSummaryPage(); } @@ -178,7 +184,7 @@ public String placeOrder(@ModelAttribute(B2B_CSE_PAYMENT_FORM) final B2BCSEPayme final CSEAdditionalAuthInfo cseAdditionalAuthInfo = createCSESubscriptionAdditionalAuthInfo(b2bCSEPaymentForm); if (getCheckoutFacade().getCheckoutCart().getPaymentInfo() != null && !b2bCSEPaymentForm.isReplenishmentOrder()) { // Pay by credit card - Place Order Now - authorize payment - final WorldpayAdditionalInfoData worldpayAdditionalInfoData = getWorldpayAdditionalInfo(request, b2bCSEPaymentForm.getSecurityCode(), cseAdditionalAuthInfo); + final WorldpayAdditionalInfoData worldpayAdditionalInfoData = getWorldpayAdditionalInfo(request, b2bCSEPaymentForm, cseAdditionalAuthInfo); try { final DirectResponseData directResponseData = worldpayDirectOrderFacade.authoriseRecurringPayment(worldpayAdditionalInfoData); if (AUTHORISED != directResponseData.getTransactionStatus()) { @@ -370,9 +376,11 @@ protected CheckoutStep getCheckoutStep() { } private WorldpayAdditionalInfoData getWorldpayAdditionalInfo(final HttpServletRequest request, - final String securityCode, final CSEAdditionalAuthInfo cseAdditionalAuthInfo) { + final B2BCSEPaymentForm b2bCSEPaymentForm, final CSEAdditionalAuthInfo cseAdditionalAuthInfo) { final WorldpayAdditionalInfoData info = worldpayAdditionalInfoFacade.createWorldpayAdditionalInfoData(request); - info.setSecurityCode(securityCode); + info.setDateOfBirth(b2bCSEPaymentForm.getDateOfBirth()); + info.setSecurityCode(b2bCSEPaymentForm.getSecurityCode()); + info.setDeviceSession(b2bCSEPaymentForm.getDeviceSession()); if (cseAdditionalAuthInfo.getAdditional3DS2() != null) { info.setAdditional3DS2(cseAdditionalAuthInfo.getAdditional3DS2()); } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayThreeDSecureEndpointController.java b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayThreeDSecureEndpointController.java index f2eb93c6..743c7ca2 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayThreeDSecureEndpointController.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/controllers/pages/checkout/steps/WorldpayThreeDSecureEndpointController.java @@ -12,11 +12,12 @@ import de.hybris.platform.b2bacceleratorfacades.checkout.data.PlaceOrderData; import de.hybris.platform.commercefacades.order.data.OrderData; import de.hybris.platform.order.InvalidCartException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @@ -24,7 +25,6 @@ import static com.worldpay.payment.TransactionStatus.AUTHORISED; import static com.worldpay.payment.TransactionStatus.ERROR; import static java.text.MessageFormat.format; -import static org.springframework.web.bind.annotation.RequestMethod.POST; /** * Controller to handle 3D secure response @@ -35,13 +35,12 @@ public class WorldpayThreeDSecureEndpointController extends WorldpayChoosePaymen private static final Logger LOG = LogManager.getLogger(WorldpayThreeDSecureEndpointController.class); + @Resource + protected WorldpayAdditionalInfoFacade worldpayAdditionalInfoFacade; @Resource private WorldpayDirectOrderFacade worldpayDirectOrderFacade; @Resource private WorldpayCartService worldpayCartService; - @Resource - protected WorldpayAdditionalInfoFacade worldpayAdditionalInfoFacade; - /** * Method to handle 3D secure response @@ -51,23 +50,23 @@ public class WorldpayThreeDSecureEndpointController extends WorldpayChoosePaymen * @param redirectAttributes * @return */ - @RequestMapping(method = POST) + @PostMapping @RequireHardLogIn public String doHandleThreeDSecureResponse(final HttpServletRequest request, final ThreeDSecureForm threeDSecureForm, final RedirectAttributes redirectAttributes) { final String worldpayOrderCode = threeDSecureForm.getMD(); TransactionStatus transactionStatus = ERROR; try { final DirectResponseData responseData = worldpayDirectOrderFacade.authorise3DSecure(threeDSecureForm.getPaRes(), - worldpayAdditionalInfoFacade.createWorldpayAdditionalInfoData(request)); + worldpayAdditionalInfoFacade.createWorldpayAdditionalInfoData(request)); transactionStatus = responseData.getTransactionStatus(); if (AUTHORISED.equals(transactionStatus)) { final PlaceOrderData placeOrderData = new PlaceOrderData(); placeOrderData.setTermsCheck(true); - OrderData orderData = getB2BCheckoutFacade().placeOrder(placeOrderData); + final OrderData orderData = getB2BCheckoutFacade().placeOrder(placeOrderData); return redirectToOrderConfirmationPage(orderData); } else { - LOG.error(format("Failed to create payment authorisation for successful 3DSecure response. Received {0} as transactionStatus", transactionStatus)); + LOG.error("Failed to create payment authorisation for successful 3DSecure response. Received [{}] as transactionStatus", transactionStatus); worldpayCartService.setWorldpayDeclineCodeOnCart(worldpayOrderCode, responseData.getReturnCode()); } } catch (final WorldpayException | InvalidCartException e) { diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/forms/validation/CseFormValidator.java b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/forms/validation/CseFormValidator.java index ab36310b..26b0b329 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/forms/validation/CseFormValidator.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/src/com/worldpay/forms/validation/CseFormValidator.java @@ -1,17 +1,26 @@ package com.worldpay.forms.validation; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.forms.CSEPaymentForm; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; +import javax.annotation.Resource; +import java.util.Date; + /** * Validate CSE form */ -@Component ("cseFormValidator") +@Component("cseFormValidator") public class CseFormValidator implements Validator { + protected static final String GLOBAL_MISSING_CSE_TOKEN = "checkout.multi.paymentMethod.cse.invalid"; + protected static final String CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY = "checkout.error.fraudSight.dob.mandatory"; + + @Resource + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacade; @Override public boolean supports(final Class aClass) { @@ -25,5 +34,19 @@ public void validate(final Object object, final Errors errors) { if (StringUtils.isBlank(form.getCseToken())) { errors.reject(GLOBAL_MISSING_CSE_TOKEN); } + + if (worldpayPaymentCheckoutFacade.isFSEnabled() && form.isDobRequired() && !isValidDate(form.getDateOfBirth())) { + errors.reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + } + + /** + * Checks if the birthday date is in the past + * + * @param birthdayDate the birthday date + * @return true if valid, false otherwise + */ + protected boolean isValidDate(final Date birthdayDate) { + return birthdayDate != null && birthdayDate.before(new Date()); } } diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepControllerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepControllerTest.java index 0308353b..2eab2a82 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepControllerTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpayCseCheckoutStepControllerTest.java @@ -47,7 +47,9 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; +import java.util.Calendar; import java.util.Collections; +import java.util.Date; import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayDirectCheckoutStepController.CMS_PAGE_MODEL; import static com.worldpay.controllers.pages.checkout.steps.AbstractWorldpayPaymentMethodCheckoutStepController.*; @@ -76,6 +78,10 @@ public class WorldpayCseCheckoutStepControllerTest { private static final String CSE_PAYMENT_DETAILS_PAGE = "CSEPaymentDetailsPage"; private static final String EVENT_ORIGIN_DOMAIN = "EVENT_ORIGIN_DOMAIN"; private static final String THREEDSFLEX_EVENT_ORIGIN_DOMAIN = "originEventDomain3DSFlex"; + private static final String BIRTHDAY_DATE = "birthdayDate"; + private static final Date BIRTHDAY_DATE_VALUE = new Date(1990, Calendar.MAY, 17); + private static final String DEVICE_SESSION = "DEVICE_SESSION"; + private static final String DEVICE_SESSION_VALUE = "device_session_value"; @Spy @InjectMocks @@ -92,7 +98,6 @@ public class WorldpayCseCheckoutStepControllerTest { @Mock private WorldpayDDCFacade workdpayDDCFacadeMock; - @Mock(answer = RETURNS_DEEP_STUBS) private HttpServletRequest httpServletRequestMock; @Mock @@ -162,8 +167,12 @@ public void setUp() throws CMSItemNotFoundException { when(cartDataMock.getWorldpayOrderCode()).thenReturn(WORLDPAY_ORDER_CODE); when(httpServletRequestMock.getSession().getId()).thenReturn(SESSION_ID); when(worldpayAdditionalInfoFacadeMock.createWorldpayAdditionalInfoData(httpServletRequestMock)).thenReturn(worldpayAdditionalInfoDataMock); + when(b2bCSEPaymentFormMock.getDateOfBirth()).thenReturn(BIRTHDAY_DATE_VALUE); + when(worldpayAdditionalInfoDataMock.getDateOfBirth()).thenReturn(BIRTHDAY_DATE_VALUE); when(checkoutCustomerStrategyMock.isAnonymousCheckout()).thenReturn(true); when(worldpayMerchantConfigDataFacadeMock.getCurrentSiteMerchantConfigData()).thenReturn(worldpayMerchantConfigDataMock); + when(b2bCSEPaymentFormMock.getDeviceSession()).thenReturn(DEVICE_SESSION_VALUE); + when(worldpayAdditionalInfoDataMock.getDeviceSession()).thenReturn(DEVICE_SESSION_VALUE); when(paymentDetailsFormMock.getBillingAddress()).thenReturn(addressFormMock); when(cmsPreviewServiceMock.getPagePreviewCriteria()).thenReturn(pagePreviewCriteriaMock); when(cmsPageServiceMock.getPageForLabelOrId(WORLDPAY_PAYMENT_AND_BILLING_CHECKOUT_STEP_CMS_PAGE_LABEL, pagePreviewCriteriaMock)).thenReturn(contentPageModelMock); @@ -181,19 +190,33 @@ public void setUp() throws CMSItemNotFoundException { } @Test - public void shouldRedirectToSummaryIfNoException() throws CMSItemNotFoundException { + public void addCseData_WhenNoExceptionAndFSDisabled_shouldRedirectToSummary() throws CMSItemNotFoundException { + // When no errors are thrown + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(false); + + final String result = testObj.addCseData(httpServletRequestMock, modelMock, b2bCSEPaymentFormMock, bindingResultMock, redirectAttrsMock); + + assertEquals(REDIRECT_TO_SUMMARY_PAGE, result); + verifyZeroInteractions(redirectAttrsMock); + } + + @Test + public void addCseData_WhenNoExceptionAndFSEnabled_shouldRedirectToSummary() throws CMSItemNotFoundException { // When no errors are thrown + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(true); - final String result = testObj.addCseData(httpServletRequestMock, modelMock, b2bCSEPaymentFormMock, bindingResultMock); + final String result = testObj.addCseData(httpServletRequestMock, modelMock, b2bCSEPaymentFormMock, bindingResultMock, redirectAttrsMock); assertEquals(REDIRECT_TO_SUMMARY_PAGE, result); + verify(redirectAttrsMock).addFlashAttribute(BIRTHDAY_DATE, BIRTHDAY_DATE_VALUE); + verify(redirectAttrsMock).addFlashAttribute(DEVICE_SESSION, DEVICE_SESSION_VALUE); } @Test public void shouldRedirectToErrorIfExceptionThrownByFacade() throws CMSItemNotFoundException, WorldpayException { doThrow(new WorldpayException("errorMessage")).when(worldpayDirectOrderFacadeMock).tokenize(any(CSEAdditionalAuthInfo.class), eq(worldpayAdditionalInfoDataMock)); - final String result = testObj.addCseData(httpServletRequestMock, modelMock, b2bCSEPaymentFormMock, bindingResultMock); + final String result = testObj.addCseData(httpServletRequestMock, modelMock, b2bCSEPaymentFormMock, bindingResultMock, redirectAttrsMock); assertEquals(CSE_PAYMENT_DETAILS_PAGE, result); } @@ -202,7 +225,7 @@ public void shouldRedirectToErrorIfExceptionThrownByFacade() throws CMSItemNotFo public void shouldDisplayCsePaymentPageIfErrorTokenizing() throws CMSItemNotFoundException, WorldpayException { doThrow(new WorldpayException("errorMessage")).when(worldpayDirectOrderFacadeMock).tokenize(any(CSEAdditionalAuthInfo.class), eq(worldpayAdditionalInfoDataMock)); - testObj.addCseData(httpServletRequestMock, modelMock, b2bCSEPaymentFormMock, bindingResultMock); + testObj.addCseData(httpServletRequestMock, modelMock, b2bCSEPaymentFormMock, bindingResultMock, redirectAttrsMock); verify(modelMock).addAttribute(eq(B2B_CSE_PAYMENT_FORM), any(CSEPaymentForm.class)); } @@ -211,7 +234,7 @@ public void shouldDisplayCsePaymentPageIfErrorTokenizing() throws CMSItemNotFoun public void shouldValidateCseFormAndRedirectToCseForm() throws CMSItemNotFoundException { doReturn(true).when(testObj).addGlobalErrors(modelMock, bindingResultMock); - final String result = testObj.addCseData(httpServletRequestMock, modelMock, b2bCSEPaymentFormMock, bindingResultMock); + final String result = testObj.addCseData(httpServletRequestMock, modelMock, b2bCSEPaymentFormMock, bindingResultMock, redirectAttrsMock); verify(cseFormValidatorMock).validate(b2bCSEPaymentFormMock, bindingResultMock); assertEquals(CSE_PAYMENT_DETAILS_PAGE, result); diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpaySummaryCheckoutStepControllerTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpaySummaryCheckoutStepControllerTest.java new file mode 100644 index 00000000..401d365b --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/controllers/pages/checkout/steps/WorldpaySummaryCheckoutStepControllerTest.java @@ -0,0 +1,492 @@ +package com.worldpay.controllers.pages.checkout.steps; + +import com.worldpay.config.merchant.WorldpayMerchantConfigData; +import com.worldpay.exception.WorldpayException; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; +import com.worldpay.facades.order.impl.WorldpayB2BAcceleratorCheckoutFacadeDecorator; +import com.worldpay.facades.payment.WorldpayAdditionalInfoFacade; +import com.worldpay.facades.payment.direct.WorldpayDDCFacade; +import com.worldpay.facades.payment.direct.WorldpayDirectOrderFacade; +import com.worldpay.facades.payment.merchant.WorldpayMerchantConfigDataFacade; +import com.worldpay.forms.B2BCSEPaymentForm; +import com.worldpay.order.data.WorldpayAdditionalInfoData; +import com.worldpay.payment.DirectResponseData; +import com.worldpay.service.WorldpayAddonEndpointService; +import de.hybris.bootstrap.annotations.UnitTest; +import de.hybris.platform.acceleratorfacades.flow.CheckoutFlowFacade; +import de.hybris.platform.acceleratorservices.storefront.util.PageTitleResolver; +import de.hybris.platform.acceleratorstorefrontcommons.breadcrumb.ResourceBreadcrumbBuilder; +import de.hybris.platform.acceleratorstorefrontcommons.checkout.steps.CheckoutGroup; +import de.hybris.platform.acceleratorstorefrontcommons.checkout.steps.CheckoutStep; +import de.hybris.platform.acceleratorstorefrontcommons.constants.WebConstants; +import de.hybris.platform.b2bacceleratorfacades.checkout.data.PlaceOrderData; +import de.hybris.platform.b2bacceleratorfacades.exception.EntityValidationException; +import de.hybris.platform.b2bacceleratorfacades.order.data.B2BDaysOfWeekData; +import de.hybris.platform.b2bacceleratorfacades.order.data.B2BReplenishmentRecurrenceEnum; +import de.hybris.platform.cms2.data.PagePreviewCriteriaData; +import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException; +import de.hybris.platform.cms2.model.pages.ContentPageModel; +import de.hybris.platform.cms2.servicelayer.services.CMSPageService; +import de.hybris.platform.cms2.servicelayer.services.CMSPreviewService; +import de.hybris.platform.commercefacades.order.CartFacade; +import de.hybris.platform.commercefacades.order.data.*; +import de.hybris.platform.commercefacades.product.ProductFacade; +import de.hybris.platform.commercefacades.product.data.ProductData; +import de.hybris.platform.commercefacades.user.data.AddressData; +import de.hybris.platform.commerceservices.order.CommerceCartModificationException; +import de.hybris.platform.cronjob.enums.DayOfWeek; +import de.hybris.platform.order.InvalidCartException; +import de.hybris.platform.servicelayer.session.SessionService; +import org.apache.commons.lang.StringUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.ui.ExtendedModelMap; +import org.springframework.ui.Model; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.*; + +import static com.worldpay.controllers.pages.checkout.steps.WorldpaySummaryCheckoutStepController.CMS_PAGE_MODEL; +import static com.worldpay.controllers.pages.checkout.steps.WorldpaySummaryCheckoutStepController.SAVED_CARD_SELECTED_ATTRIBUTE; +import static com.worldpay.payment.TransactionStatus.AUTHORISED; +import static com.worldpay.payment.TransactionStatus.REFUSED; +import static de.hybris.platform.acceleratorstorefrontcommons.constants.WebConstants.BREADCRUMBS_KEY; +import static de.hybris.platform.acceleratorstorefrontcommons.controllers.AbstractController.REDIRECT_PREFIX; +import static de.hybris.platform.commercefacades.product.ProductOption.BASIC; +import static de.hybris.platform.commercefacades.product.ProductOption.PRICE; +import static java.util.Collections.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.mockito.Answers.RETURNS_DEEP_STUBS; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.*; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class WorldpaySummaryCheckoutStepControllerTest { + + private static final String SECURITY_CODE = "securityCode"; + private static final String SUBSCRIPTION_ID = "subscriptionId"; + private static final String PAGE_TITLE = "pageTitle"; + private static final String RESOLVED_CONTENT_PAGE_TITLE = "resolvedContentPageTitle"; + private static final String SOME_FLOW_GROUP = "someFlowGroup"; + private static final String SUMMARY = "summary"; + private static final String EXCEPTION_MESSAGE = "exceptionMessage"; + private static final String PRODUCT_CODE = "productCode"; + private static final String NOINDEX_NOFOLLOW = "noindex,nofollow"; + private static final String B2B_CSE_PAYMENT_FORM = "b2bCSEPaymentForm"; + private static final String REDIRECT_VIEW = "redirectView"; + private static final String CHECKOUT_SUMMARY_PAGE = "CheckoutSummaryPage"; + private static final String THREEDSECURE_FLEX_DDC_URL_VALUE = "threeDSecureDDCUrlValue"; + private static final String THREEDSECURE_JWT_FLEX_DDC_VALUE = "THREEDSECURE_JWT_FLEX_DDC_VALUE"; + private static final String THREDSFLEX_DDC_PAGE = "ddcIframePage"; + private static final String CHALLENGE_IFRAME_3D_SECURE = "challengeIframe3dSecure"; + private static final String BIN = "bin"; + private static final String BIN_VALUE = "78954"; + private static final String PREVIOUS = "redirect:previous"; + private static final String NEXT = "redirect:next"; + private static final String CURRENT = "redirect:current"; + private static final String CART_DATA = "cartData"; + private static final String ALL_ITEMS = "allItems"; + private static final String DELIVERY_ADDRESS = "deliveryAddress"; + private static final String DELIVERY_MODE = "deliveryMode"; + private static final String PAYMENT_INFO = "paymentInfo"; + private static final String REQUEST_SECURITY_CODE = "requestSecurityCode"; + private static final String CART_SUFFIX = "/cart"; + private static final String MULTI_CHECKOUT_SUMMARY_CMS_PAGE_LABEL = "multiStepCheckoutSummary"; + private static final String CART_CODE = "0001"; + private static final String REDIRECT_URL_ORDER_CONFIRMATION = REDIRECT_PREFIX + "/checkout/orderConfirmation/"; + private static final String THREEDSECURE_JWT_FLEX_DDC = "jwt3DSecureFlexDDC"; + private static final String THREEDSECURE_FLEX_DDC_URL = "threeDSecureDDCUrl"; + private static final String DAY_1 = "DAY1"; + private static final String DAY_2 = "DAY2"; + private static final String N_DAYS = "nDays"; + private static final String NTH_DAY_OF_MONTH = "nthDayOfMonth"; + private static final String NTH_WEEK = "nthWeek"; + private static final String DAYS_OF_WEEK = "daysOfWeek"; + private static final String FORM_N_DAYS = "14"; + private static final String META_ROBOTS = "metaRobots"; + private static final String PREVIOUS_STEP_URL = "previousStepUrl"; + private static final String NEXT_STEP_URL = "nextStepUrl"; + private static final String CURRENT_STEP_URL = "currentStepUrl"; + private static final String PROGRESS_BAR_ID = "progressBarId"; + private static final String BIRTHDAY_DATE = "birthdayDate"; + private static final String DEVICE_SESSION = "DEVICE_SESSION"; + private static final String DEVICE_SESSION_VALUE = "deviceSession"; + + @Spy + @InjectMocks + private WorldpaySummaryCheckoutStepController testObj; + + @Mock + private CMSPageService cmsPageServiceMock; + @Mock + private CMSPreviewService cmsPreviewServiceMock; + @Mock + private WorldpayAdditionalInfoFacade worldpayAdditionalInfoFacadeMock; + @Mock + private WorldpayDirectOrderFacade worldpayDirectOrderFacadeMock; + @Mock + private WorldpayDDCFacade worldpayDDCFacadeMock; + @Mock + private WorldpayB2BAcceleratorCheckoutFacadeDecorator checkoutFacadeMock; + @Mock + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacadeMock; + + @Mock + private RedirectAttributes redirectAttributesMock; + @Mock + private B2BCSEPaymentForm formMock; + @Mock(answer = RETURNS_DEEP_STUBS) + private HttpServletRequest httpServletRequestMock; + @Mock + private CartFacade cartFacadeMock; + @Mock + private CartModificationData cartModificationDataMock; + @Mock(answer = RETURNS_DEEP_STUBS) + private CartData cartDataMock; + @Mock + private CheckoutFlowFacade checkoutFlowFacadeMock; + @Mock + private ContentPageModel contentPageModelMock; + @Mock + private PageTitleResolver pageTitleResolverMock; + @Mock + private ResourceBreadcrumbBuilder resourceBreadcrumbBuilderMock; + @Mock(name = "checkoutFlowGroupMap") + private Map checkoutFlowGroupMapMock; + @Mock + private Map checkoutStepMapMock; + @Mock + private CheckoutGroup checkoutGroupMock; + @Mock + private CheckoutStep checkoutStepMock; + @Mock + private AddressData deliveryAddressMock; + @Mock + private DeliveryModeData deliveryModeDataMock; + @Mock + private CCPaymentInfoData paymentInfoMock; + @Mock + private OrderEntryData orderEntryDataMock; + @Mock + private ProductData productDataMock; + @Mock + private ProductFacade productFacadeMock; + @Mock + private WorldpayAdditionalInfoData worldpayAdditionalInfoDataMock; + @Mock + private SessionService sessionServiceMock; + @Mock + private DirectResponseData directResponseDataMock; + @Mock + private PagePreviewCriteriaData pagePreviewCriteriaMock; + @Mock + private WorldpayMerchantConfigDataFacade worldpayMerchantConfigDataFacadeMock; + @Mock(answer = RETURNS_DEEP_STUBS) + private WorldpayMerchantConfigData worldpayMerchantConfigDataMock; + @Mock + private WorldpayAddonEndpointService worldpayAddonEndpointServiceMock; + @Mock + private HttpServletResponse responseMock; + @Mock + private AbstractOrderData abstractOrderDataMock; + @Mock + private B2BDaysOfWeekData b2BDaysOfWeekDataMock; + + private Model modelStub = new ExtendedModelMap(); + + private List dayList = List.of(DAY_1, DAY_2); + + private static final Date BIRTHDAY_DATE_VALUE = new GregorianCalendar(1990, Calendar.MAY, 17).getTime(); + + + @Before + public void setUp() throws CMSItemNotFoundException, WorldpayException, InvalidCartException { + doNothing().when(testObj).setupAddPaymentPage(modelStub); + doReturn(checkoutFacadeMock).when(testObj).getB2BCheckoutFacade(); + doReturn(checkoutFacadeMock).when(testObj).getCheckoutFacade(); + doReturn(checkoutStepMock).when(testObj).getCheckoutStep(); + doReturn(dayList).when(testObj).getNumberRange(anyInt(), anyInt()); + when(cmsPageServiceMock.getPageForLabelOrId(MULTI_CHECKOUT_SUMMARY_CMS_PAGE_LABEL, pagePreviewCriteriaMock)).thenReturn(contentPageModelMock); + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(Boolean.FALSE); + when(checkoutFacadeMock.getCheckoutCart()).thenReturn(cartDataMock); + when(checkoutFacadeMock.getDaysOfWeekForReplenishmentCheckoutSummary()).thenReturn(List.of(b2BDaysOfWeekDataMock)); + when(formMock.getSecurityCode()).thenReturn(SECURITY_CODE); + when(cmsPreviewServiceMock.getPagePreviewCriteria()).thenReturn(pagePreviewCriteriaMock); + when(pageTitleResolverMock.resolveContentPageTitle(PAGE_TITLE)).thenReturn(RESOLVED_CONTENT_PAGE_TITLE); + when(contentPageModelMock.getTitle()).thenReturn(PAGE_TITLE); + when(resourceBreadcrumbBuilderMock.getBreadcrumbs(anyString())).thenReturn(emptyList()); + when(formMock.isTermsCheck()).thenReturn(true); + when(checkoutFacadeMock.containsTaxValues()).thenReturn(true); + when(cartDataMock.isCalculated()).thenReturn(true); + when(checkoutFlowGroupMapMock.get(SOME_FLOW_GROUP)).thenReturn(checkoutGroupMock); + when(checkoutGroupMock.getCheckoutStepMap()).thenReturn(checkoutStepMapMock); + when(checkoutStepMapMock.get(SUMMARY)).thenReturn(checkoutStepMock); + when(cartDataMock.getPaymentInfo()).thenReturn(paymentInfoMock); + when(paymentInfoMock.getBin()).thenReturn(BIN_VALUE); + when(checkoutStepMock.previousStep()).thenReturn(PREVIOUS); + when(checkoutStepMock.nextStep()).thenReturn(NEXT); + when(checkoutStepMock.currentStep()).thenReturn(CURRENT); + when(orderEntryDataMock.getProduct()).thenReturn(productDataMock); + when(cartDataMock.getEntries()).thenReturn(singletonList(orderEntryDataMock)); + when(productDataMock.getCode()).thenReturn(PRODUCT_CODE); + when(productFacadeMock.getProductForCodeAndOptions(PRODUCT_CODE, Arrays.asList(BASIC, PRICE))).thenReturn(productDataMock); + when(worldpayAdditionalInfoFacadeMock.createWorldpayAdditionalInfoData(httpServletRequestMock)).thenReturn(worldpayAdditionalInfoDataMock); + when(sessionServiceMock.getAttribute(WebConstants.CART_RESTORATION)).thenReturn(null); + when(sessionServiceMock.getAttribute(SAVED_CARD_SELECTED_ATTRIBUTE)).thenReturn(Boolean.TRUE); + when(checkoutFlowFacadeMock.hasValidCart()).thenReturn(true); + when(worldpayAddonEndpointServiceMock.getCheckoutSummaryPage()).thenReturn(CHECKOUT_SUMMARY_PAGE); + when(worldpayMerchantConfigDataFacadeMock.getCurrentSiteMerchantConfigData()).thenReturn(worldpayMerchantConfigDataMock); + when(worldpayDirectOrderFacadeMock.authoriseRecurringPayment(worldpayAdditionalInfoDataMock)).thenReturn(directResponseDataMock); + when(directResponseDataMock.getTransactionStatus()).thenReturn(AUTHORISED); + } + + @Test + @SuppressWarnings("unchecked") + public void enterStep__IfPaymentInfoIsNotNullAndFSIsNotEnabled_ShouldReturnCheckoutSummaryPage() throws CMSItemNotFoundException { + when(cartDataMock.getDeliveryAddress()).thenReturn(deliveryAddressMock); + when(cartDataMock.getDeliveryMode()).thenReturn(deliveryModeDataMock); + when(paymentInfoMock.getSubscriptionId()).thenReturn(SUBSCRIPTION_ID); + + final String result = testObj.enterStep(modelStub, redirectAttributesMock, responseMock); + + assertThat(modelStub.asMap()).containsEntry(CART_DATA, cartDataMock); + final List orderEntryDatas = (List) modelStub.asMap().get(ALL_ITEMS); + assertThat(orderEntryDatas).hasSize(1); + assertThat(orderEntryDatas.get(0)).isEqualTo(orderEntryDataMock); + assertThat(modelStub.asMap()).containsEntry(DELIVERY_ADDRESS, deliveryAddressMock); + assertThat(modelStub.asMap()).containsEntry(DELIVERY_MODE, deliveryModeDataMock); + assertThat(modelStub.asMap()).containsEntry(PAYMENT_INFO, paymentInfoMock); + assertThat(modelStub.asMap()).containsEntry(N_DAYS, dayList); + assertThat(modelStub.asMap()).containsEntry(NTH_DAY_OF_MONTH, dayList); + assertThat(modelStub.asMap()).containsEntry(NTH_WEEK, dayList); + assertThat(modelStub.asMap()).containsEntry(DAYS_OF_WEEK, List.of(b2BDaysOfWeekDataMock)); + assertThat(modelStub.asMap()).containsEntry(REQUEST_SECURITY_CODE, Boolean.TRUE); + + assertThat(((B2BCSEPaymentForm) modelStub.asMap().get(B2B_CSE_PAYMENT_FORM)).getSecurityCode()).isNull(); + assertThat(((B2BCSEPaymentForm) modelStub.asMap().get(B2B_CSE_PAYMENT_FORM)).isTermsCheck()).isFalse(); + assertThat(((B2BCSEPaymentForm) modelStub.asMap().get(B2B_CSE_PAYMENT_FORM)).getnDays()).isEqualTo(FORM_N_DAYS); + assertThat(((B2BCSEPaymentForm) modelStub.asMap().get(B2B_CSE_PAYMENT_FORM)).getReplenishmentRecurrence()) + .isEqualTo(B2BReplenishmentRecurrenceEnum.MONTHLY); + assertThat(((B2BCSEPaymentForm) modelStub.asMap().get(B2B_CSE_PAYMENT_FORM)).getnDaysOfWeek()) + .isEqualTo(List.of(DayOfWeek.MONDAY)); + + assertThat(modelStub.asMap()).containsEntry(CMS_PAGE_MODEL, contentPageModelMock); + assertThat(modelStub.asMap()).containsEntry(BREADCRUMBS_KEY, EMPTY_LIST); + assertThat(modelStub.asMap()).containsEntry(META_ROBOTS, NOINDEX_NOFOLLOW); + + assertThat(modelStub.asMap()).containsEntry(PREVIOUS_STEP_URL, StringUtils.remove(checkoutStepMock.previousStep(), REDIRECT_PREFIX)); + assertThat(modelStub.asMap()).containsEntry(NEXT_STEP_URL, StringUtils.remove(checkoutStepMock.nextStep(), REDIRECT_PREFIX)); + assertThat(modelStub.asMap()).containsEntry(CURRENT_STEP_URL, StringUtils.remove(checkoutStepMock.currentStep(), REDIRECT_PREFIX)); + assertThat(modelStub.asMap()).containsEntry(PROGRESS_BAR_ID, checkoutStepMock.getProgressBarId()); + + assertThat(modelStub.asMap()).containsEntry(SUBSCRIPTION_ID, SUBSCRIPTION_ID); + assertThat(modelStub.asMap()).containsEntry(BIN, paymentInfoMock); + assertEquals(CHECKOUT_SUMMARY_PAGE, result); + } + + @Test + public void enterStep__IfPaymentInfoIsNull_ShouldNotThrowException() throws CMSItemNotFoundException { + when(cartDataMock.getPaymentInfo()).thenReturn(null); + + final String result = testObj.enterStep(modelStub, redirectAttributesMock, responseMock); + + assertThat(modelStub.asMap()).containsEntry(PAYMENT_INFO, null); + assertThat(modelStub.asMap()).containsEntry(SUBSCRIPTION_ID, null); + assertThat(modelStub.asMap()).doesNotContainKey(BIN); + assertEquals(CHECKOUT_SUMMARY_PAGE, result); + } + + @Test + public void enterStep__IfFSIsEnabled_ShouldAddAddFormAttributes() throws CMSItemNotFoundException { + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(Boolean.TRUE); + + modelStub.addAttribute(BIRTHDAY_DATE, BIRTHDAY_DATE_VALUE); + modelStub.addAttribute(DEVICE_SESSION, DEVICE_SESSION_VALUE); + + final String result = testObj.enterStep(modelStub, redirectAttributesMock, responseMock); + + assertThat(((B2BCSEPaymentForm) modelStub.asMap().get(B2B_CSE_PAYMENT_FORM)).getDateOfBirth()).isEqualTo(BIRTHDAY_DATE_VALUE); + assertThat(((B2BCSEPaymentForm) modelStub.asMap().get(B2B_CSE_PAYMENT_FORM)).getDeviceSession()).isEqualTo(DEVICE_SESSION_VALUE); + assertThat(result).isEqualTo(CHECKOUT_SUMMARY_PAGE); + } + + @Test + public void placeOrder_WhenCartIsInvalid_ShouldRedirectToCartPage() throws CMSItemNotFoundException, CommerceCartModificationException, InvalidCartException { + when(cartFacadeMock.validateCartData()).thenReturn(singletonList(cartModificationDataMock)); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertThat(result).isEqualTo(REDIRECT_PREFIX + CART_SUFFIX); + } + + @Test + public void placeOrder_WhenSecurityCodeIsBlankAndSubscriptionIdIsNull_ShouldStayOnSummaryPage() throws CMSItemNotFoundException, InvalidCartException { + when(cartDataMock.getPaymentInfo().getSubscriptionId()).thenReturn(null); + when(formMock.getSecurityCode()).thenReturn(StringUtils.EMPTY); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertEquals(CHECKOUT_SUMMARY_PAGE, result); + } + + @Test + public void placeOrder_WhenNoDeliveryAddress_ShouldStayOnSummaryPage() throws CMSItemNotFoundException, InvalidCartException { + when(checkoutFlowFacadeMock.hasNoDeliveryAddress()).thenReturn(true); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertEquals(CHECKOUT_SUMMARY_PAGE, result); + } + + @Test + public void placeOrder_WhenNoDeliveryMode_ShouldStayOnSummaryPage() throws CMSItemNotFoundException, InvalidCartException { + when(checkoutFlowFacadeMock.hasNoDeliveryMode()).thenReturn(true); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertEquals(CHECKOUT_SUMMARY_PAGE, result); + } + + @Test + public void placeOrder_WhenTermsAreNotChecked_ShouldStayOnSummaryPage() throws CMSItemNotFoundException, InvalidCartException { + // By default, the mock returns false, but we explicitly mock the answer here for the sake of clarity + when(formMock.isTermsCheck()).thenReturn(false); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertEquals(CHECKOUT_SUMMARY_PAGE, result); + } + + @Test + public void placeOrder_WhenCartDoesNotContainTaxValues_ShouldStayOnSummaryPage() throws CMSItemNotFoundException, InvalidCartException { + when(checkoutFacadeMock.containsTaxValues()).thenReturn(false); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertEquals(CHECKOUT_SUMMARY_PAGE, result); + } + + @Test + public void placeOrder_WhenCartIsNotCalculated_ShouldStayOnSummaryPage() throws CMSItemNotFoundException, InvalidCartException { + when(cartDataMock.isCalculated()).thenReturn(false); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertEquals(CHECKOUT_SUMMARY_PAGE, result); + } + + @Test + public void placeOrder_WhenNoPaymentInfo_ShouldStayOnSummaryPage() throws CMSItemNotFoundException, InvalidCartException { + when(checkoutFlowFacadeMock.hasNoPaymentInfo()).thenReturn(true); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertEquals(CHECKOUT_SUMMARY_PAGE, result); + } + + @Test + public void placeOrder_OnWorldpayException_ShouldRedirectsToSummaryPage() throws InvalidCartException, CMSItemNotFoundException, WorldpayException { + doThrow(new WorldpayException(EXCEPTION_MESSAGE)).when(worldpayDirectOrderFacadeMock).authoriseRecurringPayment(worldpayAdditionalInfoDataMock); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + verify(responseMock).setStatus(HttpServletResponse.SC_BAD_REQUEST); + assertThat(result).isEqualTo(CHECKOUT_SUMMARY_PAGE); + } + + @Test + public void placeOrder_OnInvalidCartException_ShouldThrowException() throws WorldpayException, InvalidCartException { + doThrow(new InvalidCartException(EXCEPTION_MESSAGE)).when(worldpayDirectOrderFacadeMock).authoriseRecurringPayment(worldpayAdditionalInfoDataMock); + + assertThatThrownBy(() -> testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock)).isInstanceOf(InvalidCartException.class); + } + + @Test + public void placeOrder_WhenTransactionStatusIsNotAuthorised_ShouldHandleRedirectResponse() throws CMSItemNotFoundException, WorldpayException, InvalidCartException { + when(worldpayDirectOrderFacadeMock.authoriseRecurringPayment(worldpayAdditionalInfoDataMock)).thenReturn(directResponseDataMock); + when(directResponseDataMock.getTransactionStatus()).thenReturn(REFUSED); + doReturn(REDIRECT_VIEW).when(testObj).handleDirectResponse(modelStub, directResponseDataMock, responseMock); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + verify(worldpayAdditionalInfoDataMock).setSecurityCode(SECURITY_CODE); + assertThat(result).isEqualTo(REDIRECT_VIEW); + } + + @Test + public void placeOrder_OnEntityValidationException_ShouldRedirectsToSummaryPage() throws InvalidCartException, CMSItemNotFoundException, WorldpayException { + doThrow(new EntityValidationException(EXCEPTION_MESSAGE)).when(checkoutFacadeMock).placeOrder(any(PlaceOrderData.class)); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + verify(formMock).setTermsCheck(Boolean.FALSE); + assertThat(result).isEqualTo(CHECKOUT_SUMMARY_PAGE); + } + + @Test + public void placeOrder_OnException_ShouldRedirectsToSummaryPage() throws InvalidCartException, CMSItemNotFoundException, WorldpayException { + doThrow(new NullPointerException(EXCEPTION_MESSAGE)).when(checkoutFacadeMock).placeOrder(any(PlaceOrderData.class)); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertThat(result).isEqualTo(CHECKOUT_SUMMARY_PAGE); + } + + @Test + public void placeOrder_WhenTransactionStatusIsAuthorised_ShouldRedirectToOrderConfirmationPage() throws CMSItemNotFoundException, WorldpayException, InvalidCartException { + when(cartDataMock.getWorldpayAPMPaymentInfo().getSubscriptionId()).thenReturn(SUBSCRIPTION_ID); + when(checkoutFacadeMock.placeOrder(any(PlaceOrderData.class))).thenReturn(abstractOrderDataMock); + when(abstractOrderDataMock.getCode()).thenReturn(CART_CODE); + + final String result = testObj.placeOrder(formMock, modelStub, httpServletRequestMock, redirectAttributesMock, responseMock); + + assertThat(result).isEqualTo(REDIRECT_URL_ORDER_CONFIRMATION + CART_CODE); + } + + @Test + public void getDDCIframeContent_shouldPopulate3DSecureJsonWebToken() { + when(worldpayAddonEndpointServiceMock.getCheckoutSummaryPage()).thenReturn(CHECKOUT_SUMMARY_PAGE); + when(worldpayMerchantConfigDataMock.getThreeDSFlexJsonWebTokenSettings().getDdcUrl()).thenReturn(THREEDSECURE_FLEX_DDC_URL_VALUE); + when(worldpayDDCFacadeMock.createJsonWebTokenForDDC()).thenReturn(THREEDSECURE_JWT_FLEX_DDC_VALUE); + when(worldpayAddonEndpointServiceMock.getDdcIframe3dSecureFlex()).thenReturn(THREDSFLEX_DDC_PAGE); + + final String result = testObj.getDDCIframeContent(modelStub); + + assertThat(modelStub.asMap()).containsEntry(THREEDSECURE_FLEX_DDC_URL, THREEDSECURE_FLEX_DDC_URL_VALUE); + assertThat(modelStub.asMap()).containsEntry(THREEDSECURE_JWT_FLEX_DDC, THREEDSECURE_JWT_FLEX_DDC_VALUE); + assertThat(result).isEqualTo(THREDSFLEX_DDC_PAGE); + } + + @Test + public void getChallengeIframeContent_ShouldReturnTheWorldpayChallengeIframe() { + when(worldpayAddonEndpointServiceMock.getChallengeIframe3dSecureFlex()).thenReturn(CHALLENGE_IFRAME_3D_SECURE); + + final String result = testObj.getChallengeIframeContent(modelStub); + + assertThat(result).isEqualTo(CHALLENGE_IFRAME_3D_SECURE); + } + + @Test + public void back_ShouldReturnThePreviousPage() { + final String result = testObj.back(redirectAttributesMock); + + assertThat(result).isEqualTo(PREVIOUS); + } + + @Test + public void next_ShouldReturnTheNextPage() { + final String result = testObj.next(redirectAttributesMock); + + assertThat(result).isEqualTo(NEXT); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/facades/impl/DefaultAPMAvailabilityFacadeTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/facades/impl/DefaultAPMAvailabilityFacadeTest.java index d21c2c74..4e44ba03 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/facades/impl/DefaultAPMAvailabilityFacadeTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/facades/impl/DefaultAPMAvailabilityFacadeTest.java @@ -20,7 +20,7 @@ public class DefaultAPMAvailabilityFacadeTest { @InjectMocks - private DefaultAPMAvailabilityFacade testObj = new DefaultAPMAvailabilityFacade(); + private DefaultAPMAvailabilityFacade testObj; @Mock private WorldpayAPMConfigurationModel apmConfigurationMock; @@ -42,4 +42,4 @@ public void isAvailableInvokesApmAvailabilityService() { verify(apmAvailabilityServiceMock).isAvailable(apmConfigurationMock, cartModelMock); } -} \ No newline at end of file +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/forms/validation/CseFormValidatorTest.java b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/forms/validation/CseFormValidatorTest.java index 6ab76b55..34f3b3cb 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/forms/validation/CseFormValidatorTest.java +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/testsrc/com/worldpay/forms/validation/CseFormValidatorTest.java @@ -1,7 +1,9 @@ package com.worldpay.forms.validation; +import com.worldpay.facades.order.WorldpayPaymentCheckoutFacade; import com.worldpay.forms.CSEPaymentForm; import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -9,21 +11,34 @@ import org.mockito.runners.MockitoJUnitRunner; import org.springframework.validation.Errors; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import static org.mockito.Mockito.*; @UnitTest -@RunWith (MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.class) public class CseFormValidatorTest { - public static final String CSE_TOKEN = "cseToken"; + private static final String CSE_TOKEN = "cseToken"; + private static final String BIRTH_DAY_DATE_FORMAT = "dd/MM/yyyy"; + private static final String CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY = "checkout.error.fraudSight.dob.mandatory"; + @InjectMocks private CseFormValidator testObj = new CseFormValidator(); + @Mock private Errors errorsMock; @Mock private CSEPaymentForm csePaymentFormMock; + @Mock + private WorldpayPaymentCheckoutFacade worldpayPaymentCheckoutFacadeMock; + + @Before + public void setUp() { + when(worldpayPaymentCheckoutFacadeMock.isFSEnabled()).thenReturn(true); + when(csePaymentFormMock.isDobRequired()).thenReturn(true); + } @Test public void shouldNotRejectIfCseIsSet() throws Exception { @@ -42,4 +57,23 @@ public void shouldRejectIfCseIsNotSet() throws Exception { verify(errorsMock).reject(CseFormValidator.GLOBAL_MISSING_CSE_TOKEN); } -} \ No newline at end of file + + @Test + public void validate_WhenFSIsEnabledAndBirthdayDateNull_ShouldAddTheError() { + when(csePaymentFormMock.getDateOfBirth()).thenReturn(null); + + testObj.validate(csePaymentFormMock, errorsMock); + + verify(errorsMock).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } + + @Test + public void validate_WhenFSIsEnabledAndBirthdayDateNotInThePast_ShouldAddTheError() throws ParseException { + final SimpleDateFormat df = new SimpleDateFormat(BIRTH_DAY_DATE_FORMAT); + when(csePaymentFormMock.getDateOfBirth()).thenReturn(df.parse("21/10/2100")); + + testObj.validate(csePaymentFormMock, errorsMock); + + verify(errorsMock).reject(CHECKOUT_ERROR_FRAUDSIGHT_DOB_MANDATORY); + } +} diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.js.properties b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.js.properties index 1cae6f57..8c6d4782 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.js.properties +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.js.properties @@ -13,4 +13,4 @@ worldpayaddon.CSE.validation.error.306=Expiry month and expiry year together mus worldpayaddon.CSE.validation.error.401=Card holder name is mandatory worldpayaddon.CSE.validation.error.402=Card holder name cannot exceed thirty (30) characters worldpayaddon.checkout.error.terms.not.accepted = Please accept our terms & conditions before submitting your order. -worldpayaddon.checkout.paymentMethod.shopperbankcode.default = Please select a bank. \ No newline at end of file +worldpayaddon.checkout.paymentMethod.shopperbankcode.default = Please select a bank. diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.properties b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.properties index b1db03cf..f9dfd2a3 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.properties +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/messages/base.properties @@ -75,3 +75,6 @@ checkout.billing.address.page.global.field.error=Some fields were not filled in text.quotes.enterSecurityCode=Card Verification Number +payment.dateOfBirth = Date of birth + +checkout.error.fraudSight.dob.mandatory = Date of birth is mandatory and must be in the past diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/dateOfBirthInput.tag b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/dateOfBirthInput.tag new file mode 100644 index 00000000..3a48899c --- /dev/null +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/dateOfBirthInput.tag @@ -0,0 +1,21 @@ +<%@ tag trimDirectiveWhitespaces="true" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> +<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> + + diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/worldpayCSECardDetails.tag b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/worldpayCSECardDetails.tag index 0492a594..7db9fc52 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/worldpayCSECardDetails.tag +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/tags/responsive/checkout/multi/worldpayCSECardDetails.tag @@ -1,6 +1,8 @@ <%@ tag trimDirectiveWhitespaces="true" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="wp-multi-checkout" tagdir="/WEB-INF/tags/addons/worldpayb2baddon/responsive/checkout/multi" %> <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> @@ -16,7 +18,25 @@ - + + + +
+ + + + + + + +
+
+
@@ -24,10 +44,12 @@
- +
- +
\ No newline at end of file +
diff --git a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayCheckoutSummaryPage.jsp b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayCheckoutSummaryPage.jsp index d07792ae..cdb7ecfb 100644 --- a/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayCheckoutSummaryPage.jsp +++ b/hybris/bin/y-ext/ext-worldpay/worldpayb2baddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/worldpayCheckoutSummaryPage.jsp @@ -49,10 +49,15 @@