Merge trunk

This commit is contained in:
Emili Castells Guasch 2025-01-27 11:06:56 +01:00
commit bef1c92f3f
165 changed files with 3796 additions and 3028 deletions

View file

@ -0,0 +1,40 @@
/**
* Settings action types
*
* Defines the constants used for dispatching actions in the settings store.
* Each constant represents a unique action type that can be handled by reducers.
*
* @file
*/
export default {
/**
* Represents setting transient (temporary) state data.
* These values are not persisted and will reset on page reload.
*/
SET_TRANSIENT: 'ppcp/settings/SET_TRANSIENT',
/**
* Represents setting persistent state data.
* These values are meant to be saved to the server and persist between page loads.
*/
SET_PERSISTENT: 'ppcp/settings/SET_PERSISTENT',
/**
* Resets the store state to its initial values.
* Used when needing to clear all settings data.
*/
RESET: 'ppcp/settings/RESET',
/**
* Initializes the store with data, typically used during store initialization
* to set up the initial state with data from the server.
*/
HYDRATE: 'ppcp/settings/HYDRATE',
/**
* Triggers the persistence of store data to the server.
* Used when changes need to be saved to the backend.
*/
DO_PERSIST_DATA: 'ppcp/settings/DO_PERSIST_DATA',
};

View file

@ -0,0 +1,81 @@
/**
* Action Creators: Define functions to create action objects.
*
* These functions update state or trigger side effects (e.g., async operations).
* Actions are categorized as Transient, Persistent, or Side effect.
*
* @file
*/
import { select } from '@wordpress/data';
import ACTION_TYPES from './action-types';
import { STORE_NAME } from './constants';
/**
* @typedef {Object} Action An action object that is handled by a reducer or control.
* @property {string} type - The action type.
* @property {Object?} payload - Optional payload for the action.
*/
/**
* Special. Resets all values in the store to initial defaults.
*
* @return {Action} The action.
*/
export const reset = () => ( {
type: ACTION_TYPES.RESET,
} );
/**
* Persistent. Sets the full store details during app initialization.
*
* @param {Object} payload Initial store data
* @return {Action} The action.
*/
export const hydrate = ( payload ) => ( {
type: ACTION_TYPES.HYDRATE,
payload,
} );
/**
* Generic transient-data updater.
*
* @param {string} prop Name of the property to update.
* @param {any} value The new value of the property.
* @return {Action} The action.
*/
export const setTransient = ( prop, value ) => ( {
type: ACTION_TYPES.SET_TRANSIENT,
payload: { [ prop ]: value },
} );
/**
* Generic persistent-data updater.
*
* @param {string} prop Name of the property to update.
* @param {any} value The new value of the property.
* @return {Action} The action.
*/
export const setPersistent = ( prop, value ) => ( {
type: ACTION_TYPES.SET_PERSISTENT,
payload: { [ prop ]: value },
} );
/**
* Transient. Marks the store as "ready", i.e., fully initialized.
*
* @param {boolean} isReady Whether the store is ready
* @return {Action} The action.
*/
export const setIsReady = ( isReady ) => setTransient( 'isReady', isReady );
/**
* Side effect. Triggers the persistence of store data to the server.
* Yields an action with the current persistent data to be saved.
*
* @return {Action} The action.
*/
export const persist = function* () {
const data = yield select( STORE_NAME ).persistentData();
yield { type: ACTION_TYPES.DO_PERSIST_DATA, data };
};

View file

