Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SearchKit - Enable rewrite in footer totals #31649

Merged
merged 2 commits into from
Dec 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ private function formatColumn($column, $data) {
$out['val'] = $this->replaceTokens($column['empty_value'], $data, 'view');
}
elseif ($column['rewrite']) {
$out['val'] = $this->rewrite($column, $data);
$out['val'] = $this->rewrite($column['rewrite'], $data);
}
else {
$dataType = $this->getSelectExpression($key)['dataType'] ?? NULL;
Expand Down Expand Up @@ -332,14 +332,15 @@ private function formatColumn($column, $data) {
/**
* Rewrite field value, subtituting tokens and evaluating smarty tags
*
* @param array $column
* @param string $rewrite
* @param array $data
* @param string $format view|raw|url
* @return string
*/
private function rewrite(array $column, array $data): string {
protected function rewrite(string $rewrite, array $data, string $format = 'view'): string {
// Cheap strpos to skip Smarty processing if not needed
$hasSmarty = strpos($column['rewrite'], '{') !== FALSE;
$output = $this->replaceTokens($column['rewrite'], $data, 'view');
$hasSmarty = strpos($rewrite, '{') !== FALSE;
$output = $this->replaceTokens($rewrite, $data, $format);
if ($hasSmarty) {
$vars = [];
$nestedIds = [];
Expand Down
131 changes: 74 additions & 57 deletions ext/search_kit/Civi/Api4/Action/SearchDisplay/Run.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ protected function processResult(SearchDisplayRunResult $result) {
$pagerMode = 'page';

$this->preprocessLinks();
$this->augmentSelectClause($apiParams, $settings);
$this->augmentSelectClause($apiParams);
$this->applyFilters();

switch ($this->return) {
Expand All @@ -70,62 +70,7 @@ protected function processResult(SearchDisplayRunResult $result) {
break;

case 'tally':
unset($apiParams['orderBy'], $apiParams['limit']);
$api = Request::create($entityName, 'get', $apiParams);
$api->setDefaultWhereClause();
$queryObject = new Api4SelectQuery($api);
$queryObject->forceSelectId = FALSE;
$sql = $queryObject->getSql();
$select = [];
foreach ($settings['columns'] as $col) {
$key = str_replace(':', '_', $col['key'] ?? '');
if (!empty($col['tally']['fn']) && \CRM_Utils_Rule::mysqlColumnNameOrAlias($key)) {
/* @var \Civi\Api4\Query\SqlFunction $sqlFnClass */
$sqlFnClass = '\Civi\Api4\Query\SqlFunction' . $col['tally']['fn'];
$fnArgs = ["`$key`"];
// Add default args (e.g. `GROUP_CONCAT(SEPARATOR)`)
foreach ($sqlFnClass::getParams() as $param) {
$name = $param['name'] ?? '';
if (!empty($param['api_default']['expr'])) {
$fnArgs[] = $name . ' ' . implode(' ', $param['api_default']['expr']);
}
// Feed field as order by
elseif ($name === 'ORDER BY') {
$fnArgs[] = "ORDER BY `$key`";
}
}
$select[] = $sqlFnClass::renderExpression(implode(' ', $fnArgs)) . " `$key`";
}
}
$query = 'SELECT ' . implode(', ', $select) . ' FROM (' . $sql . ') `api_query`';
$dao = \CRM_Core_DAO::executeQuery($query);
$dao->fetch();
$tally = [];
foreach ($settings['columns'] as $col) {
if (!empty($col['tally']['fn']) && !empty($col['key'])) {
$key = $col['key'];
$rawKey = str_replace(['.', ':'], '_', $key);
$tally[$key] = $dao->$rawKey ?? '';
// Format value according to data type of function/field
if (strlen($tally[$key])) {
$sqlExpression = SqlExpression::convert($col['tally']['fn'] . "($key)");
$selectExpression = $this->getSelectExpression($key);
$fieldName = $selectExpression['expr']->getFields()[0] ?? '';
$dataType = $selectExpression['dataType'] ?? NULL;
$sqlExpression->formatOutputValue($dataType, $tally, $key);
$field = $queryObject->getField($fieldName);
// Expand pseudoconstant list
if ($sqlExpression->supportsExpansion && $field && strpos($fieldName, ':')) {
$fieldOptions = FormattingUtil::getPseudoconstantList($field, $fieldName);
$tally[$key] = FormattingUtil::replacePseudoconstant($fieldOptions, $tally[$key]);
}
else {
$tally[$key] = $this->formatViewValue($key, $tally[$key], $tally, $dataType, $col['format'] ?? NULL);
}
}
}
}
$result[] = $tally;
$result[] = $this->getTally();
return;

default:
Expand Down Expand Up @@ -172,6 +117,78 @@ protected function processResult(SearchDisplayRunResult $result) {
}
}

/**
* @return array
* @throws \CRM_Core_Exception
*/
private function getTally(): array {
$apiParams = $this->_apiParams;
unset($apiParams['orderBy'], $apiParams['limit']);
$api = Request::create($this->savedSearch['api_entity'], 'get', $apiParams);
$api->setDefaultWhereClause();
$queryObject = new Api4SelectQuery($api);
$queryObject->forceSelectId = FALSE;
$sql = $queryObject->getSql();
$select = [];
$columns = $this->display['settings']['columns'];
foreach ($columns as $col) {
$key = str_replace(':', '_', $col['key'] ?? '');
if (!empty($col['tally']['fn']) && \CRM_Utils_Rule::mysqlColumnNameOrAlias($key)) {
/* @var \Civi\Api4\Query\SqlFunction $sqlFnClass */
$sqlFnClass = '\Civi\Api4\Query\SqlFunction' . $col['tally']['fn'];
$fnArgs = ["`$key`"];
// Add default args (e.g. `GROUP_CONCAT(SEPARATOR)`)
foreach ($sqlFnClass::getParams() as $param) {
$name = $param['name'] ?? '';
if (!empty($param['api_default']['expr'])) {
$fnArgs[] = $name . ' ' . implode(' ', $param['api_default']['expr']);
}
// Feed field as order by
elseif ($name === 'ORDER BY') {
$fnArgs[] = "ORDER BY `$key`";
}
}
$select[] = $sqlFnClass::renderExpression(implode(' ', $fnArgs)) . " `$key`";
}
}
$query = 'SELECT ' . implode(', ', $select) . ' FROM (' . $sql . ') `api_query`';
$dao = \CRM_Core_DAO::executeQuery($query);
$dao->fetch();
$tally = [];
foreach ($columns as $col) {
if (!empty($col['tally']['fn']) && !empty($col['key'])) {
$key = $col['key'];
$rawKey = str_replace(['.', ':'], '_', $key);
$tally[$key] = $dao->$rawKey ?? '';
// Format value according to data type of function/field
if (strlen($tally[$key])) {
$sqlExpression = SqlExpression::convert($col['tally']['fn'] . "($key)");
$selectExpression = $this->getSelectExpression($key);
$fieldName = $selectExpression['expr']->getFields()[0] ?? '';
$dataType = $selectExpression['dataType'] ?? NULL;
$sqlExpression->formatOutputValue($dataType, $tally, $key);
$field = $queryObject->getField($fieldName);
// Expand pseudoconstant list
if ($sqlExpression->supportsExpansion && $field && strpos($fieldName, ':')) {
$fieldOptions = FormattingUtil::getPseudoconstantList($field, $fieldName);
$tally[$key] = FormattingUtil::replacePseudoconstant($fieldOptions, $tally[$key]);
}
else {
$tally[$key] = $this->formatViewValue($key, $tally[$key], $tally, $dataType, $col['format'] ?? NULL);
}
}
}
}
$data = $tally;
// Handle any rewrite tokens
foreach ($columns as $col) {
if (!empty($col['tally']['rewrite'])) {
$tally[$key] = $this->rewrite($col['tally']['rewrite'], $data, 'raw');
}
}
return $tally;
}

/**
* Add editable information to the SearchDisplayRunResult object.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
bindings: {
model: '<',
field: '@',
// If true, limit options to only what's in the select clause
onlySelect: '<?',
suffix: '@'
},
require: {
Expand All @@ -27,7 +29,10 @@
};

this.getTokens = function() {
var allFields = ctrl.admin.getAllFields(ctrl.suffix || '', ['Field', 'Custom', 'Extra', 'Pseudo']);
let allFields = [];
if (!ctrl.onlySelect) {
allFields = ctrl.admin.getAllFields(ctrl.suffix || '', ['Field', 'Custom', 'Extra', 'Pseudo']);
}
return {
results: ctrl.admin.getSelectFields().concat(allFields)
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@
return {results: formatForSelect2(allowedFunctions, 'name', 'title', ['description'])};
};

this.toggleTallyRewrite = function(col) {
if (col.tally.rewrite) {
delete col.tally.rewrite;
} else {
col.tally.rewrite = '[' + col.key + ']';
}
};

}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@
<input class="form-control" ng-model="col.tally.label" placeholder="{{:: ts('None') }}">
<label>{{:: ts('Footer Aggregate') }}</label>
<input class="form-control" ng-model="col.tally.fn" crm-ui-select="{data: $ctrl.getTallyFunctions, placeholder: ts('None'), allowClear: true}">
<label>
<input type="checkbox" ng-click="$ctrl.toggleTallyRewrite(col)" ng-checked="!!col.tally.rewrite">
{{:: ts('Footer Rewrite') }}
</label>
<input class="form-control" ng-if="col.tally.rewrite" ng-model="col.tally.rewrite" placeholder="{{:: ts('None') }}" title="{{:: ts('Footer Rewrite') }}" ng-model-options="{updateOn: 'blur'}">
<crm-search-admin-token-select ng-if="col.tally.rewrite" model="col.tally" field="rewrite" only-select="true"></crm-search-admin-token-select>
</div>
</details>
</fieldset>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1856,6 +1856,7 @@ public function testTally(): void {
'sortable' => TRUE,
'tally' => [
'fn' => 'GROUP_FIRST',
'rewrite' => '[GROUP_FIRST_financial_type_id_label], Innit',
],
],
],
Expand All @@ -1880,7 +1881,7 @@ public function testTally(): void {
$this->assertEquals(['A, A', 'B, B', 'C, C'], $tally['GROUP_CONCAT_contact_id_sort_name']);
$this->assertSame('$1,000.00', $tally['SUM_total_amount']);
$this->assertSame('02/02/2021', $tally['GROUP_FIRST_receive_date']);
$this->assertSame('Donation', $tally['GROUP_FIRST_financial_type_id_label']);
$this->assertSame('Donation, Innit', $tally['GROUP_FIRST_financial_type_id_label']);
}

public function testContributionTotalCountWithTestAndTemplateContributions():void {
Expand Down