Skip to content

Commit

Permalink
Merge pull request #41 from logeecom/PISYL-268/implementation
Browse files Browse the repository at this point in the history
add billing address when using Trustly
  • Loading branch information
hwysoszynski authored Jan 15, 2025
2 parents 65af674 + 91b9ba1 commit 1448b7b
Show file tree
Hide file tree
Showing 20 changed files with 175 additions and 22 deletions.
3 changes: 2 additions & 1 deletion src/Action/Api/CreatePaymentAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ public function execute($request): void
'metadata' => $details['metadata'],
];

if ($details['metadata']['molliePaymentMethods'] === PaymentMethod::ALMA) {
if ($details['metadata']['molliePaymentMethods'] === PaymentMethod::ALMA ||
$details['metadata']['molliePaymentMethods'] === PaymentMethod::TRUSTLY) {
$paymentDetails['billingAddress'] = $details['billingAddress'];
}

Expand Down
2 changes: 1 addition & 1 deletion src/Action/ConvertMolliePaymentAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public function execute($request): void
$details['metadata']['customer_mollie_id'] = $model['customer_mollie_id'];
}

if ($method->getMethodId() === PaymentMethod::ALMA) {
if ($method->getMethodId() === PaymentMethod::ALMA || $method->getMethodId() === PaymentMethod::TRUSTLY) {
$billingAddress = $order->getBillingAddress();
$customer = $order->getCustomer();
$address = [];
Expand Down
39 changes: 39 additions & 0 deletions src/Controller/Action/Shop/CreditCardTranslationController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace SyliusMolliePlugin\Controller\Action\Shop;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;

final class CreditCardTranslationController
{
/** @var TranslatorInterface */
private $translator;

/**
* @param TranslatorInterface $translator
*/
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}

/**
* @param Request $request
*
* @return JsonResponse
*/
public function fetchTranslations(Request $request): JsonResponse
{
$response = [
'emptyCardHolder' => $this->translator->trans('sylius_mollie_plugin.ui.credit_card_validations.empty_card_holder'),
'emptyCardNumber' => $this->translator->trans('sylius_mollie_plugin.ui.credit_card_validations.empty_card_number'),
'emptyExpiryDate' => $this->translator->trans('sylius_mollie_plugin.ui.credit_card_validations.empty_expiry_date'),
'emptyVerificationCode' => $this->translator->trans('sylius_mollie_plugin.ui.credit_card_validations.empty_verification_code'),
'oneOrMoreInvalidFields' => $this->translator->trans('sylius_mollie_plugin.ui.credit_card_validations.one_or_more_invalid_fields'),
];

return new JsonResponse(['status' => Response::HTTP_OK, 'translations' => $response]);
}
}
58 changes: 50 additions & 8 deletions src/Helper/ConvertOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

use Mollie\Api\Types\PaymentMethod;
use Sylius\Component\Addressing\Model\ZoneInterface;
use Sylius\Component\Core\Model\ImageInterface;
use Sylius\Component\Core\Model\Scope;
use Sylius\Component\Core\Model\ShippingMethodInterface;
use Sylius\Component\Taxation\Model\TaxRateInterface;
Expand All @@ -21,6 +22,7 @@
use Sylius\Component\Customer\Model\CustomerInterface;
use Sylius\Component\Order\Model\Adjustment;
use Sylius\Component\Taxation\Resolver\TaxRateResolverInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Webmozart\Assert\Assert;

final class ConvertOrder implements ConvertOrderInterface
Expand All @@ -46,18 +48,24 @@ final class ConvertOrder implements ConvertOrderInterface
/** @var ZoneMatcherInterface */
private $zoneMatcher;

/** @var RequestStack */
private $requestStack;

public function __construct(
IntToStringConverterInterface $intToStringConverter,
CalculateTaxAmountInterface $calculateTaxAmount,
MealVoucherResolverInterface $mealVoucherResolver,
TaxRateResolverInterface $taxRateResolver,
ZoneMatcherInterface $zoneMatcher
) {
ZoneMatcherInterface $zoneMatcher,
RequestStack $requestStack
)
{
$this->intToStringConverter = $intToStringConverter;
$this->calculateTaxAmount = $calculateTaxAmount;
$this->mealVoucherResolver = $mealVoucherResolver;
$this->taxRateResolver = $taxRateResolver;
$this->zoneMatcher = $zoneMatcher;
$this->requestStack = $requestStack;
}

public function convert(
Expand All @@ -71,8 +79,7 @@ public function convert(
Assert::notNull($this->order->getBillingAddress());
$this->zone = $this->zoneMatcher->match($this->order->getBillingAddress(), Scope::TAX);

if(null === $this->zone && null !== $this->order->getChannel())
{
if (null === $this->zone && null !== $this->order->getChannel()) {
Assert::notNull($this->order->getChannel());
$this->zone = $this->order->getChannel()->getDefaultTaxZone();
}
Expand All @@ -83,7 +90,7 @@ public function convert(
$amount = $this->intToStringConverter->convertIntToString($order->getTotal(), $divisor);

$details['amount']['value'] = $amount;
$details['orderNumber'] = (string) $order->getNumber();
$details['orderNumber'] = (string)$order->getNumber();
$details['shippingAddress'] = $this->createShippingAddress($customer);
$details['billingAddress'] = $this->createBillingAddress($customer, $method->getMethodId());
$details['lines'] = $this->createLines($divisor, $method);
Expand Down Expand Up @@ -146,7 +153,7 @@ private function createLines(int $divisor, MollieGatewayConfigInterface $method)
'type' => 'physical',
'name' => $item->getProductName(),
'quantity' => $item->getQuantity(),
'vatRate' => null === $taxRate ? '0.00' : (string) $taxRate->getAmountAsPercentage(),
'vatRate' => null === $taxRate ? '0.00' : (string)$taxRate->getAmountAsPercentage(),
'unitPrice' => [
'currency' => $this->order->getCurrencyCode(),
'value' => $this->intToStringConverter->convertIntToString($this->getUnitPriceWithTax($item, $taxRate), $divisor),
Expand All @@ -161,6 +168,7 @@ private function createLines(int $divisor, MollieGatewayConfigInterface $method)
'0.00' :
$this->calculateTaxAmount->calculate($taxRate->getAmount(), $item->getTotal()),
],
'imageUrl' => $this->getImageUrl($item),
'discountAmount' => [
'currency' => $this->order->getCurrencyCode(),
'value' => $this->intToStringConverter->convertIntToString($this->getItemDiscountAmount($item), $divisor),
Expand All @@ -181,6 +189,40 @@ private function createLines(int $divisor, MollieGatewayConfigInterface $method)
return $details;
}

/**
* Fetches product image url
*
* @param OrderItem $item
*
* @return string
*/
private function getImageUrl(OrderItem $item): string
{
$images = $item->getProduct()->getImages();
$imagePaths = [];

foreach ($images as $key => $image) {
if ($image instanceof ImageInterface) {
$imagePaths[] = $image->getPath();
}
}

if (!empty($imagePaths) && isset($imagePaths[0])) {
return rtrim($this->fetchBaseShopUrl(), '/') . '/media/cache/sylius_shop_product_thumbnail/'
. $imagePaths[0];
}

return '';
}

/**
* @return string
*/
private function fetchBaseShopUrl(): string
{
return $this->requestStack->getCurrentRequest()->getSchemeAndHttpHost();
}

private function createAdjustments(Adjustment $adjustment, int $divisor): array
{
return [
Expand Down Expand Up @@ -218,7 +260,7 @@ private function createShippingFee(int $divisor): array
'type' => self::SHIPPING_TYPE,
'name' => self::SHIPPING_FEE,
'quantity' => 1,
'vatRate' => null === $taxRate ? '0.00' : (string) $taxRate->getAmountAsPercentage(),
'vatRate' => null === $taxRate ? '0.00' : (string)$taxRate->getAmountAsPercentage(),
'unitPrice' => [
'currency' => $this->order->getCurrencyCode(),
'value' => $this->intToStringConverter->convertIntToString($this->order->getShippingTotal(), $divisor),
Expand Down Expand Up @@ -247,7 +289,7 @@ private function getUnitPriceWithTax(OrderItem $item, ?TaxRateInterface $taxRate
return $item->getUnitPrice();
}

return (int) round($item->getUnitPrice() + ($item->getTaxTotal() / $item->getQuantity()));
return (int)round($item->getUnitPrice() + ($item->getTaxTotal() / $item->getQuantity()));
}

private function getItemDiscountAmount(OrderItem $item): int
Expand Down
24 changes: 17 additions & 7 deletions src/Resources/assets/shop/js/mollie/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@ $(function () {
let mollieData = $('.online-online-payment__container');
let orderId = null;
let qrCodeInterval = null;
let qrCodeUrl = null;
const initialOrderTotal = $('#sylius-summary-grand-total').text();
const cardActiveClass = 'online-payment__item--active';
const orderTotalRow = $('#sylius-summary-grand-total');
const components = Boolean(mollieData.data('components'));
let creditCardTranslations = {};

if (mollieData && mollieData[0]) {
let fetchTranslationsUrl = mollieData[0].getAttribute('data-fetchTranslations');
fetchTranslations(fetchTranslationsUrl);
}

$('input[id*="sylius_checkout_select_payment_"][type=radio]').on('change', ({currentTarget}) => {
if (!currentTarget.classList.contains('mollie-payments')) {
Expand Down Expand Up @@ -203,7 +208,7 @@ $(function () {
}

function showQrCodePopUp() {
let cartVariantDetails = document.getElementById('cart-variant-details')
let cartVariantDetails = document.getElementById('cart-variant-details');

if (cartVariantDetails) {
let qrCodeGetUrl = cartVariantDetails.getAttribute('data-getQrCode');
Expand Down Expand Up @@ -331,8 +336,13 @@ $(function () {
mollieComponentFields.classList.remove('display-grid');
}

function initializeCreditCartFields(selectedValue) {
function fetchTranslations(url) {
fetch(url).then(response => response.json()).then(data => {
creditCardTranslations = data.translations;
});
}

function initializeCreditCartFields(selectedValue) {
const environment = mollieData.data('environment');
let testmode = true;

Expand All @@ -359,7 +369,7 @@ $(function () {
const cardHolderError = document.getElementById('card-holder-error');
cardHolder.addEventListener('change', (event) => {
if (event.error && event.touched) {
cardHolderError.textContent = event.error;
cardHolderError.textContent = creditCardTranslations.emptyCardHolder ? creditCardTranslations.emptyCardHolder : event.error;
} else {
cardHolderError.textContent = '';
}
Expand All @@ -372,7 +382,7 @@ $(function () {

cardNumber.addEventListener('change', (event) => {
if (event.error && event.touched) {
cardNumberError.textContent = event.error;
cardNumberError.textContent = creditCardTranslations.emptyCardNumber ? creditCardTranslations.emptyCardNumber : event.error;
} else {
cardNumberError.textContent = '';
}
Expand All @@ -385,7 +395,7 @@ $(function () {

expiryDate.addEventListener('change', (event) => {
if (event.error && event.touched) {
expiryDateError.textContent = event.error;
expiryDateError.textContent = creditCardTranslations.emptyExpiryDate ? creditCardTranslations.emptyExpiryDate : event.error;
} else {
expiryDateError.textContent = '';
}
Expand All @@ -398,7 +408,7 @@ $(function () {

verificationCode.addEventListener('change', (event) => {
if (event.error && event.touched) {
verificationCodeError.textContent = event.error;
verificationCodeError.textContent = creditCardTranslations.emptyVerificationCode ? creditCardTranslations.emptyVerificationCode : event.error;
} else {
verificationCodeError.textContent = '';
}
Expand Down
2 changes: 2 additions & 0 deletions src/Resources/config/routing/shop.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ mollie_payment_webhook:
resource: "shop/paymentWebhook.yaml"
mollie_page_redirect:
resource: "shop/pageRedirect.yaml"
mollie_credit_card_translation:
resource: "shop/creditCardTranslation.yaml"
4 changes: 4 additions & 0 deletions src/Resources/config/routing/shop/creditCardTranslation.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
sylius_mollie_plugin_credit_card_translation:
path: /fetch-translations
defaults:
_controller: sylius_mollie_plugin.controller.action.shop.credit_card_translation_controller::fetchTranslations
3 changes: 3 additions & 0 deletions src/Resources/config/services/controller.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@
<argument type="service" id="sylius_mollie_plugin.repository.mollie_gateway_config"/>
<argument type="service" id="sylius_mollie_plugin.helper.int_to_string"/>
</service>
<service id="sylius_mollie_plugin.controller.action.shop.credit_card_translation_controller" class="SyliusMolliePlugin\Controller\Action\Shop\CreditCardTranslationController">
<argument type="service" id="translator"/>
</service>
<service id="sylius_mollie_plugin.controller.action.shop.payum_controller" class="SyliusMolliePlugin\Controller\Action\Shop\PayumController">
<argument type="service" id="payum" />
<argument type="service" id="sylius.repository.order" />
Expand Down
1 change: 1 addition & 0 deletions src/Resources/config/services/helper.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<argument type="service" id="sylius_mollie_plugin.resolver.meal_voucher_resolver"/>
<argument type="service" id="sylius.tax_rate_resolver"/>
<argument type="service" id="sylius.zone_matcher"/>
<argument type="service" id="request_stack"/>
</service>
<service id="sylius_mollie_plugin.helper.convert_price_to_amount" class="SyliusMolliePlugin\Helper\ConvertPriceToAmount">
<argument type="service" id="sylius.context.currency"/>
Expand Down
2 changes: 2 additions & 0 deletions src/Resources/translations/flashes.de.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,6 @@ sylius_mollie_plugin:
empty_payment_method_checkout: 'Wählen Sie eine Mollie-Bezahlmethode'
billie.error:
company_missing: 'Die Angabe eines Firmennamens ist für die Zahlungsart Billie verpflichtend. Bitte geben Sie einen Firmennamen an oder wählen Sie eine andere Zahlungsart.'
billing_address.error:
info_missing: 'Bei Verwendung der Trustly-Zahlungsmethode sind Vorname, Nachname und E-Mail erforderlich. Bitte ergänzen Sie die fehlenden Daten oder wählen Sie eine andere Zahlungsart.'

2 changes: 2 additions & 0 deletions src/Resources/translations/flashes.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ sylius_mollie_plugin:
authentication_failed: 'Authentication failed'
billie.error:
company_missing: 'Company name is required when Billie payment method is used. Please set company name or choose another payment method'
billing_address.error:
info_missing: 'First name, last name and email are required when Trustly payment method is used. Please add the missing data or choose another payment method.'
empty_payment_method_checkout: 'Choose one of mollie payment method'
order_checkout:
colliding_products: 'There are mixed products (recurring and non-recurring) within your cart. Proceeding with mixed content is forbidden.'
2 changes: 2 additions & 0 deletions src/Resources/translations/flashes.fr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,6 @@ sylius_mollie_plugin:
empty_payment_method_checkout: 'Veuillez choisir une méthode de paiement Mollie'
billie.error:
company_missing: "Le nom de l'entreprise est requis lorsque la méthode de paiement Billie est utilisée. Veuillez indiquer le nom de l'entreprise ou choisir une autre méthode de paiement"
billing_address.error:
info_missing: "Le prénom, le nom et l'e-mail sont requis lorsque le mode de paiement Trustly est utilisé. Veuillez ajouter les données manquantes ou choisir un autre mode de paiement."

2 changes: 2 additions & 0 deletions src/Resources/translations/flashes.nl.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,6 @@ sylius_mollie_plugin:
empty_payment_method_checkout: 'Kies een van de Mollie-betalingsmethoden'
billie.error:
company_missing: 'De bedrijfsnaam is vereist bij het gebruik van Billie. Geef de bedrijfsnaam op of kies voor een andere betaalmethode.'
billing_address.error:
error: 'Voornaam, achternaam en e-mailadres zijn vereist bij gebruik van de Trustly-betaalmethode. Voeg ontbrekende gegevens toe of kies een andere betaalmethode.'

6 changes: 6 additions & 0 deletions src/Resources/translations/messages.de.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ sylius_mollie_plugin:
veryfication_code: 'Verifizierungscode'
save_card: 'Save credit card for the future purchases'
use_saved_card: 'Use saved credit card information'
credit_card_validations:
empty_card_holder: "Karteninhaber/in muss ausgefüllt werden"
empty_card_number: "Kartennummer muss ausgefüllt werden"
empty_expiry_date: "Gültig bis muss ausgefüllt werden"
empty_verification_code: "Prüfungsscode muss ausgefüllt werden"
one_or_more_invalid_fields: "Ein oder mehrere Felder sind ungültig"
surcharge_title: 'Aufschlag'
splitting_shipment_for_order: 'Lieferung für Auftrag #%number% teilen'
split_shipment: 'Lieferung teilen'
Expand Down
6 changes: 6 additions & 0 deletions src/Resources/translations/messages.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ sylius_mollie_plugin:
veryfication_code: 'CVC/CVV'
save_card: 'Save credit card for the future purchases'
use_saved_card: 'Use saved credit card information'
credit_card_validations:
empty_card_holder: "Card holder cannot be empty"
empty_card_number: "Card number cannot be empty"
empty_expiry_date: "Expiry date cannot be empty"
empty_verification_code: "Verification code cannot be empty"
one_or_more_invalid_fields: "One or more fields are invalid"
surcharge_title: 'Surcharge'
splitting_shipment_for_order: 'Splitting shipment for Order no. #%number%'
split_shipment: 'Split shipment'
Expand Down
6 changes: 6 additions & 0 deletions src/Resources/translations/messages.fr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ sylius_mollie_plugin:
veryfication_code: "Code de vérification"
save_card: 'Save credit card for the future purchases'
use_saved_card: 'Use saved credit card information'
credit_card_validations:
empty_card_holder: "Titulaire de la carte ne peut pas être vide"
empty_card_number: "Numéro de carte ne peut pas être vide"
empty_expiry_date: "Date d'expiration ne peut pas être vide"
empty_verification_code: "Code de vérification ne peut pas être vide"
one_or_more_invalid_fields: "Un ou plusieurs champs ne sont pas valides"
surcharge_title: "Supplément"
splitting_shipment_for_order: "Fractionner l'envoi de la commande nº #%number%"
split_shipment: "Expédition fractionnée"
Expand Down
6 changes: 6 additions & 0 deletions src/Resources/translations/messages.nl.yml
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ sylius_mollie_plugin:
veryfication_code: 'Verificatiecode'
save_card: 'Save credit card for the future purchases'
use_saved_card: 'Use saved credit card information'
credit_card_validations:
empty_card_holder: "Kaarthouder kan niet leeg zijn"
empty_card_number: "Kaartnummer kan niet leeg zijn"
empty_expiry_date: "Vervaldatum kan niet leeg zijn"
empty_verification_code: "Verificatiecode kan niet leeg zijn"
one_or_more_invalid_fields: "Een of meer velden zijn ongeldigd"
surcharge_title: 'Toeslag'
splitting_shipment_for_order: 'Verzending opsplitsen voor Bestelnr. #%number%'
split_shipment: 'Verzending opsplitsen'
Expand Down
1 change: 1 addition & 0 deletions src/Resources/views/Shop/PaymentMollie/_form.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
data-environment="{{ gatewayConfig.config['environment'] }}"
data-components="{{ gatewayConfig.config['components'] | default(false) }}"
data-removeQrCode="{{ path('sylius_mollie_plugin_remove_qr_code') }}"
data-fetchTranslations="{{ path('sylius_mollie_plugin_credit_card_translation') }}"
>
{% for keyChoice, choice in methodMollie.vars.choices %}
<div class="online-payment__item online-payment__item--{{ choice.value }}" id="{{ choice.value }}"
Expand Down
Loading

0 comments on commit 1448b7b

Please sign in to comment.