@ -1,178 +0,0 @@
import { __, sprintf } from '@wordpress/i18n';
import { InputSettingsBlock } from '../../Components/ReusableComponents/SettingsBlocks';
import { Button } from '@wordpress/components';
/**
* Generates options for the environment mode settings.
*
* @param {Object} config - Configuration for the mode.
* @param {Object} settings - Current settings.
* @param {Function} updateFormValue - Callback to update settings.
* @return {Array} Options array.
*/
const generateOptions = ( config, settings, updateFormValue ) => [
{
id: `${ config.mode }_mode`,
value: `${ config.mode }_mode`,
label: config.labelTitle,
description: config.labelDescription,
additionalContent: (
<Button
variant="primary"
onClick={ () => {
updateFormValue( `${ config.mode }Connected`, true );
if ( config.mode === 'production' ) {
global.ppcpSettings.startOnboarding();
}
} }
>
{ config.buttonText }
</Button>
),
},
{
id: 'manual_connect',
value: 'manual_connect',
label: __( 'Manual Connect', 'woocommerce-paypal-payments' ),
description: sprintf(
__(
'For advanced users: Connect a custom PayPal REST app for full control over your integration. For more information on creating a PayPal REST application, <a target="_blank" href="%s">click here</a>.',
'woocommerce-paypal-payments'
),
'#'
),
additionalContent: (
<>
<InputSettingsBlock
title={ config.clientIdTitle }
actionProps={ {
value: settings[ `${ config.mode }ClientId` ],
callback: updateFormValue,
key: `${ config.mode }ClientId`,
placeholder: __(
'Enter Client ID',
'woocommerce-paypal-payments'
),
} }
/>
<InputSettingsBlock
title={ config.secretKeyTitle }
actionProps={ {
value: settings[ `${ config.mode }SecretKey` ],
callback: updateFormValue,
key: `${ config.mode }SecretKey`,
placeholder: __(
'Enter Secret Key',
'woocommerce-paypal-payments'
),
} }
/>
<Button
variant="primary"
onClick={ () =>
updateFormValue(
`${ config.mode }ManuallyConnected`,
true
)
}
>
{ __( 'Connect Account', 'woocommerce-paypal-payments' ) }
</Button>
</>
),
},
];
/**
* Generates data for a given mode (sandbox or production).
*
* @param {Object} config - Configuration for the mode.
* @param {Object} settings - Current settings.
* @param {Function} updateFormValue - Callback to update settings.
* @return {Object} Mode configuration.
*/
const generateModeData = ( config, settings, updateFormValue ) => ( {
title: config.title,
description: config.description,
connectTitle: __(
`Connect ${ config.label } Account`,
'woocommerce-paypal-payments'
),
connectDescription: config.connectDescription,
options: generateOptions( config, settings, updateFormValue ),
} );
export const sandboxData = ( { settings = {}, updateFormValue = () => {} } ) =>
generateModeData(
{
mode: 'sandbox',
label: 'Sandbox',
title: __( 'Sandbox', 'woocommerce-paypal-payments' ),
description: __(
"Test your site in PayPal's Sandbox environment.",
'woocommerce-paypal-payments'
),
connectDescription: __(
'Connect a PayPal Sandbox account in order to test your website. Transactions made will not result in actual money movement. Do not fulfil orders completed in Sandbox mode.',
'woocommerce-paypal-payments'
),
labelTitle: __( 'Sandbox Mode', 'woocommerce-paypal-payments' ),
labelDescription: __(
'Activate Sandbox mode to safely test PayPal with sample data. Once your store is ready to go live, you can easily switch to your production account.',
'woocommerce-paypal-payments'
),
buttonText: __(
'Connect Sandbox Account',
'woocommerce-paypal-payments'
),
clientIdTitle: __(
'Sandbox Client ID',
'woocommerce-paypal-payments'
),
secretKeyTitle: __(
'Sandbox Secret Key',
'woocommerce-paypal-payments'
),
},
settings,
updateFormValue
);
export const productionData = ( {
settings = {},
updateFormValue = () => {},
} ) =>
generateModeData(
{
mode: 'production',
label: 'Live',
title: __( 'Live Payments', 'woocommerce-paypal-payments' ),
description: __(
'Your site is currently configured in Sandbox mode to test payments. When you are ready, launch your site and receive live payments via PayPal.',
'woocommerce-paypal-payments'
),
connectDescription: __(
'Connect a live PayPal account to launch your site and receive live payments via PayPal. PayPal will guide you through the setup process.',
'woocommerce-paypal-payments'
),
labelTitle: __( 'Production Mode', 'woocommerce-paypal-payments' ),
labelDescription: __(
'Activate Production mode to connect your live account and receive live payments via PayPal. Stay connected in Sandbox mode to continue testing payments before going live.',
'woocommerce-paypal-payments'
),
buttonText: __(
'Set up and connect live PayPal Account',
'woocommerce-paypal-payments'
),
clientIdTitle: __(
'Live Account Client ID',
'woocommerce-paypal-payments'
),
secretKeyTitle: __(
'Live Account Secret Key',
'woocommerce-paypal-payments'
),
},
settings,
updateFormValue
);

