From 21cbed973e3180f4980a025aae8e90516098ffde Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Thu, 26 Dec 2024 15:20:55 +0100 Subject: [PATCH 01/15] feat: New Alma client service --- src/assets/js/stores/alma-store.js | 57 ++++ src/includes/Blocks/BlocksDataService.php | 153 ++++++++++ src/includes/Services/AlmaClientService.php | 286 ++++++++++++++++++ src/tests/Blocks/BlocksDataServiceTest.php | 179 +++++++++++ src/tests/Services/AlmaClientServiceTest.php | 298 +++++++++++++++++++ 5 files changed, 973 insertions(+) create mode 100644 src/assets/js/stores/alma-store.js create mode 100644 src/includes/Blocks/BlocksDataService.php create mode 100644 src/includes/Services/AlmaClientService.php create mode 100644 src/tests/Blocks/BlocksDataServiceTest.php create mode 100644 src/tests/Services/AlmaClientServiceTest.php diff --git a/src/assets/js/stores/alma-store.js b/src/assets/js/stores/alma-store.js new file mode 100644 index 00000000..d5cefde8 --- /dev/null +++ b/src/assets/js/stores/alma-store.js @@ -0,0 +1,57 @@ +import {registerStore} from '@wordpress/data'; + + +const DEFAULT_STATE = { + almaEligibility: {}, + isLoading: false, +}; + +const actions = { + setAlmaEligibility(data) { + return { + type: 'SET_ALMA_ELIGIBILITY', + payload: data, + }; + }, + setLoading(isLoading) { + return { + type: 'SET_LOADING', + payload: isLoading, + }; + }, +}; + +function reducer(state = DEFAULT_STATE, action) { + switch (action.type) { + case 'SET_ALMA_ELIGIBILITY': + console.log('SET_ALMA_ELIGIBILITY') + return { + ...state, + almaEligibility: action.payload, + }; + case 'SET_LOADING': + return { + ...state, + isLoading: action.payload, + }; + default: + return state; + } +} + +const selectors = { + getAlmaEligibility(state) { + return state.almaEligibility; + }, + isLoading(state) { + return state.isLoading; + }, +}; + +const store = registerStore('alma/alma-store', { + reducer, + actions, + selectors, +}); + +export default store; diff --git a/src/includes/Blocks/BlocksDataService.php b/src/includes/Blocks/BlocksDataService.php new file mode 100644 index 00000000..4bf405fa --- /dev/null +++ b/src/includes/Blocks/BlocksDataService.php @@ -0,0 +1,153 @@ +init_alma_client_service( $alma_client_service ); + $this->init_function_proxy( $function_proxy ); + $this->init_alma_logger( $logger ); + } + + public function init_hooks() { + add_action( + ToolsHelper::action_for_webhook( AlmaBlock::WEBHOOK_PATH ), + array( + $this, + 'get_blocks_data', + ) + ); + } + + public function get_blocks_data() { + try { + $almaClient = $this->alma_client_service->get_alma_client(); + $eligibilities = $this->alma_client_service->get_eligibility( WC()->cart, $almaClient ); + } catch ( ApiClientException $e ) { + $this->logger->info( 'Impossible to set Alma client: ' . $e->getMessage() ); + $this->function_proxy->send_http_error_response( [ + 'success' => false, + ], 500 ); + } + + $response = [ + 'success' => true, + 'eligibility' => $this->format_eligibility_for_blocks( $eligibilities ), + 'cart_total' => [ 'cart_total' => (float) WC()->cart->get_total( '' ) ], + ]; + // Send JSON response + $this->function_proxy->send_http_response( $response ); + } + + private function format_eligibility_for_blocks( $eligibilities ) { + $gateways = [ + PayNowGateway::GATEWAY_ID => [], + StandardGateway::GATEWAY_ID => [], + PayLaterGateway::GATEWAY_ID => [], + PayMoreThanFourGateway::GATEWAY_ID => [] + ]; + foreach ( $eligibilities as $plan_key => $eligibility ) { + /** @var Eligibility $eligibility */ + $installment_count = $eligibility->getInstallmentsCount(); + $deferred_days = $eligibility->getDeferredDays(); + $deferred_months = $eligibility->getDeferredMonths(); + + // Pay now + if ( $installment_count === 1 && $deferred_months === 0 && $deferred_days === 0 ) { + $gateways[ PayNowGateway::GATEWAY_ID ][ $plan_key ] = $this->format_plan_content_for_blocks( $eligibility ); + } + // Pay in installments + if ( $installment_count >= 1 && $installment_count <= 4 && $deferred_months === 0 && $deferred_days === 0 ) { + $gateways[ StandardGateway::GATEWAY_ID ][ $plan_key ] = $this->format_plan_content_for_blocks( $eligibility ); + } + // Pay in credit + if ( $installment_count > 4 && $deferred_months === 0 && $deferred_days === 0 ) { + $gateways[ PayMoreThanFourGateway::GATEWAY_ID ][ $plan_key ] = $this->format_plan_content_for_blocks( $eligibility ); + } + // Pay later + if ( $installment_count === 1 && ( $deferred_months > 0 || $deferred_days > 0 ) ) { + $gateways[ PayLaterGateway::GATEWAY_ID ][ $plan_key ] = $this->format_plan_content_for_blocks( $eligibility ); + } + } + + return $gateways; + } + + private function format_plan_content_for_blocks( $eligibility ) { + return [ + 'paymentPlan' => $eligibility->getPaymentPlan(), + 'customerTotalCostAmount' => $eligibility->getCustomerTotalCostAmount(), + ]; + } + + /** + * Init alma client service + * + * @param AlmaClientService|null $alma_client_service + * + * @return void + */ + private function init_alma_client_service( $alma_client_service ) { + if ( ! isset( $alma_client_service ) ) { + $alma_client_service = new AlmaClientService(); + } + $this->alma_client_service = $alma_client_service; + } + + /** + * @param $logger + * + * @return void + */ + private function init_alma_logger( $logger ) { + if ( ! isset( $logger ) ) { + $logger = new AlmaLogger(); + } + $this->logger = $logger; + } + + private function init_function_proxy( $function_proxy ) { + if ( ! isset( $function_proxy ) ) { + $function_proxy = new FunctionsProxy(); + } + $this->function_proxy = $function_proxy; + } + +} \ No newline at end of file diff --git a/src/includes/Services/AlmaClientService.php b/src/includes/Services/AlmaClientService.php new file mode 100644 index 00000000..e4d329c8 --- /dev/null +++ b/src/includes/Services/AlmaClientService.php @@ -0,0 +1,286 @@ +encryptor_helper = $this->init_encryptor_helper( $encryption_helper ); + $this->version_factory = $this->init_version_factory( $version_factory ); + $this->cart_helper = $this->init_cart_helper( $cart_helper ); + $this->option_proxy = $this->init_option_proxy( $option_proxy ); + $this->logger = $this->init_alma_logger( $logger ); + } + + /** + * Get Alma client with the current API KEY and mode + * + * @return Client + * @throws ApiClientException + */ + public function get_alma_client() { + try { + $alma_client = new Client( + $this->get_active_api_key(), + array( + 'mode' => $this->get_mode(), + 'logger' => $this->logger, + ) + ); + } catch ( DependenciesError $e ) { + throw new ApiClientException( $e->getMessage() ); + } catch ( ParamsError $e ) { + throw new ApiClientException( $e->getMessage() ); + } + + + $alma_client->addUserAgentComponent( 'WordPress', get_bloginfo( 'version' ) ); + $alma_client->addUserAgentComponent( 'WooCommerce', $this->version_factory->get_version() ); + $alma_client->addUserAgentComponent( 'Alma for WooCommerce', ALMA_VERSION ); + + return $alma_client; + } + + + /** + * Get alma Eligibility from cart + * + * @param Client $alma_client + * + * @return Eligibility[] | [] + */ + public function get_eligibility( $alma_client, $cart ) { + try { + $payload = $this->get_eligibility_payload_from_cart( $cart ); + $eligibility = $alma_client->payments->eligibility( $payload, true ); + } catch ( RequestError $e ) { + $this->logger->error( 'Error in get eligibility : ' . $e->getMessage() ); + + return []; + } + + return $eligibility; + } + + /** + * @param \WC_Cart $cart + * + * @return array + */ + private function get_eligibility_payload_from_cart( $cart ) { + $data = array( + 'purchase_amount' => (int) ( round( (float) $cart->get_total( '' ) * 100 ) ), + 'queries' => $this->cart_helper->get_eligible_plans_for_cart(), + 'locale' => apply_filters( 'alma_eligibility_user_locale', get_locale() ), + ); + + $billing_country = $cart->get_customer()->get_billing_country(); + $shipping_country = $cart->get_customer()->get_shipping_country(); + + if ( $billing_country ) { + $data['billing_address'] = array( 'country' => $billing_country ); + } + if ( $shipping_country ) { + $data['shipping_address'] = array( 'country' => $shipping_country ); + } + + return $data; + } + + + /** + * Get the alma setting in DB + * + * @return array + */ + private function get_alma_settings() { + return (array) $this->option_proxy->get_option( AlmaSettings::OPTIONS_KEY, array() ); + } + + /** + * Get active decrypted API key depending on mode + * + * @return string + * @throws ApiClientException + */ + private function get_active_api_key() { + return $this->get_mode() === 'live' ? $this->get_live_api_key() : $this->get_test_api_key(); + } + + /** + * Return alma mode test|live set in DB + * + * @return string + * @throws ApiClientException + */ + private function get_mode() { + $setting = $this->get_alma_settings(); + if ( isset( $setting['environment'] ) ) { + return $setting['environment'] === 'live' ? 'live' : 'test'; + } + throw new ApiClientException( 'No mode set' ); + } + + /** + * Gets API key for live environment. + * + * @return string + * @throws ApiClientException + */ + private function get_live_api_key() { + $setting = $this->get_alma_settings(); + if ( isset( $setting['live_api_key'] ) ) { + return $this->encryptor_helper->decrypt( $setting['live_api_key'] ); + } + throw new ApiClientException( 'Live api key not set' ); + } + + /** + * Gets API key for test environment. + * + * @return string + * @throws ApiClientException + */ + private function get_test_api_key() { + $setting = $this->get_alma_settings(); + if ( isset( $setting['test_api_key'] ) ) { + return $this->encryptor_helper->decrypt( $setting['test_api_key'] ); + } + throw new ApiClientException( 'Test api key not set' ); + } + + /** + * Init Alma logger + * + * @param AlmaLogger|null $logger + * + * @return AlmaLogger + */ + private function init_alma_logger( $logger ) { + if ( ! isset( $logger ) ) { + $logger = new AlmaLogger(); + } + + return $logger; + } + + /** + * Init encryptor helper + * + * @param EncryptorHelper|null $encryptor_helper + * + * @return EncryptorHelper + */ + private function init_encryptor_helper( $encryptor_helper ) { + if ( ! isset( $encryptor_helper ) ) { + $encryptor_helper = new EncryptorHelper(); + } + + return $encryptor_helper; + } + + /** + * Init version factory + * + * @param VersionFactory|null $version_factory + * + * @return VersionFactory + */ + private function init_version_factory( $version_factory ) { + if ( ! isset( $version_factory ) ) { + $version_factory = new VersionFactory(); + } + + return $version_factory; + } + + /** + * Init cart helper + * + * @param CartHelper|null $cart_helper + * + * @return CartHelper + */ + private function init_cart_helper( $cart_helper ) { + if ( ! isset( $cart_helper ) ) { + $cart_helper_builder = new CartHelperBuilder(); + $cart_helper = $cart_helper_builder->get_instance(); + } + + return $cart_helper; + } + + /** + * Init option proxy + * + * @param OptionProxy|null $option_proxy + * + * @return OptionProxy + */ + private function init_option_proxy( $option_proxy ) { + if ( ! isset( $option_proxy ) ) { + $option_proxy = new OptionProxy(); + } + + return $option_proxy; + } +} \ No newline at end of file diff --git a/src/tests/Blocks/BlocksDataServiceTest.php b/src/tests/Blocks/BlocksDataServiceTest.php new file mode 100644 index 00000000..849b05a2 --- /dev/null +++ b/src/tests/Blocks/BlocksDataServiceTest.php @@ -0,0 +1,179 @@ +alma_client_service = $this->createMock( AlmaClientService::class ); + $this->function_proxy = $this->createMock( FunctionsProxy::class ); + $this->alma_logger = $this->createMock( AlmaLogger::class ); + $this->blocks_data_service = new BlocksDataService( + $this->alma_client_service, + $this->function_proxy, + $this->alma_logger + ); + } + + public function test_get_blocks_data() { + $this->alma_client_service + ->method( 'get_eligibility' ) + ->willReturn( $this->eligibility_array() ); + $this->function_proxy + ->expects( $this->once() ) + ->method( 'send_http_response' ) + ->with( $this->response_data() ); + $this->assertNull( $this->blocks_data_service->get_blocks_data() ); + } + + private function response_data() { + return [ + 'success' => true, + 'eligibility' => [ + 'alma_pay_now' => [], + 'alma' => [ + 'general_3_0_0' => [ + 'paymentPlan' => [ + [ + "due_date" => 1735208969, + "total_amount" => 5773, + "customer_fee" => 273, + "customer_interest" => 0, + "purchase_amount" => 5500, + "localized_due_date" => "today", + "time_delta_from_start" => null + ], + [ + "due_date" => 1737887369, + "total_amount" => 5500, + "customer_fee" => 0, + "customer_interest" => 0, + "purchase_amount" => 5500, + "localized_due_date" => "January 26, 2025", + "time_delta_from_start" => null + ], + [ + "due_date" => 1740565769, + "total_amount" => 5500, + "customer_fee" => 0, + "customer_interest" => 0, + "purchase_amount" => 5500, + "localized_due_date" => "February 26, 2025", + "time_delta_from_start" => null + ] + ], + "customerTotalCostAmount" => 273 + ] + ], + 'alma_pay_later' => [ + 'general_1_15_0' => [ + 'paymentPlan' => [ + [ + "due_date" => 1736504969, + "total_amount" => 16500, + "customer_fee" => 0, + "customer_interest" => 0, + "purchase_amount" => 16500, + "localized_due_date" => "January 10, 2025", + "time_delta_from_start" => null + ], + ], + "customerTotalCostAmount" => 0 + ] + ], + 'alma_pnx_plus_4' => [] + ], + 'cart_total' => [ 'cart_total' => (float) WC()->cart->get_total( '' ) ] + ]; + } + + private function eligibility_array() { + $eligibilities = json_decode + ( + '{ + "general_1_15_0":{ + "is_eligible":true, + "reasons":null, + "constraints":null, + "payment_plan":[ + { + "due_date":1736504969, + "total_amount":16500, + "customer_fee":0, + "customer_interest":0, + "purchase_amount":16500, + "localized_due_date":"January 10, 2025", + "time_delta_from_start":null + } + ], + "installments_count":1, + "deferred_days":15, + "deferred_months":0, + "customer_total_cost_amount":0, + "customer_total_cost_bps":0, + "annual_interest_rate":0 + }, + "general_3_0_0":{ + "is_eligible":true, + "reasons":null, + "constraints":null, + "payment_plan":[ + { + "due_date":1735208969, + "total_amount":5773, + "customer_fee":273, + "customer_interest":0, + "purchase_amount":5500, + "localized_due_date":"today", + "time_delta_from_start":null + }, + { + "due_date":1737887369, + "total_amount":5500, + "customer_fee":0, + "customer_interest":0, + "purchase_amount":5500, + "localized_due_date":"January 26, 2025", + "time_delta_from_start":null + }, + { + "due_date":1740565769, + "total_amount":5500, + "customer_fee":0, + "customer_interest":0, + "purchase_amount":5500, + "localized_due_date":"February 26, 2025", + "time_delta_from_start":null + } + ], + "installments_count":3, + "deferred_days":0, + "deferred_months":0, + "customer_total_cost_amount":273, + "customer_total_cost_bps":165, + "annual_interest_rate":2230 + } + }' + , true ); + $result = []; + foreach ( $eligibilities as $eligibilityData ) { + $eligibility = new Eligibility( $eligibilityData ); + $result[ $eligibility->getPlanKey() ] = $eligibility; + } + + return $result; + } + +} \ No newline at end of file diff --git a/src/tests/Services/AlmaClientServiceTest.php b/src/tests/Services/AlmaClientServiceTest.php new file mode 100644 index 00000000..eead388f --- /dev/null +++ b/src/tests/Services/AlmaClientServiceTest.php @@ -0,0 +1,298 @@ +encryptor_helper = $this->createMock( EncryptorHelper::class ); + $this->version_factory = $this->createMock( VersionFactory::class ); + $this->cart_helper = $this->createMock( CartHelper::class ); + $this->option_proxy = $this->createMock( OptionProxy::class ); + $this->logger = $this->createMock( AlmaLogger::class ); + $this->alma_client_service = new AlmaClientService( + $this->encryptor_helper, + $this->version_factory, + $this->cart_helper, + $this->option_proxy, + $this->logger + ); + } + + /** + * @return void + * @dataProvider api_client_exception_data_provider + * @throws ApiClientException + */ + public function test_get_alma_client_without_mode( $setting, $message ) { + $this->option_proxy->method( 'get_option' )->willReturn( $setting ); + $this->expectException( ApiClientException::class ); + $this->expectExceptionMessage( $message ); + $this->alma_client_service->get_alma_client(); + } + + public function test_get_eligibility_return_empty_on_error() { + $this->cart_helper + ->method( 'get_eligible_plans_for_cart' ) + ->willReturn( [ 'installments_count' => 3 ] ); + + $client_mock = $this->createMock( Client::class ); + + $payment_endpoint = $this->createMock( Payments::class ); + $payment_endpoint + ->expects( $this->once() ) + ->method( 'eligibility' ) + ->with( + [ + 'purchase_amount' => 24523, + 'queries' => [ 'installments_count' => 3 ], + 'locale' => apply_filters( 'alma_eligibility_user_locale', get_locale() ), + 'billing_address' => [ 'country' => 'FR' ], + 'shipping_address' => [ 'country' => 'UK' ], + ], + true + ) + ->willThrowException( new RequestError( 'Eligibility Error' ) ); + $client_mock->payments = $payment_endpoint; + + $cart_mock = $this->createMock( \WC_Cart::class ); + $customer_mock = $this->createMock( \WC_Customer::class ); + $customer_mock->method( 'get_billing_country' )->willReturn( 'FR' ); + $customer_mock->method( 'get_shipping_country' )->willReturn( 'UK' ); + + $cart_mock->method( 'get_total' )->willReturn( 245.23 ); + $cart_mock->method( 'get_customer' )->willReturn( $customer_mock ); + + $this->assertEquals( [], $this->alma_client_service->get_eligibility( $client_mock, $cart_mock ) ); + + } + + public function test_get_eligibility() { + $this->cart_helper + ->method( 'get_eligible_plans_for_cart' ) + ->willReturn( [ 'installments_count' => 3 ] ); + + $client_mock = $this->createMock( Client::class ); + + $payment_endpoint = $this->createMock( Payments::class ); + $payment_endpoint + ->expects( $this->once() ) + ->method( 'eligibility' ) + ->with( + [ + 'purchase_amount' => 24523, + 'queries' => [ 'installments_count' => 3 ], + 'locale' => apply_filters( 'alma_eligibility_user_locale', get_locale() ), + 'billing_address' => [ 'country' => 'FR' ], + 'shipping_address' => [ 'country' => 'UK' ], + ], + true + ) + ->willReturn( [ 'eligibility' => 'return ' ] ); + $client_mock->payments = $payment_endpoint; + + $cart_mock = $this->createMock( \WC_Cart::class ); + $customer_mock = $this->createMock( \WC_Customer::class ); + $customer_mock->method( 'get_billing_country' )->willReturn( 'FR' ); + $customer_mock->method( 'get_shipping_country' )->willReturn( 'UK' ); + + $cart_mock->method( 'get_total' )->willReturn( 245.23 ); + $cart_mock->method( 'get_customer' )->willReturn( $customer_mock ); + + $this->assertEquals( [ 'eligibility' => 'return ' ], $this->alma_client_service->get_eligibility( $client_mock, $cart_mock ) ); + } + + + /** + * @return void + * @dataProvider get_alma_client_data_provider + * @throws ApiClientException + */ + public function test_get_alma_client_with_config( $setting, $decrypted_api_key ) { + $this->option_proxy + ->method( 'get_option' ) + ->willReturn( $setting ); + + $this->encryptor_helper + ->expects( $this->once() ) + ->method( 'decrypt' ) + ->with( 'encrypted_api_key' ) + ->willReturn( $decrypted_api_key ); + + $this->assertInstanceOf( Client::class, $this->alma_client_service->get_alma_client() ); + } + + /** + * Get Alma Client data provider test/live mode + * + * @return array[] + */ + public function get_alma_client_data_provider() { + return [ + 'Test mode' => [ + 'setting' => [ + 'environment' => 'test', + 'test_api_key' => 'encrypted_api_key', + ], + 'decrypted_api_key' => 'test_api_key', + ], + 'Live mode' => [ + 'setting' => [ + 'environment' => 'live', + 'live_api_key' => 'encrypted_api_key', + ], + 'decrypted_api_key' => 'live_api_key', + ], + ]; + } + + /** + * Api Client exception data provider + * @return array[] + */ + public function api_client_exception_data_provider() { + return [ + 'Without Mode' => [ + 'setting' => [], + 'message' => 'No mode set', + ], + 'Without test Api Key' => [ + 'setting' => [ 'environment' => 'test' ], + 'message' => 'Test api key not set', + ], + 'Without live Api Key' => [ + 'setting' => [ 'environment' => 'live' ], + 'message' => 'Live api key not set', + ] + ]; + } + + private function get_setting_mock_array() { + return [ + "enabled" => "yes", + "payment_upon_trigger_enabled" => "no", + "payment_upon_trigger_event" => "completed", + "payment_upon_trigger_display_text" => "at_shipping", + "selected_fee_plan" => "general_6_0_0", + "enabled_general_3_0_0" => "yes", + "title_alma_in_page" => "Pay in installments", + "description_alma_in_page" => "Fast and secure payment by credit card", + "title_alma_in_page_pay_now" => "Pay by credit card", + "description_alma_in_page_pay_now" => "Fast and secured payments", + "title_alma_in_page_pay_later" => "Pay later", + "description_alma_in_page_pay_later" => "Fast and secure payment by credit card", + "title_alma_in_page_pnx_plus_4" => "Pay with financing", + "description_alma_in_page_pnx_plus_4" => "Fast and secure payment by credit card", + "title_alma" => "Pay in installments", + "description_alma" => "Fast and secure payment by credit card", + "title_alma_pay_now" => "Pay by credit card", + "description_alma_pay_now" => "Fast and secured payments", + "title_alma_pay_later" => "Pay later", + "description_alma_pay_later" => "Fast and secure payment by credit card", + "title_alma_pnx_plus_4" => "Pay with financing", + "description_alma_pnx_plus_4" => "Fast and secure payment by credit card", + "title_blocks_alma_in_page" => "Pay in installments", + "description_blocks_alma_in_page" => "Fast and secure payment by credit card", + "title_blocks_alma_in_page_pay_now" => "Pay by credit card", + "description_blocks_alma_in_page_pay_now" => "Fast and secured payments", + "title_blocks_alma_in_page_pay_later" => "Pay later", + "description_blocks_alma_in_page_pay_later" => "Fast and secure payment by credit card", + "title_blocks_alma" => "Pay in installments", + "description_blocks_alma" => "Fast and secure payment by credit card", + "title_blocks_alma_pay_now" => "Pay by credit card", + "description_blocks_alma_pay_now" => "Fast and secured payments", + "title_blocks_alma_pay_later" => "Pay later", + "description_blocks_alma_pay_later" => "Fast and secure payment by credit card", + "title_blocks_alma_pnx_plus_4" => "Pay with financing", + "description_blocks_alma_pnx_plus_4" => "Fast and secure payment by credit card", + "display_cart_eligibility" => "yes", + "display_product_eligibility" => "yes", + "variable_product_price_query_selector" => "form.variations_form div.woocommerce-variation-price span.woocommerce-Price-amount bdi", + "variable_product_sale_price_query_selector" => "form.variations_form div.woocommerce-variation-price ins span.woocommerce-Price-amount bdi", + "variable_product_check_variations_event" => "check_variations", + "excluded_products_list" => "", + "cart_not_eligible_message_gift_cards" => "Some products cannot be paid with monthly or deferred installments", + "live_api_key" => "", + "test_api_key" => "encrypted_api_key", + "environment" => "test", + "share_of_checkout_enabled" => "no", + "debug" => "yes", + "keys_validity" => "yes", + "display_in_page" => "no", + "use_blocks_template" => "yes", + "allowed_fee_plans" => "a:8:{...}", + "live_merchant_id" => null, + "test_merchant_id" => "merchant_11xYpTY1GTkww5uWFKFdOllK82S1r7j5v5", + "test_merchant_name" => "ECOM Inte Shop", + "min_amount_general_1_0_0" => 100, + "max_amount_general_1_0_0" => 200000, + "enabled_general_1_0_0" => "no", + "deferred_months_general_1_0_0" => 0, + "deferred_days_general_1_0_0" => 0, + "installments_count_general_1_0_0" => 1, + "min_amount_general_2_0_0" => 5000, + "max_amount_general_2_0_0" => 200000, + "enabled_general_2_0_0" => "no", + "deferred_months_general_2_0_0" => 0, + "deferred_days_general_2_0_0" => 0, + "installments_count_general_2_0_0" => 2, + "min_amount_general_3_0_0" => 5000, + "max_amount_general_3_0_0" => 200000, + "deferred_months_general_3_0_0" => 0, + "deferred_days_general_3_0_0" => 0, + "installments_count_general_3_0_0" => 3, + "min_amount_general_1_0_1" => 5000, + "max_amount_general_1_0_1" => 200000, + "enabled_general_1_0_1" => "no", + "deferred_months_general_1_0_1" => 1, + "deferred_days_general_1_0_1" => 0, + "installments_count_general_1_0_1" => 1, + "min_amount_general_1_15_0" => 5000, + "max_amount_general_1_15_0" => 200000, + "enabled_general_1_15_0" => "yes", + "deferred_months_general_1_15_0" => 0, + "deferred_days_general_1_15_0" => 15, + "installments_count_general_1_15_0" => 1, + "min_amount_general_4_0_0" => 5000, + "max_amount_general_4_0_0" => 200000, + "enabled_general_4_0_0" => "no", + "deferred_months_general_4_0_0" => 0, + "deferred_days_general_4_0_0" => 0, + "installments_count_general_4_0_0" => 4, + "min_amount_general_6_0_0" => 40000, + "max_amount_general_6_0_0" => 200000, + "enabled_general_6_0_0" => "yes", + "deferred_months_general_6_0_0" => 0, + "deferred_days_general_6_0_0" => 0, + "installments_count_general_6_0_0" => 6, + "min_amount_general_10_0_0" => 5000, + "max_amount_general_10_0_0" => 200000, + "enabled_general_10_0_0" => "no", + "deferred_months_general_10_0_0" => 0, + "deferred_days_general_10_0_0" => 0, + "installments_count_general_10_0_0" => 10, + ]; + } +} \ No newline at end of file From 6d50e5eb8c76aecdb11c86f7c7d3de9bc27d1303 Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Thu, 26 Dec 2024 15:48:15 +0100 Subject: [PATCH 02/15] fix blocks data service --- src/includes/Blocks/BlocksDataService.php | 63 ++++++++++++++++--- .../Gateways/Standard/PayLaterGateway.php | 2 + .../Standard/PayMoreThanFourGateway.php | 2 + .../Gateways/Standard/PayNowGateway.php | 2 + .../Gateways/Standard/StandardGateway.php | 2 + src/includes/WcProxy/FunctionsProxy.php | 11 ++++ src/tests/Blocks/BlocksDataServiceTest.php | 31 +++++++++ 7 files changed, 104 insertions(+), 9 deletions(-) diff --git a/src/includes/Blocks/BlocksDataService.php b/src/includes/Blocks/BlocksDataService.php index 4bf405fa..f78125a5 100644 --- a/src/includes/Blocks/BlocksDataService.php +++ b/src/includes/Blocks/BlocksDataService.php @@ -36,16 +36,29 @@ class BlocksDataService { */ private $function_proxy; + /** + * Block data service - Webhook for blocks data + * + * @param $alma_client_service + * @param $function_proxy + * @param $logger + */ public function __construct( $alma_client_service = null, $function_proxy = null, $logger = null ) { - $this->init_alma_client_service( $alma_client_service ); - $this->init_function_proxy( $function_proxy ); - $this->init_alma_logger( $logger ); + $this->alma_client_service = $this->init_alma_client_service( $alma_client_service ); + $this->function_proxy = $this->init_function_proxy( $function_proxy ); + $this->logger = $this->init_alma_logger( $logger ); } + /** + * Init webhook alma_blocks_data + * No test need a proxy to test + * + * @return void + */ public function init_hooks() { add_action( ToolsHelper::action_for_webhook( AlmaBlock::WEBHOOK_PATH ), @@ -56,6 +69,11 @@ public function init_hooks() { ); } + /** + * Send HTTP Response to AJAX call for eligibility in checkout page + * + * @return void + */ public function get_blocks_data() { try { $almaClient = $this->alma_client_service->get_alma_client(); @@ -65,6 +83,9 @@ public function get_blocks_data() { $this->function_proxy->send_http_error_response( [ 'success' => false, ], 500 ); + + // wp_send_json_error make die but return is used on test + return; } $response = [ @@ -76,6 +97,13 @@ public function get_blocks_data() { $this->function_proxy->send_http_response( $response ); } + /** + * Format eligibility with gateway for frontend blocks + * + * @param $eligibilities + * + * @return array|array[] + */ private function format_eligibility_for_blocks( $eligibilities ) { $gateways = [ PayNowGateway::GATEWAY_ID => [], @@ -110,6 +138,11 @@ private function format_eligibility_for_blocks( $eligibilities ) { return $gateways; } + /** + * @param Eligibility $eligibility + * + * @return array + */ private function format_plan_content_for_blocks( $eligibility ) { return [ 'paymentPlan' => $eligibility->getPaymentPlan(), @@ -122,32 +155,44 @@ private function format_plan_content_for_blocks( $eligibility ) { * * @param AlmaClientService|null $alma_client_service * - * @return void + * @return AlmaClientService */ private function init_alma_client_service( $alma_client_service ) { if ( ! isset( $alma_client_service ) ) { $alma_client_service = new AlmaClientService(); } - $this->alma_client_service = $alma_client_service; + + return $alma_client_service; } /** - * @param $logger + * Init Alma Logger * - * @return void + * @param AlmaLogger|null $logger + * + * @return AlmaLogger */ private function init_alma_logger( $logger ) { if ( ! isset( $logger ) ) { $logger = new AlmaLogger(); } - $this->logger = $logger; + + return $logger; } + /** + * Init function proxy + * + * @param FunctionsProxy|null $function_proxy + * + * @return FunctionsProxy + */ private function init_function_proxy( $function_proxy ) { if ( ! isset( $function_proxy ) ) { $function_proxy = new FunctionsProxy(); } - $this->function_proxy = $function_proxy; + + return $function_proxy; } } \ No newline at end of file diff --git a/src/includes/Gateways/Standard/PayLaterGateway.php b/src/includes/Gateways/Standard/PayLaterGateway.php index e1e6dbb6..4e8c5b2c 100644 --- a/src/includes/Gateways/Standard/PayLaterGateway.php +++ b/src/includes/Gateways/Standard/PayLaterGateway.php @@ -22,6 +22,8 @@ */ class PayLaterGateway extends StandardGateway { + const GATEWAY_ID = 'alma_pay_later'; + /** * Get the gateway id. * diff --git a/src/includes/Gateways/Standard/PayMoreThanFourGateway.php b/src/includes/Gateways/Standard/PayMoreThanFourGateway.php index dd4c45fa..f7606082 100644 --- a/src/includes/Gateways/Standard/PayMoreThanFourGateway.php +++ b/src/includes/Gateways/Standard/PayMoreThanFourGateway.php @@ -22,6 +22,8 @@ */ class PayMoreThanFourGateway extends StandardGateway { + const GATEWAY_ID = 'alma_pnx_plus_4'; + /** * Get the gateway id. * diff --git a/src/includes/Gateways/Standard/PayNowGateway.php b/src/includes/Gateways/Standard/PayNowGateway.php index 431c297f..c44b4920 100644 --- a/src/includes/Gateways/Standard/PayNowGateway.php +++ b/src/includes/Gateways/Standard/PayNowGateway.php @@ -22,6 +22,8 @@ */ class PayNowGateway extends StandardGateway { + const GATEWAY_ID = 'alma_pay_now'; + /** * Get the gateway id. * diff --git a/src/includes/Gateways/Standard/StandardGateway.php b/src/includes/Gateways/Standard/StandardGateway.php index 882f6f33..86df382a 100644 --- a/src/includes/Gateways/Standard/StandardGateway.php +++ b/src/includes/Gateways/Standard/StandardGateway.php @@ -23,6 +23,8 @@ */ class StandardGateway extends AlmaPaymentGateway { + const GATEWAY_ID = 'alma'; + /** * Get the gateway id. * diff --git a/src/includes/WcProxy/FunctionsProxy.php b/src/includes/WcProxy/FunctionsProxy.php index 9b36dde0..4e2b8b0b 100644 --- a/src/includes/WcProxy/FunctionsProxy.php +++ b/src/includes/WcProxy/FunctionsProxy.php @@ -24,4 +24,15 @@ public function send_http_response( $response, $status_code = null, $flags = 0 ) wp_send_json( $response, $status_code, $flags ); } + /** + * Send HTTP error response. + * + * @param array $response Response data. + * @param int|null $status_code HTTP status code. + * @param int $flags Response flags. + */ + public function send_http_error_response( $response, $status_code = null, $flags = 0 ) { + wp_send_json_error( $response, $status_code, $flags ); + } + } diff --git a/src/tests/Blocks/BlocksDataServiceTest.php b/src/tests/Blocks/BlocksDataServiceTest.php index 849b05a2..1e2009fb 100644 --- a/src/tests/Blocks/BlocksDataServiceTest.php +++ b/src/tests/Blocks/BlocksDataServiceTest.php @@ -2,9 +2,11 @@ namespace Alma\Woocommerce\Tests\Blocks; +use Alma\API\Client; use Alma\API\Endpoints\Results\Eligibility; use Alma\Woocommerce\AlmaLogger; use Alma\Woocommerce\Blocks\BlocksDataService; +use Alma\Woocommerce\Exceptions\ApiClientException; use Alma\Woocommerce\Services\AlmaClientService; use Alma\Woocommerce\WcProxy\FunctionsProxy; use WP_UnitTestCase; @@ -27,10 +29,39 @@ public function set_up() { ); } + public function test_get_blocks_with_error_in_client() { + $this->alma_client_service + ->expects( $this->once() ) + ->method( 'get_alma_client' ) + ->willThrowException( new ApiClientException( 'Api key not set' ) ); + $this->function_proxy + ->expects( $this->once() ) + ->method( 'send_http_error_response' ) + ->with( + [ + 'success' => false, + ], 500 + ); + $this->assertNull( $this->blocks_data_service->get_blocks_data() ); + } + + /** + * Test blocks data return without error + * + * @return void + */ public function test_get_blocks_data() { + $client_mock = $this->createMock( Client::class ); + $this->alma_client_service + ->expects( $this->once() ) + ->method( 'get_alma_client' ) + ->willReturn( $client_mock ); $this->alma_client_service + ->expects( $this->once() ) ->method( 'get_eligibility' ) + ->with( WC()->cart, $client_mock ) ->willReturn( $this->eligibility_array() ); + $this->function_proxy ->expects( $this->once() ) ->method( 'send_http_response' ) From 2d71074b9860bc358100f31b9916c1d5582e2d4a Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Thu, 26 Dec 2024 15:57:07 +0100 Subject: [PATCH 03/15] feat: add reduce store and webhook url --- src/includes/Blocks/AlmaBlock.php | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/includes/Blocks/AlmaBlock.php b/src/includes/Blocks/AlmaBlock.php index 3a715844..c50b3308 100644 --- a/src/includes/Blocks/AlmaBlock.php +++ b/src/includes/Blocks/AlmaBlock.php @@ -11,10 +11,12 @@ namespace Alma\Woocommerce\Blocks; +use Alma\Woocommerce\AlmaLogger; use Alma\Woocommerce\AlmaSettings; use Alma\Woocommerce\Builders\Helpers\CartHelperBuilder; use Alma\Woocommerce\Builders\Helpers\GatewayHelperBuilder; use Alma\Woocommerce\Builders\Helpers\PlanHelperBuilder; +use Alma\Woocommerce\Builders\Helpers\ToolsHelperBuilder; use Alma\Woocommerce\Exceptions\AlmaException; use Alma\Woocommerce\Gateways\Standard\StandardGateway; use Alma\Woocommerce\Helpers\AssetsHelper; @@ -23,6 +25,7 @@ use Alma\Woocommerce\Helpers\ConstantsHelper; use Alma\Woocommerce\Helpers\GatewayHelper; use Alma\Woocommerce\Helpers\PlanHelper; +use Alma\Woocommerce\Helpers\ToolsHelper; use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType; if ( ! defined( 'ABSPATH' ) ) { @@ -75,6 +78,14 @@ class AlmaBlock extends AbstractPaymentMethodType { * @var StandardGateway */ protected $gateway; + /** + * @var AlmaLogger + */ + private $logger; + /** + * @var ToolsHelper + */ + private $tools_helper; /** * Initialize. @@ -91,6 +102,9 @@ public function initialize() { $this->cart_helper = $cart_helper_builder->get_instance(); $alma_plan_builder = new PlanHelperBuilder(); $this->alma_plan_helper = $alma_plan_builder->get_instance(); + $this->logger = new AlmaLogger(); + $tools_helper_builder = new ToolsHelperBuilder(); + $this->tools_helper = $tools_helper_builder->get_instance(); } /** @@ -135,6 +149,24 @@ public function get_payment_method_script_handles() { ALMA_VERSION, true ); + // Passer la base URL au JavaScript + wp_localize_script( 'alma-blocks-integration', 'BlocksData', [ + 'url' => $this->tools_helper->url_for_webhook( BlocksDataService::WEBHOOK_PATH ), + ] ); + + + wp_enqueue_script( + 'alma-store', + AssetsHelper::get_asset_build_url( 'alma-store.js' ), + array( + 'wp-data', + 'wp-element', + 'wc-blocks' + ), + ALMA_VERSION, + true + ); + if ( function_exists( 'wp_set_script_translations' ) ) { wp_set_script_translations( 'alma-blocks-integration' ); From b946c72b73912c267aabaee1898a13c05e6bdb8b Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Thu, 26 Dec 2024 15:57:32 +0100 Subject: [PATCH 04/15] fix: alma client service doc --- src/includes/Services/AlmaClientService.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/includes/Services/AlmaClientService.php b/src/includes/Services/AlmaClientService.php index e4d329c8..4b8f4575 100644 --- a/src/includes/Services/AlmaClientService.php +++ b/src/includes/Services/AlmaClientService.php @@ -122,6 +122,8 @@ public function get_eligibility( $alma_client, $cart ) { } /** + * Generate Payload for eligibility depending on cart + * * @param \WC_Cart $cart * * @return array From 993a016bd8871e9f4d34c052e27ea4ff122c7658 Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Thu, 26 Dec 2024 15:59:15 +0100 Subject: [PATCH 05/15] fix: add webhook url in blocks data service --- src/includes/Blocks/BlocksDataService.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/includes/Blocks/BlocksDataService.php b/src/includes/Blocks/BlocksDataService.php index f78125a5..0bbaad46 100644 --- a/src/includes/Blocks/BlocksDataService.php +++ b/src/includes/Blocks/BlocksDataService.php @@ -23,6 +23,9 @@ use Alma\Woocommerce\WcProxy\FunctionsProxy; class BlocksDataService { + + const WEBHOOK_PATH = 'alma_blocks_data'; + /** * @var AlmaClientService */ @@ -61,7 +64,7 @@ public function __construct( */ public function init_hooks() { add_action( - ToolsHelper::action_for_webhook( AlmaBlock::WEBHOOK_PATH ), + ToolsHelper::action_for_webhook( self::WEBHOOK_PATH ), array( $this, 'get_blocks_data', From e3b8628a2e16bb701d3feb24d26bc59484da1e75 Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Thu, 26 Dec 2024 16:04:45 +0100 Subject: [PATCH 06/15] fix: add webhook url in blocks data service --- src/includes/Blocks/BlocksDataService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/includes/Blocks/BlocksDataService.php b/src/includes/Blocks/BlocksDataService.php index 0bbaad46..cd75134e 100644 --- a/src/includes/Blocks/BlocksDataService.php +++ b/src/includes/Blocks/BlocksDataService.php @@ -80,7 +80,7 @@ public function init_hooks() { public function get_blocks_data() { try { $almaClient = $this->alma_client_service->get_alma_client(); - $eligibilities = $this->alma_client_service->get_eligibility( WC()->cart, $almaClient ); + $eligibilities = $this->alma_client_service->get_eligibility( $almaClient, WC()->cart ); } catch ( ApiClientException $e ) { $this->logger->info( 'Impossible to set Alma client: ' . $e->getMessage() ); $this->function_proxy->send_http_error_response( [ From 5b5ac39cd9de96cd5e64cf61fdda4690eb2434d4 Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Thu, 26 Dec 2024 16:06:03 +0100 Subject: [PATCH 07/15] fix: cart_total return type --- src/includes/Blocks/BlocksDataService.php | 2 +- src/tests/Blocks/BlocksDataServiceTest.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/includes/Blocks/BlocksDataService.php b/src/includes/Blocks/BlocksDataService.php index cd75134e..483ea421 100644 --- a/src/includes/Blocks/BlocksDataService.php +++ b/src/includes/Blocks/BlocksDataService.php @@ -94,7 +94,7 @@ public function get_blocks_data() { $response = [ 'success' => true, 'eligibility' => $this->format_eligibility_for_blocks( $eligibilities ), - 'cart_total' => [ 'cart_total' => (float) WC()->cart->get_total( '' ) ], + 'cart_total' => (float) WC()->cart->get_total( '' ), ]; // Send JSON response $this->function_proxy->send_http_response( $response ); diff --git a/src/tests/Blocks/BlocksDataServiceTest.php b/src/tests/Blocks/BlocksDataServiceTest.php index 1e2009fb..7d057659 100644 --- a/src/tests/Blocks/BlocksDataServiceTest.php +++ b/src/tests/Blocks/BlocksDataServiceTest.php @@ -59,7 +59,7 @@ public function test_get_blocks_data() { $this->alma_client_service ->expects( $this->once() ) ->method( 'get_eligibility' ) - ->with( WC()->cart, $client_mock ) + ->with( $client_mock, WC()->cart ) ->willReturn( $this->eligibility_array() ); $this->function_proxy @@ -126,7 +126,7 @@ private function response_data() { ], 'alma_pnx_plus_4' => [] ], - 'cart_total' => [ 'cart_total' => (float) WC()->cart->get_total( '' ) ] + 'cart_total' => (float) WC()->cart->get_total( '' ) ]; } From 435df0a343e6cd658bbeb14260045f223cef5592 Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Thu, 26 Dec 2024 16:10:41 +0100 Subject: [PATCH 08/15] fix: init block data webhook in plugin --- src/includes/AlmaPlugin.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/includes/AlmaPlugin.php b/src/includes/AlmaPlugin.php index 34c91b67..4f41f62a 100644 --- a/src/includes/AlmaPlugin.php +++ b/src/includes/AlmaPlugin.php @@ -14,6 +14,7 @@ } use Alma\Woocommerce\Admin\Services\NoticesService; +use Alma\Woocommerce\Blocks\BlocksDataService; use Alma\Woocommerce\Exceptions\RequirementsException; use Alma\Woocommerce\Exceptions\VersionDeprecated; use Alma\Woocommerce\Factories\VersionFactory; @@ -74,6 +75,10 @@ class AlmaPlugin { * @var VersionFactory */ protected $version_factory; + /** + * @var BlocksDataService + */ + private $blocks_data_service; /** * Protected constructor to prevent creating a new instance of the @@ -86,6 +91,8 @@ protected function __construct() { $this->plugin_helper = new PluginHelper(); $this->version_factory = new VersionFactory(); + $this->blocks_data_service = new BlocksDataService(); + try { $migration_success = $this->migration_helper->update(); } catch ( VersionDeprecated $e ) { @@ -129,6 +136,7 @@ public function init() { $this->plugin_helper->add_hooks(); $this->plugin_helper->add_shortcodes_and_scripts(); $this->plugin_helper->add_actions(); + $this->blocks_data_service->init_hooks(); } From eac9707b8fbbd7ef561a6959af8a9c12d706fa3c Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Thu, 26 Dec 2024 16:11:12 +0100 Subject: [PATCH 09/15] feat: add alma-store in compil --- webpack.config.js | 1 + 1 file changed, 1 insertion(+) diff --git a/webpack.config.js b/webpack.config.js index b4b1a933..46db9f47 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -5,6 +5,7 @@ const config = { ...defaultConfig, entry: { 'alma-checkout-blocks': path.resolve(process.cwd(), 'src', 'assets', 'js', 'alma-checkout-blocks.js'), + 'alma-store': path.resolve(process.cwd(), 'src', 'assets', 'js', 'stores', 'alma-store.js'), // 'alma-checkout-blocks-pay-later': path.resolve(process.cwd(), 'src', 'assets', 'js', 'alma-checkout-blocks-pay-later.js'), // 'alma-checkout-blocks-pay-more-than-four': path.resolve(process.cwd(), 'src', 'assets', 'js', 'alma-checkout-blocks-pay-more-than-four.js'), }, From 75532433c57bb8281abbaa388899a02b14e30dbd Mon Sep 17 00:00:00 2001 From: Francois-Gomis Date: Fri, 27 Dec 2024 16:38:45 +0100 Subject: [PATCH 10/15] feat: Fix all Blocks in page and credit --- src/assets/js/alma-checkout-blocks.js | 262 +++++++----------- src/assets/js/components/DisplayAlmaBlocks.js | 72 +++++ .../js/components/DisplayAlmaInPageBlocks.js | 78 ++++++ src/assets/js/components/Label.js | 14 + .../js/components/alma-blocks-component.tsx | 188 ++++++------- src/assets/js/hooks/fetchAlmaEligibility.js | 21 ++ src/assets/js/stores/alma-store.js | 16 +- src/build/alma-checkout-blocks.asset.php | 2 +- src/build/alma-checkout-blocks.js | 48 ++-- src/build/alma-store.asset.php | 1 + src/build/alma-store.js | 1 + src/build/style-alma-checkout-blocks.css | 2 +- src/includes/Blocks/AlmaBlock.php | 40 +-- src/includes/Blocks/BlocksDataService.php | 43 ++- .../Blocks/Inpage/PayMoreThanFourBlock.php | 55 ++++ .../Gateways/Inpage/InPageGateway.php | 1 + .../Gateways/Inpage/PayLaterGateway.php | 2 + .../Inpage/PayMoreThanFourGateway.php | 1 + .../Gateways/Inpage/PayNowGateway.php | 2 + src/includes/Helpers/PluginHelper.php | 2 + src/includes/Helpers/SettingsHelper.php | 2 + src/includes/Services/AlmaClientService.php | 15 + src/tests/Blocks/BlocksDataServiceTest.php | 116 +++++++- src/tests/Helpers/SettingsHelperTest.php | 2 + 24 files changed, 660 insertions(+), 326 deletions(-) create mode 100644 src/assets/js/components/DisplayAlmaBlocks.js create mode 100644 src/assets/js/components/DisplayAlmaInPageBlocks.js create mode 100644 src/assets/js/components/Label.js create mode 100644 src/assets/js/hooks/fetchAlmaEligibility.js create mode 100644 src/build/alma-store.asset.php create mode 100644 src/build/alma-store.js create mode 100644 src/includes/Blocks/Inpage/PayMoreThanFourBlock.php diff --git a/src/assets/js/alma-checkout-blocks.js b/src/assets/js/alma-checkout-blocks.js index fb8c1495..36ebf938 100644 --- a/src/assets/js/alma-checkout-blocks.js +++ b/src/assets/js/alma-checkout-blocks.js @@ -10,173 +10,108 @@ // phpcs:ignoreFile import {useEffect, useState} from '@wordpress/element'; -import {select} from '@wordpress/data'; -import {Logo} from '@alma/react-components'; -import {AlmaBlocks} from "./components/alma-blocks-component.tsx"; +import {select, useSelect} from '@wordpress/data'; +import {fetchAlmaEligibility} from "./hooks/fetchAlmaEligibility"; +import {Label} from "./components/Label"; +import {DisplayAlmaBlocks} from "./components/DisplayAlmaBlocks"; +import {DisplayAlmaInPageBlocks} from "./components/DisplayAlmaInPageBlocks"; import '../css/alma-checkout-blocks.css'; (function ($) { - const gateways = ['alma_pay_now', 'alma_in_page_pay_now', 'alma', 'alma_in_page', 'alma_pay_later', 'alma_in_page_pay_later', 'alma_pnx_plus_4']; + const store_key = 'alma/alma-store' var inPage = undefined; - var propsData = null; - var globalSelectedFeePlan = null; - - $.each(gateways, function (index, gateway) { - const settings = window.wc.wcSettings.getSetting(`${gateway}_data`, null); + const {CART_STORE_KEY} = window.wc.wcBlocksData + + const CartObserver = () => { + // Subscribe to the cart total + const {cartTotal} = useSelect((select) => ({ + cartTotal: select(CART_STORE_KEY).getCartTotals() + }), []); + + // Subscribe to the eligibility + const {eligibility} = useSelect( + (select) => ({ + eligibility: select(store_key).getAlmaEligibility() + }), [] + ); - if (!settings) { - return - } + // Use the cart total to fetch the new eligibility + useEffect(() => { + // BlockData is a global variable defined in the PHP file with the wp_localize_script function + fetchAlmaEligibility(store_key, BlocksData.url) + }, [cartTotal]); + + // Register the payment gateway blocks + useEffect(() => { + // For each gateway in eligibility result, we register a block + for (const gateway in eligibility) { + const settings = window.wc.wcSettings.getSetting(`${gateway}_data`, null) + const is_in_page = settings.is_in_page + const blockContent = getContentBlock(is_in_page, settings, cartTotal, gateway) + + const Block_Gateway_Alma = { + name: settings.gateway_name, + label: ( +