<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WC_Profit_Tracker
*
* Manages product cost input and order profit calculation.
*/
class WC_Profit_Tracker {
/**
* Instance of the class.
*
* @var WC_Profit_Tracker The single instance of the class.
*/
private static $_instance = null;
/**
* Get the instance of the class.
*
* @return WC_Profit_Tracker
*/
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Constructor.
* Registers all the necessary hooks.
*/
protected function __construct() {
// Add cost field to products (simple & variable)
add_action( 'woocommerce_product_options_pricing', array( $this, 'add_product_cost_field' ) );
add_action( 'woocommerce_process_product_meta', array( $this, 'save_product_cost_field' ) );
// Add cost field to product variations
add_action( 'woocommerce_product_variation_settings_attributes', array( $this, 'add_variation_cost_field' ), 10, 3 );
add_action( 'woocommerce_save_product_variation', array( $this, 'save_variation_cost_field' ), 10, 2 );
// Add columns to the orders list table
add_filter( 'manage_woocommerce_edit_shop_order_columns', array( $this, 'add_admin_columns' ), 20 );
add_action( 'manage_shop_order_posts_custom_column', array( $this, 'display_admin_columns_content' ), 20, 2 );
// Optional: Add sorting capability to columns (more advanced)
// add_filter( 'manage_edit-shop_order_sortable_columns', array( $this, 'add_sortable_columns' ) );
}
// --- Product Cost Field ---
/**
* Add the cost field to the pricing tab of product data.
*/
public function add_product_cost_field() {
global $product_object;
echo '<div class="options_group pricing">'; // Group fields visually
// Product Cost Field
woocommerce_wp_text_input(
array(
'id' => '_product_cost',
'label' => __( 'Cost', 'wc-profit-tracker' ) . ' (' . get_woocommerce_currency_symbol() . ')',
'placeholder' => __( 'Enter cost price', 'wc-profit-tracker' ),
'desc_tip' => 'true',
'description' => __( 'Enter the cost price for this product (Cost of Goods Sold).', 'wc-profit-tracker' ),
'type' => 'text',
'custom_attributes' => array(
'step' => 'any',
'min' => '0',
),
// Use value from post meta if available (for existing products)
'value' => ($product_object && $product_object->get_meta('_product_cost', true)) ? $product_object->get_meta('_product_cost', true) : '',
)
);
echo '</div>';
}
/**
* Save the custom cost field for simple products.
*
* @param int $product_id The ID of the product being saved.
*/
public function save_product_cost_field( $product_id ) {
$cost = isset( $_POST['_product_cost'] ) ? wc_format_decimal( $_POST['_product_cost'] ) : '';
// Validate and sanitize
if ( '' !== $cost && ! is_numeric( $cost ) ) {
wc_add_notice( __( 'Please enter a valid numeric value for product cost.', 'wc-profit-tracker' ), 'error' );
return;
} elseif ( '' !== $cost && floatval($cost) < 0 ) {
wc_add_notice( __( 'Product cost cannot be negative.', 'wc-profit-tracker' ), 'error' );
return;
}
update_post_meta( $product_id, '_product_cost', $cost );
}
/**
* Add the cost field to product variations.
*
* @param int $loop Loop index for variations.
* @param array $variation_data The variation data.
* @param WP_Post $variation The variation post object.
*/
public function add_variation_cost_field( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input(
array(
'id' => '_product_cost[' . $loop . ']',
'name' => '_product_cost[' . $loop . ']',
'value' => wc_format_decimal( get_post_meta( $variation->ID, '_product_cost', true ) ),
'label' => __( 'Cost', 'wc-profit-tracker' ) . ' (' . get_woocommerce_currency_symbol() . ')',
'placeholder' => __( 'Enter cost', 'wc-profit-tracker' ),
'desc_tip' => 'true',
'description' => __( 'Enter the cost price for this variation.', 'wc-profit-tracker' ),
'type' => 'text',
'wrapper_class' => 'form-row form-row-full',
'class' => 'wc_input_price', // Use WC styling class
'custom_attributes' => array(
'step' => 'any',
'min' => '0',
),
)
);
}
/**
* Save the custom cost field for product variations.
*
* @param int $variation_id The ID of the variation being saved.
* @param int $i The index of the variation in the loop.
*/
public function save_variation_cost_field( $variation_id, $i ) {
$cost = isset( $_POST['_product_cost'][ $i ] ) ? wc_format_decimal( $_POST['_product_cost'][ $i ] ) : '';
// Basic validation for variations as well
if ( '' !== $cost && ! is_numeric( $cost ) ) {
// Note: WC might show notices differently for variations. Consider JS validation too.
// update_post_meta( $variation_id, '_product_cost', '' ); // Clear if invalid
return;
} elseif ( '' !== $cost && floatval($cost) < 0 ) {
// update_post_meta( $variation_id, '_product_cost', '' ); // Clear if negative
return;
}
update_post_meta( $variation_id, '_product_cost', $cost );
}
// --- Admin Columns & Calculation ---
/**
* Add custom columns to the orders list table.
*
* @param array $columns Existing columns.
* @return array Modified columns.
*/
public function add_admin_columns( $columns ) {
$new_columns = array();
foreach ( $columns as $key => $title ) {
$new_columns[ $key ] = $title;
// Add our columns after the order ID or status
if ( $key === 'order_status' ) {
$new_columns['total_cost'] = __( 'Total Cost', 'wc-profit-tracker' );
$new_columns['profit'] = __( 'Profit', 'wc-profit-tracker' );
}
}
// Ensure columns are added even if order_status isn't found (fallback)
if ( ! isset( $new_columns['total_cost'] ) ) {
$new_columns['total_cost'] = __( 'Total Cost', 'wc-profit-tracker' );
$new_columns['profit'] = __( 'Profit', 'wc-profit-tracker' );
}
return $new_columns;
}
/**
* Display content for the custom columns.
*
* @param string $column The name of the column.
* @param int $order_id The ID of the current order.
*/
public function display_admin_columns_content( $column, $order_id ) {
if ( $column === 'total_cost' || $column === 'profit' ) {
$order = wc_get_order( $order_id );
if ( ! $order ) {
return;
}
$total_cost = $this->get_order_total_cost( $order );
$order_total = $order->get_total(); // Includes taxes, shipping etc. by default
$profit = $order_total - $total_cost;
if ( $column === 'total_cost' ) {
echo wc_price( $total_cost );
} elseif ( $column === 'profit' ) {
$profit_color = ($profit >= 0) ? 'green' : 'red';
echo '<span style="color:' . $profit_color . ';">' . wc_price( $profit ) . '</span>';
// Optional: Add indicator for loss
if ($profit < 0) {
echo ' <small>(' . __('Loss', 'wc-profit-tracker') . ')</small>';
}
}
}
}
/**
* Get the total cost of goods sold for an order.
*
* @param WC_Order $order The order object.
* @return float Total cost.
*/
public function get_order_total_cost( $order ) {
$total_cost = 0;
foreach ( $order->get_items() as $item_id => $item ) {
$product = $item->get_product();
// Skip if product doesn't exist or is invalid
if ( ! $product ) {
continue;
}
$quantity = $item->get_quantity();
$product_cost = 0;
// Get cost from variation if applicable
if ( $item->get_variation_id() && $item->get_variation_id() > 0 ) {
$variation_product = wc_get_product( $item->get_variation_id() );
if ($variation_product) {
$cost_meta = $variation_product->get_meta( '_product_cost', true );
if ( is_numeric( $cost_meta ) && $cost_meta >= 0 ) {
$product_cost = floatval( $cost_meta );
}
}
}
// If no variation cost found or it's a simple product, get product cost
if ( $product_cost === 0 ) {
$cost_meta = $product->get_meta( '_product_cost', true );
if ( is_numeric( $cost_meta ) && $cost_meta >= 0 ) {
$product_cost = floatval( $cost_meta );
}
}
// Add to total cost (cost per unit * quantity)
$total_cost += ( $product_cost * $quantity );
}
// --- Considerations for more accuracy (Future Enhancements) ---
// 1. Subtract refunds: Check order type and subtract cost proportionally.
// 2. Handle shipping cost: Decide if shipping cost paid by seller should be deducted.
// 3. Handle payment gateway fees: Store these or estimate based on total.
// 4. Account for discounts affecting cost basis.
// 5. Taxes: Generally, profit is calculated before income tax, but after sales tax collected.
// This calculation uses Order Total, which includes taxes collected. If you want Gross Profit
// before sales tax, you'd need to subtract taxes from Order Total and potentially COGS.
// For now, just return the calculated COGS based on items.
return apply_filters('wcpt_order_total_cost', $total_cost, $order);
}
/**
* Make columns sortable (Optional - requires more logic for query modification)
*
* @param array $columns Existing sortable columns.
* @return array Modified columns.
*/
// public function add_sortable_columns( $columns ) {
// $columns['total_cost'] = 'total_cost'; // 'total_cost' needs to match the column key
// $columns['profit'] = 'profit'; // 'profit' needs to match the column key
// return $columns;
// }
// NOTE: To make columns sortable, you would need to hook into 'pre_get_posts'
// and modify the main query based on the 'orderby' parameter when these columns are clicked.
// This is significantly more complex.
}