diff --git a/css/admin/frm-legacy-paypal.css b/css/admin/frm-legacy-paypal.css index 71ffdac6c9..aa69d04742 100644 --- a/css/admin/frm-legacy-paypal.css +++ b/css/admin/frm-legacy-paypal.css @@ -1 +1 @@ -.frm_single_paypal_settings .form-table{margin:0}.frm_single_paypal_settings h3{display:flex;align-items:center;gap:var(--gap-xs);margin-top:var(--gap-xs);margin-bottom:var(--gap-md)}.frm_single_paypal_settings h3 .frm_help{display:inline-flex;align-items:center}.frm_single_paypal_settings label[for^=paypal_stop_email]{display:inline-flex;align-items:center;gap:var(--gap-xs)}.frm_single_paypal_settings .frm_toggle_pp_opts{font-weight:600;cursor:pointer}.frm_single_paypal_settings p[id^=frmpp_after_pay_]{margin-bottom:var(--gap-sm)}.frm_single_paypal_settings .frmpp_after_pay_row .frm_remove_tag{margin-right:var(--gap-2xs)}.frm_single_paypal_settings #postcustomstuff.frmpp_after_pay_rows:not(:has(.frmpp_after_pay_row)){display:none !important} +.frm_single_paypal_settings .form-table{margin:0}.frm_single_paypal_settings h3{display:flex;align-items:center;gap:var(--gap-xs);margin-top:var(--gap-xs);margin-bottom:var(--gap-md)}.frm_single_paypal_settings h3 .frm_help{display:inline-flex;align-items:center}.frm_single_paypal_settings label[for^=paypal_stop_email]{display:inline-flex;align-items:center;gap:var(--gap-xs)}.frm_single_paypal_settings .frm_toggle_pp_opts{font-weight:600;cursor:pointer}.frm_single_paypal_settings p[id^=frmpp_after_pay_]{margin-bottom:var(--gap-sm)}.frm_single_paypal_settings .frmpp_after_pay_row .frm_remove_tag{margin-right:var(--gap-2xs)}.frm_single_paypal_settings #postcustomstuff.frmpp_after_pay_rows:not(:has(.frmpp_after_pay_row)){display:none !important}.frm_single_paypal_settings .frm-paypal-migration-notes{list-style:disc;padding-left:var(--gap-md)}.frm_single_paypal_settings .frm-paypal-migration-notes li{margin-bottom:var(--gap-2xs)} diff --git a/paypal/controllers/FrmPayPalLiteHooksController.php b/paypal/controllers/FrmPayPalLiteHooksController.php index 2d1ac9060d..48a663e210 100644 --- a/paypal/controllers/FrmPayPalLiteHooksController.php +++ b/paypal/controllers/FrmPayPalLiteHooksController.php @@ -67,6 +67,7 @@ function ( $options ) { ); add_action( 'frm_field_options_before_label', 'FrmPayPalLiteFieldsController::add_paypal_order_field_note', 10, 3 ); + add_action( 'frm_before_action_settings', 'FrmPayPalLiteLegacyMigrationController::show_migration_notice' ); if ( defined( 'DOING_AJAX' ) ) { self::load_ajax_hooks(); @@ -100,6 +101,7 @@ private static function load_ajax_hooks() { add_action( 'wp_ajax_nopriv_frm_paypal_report_error', 'FrmPayPalLiteAppController::report_error' ); add_action( 'wp_ajax_frm_paypal_render_seller_status', 'FrmPayPalLiteConnectHelper::handle_render_seller_status' ); + add_action( 'wp_ajax_frm_paypal_migrate_legacy_action', 'FrmPayPalLiteLegacyMigrationController::migrate_action' ); add_action( 'wp_ajax_frm_add_form_action', 'FrmPayPalLiteActionsController::maybe_modify_new_action_post_data', 1 ); } diff --git a/paypal/controllers/FrmPayPalLiteLegacyMigrationController.php b/paypal/controllers/FrmPayPalLiteLegacyMigrationController.php new file mode 100644 index 0000000000..9cac80a2e2 --- /dev/null +++ b/paypal/controllers/FrmPayPalLiteLegacyMigrationController.php @@ -0,0 +1,52 @@ +ID ) || ! current_user_can( 'frm_edit_forms' ) ) { + return; + } + + $blocker = FrmPayPalLiteLegacyMigrationHelper::get_migration_blocker( (int) $form_action->menu_order, $form_action->post_content ); + + include FrmPayPalLiteAppHelper::plugin_path() . 'views/settings/legacy-migration-notice.php'; + } + + /** + * Convert a legacy PayPal action into a PayPal Commerce payment action. + * + * @since x.x + * + * @return void + */ + public static function migrate_action() { + FrmAppHelper::permission_check( 'frm_edit_forms' ); + check_ajax_referer( 'frm_ajax', 'nonce' ); + + $action_id = FrmAppHelper::get_post_param( 'action_id', 0, 'absint' ); + $result = FrmPayPalLiteLegacyMigrationHelper::migrate( $action_id ); + + if ( is_wp_error( $result ) ) { + wp_send_json_error( array( 'message' => $result->get_error_message() ) ); + } + + wp_send_json_success( $result ); + } +} diff --git a/paypal/helpers/FrmPayPalLiteLegacyMigrationHelper.php b/paypal/helpers/FrmPayPalLiteLegacyMigrationHelper.php new file mode 100644 index 0000000000..e92dc31fff --- /dev/null +++ b/paypal/helpers/FrmPayPalLiteLegacyMigrationHelper.php @@ -0,0 +1,410 @@ + + */ + private static $periods = array( + 'D' => array( 'day', 1 ), + 'W' => array( 'week', 7 ), + 'M' => array( 'month', 30 ), + 'Y' => array( 'year', 365 ), + ); + + /** + * @since x.x + * + * @param object $form_action The form action to check. + * + * @return bool + */ + public static function is_legacy_action( $form_action ) { + return is_object( $form_action ) && ! empty( $form_action->post_excerpt ) && in_array( $form_action->post_excerpt, self::$legacy_types, true ); + } + + /** + * Get the reason the action cannot be migrated right now. + * + * @since x.x + * + * @param int $form_id The ID of the form the legacy action belongs to. + * @param array|string $legacy_settings The legacy action settings, as an array or the saved JSON. + * + * @return string An empty string when the action can be migrated. + */ + public static function get_migration_blocker( $form_id, $legacy_settings = array() ) { + $connection_error = FrmTransLiteAppHelper::get_gateway_connection_error( 'paypal' ); + + if ( $connection_error ) { + return $connection_error; + } + + if ( FrmFormAction::form_has_action_type( $form_id, 'payment' ) ) { + return __( 'This form already has a payment action, and only one is allowed per form. Delete the existing payment action to convert this one.', 'formidable' ); + } + + return self::get_after_payment_blocker( self::get_settings_array( $legacy_settings ) ); + } + + /** + * The payment action only runs After Payment rows with a Pro version that supports them, + * so converting without one would silently stop the field updates. + * + * @param array $legacy_settings The legacy action settings. + * + * @return string An empty string when the After Payment rows can run after converting. + */ + private static function get_after_payment_blocker( $legacy_settings ) { + if ( ! self::convert_change_fields( $legacy_settings['change_field'] ?? array() ) || self::after_payment_is_supported() ) { + return ''; + } + + if ( FrmAppHelper::pro_is_installed() ) { + return __( 'This action changes fields after payment, which needs the latest version of Formidable Pro. Update Formidable Pro to convert this action.', 'formidable' ); + } + + return __( 'This action changes fields after payment, which needs Formidable Pro. Activate Formidable Pro to convert this action.', 'formidable' ); + } + + /** + * Create a PayPal Commerce payment action from a legacy PayPal action, then turn the legacy action off. + * + * @since x.x + * + * @param int $action_id The ID of the legacy PayPal action. + * + * @return array|WP_Error The new action ID and notes about settings that could not be copied exactly. + */ + public static function migrate( $action_id ) { + $legacy_action = get_post( $action_id ); + + if ( ! $legacy_action || FrmFormActionsController::$action_post_type !== $legacy_action->post_type || ! self::is_legacy_action( $legacy_action ) ) { + return new WP_Error( 'frm_paypal_invalid_action', __( 'That legacy PayPal action could not be found.', 'formidable' ) ); + } + + $form_id = (int) $legacy_action->menu_order; + $legacy_settings = self::get_settings_array( $legacy_action->post_content ); + $blocker = self::get_migration_blocker( $form_id, $legacy_settings ); + + if ( $blocker ) { + return new WP_Error( 'frm_paypal_migration_blocked', $blocker ); + } + + $payment_control = FrmFormActionsController::get_form_actions( 'payment' ); + + if ( ! is_object( $payment_control ) ) { + return new WP_Error( 'frm_paypal_no_payment_action', __( 'The payment action is not available.', 'formidable' ) ); + } + + $notes = array(); + $new_action = $payment_control->prepare_new( $form_id ); + + $new_action->post_title = $legacy_action->post_title; + $new_action->post_content = array_merge( $new_action->post_content, self::convert_settings( $legacy_settings, $form_id, $notes ) ); + + $action_array = (array) $new_action; + $new_action->post_content = apply_filters( 'frm_before_save_action', $new_action->post_content, $action_array, $action_array, array(), $payment_control ); + $new_action->post_content = apply_filters( 'frm_before_save_payment_action', $new_action->post_content, $action_array, $action_array, array(), $payment_control ); + + $new_action_id = $payment_control->save_settings( $new_action ); + + if ( ! $new_action_id || is_wp_error( $new_action_id ) ) { + return new WP_Error( 'frm_paypal_migration_failed', __( 'The PayPal Commerce action could not be created. The legacy action was not changed.', 'formidable' ) ); + } + + FrmFormAction::clear_cache(); + wp_update_post( + array( + 'ID' => $legacy_action->ID, + 'post_status' => 'draft', + ) + ); + + if ( ! empty( $legacy_settings['paypal_stop_email'] ) ) { + $moved = self::move_emails_to_payment_success( $form_id ); + + if ( $moved ) { + $notes[] = sprintf( + /* translators: %d: The number of email actions that were changed. */ + _n( + 'To hold notifications until payment is received, %d email action now sends on a successful payment instead of when the entry is created.', + 'To hold notifications until payment is received, %d email actions now send on a successful payment instead of when the entry is created.', + $moved, + 'formidable' + ), + $moved + ); + } + } + + FrmFormAction::clear_cache(); + + return array( + 'action_id' => (int) $new_action_id, + 'notes' => $notes, + ); + } + + /** + * Map legacy PayPal action settings to PayPal Commerce payment action settings. + * + * @since x.x + * + * @param array $legacy The legacy action settings. + * @param int $form_id The form ID, used for a product name fallback. + * @param string[] $notes Messages about settings that could not be copied exactly, passed by reference. + * + * @return array + */ + public static function convert_settings( $legacy, $form_id, &$notes ) { + $item_name = (string) ( $legacy['paypal_item_name'] ?? '' ); + $type = (string) ( $legacy['paypal_type'] ?? '' ); + $settings = array( + 'gateway' => array( 'paypal' ), + 'type' => '_xclick-subscriptions' === $type ? 'recurring' : 'single', + 'description' => $item_name, + 'amount' => self::convert_amount( $legacy ), + 'event' => array( 'create' ), + 'conditions' => self::convert_conditions( $legacy['conditions'] ?? array() ), + ); + + if ( ! empty( $legacy['currency'] ) ) { + $settings['currency'] = strtolower( $legacy['currency'] ); + } + + if ( '_donations' === $type ) { + $notes[] = __( 'The legacy Donation payment type is now a one-time payment. PayPal Commerce does not have a separate donation checkout.', 'formidable' ); + } + + if ( 'recurring' === $settings['type'] ) { + $settings = array_merge( $settings, self::convert_recurring_settings( $legacy, $item_name, $form_id, $notes ) ); + } + + $change_fields = self::convert_change_fields( $legacy['change_field'] ?? array() ); + + if ( $change_fields ) { + // get_migration_blocker() stops the conversion when nothing can run these rows. + $settings['change_field'] = $change_fields; + } + + if ( ! empty( $legacy['business_email'] ) ) { + $notes[] = sprintf( + /* translators: %s: The PayPal email address from the legacy action. */ + __( 'Payments now go to the PayPal account connected in Global Settings, not %s.', 'formidable' ), + $legacy['business_email'] + ); + } + + if ( ! empty( $legacy['return_url'] ) || ! empty( $legacy['cancel_url'] ) ) { + $notes[] = __( 'Payments now happen on the form page, so the Return URL and Cancel URL are not used. Set a redirect in the confirmation.', 'formidable' ); + } + + return $settings; + } + + /** + * Legacy actions use either a field or a fixed amount. PayPal Commerce uses a single amount setting + * that accepts field shortcodes. + * + * @param array $legacy The legacy action settings. + * + * @return string + */ + private static function convert_amount( $legacy ) { + if ( ! empty( $legacy['paypal_amount_field'] ) && is_numeric( $legacy['paypal_amount_field'] ) ) { + return '[' . absint( $legacy['paypal_amount_field'] ) . ']'; + } + + return (string) ( $legacy['paypal_amount'] ?? '' ); + } + + /** + * Saved actions hold their settings as JSON. Actions loaded for the form settings page hold an array. + * + * @param array|string $settings The legacy action settings. + * + * @return array + */ + private static function get_settings_array( $settings ) { + $settings = FrmAppHelper::maybe_json_decode( $settings ); + return is_array( $settings ) ? $settings : array(); + } + + /** + * Legacy "After Payment" rows use the same id, status and value keys as the payment action. + * The legacy statuses, Completed and Failed, both exist in the payment action, so only + * incomplete rows are dropped. + * + * @param array $change_fields The legacy After Payment rows, keyed by row number. + * + * @return array + */ + private static function convert_change_fields( $change_fields ) { + if ( ! is_array( $change_fields ) ) { + return array(); + } + + $rows = array(); + + foreach ( $change_fields as $row ) { + if ( ! is_array( $row ) || empty( $row['id'] ) || ! in_array( $row['status'] ?? '', array( 'complete', 'failed' ), true ) ) { + continue; + } + + $rows[] = array( + 'id' => absint( $row['id'] ), + 'status' => $row['status'], + 'value' => (string) ( $row['value'] ?? '' ), + ); + } + + return $rows; + } + + /** + * Pro runs the After Payment rows of the payment action. While the Stripe add-on is active, + * its own payment action runs them instead. + * + * @return bool + */ + private static function after_payment_is_supported() { + return is_callable( 'FrmProTransLiteController::change_fields_after_payment' ) || class_exists( 'FrmTransActionsController' ); + } + + /** + * Very old legacy actions store conditions as parallel arrays. Convert them to the current row format. + * This mirrors FrmPaymentAction::migrate_values() so it also works while the PayPal add-on is inactive. + * + * @param array $conditions The legacy conditional logic settings. + * + * @return array + */ + private static function convert_conditions( $conditions ) { + if ( ! is_array( $conditions ) || empty( $conditions['hide_field'] ) || ! is_array( $conditions['hide_field'] ) ) { + return is_array( $conditions ) ? $conditions : array(); + } + + $new_conditions = array( + 'send_stop' => $conditions['send_stop'] ?? 'send', + 'any_all' => $conditions['any_all'] ?? 'any', + ); + + foreach ( $conditions['hide_field'] as $key => $field_id ) { + $new_conditions[] = array( + 'hide_field' => $field_id, + 'hide_field_cond' => $conditions['hide_field_cond'][ $key ] ?? '==', + 'hide_opt' => $conditions['hide_opt'][ $key ] ?? '', + ); + } + + return $new_conditions; + } + + /** + * @param array $legacy The legacy action settings. + * @param string $item_name The legacy item name. + * @param int $form_id The form ID, used for a product name fallback. + * @param string[] $notes Messages about settings that could not be copied exactly, passed by reference. + * + * @return array + */ + private static function convert_recurring_settings( $legacy, $item_name, $form_id, &$notes ) { + $period = self::$periods[ $legacy['repeat_time'] ?? 'M' ] ?? self::$periods['M']; + $settings = array( + 'interval' => $period[0], + 'interval_count' => max( 1, (int) ( $legacy['repeat_num'] ?? 1 ) ), + 'product_name' => $item_name, + 'product_type' => 'SERVICE', + 'payment_limit' => '', + 'trial_interval_count' => 0, + ); + + if ( '' === $settings['product_name'] ) { + // PayPal Commerce requires a product name for subscriptions. + $settings['product_name'] = FrmForm::getName( $form_id ); + } + + if ( ! empty( $legacy['trial'] ) ) { + $trial_period = self::$periods[ $legacy['trial_time'] ?? 'M' ] ?? self::$periods['M']; + $trial_days = max( 1, (int) ( $legacy['trial_num'] ?? 1 ) ) * $trial_period[1]; + $settings['trial_interval_count'] = $trial_days; + + if ( 'day' !== $trial_period[0] ) { + $notes[] = sprintf( + /* translators: %d: The number of days in the trial period. */ + __( 'PayPal Commerce trials are set in days, so the trial is now %d days.', 'formidable' ), + $trial_days + ); + } + + if ( (float) ( $legacy['trial_amount'] ?? 0 ) > 0 ) { + $notes[] = __( 'PayPal Commerce trials are free, so the legacy trial amount was not copied.', 'formidable' ); + } + } + + if ( ! empty( $legacy['retry'] ) ) { + $notes[] = __( 'The legacy "Retry a failed payment" setting has no PayPal Commerce equivalent. PayPal applies its own retry rules to subscriptions.', 'formidable' ); + } + + return $settings; + } + + /** + * The legacy "hold email notifications" setting delays emails until the payment completes. + * PayPal Commerce does the same with the Successful Payment trigger. + * + * @param int $form_id The form ID. + * + * @return int The number of email actions changed. + */ + private static function move_emails_to_payment_success( $form_id ) { + $email_control = FrmFormActionsController::get_form_actions( 'email' ); + + if ( ! is_object( $email_control ) ) { + return 0; + } + + $moved = 0; + + foreach ( FrmFormAction::get_action_for_form( $form_id, 'email' ) as $email_action ) { + $events = (array) ( $email_action->post_content['event'] ?? array() ); + + if ( ! in_array( 'create', $events, true ) ) { + continue; + } + + $events = array_values( array_diff( $events, array( 'create' ) ) ); + + if ( ! in_array( 'payment-success', $events, true ) ) { + $events[] = 'payment-success'; + } + + $email_action->post_content['event'] = $events; + $email_control->save_settings( $email_action ); + ++$moved; + } + + return $moved; + } +} diff --git a/paypal/js/action.js b/paypal/js/action.js index baf71d40ce..06a544d557 100644 --- a/paypal/js/action.js +++ b/paypal/js/action.js @@ -6,6 +6,87 @@ jQuery( actions ).on( 'change', 'select[name*="[post_content][paypal_layout]"]', onLayoutChange ); jQuery( actions ).on( 'change', 'select.frm_trans_type', onPaymentTypeChange ); + actions.addEventListener( 'click', onMigrateLegacyClick ); + + /** + * Convert a legacy PayPal action into a PayPal Commerce payment action, then reload the page. + * The reload matters. Saving the form with the old settings still on the page would delete the new action. + * + * @param {Event} event + * @return {void} + */ + function onMigrateLegacyClick( event ) { + const button = event.target.closest( '.frm-paypal-migrate-legacy' ); + if ( ! button || button.disabled ) { + return; + } + + const { __ } = wp.i18n; + const notice = button.closest( '.frm-paypal-legacy-migration' ); + const result = notice.querySelector( '.frm-paypal-migration-result' ); + const body = new FormData(); + const showError = message => { + button.disabled = false; + result.replaceChildren( + frmDom.tag( 'div', { + className: 'frm_error_style frm-mt-sm frm-mb-0', + text: message || __( 'The action could not be converted.', 'formidable' ) + } ) + ); + }; + + body.append( 'action', 'frm_paypal_migrate_legacy_action' ); + body.append( 'action_id', button.dataset.actionId ); + body.append( 'nonce', frmGlobal.nonce ); + + button.disabled = true; + result.replaceChildren( frmDom.tag( 'p', { className: 'frm-mt-sm frm-mb-0', text: __( 'Converting…', 'formidable' ) } ) ); + + fetch( ajaxurl, { method: 'POST', body } ) + .then( response => response.json() ) + .then( response => { + if ( ! response.success ) { + showError( response.data?.message ); + return; + } + + // Divs, not paragraphs, so the success message color is not replaced by the admin paragraph color. + const children = [ + frmDom.tag( 'div', { + className: 'frm-mb-xs frm-font-semibold', + text: __( 'Converted to PayPal Commerce', 'formidable' ) + } ), + frmDom.tag( 'div', { + className: 'frm-mb-sm', + text: __( 'Your PayPal Commerce action is ready and this legacy action is now off. Reload the page to see the new action.', 'formidable' ) + } ) + ]; + + if ( response.data.notes.length ) { + children.push( + frmDom.tag( 'div', { className: 'frm-mb-xs', text: __( 'Review these settings on the new action:', 'formidable' ) } ), + frmDom.tag( 'ul', { + className: 'frm-mt-0 frm-mb-sm frm-paypal-migration-notes', + children: response.data.notes.map( note => frmDom.tag( 'li', { text: note } ) ) + } ) + ); + } + + const reload = frmDom.tag( 'button', { + className: 'button frm-button-primary', + text: __( 'Reload the page', 'formidable' ) + } ); + reload.type = 'button'; + reload.addEventListener( 'click', () => window.location.reload() ); + children.push( reload ); + + notice.querySelector( '.frm-paypal-migration-intro' ).classList.add( 'frm_hidden' ); + notice.classList.replace( 'frm_note_style', 'frm_updated_message' ); + result.replaceChildren( ...children ); + reload.focus(); + } ) + .catch( () => showError() ); + } function onLayoutChange() { const settings = this.closest( '.frm_form_action_settings' ); diff --git a/paypal/views/settings/legacy-migration-notice.php b/paypal/views/settings/legacy-migration-notice.php new file mode 100644 index 0000000000..06e4879d3d --- /dev/null +++ b/paypal/views/settings/legacy-migration-notice.php @@ -0,0 +1,41 @@ + 'button', + 'class' => 'button frm-button-primary frm-paypal-migrate-legacy', + 'data-action-id' => (int) $form_action->ID, +); + +if ( $blocker ) { + $button_attrs['disabled'] = 'disabled'; +} +?> +
+
+

