Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Api4: add calculated field contact_count to Group
Browse files Browse the repository at this point in the history
This provides the current count of 'added' group members and smart group
members.
Note this does not rebuild the group cache so smart group counts may be
out of date or zero.
aydun committed May 23, 2023
1 parent 6924a00 commit ce9ddbe
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions Civi/Api4/Service/Spec/Provider/GroupGetSpecProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/

namespace Civi\Api4\Service\Spec\Provider;

use Civi\Api4\Service\Spec\FieldSpec;
use Civi\Api4\Service\Spec\RequestSpec;

/**
* @service
* @internal
*/
class GroupGetSpecProvider extends \Civi\Core\Service\AutoService implements Generic\SpecProviderInterface {

/**
* @param \Civi\Api4\Service\Spec\RequestSpec $spec
*
* @throws \CRM_Core_Exception
*/
public function modifySpec(RequestSpec $spec): void {
// Number of contacts
if (!$spec->getValue('contact_count')) {
$field = new FieldSpec('contact_count', 'Group', 'Integer');
$field->setLabel(ts('Contact Count'))
->setDescription(ts('Number of contacts in group'))
->setColumnName('id')
->setReadonly(TRUE)
->setSqlRenderer([__CLASS__, 'countContacts']);
$spec->addFieldSpec($field);
}
}

/**
* @param string $entity
* @param string $action
*
* @return bool
*/
public function applies($entity, $action): bool {
return $entity === 'Group' && $action === 'get';
}

/**
* Generate SQL for counting contacts
* in static and smart groups
*
* @return string
*/
public static function countContacts(array $field): string {
return "IF(
(SELECT COUNT(contact_id) FROM `civicrm_group_contact_cache` WHERE `group_id` = {$field['sql_name']}),
(SELECT COUNT(contact_id) FROM `civicrm_group_contact_cache` WHERE `group_id` = {$field['sql_name']}),
(SELECT COUNT(contact_id) FROM `civicrm_group_contact` WHERE `group_id` = {$field['sql_name']} AND `status` = 'Added')
)";
}

}

0 comments on commit ce9ddbe

Please sign in to comment.