1 (function(angular
, $, _
) {
4 angular
.module('search').component('crmSearch', {
8 templateUrl
: '~/search/crmSearch.html',
9 controller: function($scope
, $element
, $timeout
, crmApi4
, dialogService
, searchMeta
, formatForSelect2
) {
10 var ts
= $scope
.ts
= CRM
.ts(),
12 this.selectedRows
= [];
13 this.limit
= CRM
.cache
.get('searchPageSize', 30);
16 // After a search this.results is an object of result arrays keyed by page,
17 // 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
19 this.rowCount
= false;
20 // Have the filters (WHERE, HAVING, GROUP BY, JOIN) changed?
22 this.allRowsSelected
= false;
25 $scope
.joinTypes
= [{k
: false, v
: ts('Optional')}, {k
: true, v
: ts('Required')}];
26 $scope
.entities
= formatForSelect2(CRM
.vars
.search
.schema
, 'name', 'title', ['description', 'icon']);
28 editGroups
: CRM
.checkPerm('edit groups')
31 this.getEntity
= searchMeta
.getEntity
;
33 this.paramExists = function(param
) {
34 return _
.includes(searchMeta
.getEntity(ctrl
.entity
).params
, param
);
37 $scope
.getJoinEntities = function() {
38 var joinEntities
= _
.transform(CRM
.vars
.search
.links
[ctrl
.entity
], function(joinEntities
, link
) {
39 var entity
= searchMeta
.getEntity(link
.entity
);
42 id
: link
.entity
+ ' AS ' + link
.alias
,
44 description
: '(' + link
.alias
+ ')',
49 return {results
: joinEntities
};
52 $scope
.addJoin = function() {
53 // Debounce the onchange event using timeout
55 if ($scope
.controls
.join
) {
56 ctrl
.params
.join
= ctrl
.params
.join
|| [];
57 ctrl
.params
.join
.push([$scope
.controls
.join
, false]);
60 $scope
.controls
.join
= '';
64 $scope
.changeJoin = function(idx
) {
65 if (ctrl
.params
.join
[idx
][0]) {
66 ctrl
.params
.join
[idx
].length
= 2;
69 ctrl
.clearParam('join', idx
);
73 $scope
.changeGroupBy = function(idx
) {
74 if (!ctrl
.params
.groupBy
[idx
]) {
75 ctrl
.clearParam('groupBy', idx
);
80 * Called when clicking on a column header
84 $scope
.setOrderBy = function(col
, $event
) {
85 var dir
= $scope
.getOrderBy(col
) === 'fa-sort-asc' ? 'DESC' : 'ASC';
86 if (!$event
.shiftKey
) {
87 ctrl
.params
.orderBy
= {};
89 ctrl
.params
.orderBy
[col
] = dir
;
93 * Returns crm-i icon class for a sortable column
97 $scope
.getOrderBy = function(col
) {
98 var dir
= ctrl
.params
.orderBy
&& ctrl
.params
.orderBy
[col
];
100 return 'fa-sort-' + dir
.toLowerCase();
102 return 'fa-sort disabled';
105 $scope
.addParam = function(name
) {
106 if ($scope
.controls
[name
] && !_
.contains(ctrl
.params
[name
], $scope
.controls
[name
])) {
107 ctrl
.params
[name
].push($scope
.controls
[name
]);
108 if (name
=== 'groupBy') {
109 // Expand the aggregate block
110 $timeout(function() {
111 $('#crm-search-build-group-aggregate.collapsed .collapsible-title').click();
115 $scope
.controls
[name
] = '';
118 // Deletes an item from an array param
119 this.clearParam = function(name
, idx
) {
120 ctrl
.params
[name
].splice(idx
, 1);
123 // Prevent visual jumps in results table height during loading
124 function lockTableHeight() {
125 var $table
= $('.crm-search-results', $element
);
126 $table
.css('height', $table
.height());
129 function unlockTableHeight() {
130 $('.crm-search-results', $element
).css('height', '');
133 // Debounced callback for loadResults
134 function _loadResultsCallback() {
135 // Multiply limit to read 2 pages at once & save ajax requests
136 var params
= angular
.merge({debug
: true, limit
: ctrl
.limit
* 2}, ctrl
.params
);
138 $scope
.error
= false;
141 ctrl
.rowCount
= false;
143 if (ctrl
.rowCount
=== false) {
144 params
.select
.push('row_count');
146 params
.offset
= ctrl
.limit
* (ctrl
.page
- 1);
147 crmApi4(ctrl
.entity
, 'get', params
).then(function(success
) {
151 if (ctrl
.rowCount
=== false) {
152 ctrl
.rowCount
= success
.count
;
154 ctrl
.debug
= success
.debug
;
155 // populate this page & the next
156 ctrl
.results
[ctrl
.page
] = success
.slice(0, ctrl
.limit
);
157 if (success
.length
> ctrl
.limit
) {
158 ctrl
.results
[ctrl
.page
+ 1] = success
.slice(ctrl
.limit
);
160 $scope
.loading
= false;
164 $scope
.loading
= false;
167 ctrl
.debug
= error
.debug
;
168 $scope
.error
= errorMsg(error
);
172 var _loadResults
= _
.debounce(_loadResultsCallback
, 250);
174 function loadResults() {
175 $scope
.loading
= true;
179 // What to tell the user when search returns an error from the server
180 // Todo: parse error codes and give helpful feedback.
181 function errorMsg(error
) {
182 return ts('Ensure all search critera are set correctly and try again.');
185 this.changePage = function() {
186 if (ctrl
.stale
|| !ctrl
.results
[ctrl
.page
]) {
192 this.refreshAll = function() {
194 ctrl
.selectedRows
.length
= 0;
198 // Refresh results while staying on current page.
199 this.refreshPage = function() {
205 $scope
.onClickSearch = function() {
206 if (ctrl
.autoSearch
) {
207 ctrl
.autoSearch
= false;
213 $scope
.onClickAuto = function() {
214 ctrl
.autoSearch
= !ctrl
.autoSearch
;
215 if (ctrl
.autoSearch
&& ctrl
.stale
) {
218 $('.crm-search-auto-toggle').blur();
221 $scope
.onChangeLimit = function() {
222 // Refresh only if search has already been run
223 if (ctrl
.autoSearch
|| ctrl
.results
) {
224 // Save page size in localStorage
225 CRM
.cache
.set('searchPageSize', ctrl
.limit
);
230 function onChangeSelect(newSelect
, oldSelect
) {
231 // Re-arranging or removing columns doesn't merit a refresh, only adding columns does
232 if (!oldSelect
|| _
.difference(newSelect
, oldSelect
).length
) {
233 if (ctrl
.autoSearch
) {
241 function onChangeOrderBy() {
247 function onChangeFilters() {
249 ctrl
.selectedRows
.length
= 0;
250 if (ctrl
.autoSearch
) {
255 $scope
.selectAllRows = function() {
257 if (ctrl
.allRowsSelected
) {
258 ctrl
.allRowsSelected
= false;
259 ctrl
.selectedRows
.length
= 0;
263 ctrl
.allRowsSelected
= true;
264 if (ctrl
.page
=== 1 && ctrl
.results
[1].length
< ctrl
.limit
) {
265 ctrl
.selectedRows
= _
.pluck(ctrl
.results
[1], 'id');
268 // If more than one page of results, use ajax to fetch all ids
269 $scope
.loadingAllRows
= true;
270 var params
= _
.cloneDeep(ctrl
.params
);
271 params
.select
= ['id'];
272 crmApi4(ctrl
.entity
, 'get', params
, ['id']).then(function(ids
) {
273 $scope
.loadingAllRows
= false;
274 ctrl
.selectedRows
= _
.toArray(ids
);
278 $scope
.selectRow = function(row
) {
279 var index
= ctrl
.selectedRows
.indexOf(row
.id
);
281 ctrl
.selectedRows
.push(row
.id
);
282 ctrl
.allRowsSelected
= (ctrl
.rowCount
=== ctrl
.selectedRows
.length
);
284 ctrl
.allRowsSelected
= false;
285 ctrl
.selectedRows
.splice(index
, 1);
289 $scope
.isRowSelected = function(row
) {
290 return ctrl
.allRowsSelected
|| _
.includes(ctrl
.selectedRows
, row
.id
);
293 this.getFieldLabel = function(col
) {
294 var info
= searchMeta
.parseExpr(col
),
295 label
= info
.field
.title
;
297 label
= '(' + info
.fn
.title
+ ') ' + label
;
302 // Is a column eligible to use an aggregate function?
303 this.canAggregate = function(col
) {
304 // If the column is used for a groupBy, no
305 if (ctrl
.params
.groupBy
.indexOf(col
) > -1) {
308 // If the entity this column belongs to is being grouped by id, then also no
309 var info
= searchMeta
.parseExpr(col
);
310 return ctrl
.params
.groupBy
.indexOf(info
.prefix
+ 'id') < 0;
313 $scope
.formatResult
= function formatResult(row
, col
) {
314 var info
= searchMeta
.parseExpr(col
),
315 key
= info
.fn
? (info
.fn
.name
+ ':' + info
.path
+ info
.suffix
) : col
,
317 // Handle grouped results
318 if (info
.fn
&& info
.fn
.name
=== 'GROUP_CONCAT' && value
) {
319 return formatGroupConcatValues(info
, value
);
321 else if (info
.fn
&& info
.fn
.name
=== 'COUNT') {
324 return formatFieldValue(info
.field
, value
);
327 function formatFieldValue(field
, value
) {
328 var type
= field
.data_type
;
329 if (value
&& (type
=== 'Date' || type
=== 'Timestamp') && /^\d{4}-\d{2}-\d{2}/.test(value
)) {
330 return CRM
.utils
.formatDate(value
, null, type
=== 'Timestamp');
332 else if (type
=== 'Boolean' && typeof value
=== 'boolean') {
333 return value
? ts('Yes') : ts('No');
335 else if (type
=== 'Money') {
336 return CRM
.formatMoney(value
);
341 function formatGroupConcatValues(info
, values
) {
342 return _
.transform(values
.split(','), function(result
, val
) {
343 if (info
.field
.options
&& !info
.suffix
) {
344 result
.push(_
.result(getOption(info
.field
, val
), 'label'));
346 result
.push(formatFieldValue(info
.field
, val
));
351 function getOption(field
, value
) {
352 return _
.find(field
.options
, function(option
) {
353 // Type coersion is intentional
354 return option
.id
== value
;
358 $scope
.fieldsForGroupBy = function() {
359 return {results
: getAllFields('', function(key
) {
360 return _
.contains(ctrl
.params
.groupBy
, key
);
365 $scope
.fieldsForSelect = function() {
366 return {results
: getAllFields(':label', function(key
) {
367 return _
.contains(ctrl
.params
.select
, key
);
372 $scope
.fieldsForWhere = function() {
373 return {results
: getAllFields(':name', _
.noop
)};
376 $scope
.fieldsForHaving = function() {
377 return {results
: _
.transform(ctrl
.params
.select
, function(fields
, name
) {
378 fields
.push({id
: name
, text
: ctrl
.getFieldLabel(name
)});
382 function getDefaultSelect() {
383 return _
.filter(['id', 'display_name', 'label', 'title', 'location_type_id:label'], searchMeta
.getField
);
386 function getAllFields(suffix
, disabledIf
) {
387 function formatFields(entityName
, prefix
) {
388 return _
.transform(searchMeta
.getEntity(entityName
).fields
, function(result
, field
) {
390 id
: prefix
+ field
.name
+ (field
.options
? suffix
: ''),
392 description
: field
.description
394 if (disabledIf(item
.id
)) {
395 item
.disabled
= true;
401 var mainEntity
= searchMeta
.getEntity(ctrl
.entity
),
403 text
: mainEntity
.title
,
404 icon
: mainEntity
.icon
,
405 children
: formatFields(ctrl
.entity
, '')
407 _
.each(ctrl
.params
.join
, function(join
) {
408 var joinName
= join
[0].split(' AS '),
409 joinEntity
= searchMeta
.getEntity(joinName
[0]);
411 text
: joinEntity
.title
+ ' (' + joinName
[1] + ')',
412 icon
: joinEntity
.icon
,
413 children
: formatFields(joinEntity
.name
, joinName
[1] + '.')
420 * Fetch pseudoconstants for main entity + joined entities
422 * Sets an optionsLoaded property on each entity to avoid duplicate requests
424 function loadFieldOptions() {
425 var mainEntity
= searchMeta
.getEntity(ctrl
.entity
),
428 function enqueue(entity
) {
429 entity
.optionsLoaded
= false;
430 entities
[entity
.name
] = [entity
.name
, 'getFields', {
431 loadOptions
: CRM
.vars
.search
.loadOptions
,
432 where
: [['options', '!=', false]],
434 }, {name
: 'options'}];
437 if (typeof mainEntity
.optionsLoaded
=== 'undefined') {
440 _
.each(ctrl
.params
.join
, function(join
) {
441 var joinName
= join
[0].split(' AS '),
442 joinEntity
= searchMeta
.getEntity(joinName
[0]);
443 if (typeof joinEntity
.optionsLoaded
=== 'undefined') {
447 if (!_
.isEmpty(entities
)) {
448 crmApi4(entities
).then(function(results
) {
449 _
.each(results
, function(fields
, entityName
) {
450 var entity
= searchMeta
.getEntity(entityName
);
451 _
.each(fields
, function(options
, fieldName
) {
452 _
.find(entity
.fields
, {name
: fieldName
}).options
= options
;
454 entity
.optionsLoaded
= true;
460 this.$onInit = function() {
461 $scope
.$bindToRoute({
462 expr
: '$ctrl.params.select',
465 default: getDefaultSelect()
467 $scope
.$watchCollection('$ctrl.params.select', onChangeSelect
);
469 $scope
.$bindToRoute({
470 expr
: '$ctrl.params.orderBy',
475 $scope
.$watchCollection('$ctrl.params.orderBy', onChangeOrderBy
);
477 $scope
.$bindToRoute({
478 expr
: '$ctrl.params.where',
484 $scope
.$watch('$ctrl.params.where', onChangeFilters
, true);
486 if (this.paramExists('groupBy')) {
487 $scope
.$bindToRoute({
488 expr
: '$ctrl.params.groupBy',
494 $scope
.$watchCollection('$ctrl.params.groupBy', onChangeFilters
);
496 if (this.paramExists('join')) {
497 $scope
.$bindToRoute({
498 expr
: '$ctrl.params.join',
505 $scope
.$watch('$ctrl.params.join', onChangeFilters
, true);
507 if (this.paramExists('having')) {
508 $scope
.$bindToRoute({
509 expr
: '$ctrl.params.having',
516 $scope
.$watch('$ctrl.params.having', onChangeFilters
, true);
521 $scope
.saveGroup = function() {
522 var selectField
= ctrl
.entity
=== 'Contact' ? 'id' : 'contact_id';
523 if (ctrl
.entity
!== 'Contact' && !searchMeta
.getField('contact_id')) {
524 CRM
.alert(ts('Cannot create smart group from %1.', {1: searchMeta
.getEntity(true).title
}), ts('Missing contact_id'), 'error', {expires
: 5000});
530 visibility
: 'User and User Admin Only',
534 params
: angular
.extend({}, ctrl
.params
, {version
: 4, select
: [selectField
]})
536 delete model
.params
.orderBy
;
537 var options
= CRM
.utils
.adjustDialogDefaults({
539 title
: ts('Save smart group')
541 dialogService
.open('saveSearchDialog', '~/search/saveSmartGroup.html', model
, options
);
546 })(angular
, CRM
.$, CRM
._
);