Skip to content

Commit

Permalink
Merge pull request #61 from two-inc/brtkwr-two/cet-537-fix-issue-with…
Browse files Browse the repository at this point in the history
…-saving-address-for-logged-in-customers

CET-537/fix: Ensure address can be updated using search criteria
  • Loading branch information
brtkwr authored Dec 7, 2024
2 parents aa53a22 + 185790b commit 4d88c27
Show file tree
Hide file tree
Showing 9 changed files with 123 additions and 38 deletions.
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ scripts/ export-ignore
.gitignore export-ignore
.gitattributes export-ignore
.prettierrc export-ignore
.pre-commit-config.yaml export-ignore
bumpver.toml export-ignore
docker-compose.yaml export-ignore
README.md export-ignore
Expand Down
15 changes: 15 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ minimum_pre_commit_version: 3.2.0
default_install_hook_types: [pre-commit, commit-msg, prepare-commit-msg]
default_stages: [pre-commit]
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-ast
- id: check-added-large-files
- id: check-json
- id: check-merge-conflict
- id: check-toml
- id: check-yaml
- id: detect-private-key
- id: end-of-file-fixer
- id: pretty-format-json
args: ["--indent=\t", '--no-sort-keys']
- id: requirements-txt-fixer
- id: trailing-whitespace
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.1.0
hooks:
Expand Down
97 changes: 68 additions & 29 deletions Controller/Payment/Confirm.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Exception;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
Expand All @@ -32,6 +33,11 @@ class Confirm extends Action
*/
private $addressRepository;

/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;