View file

@ -0,0 +1,28 @@
/**
* Name of the Redux store module.
*
* Used by: Reducer, Selector, Index
*
* @type {string}
*/
export const STORE_NAME = 'wc/paypal/settings';
/**
* REST path to hydrate data of this module by loading data from the WP DB.
*
* Used by: Resolvers
* See: SettingsRestEndpoint.php
*
* @type {string}
*/
export const REST_HYDRATE_PATH = '/wc/v3/wc_paypal/settings';
/**
* REST path to persist data of this module to the WP DB.
*
* Used by: Controls
* See: SettingsRestEndpoint.php
*
* @type {string}
*/
export const REST_PERSIST_PATH = '/wc/v3/wc_paypal/settings';

View file

@ -0,0 +1,34 @@
/**
* Controls: Implement side effects, typically asynchronous operations.
*
* Controls use ACTION_TYPES keys as identifiers.
* They are triggered by corresponding actions and handle external interactions.
*
* @file
*/
import apiFetch from '@wordpress/api-fetch';
import { REST_PERSIST_PATH } from './constants';
import ACTION_TYPES from './action-types';
/**
* Control handlers for settings store actions.
* Each handler maps to an ACTION_TYPE and performs the corresponding async operation.
*/
export const controls = {
/**
* Persists settings data to the server via REST API.
* Triggered by the DO_PERSIST_DATA action to save settings changes.
*
* @param {Object} action The action object
* @param {Object} action.data The settings data to persist
* @return {Promise<Object>} The API response
*/
async [ ACTION_TYPES.DO_PERSIST_DATA ]( { data } ) {
return await apiFetch( {
path: REST_PERSIST_PATH,
method: 'POST',
data,
} );
},
};

View file

