From bf374fbea73353c801de9b274ab93ca91becbb98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20Mu=C3=B1io?= Date: Fri, 18 Jun 2021 11:37:11 -0300 Subject: [PATCH] Add filter by custom fields in Accounting Batch. https://lab.civicrm.org/dev/core/-/issues/2642 --- CRM/Batch/BAO/Batch.php | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/CRM/Batch/BAO/Batch.php b/CRM/Batch/BAO/Batch.php index 91177016e2d2..65b441c90711 100644 --- a/CRM/Batch/BAO/Batch.php +++ b/CRM/Batch/BAO/Batch.php @@ -700,7 +700,19 @@ public static function getBatchFinancialItems($entityID, $returnValues, $notPres 'financial_trxn_card_type_id', 'financial_trxn_pan_truncation', ]; - $values = []; + $values = $customJoins = []; + + // If a custom field was passed as a param, + // we'll take it into account. + $customSearchFields = []; + if (!empty($params)) { + foreach ($params as $name => $param) { + if (substr($name, 0, 6) == 'custom') { + $searchFields[] = $name; + } + } + } + foreach ($searchFields as $field) { if (isset($params[$field])) { $values[$field] = $params[$field]; @@ -723,6 +735,25 @@ public static function getBatchFinancialItems($entityID, $returnValues, $notPres $values['receive_date_low'] = $date['from']; $values['receive_date_high'] = $date['to']; } + + // Add left joins as they're needed to consider + // conditions over custom fields. + if (substr($field, 0, 6) == 'custom') { + $customFieldParams = ['id' => explode('_', $field)[1]]; + $customFieldDefaults = []; + $customField = CRM_Core_BAO_CustomField::retrieve($customFieldParams, $customFieldDefaults); + + $customGroupParams = ['id' => $customField->custom_group_id]; + $customGroupDefaults = []; + $customGroup = CRM_Core_BAO_CustomGroup::retrieve($customGroupParams, $customGroupDefaults); + + $columnName = $customField->column_name; + $tableName = $customGroup->table_name; + + if (!array_key_exists($tableName, $customJoins)) { + $customJoins[$tableName] = "LEFT JOIN $tableName ON $tableName.entity_id = civicrm_contribution.id"; + } + } } } @@ -748,6 +779,10 @@ public static function getBatchFinancialItems($entityID, $returnValues, $notPres ), NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE ); + if (count($customJoins) > 0) { + $from .= " " . implode(" ", $customJoins); + } + if (!empty($query->_where[0])) { $where = implode(' AND ', $query->_where[0]) . " AND civicrm_entity_batch.batch_id IS NULL ";