+ +

+

+ +

+

+ +

+ +
+ 'width:24px' ) ); ?> + +
+ + +
+
+
diff --git a/resources/scss/admin/frm-legacy-paypal.scss b/resources/scss/admin/frm-legacy-paypal.scss index 28544ba065..3a6d9b9c7a 100644 --- a/resources/scss/admin/frm-legacy-paypal.scss +++ b/resources/scss/admin/frm-legacy-paypal.scss @@ -41,4 +41,14 @@ #postcustomstuff.frmpp_after_pay_rows:not(:has(.frmpp_after_pay_row)) { display: none !important; } + + // Settings to review after converting to PayPal Commerce. + .frm-paypal-migration-notes { + list-style: disc; + padding-left: var(--gap-md); + + li { + margin-bottom: var(--gap-2xs); + } + } } diff --git a/tests/phpunit/paypal/test_FrmPayPalLiteLegacyMigration.php b/tests/phpunit/paypal/test_FrmPayPalLiteLegacyMigration.php new file mode 100644 index 0000000000..d0200b3bbc --- /dev/null +++ b/tests/phpunit/paypal/test_FrmPayPalLiteLegacyMigration.php @@ -0,0 +1,225 @@ + '_xclick', + 'paypal_amount_field' => 123, + 'currency' => 'USD', + 'conditions' => array( + 'hide_field' => array( 45 ), + 'hide_field_cond' => array( '==' ), + 'hide_opt' => array( 'yes' ), + ), + ), + 1, + $notes + ); + $this->assertSame( array( 'paypal' ), $value['gateway'], 'The gateway is PayPal Commerce.' ); + $this->assertSame( 'single', $value['type'], 'Single payments keep their type.' ); + $this->assertSame( '[123]', $value['amount'], 'Field amounts become shortcodes.' ); + $this->assertSame( 'usd', $value['currency'], 'Currency uses the Commerce format.' ); + $this->assertSame( 45, $value['conditions'][0]['hide_field'], 'Legacy condition fields are preserved.' ); + $this->assertSame( 'yes', $value['conditions'][0]['hide_opt'], 'Legacy condition values are preserved.' ); + } + + public function test_subscription_maps_interval_and_reports_trial_changes() { + $notes = array(); + $value = FrmPayPalLiteLegacyMigrationHelper::convert_settings( + array( + 'paypal_type' => '_xclick-subscriptions', + 'paypal_item_name' => 'Membership', + 'paypal_amount' => '12.50', + 'repeat_time' => 'W', + 'repeat_num' => 2, + 'trial' => 1, + 'trial_time' => 'M', + 'trial_num' => 3, + 'trial_amount' => '2.75', + ), + 1, + $notes + ); + $this->assertSame( 'recurring', $value['type'], 'Subscriptions remain recurring.' ); + $this->assertSame( 'week', $value['interval'], 'The billing period is preserved.' ); + $this->assertSame( 2, $value['interval_count'], 'The billing interval count is preserved.' ); + $this->assertSame( '12.50', $value['amount'], 'Fixed amounts are preserved.' ); + $this->assertSame( 90, $value['trial_interval_count'], 'Month trials convert to days.' ); + $this->assertCount( 2, $notes, 'Trial approximation and paid trial changes are disclosed.' ); + } + + public function test_donations_report_the_conversion() { + $notes = array(); + $value = FrmPayPalLiteLegacyMigrationHelper::convert_settings( + array( + 'paypal_type' => '_donations', + 'paypal_amount' => '5', + ), + 1, + $notes + ); + $this->assertSame( 'single', $value['type'], 'Donations become one-time payments.' ); + $this->assertCount( 1, $notes, 'The donation conversion is disclosed.' ); + } + + public function test_after_payment_rows_are_copied() { + $notes = array(); + $value = FrmPayPalLiteLegacyMigrationHelper::convert_settings( + array( + 'paypal_type' => '_xclick', + 'paypal_amount' => '5', + 'change_field' => array( + 3 => array( + 'id' => '12', + 'status' => 'complete', + 'value' => 'Paid [25]', + ), + 5 => array( + 'id' => '13', + 'status' => 'failed', + 'value' => 'Failed', + ), + 7 => array( + 'id' => '', + 'status' => 'complete', + 'value' => 'No field', + ), + 8 => array( + 'id' => '14', + 'status' => '', + 'value' => 'No status', + ), + ), + ), + 1, + $notes + ); + $this->assertSame( + array( + array( + 'id' => 12, + 'status' => 'complete', + 'value' => 'Paid [25]', + ), + array( + 'id' => 13, + 'status' => 'failed', + 'value' => 'Failed', + ), + ), + $value['change_field'], + 'Complete rows are copied with their statuses and shortcodes, and incomplete rows are dropped.' + ); + } + + public function test_missing_after_payment_rows_are_not_added() { + $notes = array(); + $value = FrmPayPalLiteLegacyMigrationHelper::convert_settings( + array( + 'paypal_type' => '_xclick', + 'change_field' => array( + array( + 'id' => '', + 'status' => '', + 'value' => '', + ), + ), + ), + 1, + $notes + ); + $this->assertArrayNotHasKey( 'change_field', $value, 'Empty rows add no After Payment setting.' ); + $this->assertSame( array(), $notes, 'Empty rows add no notes.' ); + } + + public function test_after_payment_rows_need_a_supporting_pro_version() { + $supported = $this->run_private_method( array( 'FrmPayPalLiteLegacyMigrationHelper', 'after_payment_is_supported' ) ); + $method = array( 'FrmPayPalLiteLegacyMigrationHelper', 'get_after_payment_blocker' ); + $rows = array( + 'change_field' => array( + array( + 'id' => 12, + 'status' => 'complete', + 'value' => 'Paid', + ), + ), + ); + + $this->assertSame( '', $this->run_private_method( $method, array( array() ) ), 'Actions without After Payment rows can always convert.' ); + $blocker = $this->run_private_method( $method, array( $rows ) ); + + if ( $supported ) { + $this->assertSame( '', $blocker, 'A loaded After Payment integration should allow conversion.' ); + return; + } + $this->assertStringContainsString( 'Activate Formidable Pro', $blocker, 'Without Pro, the conversion is blocked.' ); + + add_filter( 'frm_pro_installed', '__return_true' ); + $blocker = $this->run_private_method( $method, array( $rows ) ); + remove_filter( 'frm_pro_installed', '__return_true' ); + $this->assertStringContainsString( 'Update Formidable Pro', $blocker, 'With an outdated Pro, the conversion asks for an update.' ); + } + + public function test_invalid_actions_are_rejected() { + $result = FrmPayPalLiteLegacyMigrationHelper::migrate( 0 ); + $this->assertWPError( $result, 'Missing actions are rejected before conversion.' ); + $this->assertSame( 'frm_paypal_invalid_action', $result->get_error_code(), 'The rejection identifies the invalid action.' ); + } + + /** + * Converts the saved action, moves only create emails and prevents a duplicate conversion. + */ + public function test_migrate_preserves_subscription_and_email_settings() { + update_option( 'frm_paypal_connect_merchant_id_test', 'migration_fixture', false ); + update_option( 'frm_paypal_connect_merchant_id_live', 'migration_fixture', false ); + $form_id = $this->factory->form->create(); + $legacy_id = wp_insert_post( + array( + 'post_type' => FrmFormActionsController::$action_post_type, + 'post_excerpt' => 'paypal', + 'post_status' => 'publish', + 'post_title' => 'Gold membership', + 'menu_order' => $form_id, + 'post_content' => wp_json_encode( + array( + 'paypal_type' => '_xclick-subscriptions', + 'paypal_amount' => '9.99', + 'paypal_item_name' => 'Gold', + 'currency' => 'USD', + 'repeat_time' => 'M', + 'paypal_stop_email' => 1, + ) + ), + ) + ); + $email_control = FrmFormActionsController::get_form_actions( 'email' ); + $email = $email_control->prepare_new( $form_id ); + $email->post_content['event'] = array( 'create', 'update', 'payment-success' ); + $email_id = $email_control->save_settings( $email ); + $other = $email_control->prepare_new( $form_id ); + $other->post_content['event'] = array( 'update' ); + $other_id = $email_control->save_settings( $other ); + FrmFormAction::clear_cache(); + + $result = FrmPayPalLiteLegacyMigrationHelper::migrate( $legacy_id ); + $this->assertIsArray( $result, 'A valid legacy action should convert.' ); + $payment = get_post( $result['action_id'] ); + $settings = json_decode( $payment->post_content, true ); + $this->assertSame( 'payment', $payment->post_excerpt, 'The new action should use Commerce.' ); + $this->assertSame( array( 'paypal' ), $settings['gateway'], 'The converted action should use PayPal.' ); + $this->assertSame( 'recurring', $settings['type'], 'Subscriptions should remain recurring.' ); + $this->assertSame( '9.99', $settings['amount'], 'The saved amount should survive conversion.' ); + $this->assertSame( 'month', $settings['interval'], 'The billing period should survive conversion.' ); + $this->assertSame( 'draft', get_post_status( $legacy_id ), 'The legacy action should be disabled.' ); + $moved = json_decode( get_post( $email_id )->post_content, true ); + $this->assertSame( array( 'update', 'payment-success' ), $moved['event'], 'Only create should move, without duplicating payment-success.' ); + $unchanged = json_decode( get_post( $other_id )->post_content, true ); + $this->assertSame( array( 'update' ), $unchanged['event'], 'Emails without a create event should remain unchanged.' ); + $again = FrmPayPalLiteLegacyMigrationHelper::migrate( $legacy_id ); + $this->assertWPError( $again, 'A second conversion should be blocked.' ); + $this->assertSame( 'frm_paypal_migration_blocked', $again->get_error_code(), 'The existing Commerce action should prevent duplicates.' ); + } +} diff --git a/tests/phpunit/paypal/test_FrmPayPalLiteLegacyMigrationAjax.php b/tests/phpunit/paypal/test_FrmPayPalLiteLegacyMigrationAjax.php new file mode 100644 index 0000000000..3c78ccefee --- /dev/null +++ b/tests/phpunit/paypal/test_FrmPayPalLiteLegacyMigrationAjax.php @@ -0,0 +1,59 @@ +factory->user->create( array( 'role' => 'subscriber' ) ) ) as $user_id ) { + wp_set_current_user( $user_id ); + $_POST = array( + 'nonce' => wp_create_nonce( 'frm_ajax' ), + 'action_id' => 0, + ); + $this->_last_response = ''; + $response = $this->trigger_action( 'frm_paypal_migrate_legacy_action' ); + $this->assertStringNotContainsString( 'legacy PayPal action could not be found', $response, 'Unauthorized requests must stop before migration.' ); + $this->assertNotEmpty( $response, 'Unauthorized requests should receive a permission error.' ); + } + } + + /** + * Authorized users still need a nonce, then receive the migration result. + */ + public function test_migration_checks_the_nonce_before_processing() { + $user_id = $this->factory->user->create(); + $user = new WP_User( $user_id ); + $user->add_cap( 'frm_edit_forms' ); + wp_set_current_user( $user_id ); + + foreach ( array( '', 'wrong' ) as $nonce ) { + $_POST = array( + 'nonce' => $nonce, + 'action_id' => 0, + ); + $_REQUEST['nonce'] = $nonce; + $this->_last_response = ''; + $this->assertSame( '-1', $this->trigger_action( 'frm_paypal_migrate_legacy_action' ), 'Invalid nonces should stop migration.' ); + } + + $_POST = array( + 'nonce' => wp_create_nonce( 'frm_ajax' ), + 'action_id' => 0, + ); + $_REQUEST['nonce'] = $_POST['nonce']; + $this->_last_response = ''; + $response = json_decode( $this->trigger_action( 'frm_paypal_migrate_legacy_action' ), true ); + $this->assertFalse( $response['success'], 'An authorized request should report invalid action IDs.' ); + $this->assertStringContainsString( 'legacy PayPal action could not be found', $response['data']['message'], 'A valid nonce should reach the migration helper.' ); + } +}