CustomMetaBox.php
5 days ago
CustomerHistory.php
5 days ago
OrderAttribution.php
1 year ago
TaxonomiesMetaBox.php
3 years ago
CustomerHistory.php
305 lines
| 1 | <?php |
| 2 | declare( strict_types = 1 ); |
| 3 | |
| 4 | namespace Automattic\WooCommerce\Internal\Admin\Orders\MetaBoxes; |
| 5 | |
| 6 | use Automattic\WooCommerce\Admin\API\Reports\Customers\Query as CustomersQuery; |
| 7 | use Automattic\WooCommerce\Admin\Overrides\Order as AdminOrder; |
| 8 | use Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore; |
| 9 | use Automattic\WooCommerce\Utilities\OrderUtil; |
| 10 | use WC_Order; |
| 11 | |
| 12 | /** |
| 13 | * Class CustomerHistory |
| 14 | * |
| 15 | * @since 8.5.0 |
| 16 | */ |
| 17 | class CustomerHistory { |
| 18 | |
| 19 | /** |
| 20 | * Memoized excluded statuses to avoid redundant option reads and filter calls per request. |
| 21 | * |
| 22 | * @var string[]|null |
| 23 | */ |
| 24 | private $excluded_statuses = null; |
| 25 | |
| 26 | /** |
| 27 | * Output the customer history template for the order. |
| 28 | * |
| 29 | * @param WC_Order $order The order object. |
| 30 | * |
| 31 | * @return void |
| 32 | */ |
| 33 | public function output( WC_Order $order ): void { |
| 34 | // No history when adding a new order. |
| 35 | if ( 'auto-draft' === $order->get_status() ) { |
| 36 | return; |
| 37 | } |
| 38 | |
| 39 | $customer_history = $this->get_customer_history( $order ); |
| 40 | |
| 41 | wc_get_template( 'order/customer-history.php', $customer_history ); |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * Get the order history for the customer. |
| 46 | * |
| 47 | * @param WC_Order $order The order object. |
| 48 | * |
| 49 | * @return array{orders_count: int, total_spend: float, avg_order_value: float, tooltip: string} Order count, total spend, average order value, and tooltip text. |
| 50 | */ |
| 51 | private function get_customer_history( WC_Order $order ): array { |
| 52 | if ( OrderUtil::custom_orders_table_usage_is_enabled() ) { |
| 53 | $customer_id = $order->get_customer_id(); |
| 54 | $billing_email = $order->get_billing_email(); |
| 55 | $result = $this->query_hpos( $customer_id, $billing_email ); |
| 56 | } else { |
| 57 | $customer_report_id = $this->get_cpt_report_customer_id( $order ); |
| 58 | if ( $customer_report_id > 0 ) { |
| 59 | $result = $this->query_cpt( $customer_report_id ); |
| 60 | } else { |
| 61 | $result = (object) array( |
| 62 | 'orders_count' => 0, |
| 63 | 'total_spend' => 0, |
| 64 | ); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | $orders_count = (int) ( $result->orders_count ?? 0 ); |
| 69 | $total_spend = (float) ( $result->total_spend ?? 0 ); |
| 70 | |
| 71 | // Build a dynamic tooltip listing the excluded statuses by their translated labels. |
| 72 | // Internal statuses (auto-draft, trash) are naturally filtered out because they |
| 73 | // don't exist in wc_get_order_statuses(). checkout-draft is skipped explicitly |
| 74 | // because it is force-excluded by DraftOrders but is not a configurable option |
| 75 | // on the Analytics settings page, so it would be confusing to surface it here. |
| 76 | $all_statuses = wc_get_order_statuses(); |
| 77 | $excluded_labels = array(); |
| 78 | foreach ( $this->get_excluded_statuses() as $slug ) { |
| 79 | if ( 'checkout-draft' === $slug ) { |
| 80 | continue; |
| 81 | } |
| 82 | $prefixed = 'wc-' . $slug; |
| 83 | if ( isset( $all_statuses[ $prefixed ] ) ) { |
| 84 | $excluded_labels[] = mb_strtolower( $all_statuses[ $prefixed ] ); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | if ( ! empty( $excluded_labels ) ) { |
| 89 | $tooltip = sprintf( |
| 90 | /* translators: %s: localized list of order status names, e.g. "pending payment, failed, and cancelled" */ |
| 91 | __( 'Total number of orders for this customer, excluding %s orders, including the current one.', 'woocommerce' ), |
| 92 | wp_sprintf_l( '%l', $excluded_labels ) |
| 93 | ); |
| 94 | } else { |
| 95 | $tooltip = __( 'Total number of orders for this customer, including the current one.', 'woocommerce' ); |
| 96 | } |
| 97 | |
| 98 | return array( |
| 99 | 'orders_count' => $orders_count, |
| 100 | 'total_spend' => $total_spend, |
| 101 | 'avg_order_value' => $orders_count > 0 ? $total_spend / $orders_count : 0, |
| 102 | 'tooltip' => $tooltip, |
| 103 | ); |
| 104 | } |
| 105 | |
| 106 | /** |
| 107 | * Query customer order stats from HPOS tables. |
| 108 | * |
| 109 | * @param int $customer_id The customer user ID. |
| 110 | * @param string $billing_email The billing email address. |
| 111 | * |
| 112 | * @return object Object with orders_count and total_spend properties. |
| 113 | */ |
| 114 | private function query_hpos( int $customer_id, string $billing_email ): object { |
| 115 | global $wpdb; |
| 116 | |
| 117 | $default = (object) array( |
| 118 | 'orders_count' => 0, |
| 119 | 'total_spend' => 0, |
| 120 | ); |
| 121 | |
| 122 | $excluded_statuses_sql = $this->get_excluded_statuses_sql(); |
| 123 | $orders_table = OrdersTableDataStore::get_orders_table_name(); |
| 124 | |
| 125 | $sql = null; |
| 126 | |
| 127 | // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 128 | if ( $customer_id > 0 ) { |
| 129 | $status_filter = $excluded_statuses_sql ? "AND status NOT IN $excluded_statuses_sql" : ''; |
| 130 | $co_status_filter = $excluded_statuses_sql ? "AND co.status NOT IN $excluded_statuses_sql" : ''; |
| 131 | |
| 132 | $sql = $wpdb->prepare( |
| 133 | "SELECT COUNT(*) AS orders_count, |
| 134 | COALESCE( SUM( filtered.total_amount ), 0 ) + COALESCE( SUM( r.refund_total ), 0 ) AS total_spend |
| 135 | FROM ( |
| 136 | SELECT id, total_amount |
| 137 | FROM %i |
| 138 | WHERE customer_id = %d AND type = 'shop_order' $status_filter |
| 139 | ) AS filtered |
| 140 | LEFT JOIN ( |
| 141 | SELECT rp.parent_order_id, SUM( rp.total_amount ) AS refund_total |
| 142 | FROM %i AS rp |
| 143 | INNER JOIN %i AS co ON rp.parent_order_id = co.id |
| 144 | WHERE rp.type = 'shop_order_refund' |
| 145 | AND co.customer_id = %d AND co.type = 'shop_order' $co_status_filter |
| 146 | GROUP BY rp.parent_order_id |
| 147 | ) AS r ON filtered.id = r.parent_order_id", |
| 148 | $orders_table, |
| 149 | $customer_id, |
| 150 | $orders_table, |
| 151 | $orders_table, |
| 152 | $customer_id |
| 153 | ); |
| 154 | } elseif ( '' !== $billing_email ) { |
| 155 | $addresses_table = OrdersTableDataStore::get_addresses_table_name(); |
| 156 | $o_status_filter = $excluded_statuses_sql ? "AND o.status NOT IN $excluded_statuses_sql" : ''; |
| 157 | $co_status_filter = $excluded_statuses_sql ? "AND co.status NOT IN $excluded_statuses_sql" : ''; |
| 158 | |
| 159 | $sql = $wpdb->prepare( |
| 160 | "SELECT COUNT(*) AS orders_count, |
| 161 | COALESCE( SUM( filtered.total_amount ), 0 ) + COALESCE( SUM( r.refund_total ), 0 ) AS total_spend |
| 162 | FROM ( |
| 163 | SELECT o.id, o.total_amount |
| 164 | FROM %i AS o |
| 165 | INNER JOIN %i AS a ON o.id = a.order_id AND a.address_type = 'billing' |
| 166 | WHERE o.customer_id = 0 AND a.email = %s AND o.type = 'shop_order' $o_status_filter |
| 167 | ) AS filtered |
| 168 | LEFT JOIN ( |
| 169 | SELECT rp.parent_order_id, SUM( rp.total_amount ) AS refund_total |
| 170 | FROM %i AS rp |
| 171 | INNER JOIN %i AS co ON rp.parent_order_id = co.id |
| 172 | INNER JOIN %i AS ca ON co.id = ca.order_id AND ca.address_type = 'billing' |
| 173 | WHERE rp.type = 'shop_order_refund' |
| 174 | AND co.customer_id = 0 AND ca.email = %s AND co.type = 'shop_order' $co_status_filter |
| 175 | GROUP BY rp.parent_order_id |
| 176 | ) AS r ON filtered.id = r.parent_order_id", |
| 177 | $orders_table, |
| 178 | $addresses_table, |
| 179 | $billing_email, |
| 180 | $orders_table, |
| 181 | $orders_table, |
| 182 | $addresses_table, |
| 183 | $billing_email |
| 184 | ); |
| 185 | } |
| 186 | // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 187 | |
| 188 | if ( null === $sql ) { |
| 189 | return $default; |
| 190 | } |
| 191 | |
| 192 | // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is prepared above. |
| 193 | $row = $wpdb->get_row( $sql ); |
| 194 | |
| 195 | if ( $wpdb->last_error ) { |
| 196 | wc_get_logger()->error( |
| 197 | sprintf( 'CustomerHistory: Failed to query HPOS order stats for customer_id=%d. DB error: %s', $customer_id, $wpdb->last_error ), |
| 198 | array( 'source' => 'customer-history' ) |
| 199 | ); |
| 200 | } |
| 201 | |
| 202 | return $row ?? $default; |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * Query customer order stats via the Analytics Customers report (legacy fallback when HPOS is not active). |
| 207 | * |
| 208 | * @param int $customer_report_id The reports customer ID. |
| 209 | * |
| 210 | * @return object Object with orders_count and total_spend properties. |
| 211 | */ |
| 212 | private function query_cpt( int $customer_report_id ): object { |
| 213 | $args = array( |
| 214 | 'customers' => array( $customer_report_id ), |
| 215 | // If unset, these params have default values that affect the results. |
| 216 | 'order_after' => null, |
| 217 | 'order_before' => null, |
| 218 | ); |
| 219 | |
| 220 | $customers_query = new CustomersQuery( $args ); |
| 221 | $customer_data = $customers_query->get_data(); |
| 222 | $customer_row = $customer_data->data[0] ?? null; |
| 223 | |
| 224 | return (object) array( |
| 225 | 'orders_count' => $customer_row['orders_count'] ?? 0, |
| 226 | 'total_spend' => $customer_row['total_spend'] ?? 0, |
| 227 | ); |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Get the analytics customer ID for a CPT-backed order. |
| 232 | * |
| 233 | * @param WC_Order $order The order object. |
| 234 | * @return int The reports customer ID. |
| 235 | */ |
| 236 | private function get_cpt_report_customer_id( WC_Order $order ): int { |
| 237 | if ( ! $order->get_id() ) { |
| 238 | return 0; |
| 239 | } |
| 240 | |
| 241 | $report_order = $order instanceof AdminOrder ? $order : new AdminOrder( $order->get_id() ); |
| 242 | |
| 243 | return (int) $report_order->get_report_customer_id(); |
| 244 | } |
| 245 | |
| 246 | /** |
| 247 | * Get the list of excluded order statuses for customer history. |
| 248 | * |
| 249 | * @return string[] Excluded status slugs without wc- prefix (e.g. 'auto-draft', 'trash', 'pending', 'failed', 'cancelled'). |
| 250 | */ |
| 251 | private function get_excluded_statuses(): array { |
| 252 | if ( null !== $this->excluded_statuses ) { |
| 253 | return $this->excluded_statuses; |
| 254 | } |
| 255 | |
| 256 | $excluded_statuses = get_option( 'woocommerce_excluded_report_order_statuses', array( 'pending', 'failed', 'cancelled' ) ); |
| 257 | if ( ! is_array( $excluded_statuses ) ) { |
| 258 | $excluded_statuses = array( 'pending', 'failed', 'cancelled' ); |
| 259 | } |
| 260 | $excluded_statuses = array_merge( array( 'auto-draft', 'trash' ), $excluded_statuses ); |
| 261 | |
| 262 | /** |
| 263 | * Filter the list of excluded order statuses for customer history and analytics reports. |
| 264 | * |
| 265 | * @since 4.0.0 |
| 266 | * @param array $excluded_statuses Order statuses to exclude. |
| 267 | */ |
| 268 | $excluded_statuses = apply_filters( 'woocommerce_analytics_excluded_order_statuses', $excluded_statuses ); |
| 269 | if ( ! is_array( $excluded_statuses ) ) { |
| 270 | $excluded_statuses = array( 'auto-draft', 'trash', 'pending', 'failed', 'cancelled' ); |
| 271 | } |
| 272 | |
| 273 | $this->excluded_statuses = $excluded_statuses; |
| 274 | return $this->excluded_statuses; |
| 275 | } |
| 276 | |
| 277 | /** |
| 278 | * Get the SQL fragment for excluded order statuses. |
| 279 | * |
| 280 | * @return string SQL IN clause, e.g. ( 'auto-draft','trash','wc-pending','wc-failed',... ), or empty string if no statuses are excluded. |
| 281 | */ |
| 282 | private function get_excluded_statuses_sql(): string { |
| 283 | global $wpdb; |
| 284 | |
| 285 | $excluded_statuses = $this->get_excluded_statuses(); |
| 286 | |
| 287 | if ( empty( $excluded_statuses ) ) { |
| 288 | return ''; |
| 289 | } |
| 290 | |
| 291 | $prefixed = array_map( |
| 292 | function ( $status ) { |
| 293 | $status = sanitize_title( $status ); |
| 294 | return 'auto-draft' === $status || 'trash' === $status ? $status : 'wc-' . $status; |
| 295 | }, |
| 296 | $excluded_statuses |
| 297 | ); |
| 298 | |
| 299 | $placeholders = implode( ',', array_fill( 0, count( $prefixed ), '%s' ) ); |
| 300 | |
| 301 | // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders is a safe string of %s tokens. |
| 302 | return $wpdb->prepare( "( $placeholders )", $prefixed ); |
| 303 | } |
| 304 | } |
| 305 |