| 1 |
<?php //phpcs:ignore |
| 2 |
|
| 3 |
/** |
| 4 |
* RevenueController — assembles the /analytics/revenue response. |
| 5 |
* |
| 6 |
* @package Disco |
| 7 |
* @subpackage Disco\App\Analytics\Controllers |
| 8 |
* @since 1.3.23 |
| 9 |
*/ |
| 10 |
|
| 11 |
namespace Disco\App\Analytics\Controllers; |
| 12 |
|
| 13 |
use Disco\App\Analytics\Queries\RevenueQuery; |
| 14 |
|
| 15 |
/** |
| 16 |
* Resolves period, auto-selects interval, and delegates to RevenueQuery. |
| 17 |
* |
| 18 |
* Interval selection rules (based on current-period duration): |
| 19 |
* ≤ 90 days → day (max ~90 data points) |
| 20 |
* 91–365 days → week (max ~52 data points) |
| 21 |
* > 365 days → month (max ~24+ data points) |
| 22 |
* |
| 23 |
* No SQL in this class — pure orchestration. |
| 24 |
*/ |
| 25 |
class RevenueController extends BaseController { |
| 26 |
|
| 27 |
/** |
| 28 |
* Returns the full revenue time-series payload. |
| 29 |
* |
| 30 |
* @param array $args Request args with date_from and date_to as Y-m-d strings (optional). |
| 31 |
*/ |
| 32 |
public static function get_revenue( array $args ): array { |
| 33 |
$current = self::resolve_current_period( $args ); |
| 34 |
$compare = self::resolve_compare_period( $current ); |
| 35 |
$interval = self::resolve_interval( $current['from'], $current['to'] ); |
| 36 |
|
| 37 |
$data = ( new RevenueQuery )->get_revenue_series( $current, $interval ); |
| 38 |
|
| 39 |
return array( |
| 40 |
'current_period' => array( 'from' => $current['from'], 'to' => $current['to'] ), |
| 41 |
'compare_period' => array( 'from' => $compare['from'], 'to' => $compare['to'] ), |
| 42 |
'interval' => $interval, |
| 43 |
'data' => $data, |
| 44 |
); |
| 45 |
} |
| 46 |
|
| 47 |
// ========================================================================= |
| 48 |
// Interval resolution |
| 49 |
// ========================================================================= |
| 50 |
|
| 51 |
/** |
| 52 |
* Auto-selects a grouping interval based on the number of days in the range. |
| 53 |
* |
| 54 |
* ≤ 30 days → day |
| 55 |
* ≤ 180 days → week (up to ~6 months) |
| 56 |
* > 180 days → month |
| 57 |
* |
| 58 |
* @param string $from Y-m-d start date. |
| 59 |
* @param string $to Y-m-d end date. |
| 60 |
*/ |
| 61 |
private static function resolve_interval( string $from, string $to ): string { |
| 62 |
$days = (int) round( ( strtotime( $to ) - strtotime( $from ) ) / DAY_IN_SECONDS ) + 1; |
| 63 |
|
| 64 |
if ( $days <= 30 ) { |
| 65 |
return 'day'; |
| 66 |
} |
| 67 |
|
| 68 |
if ( $days <= 180 ) { |
| 69 |
return 'week'; |
| 70 |
} |
| 71 |
|
| 72 |
return 'month'; |
| 73 |
} |
| 74 |
|
| 75 |
} |
| 76 |
|