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