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
: ts('Optional')}, {k
: true, v
: ts('Required')}];
62 {name
: 'oop', label
: ts('OOP Style'), code
: ''},
63 {name
: 'php', label
: ts('Traditional'), code
: ''}
66 {name
: 'js', label
: ts('Single Call'), code
: ''},
67 {name
: 'js2', label
: ts('Batch Calls'), code
: ''}
70 {name
: 'ang', label
: ts('Single Call'), code
: ''},
71 {name
: 'ang2', label
: ts('Batch Calls'), code
: ''}
74 {name
: 'cv', label
: ts('CV'), code
: ''}
78 if (!entities
.length
) {
79 formatForSelect2(schema
, entities
, 'name', ['description', 'icon']);
88 function ucfirst(str
) {
89 return str
[0].toUpperCase() + str
.slice(1);
92 function lcfirst(str
) {
93 return str
[0].toLowerCase() + str
.slice(1);
96 function pluralize(str
) {
97 var lastLetter
= str
[str
.length
- 1],
98 lastTwo
= str
[str
.length
- 2] + lastLetter
;
99 if (lastLetter
=== 's' || lastTwo
=== 'ch') {
102 if (lastLetter
=== 'y' && lastTwo
!== 'ey') {
103 return str
.slice(0, -1) + 'ies';
108 // Reformat an existing array of objects for compatibility with select2
109 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
110 _
.each(input
, function(item
) {
111 var id
= (prefix
|| '') + item
[key
];
112 var formatted
= {id
: id
, text
: id
};
114 _
.merge(formatted
, _
.pick(item
, extra
));
116 container
.push(formatted
);
121 // Replaces contents of fieldList array with current fields formatted for select2
122 function getFieldList(fieldList
, action
, addPseudoconstant
) {
123 var fieldInfo
= _
.cloneDeep(_
.findWhere(getEntity().actions
, {name
: action
}).fields
);
124 fieldList
.length
= 0;
125 if (addPseudoconstant
) {
126 addPseudoconstants(fieldInfo
, addPseudoconstant
);
128 formatForSelect2(fieldInfo
, fieldList
, 'name', ['description', 'required', 'default_value']);
131 // Note: this function expects fieldList to be select2-formatted already
132 function addJoins(fieldList
, addWildcard
, addPseudoconstant
) {
133 // Add entities specified by the join param
134 _
.each(getExplicitJoins(), function(joinEntity
, joinAlias
) {
135 var wildCard
= addWildcard
? [{id
: joinAlias
+ '.*', text
: joinAlias
+ '.*', 'description': 'All core ' + joinEntity
+ ' fields'}] : [],
136 joinFields
= _
.cloneDeep(entityFields(joinEntity
));
138 if (addPseudoconstant
) {
139 addPseudoconstants(joinFields
, addPseudoconstant
);
142 text
: joinEntity
+ ' AS ' + joinAlias
,
143 description
: 'Explicit join to ' + joinEntity
,
144 children
: wildCard
.concat(formatForSelect2(joinFields
, [], 'name', ['description'], joinAlias
+ '.'))
148 // Add implicit joins based on schema links
149 _
.each(links
[$scope
.entity
], function(link
) {
150 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
151 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
153 if (addPseudoconstant
) {
154 addPseudoconstants(linkFields
, addPseudoconstant
);
158 description
: 'Implicit join to ' + link
.entity
,
159 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
165 // Note: this function transforms a raw list a-la getFields; not a select2-formatted list
166 function addPseudoconstants(fieldList
, toAdd
) {
167 var optionFields
= _
.filter(fieldList
, 'options');
168 _
.each(optionFields
, function(field
) {
169 var pos
= _
.findIndex(fieldList
, {name
: field
.name
}) + 1;
170 _
.each(toAdd
, function(suffix
) {
171 var newField
= _
.cloneDeep(field
);
172 newField
.name
+= ':' + suffix
;
173 fieldList
.splice(pos
, 0, newField
);
178 $scope
.help = function(title
, content
) {
180 $scope
.helpTitle
= helpTitle
;
181 $scope
.helpContent
= helpContent
;
183 $scope
.helpTitle
= title
;
184 $scope
.helpContent
= formatHelp(content
);
188 // Sets the static help text (which gets overridden by mousing over other elements)
189 function setHelp(title
, content
) {
190 $scope
.helpTitle
= helpTitle
= title
;
191 $scope
.helpContent
= helpContent
= formatHelp(content
);
194 // Convert plain-text help to markdown; replace variables and format links
195 function formatHelp(rawContent
) {
196 function formatRefs(see
) {
197 _
.each(see
, function(ref
, idx
) {
198 var match
= ref
.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
200 ref
= '#/explorer/' + match
[1];
202 if (ref
[0] === '\\') {
203 ref
= 'https://github.com/civicrm/civicrm-core/blob/master' + ref
.replace(/\\/i, '/') + '.php
';
205 see[idx] = '<a target
="' + (ref[0] === '#' ? '_self' : '_blank') + '" href
="' + ref + '">' + see[idx] + '</a
>';
208 var formatted = _.cloneDeep(rawContent);
209 if (formatted.description) {
210 formatted.description = marked(formatted.description);
212 if (formatted.comment) {
213 formatted.comment = marked(formatted.comment);
215 formatRefs(formatted.see);
219 $scope.fieldHelp = function(fieldName) {
220 var field = getField(fieldName, $scope.entity, $scope.action);
225 description: field.description,
226 type: field.data_type
228 if (field.default_value) {
229 info.default = field.default_value;
231 if (field.required_if) {
232 info.required_if = field.required_if;
233 } else if (field.required) {
234 info.required = 'true';
239 // Returns field list for write params (values, defaults)
240 $scope.fieldList = function(param) {
243 getFieldList(fields, $scope.action === 'getFields
' ? ($scope.params.action || 'get') : $scope.action, ['name
']);
244 // Disable fields that are already in use
245 _.each($scope.params[param] || [], function(val) {
246 var usedField = val[0].replace(':name
', '');
247 (_.findWhere(fields, {id: usedField}) || {}).disabled = true;
248 (_.findWhere(fields, {id: usedField + ':name
'}) || {}).disabled = true;
250 return {results: fields};
254 $scope.formatSelect2Item = function(row) {
255 return _.escape(row.text) +
256 (row.required ? '<span
class="crm-marker"> *</span
>' : '') +
257 (row.description ? '<div
class="crm-select2-row-description"><p
>' + _.escape(row.description) + '</p></div>' : '');
260 $scope.clearParam = function(name, idx) {
261 if (typeof idx === 'undefined') {
262 $scope.params[name] = $scope.availableParams[name].default;
264 $scope.params[name].splice(idx, 1);
268 // Gets params that should be represented as generic input fields in the explorer
269 // This fn doesn't have to be particularly efficient as its output is cached
in one
-time bindings
270 $scope
.getGenericParams = function(paramType
, defaultNull
) {
271 // Returns undefined if params are not yet set; one-time bindings will stabilize when this function returns a value
272 if (_
.isEmpty($scope
.availableParams
)) {
275 var specialParams
= ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having', 'join'];
276 if ($scope
.availableParams
.limit
&& $scope
.availableParams
.offset
) {
277 specialParams
.push('limit', 'offset');
279 return _
.transform($scope
.availableParams
, function(genericParams
, param
, name
) {
280 if (!_
.contains(specialParams
, name
) &&
281 !(typeof paramType
!== 'undefined' && !_
.contains(paramType
, param
.type
[0])) &&
282 !(typeof defaultNull
!== 'undefined' && ((param
.default === null) !== defaultNull
))
284 genericParams
[name
] = param
;
289 $scope
.selectRowCount = function() {
290 if ($scope
.isSelectRowCount()) {
291 $scope
.params
.select
= [];
293 $scope
.params
.select
= ['row_count'];
295 if ($scope
.params
.limit
== 25) {
296 $scope
.params
.limit
= 0;
301 $scope
.isSelectRowCount = function() {
302 return isSelectRowCount($scope
.params
);
305 $scope
.selectLang = function(lang
) {
306 $scope
.selectedTab
.code
= lang
;
310 function isSelectRowCount(params
) {
311 return params
&& params
.select
&& params
.select
.length
=== 1 && params
.select
[0] === 'row_count';
314 function getEntity(entityName
) {
315 return _
.findWhere(schema
, {name
: entityName
|| $scope
.entity
});
318 // Get all params that have been set
319 function getParams() {
321 _
.each($scope
.params
, function(param
, key
) {
322 if (param
!= $scope
.availableParams
[key
].default && !(typeof param
=== 'object' && _
.isEmpty(param
))) {
323 if (_
.contains($scope
.availableParams
[key
].type
, 'array') && (typeof objectParams
[key
] === 'undefined')) {
324 params
[key
] = parseYaml(JSON
.parse(angular
.toJson(param
)));
330 _
.each(objectParams
, function(defaultVal
, key
) {
333 _
.each(params
[key
], function(item
) {
334 var val
= _
.cloneDeep(item
[1]);
335 // Remove blank items from "chain" array
336 if (_
.isArray(val
)) {
337 _
.eachRight(item
[1], function(v
, k
) {
344 newParam
[item
[0]] = parseYaml(val
);
346 params
[key
] = newParam
;
352 function parseYaml(input
) {
353 if (typeof input
=== 'undefined' || input
=== '') {
356 // Return literal quoted string without removing quotes - for the sake of JOIN ON clauses
357 if (_
.isString(input
) && input
[0] === input
[input
.length
- 1] && _
.includes(["'", '"'], input
[0])) {
360 if (_
.isObject(input
) || _
.isArray(input
)) {
361 _
.each(input
, function(item
, index
) {
362 input
[index
] = parseYaml(item
);
367 var output
= (input
=== '>') ? '>' : jsyaml
.safeLoad(input
);
368 // We don't want dates parsed to js objects
369 return _
.isDate(output
) ? input
: output
;
375 this.buildFieldList = function() {
376 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
377 getFieldList($scope
.fields
, $scope
.action
);
378 getFieldList($scope
.fieldsAndJoins
, $scope
.action
, ['name']);
379 getFieldList($scope
.fieldsAndJoinsAndFunctions
, $scope
.action
);
380 getFieldList($scope
.fieldsAndJoinsAndFunctionsWithSuffixes
, $scope
.action
, ['name', 'label']);
381 getFieldList($scope
.fieldsAndJoinsAndFunctionsAndWildcards
, $scope
.action
, ['name', 'label']);
382 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
383 addJoins($scope
.fieldsAndJoins
);
384 // SQL functions are supported if HAVING is
385 if (actionInfo
.params
.having
) {
387 text
: ts('FUNCTION'),
388 description
: ts('Calculate result of a SQL function'),
389 children
: _
.transform(CRM
.vars
.api4
.functions
, function(result
, fn
) {
391 id
: fn
.name
+ '() AS ' + fn
.name
.toLowerCase(),
392 text
: fn
.name
+ '()',
393 description
: fn
.name
+ '(' + describeSqlFn(fn
.params
) + ')'
397 $scope
.fieldsAndJoinsAndFunctions
.push(functions
);
398 $scope
.fieldsAndJoinsAndFunctionsWithSuffixes
.push(functions
);
399 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.push(functions
);
401 addJoins($scope
.fieldsAndJoinsAndFunctions
, true);
402 addJoins($scope
.fieldsAndJoinsAndFunctionsWithSuffixes
, false, ['name', 'label']);
403 addJoins($scope
.fieldsAndJoinsAndFunctionsAndWildcards
, true, ['name', 'label']);
405 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
408 function selectAction() {
409 $scope
.action
= $routeParams
.api4action
;
410 if (!actions
.length
) {
411 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
414 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
415 _
.each(actionInfo
.params
, function (param
, name
) {
417 defaultVal
= _
.cloneDeep(param
.default);
419 switch (param
.type
[0]) {
422 format
= param
.type
[0];
433 if (name
=== 'limit') {
436 if (name
=== 'debug') {
439 if (name
=== 'values') {
440 defaultVal
= defaultValues(defaultVal
);
442 if (name
=== 'loadOptions' && $scope
.action
=== 'getFields') {
446 ['id', 'name', 'label'],
447 ['id', 'name', 'label', 'abbr', 'description', 'color', 'icon']
451 param
.type
= ['string'];
453 $scope
.$bindToRoute({
454 expr
: 'params["' + name
+ '"]',
458 deep
: format
=== 'json'
461 if (typeof objectParams
[name
] !== 'undefined' && name
!== 'orderBy') {
462 $scope
.$watch('params.' + name
, function (values
) {
463 // Remove empty values
464 _
.each(values
, function (clause
, index
) {
465 if (!clause
|| !clause
[0]) {
466 $scope
.clearParam(name
, index
);
471 if (name
=== 'select' && actionInfo
.params
.having
) {
472 $scope
.$watchCollection('params.select', function(values
) {
473 $scope
.havingOptions
.length
= 0;
474 _
.each(values
, function(item
) {
475 var pieces
= item
.split(' AS '),
476 alias
= _
.trim(pieces
[pieces
.length
- 1]).replace(':label', ':name');
477 $scope
.havingOptions
.push({id
: alias
, text
: alias
});
481 if (typeof objectParams
[name
] !== 'undefined' || name
=== 'groupBy' || name
=== 'select' || name
=== 'join') {
482 $scope
.$watch('controls.' + name
, function(value
) {
484 $timeout(function() {
486 if (name
=== 'join') {
487 $scope
.params
[name
].push([field
+ ' AS ' + _
.snakeCase(field
), false]);
488 ctrl
.buildFieldList();
490 else if (typeof objectParams
[name
] === 'undefined') {
491 $scope
.params
[name
].push(field
);
493 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
494 if (name
=== 'chain') {
495 var num
= $scope
.params
.chain
.length
;
496 defaultOp
[0] = field
;
497 field
= 'name_me_' + num
;
499 $scope
.params
[name
].push([field
, defaultOp
]);
501 $scope
.controls
[name
] = null;
507 ctrl
.buildFieldList();
508 $scope
.availableParams
= actionInfo
.params
;
513 function describeSqlFn(params
) {
515 _
.each(params
, function(param
) {
518 desc
+= _
.filter(param
.prefix
).join('|') + ' ';
520 if (param
.expr
=== 1) {
522 } else if (param
.expr
> 1) {
523 desc
+= 'expr, ... ';
526 desc
+= ' ' + _
.filter(param
.suffix
).join('|') + ' ';
529 return desc
.replace(/[ ]+/g, ' ');
532 function defaultValues(defaultVal
) {
533 _
.each($scope
.fields
, function(field
) {
534 if (field
.required
) {
535 defaultVal
.push([field
.id
, '']);
541 function stringify(value
, trim
) {
542 if (typeof value
=== 'undefined') {
545 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
547 str
= str
.slice(1, -1);
552 function writeCode() {
554 entity
= $scope
.entity
,
555 action
= $scope
.action
,
556 params
= getParams(),
557 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
559 if ($scope
.entity
&& $scope
.action
) {
561 if (action
.slice(0, 3) === 'get') {
562 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
563 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
565 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
566 paramCount
= _
.size(params
),
569 if (isSelectRowCount(params
)) {
570 results
= result
+ 'Count';
573 switch ($scope
.selectedTab
.code
) {
577 var js
= "'" + entity
+ "', '" + action
+ "', {";
578 _
.each(params
, function(param
, key
) {
579 js
+= "\n " + key
+ ': ' + stringify(param
) +
580 (++i
< paramCount
? ',' : '');
581 if (key
=== 'checkPermissions') {
582 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
586 if (index
|| index
=== 0) {
587 js
+= ', ' + JSON
.stringify(index
);
589 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
590 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
591 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
592 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
597 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
598 _
.each(params
, function(param
, key
) {
599 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
602 if (index
|| index
=== 0) {
603 code
.php
+= ', ' + phpFormat(index
);
608 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
609 if (isSelectRowCount(params
)) {
610 code
.oop
+= "\n ->count()";
611 } else if (_
.isNumber(index
)) {
612 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
614 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
615 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
617 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
618 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
622 if (!_
.isNumber(index
) && !isSelectRowCount(params
)) {
623 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
629 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
632 _
.each($scope
.code
, function(vals
) {
633 _
.each(vals
, function(style
) {
634 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
640 function formatOOP(entity
, action
, params
, indent
) {
642 newLine
= "\n" + _
.repeat(' ', indent
);
643 if (entity
.substr(0, 7) !== 'Custom_') {
644 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
646 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
648 _
.each(params
, function(param
, key
) {
650 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
651 _
.each(param
, function(item
, index
) {
652 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
653 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
655 } else if (key
=== 'where') {
656 _
.each(param
, function (clause
) {
657 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
658 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
660 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
663 } else if (key
=== 'select') {
665 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
666 code
+= isSelectRowCount(params
) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
667 } else if (key
=== 'chain') {
668 _
.each(param
, function(chain
, name
) {
669 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
670 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
674 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
680 function isInt(value
) {
681 if (_
.isFinite(value
)) {
684 if (!_
.isString(value
)) {
687 return /^-{0,1}\d+$/.test(value
);
690 function formatMeta(resp
) {
692 _
.each(resp
, function(val
, key
) {
693 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
694 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
697 return prettyPrintOne(_
.escape(ret
));
700 $scope
.execute = function() {
701 $scope
.status
= 'info';
702 $scope
.loading
= true;
703 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
704 params
: angular
.toJson(getParams()),
705 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
708 'X-Requested-With': 'XMLHttpRequest'
710 }).then(function(resp
) {
711 $scope
.loading
= false;
712 $scope
.status
= resp
.data
&& resp
.data
.debug
&& resp
.data
.debug
.log
? 'warning' : 'success';
713 $scope
.debug
= debugFormat(resp
.data
);
714 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
716 $scope
.loading
= false;
717 $scope
.status
= 'danger';
718 $scope
.debug
= debugFormat(resp
.data
);
719 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
723 function debugFormat(data
) {
724 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
730 * Format value to look like php code
732 function phpFormat(val
, indent
) {
733 if (typeof val
=== 'undefined') {
736 if (val
=== null || val
=== true || val
=== false) {
737 return JSON
.stringify(val
).toUpperCase();
739 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
741 baseLine
= indent
? indent
.slice(0, -2) : '',
742 newLine
= indent
? '\n' : '',
743 trailingComma
= indent
? ',' : '';
744 if ($.isPlainObject(val
)) {
745 $.each(val
, function(k
, v
) {
746 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
748 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
750 if ($.isArray(val
)) {
751 $.each(val
, function(k
, v
) {
752 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
754 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
756 if (_
.isString(val
) && !_
.contains(val
, "'")) {
757 return "'" + val
+ "'";
759 return JSON
.stringify(val
).replace(/\$/g, '\\$');
762 function fetchMeta() {
763 crmApi4(getMetaParams
)
764 .then(function(data
) {
766 getEntity().actions
= data
.actions
;
772 // Help for an entity with no action selected
773 function showEntityHelp(entityName
) {
774 var entityInfo
= getEntity(entityName
);
775 setHelp($scope
.entity
, {
776 description
: entityInfo
.description
,
777 comment
: entityInfo
.comment
,
782 if (!$scope
.entity
) {
783 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
784 } else if (!actions
.length
&& !getEntity().actions
) {
785 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
792 showEntityHelp($scope
.entity
);
795 // Update route when changing entity
796 $scope
.$watch('entity', function(newVal
, oldVal
) {
797 if (oldVal
!== newVal
) {
798 // Flush actions cache to re-fetch for new entity
800 $location
.url('/explorer/' + newVal
);
804 // Update route when changing actions
805 $scope
.$watch('action', function(newVal
, oldVal
) {
806 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
807 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
809 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
813 $scope
.paramDoc = function(name
) {
814 return docs
.params
[name
];
817 $scope
.executeDoc = function() {
819 description
: ts('Runs API call on the CiviCRM database.'),
820 comment
: ts('Results and debugging info will be displayed below.')
822 if ($scope
.action
=== 'delete') {
823 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
825 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
826 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
831 $scope
.saveDoc = function() {
833 description
: ts('Save API call as a smart group.'),
834 comment
: ts('Create a SavedSearch using these API params to populate a smart group.') +
835 '\n\n' + ts('NOTE: you must select contact id as the only field.')
839 $scope
.$watch('params', writeCode
, true);
840 $scope
.$watch('index', writeCode
);
843 $scope
.save = function() {
844 $scope
.params
.limit
= $scope
.params
.offset
= 0;
845 if ($scope
.params
.chain
.length
) {
846 CRM
.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires
: 5000});
849 if ($scope
.params
.select
.length
!== 1 || !_
.includes($scope
.params
.select
[0], 'id')) {
850 CRM
.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires
: 5000});
856 visibility
: 'User and User Admin Only',
859 entity
: $scope
.entity
,
860 params
: JSON
.parse(angular
.toJson($scope
.params
))
862 model
.params
.version
= 4;
863 delete model
.params
.chain
;
864 delete model
.params
.debug
;
865 delete model
.params
.limit
;
866 delete model
.params
.offset
;
867 delete model
.params
.orderBy
;
868 delete model
.params
.checkPermissions
;
869 var options
= CRM
.utils
.adjustDialogDefaults({
872 title
: ts('Save smart group')
874 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
878 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
879 var ts
= $scope
.ts
= CRM
.ts(),
880 model
= $scope
.model
;
881 $scope
.groupEntityRefParams
= {
884 params
: {is_hidden
: 0, is_active
: 1, 'saved_search_id.api_entity': model
.entity
},
885 extra
: ['saved_search_id', 'description', 'visibility', 'group_type']
889 minimumInputLength
: 0,
890 placeholder
: ts('Select existing group')
893 if (!CRM
.checkPerm('administer reserved groups')) {
894 $scope
.groupEntityRefParams
.api
.params
.is_reserved
= 0;
897 administerReservedGroups
: CRM
.checkPerm('administer reserved groups')
899 $scope
.options
= CRM
.vars
.api4
.groupOptions
;
900 $scope
.$watch('model.id', function(id
) {
902 _
.assign(model
, $('#api-save-search-select-group').select2('data').extra
);
905 $scope
.cancel = function() {
906 dialogService
.cancel('saveSearchDialog');
908 $scope
.save = function() {
909 $('.ui-dialog:visible').block();
910 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
911 group
.description
= model
.description
;
912 group
.visibility
= model
.visibility
;
913 group
.group_type
= model
.group_type
;
914 group
.saved_search_id
= '$id';
916 api_entity
: model
.entity
,
917 api_params
: model
.params
920 savedSearch
.id
= model
.saved_search_id
;
922 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
923 .then(function(result
) {
924 dialogService
.close('saveSearchDialog', result
[0]);
929 angular
.module('api4Explorer').directive('crmApi4Clause', function() {
932 data
: '<crmApi4Clause'
934 templateUrl
: '~/api4Explorer/Clause.html',
935 controller: function ($scope
, $element
, $timeout
) {
936 var ts
= $scope
.ts
= CRM
.ts(),
937 ctrl
= $scope
.$ctrl
= this;
938 this.conjunctions
= {AND
: ts('And'), OR
: ts('Or'), NOT
: ts('Not')};
939 this.operators
= CRM
.vars
.api4
.operators
;
942 connectWith
: '.api4-clause-group-sortable',
943 containment
: $element
.closest('.api4-clause-fieldset'),
949 this.addGroup = function(op
) {
950 $scope
.data
.clauses
.push([op
, []]);
953 this.removeGroup = function() {
954 $scope
.data
.groupParent
.splice($scope
.data
.groupIndex
, 1);
957 function onSort(event
, ui
) {
958 $($element
).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
959 $('.api4-input.form-inline').css('margin-left', '');
962 // Indent clause while dragging between nested groups
963 function onSortOver(event
, ui
) {
966 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
968 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
971 this.addClause = function() {
972 $timeout(function() {
973 if (ctrl
.newClause
) {
974 $scope
.data
.clauses
.push([ctrl
.newClause
, '=', '']);
975 ctrl
.newClause
= null;
979 $scope
.$watch('data.clauses', function(values
) {
980 // Iterate in reverse order so index doesn't get out-of-sync during splice
981 _
.forEachRight(values
, function(clause
, index
) {
982 // Remove empty values
983 if (index
>= ($scope
.data
.skip
|| 0)) {
984 if (typeof clause
!== 'undefined' && !clause
[0]) {
985 values
.splice(index
, 1);
987 // Add/remove value if operator allows for one
988 else if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
990 } else if (typeof clause
[1] === 'string' && clause
.length
=== 2) {
1000 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
1003 data
: '=api4ExpValue'
1006 link: function (scope
, element
, attrs
, ctrl
) {
1007 var ts
= scope
.ts
= CRM
.ts(),
1008 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
1009 entity
= $routeParams
.api4entity
,
1010 action
= scope
.data
.action
|| $routeParams
.api4action
;
1012 function destroyWidget() {
1013 var $el
= $(element
);
1014 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
1015 $el
.crmDatepicker('destroy');
1017 if ($el
.is('.select2-container + input')) {
1018 $el
.crmEntityRef('destroy');
1020 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
1023 function makeWidget(field
, op
) {
1024 var $el
= $(element
),
1025 inputType
= field
.input_type
,
1026 dataType
= field
.data_type
;
1028 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
1030 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
1031 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
1035 if (inputType
=== 'Date') {
1036 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
1037 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
1039 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
1040 if (field
.options
) {
1041 var id
= field
.pseudoconstant
|| 'id';
1042 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
1043 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
1044 var options
= _
.transform(data
[field
.name
].options
, function(options
, opt
) {
1045 options
.push({id
: opt
[id
], text
: opt
.label
, description
: opt
.description
, color
: opt
.color
, icon
: opt
.icon
});
1047 $el
.removeClass('loading').crmSelect2({data
: options
, multiple
: multi
});
1049 } else if (field
.fk_entity
) {
1050 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
1051 } else if (dataType
=== 'Boolean') {
1052 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
1053 {id
: 'true', text
: ts('Yes')},
1054 {id
: 'false', text
: ts('No')}
1057 } else if (dataType
=== 'Integer' && !multi
) {
1058 $el
.attr('type', 'number');
1062 function loadFieldOptions(entity
) {
1063 if (!fieldOptions
[entity
+ action
]) {
1064 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
1065 loadOptions
: ['id', 'name', 'label', 'description', 'color', 'icon'],
1067 where
: [['options', '!=', false]],
1071 return fieldOptions
[entity
+ action
];
1074 // Copied from ng-list but applied conditionally if field is multi-valued
1075 var parseList = function(viewValue
) {
1076 // If the viewValue is invalid (say required but empty) it will be `undefined`
1077 if (_
.isUndefined(viewValue
)) return;
1086 _
.each(viewValue
.split(','), function(value
) {
1087 if (value
) list
.push(_
.trim(value
));
1094 // Copied from ng-list
1095 ctrl
.$parsers
.push(parseList
);
1096 ctrl
.$formatters
.push(function(value
) {
1097 return _
.isArray(value
) ? value
.join(', ') : value
;
1100 // Copied from ng-list
1101 ctrl
.$isEmpty = function(value
) {
1102 return !value
|| !value
.length
;
1105 scope
.$watchCollection('data', function(data
) {
1107 var field
= getField(data
.field
, entity
, action
);
1108 if (field
&& data
.format
!== 'plain') {
1109 makeWidget(field
, data
.op
);
1117 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
1120 chain
: '=api4ExpChain',
1124 templateUrl
: '~/api4Explorer/Chain.html',
1125 link: function (scope
, element
, attrs
) {
1126 var ts
= scope
.ts
= CRM
.ts();
1128 function changeEntity(newEntity
, oldEntity
) {
1129 // When clearing entity remove this chain
1131 scope
.chain
[0] = '';
1134 // Reset action && index
1135 if (newEntity
!== oldEntity
) {
1136 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
1138 if (getEntity(newEntity
).actions
) {
1141 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
1142 .then(function(data
) {
1143 getEntity(data
.entity
).actions
= data
;
1144 if (data
.entity
=== scope
.chain
[1][0]) {
1151 function setActions() {
1152 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
1155 // Set default params when choosing action
1156 function changeAction(newAction
, oldAction
) {
1158 // Prepopulate links
1159 if (newAction
&& newAction
!== oldAction
) {
1161 scope
.chain
[1][3] = '';
1162 // Look for links back to main entity
1163 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
1164 if (field
.fk_entity
=== scope
.mainEntity
) {
1165 link
= [field
.name
, '$id'];
1168 // Look for links from main entity
1169 if (!link
&& newAction
!== 'create') {
1170 _
.each(entityFields(scope
.mainEntity
), function(field
) {
1171 if (field
.fk_entity
=== scope
.chain
[1][0]) {
1172 link
= ['id', '$' + field
.name
];
1173 // Since we're specifying the id, set index to getsingle
1174 scope
.chain
[1][3] = '0';
1178 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1179 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1181 else if (link
&& _
.contains(['create'], newAction
)) {
1182 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1184 else if (link
&& _
.contains(['save'], newAction
)) {
1185 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1187 scope
.chain
[1][2] = '{}';
1192 scope
.$watch("chain[1][0]", changeEntity
);
1193 scope
.$watch("chain[1][1]", changeAction
);
1198 function getEntity(entityName
) {
1199 return _
.findWhere(schema
, {name
: entityName
});
1202 function entityFields(entityName
, action
) {
1203 var entity
= getEntity(entityName
);
1204 if (entity
&& action
&& entity
.actions
) {
1205 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1207 return _
.result(entity
, 'fields');
1210 function getExplicitJoins() {
1211 return _
.transform(params
.join
, function(joins
, join
) {
1212 var j
= join
[0].split(' AS '),
1213 joinEntity
= _
.trim(j
[0]),
1214 joinAlias
= _
.trim(j
[1]) || joinEntity
.toLowerCase();
1215 joins
[joinAlias
] = joinEntity
;
1219 function getField(fieldName
, entity
, action
) {
1220 var suffix
= fieldName
.split(':')[1];
1221 fieldName
= fieldName
.split(':')[0];
1222 var fieldNames
= fieldName
.split('.');
1223 var field
= get(entity
, fieldNames
);
1224 if (field
&& suffix
) {
1225 field
.pseudoconstant
= suffix
;
1229 function get(entity
, fieldNames
) {
1230 if (fieldNames
.length
=== 1) {
1231 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1233 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1237 var linkName
= fieldNames
.shift(),
1238 newEntity
= getExplicitJoins()[linkName
] || _
.findWhere(links
[entity
], {alias
: linkName
}).entity
;
1239 return get(newEntity
, fieldNames
);
1243 // Collapsible optgroups for select2
1246 .on('select2-open', function(e
) {
1247 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1249 .off('.collapseOptionGroup')
1250 .addClass('collapsible-optgroups-enabled')
1251 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1252 $(this).parent().toggleClass('optgroup-expanded');
1256 .on('select2-close', function() {
1257 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1260 })(angular
, CRM
.$, CRM
._
);