| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\Donors\Endpoints; |
| 4 |
|
| 5 |
use Give\Framework\Database\DB; |
| 6 |
use WP_REST_Request; |
| 7 |
use WP_REST_Response; |
| 8 |
|
| 9 |
/** |
| 10 |
* @since 4.11.0 |
| 11 |
*/ |
| 12 |
class ListDonorsStats extends Endpoint |
| 13 |
{ |
| 14 |
/** |
| 15 |
* @var string |
| 16 |
*/ |
| 17 |
protected $endpoint = 'admin/donors/stats'; |
| 18 |
|
| 19 |
/** |
| 20 |
* @var WP_REST_Request |
| 21 |
*/ |
| 22 |
protected $request; |
| 23 |
|
| 24 |
/** |
| 25 |
* @since 4.11.0 |
| 26 |
*/ |
| 27 |
public function registerRoute() |
| 28 |
{ |
| 29 |
register_rest_route( |
| 30 |
'give-api/v2', |
| 31 |
$this->endpoint, |
| 32 |
[ |
| 33 |
[ |
| 34 |
'methods' => 'GET', |
| 35 |
'callback' => [$this, 'handleRequest'], |
| 36 |
'permission_callback' => [$this, 'permissionsCheck'], |
| 37 |
], |
| 38 |
'args' => [ |
| 39 |
], |
| 40 |
] |
| 41 |
); |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* @since 4.11.0 |
| 46 |
*/ |
| 47 |
public function handleRequest(WP_REST_Request $request): WP_REST_Response |
| 48 |
{ |
| 49 |
$this->request = $request; |
| 50 |
|
| 51 |
$statistics = $this->getDonorStatistics(); |
| 52 |
|
| 53 |
return new WP_REST_Response($statistics); |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Get all donor statistics in a single optimized query |
| 58 |
* |
| 59 |
* @since 4.11.0 |
| 60 |
*/ |
| 61 |
public function getDonorStatistics(): array |
| 62 |
{ |
| 63 |
$query = DB::table('give_donors', 'donors') |
| 64 |
->leftJoin('give_subscriptions as subscriptions', 'donors.id', 'subscriptions.customer_id') |
| 65 |
->selectRaw('SELECT |
| 66 |
COUNT(DISTINCT donors.id) as total_donors, |
| 67 |
COUNT(DISTINCT subscriptions.customer_id) as recurring_donors, |
| 68 |
COUNT(DISTINCT donors.id) - COUNT(DISTINCT subscriptions.customer_id) as one_time_donors |
| 69 |
'); |
| 70 |
|
| 71 |
$result = $query->get(); |
| 72 |
|
| 73 |
// Handle case when no results are found |
| 74 |
if (!$result) { |
| 75 |
return [ |
| 76 |
'donorsCount' => 0, |
| 77 |
'oneTimeDonorsCount' => 0, |
| 78 |
'subscribersCount' => 0, |
| 79 |
]; |
| 80 |
} |
| 81 |
|
| 82 |
return [ |
| 83 |
'donorsCount' => (int) $result->total_donors, |
| 84 |
'oneTimeDonorsCount' => (int) $result->one_time_donors, |
| 85 |
'subscribersCount' => (int) $result->recurring_donors, |
| 86 |
]; |
| 87 |
} |
| 88 |
|
| 89 |
} |
| 90 |
|