Merge pull request #17526 from mattwire/frontendrequiredpaymentfrequency
[civicrm-core.git] / ext / search / ang / search / crmSearch.component.js
1 (function(angular, $, _) {
2 "use strict";
3
4 angular.module('search').component('crmSearch', {
5 bindings: {
6 entity: '='
7 },
8 templateUrl: '~/search/crmSearch.html',
9 controller: function($scope, $element, $timeout, crmApi4, dialogService, searchMeta, formatForSelect2) {
10 var ts = $scope.ts = CRM.ts(),
11 ctrl = this;
12 this.selectedRows = [];
13 this.limit = CRM.cache.get('searchPageSize', 30);
14 this.page = 1;
15 this.params = {};
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
18 this.results = '';
19 this.rowCount = false;
20 // Have the filters (WHERE, HAVING, GROUP BY, JOIN) changed?
21 this.stale = true;
22 this.allRowsSelected = false;
23
24 $scope.controls = {};
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']);
27 this.perm = {
28 editGroups: CRM.checkPerm('edit groups')
29 };
30
31 this.getEntity = searchMeta.getEntity;
32
33 this.paramExists = function(param) {
34 return _.includes(searchMeta.getEntity(ctrl.entity).params, param);
35 };
36
37 $scope.getJoinEntities = function() {
38 var joinEntities = _.transform(CRM.vars.search.links[ctrl.entity], function(joinEntities, link) {
39 var entity = searchMeta.getEntity(link.entity);
40 if (entity) {
41 joinEntities.push({
42 id: link.entity + ' AS ' + link.alias,
43 text: entity.title,
44 description: '(' + link.alias + ')',
45 icon: entity.icon
46 });
47 }
48 }, []);
49 return {results: joinEntities};
50 };
51
52 $scope.addJoin = function() {
53 // Debounce the onchange event using timeout
54 $timeout(function() {
55 if ($scope.controls.join) {
56 ctrl.params.join = ctrl.params.join || [];
57 ctrl.params.join.push([$scope.controls.join, false]);
58 loadFieldOptions();
59 }
60 $scope.controls.join = '';
61 });
62 };
63
64 $scope.changeJoin = function(idx) {
65 if (ctrl.params.join[idx][0]) {
66 ctrl.params.join[idx].length = 2;
67 loadFieldOptions();
68 } else {
69 ctrl.clearParam('join', idx);
70 }
71 };
72
73 $scope.changeGroupBy = function(idx) {
74 if (!ctrl.params.groupBy[idx]) {
75 ctrl.clearParam('groupBy', idx);
76 }
77 };
78
79 /**
80 * Called when clicking on a column header
81 * @param col
82 * @param $event
83 */
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 = {};
88 }
89 ctrl.params.orderBy[col] = dir;
90 };
91
92 /**
93 * Returns crm-i icon class for a sortable column
94 * @param col
95 * @returns {string}
96 */
97 $scope.getOrderBy = function(col) {
98 var dir = ctrl.params.orderBy && ctrl.params.orderBy[col];
99 if (dir) {
100 return 'fa-sort-' + dir.toLowerCase();
101 }
102 return 'fa-sort disabled';
103 };
104
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();
112 }, 10);
113 }
114 }
115 $scope.controls[name] = '';
116 };
117
118 // Deletes an item from an array param
119 this.clearParam = function(name, idx) {
120 ctrl.params[name].splice(idx, 1);
121 };
122
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());
127 }
128
129 function unlockTableHeight() {
130 $('.crm-search-results', $element).css('height', '');
131 }
132
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);
137 lockTableHeight();
138 $scope.error = false;
139 if (ctrl.stale) {
140 ctrl.page = 1;
141 ctrl.rowCount = false;
142 }
143 if (ctrl.rowCount === false) {
144 params.select.push('row_count');
145 }
146 params.offset = ctrl.limit * (ctrl.page - 1);
147 crmApi4(ctrl.entity, 'get', params).then(function(success) {
148 if (ctrl.stale) {
149 ctrl.results = {};
150 }
151 if (ctrl.rowCount === false) {
152 ctrl.rowCount = success.count;
153 }
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);
159 }
160 $scope.loading = false;
161 ctrl.stale = false;
162 unlockTableHeight();
163 }, function(error) {
164 $scope.loading = false;
165 ctrl.results = {};
166 ctrl.stale = true;
167 ctrl.debug = error.debug;
168 $scope.error = errorMsg(error);
169 });
170 }
171
172 var _loadResults = _.debounce(_loadResultsCallback, 250);
173
174 function loadResults() {
175 $scope.loading = true;
176 _loadResults();
177 }
178
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.');
183 }
184
185 this.changePage = function() {
186 if (ctrl.stale || !ctrl.results[ctrl.page]) {
187 lockTableHeight();
188 loadResults();
189 }
190 };
191
192 this.refreshAll = function() {
193 ctrl.stale = true;
194 ctrl.selectedRows.length = 0;
195 loadResults();
196 };
197
198 // Refresh results while staying on current page.
199 this.refreshPage = function() {
200 lockTableHeight();
201 ctrl.results = {};
202 loadResults();
203 };
204
205 $scope.onClickSearch = function() {
206 if (ctrl.autoSearch) {
207 ctrl.autoSearch = false;
208 } else {
209 ctrl.refreshAll();
210 }
211 };
212
213 $scope.onClickAuto = function() {
214 ctrl.autoSearch = !ctrl.autoSearch;
215 if (ctrl.autoSearch && ctrl.stale) {
216 ctrl.refreshAll();
217 }
218 $('.crm-search-auto-toggle').blur();
219 };
220
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);
226 ctrl.refreshAll();
227 }
228 };
229
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) {
234 ctrl.refreshPage();
235 } else {
236 ctrl.stale = true;
237 }
238 }
239 }
240
241 function onChangeOrderBy() {
242 if (ctrl.results) {
243 ctrl.refreshPage();
244 }
245 }
246
247 function onChangeFilters() {
248 ctrl.stale = true;
249 ctrl.selectedRows.length = 0;
250 if (ctrl.autoSearch) {
251 ctrl.refreshAll();
252 }
253 }
254
255 $scope.selectAllRows = function() {
256 // Deselect all
257 if (ctrl.allRowsSelected) {
258 ctrl.allRowsSelected = false;
259 ctrl.selectedRows.length = 0;
260 return;
261 }
262 // Select all
263 ctrl.allRowsSelected = true;
264 if (ctrl.page === 1 && ctrl.results[1].length < ctrl.limit) {
265 ctrl.selectedRows = _.pluck(ctrl.results[1], 'id');
266 return;
267 }
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);
275 });
276 };
277
278 $scope.selectRow = function(row) {
279 var index = ctrl.selectedRows.indexOf(row.id);
280 if (index < 0) {
281 ctrl.selectedRows.push(row.id);
282 ctrl.allRowsSelected = (ctrl.rowCount === ctrl.selectedRows.length);
283 } else {
284 ctrl.allRowsSelected = false;
285 ctrl.selectedRows.splice(index, 1);
286 }
287 };
288
289 $scope.isRowSelected = function(row) {
290 return ctrl.allRowsSelected || _.includes(ctrl.selectedRows, row.id);
291 };
292
293 this.getFieldLabel = function(col) {
294 var info = searchMeta.parseExpr(col),
295 label = info.field.title;
296 if (info.fn) {
297 label = '(' + info.fn.title + ') ' + label;
298 }
299 return label;
300 };
301
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) {
306 return false;
307 }
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;
311 };
312
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,
316 value = row[key];
317 // Handle grouped results
318 if (info.fn && info.fn.name === 'GROUP_CONCAT' && value) {
319 return formatGroupConcatValues(info, value);
320 }
321 else if (info.fn && info.fn.name === 'COUNT') {
322 return value;
323 }
324 return formatFieldValue(info.field, value);
325 };
326
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');
331 }
332 else if (type === 'Boolean' && typeof value === 'boolean') {
333 return value ? ts('Yes') : ts('No');
334 }
335 else if (type === 'Money') {
336 return CRM.formatMoney(value);
337 }
338 return value;
339 }
340
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'));
345 } else {
346 result.push(formatFieldValue(info.field, val));
347 }
348 }).join(', ');
349 }
350
351 function getOption(field, value) {
352 return _.find(field.options, function(option) {
353 // Type coersion is intentional
354 return option.id == value;
355 });
356 }
357
358 $scope.fieldsForGroupBy = function() {
359 return {results: getAllFields('', function(key) {
360 return _.contains(ctrl.params.groupBy, key);
361 })
362 };
363 };
364
365 $scope.fieldsForSelect = function() {
366 return {results: getAllFields(':label', function(key) {
367 return _.contains(ctrl.params.select, key);
368 })
369 };
370 };
371
372 $scope.fieldsForWhere = function() {
373 return {results: getAllFields(':name', _.noop)};
374 };
375
376 $scope.fieldsForHaving = function() {
377 return {results: _.transform(ctrl.params.select, function(fields, name) {
378 fields.push({id: name, text: ctrl.getFieldLabel(name)});
379 })};
380 };
381
382 function getDefaultSelect() {
383 return _.filter(['id', 'display_name', 'label', 'title', 'location_type_id:label'], searchMeta.getField);
384 }
385
386 function getAllFields(suffix, disabledIf) {
387 function formatFields(entityName, prefix) {
388 return _.transform(searchMeta.getEntity(entityName).fields, function(result, field) {
389 var item = {
390 id: prefix + field.name + (field.options ? suffix : ''),
391 text: field.title,
392 description: field.description
393 };
394 if (disabledIf(item.id)) {
395 item.disabled = true;
396 }
397 result.push(item);
398 }, []);
399 }
400
401 var mainEntity = searchMeta.getEntity(ctrl.entity),
402 result = [{
403 text: mainEntity.title,
404 icon: mainEntity.icon,
405 children: formatFields(ctrl.entity, '')
406 }];
407 _.each(ctrl.params.join, function(join) {
408 var joinName = join[0].split(' AS '),
409 joinEntity = searchMeta.getEntity(joinName[0]);
410 result.push({
411 text: joinEntity.title + ' (' + joinName[1] + ')',
412 icon: joinEntity.icon,
413 children: formatFields(joinEntity.name, joinName[1] + '.')
414 });
415 });
416 return result;
417 }
418
419 /**
420 * Fetch pseudoconstants for main entity + joined entities
421 *
422 * Sets an optionsLoaded property on each entity to avoid duplicate requests
423 */
424 function loadFieldOptions() {
425 var mainEntity = searchMeta.getEntity(ctrl.entity),
426 entities = {};
427
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]],
433 select: ['options']
434 }, {name: 'options'}];
435 }
436
437 if (typeof mainEntity.optionsLoaded === 'undefined') {
438 enqueue(mainEntity);
439 }
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') {
444 enqueue(joinEntity);
445 }
446 });
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;
453 });
454 entity.optionsLoaded = true;
455 });
456 });
457 }
458 }
459
460 this.$onInit = function() {
461 $scope.$bindToRoute({
462 expr: '$ctrl.params.select',
463 param: 'select',
464 format: 'json',
465 default: getDefaultSelect()
466 });
467 $scope.$watchCollection('$ctrl.params.select', onChangeSelect);
468
469 $scope.$bindToRoute({
470 expr: '$ctrl.params.orderBy',
471 param: 'orderBy',
472 format: 'json',
473 default: {}
474 });
475 $scope.$watchCollection('$ctrl.params.orderBy', onChangeOrderBy);
476
477 $scope.$bindToRoute({
478 expr: '$ctrl.params.where',
479 param: 'where',
480 format: 'json',
481 default: [],
482 deep: true
483 });
484 $scope.$watch('$ctrl.params.where', onChangeFilters, true);
485
486 if (this.paramExists('groupBy')) {
487 $scope.$bindToRoute({
488 expr: '$ctrl.params.groupBy',
489 param: 'groupBy',
490 format: 'json',
491 default: []
492 });
493 }
494 $scope.$watchCollection('$ctrl.params.groupBy', onChangeFilters);
495
496 if (this.paramExists('join')) {
497 $scope.$bindToRoute({
498 expr: '$ctrl.params.join',
499 param: 'join',
500 format: 'json',
501 default: [],
502 deep: true
503 });
504 }
505 $scope.$watch('$ctrl.params.join', onChangeFilters, true);
506
507 if (this.paramExists('having')) {
508 $scope.$bindToRoute({
509 expr: '$ctrl.params.having',
510 param: 'having',
511 format: 'json',
512 default: [],
513 deep: true
514 });
515 }
516 $scope.$watch('$ctrl.params.having', onChangeFilters, true);
517
518 loadFieldOptions();
519 };
520
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});
525 return;
526 }
527 var model = {
528 title: '',
529 description: '',
530 visibility: 'User and User Admin Only',
531 group_type: [],
532 id: null,
533 entity: ctrl.entity,
534 params: angular.extend({}, ctrl.params, {version: 4, select: [selectField]})
535 };
536 delete model.params.orderBy;
537 var options = CRM.utils.adjustDialogDefaults({
538 autoOpen: false,
539 title: ts('Save smart group')
540 });
541 dialogService.open('saveSearchDialog', '~/search/saveSmartGroup.html', model, options);
542 };
543 }
544 });
545
546 })(angular, CRM.$, CRM._);