diff --git a/DESIGN.md b/DESIGN.md index a7c76347f..a966729e5 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -75,3 +75,36 @@ screen. Explain token permissions, legacy-key migration, SSL contact email, resource IDs, extra domains and wildcard limitations beside the relevant form. Reuse the existing stacked, wrapping layout on desktop and mobile; no new styles or wizard steps are needed. Keep the access token in a password field. + +## Frontend customer accounts + +Keep account-wide membership, billing and invoices separate from site-specific +summary and limits. Account Summary must offer a sign-in link when logged out, +an owner-scoped site chooser before site selection, and a neutral no-sites state +instead of silently rendering nothing. Do not silently select the first site: +customers may own several. Once a site is selected, omit self-referential +"See More" links and show remaining trial days from the actual membership date. +Use the existing stacked widget styles on desktop and mobile, with native links +and wrapping site names; do not add fixed-width panels or a second design system. +Frontend account pages belong on the main site; customer-site admin Account +screens remain an alternative interface to the same membership. + +On combined pages, Manage must visibly land on the selected site's controls, +using a keyboard-focusable native fragment target (Account Summary is the +fallback). Your Sites clears selected-site context and returns to the page +permalink. Successful frontend deletion returns to the account landing page, +unless an explicit destination is configured; never retain a deleted-site URL. +Sites without a template initialize the selector to numeric zero so their first +selection exposes the same destructive-action confirmation as template changes. + +Payment-method changes must return from Stripe Billing Portal to the originating +account page, using a validated local destination. Show the subscription's card +override when present; otherwise show the customer's default payment method, +including after the portal clears an override while replacing the default card. + +Native account blocks share shortcode renderers, settings and ownership checks. +Load widget preview styles inside the block editor canvas, including iframe +editors. Numeric controls save integers and toggle defaults use booleans. Group +and Columns layouts must preserve nested element attributes during early setup, +especially the Checkout form slug. Editor previews use sample data; verify real +customer actions on the published page rather than treating a preview as proof. diff --git a/inc/admin-pages/class-payment-edit-admin-page.php b/inc/admin-pages/class-payment-edit-admin-page.php index 54ac3c95f..eb6e542e4 100644 --- a/inc/admin-pages/class-payment-edit-admin-page.php +++ b/inc/admin-pages/class-payment-edit-admin-page.php @@ -1186,10 +1186,11 @@ public function register_widgets(): void { 'confirm_membership' => [ 'type' => 'toggle', 'title' => __('Activate Membership?', 'ultimate-multisite'), - 'desc' => __('This payment belongs to a pending membership. If you toggle this option, this change in status will also apply to the membership. If any sites are pending, they are also going to be published automatically.', 'ultimate-multisite'), + 'desc' => __('This payment belongs to a membership that is not active yet. Enable this option to activate, renew or reactivate it when confirming the payment. Any pending sites will also be published automatically.', 'ultimate-multisite'), 'value' => 0, 'wrapper_html_attr' => [ - 'v-if' => 'status !== original_status && status === "completed" && membership_status === "pending"', + // Mirrors handle_save(): only a pending payment being completed can confirm a membership. + 'v-if' => 'original_status === "pending" && status === "completed" && membership_status !== "active" && membership_status !== "trialing"', 'v-cloak' => '1', ], ], @@ -1480,13 +1481,35 @@ public function handle_save(): bool { if ($should_confirm_membership && $membership) { $is_initial_payment = Membership_Status::PENDING === $membership->get_status() && 0 === $membership->get_times_billed(); + $is_addon_payment = $this->is_addon_payment($payment); - // The initial payment counts as a bill, but checkout already set its period. - $membership->add_to_times_billed(1); + if ( ! $is_addon_payment) { + // The initial payment counts as a bill, but checkout already set its period. + $membership->add_to_times_billed(1); + } if ($is_initial_payment) { $membership->set_status(Membership_Status::ACTIVE); $membership_saved = $membership->save(); + } elseif ($is_addon_payment) { + /* + * Add-ons are extras on the plan, not one of its billing cycles: lift + * the hold without moving the plan's period or its bill count. + */ + $membership->set_status(Membership_Status::ACTIVE); + $membership_saved = $membership->save(); + } elseif (in_array($membership->get_status(), [Membership_Status::CANCELLED, Membership_Status::EXPIRED], true)) { + /* + * A paid reactivation. Like the Stripe and PayPal gateways, use + * reactivate() so the cancellation date clears and the reactivation + * hooks fire. Cancelling clears the gateway: record how this + * membership was paid so the account page shows it. + */ + if ( ! $membership->get_gateway() && $payment->get_gateway()) { + $membership->set_gateway($payment->get_gateway()); + } + + $membership_saved = $membership->reactivate(false); } else { $membership_saved = $membership->renew(false, Membership_Status::ACTIVE); } @@ -1529,4 +1552,22 @@ public function handle_save(): bool { return $saved; } + + /** + * Checks whether a payment came from an add-on checkout. + * + * An add-on cart holds only the extras to add to a membership. Paying for it + * is not a billing cycle of the membership's plan. + * + * @since n.e.x.t + * + * @param \WP_Ultimo\Models\Payment $payment The payment. + * @return bool + */ + private function is_addon_payment($payment): bool { + + $cart = $payment->get_meta(Payment::META_ORIGINAL_CART); + + return $cart instanceof \WP_Ultimo\Checkout\Cart && 'addon' === $cart->get_cart_type(); + } } diff --git a/inc/builders/block-editor/assets/js/blocks.js b/inc/builders/block-editor/assets/js/blocks.js index 92be99e0e..6a3985ddd 100644 --- a/inc/builders/block-editor/assets/js/blocks.js +++ b/inc/builders/block-editor/assets/js/blocks.js @@ -109,7 +109,25 @@ const obj = {}; - obj[ field_slug ] = value; + if (field.type === 'number') { + + // NumberControl emits strings, and '' while cleared; the block schema requires integers. + const number = parseInt(value, 10); + + // Keep the last valid number rather than saving an invalid one mid-edit. + if (Number.isNaN(number)) { + + return; + + } + + obj[ field_slug ] = number; + + } else { + + obj[ field_slug ] = value; + + } props.setAttributes(obj); diff --git a/inc/builders/block-editor/assets/js/blocks.min.js b/inc/builders/block-editor/assets/js/blocks.min.js index 3b527ef3a..918c39a19 100644 --- a/inc/builders/block-editor/assets/js/blocks.min.js +++ b/inc/builders/block-editor/assets/js/blocks.min.js @@ -1 +1 @@ -((e,p,c,d)=>{let h=p.createElement,l=e.registerBlockType,o=wp.serverSideRender,g=wp.components.PanelBody,m=wp.components.TextControl,w=wp.components.__experimentalNumberControl,b=wp.components.RangeControl,v=wp.components.ToggleControl,f=wp.components.TextareaControl,y=wp.components.Notice,k=wp.components.SelectControl,C=wp.blockEditor.InspectorControls,_=wp.compose.useDebounce||(e=>e);function x(t){let[e,n]=p.useState("");return h(m,{label:t.label,value:e,onChange(e){n(e),t.onSearch(e)}})}function R(t){var[e,n]=p.useState(""),n=_(n,300),l=String(t.value||0);let s=Number(l)||0,r=e.trim();e=wp.data.useSelect(function(e){var t=e("core"),e=e("core/editor"),e=e&&e.getCurrentPostId?Number(e.getCurrentPostId()):0,n={status:"publish",per_page:20,_fields:"id,title",search:r,search_columns:"post_title"},l=["postType","page",s,{_fields:"id,title,status"}],o=["postType","page",n],i=2<=r.length,n=(0{let i=[],a=[],s=null,r=null,u=!1,p=!0;return d.each(e,function(e,n){"group"===e.type&&(t=e.fields,(e=d.first(d.values(t))).desc="",n=d.first(d.keys(t)));var t=e.page_search?R:((e,t)=>{let n=m;switch(e){case"toggle":n=v;break;case"number":n=t.max&&t.min?b:w;break;case"textarea":n=f;break;case"select":n=k;break;case"note":n=y;break;default:n=m}return n})(e.type,e);d.isObject(e.required)||(e.required={});let l=!0;d.each(e.required,function(e,t){l=o.attributes[t]==e}),l&&a.push(h(t,{key:n,label:e.title,help:e.desc,value:o.attributes[n],checked:o.attributes[n],options:(e=>{let n=[];return d.each(e,function(e,t){n.push({label:e,value:t})}),n})(e.options),placeholder:e.placeholder,min:e.min,max:e.max,onChange(e){var t={};t[n]=e,o.setAttributes(t)}})),"header"===e.type&&(a.pop(),(u=null!==s?!0:u)&&(i.push(h(g,{key:r,title:s.title,description:s.desc,initialOpen:p},a)),p=!1),s=e,r=n,a=[])}),i.push(h(g,{key:r,title:s.title,help:s.desc,initialOpen:p},a)),h(C,{key:"wp-ultimo"},i)})(t.fields,e)]},save(){return null}})})})(window.wp.blocks,window.wp.element,window.wp.components,window._); \ No newline at end of file +((e,p,c,d)=>{let h=p.createElement,l=e.registerBlockType,i=wp.serverSideRender,m=wp.components.PanelBody,g=wp.components.TextControl,w=wp.components.__experimentalNumberControl,b=wp.components.RangeControl,v=wp.components.ToggleControl,f=wp.components.TextareaControl,y=wp.components.Notice,k=wp.components.SelectControl,C=wp.blockEditor.InspectorControls,_=wp.compose.useDebounce||(e=>e);function x(t){let[e,n]=p.useState("");return h(g,{label:t.label,value:e,onChange(e){n(e),t.onSearch(e)}})}function R(t){var[e,n]=p.useState(""),n=_(n,300),l=String(t.value||0);let s=Number(l)||0,r=e.trim();e=wp.data.useSelect(function(e){var t=e("core"),e=e("core/editor"),e=e&&e.getCurrentPostId?Number(e.getCurrentPostId()):0,n={status:"publish",per_page:20,_fields:"id,title",search:r,search_columns:"post_title"},l=["postType","page",s,{_fields:"id,title,status"}],i=["postType","page",n],o=2<=r.length,n=(0{let t=[],a=[],s=null,r=null,u=!1,p=!0;return d.each(e,function(l,i){"group"===l.type&&(e=l.fields,(l=d.first(d.values(e))).desc="",i=d.first(d.keys(e)));var e=l.page_search?R:((e,t)=>{let n=g;switch(e){case"toggle":n=v;break;case"number":n=t.max&&t.min?b:w;break;case"textarea":n=f;break;case"select":n=k;break;case"note":n=y;break;default:n=g}return n})(l.type,l);d.isObject(l.required)||(l.required={});let n=!0;d.each(l.required,function(e,t){n=o.attributes[t]==e}),n&&a.push(h(e,{key:i,label:l.title,help:l.desc,value:o.attributes[i],checked:o.attributes[i],options:(e=>{let n=[];return d.each(e,function(e,t){n.push({label:e,value:t})}),n})(l.options),placeholder:l.placeholder,min:l.min,max:l.max,onChange(e){var t={};if("number"===l.type){var n=parseInt(e,10);if(Number.isNaN(n))return;t[i]=n}else t[i]=e;o.setAttributes(t)}})),"header"===l.type&&(a.pop(),(u=null!==s?!0:u)&&(t.push(h(m,{key:r,title:s.title,description:s.desc,initialOpen:p},a)),p=!1),s=l,r=i,a=[])}),t.push(h(m,{key:r,title:s.title,help:s.desc,initialOpen:p},a)),h(C,{key:"wp-ultimo"},t)})(t.fields,e)]},save(){return null}})})})(window.wp.blocks,window.wp.element,window.wp.components,window._); \ No newline at end of file diff --git a/inc/builders/block-editor/class-block-editor-widget-manager.php b/inc/builders/block-editor/class-block-editor-widget-manager.php index 1a5e89ec0..1a312da59 100644 --- a/inc/builders/block-editor/class-block-editor-widget-manager.php +++ b/inc/builders/block-editor/class-block-editor-widget-manager.php @@ -125,6 +125,7 @@ public function register_block($element): void { [ 'attributes' => $attributes, 'editor_script' => 'wu-blocks', + 'editor_style' => 'wu-admin', 'render_callback' => \Closure::fromCallable([$element, 'get_content']), ] ); @@ -236,9 +237,21 @@ public function get_attributes_from_fields($element) { } $default_value = wu_get_isset($defaults, $field_id, ''); + $value = wu_get_isset($field, 'value', $default_value); + + // Block defaults must have the same types as their REST schema. + if ( ! is_callable($value)) { + if ('boolean' === $type) { + $value = (bool) $value; + } elseif ('integer' === $type) { + $value = (int) $value; + } else { + $value = (string) $value; + } + } $_fields[ $field_id ] = [ - 'default' => wu_get_isset($field, 'value', $default_value), + 'default' => $value, 'type' => $type, ]; } diff --git a/inc/class-current.php b/inc/class-current.php index 1acaa2786..3d5e170e1 100644 --- a/inc/class-current.php +++ b/inc/class-current.php @@ -232,20 +232,37 @@ public static function get_manage_url($id, $type = 'site') { $site_hash = \WP_Ultimo\Helpers\Hash::encode($id, $type); if ( ! is_admin()) { - $current_url = rtrim((string) wu_get_current_url(), '/'); - $url_param = self::param_key($type); + $remove = 'site' === $type ? [$url_param, self::param_key('membership')] : [$url_param]; + $url = remove_query_arg($remove, (string) wu_get_current_url()); + $parts = wp_parse_url($url); + $suffix = empty($parts['query']) ? '' : '?' . $parts['query']; + $fragment = empty($parts['fragment']) ? '' : '#' . $parts['fragment']; + $post = get_post(); + + // On combined account pages, land on the controls that actually changed. + if ('site' === $type && $post) { + if (has_shortcode($post->post_content, 'wu_current_site') || has_block('wp-ultimo/current-site', $post)) { + $fragment = '#wu-site-' . $site_hash; + } elseif (has_shortcode($post->post_content, 'wu_account_summary') || has_block('wp-ultimo/account-summary', $post)) { + $fragment = '#wu-summary-' . $site_hash; + } + } /* - * Check if the current URL already has a site parameter and remove it. + * Replace the trailing context in the path, not inside the query string. + * Site selection also clears membership context so the site's own + * membership is selected, rather than one left over from another site. */ - if (str_contains($current_url, '/' . $url_param . '/')) { - $current_url = preg_replace('/\/' . $url_param . '\/(.+)/', '/', $current_url); - } + $current_url = preg_replace('/[?#].*$/', '', $url); + $current_url = preg_replace('/\/' . preg_quote($url_param, '/') . '\/[^\/]+\/?$/', '', $current_url); + $current_url = rtrim($current_url, '/'); - $pretty_url = $current_url . '/' . $url_param . '/' . $site_hash; + $pretty_url = $current_url . '/' . $url_param . '/' . $site_hash . $suffix . $fragment; - $manage_site_url = get_option('permalink_structure') ? $pretty_url : add_query_arg($url_param, $site_hash); + $plain_url = add_query_arg($url_param, $site_hash, preg_replace('/#.*$/', '', $url)) . $fragment; + + $manage_site_url = get_option('permalink_structure') ? $pretty_url : $plain_url; } else { $manage_site_url = get_admin_url($id); } @@ -280,6 +297,17 @@ public function load_currents(): void { return; } + // Never retain an earlier context when a later URL override is rejected. + $this->site = false; + $this->customer = false; + $this->membership = false; + $this->site_set_via_request = false; + $this->customer_set_via_request = false; + $this->membership_set_via_request = false; + $site_set_via_request = false; + $customer_set_via_request = false; + $membership_set_via_request = false; + /* * `get_query_var()` reads from the global `$wp_query`, which * WordPress only populates during `parse_query` (just before @@ -322,21 +350,23 @@ public function load_currents(): void { $site_hash = wu_request($site_url_param, $site_hash_default); - $site_from_url = wu_get_site_by_hash($site_hash); + if ($site_hash) { + if ( ! is_string($site_hash)) { + return; + } - if ($site_from_url) { - $this->site_set_via_request = true; + $site = wu_get_site_by_hash($site_hash); - $site = $site_from_url; + if ( ! $this->can_access_context($site)) { + return; + } + + $site_set_via_request = true; } } else { $site = wu_get_current_site(); } - if ($site) { - $this->set_site($site); - } - $customer = wu_get_current_customer(); /** @@ -348,17 +378,23 @@ public function load_currents(): void { */ $customer_url_param = self::param_key('customer'); - $customer_from_url = wu_get_customer(wu_request($customer_url_param, 0)); + $customer_id = wu_request($customer_url_param, 0); + + if ($customer_id) { + if ( ! is_scalar($customer_id) || ! ctype_digit((string) $customer_id)) { + return; + } - if ($customer_from_url) { - $this->customer_set_via_request = true; + $customer = wu_get_customer($customer_id); - $customer = $customer_from_url; + if ( ! $this->can_access_context($customer)) { + return; + } + + $customer_set_via_request = true; } } - $this->set_customer($customer); - $membership = false; /* @@ -371,9 +407,17 @@ public function load_currents(): void { $membership_hash = wu_request($membership_url_param, $membership_hash_default); if ($membership_hash) { - $this->membership_set_via_request = true; + if ( ! is_string($membership_hash)) { + return; + } $membership = wu_get_membership_by_hash($membership_hash); + + if ( ! $this->can_access_context($membership)) { + return; + } + + $membership_set_via_request = true; } elseif ($site) { $membership = $site->get_membership(); } @@ -384,9 +428,47 @@ public function load_currents(): void { $membership = wu_get_isset($memberships, 0, false); } + if ($membership && ! $this->can_access_context($membership)) { + return; + } + + $this->site_set_via_request = $site_set_via_request; + $this->customer_set_via_request = $customer_set_via_request; + $this->membership_set_via_request = $membership_set_via_request; + + $this->set_site($site); + $this->set_customer($customer); $this->set_membership($membership); } + /** + * Authorizes account context against the authenticated user, never URL state. + * + * Hashes select objects; they are not access credentials. Pass an explicit + * customer ID to the model checks to avoid resolving this singleton again. + * + * @param \WP_Ultimo\Models\Customer|\WP_Ultimo\Models\Site|\WP_Ultimo\Models\Membership|false $context Requested object. + * @return bool + */ + private function can_access_context($context): bool { + + if ( ! $context || ! is_user_logged_in()) { + return false; + } + + if (current_user_can('manage_network')) { + return true; + } + + if ($context instanceof \WP_Ultimo\Models\Customer) { + return (int) $context->get_user_id() === get_current_user_id(); + } + + $customer = wu_get_current_customer(); + + return $customer && $context->is_customer_allowed($customer->get_id()); + } + /** * Get the current site instance. * diff --git a/inc/gateways/class-base-stripe-gateway.php b/inc/gateways/class-base-stripe-gateway.php index 95d6a627c..3161b8bca 100644 --- a/inc/gateways/class-base-stripe-gateway.php +++ b/inc/gateways/class-base-stripe-gateway.php @@ -820,15 +820,43 @@ public function get_change_payment_method_url($membership) { return null; } + $current_url = wu_get_current_url(); + + // Return to the page that asked for it, or to this one when the request names none. + $return_url = $this->get_requested_return_url() ?: $current_url; + return add_query_arg( [ 'wu-stripe-portal' => true, 'membership' => $membership->get_hash(), + // Encoded: the page has its own query string, which must not leak into this link. + 'redirect_url' => rawurlencode(wp_validate_redirect($return_url, $current_url)), ], home_url('/') ); } + /** + * Reads the page to return to after the Billing Portal from the request. + * + * Not wu_request(): it sanitizes with sanitize_text_field(), which strips + * percent-encoded octets such as those in non-ASCII slugs. esc_url_raw() + * keeps them. Callers must still validate the result with wp_validate_redirect(). + * + * @since n.e.x.t + * @return string The requested URL, or an empty string. + */ + private function get_requested_return_url(): string { + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigation target only; validated by the caller. + if ( ! isset($_REQUEST['redirect_url']) || ! is_string($_REQUEST['redirect_url'])) { + return ''; + } + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigation target only; validated by the caller. + return esc_url_raw(wp_unslash($_REQUEST['redirect_url'])); + } + /** * Returns payment method display info from the Stripe subscription. * @@ -848,11 +876,20 @@ public function get_payment_method_display($membership) { $subscription = $this->get_stripe_client()->subscriptions->retrieve( $sub_id, - ['expand' => ['default_payment_method']] + ['expand' => ['default_payment_method', 'customer.invoice_settings.default_payment_method']] ); $pm = $subscription->default_payment_method; + /* + * Portal updates may clear the subscription override to use the customer + * default. A legacy default_source takes precedence over that default + * when Stripe charges, so show no card rather than a different one. + */ + if ( ! $pm && empty($subscription->default_source)) { + $pm = $subscription->customer->invoice_settings->default_payment_method ?? null; + } + if ( ! $pm || ! $pm->card) { return null; } @@ -906,12 +943,14 @@ public function maybe_redirect_to_portal(): void { $s_customer_id = $membership->get_gateway_customer_id(); $stored_redirect = get_user_meta(get_current_user_id(), '_wu_change_payment_redirect', true); + $redirect_url = $this->get_requested_return_url() ?: $stored_redirect; + $fallback_url = remove_query_arg(['wu-stripe-portal', 'redirect_url'], wu_get_current_url()); - if ($stored_redirect) { + if ($redirect_url && is_string($redirect_url)) { delete_user_meta(get_current_user_id(), '_wu_change_payment_redirect'); - $return_url = add_query_arg('updated', 'payment_method', $stored_redirect); + $return_url = add_query_arg('updated', 'payment_method', wp_validate_redirect($redirect_url, $fallback_url)); } else { - $return_url = remove_query_arg('wu-stripe-portal', wu_get_current_url()); + $return_url = $fallback_url; } try { diff --git a/inc/gateways/class-manual-gateway.php b/inc/gateways/class-manual-gateway.php index 623ef28bb..ce34cf573 100644 --- a/inc/gateways/class-manual-gateway.php +++ b/inc/gateways/class-manual-gateway.php @@ -160,7 +160,7 @@ public function get_amount_update_message($to_customer = false) { * @param \WP_Ultimo\Models\Membership $membership The membership. * @param \WP_Ultimo\Models\Customer $customer The customer checking out. * @param \WP_Ultimo\Checkout\Cart $cart The cart object. - * @param string $type The checkout type. Can be 'new', 'retry', 'upgrade', 'downgrade', 'addon'. + * @param string $type The checkout type. Can be 'new', 'retry', 'upgrade', 'downgrade', 'addon', 'reactivation'. * * @throws \Exception When saving a membership fails. */ @@ -190,6 +190,10 @@ public function process_checkout($payment, $membership, $customer, $cart, $type) * - downgrade: @see upgrade. * - retry: This cart is created when a customer tries to settle a pending or failed payment. * - addon: Contains only services or packages that should be added to the membership in question. + * - reactivation: A cancelled or expired membership being paid for again. Nothing changes + * here on purpose: on-hold counts as active, so moving the membership there + * would restore access before the payment is confirmed. The administrator's + * confirmation reactivates it (Payment_Edit_Admin_Page::handle_save()). */ $status = true; @@ -215,13 +219,7 @@ public function process_checkout($payment, $membership, $customer, $cart, $type) * simply throw a exception and Ultimate Multisite will * catch it and rollback any changes. */ - if ('new' === $type) { - - // Your logic here. - } elseif ('renewal' === $type) { - - // Your logic here. - } elseif ('downgrade' === $type) { + if ('downgrade' === $type) { /* * When downgrading, we need to schedule a swap for the end of the * current expiration date. @@ -256,6 +254,17 @@ public function process_checkout($payment, $membership, $customer, $cart, $type) */ $membership->swap($cart); + /* + * A manually paid plan change is invoiced manually from now on, so the + * membership must use this gateway and stop auto-renewing elsewhere. + * Add-ons are extra items on the existing subscription: they keep its + * recurring gateway and renewal setting. + */ + if ('upgrade' === $type) { + $membership->set_gateway($this->get_id()); + $membership->set_auto_renew(false); + } + /* * Mark the membership as pending, as we need to * wait for the payment confirmation. @@ -333,7 +342,8 @@ public function process_cancellation($membership, $customer) {} * @param \WP_Ultimo\Models\Payment $payment The payment associated with the checkout. * @param \WP_Ultimo\Models\Membership $membership The membership. * @param \WP_Ultimo\Models\Customer $customer The customer checking out. - * @return void|bool + * @throws \Exception When the refund fails. + * @return void */ public function process_refund($amount, $payment, $membership, $customer): void { diff --git a/inc/ui/class-account-summary-element.php b/inc/ui/class-account-summary-element.php index b7dc1a034..09d2c8828 100644 --- a/inc/ui/class-account-summary-element.php +++ b/inc/ui/class-account-summary-element.php @@ -121,7 +121,7 @@ public function get_title() { */ public function get_description() { - return __('Displays a summary of the customer\'s account including membership and site overview.', 'ultimate-multisite'); + return __('Displays the selected site\'s plan, trial time and disk usage. On the main-site frontend, customers can select a site to view its summary.', 'ultimate-multisite'); } /** @@ -220,7 +220,11 @@ public function setup() { $this->site = WP_Ultimo()->currents->get_site(); - if ( ! $this->site || ! $this->site->is_customer_allowed()) { + if ( ! $this->site) { + return; + } + + if ( ! $this->site->is_customer_allowed()) { $this->set_display(false); return; @@ -240,8 +244,18 @@ public function setup() { is_multisite() && restore_current_blog(); + $trial_days = 0; + + if ($this->membership && 'trialing' === $this->membership->get_status()) { + $trial_end = strtotime($this->membership->get_date_trial_end() . ' UTC'); + + if ($trial_end) { + $trial_days = max(0, (int) ceil(($trial_end - time()) / DAY_IN_SECONDS)); + } + } + $this->atts = [ - 'site_trial' => 0, // @todo: fix this + 'site_trial' => $trial_days, 'space_used' => $space_used, 'space_allowed' => $space_allowed, 'percentage' => $percentage, @@ -298,8 +312,15 @@ public function output($atts, $content = null) { $this->ensure_setup(); - // Return empty if no site available (e.g., during SEO processing) if ( ! $this->site) { + if ( ! is_admin()) { + $customer = WP_Ultimo()->currents->get_customer(); + + $atts['sites'] = $customer ? $customer->get_sites() : []; + + wu_get_template('dashboard-widgets/account-summary-empty', $atts); + } + return; } @@ -311,6 +332,8 @@ public function output($atts, $content = null) { $atts['product'] = $this->product; + $atts['hide_manage_link'] = WP_Ultimo()->currents->is_site_set_via_request(); + wu_get_template('dashboard-widgets/account-summary', $atts); } diff --git a/inc/ui/class-base-element.php b/inc/ui/class-base-element.php index 1edd6024b..0196601a3 100644 --- a/inc/ui/class-base-element.php +++ b/inc/ui/class-base-element.php @@ -573,10 +573,15 @@ protected function maybe_extract_arguments($content, $type = 'shortcode') { */ $block_content = parse_blocks($content); - foreach ($block_content as $block) { + while ($block_content) { + $block = array_shift($block_content); + if ($this->get_id() === $block['blockName']) { return $block['attrs']; } + + // Groups and Columns are normal account-page layout containers. + $block_content = array_merge($block['innerBlocks'] ?? [], $block_content); } return false; diff --git a/inc/ui/class-billing-info-element.php b/inc/ui/class-billing-info-element.php index fea1724b4..8f97a166d 100644 --- a/inc/ui/class-billing-info-element.php +++ b/inc/ui/class-billing-info-element.php @@ -323,7 +323,12 @@ public function render_update_billing_address() { $membership = wu_get_membership_by_hash(wu_request('membership')); - if ( ! $membership) { + /* + * The form pre-fills the saved billing address, so it needs the same + * ownership check as the handler. Missing and foreign records get the + * same empty response, which does not reveal whether a hash exists. + */ + if ( ! $membership || ! $membership->is_customer_allowed()) { return; } diff --git a/inc/ui/class-current-site-element.php b/inc/ui/class-current-site-element.php index d38bfc3e0..eba8d68e8 100644 --- a/inc/ui/class-current-site-element.php +++ b/inc/ui/class-current-site-element.php @@ -384,7 +384,7 @@ public function output($atts, $content = null) { $my_sites_id = $atts['breadcrumbs_my_sites_page']; - $my_sites_url = empty($my_sites_id) ? remove_query_arg('site') : get_page_link($my_sites_id); + $my_sites_url = empty($my_sites_id) ? get_permalink() : get_page_link($my_sites_id); $atts['my_sites_url'] = is_admin() ? admin_url('admin.php?page=sites') : $my_sites_url; @@ -401,7 +401,12 @@ public function render_edit_site() { $site = wu_get_site_by_hash(wu_request('site')); - if ( ! $site) { + /* + * The form pre-fills the site title and description, so it needs the + * same ownership check as the handler. Missing and foreign records get + * the same empty response, which does not reveal whether a hash exists. + */ + if ( ! $site || ! $site->is_customer_allowed()) { return; } diff --git a/inc/ui/class-payment-methods-element.php b/inc/ui/class-payment-methods-element.php index 651d0b387..47e3aec6f 100644 --- a/inc/ui/class-payment-methods-element.php +++ b/inc/ui/class-payment-methods-element.php @@ -194,7 +194,7 @@ public function output($atts, $content = null) { $gateway_display = ''; if ($gateway) { - $gateway_display = $gateway->get_title(); + $gateway_display = $gateway->get_public_title(); $payment_info = $gateway->get_payment_method_display($this->membership); $change_url = $gateway->get_change_payment_method_url($this->membership); } diff --git a/inc/ui/class-site-actions-element.php b/inc/ui/class-site-actions-element.php index 13cc498ee..c05ede961 100644 --- a/inc/ui/class-site-actions-element.php +++ b/inc/ui/class-site-actions-element.php @@ -444,7 +444,7 @@ public function get_actions($atts) { 'change_payment_method', [ 'membership' => $this->membership->get_hash(), - 'redirect_url' => wu_get_current_url(), + 'redirect_url' => $this->get_encoded_current_url(), ] ), ]; @@ -454,6 +454,21 @@ public function get_actions($atts) { return apply_filters('wu_element_get_site_actions', $actions, $atts, $this->site, $this->membership); } + /** + * Returns the current page URL, encoded to travel inside a form link. + * + * Form links are built with add_query_arg(), which does not encode values. + * A page with its own query string would otherwise leak that string into + * the form link and lose everything after the first "&" on the way back. + * + * @since n.e.x.t + * @return string + */ + private function get_encoded_current_url(): string { + + return rawurlencode(wu_get_current_url()); + } + /** * Returns the danger actions actions for the element. These can be filtered. * @@ -476,7 +491,7 @@ public function get_danger_zone_actions($atts) { 'delete_site', [ 'site' => $this->site->get_hash(), - 'redirect_url' => ! $atts['redirect_after_delete'] ? false : get_page_link($atts['redirect_after_delete']), + 'redirect_url' => $atts['redirect_after_delete'] ? get_page_link($atts['redirect_after_delete']) : (is_admin() ? user_admin_url() : get_permalink()), ] ), ], @@ -496,7 +511,7 @@ public function get_danger_zone_actions($atts) { 'cancel_membership', [ 'membership' => $this->membership->get_hash(), - 'redirect_url' => wu_get_current_url(), + 'redirect_url' => $this->get_encoded_current_url(), ] ), ], @@ -516,7 +531,7 @@ public function get_danger_zone_actions($atts) { 'resubscribe_membership', [ 'membership' => $this->membership->get_hash(), - 'redirect_url' => wu_get_current_url(), + 'redirect_url' => $this->get_encoded_current_url(), ] ), ], @@ -546,7 +561,8 @@ public function render_delete_site(): void { $customer = wu_get_current_customer(); - if ( ! $customer || $customer->get_id() !== $site->get_customer_id()) { + // A missing site has no owner to compare against. + if ( ! $error && (! $customer || $customer->get_id() !== $site->get_customer_id())) { $error = __('You are not allowed to do this.', 'ultimate-multisite'); } @@ -917,13 +933,7 @@ public function handle_change_email(): void { wp_send_json_error($user_id); } - // Update customer email if exists. - $customer = wu_get_current_customer(); - - if ($customer) { - $customer->set_email_address($new_email); - $customer->save(); - } + // Customer::get_email_address() reads the linked WordPress user's email. $referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_url(wp_unslash($_SERVER['HTTP_REFERER'])) : ''; @@ -1006,6 +1016,12 @@ public function handle_change_default_site(): void { $new_primary_site = wu_request('new_primary_site'); + if ( ! is_scalar($new_primary_site) || ! ctype_digit((string) $new_primary_site) || ! isset(get_blogs_of_user(get_current_user_id())[ (int) $new_primary_site ])) { + wp_send_json_error(new \WP_Error('invalid-site', __('Please select a site from your account.', 'ultimate-multisite'))); + + return; + } + if ($new_primary_site) { update_user_meta(get_current_user_id(), 'primary_blog', $new_primary_site); $referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_url(wp_unslash($_SERVER['HTTP_REFERER'])) : ''; @@ -1156,7 +1172,8 @@ public function render_cancel_membership(): void { $customer = wu_get_current_customer(); - if ( ! is_super_admin() && (! $customer || $customer->get_id() !== $membership->get_customer_id())) { + // A missing membership has no owner to compare against. + if ( ! $error && ! is_super_admin() && (! $customer || $customer->get_id() !== $membership->get_customer_id())) { $error = __('You are not allowed to do this.', 'ultimate-multisite'); } @@ -1317,7 +1334,21 @@ public function handle_cancel_membership(): void { 'other' => wu_request('cancellation_explanation'), ]; - $reason = wu_get_isset($cancellation_options, wu_request('cancellation_reason'), ''); + if (__('CANCEL', 'ultimate-multisite') !== wu_request('confirm')) { + wp_send_json_error(new \WP_Error('not-confirmed', __('Please type CANCEL to confirm the membership cancellation.', 'ultimate-multisite'))); + + return; + } + + $reason_key = wu_request('cancellation_reason', ''); + + if ( ! is_string($reason_key) || ! array_key_exists($reason_key, $cancellation_options)) { + wp_send_json_error(new \WP_Error('invalid-reason', __('Please select a cancellation reason.', 'ultimate-multisite'))); + + return; + } + + $reason = $cancellation_options[ $reason_key ]; try { /* * Cancel the subscription on the payment gateway before @@ -1383,7 +1414,8 @@ public function render_resubscribe_membership(): void { $customer = wu_get_current_customer(); - if ( ! is_super_admin() && (! $customer || $customer->get_id() !== $membership->get_customer_id())) { + // A missing membership has no owner to compare against. + if ( ! $error && ! is_super_admin() && (! $customer || $customer->get_id() !== $membership->get_customer_id())) { $error = __('You are not allowed to do this.', 'ultimate-multisite'); } @@ -1493,14 +1525,21 @@ public function handle_resubscribe_membership(): void { } /* - * Build the checkout URL pre-filled with the customer's previous plan. - * The products[] query parameter pre-selects the plan on the checkout form. + * Reuse the existing membership, rather than starting a new site signup. + * Reactivation carts restore the original products themselves. Passing + * product slugs in GET conflicts with the form's product IDs in POST. */ - $checkout_url = wu_get_registration_url(); + $checkout_url = wu_get_membership_update_url($membership); + + // Preselect the required product field without conflicting GET products. + $session = wu_get_session('signup'); + $signup = (array) $session->get('signup'); + $signup['products'] = [$plan->get_id()]; + $session->set('signup', $signup); + $session->commit(); $checkout_url = add_query_arg( [ - 'products[]' => $plan->get_slug(), 'wu_resubscribe' => $membership->get_hash(), ], $checkout_url diff --git a/inc/ui/class-template-switching-element.php b/inc/ui/class-template-switching-element.php index ea1bd2afd..71a4cd1e3 100644 --- a/inc/ui/class-template-switching-element.php +++ b/inc/ui/class-template-switching-element.php @@ -721,13 +721,13 @@ public function output($atts, $content = null) { * giving Vue a chance to bind it before the `template_id` * watcher runs. The watcher itself also defends against the * inverse ordering (see template-switching.js: it bails out - * early when original_template_id <= 0). + * early when original_template_id < 0). */ $checkout_fields['template_id'] = [ 'type' => 'hidden', 'html_attr' => [ - 'v-init:original_template_id' => $this->site->get_template_id(), - 'v-init:template_id' => $this->site->get_template_id(), + 'v-init:original_template_id' => $current_template_id, + 'v-init:template_id' => $current_template_id, 'v-model' => 'template_id', ], ]; diff --git a/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php b/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php index 2a8cf5fb2..d296a2524 100644 --- a/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php +++ b/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php @@ -745,7 +745,7 @@ public function test_handle_save_no_membership_renewal_when_absent(): void { * * @dataProvider manual_confirmation_periods */ - public function test_manual_confirmation_period(string $status, int $times_billed, bool $renews, bool $fail_first = false): void { + public function test_manual_confirmation_period(string $status, int $times_billed, bool $renews, bool $fail_first = false, bool $addon = false): void { $customer = wu_create_customer([ 'user_id' => self::factory()->user->create(), 'email_verification' => 'none', @@ -764,17 +764,22 @@ public function test_manual_confirmation_period(string $status, int $times_bille $this->assertNotWPError($product); // Keep the day low so adding one month cannot overflow a short month. $expiration = gmdate('Y-m-09 23:59:59', strtotime('+1 year')); - $membership = wu_create_membership([ + $membership_args = [ 'customer_id' => $customer->get_id(), 'plan_id' => $product->get_id(), - 'status' => $status, + // An add-on is bought while the membership runs; the Manual gateway then puts it on hold. + 'status' => $addon ? 'active' : $status, 'amount' => 29.99, 'recurring' => true, 'duration' => 1, 'duration_unit' => 'month', 'times_billed' => $times_billed, 'date_expiration' => $expiration, - ]); + ]; + if ('cancelled' === $status) { + $membership_args['date_cancellation'] = gmdate('Y-m-d H:i:s', strtotime('-1 week')); + } + $membership = wu_create_membership($membership_args); $this->assertNotWPError($membership); $payment = wu_create_payment([ 'customer_id' => $customer->get_id(), @@ -785,6 +790,36 @@ public function test_manual_confirmation_period(string $status, int $times_bille ]); $this->assertNotWPError($payment); + if ($addon) { + $extra = wu_create_product([ + 'name' => 'Manual Confirmation Add-on', + 'slug' => 'manual-confirmation-addon-' . wp_generate_password(8, false), + 'type' => 'service', + 'pricing_type' => 'paid', + 'amount' => 5.00, + 'recurring' => true, + 'duration' => 1, + 'duration_unit' => 'month', + 'active' => true, + ]); + $this->assertNotWPError($extra); + + // A cart only builds for the membership's own customer. One with only extras keeps that membership's plan, which makes it an add-on cart. + wp_set_current_user($customer->get_user_id()); + $cart = new \WP_Ultimo\Checkout\Cart([ + 'products' => [$extra->get_id()], + 'membership_id' => $membership->get_id(), + 'currency' => 'USD', + 'country' => 'US', + ]); + wp_set_current_user(0); + $this->assertSame('addon', $cart->get_cart_type()); + $payment->update_meta(Payment::META_ORIGINAL_CART, $cart); + + $membership->set_status($status); + $this->assertNotWPError($membership->save()); + } + $membership->create_pending_site([ 'title' => 'Manual Confirmation Site', 'path' => '/manual-confirmation-' . strtolower(wp_generate_password(8, false)) . '/', @@ -801,6 +836,8 @@ public function test_manual_confirmation_period(string $status, int $times_bille $_POST['status'] = Payment_Status::COMPLETED; $_REQUEST['status'] = Payment_Status::COMPLETED; $expected_expiration = $renews ? gmdate('Y-m-d H:i:s', strtotime('+1 month', strtotime($expiration))) : $expiration; + // An add-on payment is not a billing cycle of the plan. + $expected_billed = $addon ? $times_billed : $times_billed + 1; try { if ($fail_first) { @@ -822,11 +859,19 @@ public function test_manual_confirmation_period(string $status, int $times_bille $this->page->object = wu_get_payment($payment->get_id()); } + $reactivated_before = did_action('wu_membership_post_reactivate'); + $this->assertTrue($this->page->handle_save()); $membership = wu_get_membership($membership->get_id()); $this->assertSame('active', $membership->get_status()); + if ('cancelled' === $status) { + // A paid reactivation clears the cancellation, records how it was paid and fires the hooks once. + $this->assertEmpty($membership->get_date_cancellation()); + $this->assertSame('manual', $membership->get_gateway()); + $this->assertSame($reactivated_before + 1, did_action('wu_membership_post_reactivate')); + } $this->assertSame($expected_expiration, $membership->get_date_expiration()); - $this->assertSame($times_billed + 1, $membership->get_times_billed()); + $this->assertSame($expected_billed, $membership->get_times_billed()); $this->assertSame(Payment_Status::COMPLETED, wu_get_payment($payment->get_id())->get_status()); if ('pending' === $status) { $this->assertEmpty($membership->get_pending_site()); @@ -838,7 +883,7 @@ public function test_manual_confirmation_period(string $status, int $times_bille $this->assertTrue($this->page->handle_save()); $membership = wu_get_membership($membership->get_id()); $this->assertSame($expected_expiration, $membership->get_date_expiration()); - $this->assertSame($times_billed + 1, $membership->get_times_billed()); + $this->assertSame($expected_billed, $membership->get_times_billed()); } finally { remove_filter('wp_redirect', '__return_false'); wu_save_setting('force_publish_sites_sync', $force_sync); @@ -851,6 +896,9 @@ public function manual_confirmation_periods(): array { 'active renewal' => ['active', 1, true], 'pending billed renewal' => ['pending', 1, true], 'expired renewal' => ['expired', 1, true], + 'cancelled reactivation' => ['cancelled', 1, true], + 'on-hold renewal' => ['on-hold', 1, true], + 'on-hold add-on' => ['on-hold', 1, false, false, true], 'initial save retry' => ['pending', 0, false, true], 'renewal save retry' => ['active', 1, true, true], ]; diff --git a/tests/WP_Ultimo/Current_Test.php b/tests/WP_Ultimo/Current_Test.php index 279695fa5..d105b1f6d 100644 --- a/tests/WP_Ultimo/Current_Test.php +++ b/tests/WP_Ultimo/Current_Test.php @@ -440,4 +440,97 @@ public function test_load_currents_skips_rerun_during_ajax(): void { remove_filter('wp_doing_ajax', '__return_true'); } + + /** URL-selected account objects require the real owner's authentication. */ + public function test_request_context_requires_ownership(): void { + + $saved_current = clone $this->current; + $saved_user_id = get_current_user_id(); + $saved_hash = get_query_var('site_hash', ''); + $admin_id = 0; + + try { + $owner_id = self::factory()->user->create(['role' => 'subscriber']); + $stranger_id = self::factory()->user->create(['role' => 'subscriber']); + $admin_id = self::factory()->user->create(['role' => 'administrator']); + $customer = wu_create_customer(['user_id' => $owner_id]); + $stranger = wu_create_customer(['user_id' => $stranger_id]); + $this->assertNotWPError($customer); + $this->assertNotWPError($stranger); + + $membership = wu_create_membership( + [ + 'customer_id' => $customer->get_id(), + 'status' => 'active', + 'skip_validation' => true, + ] + ); + $this->assertNotWPError($membership); + + $site = wu_get_site(self::factory()->blog->create(['user_id' => $owner_id])); + $site->set_type('customer_owned'); + $site->set_customer_id($customer->get_id()); + $site->set_membership_id($membership->get_id()); + $this->assertNotWPError($site->save()); + + $this->go_to(home_url('/')); + set_current_screen('front'); + grant_super_admin($admin_id); + + foreach ([$owner_id, $stranger_id, 0, $admin_id] as $viewer_id) { + wp_set_current_user($viewer_id); + + foreach (['membership', 'site', 'pretty_site', 'customer', 'spoofed_customer'] as $context_type) { + $_GET = []; + $_REQUEST = []; + set_query_var('site_hash', ''); + + if ('pretty_site' === $context_type) { + set_query_var('site_hash', $site->get_hash()); + } elseif ('spoofed_customer' === $context_type) { + $_GET = [ + 'customer' => $customer->get_id(), + 'membership' => $membership->get_hash(), + ]; + } else { + $values = [ + 'membership' => $membership->get_hash(), + 'site' => $site->get_hash(), + 'customer' => $customer->get_id(), + ]; + $_GET = [$context_type => $values[$context_type]]; + } + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Synthetic request selection; ownership is the boundary under test. + $_REQUEST = $_GET; + $this->current->load_currents(); + + if (in_array($viewer_id, [$owner_id, $admin_id], true)) { + $this->assertSame($membership->get_id(), $this->current->get_membership()->get_id(), $context_type); + } else { + $this->assertFalse($this->current->get_membership(), $context_type); + $this->assertFalse($this->current->get_customer(), $context_type); + $this->assertFalse($this->current->get_site(), $context_type); + $this->assertFalse($this->current->is_site_set_via_request()); + $this->assertFalse($this->current->is_membership_set_via_request()); + } + } + } + } finally { + if ($admin_id) { + revoke_super_admin($admin_id); + } + + set_query_var('site_hash', $saved_hash); + wp_set_current_user($saved_user_id); + + // Do not leave the final synthetic membership in the shared singleton. + foreach ((new \ReflectionClass(Current::class))->getProperties() as $property) { + if ( ! $property->isStatic()) { + $property->setAccessible(true); + $property->setValue($this->current, $property->getValue($saved_current)); + } + } + } + } } diff --git a/tests/WP_Ultimo/Gateways/Base_Stripe_Gateway_Test.php b/tests/WP_Ultimo/Gateways/Base_Stripe_Gateway_Test.php index eea6912fd..37651c7ab 100644 --- a/tests/WP_Ultimo/Gateways/Base_Stripe_Gateway_Test.php +++ b/tests/WP_Ultimo/Gateways/Base_Stripe_Gateway_Test.php @@ -633,6 +633,51 @@ public function test_get_change_payment_method_url_returns_url(): void { $this->assertStringContainsString('abc123hash', $result); } + /** + * The portal link returns to the page that built it, whole. + * + * Without a requested return URL it falls back to the current page. With one, + * the URL's own query string must survive: add_query_arg() does not encode + * values, so the URL has to be encoded before it is nested in the link. + */ + public function test_get_change_payment_method_url_keeps_the_return_url(): void { + wu_save_setting('stripe_enable_portal', 1); + + $membership_mock = $this->getMockBuilder(\WP_Ultimo\Models\Membership::class) + ->disableOriginalConstructor() + ->onlyMethods(['get_gateway_subscription_id', 'get_hash']) + ->getMock(); + + $membership_mock->method('get_gateway_subscription_id')->willReturn('sub_test123'); + $membership_mock->method('get_hash')->willReturn('abc123hash'); + + $server = $_SERVER; + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Fixture: saves the incoming request to restore it. + $request = $_REQUEST; + + try { + $_SERVER['HTTP_HOST'] = 'example.org'; + $_SERVER['REQUEST_URI'] = '/account/?tab=billing'; + + unset($_REQUEST['redirect_url']); + + parse_str((string) wp_parse_url($this->gateway->get_change_payment_method_url($membership_mock), PHP_URL_QUERY), $query); + + $this->assertSame('http://example.org/account/?tab=billing', $query['redirect_url'], 'Without a requested return URL the link returns to the current page.'); + + $_REQUEST['redirect_url'] = 'http://example.org/account/?tab=billing&utm=a%26b'; + + parse_str((string) wp_parse_url($this->gateway->get_change_payment_method_url($membership_mock), PHP_URL_QUERY), $query); + + $this->assertSame('http://example.org/account/?tab=billing&utm=a%26b', $query['redirect_url']); + $this->assertSame('abc123hash', $query['membership']); + $this->assertArrayNotHasKey('utm', $query, 'The return URL\'s own query string must not leak into the link.'); + } finally { + $_SERVER = $server; + $_REQUEST = $request; + } + } + // ========================================================================= // get_payment_method_display // ========================================================================= diff --git a/tests/WP_Ultimo/Gateways/Manual_Gateway_Checkout_Process_Test.php b/tests/WP_Ultimo/Gateways/Manual_Gateway_Checkout_Process_Test.php index a43402439..da5d7a9e4 100644 --- a/tests/WP_Ultimo/Gateways/Manual_Gateway_Checkout_Process_Test.php +++ b/tests/WP_Ultimo/Gateways/Manual_Gateway_Checkout_Process_Test.php @@ -206,6 +206,135 @@ public function test_process_checkout(string $type, bool $recurring, bool $trial $second_product->delete(); } + /** + * Builds a membership, a pending manual payment and a cart for one scenario. + * + * @param string $slug Unique plan slug. + * @param string $cart_type Cart type to build. + * @param array $membership_args Membership attributes. + * @return array{0: \WP_Ultimo\Models\Membership, 1: \WP_Ultimo\Models\Payment, 2: \WP_Ultimo\Checkout\Cart} + */ + private function build_checkout(string $slug, string $cart_type, array $membership_args): array { + + $customer = self::$customer; + + wp_set_current_user($customer->get_user_id(), $customer->get_username()); + + $product = wu_create_product( + [ + 'name' => $slug, + 'slug' => $slug, + 'amount' => 50.00, + 'recurring' => true, + 'duration' => 1, + 'duration_unit' => 'month', + 'type' => 'plan', + 'pricing_type' => 'paid', + 'active' => true, + ] + ); + + $membership = wu_create_membership( + array_merge( + [ + 'customer_id' => $customer->get_id(), + 'plan_id' => $product->get_id(), + 'recurring' => true, + ], + $membership_args + ) + ); + + $this->assertNotWPError($membership); + + $cart = new \WP_Ultimo\Checkout\Cart( + [ + 'cart_type' => $cart_type, + 'products' => [$product->get_id()], + 'duration' => 1, + 'duration_unit' => 'month', + 'membership_id' => $membership->get_id(), + 'currency' => 'USD', + 'country' => 'US', + ] + ); + + $payment = wu_create_payment( + [ + 'customer_id' => $customer->get_id(), + 'membership_id' => $membership->get_id(), + 'gateway' => 'manual', + 'status' => Payment_Status::PENDING, + 'total' => 50.00, + ] + ); + + return [$membership, $payment, $cart]; + } + + /** + * On-hold counts as active, so a reactivation must not restore access + * before an administrator confirms the payment. + */ + public function test_reactivation_keeps_the_membership_inactive_until_payment_is_confirmed(): void { + + [$membership, $payment, $cart] = $this->build_checkout( + 'manual-reactivation-plan', + 'upgrade', + ['status' => Membership_Status::CANCELLED] + ); + + $this->gateway->process_checkout($payment, $membership, self::$customer, $cart, 'reactivation'); + + $reloaded = wu_get_membership($membership->get_id()); + + $this->assertSame(Membership_Status::CANCELLED, $reloaded->get_status()); + $this->assertFalse($reloaded->is_active(), 'Access must wait for the payment confirmation.'); + $this->assertSame(Payment_Status::PENDING, $payment->get_status()); + } + + /** + * An add-on is an extra item on the existing subscription: paying for it + * manually must not move the membership off its recurring gateway. + */ + public function test_addon_keeps_the_existing_recurring_gateway(): void { + + [$membership, $payment, $cart] = $this->build_checkout( + 'manual-addon-plan', + 'addon', + [ + 'status' => Membership_Status::ACTIVE, + 'gateway' => 'free', + ] + ); + + $this->gateway->process_checkout($payment, $membership, self::$customer, $cart, 'addon'); + + $this->assertSame('free', wu_get_membership($membership->get_id())->get_gateway()); + } + + /** + * A manually paid plan change is invoiced manually from now on. + */ + public function test_upgrade_moves_the_membership_to_the_manual_gateway(): void { + + [$membership, $payment, $cart] = $this->build_checkout( + 'manual-upgrade-plan', + 'upgrade', + [ + 'status' => Membership_Status::ACTIVE, + 'gateway' => 'free', + ] + ); + + $this->gateway->process_checkout($payment, $membership, self::$customer, $cart, 'upgrade'); + + $reloaded = wu_get_membership($membership->get_id()); + + $this->assertSame('manual', $reloaded->get_gateway()); + $this->assertFalse($reloaded->should_auto_renew()); + } + public function tearDown(): void { parent::tearDown(); diff --git a/views/dashboard-widgets/account-summary-empty.php b/views/dashboard-widgets/account-summary-empty.php new file mode 100644 index 000000000..5ab0adaf1 --- /dev/null +++ b/views/dashboard-widgets/account-summary-empty.php @@ -0,0 +1,33 @@ + +
+
+ +

