WC_REST_Report_Sales_Controller::prepare_item_for_response
Prepare a report sales object for serialization.
Extends the v2 response with a per-period refunds field inside each totals[date] bucket so consumers can compute net sales per period without a second request. Top-level total_refunds and per-period sales semantics are unchanged.
Method of the class: WC_REST_Report_Sales_Controller{}
No Hooks.
Returns
WP_REST_Response.
Usage
$WC_REST_Report_Sales_Controller = new WC_REST_Report_Sales_Controller(); $WC_REST_Report_Sales_Controller->prepare_item_for_response( $_, $request );
- $_(null) (required)
- Unused.
- $request(required)
- .
WC_REST_Report_Sales_Controller::prepare_item_for_response() WC REST Report Sales Controller::prepare item for response code WC 11.1.2
public function prepare_item_for_response( $_, $request ) {
$response = parent::prepare_item_for_response( $_, $request );
$data = $response->get_data();
if ( ! isset( $data['totals'] ) || ! is_array( $data['totals'] ) ) {
return $response;
}
// Initialise the refunds bucket on every period so consumers get a
// stable shape (decimal string) even on periods with no refunds.
foreach ( $data['totals'] as $time => $bucket ) {
$data['totals'][ $time ]['refunds'] = wc_format_decimal( 0.00, 2 );
}
// `$this->report` is a WC_Report_Sales_By_Date (the v1 base annotates
// it as the abstract WC_Admin_Report). Annotate locally so the call to
// the concrete `get_report_data()` typechecks.
/** @var WC_Report_Sales_By_Date $report */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$report = $this->report;
$report_data = $report->get_report_data();
if ( ! empty( $report_data->refund_lines ) ) {
foreach ( $report_data->refund_lines as $refund ) {
// Match the bucket key format used by the parent's sales /
// orders / items / coupons loops (local time, not UTC) so
// refunds line up with their corresponding sales row.
// phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- Match adjacent loops in v1 base controller.
$time = ( 'day' === $this->report->chart_groupby ) ? date( 'Y-m-d', strtotime( $refund->post_date ) ) : date( 'Y-m', strtotime( $refund->post_date ) );
if ( ! isset( $data['totals'][ $time ] ) ) {
continue;
}
$data['totals'][ $time ]['refunds'] = wc_format_decimal( (float) $data['totals'][ $time ]['refunds'] + (float) $refund->total_refund, 2 );
}
}
$response->set_data( $data );
return $response;
}