Merge pull request #17476 from civicrm/5.26
[civicrm-core.git] / ang / api4Explorer / Explorer.js
CommitLineData
19b53e5b
C
1(function(angular, $, _, undefined) {
2
3 // Schema metadata
4 var schema = CRM.vars.api4.schema;
5 // FK schema data
6 var links = CRM.vars.api4.links;
7 // Cache list of entities
8 var entities = [];
9 // Cache list of actions
10 var actions = [];
11 // Field options
12 var fieldOptions = {};
13
14
15 angular.module('api4Explorer').config(function($routeProvider) {
16 $routeProvider.when('/explorer/:api4entity?/:api4action?', {
17 controller: 'Api4Explorer',
18 templateUrl: '~/api4Explorer/Explorer.html',
19 reloadOnSearch: false
20 });
21 });
22
4e97c268 23 angular.module('api4Explorer').controller('Api4Explorer', function($scope, $routeParams, $location, $timeout, $http, crmUiHelp, crmApi4, dialogService) {
6f97b1d9 24 var ts = $scope.ts = CRM.ts();
19b53e5b
C
25 $scope.entities = entities;
26 $scope.actions = actions;
27 $scope.fields = [];
9f6c0e4f 28 $scope.havingOptions = [];
19b53e5b 29 $scope.fieldsAndJoins = [];
a26e006b
CW
30 $scope.fieldsAndJoinsAndFunctions = [];
31 $scope.fieldsAndJoinsAndFunctionsAndWildcards = [];
19b53e5b
C
32 $scope.availableParams = {};
33 $scope.params = {};
34 $scope.index = '';
19d01932 35 $scope.selectedTab = {result: 'result', code: 'php'};
b65fa6dc 36 $scope.perm = {
d7507e89
CW
37 accessDebugOutput: CRM.checkPerm('access debug output'),
38 editGroups: CRM.checkPerm('edit groups')
b65fa6dc 39 };
136ca5bb 40 marked.setOptions({highlight: prettyPrintOne});
19b53e5b 41 var getMetaParams = {},
bb3786d2 42 objectParams = {orderBy: 'ASC', values: '', defaults: '', chain: ['Entity', '', '{}']},
9cea3619 43 docs = CRM.vars.api4.docs,
19b53e5b
C
44 helpTitle = '',
45 helpContent = {};
46 $scope.helpTitle = '';
47 $scope.helpContent = {};
48 $scope.entity = $routeParams.api4entity;
49 $scope.result = [];
b65fa6dc 50 $scope.debug = null;
19b53e5b
C
51 $scope.status = 'default';
52 $scope.loading = false;
53 $scope.controls = {};
f28caa2c 54 $scope.langs = ['php', 'js', 'ang', 'cli'];
c2d3af50 55 $scope.joinTypes = [{k: false, v: ts('Optional')}, {k: true, v: ts('Required')}];
f28caa2c
CW
56 $scope.code = {
57 php: [
58 {name: 'oop', label: ts('OOP Style'), code: ''},
59 {name: 'php', label: ts('Traditional'), code: ''}
60 ],
61 js: [
62 {name: 'js', label: ts('Single Call'), code: ''},
63 {name: 'js2', label: ts('Batch Calls'), code: ''}
64 ],
65 ang: [
66 {name: 'ang', label: ts('Single Call'), code: ''},
67 {name: 'ang2', label: ts('Batch Calls'), code: ''}
68 ],
69 cli: [
70 {name: 'cv', label: ts('CV'), code: ''}
71 ]
72 };
19b53e5b
C
73
74 if (!entities.length) {
75 formatForSelect2(schema, entities, 'name', ['description']);
76 }
77
78 $scope.$bindToRoute({
79 expr: 'index',
80 param: 'index',
81 default: ''
82 });
83
84 function ucfirst(str) {
85 return str[0].toUpperCase() + str.slice(1);
86 }
87
88 function lcfirst(str) {
89 return str[0].toLowerCase() + str.slice(1);
90 }
91
92 function pluralize(str) {
93 switch (str[str.length-1]) {
94 case 's':
95 return str + 'es';
96 case 'y':
97 return str.slice(0, -1) + 'ies';
98 default:
99 return str + 's';
100 }
101 }
102
19b53e5b
C
103 // Reformat an existing array of objects for compatibility with select2
104 function formatForSelect2(input, container, key, extra, prefix) {
105 _.each(input, function(item) {
106 var id = (prefix || '') + item[key];
107 var formatted = {id: id, text: id};
108 if (extra) {
109 _.merge(formatted, _.pick(item, extra));
110 }
111 container.push(formatted);
112 });
113 return container;
114 }
115
37d82abe
CW
116 // Returns field list formatted for select2
117 function getFieldList(action, addPseudoconstant) {
19b53e5b 118 var fields = [],
c752d94b 119 fieldInfo = _.findWhere(getEntity().actions, {name: action}).fields;
37d82abe
CW
120 if (addPseudoconstant) {
121 fieldInfo = _.cloneDeep(fieldInfo);
122 addPseudoconstants(fieldInfo, addPseudoconstant);
123 }
19b53e5b
C
124 formatForSelect2(fieldInfo, fields, 'name', ['description', 'required', 'default_value']);
125 return fields;
126 }
127
37d82abe
CW
128 // Note: this function expects fieldList to be select2-formatted already
129 function addJoins(fieldList, addWildcard, addPseudoconstant) {
7d91265c
CW
130 var fields = _.cloneDeep(fieldList);
131 _.each(links[$scope.entity], function(link) {
39e0f675
CW
132 var linkFields = _.cloneDeep(entityFields(link.entity)),
133 wildCard = addWildcard ? [{id: link.alias + '.*', text: link.alias + '.*', 'description': 'All core ' + link.entity + ' fields'}] : [];
19b53e5b 134 if (linkFields) {
37d82abe
CW
135 if (addPseudoconstant) {
136 addPseudoconstants(linkFields, addPseudoconstant);
137 }
19b53e5b
C
138 fields.push({
139 text: link.alias,
c2d3af50 140 description: 'Implicit join to ' + link.entity,
39e0f675 141 children: wildCard.concat(formatForSelect2(linkFields, [], 'name', ['description'], link.alias + '.'))
19b53e5b
C
142 });
143 }
144 });
145 return fields;
146 }
147
37d82abe
CW
148 // Note: this function transforms a raw list a-la getFields; not a select2-formatted list
149 function addPseudoconstants(fieldList, toAdd) {
150 var optionFields = _.filter(fieldList, 'options');
151 _.each(optionFields, function(field) {
152 var pos = _.findIndex(fieldList, {name: field.name}) + 1;
153 _.each(toAdd, function(suffix) {
154 var newField = _.cloneDeep(field);
155 newField.name += ':' + suffix;
156 fieldList.splice(pos, 0, newField);
157 });
158 });
159 }
160
136ca5bb
CW
161 $scope.help = function(title, content) {
162 if (!content) {
19b53e5b
C
163 $scope.helpTitle = helpTitle;
164 $scope.helpContent = helpContent;
165 } else {
166 $scope.helpTitle = title;
fc95d9a5 167 $scope.helpContent = formatHelp(content);
19b53e5b
C
168 }
169 };
170
136ca5bb
CW
171 // Sets the static help text (which gets overridden by mousing over other elements)
172 function setHelp(title, content) {
173 $scope.helpTitle = helpTitle = title;
fc95d9a5 174 $scope.helpContent = helpContent = formatHelp(content);
136ca5bb
CW
175 }
176
fc95d9a5
CW
177 // Convert plain-text help to markdown; replace variables and format links
178 function formatHelp(rawContent) {
179 function formatRefs(see) {
180 _.each(see, function(ref, idx) {
181 var match = ref.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
182 if (match) {
183 ref = '#/explorer/' + match[1];
184 }
185 if (ref[0] === '\\') {
186 ref = 'https://github.com/civicrm/civicrm-core/blob/master' + ref.replace(/\\/i, '/') + '.php';
187 }
188 see[idx] = '<a target="' + (ref[0] === '#' ? '_self' : '_blank') + '" href="' + ref + '">' + see[idx] + '</a>';
189 });
190 }
136ca5bb
CW
191 var formatted = _.cloneDeep(rawContent);
192 if (formatted.description) {
193 formatted.description = marked(formatted.description);
194 }
195 if (formatted.comment) {
196 formatted.comment = marked(formatted.comment);
197 }
fc95d9a5 198 formatRefs(formatted.see);
136ca5bb
CW
199 return formatted;
200 }
201
19b53e5b
C
202 $scope.fieldHelp = function(fieldName) {
203 var field = getField(fieldName, $scope.entity, $scope.action);
204 if (!field) {
205 return;
206 }
207 var info = {
208 description: field.description,
209 type: field.data_type
210 };
211 if (field.default_value) {
212 info.default = field.default_value;
213 }
214 if (field.required_if) {
215 info.required_if = field.required_if;
216 } else if (field.required) {
217 info.required = 'true';
218 }
219 return info;
220 };
221
37d82abe 222 // Returns field list for write params (values, defaults)
bb3786d2
CW
223 $scope.fieldList = function(param) {
224 return function() {
37d82abe 225 var fields = _.cloneDeep(getFieldList($scope.action === 'getFields' ? ($scope.params.action || 'get') : $scope.action, ['name']));
bb3786d2
CW
226 // Disable fields that are already in use
227 _.each($scope.params[param] || [], function(val) {
37d82abe
CW
228 var usedField = val[0].replace(':name', '');
229 (_.findWhere(fields, {id: usedField}) || {}).disabled = true;
230 (_.findWhere(fields, {id: usedField + ':name'}) || {}).disabled = true;
bb3786d2
CW
231 });
232 return {results: fields};
233 };
19b53e5b
C
234 };
235
236 $scope.formatSelect2Item = function(row) {
237 return _.escape(row.text) +
238 (row.required ? '<span class="crm-marker"> *</span>' : '') +
239 (row.description ? '<div class="crm-select2-row-description"><p>' + _.escape(row.description) + '</p></div>' : '');
240 };
241
a26e006b
CW
242 $scope.clearParam = function(name, idx) {
243 if (typeof idx === 'undefined') {
244 $scope.params[name] = $scope.availableParams[name].default;
245 } else {
246 $scope.params[name].splice(idx, 1);
247 }
19b53e5b
C
248 };
249
f0acec37
CW
250 // Gets params that should be represented as generic input fields in the explorer
251 // This fn doesn't have to be particularly efficient as its output is cached in one-time bindings
252 $scope.getGenericParams = function(paramType, defaultNull) {
253 // Returns undefined if params are not yet set; one-time bindings will stabilize when this function returns a value
254 if (_.isEmpty($scope.availableParams)) {
255 return;
256 }
c2d3af50 257 var specialParams = ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having', 'join'];
f0acec37
CW
258 if ($scope.availableParams.limit && $scope.availableParams.offset) {
259 specialParams.push('limit', 'offset');
260 }
261 return _.transform($scope.availableParams, function(genericParams, param, name) {
262 if (!_.contains(specialParams, name) &&
263 !(typeof paramType !== 'undefined' && !_.contains(paramType, param.type[0])) &&
264 !(typeof defaultNull !== 'undefined' && ((param.default === null) !== defaultNull))
265 ) {
266 genericParams[name] = param;
267 }
268 });
19b53e5b
C
269 };
270
271 $scope.selectRowCount = function() {
272 if ($scope.isSelectRowCount()) {
273 $scope.params.select = [];
274 } else {
275 $scope.params.select = ['row_count'];
2a68b84a 276 $scope.index = '';
19b53e5b
C
277 if ($scope.params.limit == 25) {
278 $scope.params.limit = 0;
279 }
280 }
281 };
282
283 $scope.isSelectRowCount = function() {
b568c26c 284 return isSelectRowCount($scope.params);
19b53e5b
C
285 };
286
f28caa2c
CW
287 $scope.selectLang = function(lang) {
288 $scope.selectedTab.code = lang;
289 writeCode();
290 };
291
b568c26c
CW
292 function isSelectRowCount(params) {
293 return params && params.select && params.select.length === 1 && params.select[0] === 'row_count';
294 }
295
19b53e5b
C
296 function getEntity(entityName) {
297 return _.findWhere(schema, {name: entityName || $scope.entity});
298 }
299
300 // Get all params that have been set
301 function getParams() {
302 var params = {};
303 _.each($scope.params, function(param, key) {
304 if (param != $scope.availableParams[key].default && !(typeof param === 'object' && _.isEmpty(param))) {
305 if (_.contains($scope.availableParams[key].type, 'array') && (typeof objectParams[key] === 'undefined')) {
6ba6f2bd 306 params[key] = parseYaml(JSON.parse(angular.toJson(param)));
19b53e5b
C
307 } else {
308 params[key] = param;
309 }
310 }
311 });
312 _.each(objectParams, function(defaultVal, key) {
313 if (params[key]) {
314 var newParam = {};
315 _.each(params[key], function(item) {
cddf293f
CW
316 var val = _.cloneDeep(item[1]);
317 // Remove blank items from "chain" array
318 if (_.isArray(val)) {
319 _.eachRight(item[1], function(v, k) {
320 if (v) {
321 return false;
322 }
323 val.length--;
324 });
325 }
326 newParam[item[0]] = parseYaml(val);
19b53e5b
C
327 });
328 params[key] = newParam;
329 }
330 });
331 return params;
332 }
333
334 function parseYaml(input) {
335 if (typeof input === 'undefined') {
336 return undefined;
337 }
6ba6f2bd
CW
338 if (input === '') {
339 return '';
340 }
19b53e5b
C
341 if (_.isObject(input) || _.isArray(input)) {
342 _.each(input, function(item, index) {
343 input[index] = parseYaml(item);
344 });
345 return input;
346 }
347 try {
348 var output = (input === '>') ? '>' : jsyaml.safeLoad(input);
349 // We don't want dates parsed to js objects
350 return _.isDate(output) ? input : output;
351 } catch (e) {
352 return input;
353 }
354 }
355
356 function selectAction() {
357 $scope.action = $routeParams.api4action;
39e0f675 358 $scope.fieldsAndJoins.length = 0;
a26e006b
CW
359 $scope.fieldsAndJoinsAndFunctions.length = 0;
360 $scope.fieldsAndJoinsAndFunctionsAndWildcards.length = 0;
19b53e5b
C
361 if (!actions.length) {
362 formatForSelect2(getEntity().actions, actions, 'name', ['description', 'params']);
363 }
364 if ($scope.action) {
365 var actionInfo = _.findWhere(actions, {id: $scope.action});
c752d94b 366 $scope.fields = getFieldList($scope.action);
19b53e5b 367 if (_.contains(['get', 'update', 'delete', 'replace'], $scope.action)) {
37d82abe
CW
368 $scope.fieldsAndJoins = addJoins(getFieldList($scope.action, ['name']));
369 var functions = [];
a26e006b
CW
370 // SQL functions are supported if HAVING is
371 if (actionInfo.params.having) {
37d82abe 372 functions.push({
a26e006b
CW
373 text: ts('FUNCTION'),
374 description: ts('Calculate result of a SQL function'),
375 children: _.transform(CRM.vars.api4.functions, function(result, fn) {
376 result.push({
377 id: fn.name + '() AS ' + fn.name.toLowerCase(),
378 text: fn.name + '()',
379 description: fn.name + '(' + describeSqlFn(fn.params) + ')'
380 });
381 })
382 });
383 }
37d82abe
CW
384 $scope.fieldsAndJoinsAndFunctions = addJoins($scope.fields.concat(functions), true);
385 $scope.fieldsAndJoinsAndFunctionsAndWildcards = addJoins(getFieldList($scope.action, ['name', 'label']).concat(functions), true, ['name', 'label']);
19b53e5b 386 } else {
37d82abe 387 $scope.fieldsAndJoins = getFieldList($scope.action, ['name']);
a26e006b 388 $scope.fieldsAndJoinsAndFunctions = $scope.fields;
37d82abe 389 $scope.fieldsAndJoinsAndFunctionsAndWildcards = getFieldList($scope.action, ['name', 'label']);
19b53e5b 390 }
a26e006b 391 $scope.fieldsAndJoinsAndFunctionsAndWildcards.unshift({id: '*', text: '*', 'description': 'All core ' + $scope.entity + ' fields'});
19b53e5b
C
392 _.each(actionInfo.params, function (param, name) {
393 var format,
394 defaultVal = _.cloneDeep(param.default);
395 if (param.type) {
396 switch (param.type[0]) {
397 case 'int':
398 case 'bool':
399 format = param.type[0];
400 break;
401
402 case 'array':
403 case 'object':
404 format = 'json';
405 break;
406
407 default:
408 format = 'raw';
409 }
9ebb0bb9 410 if (name === 'limit') {
19b53e5b
C
411 defaultVal = 25;
412 }
9ebb0bb9
CW
413 if (name === 'debug') {
414 defaultVal = true;
415 }
19b53e5b
C
416 if (name === 'values') {
417 defaultVal = defaultValues(defaultVal);
418 }
bb6bfd68
CW
419 if (name === 'loadOptions' && $scope.action === 'getFields') {
420 param.options = [
421 false,
422 true,
423 ['id', 'name', 'label'],
424 ['id', 'name', 'label', 'abbr', 'description', 'color', 'icon']
425 ];
426 format = 'json';
427 defaultVal = false;
428 param.type = ['string'];
429 }
19b53e5b
C
430 $scope.$bindToRoute({
431 expr: 'params["' + name + '"]',
432 param: name,
433 format: format,
434 default: defaultVal,
435 deep: format === 'json'
436 });
437 }
f0acec37
CW
438 if (typeof objectParams[name] !== 'undefined' && name !== 'orderBy') {
439 $scope.$watch('params.' + name, function (values) {
19b53e5b 440 // Remove empty values
a26e006b 441 _.each(values, function (clause, index) {
19b53e5b 442 if (!clause || !clause[0]) {
a26e006b 443 $scope.clearParam(name, index);
19b53e5b
C
444 }
445 });
446 }, true);
a26e006b 447 }
9f6c0e4f
CW
448 if (name === 'select' && actionInfo.params.having) {
449 $scope.$watchCollection('params.select', function(values) {
450 $scope.havingOptions.length = 0;
451 _.each(values, function(item) {
452 var pieces = item.split(' AS '),
37d82abe 453 alias = _.trim(pieces[pieces.length - 1]).replace(':label', ':name');
9f6c0e4f
CW
454 $scope.havingOptions.push({id: alias, text: alias});
455 });
456 });
457 }
c2d3af50 458 if (typeof objectParams[name] !== 'undefined' || name === 'groupBy' || name === 'select' || name === 'join') {
19b53e5b
C
459 $scope.$watch('controls.' + name, function(value) {
460 var field = value;
461 $timeout(function() {
462 if (field) {
c2d3af50
CW
463 if (name === 'join') {
464 $scope.params[name].push([field + ' AS ' + _.snakeCase(field), false, '[]']);
465 }
466 else if (typeof objectParams[name] === 'undefined') {
f0acec37
CW
467 $scope.params[name].push(field);
468 } else {
469 var defaultOp = _.cloneDeep(objectParams[name]);
470 if (name === 'chain') {
471 var num = $scope.params.chain.length;
472 defaultOp[0] = field;
473 field = 'name_me_' + num;
474 }
475 $scope.params[name].push([field, defaultOp]);
19b53e5b 476 }
19b53e5b
C
477 $scope.controls[name] = null;
478 }
479 });
480 });
481 }
482 });
483 $scope.availableParams = actionInfo.params;
484 }
485 writeCode();
486 }
487
a26e006b
CW
488 function describeSqlFn(params) {
489 var desc = ' ';
490 _.each(params, function(param) {
491 desc += ' ';
492 if (param.prefix) {
493 desc += _.filter(param.prefix).join('|') + ' ';
494 }
495 if (param.expr === 1) {
496 desc += 'expr ';
497 } else if (param.expr > 1) {
498 desc += 'expr, ... ';
499 }
500 if (param.suffix) {
501 desc += ' ' + _.filter(param.suffix).join('|') + ' ';
502 }
503 });
504 return desc.replace(/[ ]+/g, ' ');
505 }
506
19b53e5b
C
507 function defaultValues(defaultVal) {
508 _.each($scope.fields, function(field) {
509 if (field.required) {
510 defaultVal.push([field.id, '']);
511 }
512 });
513 return defaultVal;
514 }
515
516 function stringify(value, trim) {
517 if (typeof value === 'undefined') {
518 return '';
519 }
520 var str = JSON.stringify(value).replace(/,/g, ', ');
521 if (trim) {
522 str = str.slice(1, -1);
523 }
524 return str.trim();
525 }
526
527 function writeCode() {
19d01932 528 var code = {},
19b53e5b
C
529 entity = $scope.entity,
530 action = $scope.action,
531 params = getParams(),
2a68b84a 532 index = isInt($scope.index) ? +$scope.index : parseYaml($scope.index),
19b53e5b
C
533 result = 'result';
534 if ($scope.entity && $scope.action) {
9ebb0bb9 535 delete params.debug;
19b53e5b
C
536 if (action.slice(0, 3) === 'get') {
537 result = entity.substr(0, 7) === 'Custom_' ? _.camelCase(entity.substr(7)) : entity;
538 result = lcfirst(action.replace(/s$/, '').slice(3) || result);
539 }
540 var results = lcfirst(_.isNumber(index) ? result : pluralize(result)),
541 paramCount = _.size(params),
19b53e5b
C
542 i = 0;
543
b568c26c 544 if (isSelectRowCount(params)) {
19b53e5b
C
545 results = result + 'Count';
546 }
547
f28caa2c
CW
548 switch ($scope.selectedTab.code) {
549 case 'js':
550 case 'ang':
551 // Write javascript
552 var js = "'" + entity + "', '" + action + "', {";
553 _.each(params, function(param, key) {
554 js += "\n " + key + ': ' + stringify(param) +
555 (++i < paramCount ? ',' : '');
556 if (key === 'checkPermissions') {
557 js += ' // IGNORED: permissions are always enforced from client-side requests';
558 }
559 });
560 js += "\n}";
561 if (index || index === 0) {
562 js += ', ' + JSON.stringify(index);
563 }
564 code.js = "CRM.api4(" + js + ").then(function(" + results + ") {\n // do something with " + results + " array\n}, function(failure) {\n // handle failure\n});";
565 code.js2 = "CRM.api4({" + results + ': [' + js + "]}).then(function(batch) {\n // do something with batch." + results + " array\n}, function(failure) {\n // handle failure\n});";
566 code.ang = "crmApi4(" + js + ").then(function(" + results + ") {\n // do something with " + results + " array\n}, function(failure) {\n // handle failure\n});";
567 code.ang2 = "crmApi4({" + results + ': [' + js + "]}).then(function(batch) {\n // do something with batch." + results + " array\n}, function(failure) {\n // handle failure\n});";
568 break;
569
570 case 'php':
571 // Write php code
572 code.php = '$' + results + " = civicrm_api4('" + entity + "', '" + action + "', [";
573 _.each(params, function(param, key) {
574 code.php += "\n '" + key + "' => " + phpFormat(param, 4) + ',';
575 });
576 code.php += "\n]";
577 if (index || index === 0) {
578 code.php += ', ' + phpFormat(index);
579 }
580 code.php += ");";
581
582 // Write oop code
583 code.oop = '$' + results + " = " + formatOOP(entity, action, params, 2) + "\n ->execute()";
584 if (isSelectRowCount(params)) {
585 code.oop += "\n ->count()";
586 } else if (_.isNumber(index)) {
587 code.oop += !index ? '\n ->first()' : (index === -1 ? '\n ->last()' : '\n ->itemAt(' + index + ')');
588 } else if (index) {
589 if (_.isString(index) || (_.isPlainObject(index) && !index[0] && !index['0'])) {
590 code.oop += "\n ->indexBy('" + (_.isPlainObject(index) ? _.keys(index)[0] : index) + "')";
591 }
592 if (_.isArray(index) || _.isPlainObject(index)) {
593 code.oop += "\n ->column('" + (_.isArray(index) ? index[0] : _.values(index)[0]) + "')";
594 }
595 }
596 code.oop += ";\n";
597 if (!_.isNumber(index) && !isSelectRowCount(params)) {
598 code.oop += "foreach ($" + results + ' as $' + ((_.isString(index) && index) ? index + ' => $' : '') + result + ') {\n // do something\n}';
599 }
600 break;
3b1f7ce7 601
f28caa2c
CW
602 case 'cli':
603 // Write cli code
604 code.cv = 'cv api4 ' + entity + '.' + action + " '" + stringify(params) + "'";
19b53e5b 605 }
19b53e5b 606 }
19d01932 607 _.each($scope.code, function(vals) {
f28caa2c 608 _.each(vals, function(style) {
19d01932
CW
609 style.code = code[style.name] ? prettyPrintOne(code[style.name]) : '';
610 });
19b53e5b
C
611 });
612 }
613
b568c26c
CW
614 // Format oop params
615 function formatOOP(entity, action, params, indent) {
616 var code = '',
617 newLine = "\n" + _.repeat(' ', indent);
618 if (entity.substr(0, 7) !== 'Custom_') {
619 code = "\\Civi\\Api4\\" + entity + '::' + action + '()';
620 } else {
621 code = "\\Civi\\Api4\\CustomValue::" + action + "('" + entity.substr(7) + "')";
622 }
623 _.each(params, function(param, key) {
624 var val = '';
625 if (typeof objectParams[key] !== 'undefined' && key !== 'chain') {
626 _.each(param, function(item, index) {
627 val = phpFormat(index) + ', ' + phpFormat(item, 2 + indent);
628 code += newLine + "->add" + ucfirst(key).replace(/s$/, '') + '(' + val + ')';
629 });
630 } else if (key === 'where') {
631 _.each(param, function (clause) {
632 if (clause[0] === 'AND' || clause[0] === 'OR' || clause[0] === 'NOT') {
633 code += newLine + "->addClause(" + phpFormat(clause[0]) + ", " + phpFormat(clause[1]).slice(1, -1) + ')';
634 } else {
635 code += newLine + "->addWhere(" + phpFormat(clause).slice(1, -1) + ")";
636 }
637 });
638 } else if (key === 'select') {
639 code += newLine;
640 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
641 code += isSelectRowCount(params) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param).slice(1, -1) + ')';
642 } else if (key === 'chain') {
643 _.each(param, function(chain, name) {
644 code += newLine + "->addChain('" + name + "', " + formatOOP(chain[0], chain[1], chain[2], 2 + indent);
645 code += (chain.length > 3 ? ',' : '') + (!_.isEmpty(chain[2]) ? newLine : ' ') + (chain.length > 3 ? phpFormat(chain[3]) : '') + ')';
646 });
647 }
648 else {
649 code += newLine + "->set" + ucfirst(key) + '(' + phpFormat(param, 2 + indent) + ')';
650 }
651 });
652 return code;
653 }
654
19b53e5b
C
655 function isInt(value) {
656 if (_.isFinite(value)) {
657 return true;
658 }
659 if (!_.isString(value)) {
660 return false;
661 }
662 return /^-{0,1}\d+$/.test(value);
663 }
664
665 function formatMeta(resp) {
666 var ret = '';
667 _.each(resp, function(val, key) {
668 if (key !== 'values' && !_.isPlainObject(val) && !_.isFunction(val)) {
669 ret += (ret.length ? ', ' : '') + key + ': ' + (_.isArray(val) ? '[' + val + ']' : val);
670 }
671 });
3b1f7ce7 672 return prettyPrintOne(_.escape(ret));
19b53e5b
C
673 }
674
675 $scope.execute = function() {
2aafb0fc 676 $scope.status = 'info';
19b53e5b 677 $scope.loading = true;
2e40130b 678 $http.post(CRM.url('civicrm/ajax/api4/' + $scope.entity + '/' + $scope.action, {
19b53e5b 679 params: angular.toJson(getParams()),
2a68b84a 680 index: isInt($scope.index) ? +$scope.index : parseYaml($scope.index)
2e40130b 681 }), null, {
ea3acfee
SL
682 headers: {
683 'X-Requested-With': 'XMLHttpRequest'
684 }
685 }).then(function(resp) {
19b53e5b 686 $scope.loading = false;
2aafb0fc 687 $scope.status = resp.data && resp.data.debug && resp.data.debug.log ? 'warning' : 'success';
b65fa6dc 688 $scope.debug = debugFormat(resp.data);
3b1f7ce7 689 $scope.result = [formatMeta(resp.data), prettyPrintOne(_.escape(JSON.stringify(resp.data.values, null, 2)), 'js', 1)];
19b53e5b
C
690 }, function(resp) {
691 $scope.loading = false;
692 $scope.status = 'danger';
b65fa6dc 693 $scope.debug = debugFormat(resp.data);
3b1f7ce7 694 $scope.result = [formatMeta(resp), prettyPrintOne(_.escape(JSON.stringify(resp.data, null, 2)))];
19b53e5b
C
695 });
696 };
697
b65fa6dc
CW
698 function debugFormat(data) {
699 var debug = data.debug ? prettyPrintOne(_.escape(JSON.stringify(data.debug, null, 2)).replace(/\\n/g, "\n")) : null;
700 delete data.debug;
701 return debug;
702 }
703
19b53e5b
C
704 /**
705 * Format value to look like php code
706 */
707 function phpFormat(val, indent) {
708 if (typeof val === 'undefined') {
709 return '';
710 }
6ba6f2bd
CW
711 if (val === null || val === true || val === false) {
712 return JSON.stringify(val).toUpperCase();
713 }
19b53e5b
C
714 indent = (typeof indent === 'number') ? _.repeat(' ', indent) : (indent || '');
715 var ret = '',
716 baseLine = indent ? indent.slice(0, -2) : '',
cddf293f
CW
717 newLine = indent ? '\n' : '',
718 trailingComma = indent ? ',' : '';
19b53e5b
C
719 if ($.isPlainObject(val)) {
720 $.each(val, function(k, v) {
721 ret += (ret ? ', ' : '') + newLine + indent + "'" + k + "' => " + phpFormat(v);
722 });
cddf293f 723 return '[' + ret + trailingComma + newLine + baseLine + ']';
19b53e5b
C
724 }
725 if ($.isArray(val)) {
726 $.each(val, function(k, v) {
727 ret += (ret ? ', ' : '') + newLine + indent + phpFormat(v);
728 });
cddf293f 729 return '[' + ret + trailingComma + newLine + baseLine + ']';
19b53e5b
C
730 }
731 if (_.isString(val) && !_.contains(val, "'")) {
732 return "'" + val + "'";
733 }
734 return JSON.stringify(val).replace(/\$/g, '\\$');
735 }
736
737 function fetchMeta() {
738 crmApi4(getMetaParams)
739 .then(function(data) {
740 if (data.actions) {
741 getEntity().actions = data.actions;
742 selectAction();
743 }
744 });
745 }
746
747 // Help for an entity with no action selected
748 function showEntityHelp(entityName) {
749 var entityInfo = getEntity(entityName);
136ca5bb 750 setHelp($scope.entity, {
19b53e5b 751 description: entityInfo.description,
0493ec47
CW
752 comment: entityInfo.comment,
753 see: entityInfo.see
136ca5bb 754 });
19b53e5b
C
755 }
756
757 if (!$scope.entity) {
136ca5bb 758 setHelp(ts('APIv4 Explorer'), {description: docs.description, comment: docs.comment, see: docs.see});
19b53e5b
C
759 } else if (!actions.length && !getEntity().actions) {
760 getMetaParams.actions = [$scope.entity, 'getActions', {chain: {fields: [$scope.entity, 'getFields', {action: '$name'}]}}];
761 fetchMeta();
762 } else {
763 selectAction();
764 }
765
766 if ($scope.entity) {
767 showEntityHelp($scope.entity);
768 }
769
770 // Update route when changing entity
771 $scope.$watch('entity', function(newVal, oldVal) {
772 if (oldVal !== newVal) {
773 // Flush actions cache to re-fetch for new entity
774 actions = [];
775 $location.url('/explorer/' + newVal);
776 }
777 });
778
779 // Update route when changing actions
780 $scope.$watch('action', function(newVal, oldVal) {
781 if ($scope.entity && $routeParams.api4action !== newVal && !_.isUndefined(newVal)) {
782 $location.url('/explorer/' + $scope.entity + '/' + newVal);
783 } else if (newVal) {
136ca5bb 784 setHelp($scope.entity + '::' + newVal, _.pick(_.findWhere(getEntity().actions, {name: newVal}), ['description', 'comment', 'see']));
19b53e5b
C
785 }
786 });
787
9cea3619
CW
788 $scope.paramDoc = function(name) {
789 return docs.params[name];
19b53e5b
C
790 };
791
2c5d5bca
CW
792 $scope.executeDoc = function() {
793 var doc = {
794 description: ts('Runs API call on the CiviCRM database.'),
795 comment: ts('Results and debugging info will be displayed below.')
796 };
797 if ($scope.action === 'delete') {
798 doc.WARNING = ts('This API call will be executed on the real database. Deleting data cannot be undone.');
799 }
800 else if ($scope.action && $scope.action.slice(0, 3) !== 'get') {
801 doc.WARNING = ts('This API call will be executed on the real database. It cannot be undone.');
802 }
803 return doc;
804 };
805
806 $scope.saveDoc = function() {
807 return {
808 description: ts('Save API call as a smart group.'),
48102254
CW
809 comment: ts('Create a SavedSearch using these API params to populate a smart group.') +
810 '\n\n' + ts('NOTE: you must select contact id as the only field.')
2c5d5bca
CW
811 };
812 };
813
19b53e5b
C
814 $scope.$watch('params', writeCode, true);
815 $scope.$watch('index', writeCode);
816 writeCode();
817
4e97c268 818 $scope.save = function() {
48102254
CW
819 $scope.params.limit = $scope.params.offset = 0;
820 if ($scope.params.chain.length) {
821 CRM.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires: 5000});
822 return;
823 }
824 if ($scope.params.select.length !== 1 || !_.includes($scope.params.select[0], 'id')) {
825 CRM.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires: 5000});
826 return;
827 }
4e97c268
CW
828 var model = {
829 title: '',
d7507e89
CW
830 description: '',
831 visibility: 'User and User Admin Only',
832 group_type: [],
4e97c268
CW
833 id: null,
834 entity: $scope.entity,
835 params: JSON.parse(angular.toJson($scope.params))
836 };
837 model.params.version = 4;
4e97c268
CW
838 delete model.params.chain;
839 delete model.params.debug;
840 delete model.params.limit;
48102254
CW
841 delete model.params.offset;
842 delete model.params.orderBy;
4e97c268
CW
843 delete model.params.checkPermissions;
844 var options = CRM.utils.adjustDialogDefaults({
845 width: '500px',
846 autoOpen: false,
847 title: ts('Save smart group')
848 });
849 dialogService.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model, options);
850 };
851 });
852
853 angular.module('api4Explorer').controller('SaveSearchCtrl', function($scope, crmApi4, dialogService) {
854 var ts = $scope.ts = CRM.ts(),
855 model = $scope.model;
d7507e89
CW
856 $scope.groupEntityRefParams = {
857 entity: 'Group',
858 api: {
859 params: {is_hidden: 0, is_active: 1, 'saved_search_id.api_entity': model.entity},
860 extra: ['saved_search_id', 'description', 'visibility', 'group_type']
861 },
862 select: {
863 allowClear: true,
864 minimumInputLength: 0,
865 placeholder: ts('Select existing group')
866 }
867 };
868 if (!CRM.checkPerm('administer reserved groups')) {
869 $scope.groupEntityRefParams.api.params.is_reserved = 0;
870 }
871 $scope.perm = {
872 administerReservedGroups: CRM.checkPerm('administer reserved groups')
873 };
874 $scope.options = CRM.vars.api4.groupOptions;
4e97c268
CW
875 $scope.$watch('model.id', function(id) {
876 if (id) {
d7507e89 877 _.assign(model, $('#api-save-search-select-group').select2('data').extra);
4e97c268
CW
878 }
879 });
880 $scope.cancel = function() {
881 dialogService.cancel('saveSearchDialog');
882 };
883 $scope.save = function() {
884 $('.ui-dialog:visible').block();
885 var group = model.id ? {id: model.id} : {title: model.title};
886 group.description = model.description;
d7507e89
CW
887 group.visibility = model.visibility;
888 group.group_type = model.group_type;
4e97c268
CW
889 group.saved_search_id = '$id';
890 var savedSearch = {
891 api_entity: model.entity,
892 api_params: model.params
893 };
894 if (group.id) {
d7507e89 895 savedSearch.id = model.saved_search_id;
4e97c268
CW
896 }
897 crmApi4('SavedSearch', 'save', {records: [savedSearch], chain: {group: ['Group', 'save', {'records': [group]}]}})
898 .then(function(result) {
899 dialogService.close('saveSearchDialog', result[0]);
900 });
901 };
19b53e5b
C
902 });
903
24463df7 904 angular.module('api4Explorer').directive('crmApi4Clause', function($timeout) {
19b53e5b
C
905 return {
906 scope: {
24463df7 907 data: '=crmApi4Clause'
19b53e5b 908 },
24463df7 909 templateUrl: '~/api4Explorer/Clause.html',
19b53e5b 910 link: function (scope, element, attrs) {
6f97b1d9 911 var ts = scope.ts = CRM.ts();
19b53e5b
C
912 scope.newClause = '';
913 scope.conjunctions = ['AND', 'OR', 'NOT'];
914 scope.operators = CRM.vars.api4.operators;
915
916 scope.addGroup = function(op) {
24463df7 917 scope.data.clauses.push([op, []]);
19b53e5b
C
918 };
919
920 scope.removeGroup = function() {
921 scope.data.groupParent.splice(scope.data.groupIndex, 1);
922 };
923
924 scope.onSort = function(event, ui) {
24463df7 925 $(element).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event.type === 'sortstart');
19b53e5b
C
926 $('.api4-input.form-inline').css('margin-left', '');
927 };
928
929 // Indent clause while dragging between nested groups
930 scope.onSortOver = function(event, ui) {
931 var offset = 0;
932 if (ui.sender) {
933 offset = $(ui.placeholder).offset().left - $(ui.sender).offset().left;
934 }
935 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset + 'px');
936 };
937
938 scope.$watch('newClause', function(value) {
939 var field = value;
940 $timeout(function() {
941 if (field) {
24463df7 942 scope.data.clauses.push([field, '=', '']);
19b53e5b
C
943 scope.newClause = null;
944 }
945 });
946 });
24463df7 947 scope.$watch('data.clauses', function(values) {
19b53e5b
C
948 // Remove empty values
949 _.each(values, function(clause, index) {
950 if (typeof clause !== 'undefined' && !clause[0]) {
951 values.splice(index, 1);
952 }
6ba6f2bd
CW
953 if (typeof clause[1] === 'string' && _.contains(clause[1], 'NULL')) {
954 clause.length = 2;
955 } else if (typeof clause[1] === 'string' && clause.length == 2) {
956 clause.push('');
957 }
19b53e5b
C
958 });
959 }, true);
960 }
961 };
962 });
963
964 angular.module('api4Explorer').directive('api4ExpValue', function($routeParams, crmApi4) {
965 return {
966 scope: {
967 data: '=api4ExpValue'
968 },
969 require: 'ngModel',
970 link: function (scope, element, attrs, ctrl) {
6f97b1d9 971 var ts = scope.ts = CRM.ts(),
6872a653 972 multi = _.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope.data.op),
19b53e5b 973 entity = $routeParams.api4entity,
c752d94b 974 action = scope.data.action || $routeParams.api4action;
19b53e5b
C
975
976 function destroyWidget() {
977 var $el = $(element);
978 if ($el.is('.crm-form-date-wrapper .crm-hidden-date')) {
979 $el.crmDatepicker('destroy');
980 }
981 if ($el.is('.select2-container + input')) {
982 $el.crmEntityRef('destroy');
983 }
984 $(element).removeData().removeAttr('type').removeAttr('placeholder').show();
985 }
986
987 function makeWidget(field, op) {
988 var $el = $(element),
bc356925 989 inputType = field.input_type,
19b53e5b
C
990 dataType = field.data_type;
991 if (!op) {
992 op = field.serialize || dataType === 'Array' ? 'IN' : '=';
993 }
6872a653 994 multi = _.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op);
19b53e5b
C
995 if (op === 'IS NULL' || op === 'IS NOT NULL') {
996 $el.hide();
997 return;
998 }
999 if (inputType === 'Date') {
1000 if (_.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op)) {
1001 $el.crmDatepicker({time: (field.input_attrs && field.input_attrs.time) || false});
1002 }
1003 } else if (_.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op) && (field.fk_entity || field.options || dataType === 'Boolean')) {
37d82abe
CW
1004 if (field.options) {
1005 var id = field.pseudoconstant || 'id';
19b53e5b
C
1006 $el.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple: multi, data: [{id: '', text: ''}]});
1007 loadFieldOptions(field.entity || entity).then(function(data) {
37d82abe
CW
1008 var options = _.transform(data[field.name].options, function(options, opt) {
1009 options.push({id: opt[id], text: opt.label, description: opt.description, color: opt.color, icon: opt.icon});
1010 }, []);
1011 $el.removeClass('loading').crmSelect2({data: options, multiple: multi});
19b53e5b 1012 });
37d82abe
CW
1013 } else if (field.fk_entity) {
1014 $el.crmEntityRef({entity: field.fk_entity, select:{multiple: multi}});
19b53e5b
C
1015 } else if (dataType === 'Boolean') {
1016 $el.attr('placeholder', ts('- select -')).crmSelect2({allowClear: false, multiple: multi, placeholder: ts('- select -'), data: [
2929a8fb
CW
1017 {id: 'true', text: ts('Yes')},
1018 {id: 'false', text: ts('No')}
19b53e5b
C
1019 ]});
1020 }
6872a653 1021 } else if (dataType === 'Integer' && !multi) {
19b53e5b
C
1022 $el.attr('type', 'number');
1023 }
1024 }
1025
1026 function loadFieldOptions(entity) {
1027 if (!fieldOptions[entity + action]) {
1028 fieldOptions[entity + action] = crmApi4(entity, 'getFields', {
37d82abe 1029 loadOptions: ['id', 'name', 'label', 'description', 'color', 'icon'],
19b53e5b 1030 action: action,
37d82abe
CW
1031 where: [['options', '!=', false]],
1032 select: ['options']
1033 }, 'name');
19b53e5b
C
1034 }
1035 return fieldOptions[entity + action];
1036 }
1037
1038 // Copied from ng-list but applied conditionally if field is multi-valued
1039 var parseList = function(viewValue) {
1040 // If the viewValue is invalid (say required but empty) it will be `undefined`
1041 if (_.isUndefined(viewValue)) return;
1042
1043 if (!multi) {
1044 return viewValue;
1045 }
1046
1047 var list = [];
1048
1049 if (viewValue) {
1050 _.each(viewValue.split(','), function(value) {
1051 if (value) list.push(_.trim(value));
1052 });
1053 }
1054
1055 return list;
1056 };
1057
1058 // Copied from ng-list
1059 ctrl.$parsers.push(parseList);
1060 ctrl.$formatters.push(function(value) {
1061 return _.isArray(value) ? value.join(', ') : value;
1062 });
1063
1064 // Copied from ng-list
1065 ctrl.$isEmpty = function(value) {
1066 return !value || !value.length;
1067 };
1068
1069 scope.$watchCollection('data', function(data) {
1070 destroyWidget();
1071 var field = getField(data.field, entity, action);
1072 if (field) {
1073 makeWidget(field, data.op);
1074 }
1075 });
1076 }
1077 };
1078 });
1079
1080
1081 angular.module('api4Explorer').directive('api4ExpChain', function(crmApi4) {
1082 return {
1083 scope: {
1084 chain: '=api4ExpChain',
1085 mainEntity: '=',
1086 entities: '='
1087 },
1088 templateUrl: '~/api4Explorer/Chain.html',
1089 link: function (scope, element, attrs) {
6f97b1d9 1090 var ts = scope.ts = CRM.ts();
19b53e5b
C
1091
1092 function changeEntity(newEntity, oldEntity) {
1093 // When clearing entity remove this chain
1094 if (!newEntity) {
1095 scope.chain[0] = '';
1096 return;
1097 }
1098 // Reset action && index
1099 if (newEntity !== oldEntity) {
1100 scope.chain[1][1] = scope.chain[1][2] = '';
1101 }
1102 if (getEntity(newEntity).actions) {
1103 setActions();
1104 } else {
1105 crmApi4(newEntity, 'getActions', {chain: {fields: [newEntity, 'getFields', {action: '$name'}]}})
1106 .then(function(data) {
1107 getEntity(data.entity).actions = data;
1108 if (data.entity === scope.chain[1][0]) {
1109 setActions();
1110 }
1111 });
1112 }
1113 }
1114
1115 function setActions() {
1116 scope.actions = [''].concat(_.pluck(getEntity(scope.chain[1][0]).actions, 'name'));
1117 }
1118
1119 // Set default params when choosing action
1120 function changeAction(newAction, oldAction) {
1121 var link;
1122 // Prepopulate links
1123 if (newAction && newAction !== oldAction) {
1124 // Clear index
1125 scope.chain[1][3] = '';
1126 // Look for links back to main entity
1127 _.each(entityFields(scope.chain[1][0]), function(field) {
1128 if (field.fk_entity === scope.mainEntity) {
1129 link = [field.name, '$id'];
1130 }
1131 });
1132 // Look for links from main entity
1133 if (!link && newAction !== 'create') {
1134 _.each(entityFields(scope.mainEntity), function(field) {
1135 if (field.fk_entity === scope.chain[1][0]) {
1136 link = ['id', '$' + field.name];
1137 // Since we're specifying the id, set index to getsingle
1138 scope.chain[1][3] = '0';
1139 }
1140 });
1141 }
1142 if (link && _.contains(['get', 'update', 'replace', 'delete'], newAction)) {
1143 scope.chain[1][2] = '{where: [[' + link[0] + ', =, ' + link[1] + ']]}';
1144 }
1145 else if (link && _.contains(['create'], newAction)) {
1146 scope.chain[1][2] = '{values: {' + link[0] + ': ' + link[1] + '}}';
cddf293f
CW
1147 }
1148 else if (link && _.contains(['save'], newAction)) {
1149 scope.chain[1][2] = '{records: [{' + link[0] + ': ' + link[1] + '}]}';
19b53e5b
C
1150 } else {
1151 scope.chain[1][2] = '{}';
1152 }
1153 }
1154 }
1155
1156 scope.$watch("chain[1][0]", changeEntity);
1157 scope.$watch("chain[1][1]", changeAction);
1158 }
1159 };
1160 });
1161
1162 function getEntity(entityName) {
1163 return _.findWhere(schema, {name: entityName});
1164 }
1165
1166 function entityFields(entityName, action) {
1167 var entity = getEntity(entityName);
1168 if (entity && action && entity.actions) {
1169 return _.findWhere(entity.actions, {name: action}).fields;
1170 }
1171 return _.result(entity, 'fields');
1172 }
1173
1174 function getField(fieldName, entity, action) {
37d82abe
CW
1175 var suffix = fieldName.split(':')[1];
1176 fieldName = fieldName.split(':')[0];
19b53e5b 1177 var fieldNames = fieldName.split('.');
37d82abe
CW
1178 var field = get(entity, fieldNames);
1179 if (field && suffix) {
1180 field.pseudoconstant = suffix;
1181 }
1182 return field;
19b53e5b
C
1183
1184 function get(entity, fieldNames) {
1185 if (fieldNames.length === 1) {
1186 return _.findWhere(entityFields(entity, action), {name: fieldNames[0]});
1187 }
1188 var comboName = _.findWhere(entityFields(entity, action), {name: fieldNames[0] + '.' + fieldNames[1]});
1189 if (comboName) {
1190 return comboName;
1191 }
1192 var linkName = fieldNames.shift(),
7d91265c 1193 newEntity = _.findWhere(links[entity], {alias: linkName}).entity;
19b53e5b
C
1194 return get(newEntity, fieldNames);
1195 }
1196 }
1197
1198 // Collapsible optgroups for select2
1199 $(function() {
1200 $('body')
1201 .on('select2-open', function(e) {
1202 if ($(e.target).hasClass('collapsible-optgroups')) {
1203 $('#select2-drop')
1204 .off('.collapseOptionGroup')
1205 .addClass('collapsible-optgroups-enabled')
1206 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1207 $(this).parent().toggleClass('optgroup-expanded');
1208 });
1209 }
1210 })
1211 .on('select2-close', function() {
1212 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1213 });
1214 });
1215})(angular, CRM.$, CRM._);