/**
* @var OrderService
*/
Expand All @@ -45,11 +51,13 @@ class Confirm extends Action
public function __construct(
Context $context,
AddressRepositoryInterface $addressRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
OrderService $orderService,
OrderSender $orderSender,
ConfigRepository $configRepository
) {
$this->addressRepository = $addressRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->orderService = $orderService;
$this->orderSender = $orderSender;
$this->configRepository = $configRepository;
Expand All @@ -69,17 +77,10 @@ public function execute()
if (isset($twoOrder['state']) && $twoOrder['state'] != 'UNVERIFIED') {
if (in_array($twoOrder['state'], ['VERIFIED', 'CONFIRMED'])) {
$this->orderService->confirmOrder($order);
$this->orderSender->send($order);
}
$this->orderSender->send($order);
try {
$this->updateCustomerAddress($order, $twoOrder);
} catch (LocalizedException $exception) {
$message = __(
"Failed to update %1 customer address: %2",
$this->configRepository::PROVIDER,
$exception->getMessage()
);
$this->orderService->addOrderComment($order, $message);
} catch (Exception $exception) {
$message = __(
"Failed to update %1 customer address: %2",
Expand All @@ -91,15 +92,16 @@ public function execute()
$this->orderService->processOrder($order, $twoOrder['id']);
return $this->getResponse()->setRedirect($this->_url->getUrl('checkout/onepage/success'));
} else {
$comment = __(
'Unable to confirm %1 order with %2 state.',
$this->configRepository::PROVIDER,
$twoOrder['state'] ?? 'undefined'
);
$this->orderService->addOrderComment($order, $comment);
$message = __(
'Unable to retrieve payment information for your invoice purchase with %1. ' .
'The cart will be restored.',
'Your invoice purchase with %1 could not be processed. The cart will be restored.',
$this->configRepository::PROVIDER
);
if (!empty($twoOrder['decline_reason'])) {
$message = __('%1 Decline reason: %2', $message, $twoOrder['decline_reason']);
}
$this->orderService->addOrderComment($order, $message);
throw new LocalizedException($message);
}
} catch (Exception $exception) {
Expand All @@ -124,25 +126,62 @@ public function execute()
private function updateCustomerAddress($order, $twoOrder)
{
$customerAddress = null;
if ($order->getBillingAddress()->getCustomerAddressId()) {
$billingAddress = $order->getBillingAddress();
if ($billingAddress->getCustomerAddressId()) {
// Try to load the customer address by ID
$customerAddress = $this->addressRepository->getById(
$order->getBillingAddress()->getCustomerAddressId()
$billingAddress->getCustomerAddressId()
);
if ($customerAddress && $customerAddress->getId()) {
if (isset($twoOrder['buyer']['company']['organization_number'])) {
$customerAddress->setData('company_id', $twoOrder['buyer']['company']['organization_number']);
}
if (isset($twoOrder['buyer']['company']['company_name'])) {
$customerAddress->setData('company_name', $twoOrder['buyer']['company']['company_name']);
}
if (isset($twoOrder['buyer_department'])) {
$customerAddress->setData('department', $twoOrder['buyer_department']);
}
if (isset($twoOrder['buyer_project'])) {
$customerAddress->setData('project', $twoOrder['buyer_project']);
}
if ($customerAddress == null && $order->getCustomerId()) {
// Build a search criteria to find customer addresse that matches the billing address
$keys = [
'parent_id',
'firstname',
'middlename',
'lastname',
'street',
'city',
'postcode',
'country_id',
'region_id',
'region',
'telephone',
'company',
];
foreach ($keys as $key) {
$value = ($key === 'parent_id')
? $order->getCustomerId()
: $billingAddress->getData($key);
if (!empty($value)) {
$this->searchCriteriaBuilder->addFilter($key, $value, 'eq');
}
$this->addressRepository->save($customerAddress);
}
$searchCriteria = $this->searchCriteriaBuilder->create();
$customerAddressCollection = $this->addressRepository
->getList($searchCriteria)
->getItems();
$customerAddress = $customerAddressCollection[0] ?? null;
}
if ($customerAddress && $customerAddress->getId()) {
if (isset($twoOrder['buyer']['company']['organization_number'])) {
$customerAddress->setData('company_id', $twoOrder['buyer']['company']['organization_number']);
}
if (isset($twoOrder['buyer']['company']['company_name'])) {
$customerAddress->setData('company_name', $twoOrder['buyer']['company']['company_name']);
}
if (isset($twoOrder['buyer_department'])) {
$customerAddress->setData('department', $twoOrder['buyer_department']);
}
if (isset($twoOrder['buyer_project'])) {
$customerAddress->setData('project', $twoOrder['buyer_project']);
}
$this->addressRepository->save($customerAddress);
$message = __(
"%1 customer address updated.",
$this->configRepository::PROVIDER,
);
$this->orderService->addOrderComment($order, $message);
}
}
}
6 changes: 3 additions & 3 deletions Model/Ui/ConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public function getConfig(): array
$provider = $this->configRepository::PROVIDER;
$tryAgainLater = __('Please try again later.');
$soleTraderaccountCouldNotBeVerified = __('Your sole trader account could not be verified.');
$paymentTerms = __("Payment Terms");
$paymentTerms = __("%1 terms and conditions", $this->configRepository::PROVIDER);
$paymentTermsLink = $this->configRepository->getCheckoutPageUrl() . '/terms';

return [
Expand Down Expand Up @@ -116,10 +116,10 @@ public function getConfig(): array
$tryAgainLater
),
'paymentTermsMessage' => __(
'By checking this box, I confirm that I have read and agree to the %1.',
'By checking this box, I confirm that I have read and agree to %1.',
sprintf('<a href="%s" target="_blank">%s</a>', $paymentTermsLink, $paymentTerms)
),
'termsNotAcceptedMessage' => __('You must first accept the payment terms.'),
'termsNotAcceptedMessage' => __('You must accept %1 to place order.', $paymentTerms),
'soleTraderErrorMessage' => __(
'Something went wrong with your request to %1. %2',
$provider,
Expand Down
10 changes: 4 additions & 6 deletions Service/Payment/OrderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -306,13 +306,11 @@ public function processOrder(Order $order, string $transactionId)
if ($invoice->getGrandTotal() > 0) {
$invoice->setRequestedCaptureCase(Invoice::CAPTURE_ONLINE);
$invoice->register();
$this->addOrderComment(
$order,
sprintf(
'%s order payment has been verified',
$this->configRepository::PROVIDER
)
$message = __(
'%1 payment has been verified by the customer.',
$this->configRepository::PROVIDER
);
$this->addOrderComment($order, $message);
$transactionSave = $this->transaction
->addObject(
$payment
Expand Down
8 changes: 8 additions & 0 deletions i18n/en_US.csv
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
"%1 Decline reason: %2","%1 Decline reason: %2"
"%1 Details","%1 Details"
"%1 [Trace ID: %2]","%1 [Trace ID: %2]"
"%1 customer address updated.","%1 customer address updated."
"%1 order has been marked as cancelled","%1 order has been marked as cancelled"
"%1 order invoice has not been issued yet.","%1 order invoice has not been issued yet."
"%1 order marked as completed.","%1 order marked as completed."
"%1 order marked as partially completed.","%1 order marked as partially completed."
"%1 payment has been verified by the customer.","%1 payment has been verified by the customer."
"%1 payment terms","%1 payment terms"
"%1 requires whole order to be shipped before it can be fulfilled.","%1 requires whole order to be shipped before it can be fulfilled."
"%1 terms and conditions","%1 terms and conditions"
"* Required Fields","* Required Fields"
"API key","API key"
"API key is missing","API key is missing"
Expand All @@ -20,6 +24,7 @@
"Amount is missing","Amount is missing"
Branding,Branding
"Buy now, receive your goods, pay your invoice later.","Buy now, receive your goods, pay your invoice later."
"By checking this box, I confirm that I have read and agree to %1.","By checking this box, I confirm that I have read and agree to %1."
"By checking this box, I confirm that I have read and agree to the %1.","By checking this box, I confirm that I have read and agree to the %1."
"Check last 100 debug log records","Check last 100 debug log records"
"Check last 100 error log records","Check last 100 error log records"
Expand Down Expand Up @@ -93,11 +98,14 @@ TWO,TWO
"The capture action is not available.","The capture action is not available."
Title,Title
"Two is a payment solution for B2B purchases online, allowing you to buy from your favourite merchants and suppliers on trade credit. Using Two, you can access flexible trade credit instantly to make purchasing simple.","Two is a payment solution for B2B purchases online, allowing you to buy from your favourite merchants and suppliers on trade credit. Using Two, you can access flexible trade credit instantly to make purchasing simple."
"Unable to confirm %1 order with %2 state.","Unable to confirm %1 order with %2 state."
"Unable to find the requested %1 order","Unable to find the requested %1 order"
"Unable to retrieve payment information for your invoice purchase with %1. The cart will be restored.","Unable to retrieve payment information for your invoice purchase with %1. The cart will be restored."
Version,Version
"You must accept %1 to place order.","You must accept %1 to place order."
"You must first accept the payment terms.","You must first accept the payment terms."
"You will be redirected to %1 when you place order.","You will be redirected to %1 when you place order."
"Your invoice purchase with %1 could not be processed. The cart will be restored.","Your invoice purchase with %1 could not be processed. The cart will be restored."
"Your invoice purchase with %1 failed verification. The cart will be restored.","Your invoice purchase with %1 failed verification. The cart will be restored."
"Your invoice purchase with %1 has been cancelled. The cart will be restored.","Your invoice purchase with %1 has been cancelled. The cart will be restored."
"Your invoice purchase with %1 has been declined.","Your invoice purchase with %1 has been declined."
Expand Down
8 changes: 8 additions & 0 deletions i18n/nb_NO.csv
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
"%1 Decline reason: %2","%1 Årsak til avvisning: %2"
"%1 Details","%1 Detaljer"
"%1 [Trace ID: %2]","%1 [Sporings-ID: %2]"
"%1 customer address updated.","%1 kundeadresse oppdatert."
"%1 order has been marked as cancelled","%1 ordre er merket som kansellert"
"%1 order invoice has not been issued yet.","%1 ordrefaktura er ikke utstedt ennå."
"%1 order marked as completed.","%1 bestilling merket som fullført."
"%1 order marked as partially completed.","%1 bestilling merket som delvis fullført."
"%1 payment has been verified by the customer.","%1 betaling er bekreftet av kunden."
"%1 payment terms","%1 betalingsbetingelser"
"%1 requires whole order to be shipped before it can be fulfilled.","%1 krever at hele bestillingen sendes før den kan oppfylles."
"%1 terms and conditions","%1 vilkår og betingelser"
"* Required Fields","* Obligatoriske felter"
"API key",API-nøkkel
"API key is missing","API-nøkkel mangler"
Expand All @@ -20,6 +24,7 @@
"Amount is missing","Beløp mangler"
Branding,Merkevarebygging
"Buy now, receive your goods, pay your invoice later.","Kjøp nå, motta varene dine, betal fakturaen senere."
"By checking this box, I confirm that I have read and agree to %1.","Ved å merke av i denne boksen, bekrefter jeg at jeg har lest og godtar %1."
"By checking this box, I confirm that I have read and agree to the %1.","Ved å krysse av denne boksen bekrefter jeg at jeg har lest og godtar %1."
"Check last 100 debug log records","Sjekk siste 100 feilsøkingsloggposter"
"Check last 100 error log records","Sjekk siste 100 feilloggposter"
Expand Down Expand Up @@ -93,11 +98,14 @@ TWO,TWO
"The capture action is not available.","Opptakshandlingen er ikke tilgjengelig."
Title,Tittel
"Two is a payment solution for B2B purchases online, allowing you to buy from your favourite merchants and suppliers on trade credit. Using Two, you can access flexible trade credit instantly to make purchasing simple.","Two er en betalingsløsning for B2B-kjøp på nettet, som lar deg kjøpe fra dine favorittforhandlere og leverandører på handelskreditt. Med Two kan du få tilgang til fleksibel handelskreditt umiddelbart for å gjøre innkjøp enkelt."
"Unable to confirm %1 order with %2 state.","Kan ikke bekrefte %1 bestilling med %2 status."
"Unable to find the requested %1 order","Kan ikke finne den forespurte bestillingen %1"
"Unable to retrieve payment information for your invoice purchase with %1. The cart will be restored.","Kan ikke hente betalingsinformasjon for fakturakjøpet med %1. Vognen vil bli restaurert."
Version,Versjon
"You must accept %1 to place order.","Du må akseptere %1 for å legge inn bestillingen."
"You must first accept the payment terms.","Du må først godta betalingsvilkårene."
"You will be redirected to %1 when you place order.","Du vil bli omdirigert til %1 når du legger inn bestilling."
"Your invoice purchase with %1 could not be processed. The cart will be restored.","Fakturaen din med %1 kunne ikke behandles. Handlevognen vil bli gjenopprettet."
"Your invoice purchase with %1 failed verification. The cart will be restored.","Fakturakjøpet med %1 mislyktes i bekreftelsen. Vognen vil bli restaurert."
"Your invoice purchase with %1 has been cancelled. The cart will be restored.","Ditt fakturakjøp med %1 er kansellert. Vognen vil bli restaurert."
"Your invoice purchase with %1 has been declined.","Ditt fakturakjøp med %1 har blitt avvist."
Expand Down
Loading

0 comments on commit 4d88c27

Please sign in to comment.