Merge pull request #19262 from eileenmcnaughton/recur_test
[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 ctrl.savedSearch.api_params.join.push(params);
249 loadFieldOptions();
250 }
251 $scope.controls.join = '';
252 });
253 };
254
255 $scope.changeJoin = function(idx) {
256 if (ctrl.savedSearch.api_params.join[idx][0]) {
257 ctrl.savedSearch.api_params.join[idx].length = 2;
258 loadFieldOptions();
259 } else {
260 ctrl.clearParam('join', idx);
261 }
262 };
263
264 $scope.changeGroupBy = function(idx) {
265 if (!ctrl.savedSearch.api_params.groupBy[idx]) {
266 ctrl.clearParam('groupBy', idx);
267 }
268 // Remove aggregate functions when no grouping
269 if (!ctrl.savedSearch.api_params.groupBy.length) {
270 _.each(ctrl.savedSearch.api_params.select, function(col, pos) {
271 if (_.contains(col, '(')) {
272 var info = searchMeta.parseExpr(col);
273 if (info.fn.category === 'aggregate') {
274 ctrl.savedSearch.api_params.select[pos] = info.path + info.suffix;
275 }
276 }
277 });
278 }
279 };
280
281 function validate() {
282 var errors = [],
283 errorEl,
284 label,
285 tab;
286 if (!ctrl.savedSearch.label) {
287 errorEl = '#crm-saved-search-label';
288 label = ts('Search Label');
289 errors.push(ts('%1 is a required field.', {1: label}));
290 }
291 if (ctrl.groupExists && !ctrl.savedSearch.groups[0].title) {
292 errorEl = '#crm-search-admin-group-title';
293 label = ts('Group Title');
294 errors.push(ts('%1 is a required field.', {1: label}));
295 tab = 'group';
296 }
297 _.each(ctrl.savedSearch.displays, function(display, index) {
298 if (!display.trashed && !display.label) {
299 errorEl = '#crm-search-admin-display-label';
300 label = ts('Display Label');
301 errors.push(ts('%1 is a required field.', {1: label}));
302 tab = 'display_' + index;
303 }
304 });
305 if (errors.length) {
306 if (tab) {
307 $scope.selectTab(tab);
308 }
309 $(errorEl).crmError(errors.join('<br>'), ts('Error Saving'), {expires: 5000});
310 }
311 return !errors.length;
312 }
313
314 /**
315 * Called when clicking on a column header
316 * @param col
317 * @param $event
318 */
319 $scope.setOrderBy = function(col, $event) {
320 var dir = $scope.getOrderBy(col) === 'fa-sort-asc' ? 'DESC' : 'ASC';
321 if (!$event.shiftKey || !ctrl.savedSearch.api_params.orderBy) {
322 ctrl.savedSearch.api_params.orderBy = {};
323 }
324 ctrl.savedSearch.api_params.orderBy[col] = dir;
325 if (ctrl.results) {
326 ctrl.refreshPage();
327 }
328 };
329
330 /**
331 * Returns crm-i icon class for a sortable column
332 * @param col
333 * @returns {string}
334 */
335 $scope.getOrderBy = function(col) {
336 var dir = ctrl.savedSearch.api_params.orderBy && ctrl.savedSearch.api_params.orderBy[col];
337 if (dir) {
338 return 'fa-sort-' + dir.toLowerCase();
339 }
340 return 'fa-sort disabled';
341 };
342
343 $scope.addParam = function(name) {
344 if ($scope.controls[name] && !_.contains(ctrl.savedSearch.api_params[name], $scope.controls[name])) {
345 ctrl.savedSearch.api_params[name].push($scope.controls[name]);
346 if (name === 'groupBy') {
347 // Expand the aggregate block
348 $timeout(function() {
349 $('#crm-search-build-group-aggregate.collapsed .collapsible-title').click();
350 }, 10);
351 }
352 }
353 $scope.controls[name] = '';
354 };
355
356 // Deletes an item from an array param
357 this.clearParam = function(name, idx) {
358 ctrl.savedSearch.api_params[name].splice(idx, 1);
359 };
360
361 // Prevent visual jumps in results table height during loading
362 function lockTableHeight() {
363 var $table = $('.crm-search-results', $element);
364 $table.css('height', $table.height());
365 }
366
367 function unlockTableHeight() {
368 $('.crm-search-results', $element).css('height', '');
369 }
370
371 // Ensure all non-grouped columns are aggregated if using GROUP BY
372 function aggregateGroupByColumns() {
373 if (ctrl.savedSearch.api_params.groupBy.length) {
374 _.each(ctrl.savedSearch.api_params.select, function(col, pos) {
375 if (!_.contains(col, '(') && ctrl.canAggregate(col)) {
376 ctrl.savedSearch.api_params.select[pos] = ctrl.DEFAULT_AGGREGATE_FN + '(DISTINCT ' + col + ')';
377 }
378 });
379 }
380 }
381
382 // Debounced callback for loadResults
383 function _loadResultsCallback() {
384 // Multiply limit to read 2 pages at once & save ajax requests
385 var params = _.merge(_.cloneDeep(ctrl.savedSearch.api_params), {debug: true, limit: ctrl.limit * 2});
386 // Select the ids of joined entities (helps with displaying links)
387 _.each(params.join, function(join) {
388 var idField = join[0].split(' AS ')[1] + '.id';
389 if (!_.includes(params.select, idField) && !ctrl.canAggregate(idField)) {
390 params.select.push(idField);
391 }
392 });
393 lockTableHeight();
394 $scope.error = false;
395 if (ctrl.stale) {
396 ctrl.page = 1;
397 ctrl.rowCount = false;
398 }
399 if (ctrl.rowCount === false) {
400 params.select.push('row_count');
401 }
402 params.offset = ctrl.limit * (ctrl.page - 1);
403 crmApi4(ctrl.savedSearch.api_entity, 'get', params).then(function(success) {
404 if (ctrl.stale) {
405 ctrl.results = {};
406 }
407 if (ctrl.rowCount === false) {
408 ctrl.rowCount = success.count;
409 }
410 ctrl.debug = success.debug;
411 // populate this page & the next
412 ctrl.results[ctrl.page] = success.slice(0, ctrl.limit);
413 if (success.length > ctrl.limit) {
414 ctrl.results[ctrl.page + 1] = success.slice(ctrl.limit);
415 }
416 $scope.loading = false;
417 ctrl.stale = false;
418 unlockTableHeight();
419 }, function(error) {
420 $scope.loading = false;
421 ctrl.results = {};
422 ctrl.stale = true;
423 ctrl.debug = error.debug;
424 $scope.error = errorMsg(error);
425 })
426 .finally(function() {
427 if (ctrl.debug) {
428 ctrl.debug.params = JSON.stringify(params, null, 2);
429 if (ctrl.debug.timeIndex) {
430 ctrl.debug.timeIndex = Number.parseFloat(ctrl.debug.timeIndex).toPrecision(2);
431 }
432 }
433 });
434 }
435
436 var _loadResults = _.debounce(_loadResultsCallback, 250);
437
438 function loadResults() {
439 $scope.loading = true;
440 aggregateGroupByColumns();
441 _loadResults();
442 }
443
444 // What to tell the user when search returns an error from the server
445 // Todo: parse error codes and give helpful feedback.
446 function errorMsg(error) {
447 return ts('Ensure all search critera are set correctly and try again.');
448 }
449
450 this.changePage = function() {
451 if (ctrl.stale || !ctrl.results[ctrl.page]) {
452 lockTableHeight();
453 loadResults();
454 }
455 };
456
457 this.refreshAll = function() {
458 ctrl.stale = true;
459 ctrl.selectedRows.length = 0;
460 loadResults();
461 };
462
463 // Refresh results while staying on current page.
464 this.refreshPage = function() {
465 lockTableHeight();
466 ctrl.results = {};
467 loadResults();
468 };
469
470 $scope.onClickSearch = function() {
471 if (ctrl.autoSearch) {
472 ctrl.autoSearch = false;
473 } else {
474 ctrl.refreshAll();
475 }
476 };
477
478 $scope.onClickAuto = function() {
479 ctrl.autoSearch = !ctrl.autoSearch;
480 if (ctrl.autoSearch && ctrl.stale) {
481 ctrl.refreshAll();
482 }
483 $('.crm-search-auto-toggle').blur();
484 };
485
486 $scope.onChangeLimit = function() {
487 // Refresh only if search has already been run
488 if (ctrl.autoSearch || ctrl.results) {
489 // Save page size in localStorage
490 CRM.cache.set('searchPageSize', ctrl.limit);
491 ctrl.refreshAll();
492 }
493 };
494
495 function onChangeSelect(newSelect, oldSelect) {
496 // When removing a column from SELECT, also remove from ORDER BY
497 _.each(_.difference(_.keys(ctrl.savedSearch.api_params.orderBy), newSelect), function(col) {
498 delete ctrl.savedSearch.api_params.orderBy[col];
499 });
500 // Re-arranging or removing columns doesn't merit a refresh, only adding columns does
501 if (!oldSelect || _.difference(newSelect, oldSelect).length) {
502 if (ctrl.autoSearch) {
503 ctrl.refreshPage();
504 } else {
505 ctrl.stale = true;
506 }
507 }
508 if (ctrl.load) {
509 ctrl.saved = false;
510 }
511 }
512
513 function onChangeFilters() {
514 ctrl.stale = true;
515 ctrl.selectedRows.length = 0;
516 if (ctrl.load) {
517 ctrl.saved = false;
518 }
519 if (ctrl.autoSearch) {
520 ctrl.refreshAll();
521 }
522 }
523
524 $scope.selectAllRows = function() {
525 // Deselect all
526 if (ctrl.allRowsSelected) {
527 ctrl.allRowsSelected = false;
528 ctrl.selectedRows.length = 0;
529 return;
530 }
531 // Select all
532 ctrl.allRowsSelected = true;
533 if (ctrl.page === 1 && ctrl.results[1].length < ctrl.limit) {
534 ctrl.selectedRows = _.pluck(ctrl.results[1], 'id');
535 return;
536 }
537 // If more than one page of results, use ajax to fetch all ids
538 $scope.loadingAllRows = true;
539 var params = _.cloneDeep(ctrl.savedSearch.api_params);
540 params.select = ['id'];
541 crmApi4(ctrl.savedSearch.api_entity, 'get', params, ['id']).then(function(ids) {
542 $scope.loadingAllRows = false;
543 ctrl.selectedRows = _.toArray(ids);
544 });
545 };
546
547 $scope.selectRow = function(row) {
548 var index = ctrl.selectedRows.indexOf(row.id);
549 if (index < 0) {
550 ctrl.selectedRows.push(row.id);
551 ctrl.allRowsSelected = (ctrl.rowCount === ctrl.selectedRows.length);
552 } else {
553 ctrl.allRowsSelected = false;
554 ctrl.selectedRows.splice(index, 1);
555 }
556 };
557
558 $scope.isRowSelected = function(row) {
559 return ctrl.allRowsSelected || _.includes(ctrl.selectedRows, row.id);
560 };
561
562 this.getFieldLabel = searchMeta.getDefaultLabel;
563
564 // Is a column eligible to use an aggregate function?
565 this.canAggregate = function(col) {
566 // If the query does not use grouping, never
567 if (!ctrl.savedSearch.api_params.groupBy.length) {
568 return false;
569 }
570 var info = searchMeta.parseExpr(col);
571 // If the column is used for a groupBy, no
572 if (ctrl.savedSearch.api_params.groupBy.indexOf(info.path) > -1) {
573 return false;
574 }
575 // If the entity this column belongs to is being grouped by id, then also no
576 return ctrl.savedSearch.api_params.groupBy.indexOf(info.prefix + 'id') < 0;
577 };
578
579 $scope.formatResult = function(row, col) {
580 var info = searchMeta.parseExpr(col),
581 value = row[info.alias];
582 if (info.fn && info.fn.name === 'COUNT') {
583 return value;
584 }
585 // Output user-facing name/label fields as a link, if possible
586 if (info.field && _.includes(['display_name', 'title', 'label', 'subject'], info.field.name) && !info.fn && typeof value === 'string') {
587 var link = getEntityUrl(row, info);
588 if (link) {
589 return '<a href="' + _.escape(link.url) + '" title="' + _.escape(link.title) + '">' + formatFieldValue(info.field, value) + '</a>';
590 }
591 }
592 return formatFieldValue(info.field, value);
593 };
594
595 // Attempts to construct a view url for a given entity
596 function getEntityUrl(row, info) {
597 var entity = searchMeta.getEntity(info.field.entity),
598 path = _.result(_.findWhere(entity.paths, {action: 'view'}), 'path');
599 // Only proceed if the path metadata exists for this entity
600 if (path) {
601 // Replace tokens in the path (e.g. [id])
602 var tokens = path.match(/\[\w*]/g) || [],
603 replacements = _.transform(tokens, function(replacements, token) {
604 var fieldName = info.prefix + token.slice(1, token.length - 1);
605 if (row[fieldName]) {
606 replacements.push(row[fieldName]);
607 }
608 });
609 // Only proceed if the row contains all the necessary data to resolve tokens
610 if (tokens.length === replacements.length) {
611 _.each(tokens, function(token, index) {
612 path = path.replace(token, replacements[index]);
613 });
614 return {url: CRM.url(path), title: path.title};
615 }
616 }
617 }
618
619 function formatFieldValue(field, value) {
620 var type = field.data_type,
621 result = value;
622 if (_.isArray(value)) {
623 return _.map(value, function(val) {
624 return formatFieldValue(field, val);
625 }).join(', ');
626 }
627 if (value && (type === 'Date' || type === 'Timestamp') && /^\d{4}-\d{2}-\d{2}/.test(value)) {
628 result = CRM.utils.formatDate(value, null, type === 'Timestamp');
629 }
630 else if (type === 'Boolean' && typeof value === 'boolean') {
631 result = value ? ts('Yes') : ts('No');
632 }
633 else if (type === 'Money' && typeof value === 'number') {
634 result = CRM.formatMoney(value);
635 }
636 return _.escape(result);
637 }
638
639 $scope.fieldsForGroupBy = function() {
640 return {results: getAllFields('', function(key) {
641 return _.contains(ctrl.savedSearch.api_params.groupBy, key);
642 })
643 };
644 };
645
646 $scope.fieldsForSelect = function() {
647 return {results: getAllFields(':label', function(key) {
648 return _.contains(ctrl.savedSearch.api_params.select, key);
649 })
650 };
651 };
652
653 $scope.fieldsForWhere = function() {
654 return {results: getAllFields(':name', _.noop)};
655 };
656
657 $scope.fieldsForHaving = function() {
658 return {results: _.transform(ctrl.savedSearch.api_params.select, function(fields, name) {
659 fields.push({id: name, text: ctrl.getFieldLabel(name)});
660 })};
661 };
662
663 $scope.sortableColumnOptions = {
664 axis: 'x',
665 handle: '.crm-draggable',
666 update: function(e, ui) {
667 // Don't allow items to be moved to position 0 if locked
668 if (!ui.item.sortable.dropindex && ctrl.groupExists) {
669 ui.item.sortable.cancel();
670 }
671 }
672 };
673
674 // Sets the default select clause based on commonly-named fields
675 function getDefaultSelect() {
676 var whitelist = ['id', 'name', 'subject', 'display_name', 'label', 'title'];
677 return _.transform(searchMeta.getEntity(ctrl.savedSearch.api_entity).fields, function(select, field) {
678 if (_.includes(whitelist, field.name) || _.includes(field.name, '_type_id')) {
679 select.push(field.name + (field.options ? ':label' : ''));
680 }
681 });
682 }
683
684 function getAllFields(suffix, disabledIf) {
685 function formatFields(entityName, join) {
686 var prefix = join ? join.alias + '.' : '',
687 result = [];
688
689 function addFields(fields) {
690 _.each(fields, function(field) {
691 var item = {
692 id: prefix + field.name + (field.options ? suffix : ''),
693 text: field.label,
694 description: field.description
695 };
696 if (disabledIf(item.id)) {
697 item.disabled = true;
698 }
699 result.push(item);
700 });
701 }
702
703 // Add extra searchable fields from bridge entity
704 if (join && join.bridge) {
705 addFields(_.filter(searchMeta.getEntity(join.bridge).fields, function(field) {
706 return (field.name !== 'id' && field.name !== 'entity_id' && field.name !== 'entity_table' && !field.fk_entity);
707 }));
708 }
709
710 addFields(searchMeta.getEntity(entityName).fields);
711 return result;
712 }
713
714 var mainEntity = searchMeta.getEntity(ctrl.savedSearch.api_entity),
715 result = [{
716 text: mainEntity.title_plural,
717 icon: mainEntity.icon,
718 children: formatFields(ctrl.savedSearch.api_entity)
719 }];
720 _.each(ctrl.savedSearch.api_params.join, function(join) {
721 var joinInfo = searchMeta.getJoin(join[0]),
722 joinEntity = searchMeta.getEntity(joinInfo.entity);
723 result.push({
724 text: joinInfo.label,
725 description: joinInfo.description,
726 icon: joinEntity.icon,
727 children: formatFields(joinEntity.name, joinInfo)
728 });
729 });
730 return result;
731 }
732
733 /**
734 * Fetch pseudoconstants for main entity + joined entities
735 *
736 * Sets an optionsLoaded property on each entity to avoid duplicate requests
737 */
738 function loadFieldOptions() {
739 var mainEntity = searchMeta.getEntity(ctrl.savedSearch.api_entity),
740 entities = {};
741
742 function enqueue(entity) {
743 entity.optionsLoaded = false;
744 entities[entity.name] = [entity.name, 'getFields', {
745 loadOptions: ['id', 'name', 'label', 'description', 'color', 'icon'],
746 where: [['options', '!=', false]],
747 select: ['options']
748 }, {name: 'options'}];
749 }
750
751 if (typeof mainEntity.optionsLoaded === 'undefined') {
752 enqueue(mainEntity);
753 }
754 _.each(ctrl.savedSearch.api_params.join, function(join) {
755 var joinInfo = searchMeta.getJoin(join[0]),
756 joinEntity = searchMeta.getEntity(joinInfo.entity),
757 bridgeEntity = joinInfo.bridge ? searchMeta.getEntity(joinInfo.bridge) : null;
758 if (typeof joinEntity.optionsLoaded === 'undefined') {
759 enqueue(joinEntity);
760 }
761 if (bridgeEntity && typeof bridgeEntity.optionsLoaded === 'undefined') {
762 enqueue(bridgeEntity);
763 }
764 });
765 if (!_.isEmpty(entities)) {
766 crmApi4(entities).then(function(results) {
767 _.each(results, function(fields, entityName) {
768 var entity = searchMeta.getEntity(entityName);
769 _.each(fields, function(options, fieldName) {
770 _.find(entity.fields, {name: fieldName}).options = options;
771 });
772 entity.optionsLoaded = true;
773 });
774 });
775 }
776 }
777
778 }
779 });
780
781 })(angular, CRM.$, CRM._);