1 (function(angular
, $, _
) {
4 angular
.module('search').component('crmSearch', {
9 templateUrl
: '~/search/crmSearch.html',
10 controller: function($scope
, $element
, $timeout
, crmApi4
, dialogService
, searchMeta
, formatForSelect2
) {
11 var ts
= $scope
.ts
= CRM
.ts(),
13 this.selectedRows
= [];
14 this.limit
= CRM
.cache
.get('searchPageSize', 30);
17 // After a search this.results is an object of result arrays keyed by page,
18 // Prior to searching it's an empty string because 1: falsey and 2: doesn't throw an error if you try to access undefined properties
20 this.rowCount
= false;
21 // Have the filters (WHERE, HAVING, GROUP BY, JOIN) changed?
23 this.allRowsSelected
= false;
26 $scope
.joinTypes
= [{k
: false, v
: ts('Optional')}, {k
: true, v
: ts('Required')}];
27 $scope
.entities
= formatForSelect2(CRM
.vars
.search
.schema
, 'name', 'titlePlural', ['description', 'icon']);
29 editGroups
: CRM
.checkPerm('edit groups')
32 this.getEntity
= searchMeta
.getEntity
;
34 this.paramExists = function(param
) {
35 return _
.includes(searchMeta
.getEntity(ctrl
.entity
).params
, param
);
38 $scope
.getJoinEntities = function() {
39 var joinEntities
= _
.transform(CRM
.vars
.search
.links
[ctrl
.entity
], function(joinEntities
, link
) {
40 var entity
= searchMeta
.getEntity(link
.entity
);
43 id
: link
.entity
+ ' AS ' + link
.alias
,
44 text
: entity
.titlePlural
,
45 description
: '(' + link
.alias
+ ')',
50 return {results
: joinEntities
};
53 $scope
.addJoin = function() {
54 // Debounce the onchange event using timeout
56 if ($scope
.controls
.join
) {
57 ctrl
.params
.join
= ctrl
.params
.join
|| [];
58 ctrl
.params
.join
.push([$scope
.controls
.join
, false]);
61 $scope
.controls
.join
= '';
65 $scope
.changeJoin = function(idx
) {
66 if (ctrl
.params
.join
[idx
][0]) {
67 ctrl
.params
.join
[idx
].length
= 2;
70 ctrl
.clearParam('join', idx
);
74 $scope
.changeGroupBy = function(idx
) {
75 if (!ctrl
.params
.groupBy
[idx
]) {
76 ctrl
.clearParam('groupBy', idx
);
81 * Called when clicking on a column header
85 $scope
.setOrderBy = function(col
, $event
) {
86 var dir
= $scope
.getOrderBy(col
) === 'fa-sort-asc' ? 'DESC' : 'ASC';
87 if (!$event
.shiftKey
) {
88 ctrl
.params
.orderBy
= {};
90 ctrl
.params
.orderBy
[col
] = dir
;
94 * Returns crm-i icon class for a sortable column
98 $scope
.getOrderBy = function(col
) {
99 var dir
= ctrl
.params
.orderBy
&& ctrl
.params
.orderBy
[col
];
101 return 'fa-sort-' + dir
.toLowerCase();
103 return 'fa-sort disabled';
106 $scope
.addParam = function(name
) {
107 if ($scope
.controls
[name
] && !_
.contains(ctrl
.params
[name
], $scope
.controls
[name
])) {
108 ctrl
.params
[name
].push($scope
.controls
[name
]);
109 if (name
=== 'groupBy') {
110 // Expand the aggregate block
111 $timeout(function() {
112 $('#crm-search-build-group-aggregate.collapsed .collapsible-title').click();
116 $scope
.controls
[name
] = '';
119 // Deletes an item from an array param
120 this.clearParam = function(name
, idx
) {
121 ctrl
.params
[name
].splice(idx
, 1);
124 // Prevent visual jumps in results table height during loading
125 function lockTableHeight() {
126 var $table
= $('.crm-search-results', $element
);
127 $table
.css('height', $table
.height());
130 function unlockTableHeight() {
131 $('.crm-search-results', $element
).css('height', '');
134 // Debounced callback for loadResults
135 function _loadResultsCallback() {
136 // Multiply limit to read 2 pages at once & save ajax requests
137 var params
= angular
.merge({debug
: true, limit
: ctrl
.limit
* 2}, ctrl
.params
);
139 $scope
.error
= false;
142 ctrl
.rowCount
= false;
144 if (ctrl
.rowCount
=== false) {
145 params
.select
.push('row_count');
147 params
.offset
= ctrl
.limit
* (ctrl
.page
- 1);
148 crmApi4(ctrl
.entity
, 'get', params
).then(function(success
) {
152 if (ctrl
.rowCount
=== false) {
153 ctrl
.rowCount
= success
.count
;
155 ctrl
.debug
= success
.debug
;
156 // populate this page & the next
157 ctrl
.results
[ctrl
.page
] = success
.slice(0, ctrl
.limit
);
158 if (success
.length
> ctrl
.limit
) {
159 ctrl
.results
[ctrl
.page
+ 1] = success
.slice(ctrl
.limit
);
161 $scope
.loading
= false;
165 $scope
.loading
= false;
168 ctrl
.debug
= error
.debug
;
169 $scope
.error
= errorMsg(error
);
171 .finally(function() {
173 ctrl
.debug
.params
= JSON
.stringify(_
.extend({version
: 4}, ctrl
.params
), null, 2);
174 if (ctrl
.debug
.timeIndex
) {
175 ctrl
.debug
.timeIndex
= Number
.parseFloat(ctrl
.debug
.timeIndex
).toPrecision(2);
181 var _loadResults
= _
.debounce(_loadResultsCallback
, 250);
183 function loadResults() {
184 $scope
.loading
= true;
188 // What to tell the user when search returns an error from the server
189 // Todo: parse error codes and give helpful feedback.
190 function errorMsg(error
) {
191 return ts('Ensure all search critera are set correctly and try again.');
194 this.changePage = function() {
195 if (ctrl
.stale
|| !ctrl
.results
[ctrl
.page
]) {
201 this.refreshAll = function() {
203 ctrl
.selectedRows
.length
= 0;
207 // Refresh results while staying on current page.
208 this.refreshPage = function() {
214 $scope
.onClickSearch = function() {
215 if (ctrl
.autoSearch
) {
216 ctrl
.autoSearch
= false;
222 $scope
.onClickAuto = function() {
223 ctrl
.autoSearch
= !ctrl
.autoSearch
;
224 if (ctrl
.autoSearch
&& ctrl
.stale
) {
227 $('.crm-search-auto-toggle').blur();
230 $scope
.onChangeLimit = function() {
231 // Refresh only if search has already been run
232 if (ctrl
.autoSearch
|| ctrl
.results
) {
233 // Save page size in localStorage
234 CRM
.cache
.set('searchPageSize', ctrl
.limit
);
239 function onChangeSelect(newSelect
, oldSelect
) {
240 // Re-arranging or removing columns doesn't merit a refresh, only adding columns does
241 if (!oldSelect
|| _
.difference(newSelect
, oldSelect
).length
) {
242 if (ctrl
.autoSearch
) {
249 ctrl
.load
.saved
= false;
253 function onChangeOrderBy() {
259 function onChangeFilters() {
261 ctrl
.selectedRows
.length
= 0;
263 ctrl
.load
.saved
= false;
265 if (ctrl
.autoSearch
) {
270 $scope
.selectAllRows = function() {
272 if (ctrl
.allRowsSelected
) {
273 ctrl
.allRowsSelected
= false;
274 ctrl
.selectedRows
.length
= 0;
278 ctrl
.allRowsSelected
= true;
279 if (ctrl
.page
=== 1 && ctrl
.results
[1].length
< ctrl
.limit
) {
280 ctrl
.selectedRows
= _
.pluck(ctrl
.results
[1], 'id');
283 // If more than one page of results, use ajax to fetch all ids
284 $scope
.loadingAllRows
= true;
285 var params
= _
.cloneDeep(ctrl
.params
);
286 params
.select
= ['id'];
287 crmApi4(ctrl
.entity
, 'get', params
, ['id']).then(function(ids
) {
288 $scope
.loadingAllRows
= false;
289 ctrl
.selectedRows
= _
.toArray(ids
);
293 $scope
.selectRow = function(row
) {
294 var index
= ctrl
.selectedRows
.indexOf(row
.id
);
296 ctrl
.selectedRows
.push(row
.id
);
297 ctrl
.allRowsSelected
= (ctrl
.rowCount
=== ctrl
.selectedRows
.length
);
299 ctrl
.allRowsSelected
= false;
300 ctrl
.selectedRows
.splice(index
, 1);
304 $scope
.isRowSelected = function(row
) {
305 return ctrl
.allRowsSelected
|| _
.includes(ctrl
.selectedRows
, row
.id
);
308 this.getFieldLabel = function(col
) {
309 var info
= searchMeta
.parseExpr(col
),
310 label
= info
.field
.label
;
312 label
= '(' + info
.fn
.title
+ ') ' + label
;
317 // Is a column eligible to use an aggregate function?
318 this.canAggregate = function(col
) {
319 // If the column is used for a groupBy, no
320 if (ctrl
.params
.groupBy
.indexOf(col
) > -1) {
323 // If the entity this column belongs to is being grouped by id, then also no
324 var info
= searchMeta
.parseExpr(col
);
325 return ctrl
.params
.groupBy
.indexOf(info
.prefix
+ 'id') < 0;
328 $scope
.formatResult
= function formatResult(row
, col
) {
329 var info
= searchMeta
.parseExpr(col
),
330 key
= info
.fn
? (info
.fn
.name
+ ':' + info
.path
+ info
.suffix
) : col
,
332 // Handle grouped results
333 if (info
.fn
&& info
.fn
.name
=== 'GROUP_CONCAT' && value
) {
334 return formatGroupConcatValues(info
, value
);
336 else if (info
.fn
&& info
.fn
.name
=== 'COUNT') {
339 return formatFieldValue(info
.field
, value
);
342 function formatFieldValue(field
, value
) {
343 var type
= field
.data_type
;
344 if (value
&& (type
=== 'Date' || type
=== 'Timestamp') && /^\d{4}-\d{2}-\d{2}/.test(value
)) {
345 return CRM
.utils
.formatDate(value
, null, type
=== 'Timestamp');
347 else if (type
=== 'Boolean' && typeof value
=== 'boolean') {
348 return value
? ts('Yes') : ts('No');
350 else if (type
=== 'Money') {
351 return CRM
.formatMoney(value
);
353 if (_
.isArray(value
)) {
354 return value
.join(', ');
359 function formatGroupConcatValues(info
, values
) {
360 return _
.transform(values
.split(','), function(result
, val
) {
361 if (info
.field
.options
&& !info
.suffix
) {
362 result
.push(_
.result(getOption(info
.field
, val
), 'label'));
364 result
.push(formatFieldValue(info
.field
, val
));
369 function getOption(field
, value
) {
370 return _
.find(field
.options
, function(option
) {
371 // Type coersion is intentional
372 return option
.id
== value
;
376 $scope
.fieldsForGroupBy = function() {
377 return {results
: getAllFields('', function(key
) {
378 return _
.contains(ctrl
.params
.groupBy
, key
);
383 $scope
.fieldsForSelect = function() {
384 return {results
: getAllFields(':label', function(key
) {
385 return _
.contains(ctrl
.params
.select
, key
);
390 $scope
.fieldsForWhere = function() {
391 return {results
: getAllFields(':name', _
.noop
)};
394 $scope
.fieldsForHaving = function() {
395 return {results
: _
.transform(ctrl
.params
.select
, function(fields
, name
) {
396 fields
.push({id
: name
, text
: ctrl
.getFieldLabel(name
)});
400 function getDefaultSelect() {
401 return _
.filter(['id', 'display_name', 'label', 'title', 'location_type_id:label'], searchMeta
.getField
);
404 function getAllFields(suffix
, disabledIf
) {
405 function formatFields(entityName
, prefix
) {
406 return _
.transform(searchMeta
.getEntity(entityName
).fields
, function(result
, field
) {
408 id
: prefix
+ field
.name
+ (field
.options
? suffix
: ''),
410 description
: field
.description
412 if (disabledIf(item
.id
)) {
413 item
.disabled
= true;
419 var mainEntity
= searchMeta
.getEntity(ctrl
.entity
),
421 text
: mainEntity
.titlePlural
,
422 icon
: mainEntity
.icon
,
423 children
: formatFields(ctrl
.entity
, '')
425 _
.each(ctrl
.params
.join
, function(join
) {
426 var joinName
= join
[0].split(' AS '),
427 joinEntity
= searchMeta
.getEntity(joinName
[0]);
429 text
: joinEntity
.titlePlural
+ ' (' + joinName
[1] + ')',
430 icon
: joinEntity
.icon
,
431 children
: formatFields(joinEntity
.name
, joinName
[1] + '.')
438 * Fetch pseudoconstants for main entity + joined entities
440 * Sets an optionsLoaded property on each entity to avoid duplicate requests
442 function loadFieldOptions() {
443 var mainEntity
= searchMeta
.getEntity(ctrl
.entity
),
446 function enqueue(entity
) {
447 entity
.optionsLoaded
= false;
448 entities
[entity
.name
] = [entity
.name
, 'getFields', {
449 loadOptions
: CRM
.vars
.search
.loadOptions
,
450 where
: [['options', '!=', false]],
452 }, {name
: 'options'}];
455 if (typeof mainEntity
.optionsLoaded
=== 'undefined') {
458 _
.each(ctrl
.params
.join
, function(join
) {
459 var joinName
= join
[0].split(' AS '),
460 joinEntity
= searchMeta
.getEntity(joinName
[0]);
461 if (typeof joinEntity
.optionsLoaded
=== 'undefined') {
465 if (!_
.isEmpty(entities
)) {
466 crmApi4(entities
).then(function(results
) {
467 _
.each(results
, function(fields
, entityName
) {
468 var entity
= searchMeta
.getEntity(entityName
);
469 _
.each(fields
, function(options
, fieldName
) {
470 _
.find(entity
.fields
, {name
: fieldName
}).options
= options
;
472 entity
.optionsLoaded
= true;
478 this.$onInit = function() {
479 $scope
.$bindToRoute({
480 expr
: '$ctrl.params.select',
483 default: getDefaultSelect()
485 $scope
.$watchCollection('$ctrl.params.select', onChangeSelect
);
487 $scope
.$bindToRoute({
488 expr
: '$ctrl.params.orderBy',
493 $scope
.$watchCollection('$ctrl.params.orderBy', onChangeOrderBy
);
495 $scope
.$bindToRoute({
496 expr
: '$ctrl.params.where',
502 $scope
.$watch('$ctrl.params.where', onChangeFilters
, true);
504 if (this.paramExists('groupBy')) {
505 $scope
.$bindToRoute({
506 expr
: '$ctrl.params.groupBy',
512 $scope
.$watchCollection('$ctrl.params.groupBy', onChangeFilters
);
514 if (this.paramExists('join')) {
515 $scope
.$bindToRoute({
516 expr
: '$ctrl.params.join',
523 $scope
.$watch('$ctrl.params.join', onChangeFilters
, true);
525 if (this.paramExists('having')) {
526 $scope
.$bindToRoute({
527 expr
: '$ctrl.params.having',
534 $scope
.$watch('$ctrl.params.having', onChangeFilters
, true);
537 this.params
= this.load
.api_params
;
538 $timeout(function() {
539 ctrl
.load
.saved
= true;
546 $scope
.saveGroup = function() {
547 var selectField
= ctrl
.entity
=== 'Contact' ? 'id' : 'contact_id';
548 if (ctrl
.entity
!== 'Contact' && !searchMeta
.getField('contact_id')) {
549 CRM
.alert(ts('Cannot create smart group from %1.', {1: searchMeta
.getEntity(true).titlePlural
}), ts('Missing contact_id'), 'error', {expires
: 5000});
555 visibility
: 'User and User Admin Only',
557 id
: ctrl
.load
? ctrl
.load
.id
: null,
559 params
: angular
.extend({}, ctrl
.params
, {version
: 4})
561 delete model
.params
.orderBy
;
562 var options
= CRM
.utils
.adjustDialogDefaults({
564 title
: ts('Save smart group')
566 dialogService
.open('saveSearchDialog', '~/search/saveSmartGroup.html', model
, options
)
569 ctrl
.load
.saved
= true;
576 })(angular
, CRM
.$, CRM
._
);