@ -0,0 +1,141 @@
/**
* Hooks: Provide the main API for components to interact with the store.
*
* These encapsulate store interactions, offering a consistent interface.
* Hooks simplify data access and manipulation for components.
*
* @file
*/
import { useDispatch } from '@wordpress/data';
import { STORE_NAME } from './constants';
import { createHooksForStore } from '../utils';
const useHooks = () => {
const { useTransient, usePersistent } = createHooksForStore( STORE_NAME );
const { persist } = useDispatch( STORE_NAME );
// Read-only flags and derived state.
const [ isReady ] = useTransient( 'isReady' );
// Persistent accessors.
const [ invoicePrefix, setInvoicePrefix ] =
usePersistent( 'invoicePrefix' );
const [ authorizeOnly, setAuthorizeOnly ] =
usePersistent( 'authorizeOnly' );
const [ captureVirtualOnlyOrders, setCaptureVirtualOnlyOrders ] =
usePersistent( 'captureVirtualOnlyOrders' );
const [ savePaypalAndVenmo, setSavePaypalAndVenmo ] =
usePersistent( 'savePaypalAndVenmo' );
const [ saveCardDetails, setSaveCardDetails ] =
usePersistent( 'saveCardDetails' );
const [ payNowExperience, setPayNowExperience ] =
usePersistent( 'payNowExperience' );
const [ logging, setLogging ] = usePersistent( 'logging' );
const [ subtotalAdjustment, setSubtotalAdjustment ] =
usePersistent( 'subtotalAdjustment' );
const [ brandName, setBrandName ] = usePersistent( 'brandName' );
const [ softDescriptor, setSoftDescriptor ] =
usePersistent( 'softDescriptor' );
const [ landingPage, setLandingPage ] = usePersistent( 'landingPage' );
const [ buttonLanguage, setButtonLanguage ] =
usePersistent( 'buttonLanguage' );
const [ disabledCards, setDisabledCards ] =
usePersistent( 'disabledCards' );
return {
persist,
isReady,
invoicePrefix,
setInvoicePrefix,
authorizeOnly,
setAuthorizeOnly,
captureVirtualOnlyOrders,
setCaptureVirtualOnlyOrders,
savePaypalAndVenmo,
setSavePaypalAndVenmo,
saveCardDetails,
setSaveCardDetails,
payNowExperience,
setPayNowExperience,
logging,
setLogging,
subtotalAdjustment,
setSubtotalAdjustment,
brandName,
setBrandName,
softDescriptor,
setSoftDescriptor,
landingPage,
setLandingPage,
buttonLanguage,
setButtonLanguage,
disabledCards,
setDisabledCards,
};
};
export const useStore = () => {
const { persist, isReady } = useHooks();
return { persist, isReady };
};
export const useSettings = () => {
const {
invoicePrefix,
setInvoicePrefix,
authorizeOnly,
setAuthorizeOnly,
captureVirtualOnlyOrders,
setCaptureVirtualOnlyOrders,
savePaypalAndVenmo,
setSavePaypalAndVenmo,
saveCardDetails,
setSaveCardDetails,
payNowExperience,
setPayNowExperience,
logging,
setLogging,
subtotalAdjustment,
setSubtotalAdjustment,
brandName,
setBrandName,
softDescriptor,
setSoftDescriptor,
landingPage,
setLandingPage,
buttonLanguage,
setButtonLanguage,
disabledCards,
setDisabledCards,
} = useHooks();
return {
invoicePrefix,
setInvoicePrefix,
authorizeOnly,
setAuthorizeOnly,
captureVirtualOnlyOrders,
setCaptureVirtualOnlyOrders,
savePaypalAndVenmo,
setSavePaypalAndVenmo,
saveCardDetails,
setSaveCardDetails,
payNowExperience,
setPayNowExperience,
logging,
setLogging,
subtotalAdjustment,
setSubtotalAdjustment,
brandName,
setBrandName,
softDescriptor,
setSoftDescriptor,
landingPage,
setLandingPage,
buttonLanguage,
setButtonLanguage,
disabledCards,
setDisabledCards,
};
};

View file

@ -0,0 +1,40 @@
/**
* Store Configuration: Defines and registers the settings data store.
*
* Creates a Redux-style store with WordPress data layer integration.
* Combines reducers, actions, selectors and controls into a unified store.
*
* @file
*/
import { createReduxStore, register } from '@wordpress/data';
import { controls as wpControls } from '@wordpress/data-controls';
import { STORE_NAME } from './constants';
import reducer from './reducer';
import * as selectors from './selectors';
import * as actions from './actions';
import * as hooks from './hooks';
import { resolvers } from './resolvers';
import { controls } from './controls';
/**
* Initializes and registers the settings store with WordPress data layer.
* Combines custom controls with WordPress data controls.
*
* @return {boolean} True if initialization succeeded, false otherwise.
*/
export const initStore = () => {
const store = createReduxStore( STORE_NAME, {
reducer,
controls: { ...wpControls, ...controls },
actions,
selectors,
resolvers,
} );
register( store );
return Boolean( wp.data.select( STORE_NAME ) );
};
export { hooks, selectors, STORE_NAME };

View file

