Files
Geoff TaylorandGitHub 460b101b47 fix: HPOS order mutation data loss, COT cursor pagination, email tests, checkout auth (#1003)
* devops: WC email template tests, COT cursor HPOS fix, checkout account auth

WC Email Template Tests:
- Add WooCommerceEmailTemplatesTest verifying WC email templates are used
  for registerCustomer, checkout with account creation, and password reset
- Use MockPHPMailer to capture emails and verify HTML content type
- Disable deferred transactional emails during tests via GRAPHQL_TESTING flag

COT Cursor HPOS Fix:
- Fix COT_Cursor::compare_with to resolve orderby aliases and legacy meta
  keys (_order_total, _date_completed, etc.) to COT column names
- Add resolve_orderby_alias() mapping short aliases and meta keys to columns
- Add DB_Hooks::clean_query_vars to translate post_* and meta_key orderby
  to COT-compatible equivalents via woocommerce_order_query_args filter

Checkout Account Authentication:
- Add authenticate field to CreateAccountInput type
- Gate wc_set_customer_auth_cookie() behind authenticate flag in checkout
  mutation so account creation doesn't auto-authenticate by default

Closes #882

* devops: codeception.dist.yml updated

* fix: Functional test cleanup and CI coverage condition

Test fixes:
- Enable authorizing URL fields in ProtectedRouterCest and
  DownloadableItemAuthCest via setWooGraphQLSetting
- Add stale data cleanup (sessions, users, products, orders) to
  GraphQLE2E _setupStore/getCatalog/setupStoreAndUsers
- Fix CartTransactionQueueCest and CartQueriesTest for test isolation

CI:
- Only run coverage job when at least one upstream job succeeds

* chore: Linter compliances met

* fix: HPOS order mutation data loss and CI coverage condition

Refactor order create/update mutations to set all props on a single
WC_Order instance before saving, mirroring the WC REST API pattern.
Previously, separate add_order_meta() and add_items() calls each loaded
their own order instance and saved independently, causing HPOS data loss
for payment method, addresses, and other fields.

Also fix CI coverage job to only run when all upstream jobs succeed,
and correct test assertions for RAW format line item totals.

Closes #591

* chore: Linter compliances met

* chore: Remove dead code from Order_Mutation after prepare_order refactor

Removes add_items() and update_address() which are no longer called
after the prepare_order() consolidation.

* chore: Remove dead code add_order_meta and update_item_meta_data
2026-03-30 21:42:00 -04:00

292 lines
8.5 KiB
PHP

<?php
use WPGraphQL\WooCommerce\Vendor\Firebase\JWT\JWT;
use WPGraphQL\WooCommerce\Vendor\Firebase\JWT\Key;
use Tests\WPGraphQL\Logger\CodeceptLogger as Signal;
class ProtectedRouterCest {
private $product_catalog;
public function _before( FunctionalTester $I ) {
$this->product_catalog = $I->getCatalog();
if ( ! defined( 'GRAPHQL_WOOCOMMERCE_SECRET_KEY' ) ) {
define( 'GRAPHQL_WOOCOMMERCE_SECRET_KEY', 'testestestestestestestestestest!!' );
}
// Enable authorizing URL fields so checkoutNonce, accountNonce, and
// addPaymentMethodNonce fields are registered on the Customer type.
$I->setWooGraphQLSetting(
'enable_authorizing_url_fields',
[
'cart_url' => 'cart_url',
'checkout_url' => 'checkout_url',
'account_url' => 'account_url',
'add_payment_method_url' => 'add_payment_method_url',
]
);
}
/**
* Helper: Starts a guest session by adding a product to the cart.
* Returns the cart item key and raw session token.
*/
private function startNewSession( FunctionalTester $I ): array {
$success = $I->addToCart(
[
'clientMutationId' => 'someId',
'productId' => $this->product_catalog['t-shirt'],
'quantity' => 5,
]
);
$I->assertQuerySuccessful(
$success,
[ $I->expectField( 'addToCart.cartItem.key', Signal::NOT_NULL ) ]
);
$session_token = $I->grabHttpHeader( 'woocommerce-session' );
return [
'key' => $I->lodashGet( $success, 'data.addToCart.cartItem.key' ),
'session_token' => $session_token,
];
}
/**
* Helper: Decodes the session token and returns the customer_id (session_id).
*/
private function getSessionId( string $session_token ): string {
JWT::$leeway = 60;
$token_data = JWT::decode( $session_token, new Key( GRAPHQL_WOOCOMMERCE_SECRET_KEY, 'HS256' ) );
return $token_data->data->customer_id;
}
/**
* Test that a valid nonce redirects to the checkout page.
*/
public function testValidNonceRedirectsToCheckout( FunctionalTester $I ) {
$session_data = $this->startNewSession( $I );
$session_id = $this->getSessionId( $session_data['session_token'] );
$query = 'query { customer { checkoutNonce } }';
$success = $I->sendGraphQLRequest(
$query,
null,
[ 'woocommerce-session' => "Session {$session_data['session_token']}" ]
);
$checkout_nonce = $I->lodashGet( $success, 'data.customer.checkoutNonce' );
$I->assertNotEmpty( $checkout_nonce );
$I->stopFollowingRedirects();
$wp_url = getenv( 'WORDPRESS_URL' );
$I->amOnUrl( "{$wp_url}/transfer-session?session_id={$session_id}&_wc_checkout={$checkout_nonce}" );
$I->seeResponseCodeIs( 302 );
$I->followRedirect();
$I->seeInCurrentUrl( '/checkout' );
$I->startFollowingRedirects();
}
/**
* Test that an invalid nonce does NOT redirect to checkout.
*/
public function testInvalidNonceDoesNotRedirectToCheckout( FunctionalTester $I ) {
$session_data = $this->startNewSession( $I );
$session_id = $this->getSessionId( $session_data['session_token'] );
$I->stopFollowingRedirects();
$wp_url = getenv( 'WORDPRESS_URL' );
$I->amOnUrl( "{$wp_url}/transfer-session?session_id={$session_id}&_wc_checkout=invalid_nonce" );
$I->seeResponseCodeIs( 302 );
$I->followRedirect();
$I->dontSeeInCurrentUrl( '/checkout' );
$I->startFollowingRedirects();
}
/**
* Test that an expired nonce (after client_session_id change) does NOT redirect to checkout.
*/
public function testExpiredNonceDoesNotRedirectToCheckout( FunctionalTester $I ) {
$this->startNewSession( $I );
$session_token = $I->grabHttpHeader( 'woocommerce-session' );
$query = '
mutation($input: UpdateSessionInput!) {
updateSession(input: $input) {
session { key value }
customer { checkoutUrl }
}
}
';
// Set client_session_id and get checkout URL.
$success = $I->sendGraphQLRequest(
$query,
[
'input' => [
'sessionData' => [
[ 'key' => 'client_session_id', 'value' => 'original-session-id' ],
],
],
],
[ 'woocommerce-session' => "Session {$session_token}" ]
);
$expired_checkout_url = $I->lodashGet( $success, 'data.updateSession.customer.checkoutUrl' );
$I->assertNotEmpty( $expired_checkout_url );
// Change client_session_id to invalidate the nonce.
$I->sendGraphQLRequest(
$query,
[
'input' => [
'sessionData' => [
[ 'key' => 'client_session_id', 'value' => 'new-session-id' ],
],
],
],
[ 'woocommerce-session' => "Session {$session_token}" ]
);
// The old checkout URL should no longer redirect to checkout.
$I->stopFollowingRedirects();
$I->amOnUrl( $expired_checkout_url );
$I->seeResponseCodeIs( 302 );
$I->followRedirect();
$I->dontSeeInCurrentUrl( '/checkout' );
$I->startFollowingRedirects();
}
/**
* Test that the session cart URL redirects correctly.
*/
public function testGetTheSessionCartUrl( FunctionalTester $I ) {
$session_data = $this->startNewSession( $I );
$session_id = $this->getSessionId( $session_data['session_token'] );
$query = 'query { customer { cartNonce } }';
$success = $I->sendGraphQLRequest(
$query,
null,
[ 'woocommerce-session' => "Session {$session_data['session_token']}" ]
);
$cart_nonce = $I->lodashGet( $success, 'data.customer.cartNonce' );
$I->assertNotEmpty( $cart_nonce );
$I->stopFollowingRedirects();
$wp_url = getenv( 'WORDPRESS_URL' );
$I->amOnUrl( "{$wp_url}/transfer-session?session_id={$session_id}&_wc_cart={$cart_nonce}" );
$I->seeResponseCodeIs( 302 );
$I->followRedirect();
$I->seeInCurrentUrl( '/cart' );
$I->startFollowingRedirects();
}
/**
* Helper: Sets up a logged-in user session and creates the my-account page.
* Returns auth_token, session_token, and session_id.
*/
private function setupAuthenticatedSession( FunctionalTester $I ): array {
$I->setupStoreAndUsers();
// Create the my-account page and set it as the WooCommerce account page.
$account_page_id = $I->havePostInDatabase(
[
'post_type' => 'page',
'post_title' => 'My Account',
'post_name' => 'my-account',
'post_status' => 'publish',
]
);
$I->haveOptionInDatabase( 'woocommerce_myaccount_page_id', $account_page_id );
$login = $I->login(
[
'clientMutationId' => 'login',
'username' => 'jimbo1234@example.com',
'password' => 'password',
]
);
$auth_token = $I->lodashGet( $login, 'data.login.authToken' );
$customer_id = $I->lodashGet( $login, 'data.login.customer.databaseId' );
$session_token = $I->grabHttpHeader( 'woocommerce-session' );
$session_id = $this->getSessionId( $session_token );
// For registered users, the session_id should be the user's database ID.
$I->assertEquals( (string) $customer_id, $session_id );
return compact( 'auth_token', 'session_token', 'session_id' );
}
/**
* Test that the session account URL redirects correctly.
*/
public function testGetTheSessionAccountUrl( FunctionalTester $I ) {
$session = $this->setupAuthenticatedSession( $I );
$query = 'query { customer { accountNonce } }';
$success = $I->sendGraphQLRequest(
$query,
null,
[
'Authorization' => "Bearer {$session['auth_token']}",
'woocommerce-session' => "Session {$session['session_token']}",
]
);
$account_nonce = $I->lodashGet( $success, 'data.customer.accountNonce' );
$I->assertNotEmpty( $account_nonce );
$I->stopFollowingRedirects();
$wp_url = getenv( 'WORDPRESS_URL' );
$I->amOnUrl( "{$wp_url}/transfer-session?session_id={$session['session_id']}&_wc_account={$account_nonce}" );
$I->seeResponseCodeIs( 302 );
$I->followRedirect();
$I->seeInCurrentUrl( '/my-account' );
$I->startFollowingRedirects();
}
/**
* Test that the session add payment method URL redirects correctly.
*/
public function testGetTheSessionAddPaymentMethodUrl( FunctionalTester $I ) {
$session = $this->setupAuthenticatedSession( $I );
$query = 'query { customer { addPaymentMethodNonce } }';
$success = $I->sendGraphQLRequest(
$query,
null,
[
'Authorization' => "Bearer {$session['auth_token']}",
'woocommerce-session' => "Session {$session['session_token']}",
]
);
$payment_nonce = $I->lodashGet( $success, 'data.customer.addPaymentMethodNonce' );
$I->assertNotEmpty( $payment_nonce );
$I->stopFollowingRedirects();
$wp_url = getenv( 'WORDPRESS_URL' );
$I->amOnUrl( "{$wp_url}/transfer-session?session_id={$session['session_id']}&_wc_payment={$payment_nonce}" );
$I->seeResponseCodeIs( 302 );
$I->followRedirect();
$I->seeInCurrentUrl( 'add-payment-method' );
$I->startFollowingRedirects();
}
}