Merge pull request #19426 from colemanw/searchCount
[civicrm-core.git] / ext / search / ang / crmSearchAdmin / crmSearchAdmin.component.js
1 (function(angular, $, _) {
2 "use strict";
3
4 angular.module('crmSearchAdmin').component('crmSearchAdmin', {
5 bindings: {
6 savedSearch: '<'
7 },
8 templateUrl: '~/crmSearchAdmin/crmSearchAdmin.html',
9 controller: function($scope, $element, $location, $timeout, crmApi4, dialogService, searchMeta, formatForSelect2) {
10 var ts = $scope.ts = CRM.ts(),
11 ctrl = this;
12
13 this.DEFAULT_AGGREGATE_FN = 'GROUP_CONCAT';
14
15 this.selectedRows = [];
16 this.limit = CRM.cache.get('searchPageSize', 30);
17 this.page = 1;
18 this.displayTypes = _.indexBy(CRM.crmSearchAdmin.displayTypes, 'name');
19 // After a search this.results is an object of result arrays keyed by page,
20 // Initially this.results is an empty string because 1: it's falsey (unlike an empty object) and 2: it doesn't throw an error if you try to access undefined properties (unlike null)
21 this.results = '';
22 this.rowCount = false;
23 this.allRowsSelected = false;
24 // Have the filters (WHERE, HAVING, GROUP BY, JOIN) changed?
25 this.stale = true;
26
27 $scope.controls = {tab: 'compose'};
28 $scope.joinTypes = [{k: false, v: ts('Optional')}, {k: true, v: ts('Required')}];
29 $scope.groupOptions = CRM.crmSearchActions.groupOptions;
30 // Try to create a sensible list of entities one might want to search for,
31 // excluding those whos primary purpose is to provide joins or option lists to other entities
32 var primaryEntities = _.filter(CRM.crmSearchAdmin.schema, function(entity) {
33 return !_.includes(entity.type, 'EntityBridge') && !_.includes(entity.type, 'OptionList');
34 });
35 $scope.entities = formatForSelect2(primaryEntities, 'name', 'title_plural', ['description', 'icon']);
36 this.perm = {
37 editGroups: CRM.checkPerm('edit groups')
38 };
39
40 this.$onInit = function() {
41 this.entityTitle = searchMeta.getEntity(this.savedSearch.api_entity).title_plural;
42
43 this.savedSearch.displays = this.savedSearch.displays || [];
44 this.savedSearch.groups = this.savedSearch.groups || [];
45 this.groupExists = !!this.savedSearch.groups.length;
46
47 if (!this.savedSearch.id) {
48 $scope.$bindToRoute({
49 param: 'params',
50 expr: '$ctrl.savedSearch.api_params',
51 deep: true,
52 default: {
53 version: 4,
54 select: getDefaultSelect(),
55 orderBy: {},
56 where: [],
57 }
58 });
59 }
60
61 $scope.$watchCollection('$ctrl.savedSearch.api_params.select', onChangeSelect);
62
63 $scope.$watch('$ctrl.savedSearch.api_params.where', onChangeFilters, true);
64
65 if (this.paramExists('groupBy')) {
66 this.savedSearch.api_params.groupBy = this.savedSearch.api_params.groupBy || [];
67 $scope.$watchCollection('$ctrl.savedSearch.api_params.groupBy', onChangeFilters);
68 }
69
70 if (this.paramExists('join')) {
71 this.savedSearch.api_params.join = this.savedSearch.api_params.join || [];
72 $scope.$watch('$ctrl.savedSearch.api_params.join', onChangeFilters, true);
73 }
74
75 if (this.paramExists('having')) {
76 this.savedSearch.api_params.having = this.savedSearch.api_params.having || [];
77 $scope.$watch('$ctrl.savedSearch.api_params.having', onChangeFilters, true);
78 }
79
80 $scope.$watch('$ctrl.savedSearch', onChangeAnything, true);
81
82 // After watcher runs for the first time and messes up the status, set it correctly
83 $timeout(function() {
84 $scope.status = ctrl.savedSearch && ctrl.savedSearch.id ? 'saved' : 'unsaved';
85 });
86
87 loadFieldOptions();
88 };
89
90 function onChangeAnything() {
91 $scope.status = 'unsaved';
92 }
93
94 this.save = function() {
95 if (!validate()) {
96 return;
97 }
98 $scope.status = 'saving';
99 var params = _.cloneDeep(ctrl.savedSearch),
100 apiCalls = {},
101 chain = {};
102 if (ctrl.groupExists) {
103 chain.groups = ['Group', 'save', {defaults: {saved_search_id: '$id'}, records: params.groups}];
104 delete params.groups;
105 } else if (params.id) {
106 apiCalls.deleteGroup = ['Group', 'delete', {where: [['saved_search_id', '=', params.id]]}];
107 }
108 if (params.displays && params.displays.length) {
109 chain.displays = ['SearchDisplay', 'replace', {where: [['saved_search_id', '=', '$id']], records: params.displays}];
110 } else if (params.id) {
111 apiCalls.deleteDisplays = ['SearchDisplay', 'delete', {where: [['saved_search_id', '=', params.id]]}];
112 }
113 delete params.displays;
114 apiCalls.saved = ['SavedSearch', 'save', {records: [params], chain: chain}, 0];
115 crmApi4(apiCalls).then(function(results) {
116 // After saving a new search, redirect to the edit url
117 if (!ctrl.savedSearch.id) {
118 $location.url('edit/' + results.saved.id);
119 }
120 // Set new status to saved unless the user changed something in the interim
121 var newStatus = $scope.status === 'unsaved' ? 'unsaved' : 'saved';
122 if (results.saved.groups && results.saved.groups.length) {
123 ctrl.savedSearch.groups[0].id = results.saved.groups[0].id;
124 }
125 ctrl.savedSearch.displays = results.saved.displays || [];
126 // Wait until after onChangeAnything to update status
127 $timeout(function() {
128 $scope.status = newStatus;
129 });
130 });
131 };
132
133 this.paramExists = function(param) {
134 return _.includes(searchMeta.getEntity(ctrl.savedSearch.api_entity).params, param);
135 };
136
137 this.addDisplay = function(type) {
138 ctrl.savedSearch.displays.push({
139 type: type,
140 label: ''
141 });
142 $scope.selectTab('display_' + (ctrl.savedSearch.displays.length - 1));
143 };
144
145 this.removeDisplay = function(index) {
146 var display = ctrl.savedSearch.displays[index];
147 if (display.id) {
148 display.trashed = !display.trashed;
149 if ($scope.controls.tab === ('display_' + index) && display.trashed) {
150 $scope.selectTab('compose');
151 } else if (!display.trashed) {
152 $scope.selectTab('display_' + index);
153 }
154 } else {
155 $scope.selectTab('compose');
156 ctrl.savedSearch.displays.splice(index, 1);
157 }
158 };
159
160 this.addGroup = function() {
161 ctrl.savedSearch.groups.push({
162 title: '',
163 description: '',
164 visibility: 'User and User Admin Only',
165 group_type: []
166 });
167 ctrl.groupExists = true;
168 $scope.selectTab('group');
169 };
170
171 $scope.selectTab = function(tab) {
172 if (tab === 'group') {
173 $scope.smartGroupColumns = searchMeta.getSmartGroupColumns(ctrl.savedSearch.api_entity, ctrl.savedSearch.api_params);
174 var smartGroupColumns = _.map($scope.smartGroupColumns, 'id');
175 if (smartGroupColumns.length && !_.includes(smartGroupColumns, ctrl.savedSearch.api_params.select[0])) {
176 ctrl.savedSearch.api_params.select.unshift(smartGroupColumns[0]);
177 }
178 }
179 ctrl.savedSearch.api_params.select = _.uniq(ctrl.savedSearch.api_params.select);
180 $scope.controls.tab = tab;
181 };
182
183 this.removeGroup = function() {
184 ctrl.groupExists = !ctrl.groupExists;
185 if (!ctrl.groupExists && (!ctrl.savedSearch.groups.length || !ctrl.savedSearch.groups[0].id)) {
186 ctrl.savedSearch.groups.length = 0;
187 }
188 if ($scope.controls.tab === 'group') {
189 $scope.selectTab('compose');
190 }
191 };
192
193 function addNum(name, num) {
194 return name + (num < 10 ? '_0' : '_') + num;
195 }
196
197 function getExistingJoins() {
198 return _.transform(ctrl.savedSearch.api_params.join || [], function(joins, join) {
199 joins[join[0].split(' AS ')[1]] = searchMeta.getJoin(join[0]);
200 }, {});
201 }
202
203 $scope.getJoin = searchMeta.getJoin;
204
205 $scope.getJoinEntities = function() {
206 var existingJoins = getExistingJoins();
207
208 function addEntityJoins(entity, stack, baseEntity) {
209 return _.transform(CRM.crmSearchAdmin.joins[entity], function(joinEntities, join) {
210 var num = 0;
211 // Add all joins that don't just point directly back to the original entity
212 if (!(baseEntity === join.entity && !join.multi)) {
213 do {
214 appendJoin(joinEntities, join, ++num, stack, entity);
215 } while (addNum((stack ? stack + '_' : '') + join.alias, num) in existingJoins);
216 }
217 }, []);
218 }
219
220 function appendJoin(collection, join, num, stack, baseEntity) {
221 var alias = addNum((stack ? stack + '_' : '') + join.alias, num),
222 opt = {
223 id: join.entity + ' AS ' + alias,
224 description: join.description,
225 text: join.label + (num > 1 ? ' ' + num : ''),
226 icon: searchMeta.getEntity(join.entity).icon,
227 disabled: alias in existingJoins
228 };
229 if (alias in existingJoins) {
230 opt.children = addEntityJoins(join.entity, (stack ? stack + '_' : '') + alias, baseEntity);
231 }
232 collection.push(opt);
233 }
234
235 return {results: addEntityJoins(ctrl.savedSearch.api_entity)};
236 };
237
238 $scope.addJoin = function() {
239 // Debounce the onchange event using timeout
240 $timeout(function() {
241 if ($scope.controls.join) {
242 ctrl.savedSearch.api_params.join = ctrl.savedSearch.api_params.join || [];
243 var join = searchMeta.getJoin($scope.controls.join),
244 params = [$scope.controls.join, false];
245 _.each(_.cloneDeep(join.conditions), function(condition) {
246 params.push(condition);
247 });
248 _.each(_.cloneDeep(join.defaults), function(condition) {
249 params.push(condition);
250 });
251 ctrl.savedSearch.api_params.join.push(params);
252 loadFieldOptions();
253 }
254 $scope.controls.join = '';
255 });
256 };
257
258 $scope.changeGroupBy = function(idx) {
259 if (!ctrl.savedSearch.api_params.groupBy[idx]) {
260 ctrl.clearParam('groupBy', idx);
261 }
262 // Remove aggregate functions when no grouping
263 if (!ctrl.savedSearch.api_params.groupBy.length) {
264 _.each(ctrl.savedSearch.api_params.select, function(col, pos) {
265 if (_.contains(col, '(')) {
266 var info = searchMeta.parseExpr(col);
267 if (info.fn.category === 'aggregate') {
268 ctrl.savedSearch.api_params.select[pos] = info.path + info.suffix;
269 }
270 }
271 });
272 }
273 };
274
275 function validate() {
276 var errors = [],
277 errorEl,
278 label,
279 tab;
280 if (!ctrl.savedSearch.label) {
281 errorEl = '#crm-saved-search-label';
282 label = ts('Search Label');
283 errors.push(ts('%1 is a required field.', {1: label}));
284 }
285 if (ctrl.groupExists && !ctrl.savedSearch.groups[0].title) {
286 errorEl = '#crm-search-admin-group-title';
287 label = ts('Group Title');
288 errors.push(ts('%1 is a required field.', {1: label}));
289 tab = 'group';
290 }
291 _.each(ctrl.savedSearch.displays, function(display, index) {
292 if (!display.trashed && !display.label) {
293 errorEl = '#crm-search-admin-display-label';
294 label = ts('Display Label');
295 errors.push(ts('%1 is a required field.', {1: label}));
296 tab = 'display_' + index;
297 }
298 });
299 if (errors.length) {
300 if (tab) {
301 $scope.selectTab(tab);
302 }
303 $(errorEl).crmError(errors.join('<br>'), ts('Error Saving'), {expires: 5000});
304 }
305 return !errors.length;
306 }
307
308 /**
309 * Called when clicking on a column header
310 * @param col
311 * @param $event
312 */
313 $scope.setOrderBy = function(col, $event) {
314 var dir = $scope.getOrderBy(col) === 'fa-sort-asc' ? 'DESC' : 'ASC';
315 if (!$event.shiftKey || !ctrl.savedSearch.api_params.orderBy) {
316 ctrl.savedSearch.api_params.orderBy = {};
317 }
318 ctrl.savedSearch.api_params.orderBy[col] = dir;
319 if (ctrl.results) {
320 ctrl.refreshPage();
321 }
322 };
323
324 /**
325 * Returns crm-i icon class for a sortable column
326 * @param col
327 * @returns {string}
328 */
329 $scope.getOrderBy = function(col) {
330 var dir = ctrl.savedSearch.api_params.orderBy && ctrl.savedSearch.api_params.orderBy[col];
331 if (dir) {
332 return 'fa-sort-' + dir.toLowerCase();
333 }
334 return 'fa-sort disabled';
335 };
336
337 $scope.addParam = function(name) {
338 if ($scope.controls[name] && !_.contains(ctrl.savedSearch.api_params[name], $scope.controls[name])) {
339 ctrl.savedSearch.api_params[name].push($scope.controls[name]);
340 if (name === 'groupBy') {
341 // Expand the aggregate block
342 $timeout(function() {
343 $('#crm-search-build-group-aggregate.collapsed .collapsible-title').click();
344 }, 10);
345 }
346 }
347 $scope.controls[name] = '';
348 };
349
350 // Deletes an item from an array param
351 this.clearParam = function(name, idx) {
352 ctrl.savedSearch.api_params[name].splice(idx, 1);
353 };
354
355 // Prevent visual jumps in results table height during loading
356 function lockTableHeight() {
357 var $table = $('.crm-search-results', $element);
358 $table.css('height', $table.height());
359 }
360
361 function unlockTableHeight() {
362 $('.crm-search-results', $element).css('height', '');
363 }
364
365 // Ensure all non-grouped columns are aggregated if using GROUP BY
366 function aggregateGroupByColumns() {
367 if (ctrl.savedSearch.api_params.groupBy.length) {
368 _.each(ctrl.savedSearch.api_params.select, function(col, pos) {
369 if (!_.contains(col, '(') && ctrl.canAggregate(col)) {
370 ctrl.savedSearch.api_params.select[pos] = ctrl.DEFAULT_AGGREGATE_FN + '(DISTINCT ' + col + ')';
371 }
372 });
373 }
374 }
375
376 // Debounced callback for loadResults
377 function _loadResultsCallback() {
378 // Multiply limit to read 2 pages at once & save ajax requests
379 var params = _.merge(_.cloneDeep(ctrl.savedSearch.api_params), {debug: true, limit: ctrl.limit * 2});
380 // Select the ids of joined entities (helps with displaying links)
381 _.each(params.join, function(join) {
382 var idField = join[0].split(' AS ')[1] + '.id';
383 if (!_.includes(params.select, idField) && !ctrl.canAggregate(idField)) {
384 params.select.push(idField);
385 }
386 });
387 lockTableHeight();
388 $scope.error = false;
389 if (ctrl.stale) {
390 ctrl.page = 1;
391 ctrl.rowCount = false;
392 }
393 params.offset = ctrl.limit * (ctrl.page - 1);
394 crmApi4(ctrl.savedSearch.api_entity, 'get', params).then(function(success) {
395 if (ctrl.stale) {
396 ctrl.results = {};
397 // Get row count for pager
398 // Select is only needed needed by HAVING
399 params.select = params.having && params.having.length ? params.select : [];
400 params.select.push('row_count');
401 delete params.debug;
402 crmApi4(ctrl.savedSearch.api_entity, 'get', params).then(function(result) {
403 ctrl.rowCount = result.count;
404 });
405 }
406 ctrl.debug = success.debug;
407 // populate this page & the next
408 ctrl.results[ctrl.page] = success.slice(0, ctrl.limit);
409 if (success.length > ctrl.limit) {
410 ctrl.results[ctrl.page + 1] = success.slice(ctrl.limit);
411 }
412 $scope.loading = false;
413 ctrl.stale = false;
414 unlockTableHeight();
415 }, function(error) {
416 $scope.loading = false;
417 ctrl.results = {};
418 ctrl.stale = true;
419 ctrl.debug = error.debug;
420 $scope.error = errorMsg(error);
421 })
422 .finally(function() {
423 if (ctrl.debug) {
424 ctrl.debug.params = JSON.stringify(params, null, 2);
425 if (ctrl.debug.timeIndex) {
426 ctrl.debug.timeIndex = Number.parseFloat(ctrl.debug.timeIndex).toPrecision(2);
427 }
428 }
429 });
430 }
431
432 var _loadResults = _.debounce(_loadResultsCallback, 250);
433
434 function loadResults() {
435 $scope.loading = true;
436 aggregateGroupByColumns();
437 _loadResults();
438 }
439
440 // What to tell the user when search returns an error from the server
441 // Todo: parse error codes and give helpful feedback.
442 function errorMsg(error) {
443 return ts('Ensure all search critera are set correctly and try again.');
444 }
445
446 this.changePage = function() {
447 if (ctrl.stale || !ctrl.results[ctrl.page]) {
448 lockTableHeight();
449 loadResults();
450 }
451 };
452
453 this.refreshAll = function() {
454 ctrl.stale = true;
455 ctrl.selectedRows.length = 0;
456 loadResults();
457 };
458
459 // Refresh results while staying on current page.
460 this.refreshPage = function() {
461 lockTableHeight();
462 ctrl.results = {};
463 loadResults();
464 };
465
466 $scope.onClickSearch = function() {
467 if (ctrl.autoSearch) {
468 ctrl.autoSearch = false;
469 } else {
470 ctrl.refreshAll();
471 }
472 };
473
474 $scope.onClickAuto = function() {
475 ctrl.autoSearch = !ctrl.autoSearch;
476 if (ctrl.autoSearch && ctrl.stale) {
477 ctrl.refreshAll();
478 }
479 $('.crm-search-auto-toggle').blur();
480 };
481
482 $scope.onChangeLimit = function() {
483 // Refresh only if search has already been run
484 if (ctrl.autoSearch || ctrl.results) {
485 // Save page size in localStorage
486 CRM.cache.set('searchPageSize', ctrl.limit);
487 ctrl.refreshAll();
488 }
489 };
490
491 function onChangeSelect(newSelect, oldSelect) {
492 // When removing a column from SELECT, also remove from ORDER BY
493 _.each(_.difference(_.keys(ctrl.savedSearch.api_params.orderBy), newSelect), function(col) {
494 delete ctrl.savedSearch.api_params.orderBy[col];
495 });
496 // Re-arranging or removing columns doesn't merit a refresh, only adding columns does
497 if (!oldSelect || _.difference(newSelect, oldSelect).length) {
498 if (ctrl.autoSearch) {
499 ctrl.refreshPage();
500 } else {
501 ctrl.stale = true;
502 }
503 }
504 if (ctrl.load) {
505 ctrl.saved = false;
506 }
507 }
508
509 function onChangeFilters() {
510 ctrl.stale = true;
511 ctrl.selectedRows.length = 0;
512 if (ctrl.load) {
513 ctrl.saved = false;
514 }
515 if (ctrl.autoSearch) {
516 ctrl.refreshAll();
517 }
518 }
519
520 $scope.selectAllRows = function() {
521 // Deselect all
522 if (ctrl.allRowsSelected) {
523 ctrl.allRowsSelected = false;
524 ctrl.selectedRows.length = 0;
525 return;
526 }
527 // Select all
528 ctrl.allRowsSelected = true;
529 if (ctrl.page === 1 && ctrl.results[1].length < ctrl.limit) {
530 ctrl.selectedRows = _.pluck(ctrl.results[1], 'id');
531 return;
532 }
533 // If more than one page of results, use ajax to fetch all ids
534 $scope.loadingAllRows = true;
535 var params = _.cloneDeep(ctrl.savedSearch.api_params);
536 // Select is only needed needed by HAVING
537 params.select = params.having && params.having.length ? params.select : [];
538 params.select.push('id');
539 crmApi4(ctrl.savedSearch.api_entity, 'get', params, ['id']).then(function(ids) {
540 $scope.loadingAllRows = false;
541 ctrl.selectedRows = _.toArray(ids);
542 });
543 };
544
545 $scope.selectRow = function(row) {
546 var index = ctrl.selectedRows.indexOf(row.id);
547 if (index < 0) {
548 ctrl.selectedRows.push(row.id);
549 ctrl.allRowsSelected = (ctrl.rowCount === ctrl.selectedRows.length);
550 } else {
551 ctrl.allRowsSelected = false;
552 ctrl.selectedRows.splice(index, 1);
553 }
554 };
555
556 $scope.isRowSelected = function(row) {
557 return ctrl.allRowsSelected || _.includes(ctrl.selectedRows, row.id);
558 };
559
560 this.getFieldLabel = searchMeta.getDefaultLabel;
561
562 // Is a column eligible to use an aggregate function?
563 this.canAggregate = function(col) {
564 // If the query does not use grouping, never
565 if (!ctrl.savedSearch.api_params.groupBy.length) {
566 return false;
567 }
568 var info = searchMeta.parseExpr(col);
569 // If the column is used for a groupBy, no
570 if (ctrl.savedSearch.api_params.groupBy.indexOf(info.path) > -1) {
571 return false;
572 }
573 // If the entity this column belongs to is being grouped by id, then also no
574 return ctrl.savedSearch.api_params.groupBy.indexOf(info.prefix + 'id') < 0;
575 };
576
577 $scope.formatResult = function(row, col) {
578 var info = searchMeta.parseExpr(col),
579 value = row[info.alias];
580 if (info.fn && info.fn.name === 'COUNT') {
581 return value;
582 }
583 // Output user-facing name/label fields as a link, if possible
584 if (info.field && _.includes(['display_name', 'title', 'label', 'subject'], info.field.name) && !info.fn && typeof value === 'string') {
585 var link = getEntityUrl(row, info);
586 if (link) {
587 return '<a href="' + _.escape(link.url) + '" title="' + _.escape(link.title) + '">' + formatFieldValue(info.field, value) + '</a>';
588 }
589 }
590 return formatFieldValue(info.field, value);
591 };
592
593 // Attempts to construct a view url for a given entity
594 function getEntityUrl(row, info) {
595 var entity = searchMeta.getEntity(info.field.entity),
596 path = _.result(_.findWhere(entity.paths, {action: 'view'}), 'path');
597 // Only proceed if the path metadata exists for this entity
598 if (path) {
599 // Replace tokens in the path (e.g. [id])
600 var tokens = path.match(/\[\w*]/g) || [],
601 replacements = _.transform(tokens, function(replacements, token) {
602 var fieldName = info.prefix + token.slice(1, token.length - 1);
603 if (row[fieldName]) {
604 replacements.push(row[fieldName]);
605 }
606 });
607 // Only proceed if the row contains all the necessary data to resolve tokens
608 if (tokens.length === replacements.length) {
609 _.each(tokens, function(token, index) {
610 path = path.replace(token, replacements[index]);
611 });
612 return {url: CRM.url(path), title: path.title};
613 }
614 }
615 }
616
617 function formatFieldValue(field, value) {
618 var type = field.data_type,
619 result = value;
620 if (_.isArray(value)) {
621 return _.map(value, function(val) {
622 return formatFieldValue(field, val);
623 }).join(', ');
624 }
625 if (value && (type === 'Date' || type === 'Timestamp') && /^\d{4}-\d{2}-\d{2}/.test(value)) {
626 result = CRM.utils.formatDate(value, null, type === 'Timestamp');
627 }
628 else if (type === 'Boolean' && typeof value === 'boolean') {
629 result = value ? ts('Yes') : ts('No');
630 }
631 else if (type === 'Money' && typeof value === 'number') {
632 result = CRM.formatMoney(value);
633 }
634 return _.escape(result);
635 }
636
637 $scope.fieldsForGroupBy = function() {
638 return {results: getAllFields('', function(key) {
639 return _.contains(ctrl.savedSearch.api_params.groupBy, key);
640 })
641 };
642 };
643
644 $scope.fieldsForSelect = function() {
645 return {results: getAllFields(':label', function(key) {
646 return _.contains(ctrl.savedSearch.api_params.select, key);
647 })
648 };
649 };
650
651 $scope.fieldsForWhere = function() {
652 return {results: getAllFields(':name', _.noop)};
653 };
654
655 $scope.fieldsForHaving = function() {
656 return {results: _.transform(ctrl.savedSearch.api_params.select, function(fields, name) {
657 fields.push({id: name, text: ctrl.getFieldLabel(name)});
658 })};
659 };
660
661 $scope.sortableColumnOptions = {
662 axis: 'x',
663 handle: '.crm-draggable',
664 update: function(e, ui) {
665 // Don't allow items to be moved to position 0 if locked
666 if (!ui.item.sortable.dropindex && ctrl.groupExists) {
667 ui.item.sortable.cancel();
668 }
669 }
670 };
671
672 // Sets the default select clause based on commonly-named fields
673 function getDefaultSelect() {
674 var whitelist = ['id', 'name', 'subject', 'display_name', 'label', 'title'];
675 return _.transform(searchMeta.getEntity(ctrl.savedSearch.api_entity).fields, function(select, field) {
676 if (_.includes(whitelist, field.name) || _.includes(field.name, '_type_id')) {
677 select.push(field.name + (field.options ? ':label' : ''));
678 }
679 });
680 }
681
682 function getAllFields(suffix, disabledIf) {
683 function formatFields(entityName, join) {
684 var prefix = join ? join.alias + '.' : '',
685 result = [];
686
687 function addFields(fields) {
688 _.each(fields, function(field) {
689 var item = {
690 id: prefix + field.name + (field.options ? suffix : ''),
691 text: field.label,
692 description: field.description
693 };
694 if (disabledIf(item.id)) {
695 item.disabled = true;
696 }
697 result.push(item);
698 });
699 }
700
701 // Add extra searchable fields from bridge entity
702 if (join && join.bridge) {
703 addFields(_.filter(searchMeta.getEntity(join.bridge).fields, function(field) {
704 return (field.name !== 'id' && field.name !== 'entity_id' && field.name !== 'entity_table' && !field.fk_entity);
705 }));
706 }
707
708 addFields(searchMeta.getEntity(entityName).fields);
709 return result;
710 }
711
712 var mainEntity = searchMeta.getEntity(ctrl.savedSearch.api_entity),
713 result = [{
714 text: mainEntity.title_plural,
715 icon: mainEntity.icon,
716 children: formatFields(ctrl.savedSearch.api_entity)
717 }];
718 _.each(ctrl.savedSearch.api_params.join, function(join) {
719 var joinInfo = searchMeta.getJoin(join[0]),
720 joinEntity = searchMeta.getEntity(joinInfo.entity);
721 result.push({
722 text: joinInfo.label,
723 description: joinInfo.description,
724 icon: joinEntity.icon,
725 children: formatFields(joinEntity.name, joinInfo)
726 });
727 });
728 return result;
729 }
730
731 /**
732 * Fetch pseudoconstants for main entity + joined entities
733 *
734 * Sets an optionsLoaded property on each entity to avoid duplicate requests
735 */
736 function loadFieldOptions() {
737 var mainEntity = searchMeta.getEntity(ctrl.savedSearch.api_entity),
738 entities = {};
739
740 function enqueue(entity) {
741 entity.optionsLoaded = false;
742 entities[entity.name] = [entity.name, 'getFields', {
743 loadOptions: ['id', 'name', 'label', 'description', 'color', 'icon'],
744 where: [['options', '!=', false]],
745 select: ['options']
746 }, {name: 'options'}];
747 }
748
749 if (typeof mainEntity.optionsLoaded === 'undefined') {
750 enqueue(mainEntity);
751 }
752 _.each(ctrl.savedSearch.api_params.join, function(join) {
753 var joinInfo = searchMeta.getJoin(join[0]),
754 joinEntity = searchMeta.getEntity(joinInfo.entity),
755 bridgeEntity = joinInfo.bridge ? searchMeta.getEntity(joinInfo.bridge) : null;
756 if (typeof joinEntity.optionsLoaded === 'undefined') {
757 enqueue(joinEntity);
758 }
759 if (bridgeEntity && typeof bridgeEntity.optionsLoaded === 'undefined') {
760 enqueue(bridgeEntity);
761 }
762 });
763 if (!_.isEmpty(entities)) {
764 crmApi4(entities).then(function(results) {
765 _.each(results, function(fields, entityName) {
766 var entity = searchMeta.getEntity(entityName);
767 _.each(fields, function(options, fieldName) {
768 _.find(entity.fields, {name: fieldName}).options = options;
769 });
770 entity.optionsLoaded = true;
771 });
772 });
773 }
774 }
775
776 }
777 });
778
779 })(angular, CRM.$, CRM._);