## Function: wpd_calculate_cost_profit_by_order

Calculate and retrieve complete cost and profit data for a WooCommerce order.

### Description

This is the primary function for retrieving order profit calculations. It calculates all costs (products, shipping, fees, custom costs) and returns a comprehensive array of profit data. Use this when you need to get profit information for an order programmatically.

#### Location

File:`includes/wpd-functions.php`

Line:~165

### Function Signature

    wpd_calculate_cost_profit_by_order( $order_id_or_object = null, $update_values = false )

### Parameters

Parameter | Type | Required | Description
--- | --- | --- | ---
$order_id_or_object | int|WC_Order|null | No | Order ID, WC_Order object, or null for current order
$update_values | bool | No | Whether to save calculation results to database (default: false)

#### Return Value

Type: array|false

Description: Array of profit calculations, or false if order invalid

### Return Array Structure

    array(
        // Revenue
        'order_total' => 125.50,
        'order_total_inc_tax' => 135.00,
        'order_total_ex_tax' => 125.50,
        'order_tax' => 9.50,
        'order_discount' => 10.00,
        // Product Costs
        'product_cost' => 52.00,
        'product_cost_per_unit' => 26.00,
        // Shipping
        'shipping_cost' => 8.00,
        'shipping_revenue' => 10.00,
        // Fees
        'payment_gateway_cost' => 3.95,
        'payment_method' => 'stripe',
        // Custom Costs
        'custom_order_costs' => array(),
        'custom_product_costs' => array(),
        // Calculated Totals
        'total_costs' => 63.95,
        'gross_profit' => 61.55,
        'profit_margin' => 49.04,
        // Meta
        'currency' => 'USD',
        'order_date' => '2024-01-15 14:30:00',
        'order_status' => 'completed'
    )

#### Example Usage

### Basic Usage - Get Profit for Order

    // By order ID
    $profit_data = wpd_calculate_cost_profit_by_order( 12345 );

    if ( $profit_data ) {
        $profit = $profit_data['gross_profit'];
        $margin = $profit_data['profit_margin'];
        echo 'Order profit: $' . number_format( $profit, 2 );
        echo 'Margin: ' . number_format( $margin, 2 ) . '%';
    }

### Using Order Object

    // Get order object
    $order = wc_get_order( 12345 );

    if ( $order ) {
        $profit_data = wpd_calculate_cost_profit_by_order( $order );

        // Access specific values
        $revenue = $profit_data['order_total_ex_tax'];
        $costs = $profit_data['total_costs'];
        $profit = $profit_data['gross_profit'];
    }

### Calculate and Save to Database

    // Recalculate and save results
    $profit_data = wpd_calculate_cost_profit_by_order( 12345, true );

    // Results are now saved to order meta and database
    // Future calls will use cached values

### In WooCommerce Hook

    add_action( 'woocommerce_order_status_completed', 'custom_profit_check' );

    function custom_profit_check( $order_id ) {
        // Calculate profit when order completes
        $profit_data = wpd_calculate_cost_profit_by_order( $order_id );

        if ( $profit_data && $profit_data['gross_profit'] < 0 ) {
            // Order is unprofitable - send alert
            wp_mail(
                'owner@store.com',
                'Unprofitable Order Alert',
                sprintf( 'Order #%d has negative profit: $%s',
                    $order_id,
                    number_format( $profit_data['gross_profit'], 2 )
                )
            );
        }
    }

### Bulk Profit Calculation

    // Calculate profit for multiple orders
    $order_ids = array( 100, 101, 102, 103, 104 );
    $total_profit = 0;

    foreach ( $order_ids as $order_id ) {
        $profit_data = wpd_calculate_cost_profit_by_order( $order_id );
        if ( $profit_data ) {
            $total_profit += $profit_data['gross_profit'];
        }
    }

    echo 'Total profit: $' . number_format( $total_profit, 2 );

