From 5b475522168219a7d7bfaaa5ed4e206058e30e60 Mon Sep 17 00:00:00 2001 From: Aidan Saunders Date: Tue, 23 May 2023 22:13:11 +0100 Subject: [PATCH] Api4: add calculated field `contact_count` to Group 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. See https://stackoverflow.com/questions/47918929/coalesce-for-zero-instead-of-null/47919047#47919047 for the COALESCE(NULLIF()) construct. --- .../Spec/Provider/GroupGetSpecProvider.php | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Civi/Api4/Service/Spec/Provider/GroupGetSpecProvider.php diff --git a/Civi/Api4/Service/Spec/Provider/GroupGetSpecProvider.php b/Civi/Api4/Service/Spec/Provider/GroupGetSpecProvider.php new file mode 100644 index 0000000000..a42d7d37ab --- /dev/null +++ b/Civi/Api4/Service/Spec/Provider/GroupGetSpecProvider.php @@ -0,0 +1,65 @@ +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 "COALESCE( + NULLIF((SELECT COUNT(contact_id) FROM `civicrm_group_contact_cache` WHERE `group_id` = {$field['sql_name']}), 0), + (SELECT COUNT(contact_id) FROM `civicrm_group_contact` WHERE `group_id` = {$field['sql_name']} AND `status` = 'Added') + )"; + } + +} -- 2.25.1