1 (function(angular
, $, _
, undefined) {
4 var schema
= CRM
.vars
.api4
.schema
;
6 var links
= CRM
.vars
.api4
.links
;
7 // Cache list of entities
9 // Cache list of actions
12 var fieldOptions
= {};
15 angular
.module('api4Explorer').config(function($routeProvider
) {
16 $routeProvider
.when('/explorer/:api4entity?/:api4action?', {
17 controller
: 'Api4Explorer',
18 templateUrl
: '~/api4Explorer/Explorer.html',
23 angular
.module('api4Explorer').controller('Api4Explorer', function($scope
, $routeParams
, $location
, $timeout
, $http
, crmUiHelp
, crmApi4
, dialogService
) {
24 var ts
= $scope
.ts
= CRM
.ts();
25 $scope
.entities
= entities
;
26 $scope
.actions
= actions
;
28 $scope
.havingOptions
= [];
29 $scope
.fieldsAndJoins
= [];
30 $scope
.fieldsAndJoinsAndFunctions
= [];
31 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= [];
32 $scope
.availableParams
= {};
35 $scope
.selectedTab
= {result
: 'result', code
: 'php'};
37 accessDebugOutput
: CRM
.checkPerm('access debug output'),
38 editGroups
: CRM
.checkPerm('edit groups')
40 marked
.setOptions({highlight
: prettyPrintOne
});
41 var getMetaParams
= {},
42 objectParams
= {orderBy
: 'ASC', values
: '', defaults
: '', chain
: ['Entity', '', '{}']},
43 docs
= CRM
.vars
.api4
.docs
,
46 $scope
.helpTitle
= '';
47 $scope
.helpContent
= {};
48 $scope
.entity
= $routeParams
.api4entity
;
51 $scope
.status
= 'default';
52 $scope
.loading
= false;
54 $scope
.langs
= ['php', 'js', 'ang', 'cli'];
57 {name
: 'oop', label
: ts('OOP Style'), code
: ''},
58 {name
: 'php', label
: ts('Traditional'), code
: ''}
61 {name
: 'js', label
: ts('Single Call'), code
: ''},
62 {name
: 'js2', label
: ts('Batch Calls'), code
: ''}
65 {name
: 'ang', label
: ts('Single Call'), code
: ''},
66 {name
: 'ang2', label
: ts('Batch Calls'), code
: ''}
69 {name
: 'cv', label
: ts('CV'), code
: ''}
73 if (!entities
.length
) {
74 formatForSelect2(schema
, entities
, 'name', ['description']);
83 function ucfirst(str
) {
84 return str
[0].toUpperCase() + str
.slice(1);
87 function lcfirst(str
) {
88 return str
[0].toLowerCase() + str
.slice(1);
91 function pluralize(str
) {
92 switch (str
[str
.length
-1]) {
96 return str
.slice(0, -1) + 'ies';
102 // Reformat an existing array of objects for compatibility with select2
103 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
104 _
.each(input
, function(item
) {
105 var id
= (prefix
|| '') + item
[key
];
106 var formatted
= {id
: id
, text
: id
};
108 _
.merge(formatted
, _
.pick(item
, extra
));
110 container
.push(formatted
);
115 // Returns field list formatted for select2
116 function getFieldList(action
, addPseudoconstant
) {
118 fieldInfo
= _
.findWhere(getEntity().actions
, {name
: action
}).fields
;
119 if (addPseudoconstant
) {
120 fieldInfo
= _
.cloneDeep(fieldInfo
);
121 addPseudoconstants(fieldInfo
, addPseudoconstant
);
123 formatForSelect2(fieldInfo
, fields
, 'name', ['description', 'required', 'default_value']);
127 // Note: this function expects fieldList to be select2-formatted already
128 function addJoins(fieldList
, addWildcard
, addPseudoconstant
) {
129 var fields
= _
.cloneDeep(fieldList
);
130 _
.each(links
[$scope
.entity
], function(link
) {
131 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
132 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
134 if (addPseudoconstant
) {
135 addPseudoconstants(linkFields
, addPseudoconstant
);
139 description
: 'Join to ' + link
.entity
,
140 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
147 // Note: this function transforms a raw list a-la getFields; not a select2-formatted list
148 function addPseudoconstants(fieldList
, toAdd
) {
149 var optionFields
= _
.filter(fieldList
, 'options');
150 _
.each(optionFields
, function(field
) {
151 var pos
= _
.findIndex(fieldList
, {name
: field
.name
}) + 1;
152 _
.each(toAdd
, function(suffix
) {
153 var newField
= _
.cloneDeep(field
);
154 newField
.name
+= ':' + suffix
;
155 fieldList
.splice(pos
, 0, newField
);
160 $scope
.help = function(title
, content
) {
162 $scope
.helpTitle
= helpTitle
;
163 $scope
.helpContent
= helpContent
;
165 $scope
.helpTitle
= title
;
166 $scope
.helpContent
= formatHelp(content
);
170 // Sets the static help text (which gets overridden by mousing over other elements)
171 function setHelp(title
, content
) {
172 $scope
.helpTitle
= helpTitle
= title
;
173 $scope
.helpContent
= helpContent
= formatHelp(content
);
176 // Convert plain-text help to markdown; replace variables and format links
177 function formatHelp(rawContent
) {
178 function formatRefs(see
) {
179 _
.each(see
, function(ref
, idx
) {
180 var match
= ref
.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
182 ref
= '#/explorer/' + match
[1];
184 if (ref
[0] === '\\') {
185 ref
= 'https://github.com/civicrm/civicrm-core/blob/master' + ref
.replace(/\\/i, '/') + '.php
';
187 see[idx] = '<a target
="' + (ref[0] === '#' ? '_self' : '_blank') + '" href
="' + ref + '">' + see[idx] + '</a
>';
190 var formatted = _.cloneDeep(rawContent);
191 if (formatted.description) {
192 formatted.description = marked(formatted.description);
194 if (formatted.comment) {
195 formatted.comment = marked(formatted.comment);
197 formatRefs(formatted.see);
201 $scope.fieldHelp = function(fieldName) {
202 var field = getField(fieldName, $scope.entity, $scope.action);
207 description: field.description,
208 type: field.data_type
210 if (field.default_value) {
211 info.default = field.default_value;
213 if (field.required_if) {
214 info.required_if = field.required_if;
215 } else if (field.required) {
216 info.required = 'true';
221 // Returns field list for write params (values, defaults)
222 $scope.fieldList = function(param) {
224 var fields = _.cloneDeep(getFieldList($scope.action === 'getFields
' ? ($scope.params.action || 'get') : $scope.action, ['name
']));
225 // Disable fields that are already in use
226 _.each($scope.params[param] || [], function(val) {
227 var usedField = val[0].replace(':name
', '');
228 (_.findWhere(fields, {id: usedField}) || {}).disabled = true;
229 (_.findWhere(fields, {id: usedField + ':name
'}) || {}).disabled = true;
231 return {results: fields};
235 $scope.formatSelect2Item = function(row) {
236 return _.escape(row.text) +
237 (row.required ? '<span
class="crm-marker"> *</span
>' : '') +
238 (row.description ? '<div
class="crm-select2-row-description"><p
>' + _.escape(row.description) + '</p></div>' : '');
241 $scope.clearParam = function(name, idx) {
242 if (typeof idx === 'undefined') {
243 $scope.params[name] = $scope.availableParams[name].default;
245 $scope.params[name].splice(idx, 1);
249 // Gets params that should be represented as generic input fields in the explorer
250 // This fn doesn't have to be particularly efficient as its output is cached
in one
-time bindings
251 $scope
.getGenericParams = function(paramType
, defaultNull
) {
252 // Returns undefined if params are not yet set; one-time bindings will stabilize when this function returns a value
253 if (_
.isEmpty($scope
.availableParams
)) {
256 var specialParams
= ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having'];
257 if ($scope
.availableParams
.limit
&& $scope
.availableParams
.offset
) {
258 specialParams
.push('limit', 'offset');
260 return _
.transform($scope
.availableParams
, function(genericParams
, param
, name
) {
261 if (!_
.contains(specialParams
, name
) &&
262 !(typeof paramType
!== 'undefined' && !_
.contains(paramType
, param
.type
[0])) &&
263 !(typeof defaultNull
!== 'undefined' && ((param
.default === null) !== defaultNull
))
265 genericParams
[name
] = param
;
270 $scope
.selectRowCount = function() {
271 if ($scope
.isSelectRowCount()) {
272 $scope
.params
.select
= [];
274 $scope
.params
.select
= ['row_count'];
276 if ($scope
.params
.limit
== 25) {
277 $scope
.params
.limit
= 0;
282 $scope
.isSelectRowCount = function() {
283 return isSelectRowCount($scope
.params
);
286 $scope
.selectLang = function(lang
) {
287 $scope
.selectedTab
.code
= lang
;
291 function isSelectRowCount(params
) {
292 return params
&& params
.select
&& params
.select
.length
=== 1 && params
.select
[0] === 'row_count';
295 function getEntity(entityName
) {
296 return _
.findWhere(schema
, {name
: entityName
|| $scope
.entity
});
299 // Get all params that have been set
300 function getParams() {
302 _
.each($scope
.params
, function(param
, key
) {
303 if (param
!= $scope
.availableParams
[key
].default && !(typeof param
=== 'object' && _
.isEmpty(param
))) {
304 if (_
.contains($scope
.availableParams
[key
].type
, 'array') && (typeof objectParams
[key
] === 'undefined')) {
305 params
[key
] = parseYaml(JSON
.parse(angular
.toJson(param
)));
311 _
.each(objectParams
, function(defaultVal
, key
) {
314 _
.each(params
[key
], function(item
) {
315 var val
= _
.cloneDeep(item
[1]);
316 // Remove blank items from "chain" array
317 if (_
.isArray(val
)) {
318 _
.eachRight(item
[1], function(v
, k
) {
325 newParam
[item
[0]] = parseYaml(val
);
327 params
[key
] = newParam
;
333 function parseYaml(input
) {
334 if (typeof input
=== 'undefined') {
340 if (_
.isObject(input
) || _
.isArray(input
)) {
341 _
.each(input
, function(item
, index
) {
342 input
[index
] = parseYaml(item
);
347 var output
= (input
=== '>') ? '>' : jsyaml
.safeLoad(input
);
348 // We don't want dates parsed to js objects
349 return _
.isDate(output
) ? input
: output
;
355 function selectAction() {
356 $scope
.action
= $routeParams
.api4action
;
357 $scope
.fieldsAndJoins
.length
= 0;
358 $scope
.fieldsAndJoinsAndFunctions
.length
= 0;
359 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.length
= 0;
360 if (!actions
.length
) {
361 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
364 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
365 $scope
.fields
= getFieldList($scope
.action
);
366 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
367 $scope
.fieldsAndJoins
= addJoins(getFieldList($scope
.action
, ['name']));
369 // SQL functions are supported if HAVING is
370 if (actionInfo
.params
.having
) {
372 text
: ts('FUNCTION'),
373 description
: ts('Calculate result of a SQL function'),
374 children
: _
.transform(CRM
.vars
.api4
.functions
, function(result
, fn
) {
376 id
: fn
.name
+ '() AS ' + fn
.name
.toLowerCase(),
377 text
: fn
.name
+ '()',
378 description
: fn
.name
+ '(' + describeSqlFn(fn
.params
) + ')'
383 $scope
.fieldsAndJoinsAndFunctions
= addJoins($scope
.fields
.concat(functions
), true);
384 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= addJoins(getFieldList($scope
.action
, ['name', 'label']).concat(functions
), true, ['name', 'label']);
386 $scope
.fieldsAndJoins
= getFieldList($scope
.action
, ['name']);
387 $scope
.fieldsAndJoinsAndFunctions
= $scope
.fields
;
388 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= getFieldList($scope
.action
, ['name', 'label']);
390 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
391 _
.each(actionInfo
.params
, function (param
, name
) {
393 defaultVal
= _
.cloneDeep(param
.default);
395 switch (param
.type
[0]) {
398 format
= param
.type
[0];
409 if (name
=== 'limit') {
412 if (name
=== 'debug') {
415 if (name
=== 'values') {
416 defaultVal
= defaultValues(defaultVal
);
418 if (name
=== 'loadOptions' && $scope
.action
=== 'getFields') {
422 ['id', 'name', 'label'],
423 ['id', 'name', 'label', 'abbr', 'description', 'color', 'icon']
427 param
.type
= ['string'];
429 $scope
.$bindToRoute({
430 expr
: 'params["' + name
+ '"]',
434 deep
: format
=== 'json'
437 if (typeof objectParams
[name
] !== 'undefined' && name
!== 'orderBy') {
438 $scope
.$watch('params.' + name
, function (values
) {
439 // Remove empty values
440 _
.each(values
, function (clause
, index
) {
441 if (!clause
|| !clause
[0]) {
442 $scope
.clearParam(name
, index
);
447 if (name
=== 'select' && actionInfo
.params
.having
) {
448 $scope
.$watchCollection('params.select', function(values
) {
449 $scope
.havingOptions
.length
= 0;
450 _
.each(values
, function(item
) {
451 var pieces
= item
.split(' AS '),
452 alias
= _
.trim(pieces
[pieces
.length
- 1]).replace(':label', ':name');
453 $scope
.havingOptions
.push({id
: alias
, text
: alias
});
457 if (typeof objectParams
[name
] !== 'undefined' || name
=== 'groupBy' || name
=== 'select') {
458 $scope
.$watch('controls.' + name
, function(value
) {
460 $timeout(function() {
462 if (typeof objectParams
[name
] === 'undefined') {
463 $scope
.params
[name
].push(field
);
465 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
466 if (name
=== 'chain') {
467 var num
= $scope
.params
.chain
.length
;
468 defaultOp
[0] = field
;
469 field
= 'name_me_' + num
;
471 $scope
.params
[name
].push([field
, defaultOp
]);
473 $scope
.controls
[name
] = null;
479 $scope
.availableParams
= actionInfo
.params
;
484 function describeSqlFn(params
) {
486 _
.each(params
, function(param
) {
489 desc
+= _
.filter(param
.prefix
).join('|') + ' ';
491 if (param
.expr
=== 1) {
493 } else if (param
.expr
> 1) {
494 desc
+= 'expr, ... ';
497 desc
+= ' ' + _
.filter(param
.suffix
).join('|') + ' ';
500 return desc
.replace(/[ ]+/g, ' ');
503 function defaultValues(defaultVal
) {
504 _
.each($scope
.fields
, function(field
) {
505 if (field
.required
) {
506 defaultVal
.push([field
.id
, '']);
512 function stringify(value
, trim
) {
513 if (typeof value
=== 'undefined') {
516 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
518 str
= str
.slice(1, -1);
523 function writeCode() {
525 entity
= $scope
.entity
,
526 action
= $scope
.action
,
527 params
= getParams(),
528 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
530 if ($scope
.entity
&& $scope
.action
) {
532 if (action
.slice(0, 3) === 'get') {
533 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
534 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
536 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
537 paramCount
= _
.size(params
),
540 if (isSelectRowCount(params
)) {
541 results
= result
+ 'Count';
544 switch ($scope
.selectedTab
.code
) {
548 var js
= "'" + entity
+ "', '" + action
+ "', {";
549 _
.each(params
, function(param
, key
) {
550 js
+= "\n " + key
+ ': ' + stringify(param
) +
551 (++i
< paramCount
? ',' : '');
552 if (key
=== 'checkPermissions') {
553 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
557 if (index
|| index
=== 0) {
558 js
+= ', ' + JSON
.stringify(index
);
560 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
561 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
562 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
563 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
568 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
569 _
.each(params
, function(param
, key
) {
570 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
573 if (index
|| index
=== 0) {
574 code
.php
+= ', ' + phpFormat(index
);
579 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
580 if (isSelectRowCount(params
)) {
581 code
.oop
+= "\n ->count()";
582 } else if (_
.isNumber(index
)) {
583 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
585 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
586 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
588 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
589 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
593 if (!_
.isNumber(index
) && !isSelectRowCount(params
)) {
594 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
600 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
603 _
.each($scope
.code
, function(vals
) {
604 _
.each(vals
, function(style
) {
605 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
611 function formatOOP(entity
, action
, params
, indent
) {
613 newLine
= "\n" + _
.repeat(' ', indent
);
614 if (entity
.substr(0, 7) !== 'Custom_') {
615 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
617 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
619 _
.each(params
, function(param
, key
) {
621 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
622 _
.each(param
, function(item
, index
) {
623 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
624 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
626 } else if (key
=== 'where') {
627 _
.each(param
, function (clause
) {
628 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
629 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
631 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
634 } else if (key
=== 'select') {
636 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
637 code
+= isSelectRowCount(params
) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
638 } else if (key
=== 'chain') {
639 _
.each(param
, function(chain
, name
) {
640 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
641 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
645 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
651 function isInt(value
) {
652 if (_
.isFinite(value
)) {
655 if (!_
.isString(value
)) {
658 return /^-{0,1}\d+$/.test(value
);
661 function formatMeta(resp
) {
663 _
.each(resp
, function(val
, key
) {
664 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
665 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
668 return prettyPrintOne(_
.escape(ret
));
671 $scope
.execute = function() {
672 $scope
.status
= 'warning';
673 $scope
.loading
= true;
674 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
675 params
: angular
.toJson(getParams()),
676 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
679 'X-Requested-With': 'XMLHttpRequest'
681 }).then(function(resp
) {
682 $scope
.loading
= false;
683 $scope
.status
= 'success';
684 $scope
.debug
= debugFormat(resp
.data
);
685 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
687 $scope
.loading
= false;
688 $scope
.status
= 'danger';
689 $scope
.debug
= debugFormat(resp
.data
);
690 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
694 function debugFormat(data
) {
695 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
701 * Format value to look like php code
703 function phpFormat(val
, indent
) {
704 if (typeof val
=== 'undefined') {
707 if (val
=== null || val
=== true || val
=== false) {
708 return JSON
.stringify(val
).toUpperCase();
710 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
712 baseLine
= indent
? indent
.slice(0, -2) : '',
713 newLine
= indent
? '\n' : '',
714 trailingComma
= indent
? ',' : '';
715 if ($.isPlainObject(val
)) {
716 $.each(val
, function(k
, v
) {
717 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
719 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
721 if ($.isArray(val
)) {
722 $.each(val
, function(k
, v
) {
723 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
725 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
727 if (_
.isString(val
) && !_
.contains(val
, "'")) {
728 return "'" + val
+ "'";
730 return JSON
.stringify(val
).replace(/\$/g, '\\$');
733 function fetchMeta() {
734 crmApi4(getMetaParams
)
735 .then(function(data
) {
737 getEntity().actions
= data
.actions
;
743 // Help for an entity with no action selected
744 function showEntityHelp(entityName
) {
745 var entityInfo
= getEntity(entityName
);
746 setHelp($scope
.entity
, {
747 description
: entityInfo
.description
,
748 comment
: entityInfo
.comment
,
753 if (!$scope
.entity
) {
754 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
755 } else if (!actions
.length
&& !getEntity().actions
) {
756 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
763 showEntityHelp($scope
.entity
);
766 // Update route when changing entity
767 $scope
.$watch('entity', function(newVal
, oldVal
) {
768 if (oldVal
!== newVal
) {
769 // Flush actions cache to re-fetch for new entity
771 $location
.url('/explorer/' + newVal
);
775 // Update route when changing actions
776 $scope
.$watch('action', function(newVal
, oldVal
) {
777 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
778 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
780 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
784 $scope
.paramDoc = function(name
) {
785 return docs
.params
[name
];
788 $scope
.executeDoc = function() {
790 description
: ts('Runs API call on the CiviCRM database.'),
791 comment
: ts('Results and debugging info will be displayed below.')
793 if ($scope
.action
=== 'delete') {
794 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
796 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
797 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
802 $scope
.saveDoc = function() {
804 description
: ts('Save API call as a smart group.'),
805 comment
: ts('Create a SavedSearch using these API params to populate a smart group.') +
806 '\n\n' + ts('NOTE: you must select contact id as the only field.')
810 $scope
.$watch('params', writeCode
, true);
811 $scope
.$watch('index', writeCode
);
814 $scope
.save = function() {
815 $scope
.params
.limit
= $scope
.params
.offset
= 0;
816 if ($scope
.params
.chain
.length
) {
817 CRM
.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires
: 5000});
820 if ($scope
.params
.select
.length
!== 1 || !_
.includes($scope
.params
.select
[0], 'id')) {
821 CRM
.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires
: 5000});
827 visibility
: 'User and User Admin Only',
830 entity
: $scope
.entity
,
831 params
: JSON
.parse(angular
.toJson($scope
.params
))
833 model
.params
.version
= 4;
834 delete model
.params
.chain
;
835 delete model
.params
.debug
;
836 delete model
.params
.limit
;
837 delete model
.params
.offset
;
838 delete model
.params
.orderBy
;
839 delete model
.params
.checkPermissions
;
840 var options
= CRM
.utils
.adjustDialogDefaults({
843 title
: ts('Save smart group')
845 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
849 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
850 var ts
= $scope
.ts
= CRM
.ts(),
851 model
= $scope
.model
;
852 $scope
.groupEntityRefParams
= {
855 params
: {is_hidden
: 0, is_active
: 1, 'saved_search_id.api_entity': model
.entity
},
856 extra
: ['saved_search_id', 'description', 'visibility', 'group_type']
860 minimumInputLength
: 0,
861 placeholder
: ts('Select existing group')
864 if (!CRM
.checkPerm('administer reserved groups')) {
865 $scope
.groupEntityRefParams
.api
.params
.is_reserved
= 0;
868 administerReservedGroups
: CRM
.checkPerm('administer reserved groups')
870 $scope
.options
= CRM
.vars
.api4
.groupOptions
;
871 $scope
.$watch('model.id', function(id
) {
873 _
.assign(model
, $('#api-save-search-select-group').select2('data').extra
);
876 $scope
.cancel = function() {
877 dialogService
.cancel('saveSearchDialog');
879 $scope
.save = function() {
880 $('.ui-dialog:visible').block();
881 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
882 group
.description
= model
.description
;
883 group
.visibility
= model
.visibility
;
884 group
.group_type
= model
.group_type
;
885 group
.saved_search_id
= '$id';
887 api_entity
: model
.entity
,
888 api_params
: model
.params
891 savedSearch
.id
= model
.saved_search_id
;
893 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
894 .then(function(result
) {
895 dialogService
.close('saveSearchDialog', result
[0]);
900 angular
.module('api4Explorer').directive('crmApi4Clause', function($timeout
) {
903 data
: '=crmApi4Clause'
905 templateUrl
: '~/api4Explorer/Clause.html',
906 link: function (scope
, element
, attrs
) {
907 var ts
= scope
.ts
= CRM
.ts();
908 scope
.newClause
= '';
909 scope
.conjunctions
= ['AND', 'OR', 'NOT'];
910 scope
.operators
= CRM
.vars
.api4
.operators
;
912 scope
.addGroup = function(op
) {
913 scope
.data
.clauses
.push([op
, []]);
916 scope
.removeGroup = function() {
917 scope
.data
.groupParent
.splice(scope
.data
.groupIndex
, 1);
920 scope
.onSort = function(event
, ui
) {
921 $(element
).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
922 $('.api4-input.form-inline').css('margin-left', '');
925 // Indent clause while dragging between nested groups
926 scope
.onSortOver = function(event
, ui
) {
929 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
931 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
934 scope
.$watch('newClause', function(value
) {
936 $timeout(function() {
938 scope
.data
.clauses
.push([field
, '=', '']);
939 scope
.newClause
= null;
943 scope
.$watch('data.clauses', function(values
) {
944 // Remove empty values
945 _
.each(values
, function(clause
, index
) {
946 if (typeof clause
!== 'undefined' && !clause
[0]) {
947 values
.splice(index
, 1);
949 if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
951 } else if (typeof clause
[1] === 'string' && clause
.length
== 2) {
960 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
963 data
: '=api4ExpValue'
966 link: function (scope
, element
, attrs
, ctrl
) {
967 var ts
= scope
.ts
= CRM
.ts(),
968 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
969 entity
= $routeParams
.api4entity
,
970 action
= scope
.data
.action
|| $routeParams
.api4action
;
972 function destroyWidget() {
973 var $el
= $(element
);
974 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
975 $el
.crmDatepicker('destroy');
977 if ($el
.is('.select2-container + input')) {
978 $el
.crmEntityRef('destroy');
980 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
983 function makeWidget(field
, op
) {
984 var $el
= $(element
),
985 inputType
= field
.input_type
,
986 dataType
= field
.data_type
;
988 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
990 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
991 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
995 if (inputType
=== 'Date') {
996 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
997 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
999 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
1000 if (field
.options
) {
1001 var id
= field
.pseudoconstant
|| 'id';
1002 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
1003 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
1004 var options
= _
.transform(data
[field
.name
].options
, function(options
, opt
) {
1005 options
.push({id
: opt
[id
], text
: opt
.label
, description
: opt
.description
, color
: opt
.color
, icon
: opt
.icon
});
1007 $el
.removeClass('loading').crmSelect2({data
: options
, multiple
: multi
});
1009 } else if (field
.fk_entity
) {
1010 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
1011 } else if (dataType
=== 'Boolean') {
1012 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
1013 {id
: 'true', text
: ts('Yes')},
1014 {id
: 'false', text
: ts('No')}
1017 } else if (dataType
=== 'Integer' && !multi
) {
1018 $el
.attr('type', 'number');
1022 function loadFieldOptions(entity
) {
1023 if (!fieldOptions
[entity
+ action
]) {
1024 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
1025 loadOptions
: ['id', 'name', 'label', 'description', 'color', 'icon'],
1027 where
: [['options', '!=', false]],
1031 return fieldOptions
[entity
+ action
];
1034 // Copied from ng-list but applied conditionally if field is multi-valued
1035 var parseList = function(viewValue
) {
1036 // If the viewValue is invalid (say required but empty) it will be `undefined`
1037 if (_
.isUndefined(viewValue
)) return;
1046 _
.each(viewValue
.split(','), function(value
) {
1047 if (value
) list
.push(_
.trim(value
));
1054 // Copied from ng-list
1055 ctrl
.$parsers
.push(parseList
);
1056 ctrl
.$formatters
.push(function(value
) {
1057 return _
.isArray(value
) ? value
.join(', ') : value
;
1060 // Copied from ng-list
1061 ctrl
.$isEmpty = function(value
) {
1062 return !value
|| !value
.length
;
1065 scope
.$watchCollection('data', function(data
) {
1067 var field
= getField(data
.field
, entity
, action
);
1069 makeWidget(field
, data
.op
);
1077 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
1080 chain
: '=api4ExpChain',
1084 templateUrl
: '~/api4Explorer/Chain.html',
1085 link: function (scope
, element
, attrs
) {
1086 var ts
= scope
.ts
= CRM
.ts();
1088 function changeEntity(newEntity
, oldEntity
) {
1089 // When clearing entity remove this chain
1091 scope
.chain
[0] = '';
1094 // Reset action && index
1095 if (newEntity
!== oldEntity
) {
1096 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
1098 if (getEntity(newEntity
).actions
) {
1101 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
1102 .then(function(data
) {
1103 getEntity(data
.entity
).actions
= data
;
1104 if (data
.entity
=== scope
.chain
[1][0]) {
1111 function setActions() {
1112 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
1115 // Set default params when choosing action
1116 function changeAction(newAction
, oldAction
) {
1118 // Prepopulate links
1119 if (newAction
&& newAction
!== oldAction
) {
1121 scope
.chain
[1][3] = '';
1122 // Look for links back to main entity
1123 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
1124 if (field
.fk_entity
=== scope
.mainEntity
) {
1125 link
= [field
.name
, '$id'];
1128 // Look for links from main entity
1129 if (!link
&& newAction
!== 'create') {
1130 _
.each(entityFields(scope
.mainEntity
), function(field
) {
1131 if (field
.fk_entity
=== scope
.chain
[1][0]) {
1132 link
= ['id', '$' + field
.name
];
1133 // Since we're specifying the id, set index to getsingle
1134 scope
.chain
[1][3] = '0';
1138 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1139 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1141 else if (link
&& _
.contains(['create'], newAction
)) {
1142 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1144 else if (link
&& _
.contains(['save'], newAction
)) {
1145 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1147 scope
.chain
[1][2] = '{}';
1152 scope
.$watch("chain[1][0]", changeEntity
);
1153 scope
.$watch("chain[1][1]", changeAction
);
1158 function getEntity(entityName
) {
1159 return _
.findWhere(schema
, {name
: entityName
});
1162 function entityFields(entityName
, action
) {
1163 var entity
= getEntity(entityName
);
1164 if (entity
&& action
&& entity
.actions
) {
1165 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1167 return _
.result(entity
, 'fields');
1170 function getField(fieldName
, entity
, action
) {
1171 var suffix
= fieldName
.split(':')[1];
1172 fieldName
= fieldName
.split(':')[0];
1173 var fieldNames
= fieldName
.split('.');
1174 var field
= get(entity
, fieldNames
);
1175 if (field
&& suffix
) {
1176 field
.pseudoconstant
= suffix
;
1180 function get(entity
, fieldNames
) {
1181 if (fieldNames
.length
=== 1) {
1182 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1184 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1188 var linkName
= fieldNames
.shift(),
1189 newEntity
= _
.findWhere(links
[entity
], {alias
: linkName
}).entity
;
1190 return get(newEntity
, fieldNames
);
1194 // Collapsible optgroups for select2
1197 .on('select2-open', function(e
) {
1198 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1200 .off('.collapseOptionGroup')
1201 .addClass('collapsible-optgroups-enabled')
1202 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1203 $(this).parent().toggleClass('optgroup-expanded');
1207 .on('select2-close', function() {
1208 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1211 })(angular
, CRM
.$, CRM
._
);