### Custom Profit Report

    function generate_daily_profit_summary() {
        // Get today's orders
        $args = array(
            'limit' => -1,
            'date_created' => '>=' . strtotime( 'today' ),
            'status' => array( 'processing', 'completed' )
        );
        $orders = wc_get_orders( $args );

        $total_revenue = 0;
        $total_costs = 0;
        $total_profit = 0;

        foreach ( $orders as $order ) {
            $profit_data = wpd_calculate_cost_profit_by_order( $order );
            if ( $profit_data ) {
                $total_revenue += $profit_data['order_total_ex_tax'];
                $total_costs += $profit_data['total_costs'];
                $total_profit += $profit_data['gross_profit'];
            }
        }

        return array(
            'revenue' => $total_revenue,
            'costs' => $total_costs,
            'profit' => $total_profit,
            'margin' => $total_revenue > 0 ? ($total_profit / $total_revenue) * 100 : 0,
            'order_count' => count( $orders )
        );
    }

#### Return Value Details

### Revenue Fields

- order_total: Complete order total including tax
- order_total_inc_tax: Total including tax
- order_total_ex_tax: Total excluding tax (used for profit calculation)
- order_tax: Tax amount collected
- order_discount: Discounts applied

### Cost Fields

- product_cost: Total cost of all products in order
- shipping_cost: Shipping fulfillment cost
- payment_gateway_cost: Payment processing fees
- custom_order_costs: Array of custom order-level costs
- custom_product_costs: Array of custom product-level costs
- total_costs: Sum of all costs

#### Profit Fields

- gross_profit: Revenue minus total costs
- profit_margin: Profit as percentage of revenue

### Performance Considerations

### Caching

Results are cached after calculation:

- First call: Performs full calculation
- Subsequent calls: Returns cached value
- Cache invalidated when order or costs updated

### When to Use update_values Parameter

$update_values = false (default):

- Just retrieving data for display
- Don't need to save to database
- Faster (reads from cache if available)

$update_values = true:

- Want to force recalculation
- Save new calculation to database
- After updating costs/settings
- Slower (always recalculates)

### Error Handling

    $profit_data = wpd_calculate_cost_profit_by_order( $order_id );

    if ( false === $profit_data ) {
        // Order doesn't exist or calculation failed
        error_log( 'Could not calculate profit for order #' . $order_id );
        return;
    }

    // Safe to use profit data
    $profit = $profit_data['gross_profit'];

#### Common Use Cases

### Display Profit in Custom Location

    add_action( 'woocommerce_admin_order_data_after_order_details', 'display_order_profit' );

    function display_order_profit( $order ) {
        $profit_data = wpd_calculate_cost_profit_by_order( $order );

        if ( $profit_data ) {
            echo 'Order Profit: ' . wc_price( $profit_data['gross_profit'] ) . '';
        }
    }

### Export Profit Data to CSV

    function export_profit_data_csv() {
        $orders = wc_get_orders( array( 'limit' => -1 ) );
        $csv_data = array();

        // Header row
        $csv_data[] = array( 'Order ID', 'Date', 'Revenue', 'Costs', 'Profit', 'Margin %' );

        foreach ( $orders as $order ) {
            $profit_data = wpd_calculate_cost_profit_by_order( $order );
            if ( $profit_data ) {
                $csv_data[] = array(
                    $order->get_id(),
                    $order->get_date_created()->date( 'Y-m-d' ),
                    $profit_data['order_total_ex_tax'],
                    $profit_data['total_costs'],
                    $profit_data['gross_profit'],
                    $profit_data['profit_margin']
                );
            }
        }

        // Output CSV
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="profit-export.csv"');
        $output = fopen('php://output', 'w');

        foreach ( $csv_data as $row ) {
            fputcsv( $output, $row );
        }

        fclose( $output );
        exit;
    }

### Related

- wpd_ai_calculate_cost_profit_by_order filter
- wpd_get_cost_price_by_product_id() function