@ -0,0 +1,102 @@
/**
* Reducer: Defines store structure and state updates for this module.
*
* Manages both transient (temporary) and persistent (saved) state.
* The initial state must define all properties, as dynamic additions are not supported.
*
* @file
*/
import { createReducer, createReducerSetters } from '../utils';
import ACTION_TYPES from './action-types';
// Store structure.
/**
* Transient: Values that are _not_ saved to the DB (like app lifecycle-flags).
* These reset on page reload.
*/
const defaultTransient = Object.freeze( {
isReady: false,
} );
/**
* Persistent: Values that are loaded from and saved to the DB.
* These represent the core PayPal payment settings configuration.
*/
const defaultPersistent = Object.freeze( {
invoicePrefix: '', // Prefix for PayPal invoice IDs
authorizeOnly: false, // Whether to only authorize payments initially
captureVirtualOnlyOrders: false, // Auto-capture virtual-only orders
savePaypalAndVenmo: false, // Enable PayPal & Venmo vaulting
saveCardDetails: false, // Enable card vaulting
payNowExperience: false, // Enable Pay Now experience
logging: false, // Enable debug logging
subtotalAdjustment: 'skip_details', // Handling for subtotal mismatches
brandName: '', // Merchant brand name for PayPal
softDescriptor: '', // Payment descriptor on statements
landingPage: 'any', // PayPal checkout landing page
buttonLanguage: '', // Language for PayPal buttons
disabledCards: [], // Disabled credit card types
} );
// Reducer logic.
const [ changeTransient, changePersistent ] = createReducerSetters(
defaultTransient,
defaultPersistent
);
/**
* Reducer implementation mapping actions to state updates.
*/
const reducer = createReducer( defaultTransient, defaultPersistent, {
/**
* Updates temporary state values
*
* @param {Object} state Current state
* @param {Object} payload Update payload
* @return {Object} Updated state
*/
[ ACTION_TYPES.SET_TRANSIENT ]: ( state, payload ) => {
return changeTransient( state, payload );
},
/**
* Updates persistent configuration values
*
* @param {Object} state Current state
* @param {Object} payload Update payload
* @return {Object} Updated state
*/
[ ACTION_TYPES.SET_PERSISTENT ]: ( state, payload ) =>
changePersistent( state, payload ),
/**
* Resets state to defaults while maintaining initialization status
*
* @param {Object} state Current state
* @return {Object} Reset state
*/
[ ACTION_TYPES.RESET ]: ( state ) => {
const cleanState = changeTransient(
changePersistent( state, defaultPersistent ),
defaultTransient
);
cleanState.isReady = true; // Keep initialization flag
return cleanState;
},
/**
* Initializes persistent state with data from the server
*
* @param {Object} state Current state
* @param {Object} payload Hydration payload containing server data
* @param {Object} payload.data The settings data to hydrate
* @return {Object} Hydrated state
*/
[ ACTION_TYPES.HYDRATE ]: ( state, payload ) =>
changePersistent( state, payload.data ),
} );
export default reducer;

View file

