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 function getFieldList(action
) {
117 fieldInfo
= _
.findWhere(getEntity().actions
, {name
: action
}).fields
;
118 formatForSelect2(fieldInfo
, fields
, 'name', ['description', 'required', 'default_value']);
122 function addJoins(fieldList
, addWildcard
) {
123 var fields
= _
.cloneDeep(fieldList
),
124 fks
= _
.findWhere(links
, {entity
: $scope
.entity
}) || {};
125 _
.each(fks
.links
, function(link
) {
126 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
127 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
131 description
: 'Join to ' + link
.entity
,
132 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
139 $scope
.help = function(title
, content
) {
141 $scope
.helpTitle
= helpTitle
;
142 $scope
.helpContent
= helpContent
;
144 $scope
.helpTitle
= title
;
145 $scope
.helpContent
= formatHelp(content
);
149 // Sets the static help text (which gets overridden by mousing over other elements)
150 function setHelp(title
, content
) {
151 $scope
.helpTitle
= helpTitle
= title
;
152 $scope
.helpContent
= helpContent
= formatHelp(content
);
155 // Convert plain-text help to markdown; replace variables and format links
156 function formatHelp(rawContent
) {
157 function formatRefs(see
) {
158 _
.each(see
, function(ref
, idx
) {
159 var match
= ref
.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
161 ref
= '#/explorer/' + match
[1];
163 if (ref
[0] === '\\') {
164 ref
= 'https://github.com/civicrm/civicrm-core/blob/master' + ref
.replace(/\\/i, '/') + '.php
';
166 see[idx] = '<a target
="' + (ref[0] === '#' ? '_self' : '_blank') + '" href
="' + ref + '">' + see[idx] + '</a
>';
169 var formatted = _.cloneDeep(rawContent);
170 if (formatted.description) {
171 formatted.description = marked(formatted.description);
173 if (formatted.comment) {
174 formatted.comment = marked(formatted.comment);
176 formatRefs(formatted.see);
180 $scope.fieldHelp = function(fieldName) {
181 var field = getField(fieldName, $scope.entity, $scope.action);
186 description: field.description,
187 type: field.data_type
189 if (field.default_value) {
190 info.default = field.default_value;
192 if (field.required_if) {
193 info.required_if = field.required_if;
194 } else if (field.required) {
195 info.required = 'true';
200 $scope.fieldList = function(param) {
202 var fields = _.cloneDeep($scope.action === 'getFields
' ? getFieldList($scope.params.action || 'get') : $scope.fields);
203 // Disable fields that are already in use
204 _.each($scope.params[param] || [], function(val) {
205 (_.findWhere(fields, {id: val[0]}) || {}).disabled = true;
207 return {results: fields};
211 $scope.formatSelect2Item = function(row) {
212 return _.escape(row.text) +
213 (row.required ? '<span
class="crm-marker"> *</span
>' : '') +
214 (row.description ? '<div
class="crm-select2-row-description"><p
>' + _.escape(row.description) + '</p></div>' : '');
217 $scope.clearParam = function(name, idx) {
218 if (typeof idx === 'undefined') {
219 $scope.params[name] = $scope.availableParams[name].default;
221 $scope.params[name].splice(idx, 1);
225 // Gets params that should be represented as generic input fields in the explorer
226 // This fn doesn't have to be particularly efficient as its output is cached
in one
-time bindings
227 $scope
.getGenericParams = function(paramType
, defaultNull
) {
228 // Returns undefined if params are not yet set; one-time bindings will stabilize when this function returns a value
229 if (_
.isEmpty($scope
.availableParams
)) {
232 var specialParams
= ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having'];
233 if ($scope
.availableParams
.limit
&& $scope
.availableParams
.offset
) {
234 specialParams
.push('limit', 'offset');
236 return _
.transform($scope
.availableParams
, function(genericParams
, param
, name
) {
237 if (!_
.contains(specialParams
, name
) &&
238 !(typeof paramType
!== 'undefined' && !_
.contains(paramType
, param
.type
[0])) &&
239 !(typeof defaultNull
!== 'undefined' && ((param
.default === null) !== defaultNull
))
241 genericParams
[name
] = param
;
246 $scope
.selectRowCount = function() {
247 if ($scope
.isSelectRowCount()) {
248 $scope
.params
.select
= [];
250 $scope
.params
.select
= ['row_count'];
252 if ($scope
.params
.limit
== 25) {
253 $scope
.params
.limit
= 0;
258 $scope
.isSelectRowCount = function() {
259 return isSelectRowCount($scope
.params
);
262 $scope
.selectLang = function(lang
) {
263 $scope
.selectedTab
.code
= lang
;
267 function isSelectRowCount(params
) {
268 return params
&& params
.select
&& params
.select
.length
=== 1 && params
.select
[0] === 'row_count';
271 function getEntity(entityName
) {
272 return _
.findWhere(schema
, {name
: entityName
|| $scope
.entity
});
275 // Get all params that have been set
276 function getParams() {
278 _
.each($scope
.params
, function(param
, key
) {
279 if (param
!= $scope
.availableParams
[key
].default && !(typeof param
=== 'object' && _
.isEmpty(param
))) {
280 if (_
.contains($scope
.availableParams
[key
].type
, 'array') && (typeof objectParams
[key
] === 'undefined')) {
281 params
[key
] = parseYaml(JSON
.parse(angular
.toJson(param
)));
287 _
.each(objectParams
, function(defaultVal
, key
) {
290 _
.each(params
[key
], function(item
) {
291 var val
= _
.cloneDeep(item
[1]);
292 // Remove blank items from "chain" array
293 if (_
.isArray(val
)) {
294 _
.eachRight(item
[1], function(v
, k
) {
301 newParam
[item
[0]] = parseYaml(val
);
303 params
[key
] = newParam
;
309 function parseYaml(input
) {
310 if (typeof input
=== 'undefined') {
316 if (_
.isObject(input
) || _
.isArray(input
)) {
317 _
.each(input
, function(item
, index
) {
318 input
[index
] = parseYaml(item
);
323 var output
= (input
=== '>') ? '>' : jsyaml
.safeLoad(input
);
324 // We don't want dates parsed to js objects
325 return _
.isDate(output
) ? input
: output
;
331 function selectAction() {
332 $scope
.action
= $routeParams
.api4action
;
333 $scope
.fieldsAndJoins
.length
= 0;
334 $scope
.fieldsAndJoinsAndFunctions
.length
= 0;
335 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.length
= 0;
336 if (!actions
.length
) {
337 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
340 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
341 $scope
.fields
= getFieldList($scope
.action
);
342 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
343 $scope
.fieldsAndJoins
= addJoins($scope
.fields
);
344 var fieldsAndFunctions
= _
.cloneDeep($scope
.fields
);
345 // SQL functions are supported if HAVING is
346 if (actionInfo
.params
.having
) {
347 fieldsAndFunctions
.push({
348 text
: ts('FUNCTION'),
349 description
: ts('Calculate result of a SQL function'),
350 children
: _
.transform(CRM
.vars
.api4
.functions
, function(result
, fn
) {
352 id
: fn
.name
+ '() AS ' + fn
.name
.toLowerCase(),
353 text
: fn
.name
+ '()',
354 description
: fn
.name
+ '(' + describeSqlFn(fn
.params
) + ')'
359 $scope
.fieldsAndJoinsAndFunctions
= addJoins(fieldsAndFunctions
, true);
360 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= addJoins(fieldsAndFunctions
, true);
362 $scope
.fieldsAndJoins
= $scope
.fields
;
363 $scope
.fieldsAndJoinsAndFunctions
= $scope
.fields
;
364 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= _
.cloneDeep($scope
.fields
);
366 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
367 _
.each(actionInfo
.params
, function (param
, name
) {
369 defaultVal
= _
.cloneDeep(param
.default);
371 switch (param
.type
[0]) {
374 format
= param
.type
[0];
385 if (name
=== 'limit') {
388 if (name
=== 'debug') {
391 if (name
=== 'values') {
392 defaultVal
= defaultValues(defaultVal
);
394 $scope
.$bindToRoute({
395 expr
: 'params["' + name
+ '"]',
399 deep
: format
=== 'json'
402 if (typeof objectParams
[name
] !== 'undefined' && name
!== 'orderBy') {
403 $scope
.$watch('params.' + name
, function (values
) {
404 // Remove empty values
405 _
.each(values
, function (clause
, index
) {
406 if (!clause
|| !clause
[0]) {
407 $scope
.clearParam(name
, index
);
412 if (name
=== 'select' && actionInfo
.params
.having
) {
413 $scope
.$watchCollection('params.select', function(values
) {
414 $scope
.havingOptions
.length
= 0;
415 _
.each(values
, function(item
) {
416 var pieces
= item
.split(' AS '),
417 alias
= _
.trim(pieces
[pieces
.length
- 1]);
418 $scope
.havingOptions
.push({id
: alias
, text
: alias
});
422 if (typeof objectParams
[name
] !== 'undefined' || name
=== 'groupBy' || name
=== 'select') {
423 $scope
.$watch('controls.' + name
, function(value
) {
425 $timeout(function() {
427 if (typeof objectParams
[name
] === 'undefined') {
428 $scope
.params
[name
].push(field
);
430 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
431 if (name
=== 'chain') {
432 var num
= $scope
.params
.chain
.length
;
433 defaultOp
[0] = field
;
434 field
= 'name_me_' + num
;
436 $scope
.params
[name
].push([field
, defaultOp
]);
438 $scope
.controls
[name
] = null;
444 $scope
.availableParams
= actionInfo
.params
;
449 function describeSqlFn(params
) {
451 _
.each(params
, function(param
) {
454 desc
+= _
.filter(param
.prefix
).join('|') + ' ';
456 if (param
.expr
=== 1) {
458 } else if (param
.expr
> 1) {
459 desc
+= 'expr, ... ';
462 desc
+= ' ' + _
.filter(param
.suffix
).join('|') + ' ';
465 return desc
.replace(/[ ]+/g, ' ');
468 function defaultValues(defaultVal
) {
469 _
.each($scope
.fields
, function(field
) {
470 if (field
.required
) {
471 defaultVal
.push([field
.id
, '']);
477 function stringify(value
, trim
) {
478 if (typeof value
=== 'undefined') {
481 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
483 str
= str
.slice(1, -1);
488 function writeCode() {
490 entity
= $scope
.entity
,
491 action
= $scope
.action
,
492 params
= getParams(),
493 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
495 if ($scope
.entity
&& $scope
.action
) {
497 if (action
.slice(0, 3) === 'get') {
498 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
499 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
501 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
502 paramCount
= _
.size(params
),
505 if (isSelectRowCount(params
)) {
506 results
= result
+ 'Count';
509 switch ($scope
.selectedTab
.code
) {
513 var js
= "'" + entity
+ "', '" + action
+ "', {";
514 _
.each(params
, function(param
, key
) {
515 js
+= "\n " + key
+ ': ' + stringify(param
) +
516 (++i
< paramCount
? ',' : '');
517 if (key
=== 'checkPermissions') {
518 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
522 if (index
|| index
=== 0) {
523 js
+= ', ' + JSON
.stringify(index
);
525 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
526 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
527 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
528 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
533 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
534 _
.each(params
, function(param
, key
) {
535 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
538 if (index
|| index
=== 0) {
539 code
.php
+= ', ' + phpFormat(index
);
544 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
545 if (isSelectRowCount(params
)) {
546 code
.oop
+= "\n ->count()";
547 } else if (_
.isNumber(index
)) {
548 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
550 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
551 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
553 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
554 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
558 if (!_
.isNumber(index
) && !isSelectRowCount(params
)) {
559 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
565 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
568 _
.each($scope
.code
, function(vals
) {
569 _
.each(vals
, function(style
) {
570 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
576 function formatOOP(entity
, action
, params
, indent
) {
578 newLine
= "\n" + _
.repeat(' ', indent
);
579 if (entity
.substr(0, 7) !== 'Custom_') {
580 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
582 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
584 _
.each(params
, function(param
, key
) {
586 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
587 _
.each(param
, function(item
, index
) {
588 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
589 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
591 } else if (key
=== 'where') {
592 _
.each(param
, function (clause
) {
593 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
594 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
596 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
599 } else if (key
=== 'select') {
601 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
602 code
+= isSelectRowCount(params
) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
603 } else if (key
=== 'chain') {
604 _
.each(param
, function(chain
, name
) {
605 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
606 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
610 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
616 function isInt(value
) {
617 if (_
.isFinite(value
)) {
620 if (!_
.isString(value
)) {
623 return /^-{0,1}\d+$/.test(value
);
626 function formatMeta(resp
) {
628 _
.each(resp
, function(val
, key
) {
629 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
630 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
633 return prettyPrintOne(_
.escape(ret
));
636 $scope
.execute = function() {
637 $scope
.status
= 'warning';
638 $scope
.loading
= true;
639 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
640 params
: angular
.toJson(getParams()),
641 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
644 'X-Requested-With': 'XMLHttpRequest'
646 }).then(function(resp
) {
647 $scope
.loading
= false;
648 $scope
.status
= 'success';
649 $scope
.debug
= debugFormat(resp
.data
);
650 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
652 $scope
.loading
= false;
653 $scope
.status
= 'danger';
654 $scope
.debug
= debugFormat(resp
.data
);
655 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
659 function debugFormat(data
) {
660 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
666 * Format value to look like php code
668 function phpFormat(val
, indent
) {
669 if (typeof val
=== 'undefined') {
672 if (val
=== null || val
=== true || val
=== false) {
673 return JSON
.stringify(val
).toUpperCase();
675 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
677 baseLine
= indent
? indent
.slice(0, -2) : '',
678 newLine
= indent
? '\n' : '',
679 trailingComma
= indent
? ',' : '';
680 if ($.isPlainObject(val
)) {
681 $.each(val
, function(k
, v
) {
682 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
684 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
686 if ($.isArray(val
)) {
687 $.each(val
, function(k
, v
) {
688 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
690 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
692 if (_
.isString(val
) && !_
.contains(val
, "'")) {
693 return "'" + val
+ "'";
695 return JSON
.stringify(val
).replace(/\$/g, '\\$');
698 function fetchMeta() {
699 crmApi4(getMetaParams
)
700 .then(function(data
) {
702 getEntity().actions
= data
.actions
;
708 // Help for an entity with no action selected
709 function showEntityHelp(entityName
) {
710 var entityInfo
= getEntity(entityName
);
711 setHelp($scope
.entity
, {
712 description
: entityInfo
.description
,
713 comment
: entityInfo
.comment
,
718 if (!$scope
.entity
) {
719 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
720 } else if (!actions
.length
&& !getEntity().actions
) {
721 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
728 showEntityHelp($scope
.entity
);
731 // Update route when changing entity
732 $scope
.$watch('entity', function(newVal
, oldVal
) {
733 if (oldVal
!== newVal
) {
734 // Flush actions cache to re-fetch for new entity
736 $location
.url('/explorer/' + newVal
);
740 // Update route when changing actions
741 $scope
.$watch('action', function(newVal
, oldVal
) {
742 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
743 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
745 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
749 $scope
.paramDoc = function(name
) {
750 return docs
.params
[name
];
753 $scope
.executeDoc = function() {
755 description
: ts('Runs API call on the CiviCRM database.'),
756 comment
: ts('Results and debugging info will be displayed below.')
758 if ($scope
.action
=== 'delete') {
759 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
761 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
762 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
767 $scope
.saveDoc = function() {
769 description
: ts('Save API call as a smart group.'),
770 comment
: ts('Create a SavedSearch using these API params to populate a smart group.') +
771 '\n\n' + ts('NOTE: you must select contact id as the only field.')
775 $scope
.$watch('params', writeCode
, true);
776 $scope
.$watch('index', writeCode
);
779 $scope
.save = function() {
780 $scope
.params
.limit
= $scope
.params
.offset
= 0;
781 if ($scope
.params
.chain
.length
) {
782 CRM
.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires
: 5000});
785 if ($scope
.params
.select
.length
!== 1 || !_
.includes($scope
.params
.select
[0], 'id')) {
786 CRM
.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires
: 5000});
792 visibility
: 'User and User Admin Only',
795 entity
: $scope
.entity
,
796 params
: JSON
.parse(angular
.toJson($scope
.params
))
798 model
.params
.version
= 4;
799 delete model
.params
.chain
;
800 delete model
.params
.debug
;
801 delete model
.params
.limit
;
802 delete model
.params
.offset
;
803 delete model
.params
.orderBy
;
804 delete model
.params
.checkPermissions
;
805 var options
= CRM
.utils
.adjustDialogDefaults({
808 title
: ts('Save smart group')
810 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
814 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
815 var ts
= $scope
.ts
= CRM
.ts(),
816 model
= $scope
.model
;
817 $scope
.groupEntityRefParams
= {
820 params
: {is_hidden
: 0, is_active
: 1, 'saved_search_id.api_entity': model
.entity
},
821 extra
: ['saved_search_id', 'description', 'visibility', 'group_type']
825 minimumInputLength
: 0,
826 placeholder
: ts('Select existing group')
829 if (!CRM
.checkPerm('administer reserved groups')) {
830 $scope
.groupEntityRefParams
.api
.params
.is_reserved
= 0;
833 administerReservedGroups
: CRM
.checkPerm('administer reserved groups')
835 $scope
.options
= CRM
.vars
.api4
.groupOptions
;
836 $scope
.$watch('model.id', function(id
) {
838 _
.assign(model
, $('#api-save-search-select-group').select2('data').extra
);
841 $scope
.cancel = function() {
842 dialogService
.cancel('saveSearchDialog');
844 $scope
.save = function() {
845 $('.ui-dialog:visible').block();
846 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
847 group
.description
= model
.description
;
848 group
.visibility
= model
.visibility
;
849 group
.group_type
= model
.group_type
;
850 group
.saved_search_id
= '$id';
852 api_entity
: model
.entity
,
853 api_params
: model
.params
856 savedSearch
.id
= model
.saved_search_id
;
858 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
859 .then(function(result
) {
860 dialogService
.close('saveSearchDialog', result
[0]);
865 angular
.module('api4Explorer').directive('crmApi4Clause', function($timeout
) {
868 data
: '=crmApi4Clause'
870 templateUrl
: '~/api4Explorer/Clause.html',
871 link: function (scope
, element
, attrs
) {
872 var ts
= scope
.ts
= CRM
.ts();
873 scope
.newClause
= '';
874 scope
.conjunctions
= ['AND', 'OR', 'NOT'];
875 scope
.operators
= CRM
.vars
.api4
.operators
;
877 scope
.addGroup = function(op
) {
878 scope
.data
.clauses
.push([op
, []]);
881 scope
.removeGroup = function() {
882 scope
.data
.groupParent
.splice(scope
.data
.groupIndex
, 1);
885 scope
.onSort = function(event
, ui
) {
886 $(element
).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
887 $('.api4-input.form-inline').css('margin-left', '');
890 // Indent clause while dragging between nested groups
891 scope
.onSortOver = function(event
, ui
) {
894 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
896 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
899 scope
.$watch('newClause', function(value
) {
901 $timeout(function() {
903 scope
.data
.clauses
.push([field
, '=', '']);
904 scope
.newClause
= null;
908 scope
.$watch('data.clauses', function(values
) {
909 // Remove empty values
910 _
.each(values
, function(clause
, index
) {
911 if (typeof clause
!== 'undefined' && !clause
[0]) {
912 values
.splice(index
, 1);
914 if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
916 } else if (typeof clause
[1] === 'string' && clause
.length
== 2) {
925 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
928 data
: '=api4ExpValue'
931 link: function (scope
, element
, attrs
, ctrl
) {
932 var ts
= scope
.ts
= CRM
.ts(),
933 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
934 entity
= $routeParams
.api4entity
,
935 action
= scope
.data
.action
|| $routeParams
.api4action
;
937 function destroyWidget() {
938 var $el
= $(element
);
939 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
940 $el
.crmDatepicker('destroy');
942 if ($el
.is('.select2-container + input')) {
943 $el
.crmEntityRef('destroy');
945 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
948 function makeWidget(field
, op
) {
949 var $el
= $(element
),
950 inputType
= field
.input_type
,
951 dataType
= field
.data_type
;
953 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
955 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
956 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
960 if (inputType
=== 'Date') {
961 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
962 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
964 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
965 if (field
.fk_entity
) {
966 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
967 } else if (field
.options
) {
968 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
969 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
971 _
.each(_
.findWhere(data
, {name
: field
.name
}).options
, function(val
, key
) {
972 options
.push({id
: key
, text
: val
});
974 $el
.removeClass('loading').select2({data
: options
, multiple
: multi
});
976 } else if (dataType
=== 'Boolean') {
977 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
978 {id
: 'true', text
: ts('Yes')},
979 {id
: 'false', text
: ts('No')}
982 } else if (dataType
=== 'Integer' && !multi
) {
983 $el
.attr('type', 'number');
987 function loadFieldOptions(entity
) {
988 if (!fieldOptions
[entity
+ action
]) {
989 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
992 where
: [["options", "!=", false]],
993 select
: ["name", "options"]
996 return fieldOptions
[entity
+ action
];
999 // Copied from ng-list but applied conditionally if field is multi-valued
1000 var parseList = function(viewValue
) {
1001 // If the viewValue is invalid (say required but empty) it will be `undefined`
1002 if (_
.isUndefined(viewValue
)) return;
1011 _
.each(viewValue
.split(','), function(value
) {
1012 if (value
) list
.push(_
.trim(value
));
1019 // Copied from ng-list
1020 ctrl
.$parsers
.push(parseList
);
1021 ctrl
.$formatters
.push(function(value
) {
1022 return _
.isArray(value
) ? value
.join(', ') : value
;
1025 // Copied from ng-list
1026 ctrl
.$isEmpty = function(value
) {
1027 return !value
|| !value
.length
;
1030 scope
.$watchCollection('data', function(data
) {
1032 var field
= getField(data
.field
, entity
, action
);
1034 makeWidget(field
, data
.op
);
1042 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
1045 chain
: '=api4ExpChain',
1049 templateUrl
: '~/api4Explorer/Chain.html',
1050 link: function (scope
, element
, attrs
) {
1051 var ts
= scope
.ts
= CRM
.ts();
1053 function changeEntity(newEntity
, oldEntity
) {
1054 // When clearing entity remove this chain
1056 scope
.chain
[0] = '';
1059 // Reset action && index
1060 if (newEntity
!== oldEntity
) {
1061 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
1063 if (getEntity(newEntity
).actions
) {
1066 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
1067 .then(function(data
) {
1068 getEntity(data
.entity
).actions
= data
;
1069 if (data
.entity
=== scope
.chain
[1][0]) {
1076 function setActions() {
1077 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
1080 // Set default params when choosing action
1081 function changeAction(newAction
, oldAction
) {
1083 // Prepopulate links
1084 if (newAction
&& newAction
!== oldAction
) {
1086 scope
.chain
[1][3] = '';
1087 // Look for links back to main entity
1088 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
1089 if (field
.fk_entity
=== scope
.mainEntity
) {
1090 link
= [field
.name
, '$id'];
1093 // Look for links from main entity
1094 if (!link
&& newAction
!== 'create') {
1095 _
.each(entityFields(scope
.mainEntity
), function(field
) {
1096 if (field
.fk_entity
=== scope
.chain
[1][0]) {
1097 link
= ['id', '$' + field
.name
];
1098 // Since we're specifying the id, set index to getsingle
1099 scope
.chain
[1][3] = '0';
1103 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1104 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1106 else if (link
&& _
.contains(['create'], newAction
)) {
1107 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1109 else if (link
&& _
.contains(['save'], newAction
)) {
1110 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1112 scope
.chain
[1][2] = '{}';
1117 scope
.$watch("chain[1][0]", changeEntity
);
1118 scope
.$watch("chain[1][1]", changeAction
);
1123 function getEntity(entityName
) {
1124 return _
.findWhere(schema
, {name
: entityName
});
1127 function entityFields(entityName
, action
) {
1128 var entity
= getEntity(entityName
);
1129 if (entity
&& action
&& entity
.actions
) {
1130 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1132 return _
.result(entity
, 'fields');
1135 function getField(fieldName
, entity
, action
) {
1136 var fieldNames
= fieldName
.split('.');
1137 return get(entity
, fieldNames
);
1139 function get(entity
, fieldNames
) {
1140 if (fieldNames
.length
=== 1) {
1141 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1143 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1147 var linkName
= fieldNames
.shift(),
1148 entityLinks
= _
.findWhere(links
, {entity
: entity
}).links
,
1149 newEntity
= _
.findWhere(entityLinks
, {alias
: linkName
}).entity
;
1150 return get(newEntity
, fieldNames
);
1154 // Collapsible optgroups for select2
1157 .on('select2-open', function(e
) {
1158 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1160 .off('.collapseOptionGroup')
1161 .addClass('collapsible-optgroups-enabled')
1162 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1163 $(this).parent().toggleClass('optgroup-expanded');
1167 .on('select2-close', function() {
1168 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1171 })(angular
, CRM
.$, CRM
._
);