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
= {};
17 angular
.module('api4Explorer').config(function($routeProvider
) {
18 $routeProvider
.when('/explorer/:api4entity?/:api4action?', {
19 controller
: 'Api4Explorer',
20 templateUrl
: '~/api4Explorer/Explorer.html',
25 angular
.module('api4Explorer').controller('Api4Explorer', function($scope
, $routeParams
, $location
, $timeout
, $http
, crmUiHelp
, crmApi4
, dialogService
) {
26 var ts
= $scope
.ts
= CRM
.ts(),
27 ctrl
= $scope
.$ctrl
= this;
28 $scope
.entities
= entities
;
29 $scope
.actions
= actions
;
31 $scope
.havingOptions
= [];
32 $scope
.fieldsAndJoins
= [];
33 $scope
.fieldsAndJoinsAndFunctions
= [];
34 $scope
.fieldsAndJoinsAndFunctionsWithSuffixes
= [];
35 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= [];
36 $scope
.availableParams
= {};
37 params
= $scope
.params
= {};
39 $scope
.selectedTab
= {result
: 'result', code
: 'php'};
41 accessDebugOutput
: CRM
.checkPerm('access debug output'),
42 editGroups
: CRM
.checkPerm('edit groups')
44 marked
.setOptions({highlight
: prettyPrintOne
});
45 var getMetaParams
= {},
46 objectParams
= {orderBy
: 'ASC', values
: '', defaults
: '', chain
: ['Entity', '', '{}']},
47 docs
= CRM
.vars
.api4
.docs
,
50 $scope
.helpTitle
= '';
51 $scope
.helpContent
= {};
52 $scope
.entity
= $routeParams
.api4entity
;
55 $scope
.status
= 'default';
56 $scope
.loading
= false;
58 $scope
.langs
= ['php', 'js', 'ang', 'cli'];
59 $scope
.joinTypes
= [{k
: false, v
: 'FALSE (LEFT JOIN)'}, {k
: true, v
: 'TRUE (INNER JOIN)'}];
60 $scope
.bridgeEntities
= _
.filter(schema
, {type
: 'BridgeEntity'});
63 {name
: 'oop', label
: ts('OOP Style'), code
: ''},
64 {name
: 'php', label
: ts('Traditional'), code
: ''}
67 {name
: 'js', label
: ts('Single Call'), code
: ''},
68 {name
: 'js2', label
: ts('Batch Calls'), code
: ''}
71 {name
: 'ang', label
: ts('Single Call'), code
: ''},
72 {name
: 'ang2', label
: ts('Batch Calls'), code
: ''}
75 {name
: 'cv', label
: ts('CV'), code
: ''}
79 if (!entities
.length
) {
80 formatForSelect2(schema
, entities
, 'name', ['description', 'icon']);
89 function ucfirst(str
) {
90 return str
[0].toUpperCase() + str
.slice(1);
93 function lcfirst(str
) {
94 return str
[0].toLowerCase() + str
.slice(1);
97 function pluralize(str
) {
98 var lastLetter
= str
[str
.length
- 1],
99 lastTwo
= str
[str
.length
- 2] + lastLetter
;
100 if (lastLetter
=== 's' || lastLetter
=== 'x' || lastTwo
=== 'ch') {
103 if (lastLetter
=== 'y' && lastTwo
!== 'ey') {
104 return str
.slice(0, -1) + 'ies';
109 // Reformat an existing array of objects for compatibility with select2
110 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
111 _
.each(input
, function(item
) {
112 var id
= (prefix
|| '') + item
[key
];
113 var formatted
= {id
: id
, text
: id
};
115 _
.merge(formatted
, _
.pick(item
, extra
));
117 container
.push(formatted
);
122 // Replaces contents of fieldList array with current fields formatted for select2
123 function getFieldList(fieldList
, action
, addPseudoconstant
) {
124 var fieldInfo
= _
.cloneDeep(_
.findWhere(getEntity().actions
, {name
: action
}).fields
);
125 fieldList
.length
= 0;
126 if (addPseudoconstant
) {
127 addPseudoconstants(fieldInfo
, addPseudoconstant
);
129 formatForSelect2(fieldInfo
, fieldList
, 'name', ['description', 'required', 'default_value']);
132 // Note: this function expects fieldList to be select2-formatted already
133 function addJoins(fieldList
, addWildcard
, addPseudoconstant
) {
134 // Add entities specified by the join param
135 _
.each(getExplicitJoins(), function(joinEntity
, joinAlias
) {
136 var wildCard
= addWildcard
? [{id
: joinAlias
+ '.*', text
: joinAlias
+ '.*', 'description': 'All core ' + joinEntity
+ ' fields'}] : [],
137 joinFields
= _
.cloneDeep(entityFields(joinEntity
));
139 if (addPseudoconstant
) {
140 addPseudoconstants(joinFields
, addPseudoconstant
);
143 text
: joinEntity
+ ' AS ' + joinAlias
,
144 description
: 'Explicit join to ' + joinEntity
,
145 children
: wildCard
.concat(formatForSelect2(joinFields
, [], 'name', ['description'], joinAlias
+ '.'))
149 // Add implicit joins based on schema links
150 _
.each(links
[$scope
.entity
], function(link
) {
151 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
152 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
154 if (addPseudoconstant
) {
155 addPseudoconstants(linkFields
, addPseudoconstant
);
159 description
: 'Implicit join to ' + link
.entity
,
160 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
166 // Note: this function transforms a raw list a-la getFields; not a select2-formatted list
167 function addPseudoconstants(fieldList
, toAdd
) {
168 var optionFields
= _
.filter(fieldList
, 'options');
169 _
.each(optionFields
, function(field
) {
170 var pos
= _
.findIndex(fieldList
, {name
: field
.name
}) + 1;
171 _
.each(toAdd
, function(suffix
) {
172 var newField
= _
.cloneDeep(field
);
173 newField
.name
+= ':' + suffix
;
174 fieldList
.splice(pos
, 0, newField
);
179 $scope
.help = function(title
, content
) {
181 $scope
.helpTitle
= helpTitle
;
182 $scope
.helpContent
= helpContent
;
184 $scope
.helpTitle
= title
;
185 $scope
.helpContent
= formatHelp(content
);
189 // Sets the static help text (which gets overridden by mousing over other elements)
190 function setHelp(title
, content
) {
191 $scope
.helpTitle
= helpTitle
= title
;
192 $scope
.helpContent
= helpContent
= formatHelp(content
);
195 // Convert plain-text help to markdown; replace variables and format links
196 function formatHelp(rawContent
) {
197 function formatRefs(see
) {
198 _
.each(see
, function(ref
, idx
) {
199 var match
= ref
.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
201 ref
= '#/explorer/' + match
[1];
203 if (ref
[0] === '\\') {
204 ref
= 'https://github.com/civicrm/civicrm-core/blob/master' + ref
.replace(/\\/i, '/') + '.php
';
206 see[idx] = '<a target
="' + (ref[0] === '#' ? '_self' : '_blank') + '" href
="' + ref + '">' + see[idx] + '</a
>';
209 var formatted = _.cloneDeep(rawContent);
210 if (formatted.description) {
211 formatted.description = marked(formatted.description);
213 if (formatted.comment) {
214 formatted.comment = marked(formatted.comment);
216 formatRefs(formatted.see);
220 $scope.fieldHelp = function(fieldName) {
221 var field = getField(fieldName, $scope.entity, $scope.action);
226 description: field.description,
227 type: field.data_type
229 if (field.default_value) {
230 info.default = field.default_value;
232 if (field.required_if) {
233 info.required_if = field.required_if;
234 } else if (field.required) {
235 info.required = 'true';
240 // Returns field list for write params (values, defaults)
241 $scope.fieldList = function(param) {
244 getFieldList(fields, $scope.action === 'getFields
' ? ($scope.params.action || 'get') : $scope.action, ['name
']);
245 // Disable fields that are already in use
246 _.each($scope.params[param] || [], function(val) {
247 var usedField = val[0].replace(':name
', '');
248 (_.findWhere(fields, {id: usedField}) || {}).disabled = true;
249 (_.findWhere(fields, {id: usedField + ':name
'}) || {}).disabled = true;
251 return {results: fields};
255 $scope.formatSelect2Item = function(row) {
256 return _.escape(row.text) +
257 (row.required ? '<span
class="crm-marker"> *</span
>' : '') +
258 (row.description ? '<div
class="crm-select2-row-description"><p
>' + _.escape(row.description) + '</p></div>' : '');
261 $scope.clearParam = function(name, idx) {
262 if (typeof idx === 'undefined') {
263 $scope.params[name] = $scope.availableParams[name].default;
265 $scope.params[name].splice(idx, 1);
269 // Gets params that should be represented as generic input fields in the explorer
270 // This fn doesn't have to be particularly efficient as its output is cached
in one
-time bindings
271 $scope
.getGenericParams = function(paramType
, defaultNull
) {
272 // Returns undefined if params are not yet set; one-time bindings will stabilize when this function returns a value
273 if (_
.isEmpty($scope
.availableParams
)) {
276 var specialParams
= ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having', 'join'];
277 if ($scope
.availableParams
.limit
&& $scope
.availableParams
.offset
) {
278 specialParams
.push('limit', 'offset');
280 return _
.transform($scope
.availableParams
, function(genericParams
, param
, name
) {
281 if (!_
.contains(specialParams
, name
) &&
282 !(typeof paramType
!== 'undefined' && !_
.contains(paramType
, param
.type
[0])) &&
283 !(typeof defaultNull
!== 'undefined' && ((param
.default === null) !== defaultNull
))
285 genericParams
[name
] = param
;
290 $scope
.selectRowCount = function() {
291 var index
= params
.select
.indexOf('row_count');
293 $scope
.params
.select
.push('row_count');
295 $scope
.params
.select
.splice(index
, 1);
299 $scope
.isSelectRowCount = function() {
300 return isSelectRowCount($scope
.params
);
303 $scope
.selectLang = function(lang
) {
304 $scope
.selectedTab
.code
= lang
;
308 function isSelectRowCount(params
) {
309 return params
&& params
.select
&& params
.select
.indexOf('row_count') >= 0;
312 function getEntity(entityName
) {
313 return _
.findWhere(schema
, {name
: entityName
|| $scope
.entity
});
316 // Get name of entity given join alias
317 function entityNameFromAlias(alias
) {
318 var joins
= getExplicitJoins(),
319 entity
= $scope
.entity
,
320 path
= alias
.split('.');
321 // First check explicit joins
325 // Then lookup implicit links
326 _
.each(path
, function(node
) {
327 entity
= _
.find(links
[entity
], {alias
: node
}).entity
;
332 // Get all params that have been set
333 function getParams() {
335 _
.each($scope
.params
, function(param
, key
) {
336 if (param
!= $scope
.availableParams
[key
].default && !(typeof param
=== 'object' && _
.isEmpty(param
))) {
337 if (_
.contains($scope
.availableParams
[key
].type
, 'array') && (typeof objectParams
[key
] === 'undefined')) {
338 params
[key
] = parseYaml(JSON
.parse(angular
.toJson(param
)));
344 _
.each(objectParams
, function(defaultVal
, key
) {
347 _
.each(params
[key
], function(item
) {
348 var val
= _
.cloneDeep(item
[1]);
349 // Remove blank items from "chain" array
350 if (_
.isArray(val
)) {
351 _
.eachRight(item
[1], function(v
, k
) {
358 newParam
[item
[0]] = parseYaml(val
);
360 params
[key
] = newParam
;
366 function parseYaml(input
) {
367 if (typeof input
=== 'undefined' || input
=== '') {
370 // Return literal quoted string without removing quotes - for the sake of JOIN ON clauses
371 if (_
.isString(input
) && input
[0] === input
[input
.length
- 1] && _
.includes(["'", '"'], input
[0])) {
374 if (_
.isObject(input
) || _
.isArray(input
)) {
375 _
.each(input
, function(item
, index
) {
376 input
[index
] = parseYaml(item
);
381 var output
= (input
=== '>') ? '>' : jsyaml
.safeLoad(input
);
382 // We don't want dates parsed to js objects
383 return _
.isDate(output
) ? input
: output
;
389 this.buildFieldList = function() {
390 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
391 getFieldList($scope
.fields
, $scope
.action
);
392 getFieldList($scope
.fieldsAndJoins
, $scope
.action
, ['name']);
393 getFieldList($scope
.fieldsAndJoinsAndFunctions
, $scope
.action
);
394 getFieldList($scope
.fieldsAndJoinsAndFunctionsWithSuffixes
, $scope
.action
, ['name', 'label']);
395 getFieldList($scope
.fieldsAndJoinsAndFunctionsAndWildcards
, $scope
.action
, ['name', 'label']);
396 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
397 addJoins($scope
.fieldsAndJoins
);
398 // SQL functions are supported if HAVING is
399 if (actionInfo
.params
.having
) {
401 text
: ts('FUNCTION'),
402 description
: ts('Calculate result of a SQL function'),
403 children
: _
.transform(CRM
.vars
.api4
.functions
, function(result
, fn
) {
405 id
: fn
.name
+ '() AS ' + fn
.name
.toLowerCase(),
406 text
: fn
.name
+ '()',
407 description
: fn
.name
+ '(' + describeSqlFn(fn
.params
) + ')'
411 $scope
.fieldsAndJoinsAndFunctions
.push(functions
);
412 $scope
.fieldsAndJoinsAndFunctionsWithSuffixes
.push(functions
);
413 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.push(functions
);
415 addJoins($scope
.fieldsAndJoinsAndFunctions
, true);
416 addJoins($scope
.fieldsAndJoinsAndFunctionsWithSuffixes
, false, ['name', 'label']);
417 addJoins($scope
.fieldsAndJoinsAndFunctionsAndWildcards
, true, ['name', 'label']);
419 // Custom fields are supported if HAVING is
420 if (actionInfo
.params
.having
) {
421 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: 'custom.*', text
: 'custom.*', 'description': 'All custom fields'});
423 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
426 function selectAction() {
427 $scope
.action
= $routeParams
.api4action
;
428 if (!actions
.length
) {
429 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
432 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
433 _
.each(actionInfo
.params
, function (param
, name
) {
435 defaultVal
= _
.cloneDeep(param
.default);
437 switch (param
.type
[0]) {
440 format
= param
.type
[0];
451 if (name
=== 'limit') {
454 if (name
=== 'debug') {
457 if (name
=== 'values') {
458 defaultVal
= defaultValues(defaultVal
);
460 if (name
=== 'loadOptions' && $scope
.action
=== 'getFields') {
464 ['id', 'name', 'label'],
465 ['id', 'name', 'label', 'abbr', 'description', 'color', 'icon']
469 param
.type
= ['string'];
471 $scope
.$bindToRoute({
472 expr
: 'params["' + name
+ '"]',
476 deep
: format
=== 'json'
479 if (typeof objectParams
[name
] !== 'undefined' && name
!== 'orderBy') {
480 $scope
.$watch('params.' + name
, function (values
) {
481 // Remove empty values
482 _
.each(values
, function (clause
, index
) {
483 if (!clause
|| !clause
[0]) {
484 $scope
.clearParam(name
, index
);
489 if (name
=== 'select' && actionInfo
.params
.having
) {
490 $scope
.$watchCollection('params.select', function(newSelect
) {
491 // Ignore row_count, it can't be used in HAVING clause
492 var select
= _
.without(newSelect
, 'row_count');
493 $scope
.havingOptions
.length
= 0;
494 // An empty select is an implicit *
495 if (!select
.length
) {
498 _
.each(select
, function(item
) {
500 pieces
= item
.split(' AS '),
501 alias
= _
.trim(pieces
[pieces
.length
- 1]).replace(':label', ':name');
503 if (alias
[alias
.length
- 1] === '*') {
504 if (alias
.length
> 1) {
505 joinEntity
= entityNameFromAlias(alias
.slice(0, -2));
507 var fieldList
= _
.filter(getEntity(joinEntity
).fields
, {custom_field_id
: null});
508 formatForSelect2(fieldList
, $scope
.havingOptions
, 'name', ['description', 'required', 'default_value'], alias
.slice(0, -1));
511 $scope
.havingOptions
.push({id
: alias
, text
: alias
});
516 if (typeof objectParams
[name
] !== 'undefined' || name
=== 'groupBy' || name
=== 'select' || name
=== 'join') {
517 $scope
.$watch('controls.' + name
, function(value
) {
519 $timeout(function() {
521 if (name
=== 'join') {
522 $scope
.params
[name
].push([field
+ ' AS ' + _
.snakeCase(field
), false]);
523 ctrl
.buildFieldList();
525 else if (typeof objectParams
[name
] === 'undefined') {
526 $scope
.params
[name
].push(field
);
528 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
529 if (name
=== 'chain') {
530 var num
= $scope
.params
.chain
.length
;
531 defaultOp
[0] = field
;
532 field
= 'name_me_' + num
;
534 $scope
.params
[name
].push([field
, defaultOp
]);
536 $scope
.controls
[name
] = null;
542 ctrl
.buildFieldList();
543 $scope
.availableParams
= actionInfo
.params
;
548 function describeSqlFn(params
) {
550 _
.each(params
, function(param
) {
553 desc
+= _
.filter(param
.prefix
).join('|') + ' ';
555 if (param
.expr
=== 1) {
557 } else if (param
.expr
> 1) {
558 desc
+= 'expr, ... ';
561 desc
+= ' ' + _
.filter(param
.suffix
).join('|') + ' ';
564 return desc
.replace(/[ ]+/g, ' ');
567 function defaultValues(defaultVal
) {
568 _
.each($scope
.fields
, function(field
) {
569 if (field
.required
) {
570 defaultVal
.push([field
.id
, '']);
576 function stringify(value
, trim
) {
577 if (typeof value
=== 'undefined') {
580 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
582 str
= str
.slice(1, -1);
587 function writeCode() {
589 entity
= $scope
.entity
,
590 action
= $scope
.action
,
591 params
= getParams(),
592 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
594 if ($scope
.entity
&& $scope
.action
) {
596 if (action
.slice(0, 3) === 'get') {
597 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
598 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
600 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
601 paramCount
= _
.size(params
),
604 switch ($scope
.selectedTab
.code
) {
608 var js
= "'" + entity
+ "', '" + action
+ "', {";
609 _
.each(params
, function(param
, key
) {
610 js
+= "\n " + key
+ ': ' + stringify(param
) +
611 (++i
< paramCount
? ',' : '');
612 if (key
=== 'checkPermissions') {
613 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
617 if (index
|| index
=== 0) {
618 js
+= ', ' + JSON
.stringify(index
);
620 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
621 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
622 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
623 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
628 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
629 _
.each(params
, function(param
, key
) {
630 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
633 if (index
|| index
=== 0) {
634 code
.php
+= ', ' + phpFormat(index
);
639 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
640 if (_
.isNumber(index
)) {
641 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
643 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
644 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
646 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
647 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
651 if (!_
.isNumber(index
)) {
652 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
658 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
661 _
.each($scope
.code
, function(vals
) {
662 _
.each(vals
, function(style
) {
663 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
669 function formatOOP(entity
, action
, params
, indent
) {
671 newLine
= "\n" + _
.repeat(' ', indent
),
672 perm
= params
.checkPermissions
=== false ? 'FALSE' : '';
673 if (entity
.substr(0, 7) !== 'Custom_') {
674 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '(' + perm
+ ')';
676 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "'" + (perm
? ', ' : '') + perm
+ ")";
678 _
.each(params
, function(param
, key
) {
680 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
681 _
.each(param
, function(item
, index
) {
682 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
683 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
685 } else if (key
=== 'where') {
686 _
.each(param
, function (clause
) {
687 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
688 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
690 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
693 } else if (key
=== 'select') {
694 // selectRowCount() is a shortcut for addSelect('row_count')
695 if (isSelectRowCount(params
)) {
696 code
+= newLine
+ '->selectRowCount()';
697 param
= _
.without(param
, 'row_count');
699 // addSelect() is a variadic function & can take multiple arguments
701 code
+= newLine
+ '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
703 } else if (key
=== 'chain') {
704 _
.each(param
, function(chain
, name
) {
705 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
706 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
709 else if (key
!== 'checkPermissions') {
710 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
716 function isInt(value
) {
717 if (_
.isFinite(value
)) {
720 if (!_
.isString(value
)) {
723 return /^-{0,1}\d+$/.test(value
);
726 function formatMeta(resp
) {
728 _
.each(resp
, function(val
, key
) {
729 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
730 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
733 return prettyPrintOne(_
.escape(ret
));
736 $scope
.execute = function() {
737 $scope
.status
= 'info';
738 $scope
.loading
= true;
739 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
740 params
: angular
.toJson(getParams()),
741 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
744 'X-Requested-With': 'XMLHttpRequest'
746 }).then(function(resp
) {
747 $scope
.loading
= false;
748 $scope
.status
= resp
.data
&& resp
.data
.debug
&& resp
.data
.debug
.log
? 'warning' : 'success';
749 $scope
.debug
= debugFormat(resp
.data
);
751 formatMeta(resp
.data
),
752 prettyPrintOne('(' + resp
.data
.values
.length
+ ') ' + _
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)
755 $scope
.loading
= false;
756 $scope
.status
= 'danger';
757 $scope
.debug
= debugFormat(resp
.data
);
760 prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))
765 function debugFormat(data
) {
766 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
772 * Format value to look like php code
774 function phpFormat(val
, indent
) {
775 if (typeof val
=== 'undefined') {
778 if (val
=== null || val
=== true || val
=== false) {
779 return JSON
.stringify(val
).toUpperCase();
781 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
783 baseLine
= indent
? indent
.slice(0, -2) : '',
784 newLine
= indent
? '\n' : '',
785 trailingComma
= indent
? ',' : '';
786 if ($.isPlainObject(val
)) {
787 $.each(val
, function(k
, v
) {
788 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
790 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
792 if ($.isArray(val
)) {
793 $.each(val
, function(k
, v
) {
794 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
796 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
798 if (_
.isString(val
) && !_
.contains(val
, "'")) {
799 return "'" + val
+ "'";
801 return JSON
.stringify(val
).replace(/\$/g, '\\$');
804 function fetchMeta() {
805 crmApi4(getMetaParams
)
806 .then(function(data
) {
808 getEntity().actions
= data
.actions
;
814 // Help for an entity with no action selected
815 function showEntityHelp(entityName
) {
816 var entityInfo
= getEntity(entityName
);
817 setHelp($scope
.entity
, {
818 description
: entityInfo
.description
,
819 comment
: entityInfo
.comment
,
824 if (!$scope
.entity
) {
825 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
826 } else if (!actions
.length
&& !getEntity().actions
) {
827 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
834 showEntityHelp($scope
.entity
);
837 // Update route when changing entity
838 $scope
.$watch('entity', function(newVal
, oldVal
) {
839 if (oldVal
!== newVal
) {
840 // Flush actions cache to re-fetch for new entity
842 $location
.url('/explorer/' + newVal
);
846 // Update route when changing actions
847 $scope
.$watch('action', function(newVal
, oldVal
) {
848 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
849 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
851 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
855 $scope
.paramDoc = function(name
) {
856 return docs
.params
[name
];
859 $scope
.executeDoc = function() {
861 description
: ts('Runs API call on the CiviCRM database.'),
862 comment
: ts('Results and debugging info will be displayed below.')
864 if ($scope
.action
=== 'delete') {
865 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
867 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
868 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
873 $scope
.saveDoc = function() {
875 description
: ts('Save API call as a smart group.'),
876 comment
: ts('Create a SavedSearch using these API params to populate a smart group.') +
877 '\n\n' + ts('NOTE: you must select contact id as the only field.')
881 $scope
.$watch('params', writeCode
, true);
882 $scope
.$watch('index', writeCode
);
885 $scope
.save = function() {
886 $scope
.params
.limit
= $scope
.params
.offset
= 0;
887 if ($scope
.params
.chain
.length
) {
888 CRM
.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires
: 5000});
891 if ($scope
.params
.select
.length
!== 1 || !_
.includes($scope
.params
.select
[0], 'id')) {
892 CRM
.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires
: 5000});
898 visibility
: 'User and User Admin Only',
901 entity
: $scope
.entity
,
902 params
: JSON
.parse(angular
.toJson($scope
.params
))
904 model
.params
.version
= 4;
905 delete model
.params
.chain
;
906 delete model
.params
.debug
;
907 delete model
.params
.limit
;
908 delete model
.params
.offset
;
909 delete model
.params
.orderBy
;
910 delete model
.params
.checkPermissions
;
911 var options
= CRM
.utils
.adjustDialogDefaults({
914 title
: ts('Save smart group')
916 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
920 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
921 var ts
= $scope
.ts
= CRM
.ts(),
922 model
= $scope
.model
;
923 $scope
.groupEntityRefParams
= {
926 params
: {is_hidden
: 0, is_active
: 1, 'saved_search_id.api_entity': model
.entity
},
927 extra
: ['saved_search_id', 'description', 'visibility', 'group_type']
931 minimumInputLength
: 0,
932 placeholder
: ts('Select existing group')
935 if (!CRM
.checkPerm('administer reserved groups')) {
936 $scope
.groupEntityRefParams
.api
.params
.is_reserved
= 0;
939 administerReservedGroups
: CRM
.checkPerm('administer reserved groups')
941 $scope
.options
= CRM
.vars
.api4
.groupOptions
;
942 $scope
.$watch('model.id', function(id
) {
944 _
.assign(model
, $('#api-save-search-select-group').select2('data').extra
);
947 $scope
.cancel = function() {
948 dialogService
.cancel('saveSearchDialog');
950 $scope
.save = function() {
951 $('.ui-dialog:visible').block();
952 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
953 group
.description
= model
.description
;
954 group
.visibility
= model
.visibility
;
955 group
.group_type
= model
.group_type
;
956 group
.saved_search_id
= '$id';
958 api_entity
: model
.entity
,
959 api_params
: model
.params
962 savedSearch
.id
= model
.saved_search_id
;
964 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
965 .then(function(result
) {
966 dialogService
.close('saveSearchDialog', result
[0]);
971 angular
.module('api4Explorer').directive('crmApi4Clause', function() {
974 data
: '<crmApi4Clause'
976 templateUrl
: '~/api4Explorer/Clause.html',
977 controller: function ($scope
, $element
, $timeout
) {
978 var ts
= $scope
.ts
= CRM
.ts(),
979 ctrl
= $scope
.$ctrl
= this;
980 this.conjunctions
= {AND
: ts('And'), OR
: ts('Or'), NOT
: ts('Not')};
981 this.operators
= CRM
.vars
.api4
.operators
;
984 connectWith
: '.api4-clause-group-sortable',
985 containment
: $element
.closest('.api4-clause-fieldset'),
991 this.addGroup = function(op
) {
992 $scope
.data
.clauses
.push([op
, []]);
995 this.removeGroup = function() {
996 $scope
.data
.groupParent
.splice($scope
.data
.groupIndex
, 1);
999 function onSort(event
, ui
) {
1000 $($element
).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
1001 $('.api4-input.form-inline').css('margin-left', '');
1004 // Indent clause while dragging between nested groups
1005 function onSortOver(event
, ui
) {
1008 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
1010 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
1013 this.addClause = function() {
1014 $timeout(function() {
1015 if (ctrl
.newClause
) {
1016 $scope
.data
.clauses
.push([ctrl
.newClause
, '=', '']);
1017 ctrl
.newClause
= null;
1021 $scope
.$watch('data.clauses', function(values
) {
1022 // Iterate in reverse order so index doesn't get out-of-sync during splice
1023 _
.forEachRight(values
, function(clause
, index
) {
1024 // Remove empty values
1025 if (index
>= ($scope
.data
.skip
|| 0)) {
1026 if (typeof clause
!== 'undefined' && !clause
[0]) {
1027 values
.splice(index
, 1);
1029 // Add/remove value if operator allows for one
1030 else if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
1032 } else if (typeof clause
[1] === 'string' && clause
.length
=== 2) {
1042 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
1045 data
: '=api4ExpValue'
1048 link: function (scope
, element
, attrs
, ctrl
) {
1049 var ts
= scope
.ts
= CRM
.ts(),
1050 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
1051 entity
= $routeParams
.api4entity
,
1052 action
= scope
.data
.action
|| $routeParams
.api4action
;
1054 function destroyWidget() {
1055 var $el
= $(element
);
1056 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
1057 $el
.crmDatepicker('destroy');
1059 if ($el
.is('.select2-container + input')) {
1060 $el
.crmEntityRef('destroy');
1062 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
1065 function makeWidget(field
, op
) {
1066 var $el
= $(element
),
1067 inputType
= field
.input_type
,
1068 dataType
= field
.data_type
;
1070 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
1072 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
1073 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
1077 if (inputType
=== 'Date') {
1078 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
1079 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
1081 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
1082 if (field
.options
) {
1083 var id
= field
.pseudoconstant
|| 'id';
1084 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
1085 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
1086 var options
= _
.transform(data
[field
.name
].options
, function(options
, opt
) {
1087 options
.push({id
: opt
[id
], text
: opt
.label
, description
: opt
.description
, color
: opt
.color
, icon
: opt
.icon
});
1089 $el
.removeClass('loading').crmSelect2({data
: options
, multiple
: multi
});
1091 } else if (field
.fk_entity
) {
1092 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
1093 } else if (dataType
=== 'Boolean') {
1094 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
1095 {id
: 'true', text
: ts('Yes')},
1096 {id
: 'false', text
: ts('No')}
1099 } else if (dataType
=== 'Integer' && !multi
) {
1100 $el
.attr('type', 'number');
1104 function loadFieldOptions(entity
) {
1105 if (!fieldOptions
[entity
+ action
]) {
1106 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
1107 loadOptions
: ['id', 'name', 'label', 'description', 'color', 'icon'],
1109 where
: [['options', '!=', false]],
1113 return fieldOptions
[entity
+ action
];
1116 // Copied from ng-list but applied conditionally if field is multi-valued
1117 var parseList = function(viewValue
) {
1118 // If the viewValue is invalid (say required but empty) it will be `undefined`
1119 if (_
.isUndefined(viewValue
)) return;
1128 _
.each(viewValue
.split(','), function(value
) {
1129 if (value
) list
.push(_
.trim(value
));
1136 // Copied from ng-list
1137 ctrl
.$parsers
.push(parseList
);
1138 ctrl
.$formatters
.push(function(value
) {
1139 return _
.isArray(value
) ? value
.join(', ') : value
;
1142 // Copied from ng-list
1143 ctrl
.$isEmpty = function(value
) {
1144 return !value
|| !value
.length
;
1147 scope
.$watchCollection('data', function(data
) {
1149 var field
= getField(data
.field
, entity
, action
);
1150 if (field
&& data
.format
!== 'plain') {
1151 makeWidget(field
, data
.op
);
1159 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
1162 chain
: '=api4ExpChain',
1166 templateUrl
: '~/api4Explorer/Chain.html',
1167 link: function (scope
, element
, attrs
) {
1168 var ts
= scope
.ts
= CRM
.ts();
1170 function changeEntity(newEntity
, oldEntity
) {
1171 // When clearing entity remove this chain
1173 scope
.chain
[0] = '';
1176 // Reset action && index
1177 if (newEntity
!== oldEntity
) {
1178 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
1180 if (getEntity(newEntity
).actions
) {
1183 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
1184 .then(function(data
) {
1185 getEntity(data
.entity
).actions
= data
;
1186 if (data
.entity
=== scope
.chain
[1][0]) {
1193 function setActions() {
1194 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
1197 // Set default params when choosing action
1198 function changeAction(newAction
, oldAction
) {
1200 // Prepopulate links
1201 if (newAction
&& newAction
!== oldAction
) {
1203 scope
.chain
[1][3] = '';
1204 // Look for links back to main entity
1205 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
1206 if (field
.fk_entity
=== scope
.mainEntity
) {
1207 link
= [field
.name
, '$id'];
1210 // Look for links from main entity
1211 if (!link
&& newAction
!== 'create') {
1212 _
.each(entityFields(scope
.mainEntity
), function(field
) {
1213 if (field
.fk_entity
=== scope
.chain
[1][0]) {
1214 link
= ['id', '$' + field
.name
];
1215 // Since we're specifying the id, set index to getsingle
1216 scope
.chain
[1][3] = '0';
1220 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1221 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1223 else if (link
&& _
.contains(['create'], newAction
)) {
1224 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1226 else if (link
&& _
.contains(['save'], newAction
)) {
1227 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1229 scope
.chain
[1][2] = '{}';
1234 scope
.$watch("chain[1][0]", changeEntity
);
1235 scope
.$watch("chain[1][1]", changeAction
);
1240 function getEntity(entityName
) {
1241 return _
.findWhere(schema
, {name
: entityName
});
1244 function entityFields(entityName
, action
) {
1245 var entity
= getEntity(entityName
);
1246 if (entity
&& action
&& entity
.actions
) {
1247 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1249 return _
.result(entity
, 'fields');
1252 function getExplicitJoins() {
1253 return _
.transform(params
.join
, function(joins
, join
) {
1254 var j
= join
[0].split(' AS '),
1255 joinEntity
= _
.trim(j
[0]),
1256 joinAlias
= _
.trim(j
[1]) || joinEntity
.toLowerCase();
1257 joins
[joinAlias
] = joinEntity
;
1261 function getField(fieldName
, entity
, action
) {
1262 var suffix
= fieldName
.split(':')[1];
1263 fieldName
= fieldName
.split(':')[0];
1264 var fieldNames
= fieldName
.split('.');
1265 var field
= get(entity
, fieldNames
);
1266 if (field
&& suffix
) {
1267 field
.pseudoconstant
= suffix
;
1271 function get(entity
, fieldNames
) {
1272 if (fieldNames
.length
=== 1) {
1273 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1275 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1279 var linkName
= fieldNames
.shift(),
1280 newEntity
= getExplicitJoins()[linkName
] || _
.findWhere(links
[entity
], {alias
: linkName
}).entity
;
1281 return get(newEntity
, fieldNames
);
1285 // Collapsible optgroups for select2
1288 .on('select2-open', function(e
) {
1289 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1291 .off('.collapseOptionGroup')
1292 .addClass('collapsible-optgroups-enabled')
1293 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1294 $(this).parent().toggleClass('optgroup-expanded');
1298 .on('select2-close', function() {
1299 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1302 })(angular
, CRM
.$, CRM
._
);