@ -0,0 +1,57 @@
/**
* Resolvers: Handle asynchronous data fetching for the store.
*
* These functions update store state with data from external sources.
* Each resolver corresponds to a specific selector (selector with same name must exist).
* Resolvers are called automatically when selectors request unavailable data.
*
* @file
*/
import { dispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { apiFetch } from '@wordpress/data-controls';
import { STORE_NAME, REST_HYDRATE_PATH } from './constants';
export const resolvers = {
/**
* Retrieve PayPal settings from the site's REST API.
* Hydrates the store with the retrieved data and marks it as ready.
*
* @generator
* @yield {Object} API fetch and dispatch actions
*/
*persistentData() {
try {
// Fetch settings data from REST API
const result = yield apiFetch( {
path: REST_HYDRATE_PATH,
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
} );
// Update store with retrieved data
yield dispatch( STORE_NAME ).hydrate( result );
// Mark store as ready for use
yield dispatch( STORE_NAME ).setIsReady( true );
} catch ( e ) {
// Log detailed error information for debugging
console.error( 'Full error details:', {
error: e,
path: REST_HYDRATE_PATH,
store: STORE_NAME,
} );
// Display user-friendly error notice
yield dispatch( 'core/notices' ).createErrorNotice(
__(
'Error retrieving PayPal settings details.',
'woocommerce-paypal-payments'
)
);
}
},
};

View file

@ -0,0 +1,46 @@
/**
* Selectors: Extract specific pieces of state from the store.
*
* These functions provide a consistent interface for accessing store data.
* They allow components to retrieve data without knowing the store structure.
*
* @file
*/
/**
* Empty frozen object used as fallback when state is undefined.
*
* @constant
* @type {Object}
*/
const EMPTY_OBJ = Object.freeze( {} );
/**
* Base selector that ensures a valid state object.
*
* @param {Object|undefined} state The current state
* @return {Object} The state or empty object if undefined
*/
export const getState = ( state ) => state || EMPTY_OBJ;
/**
* Retrieves persistent (saved) data from the store.
*
* @param {Object} state The current state
* @return {Object} The persistent data or empty object if undefined
*/
export const persistentData = ( state ) => {
return getState( state ).data || EMPTY_OBJ;
};
/**
* Retrieves transient (temporary) data from the store.
* Excludes persistent data stored in the 'data' property.
*
* @param {Object} state The current state
* @return {Object} The transient state or empty object if undefined
*/
export const transientData = ( state ) => {
const { data, ...transientState } = getState( state );
return transientState || EMPTY_OBJ;
};

View file

@ -1,170 +0,0 @@
import { __ } from '@wordpress/i18n';
import { selectTab, TAB_IDS } from '../../utils/tabSelector';
export const todosData = [
{
id: 'enable_fastlane',
title: __( 'Enable Fastlane', 'woocommerce-paypal-payments' ),
description: __(
'Accelerate your guest checkout with Fastlane by PayPal.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
selectTab( TAB_IDS.PAYMENT_METHODS, 'ppcp-card-payments-card' );
},
},
{
id: 'enable_credit_debit_cards',
title: __(
'Enable Credit and Debit Cards on your checkout',
'woocommerce-paypal-payments'
),
description: __(
'Credit and Debit Cards is now available for Blocks checkout pages.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
selectTab( TAB_IDS.PAYMENT_METHODS, 'ppcp-card-payments-card' );
},
},
{
id: 'enable_pay_later_messaging',
title: __(
'Enable Pay Later messaging',
'woocommerce-paypal-payments'
),
description: __(
'Show Pay Later messaging to boost conversion rate and increase cart size.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
selectTab( TAB_IDS.OVERVIEW, 'pay_later_messaging' );
},
},
{
id: 'configure_paypal_subscription',
title: __(
'Configure a PayPal Subscription',
'woocommerce-paypal-payments'
),
description: __(
'Connect a subscriptions-type product from WooCommerce with PayPal.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
console.log(
'Take merchant to product list, filtered with subscription-type products'
);
},
},
{
id: 'register_domain_apple_pay',
title: __(
'Register Domain for Apple Pay',
'woocommerce-paypal-payments'
),
description: __(
'To enable Apple Pay, you must register your domain with PayPal.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
selectTab( TAB_IDS.OVERVIEW, 'apple_pay' );
},
},
{
id: 'add_digital_wallets_to_account',
title: __(
'Add digital wallets to your account',
'woocommerce-paypal-payments'
),
description: __(
'Add the ability to accept Apple Pay & Google Pay to your PayPal account.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
console.log(
'Take merchant to PayPal to enable Apple Pay & Google Pay'
);
},
},
{
id: 'add_apple_pay_to_account',
title: __(
'Add Apple Pay to your account',
'woocommerce-paypal-payments'
),
description: __(
'Add the ability to accept Apple Pay to your PayPal account.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
console.log( 'Take merchant to PayPal to enable Apple Pay' );
},
},
{
id: 'add_google_pay_to_account',
title: __(
'Add Google Pay to your account',
'woocommerce-paypal-payments'
),
description: __(
'Add the ability to accept Google Pay to your PayPal account.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
console.log( 'Take merchant to PayPal to enable Google Pay' );
},
},
{
id: 'enable_apple_pay',
title: __( 'Enable Apple Pay', 'woocommerce-paypal-payments' ),
description: __(
'Allow your buyers to check out via Apple Pay.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
selectTab( TAB_IDS.OVERVIEW, 'apple_pay' );
},
},
{
id: 'enable_google_pay',
title: __( 'Enable Google Pay', 'woocommerce-paypal-payments' ),
description: __(
'Allow your buyers to check out via Google Pay.',
'woocommerce-paypal-payments'
),
isCompleted: () => {
return false;
},
onClick: () => {
selectTab( TAB_IDS.OVERVIEW, 'google_pay' );
},
},
];