+ + +

+ + +

+ + +
+
diff --git a/views/dashboard-widgets/account-summary.php b/views/dashboard-widgets/account-summary.php index bf6a38b6c..d3d625224 100644 --- a/views/dashboard-widgets/account-summary.php +++ b/views/dashboard-widgets/account-summary.php @@ -6,8 +6,9 @@ */ defined('ABSPATH') || exit; +// phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase -- className is the shared block/template attribute. ?> -
+
@@ -24,7 +25,7 @@ - +
diff --git a/views/dashboard-widgets/current-site.php b/views/dashboard-widgets/current-site.php index 152332c34..c8ee236a4 100644 --- a/views/dashboard-widgets/current-site.php +++ b/views/dashboard-widgets/current-site.php @@ -7,7 +7,7 @@ defined('ABSPATH') || exit; ?> -
+
diff --git a/views/shortcodes/shortcodes.php b/views/shortcodes/shortcodes.php index 8f38792db..2d9d1302e 100644 --- a/views/shortcodes/shortcodes.php +++ b/views/shortcodes/shortcodes.php @@ -15,6 +15,26 @@
+
+
+

+

+
[wu_account_summary]
+[wu_current_membership]
+[wu_billing_info]
+[wu_payment_methods]
+[wu_invoices]
+[wu_current_site]
+[wu_limits]
+[wu_site_actions]
+

+

Memberships > Default Membership Update Page.', 'ultimate-multisite'); ?>

+

[wu_checkout slug="wu-checkout"]

+

+

+
+
+