Class: WPD_Data_Warehouse_React
The WPD_Data_Warehouse_React class is the centralized data warehouse for Alpha Insights. It fetches, processes, and stores all WooCommerce and analytics data including orders, products, customers, expenses, campaigns, subscriptions, and website analytics.
Overview
This class serves as a high-level data access layer that:
- Fetches data from database using specialized
fetch_*_data()methods - Stores all data internally in a structured
$dataarray - Applies date ranges and filters to all queries
- Organizes data into four components: totals, categorized_data, data_table, and data_by_date
- Tracks execution time and database record counts
- Provides date containers for time-series charting
- Manages memory limits and handles large datasets efficiently
Location
File: includes/classes/WPD_Data_Warehouse_React.php
Data Structure
All data is stored in the private $data array with these top-level keys:
store_profit– Bottom-line store profit after expensesorders– WooCommerce order datacustomers– Customer metrics (fetched via sales data)products– Product performance (fetched via sales data)coupons– Coupon usage (fetched via sales data)taxes– Tax data (fetched via sales data)refunds– Refund metrics (fetched via sales data)subscriptions– WooCommerce Subscriptions dataexpenses– Store expenses from Alpha Insightsfacebook_campaigns– Facebook Ads campaign datagoogle_campaigns– Google Ads campaign dataanalytics– Website analytics events and sessionsanonymous_queries– Custom SQL query results
Each data type has this structure:
array(
'totals' =>
array(
)
,
// Aggregate metrics
'categorized_data' =>
array(
)
,
// Data grouped by categories
'data_table' =>
array(
)
,
// Tabular data for display
'data_by_date' =>
array(
)
,
// Time-series data
'total_db_records' => 0,
// Number of records fetched
'execution_time' => 0 // Query execution time in seconds
)
Main Public Methods
Constructor & Filter Management
__construct( $filter = array() )
Purpose: Initialize the data warehouse with optional filters
Parameters:
$filter(array) – Filter configuration including date ranges and data filters
Example:
$filter = array(
'date_from' => '2024-01-01',
'date_to' => '2024-01-31',
'data_filters' => array(
'orders' => array(
'order_status' => array('wc-completed', 'wc-processing')
)
)
);
$warehouse = new WPD_Data_Warehouse_React( $filter );
update_filter( $key, $value )
Purpose: Update a specific filter after initialization
Parameters:
$key(string) – Filter key to update$value(mixed) – New value for the filter
Returns: Boolean (true on success, false on failure)
get_filter( $key = null, $default = null )
Purpose: Retrieve a filter value or all filters
Parameters:
$key(string|null) – Specific filter key, or null to get all filters$default(mixed|null) – Default value if key doesn’t exist
Returns: Mixed (filter value, array of all filters, or default)
Data Fetching Methods
fetch_sales_data()
Purpose: Fetch WooCommerce orders and related data (products, customers, coupons, taxes, refunds)
Returns: Array of orders data
Populates: orders, products, customers, coupons, taxes, refunds data types
Example:
$warehouse = new WPD_Data_Warehouse_React( array(
'date_from' => '2024-01-01',
'date_to' => '2024-01-31'
));
// Fetch sales data
$warehouse->fetch_sales_data();
// Access the data
$order_totals = $warehouse->get_data('orders', 'totals');
echo $order_totals['total_order_revenue_ex_tax'];
fetch_expense_data()
Purpose: Fetch expense data from Alpha Insights expense custom post type
Returns: Array of expense data
Populates: expenses data type
Filters: Respects date_from, date_to, and expense_category filters
fetch_store_profit_data()
Purpose: Calculate bottom-line store profit (order profit minus expenses)
Returns: Array of store profit data including P&L statement
Populates: store_profit data type
Note: Automatically calls fetch_sales_data() and fetch_expense_data() if not already fetched
fetch_subscriptions_data()
Purpose: Fetch WooCommerce Subscriptions data (requires WooCommerce Subscriptions plugin)
Returns: Array of subscription metrics
Populates: subscriptions data type
fetch_facebook_campaign_data()
Purpose: Fetch Facebook Ads campaign data from Alpha Insights campaign post type
Returns: Array of campaign performance data
Populates: facebook_campaigns data type
Filters: Supports campaign_id filter to fetch specific campaign
fetch_google_campaign_data()
Purpose: Fetch Google Ads campaign data from Alpha Insights campaign post type
Returns: Array of campaign performance data
Populates: google_campaigns data type
Filters: Supports campaign_id filter to fetch specific campaign
fetch_analytics_data()
Purpose: Fetch website analytics data (events, sessions, page views)
Returns: Array of analytics data
Populates: analytics data type
Data Retrieval Methods
get_data( $data_type = false, $data_key = false )
Purpose: Retrieve stored data from the warehouse
Parameters:
$data_type(string|false) – Data type (e.g., ‘orders’, ‘expenses’, ‘store_profit’)$data_key(string|false) – Specific key within the data type (e.g., ‘totals’, ‘data_by_date’)
Returns: Array of data, or false if not found
Examples:
// Get all data
$all_data = $warehouse->get_data();
// Get all orders data
$orders_data = $warehouse->get_data('orders');
// Get orders totals only
$orders_totals = $warehouse->get_data('orders', 'totals');
// Get orders data by date
$orders_by_date = $warehouse->get_data('orders', 'data_by_date');
set_data( $data_type, $data )
Purpose: Manually set data into the warehouse (useful for custom queries)
Parameters:
$data_type(string) – Data type to store under$data(array) – Data to store
Returns: Boolean (false on error)
Date & Time Methods
get_date_from( $format = ‘Y-m-d’ )
Purpose: Get the start date from the filter
Returns: String formatted date
get_date_to( $format = ‘Y-m-d’ )
Purpose: Get the end date from the filter
Returns: String formatted date
get_n_days_range()
Purpose: Calculate the number of days in the date range
Returns: Integer number of days
get_date_range_array( $first, $last, $step = ‘+1 day’, $output_format = ‘Y-m-d’ )
Purpose: Generate an array of dates between two dates
Parameters:
$first(string) – Start date$last(string) – End date$step(string) – Date increment (e.g., ‘+1 day’, ‘+1 week’)$output_format(string) – Date format for output
Returns: Array of date strings
get_data_by_date_range_container()
Purpose: Get an empty array with dates as keys for the current date range
Returns: Array with date keys and 0 values
Use Case: Create empty date containers for charting before populating with data
get_data_by_day_container()
Purpose: Get an empty array with days of week as keys (Mon-Sun)
Returns: Array with day keys and 0 values
get_data_by_hour_container()
Purpose: Get an empty array with hours as keys (00-23)
Returns: Array with hour keys and 0 values
Utility Methods
get_errors()
Purpose: Get all errors that occurred during data fetching
Returns: Array of error messages
get_execution_time()
Purpose: Get execution time for all data fetching operations
Returns: Array with execution time per data type and total
get_total_db_records()
Purpose: Get total number of database records fetched across all data types
Returns: Integer count
get_store_currency()
Purpose: Get the store’s currency code from WooCommerce settings
Returns: String currency code (e.g., ‘USD’, ‘GBP’)
determine_traffic_source( $referral_url, $query_parameters = null )
Purpose: Determine the traffic source from a referral URL
Parameters:
$referral_url(string) – The referral URL$query_parameters(array|null) – Optional query parameters
Returns: String traffic source (e.g., ‘google’, ‘facebook’, ‘direct’)
Filter Configuration
The filter array supports these keys:
array(
// Date Filters
'date_from' => '2024-01-01',
// Start date (Y-m-d format)
'date_to' => '2024-01-31',
// End date (Y-m-d format)
'date_format_display' => 'day',
// Grouping: day,
month,
quarter,
year
'date_format_string' => 'Y-m-d',
// PHP date format string
// Additional Order Data
'additional_order_data' =>
array(
'products',
'customers',
'coupons'
)
,
// Data Filters
'data_filters' =>
array(
'orders' =>
array(
'order_status' =>
array(
'wc-completed',
'wc-processing'
)
,
'billing_email' => 'customer@example.com',
'traffic_source' =>
array(
'facebook',
'google'
)
,
'device_type' =>
array(
'mobile',
'desktop'
)
,
'query_parameter_values' =>
array(
'utm_campaign' => 'summer-sale'
)
,
'order_ids' =>
array(
123,
456
)
)
,
'products' =>
array(
'products' =>
array(
100,
101,
102
)
,
// Product IDs
'product_category' =>
array(
15,
22
)
,
// Category IDs
'product_tag' =>
array(
5,
8
)
// Tag IDs
)
,
'customers' =>
array(
'billing_country' =>
array(
'US',
'GB'
)
)
,
'expenses' =>
array(
'expense_category' =>
array(
10,
11
)
// Expense category term IDs
)
,
'website_traffic' =>
array(
'traffic_source' =>
array(
'google',
'direct'
)
)
)
,
// Campaign Filters
'campaign_id' => 123,
// Filter by specific campaign ID
'campaign_date_override' => true,
// Use campaign's date range instead
// Performance
'cache' => true, // Enable query caching (default: true)
)
Complete Usage Example
// Initialize with filters
$warehouse = new WPD_Data_Warehouse_React( array(
'date_from' => '2024-01-01',
'date_to' => '2024-01-31',
'data_filters' => array(
'orders' => array(
'order_status' => array('wc-completed', 'wc-processing'),
'traffic_source' => array('facebook')
),
'products' => array(
'product_category' => array(15, 22)
)
)
));
// Fetch sales and expense data
$warehouse->fetch_sales_data();
$warehouse->fetch_expense_data();
$warehouse->fetch_store_profit_data();
// Get totals
$order_totals = $warehouse->get_data('orders', 'totals');
$expense_totals = $warehouse->get_data('expenses', 'totals');
$profit_totals = $warehouse->get_data('store_profit', 'totals');
// Get time-series data for charting
$revenue_by_date = $warehouse->get_data('orders', 'data_by_date');
$profit_by_date = $warehouse->get_data('store_profit', 'data_by_date');
// Get categorized data
$products_by_category = $warehouse->get_data('products', 'categorized_data');
// Get data table for display
$product_table = $warehouse->get_data('products', 'data_table');
// Check performance
$execution_time = $warehouse->get_execution_time();
$total_records = $warehouse->get_total_db_records();
// Display metrics
echo "Total Revenue: " . $order_totals['total_order_revenue_ex_tax'] . "n";
echo "Total Expenses: " . $expense_totals['total_amount_paid'] . "n";
echo "Store Profit: " . $profit_totals['total_store_profit'] . "n";
echo "Profit Margin: " . $profit_totals['average_store_margin'] . "%n";
echo "Records Fetched: " . $total_records . "n";
echo "Execution Time: " . $execution_time['total'] . " secondsn";
Notes
- The class is used extensively by
WPD_React_Reportfor React-based reports - All date ranges respect the store’s timezone settings
- Data is cached internally – you can call
get_data()multiple times without re-querying - The
fetch_store_profit_data()method automatically fetches orders and expenses if not already loaded - Memory limits are enforced via
$default_data_table_limitproperty (default: 500 records) - Campaign data requires Alpha Insights campaign tracking to be set up
- Analytics data requires Alpha Insights analytics tracking to be enabled
- Subscriptions data requires WooCommerce Subscriptions plugin
Related Classes
WPD_React_Report– Uses this class to fetch data for React reportsWPD_Order_Calculator– Handles profit calculations for individual ordersWPD_Report_API– REST API handler that uses this class for data endpoints