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'];
55 $scope
.joinTypes
= [{k
: false, v
: ts('Optional')}, {k
: true, v
: ts('Required')}];
58 {name
: 'oop', label
: ts('OOP Style'), code
: ''},
59 {name
: 'php', label
: ts('Traditional'), code
: ''}
62 {name
: 'js', label
: ts('Single Call'), code
: ''},
63 {name
: 'js2', label
: ts('Batch Calls'), code
: ''}
66 {name
: 'ang', label
: ts('Single Call'), code
: ''},
67 {name
: 'ang2', label
: ts('Batch Calls'), code
: ''}
70 {name
: 'cv', label
: ts('CV'), code
: ''}
74 if (!entities
.length
) {
75 formatForSelect2(schema
, entities
, 'name', ['description']);
84 function ucfirst(str
) {
85 return str
[0].toUpperCase() + str
.slice(1);
88 function lcfirst(str
) {
89 return str
[0].toLowerCase() + str
.slice(1);
92 function pluralize(str
) {
93 switch (str
[str
.length
-1]) {
97 return str
.slice(0, -1) + 'ies';
103 // Reformat an existing array of objects for compatibility with select2
104 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
105 _
.each(input
, function(item
) {
106 var id
= (prefix
|| '') + item
[key
];
107 var formatted
= {id
: id
, text
: id
};
109 _
.merge(formatted
, _
.pick(item
, extra
));
111 container
.push(formatted
);
116 // Returns field list formatted for select2
117 function getFieldList(action
, addPseudoconstant
) {
119 fieldInfo
= _
.findWhere(getEntity().actions
, {name
: action
}).fields
;
120 if (addPseudoconstant
) {
121 fieldInfo
= _
.cloneDeep(fieldInfo
);
122 addPseudoconstants(fieldInfo
, addPseudoconstant
);
124 formatForSelect2(fieldInfo
, fields
, 'name', ['description', 'required', 'default_value']);
128 // Note: this function expects fieldList to be select2-formatted already
129 function addJoins(fieldList
, addWildcard
, addPseudoconstant
) {
130 var fields
= _
.cloneDeep(fieldList
);
131 _
.each(links
[$scope
.entity
], function(link
) {
132 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
133 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
135 if (addPseudoconstant
) {
136 addPseudoconstants(linkFields
, addPseudoconstant
);
140 description
: 'Implicit join to ' + link
.entity
,
141 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
148 // Note: this function transforms a raw list a-la getFields; not a select2-formatted list
149 function addPseudoconstants(fieldList
, toAdd
) {
150 var optionFields
= _
.filter(fieldList
, 'options');
151 _
.each(optionFields
, function(field
) {
152 var pos
= _
.findIndex(fieldList
, {name
: field
.name
}) + 1;
153 _
.each(toAdd
, function(suffix
) {
154 var newField
= _
.cloneDeep(field
);
155 newField
.name
+= ':' + suffix
;
156 fieldList
.splice(pos
, 0, newField
);
161 $scope
.help = function(title
, content
) {
163 $scope
.helpTitle
= helpTitle
;
164 $scope
.helpContent
= helpContent
;
166 $scope
.helpTitle
= title
;
167 $scope
.helpContent
= formatHelp(content
);
171 // Sets the static help text (which gets overridden by mousing over other elements)
172 function setHelp(title
, content
) {
173 $scope
.helpTitle
= helpTitle
= title
;
174 $scope
.helpContent
= helpContent
= formatHelp(content
);
177 // Convert plain-text help to markdown; replace variables and format links
178 function formatHelp(rawContent
) {
179 function formatRefs(see
) {
180 _
.each(see
, function(ref
, idx
) {
181 var match
= ref
.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
183 ref
= '#/explorer/' + match
[1];
185 if (ref
[0] === '\\') {
186 ref
= 'https://github.com/civicrm/civicrm-core/blob/master' + ref
.replace(/\\/i, '/') + '.php
';
188 see[idx] = '<a target
="' + (ref[0] === '#' ? '_self' : '_blank') + '" href
="' + ref + '">' + see[idx] + '</a
>';
191 var formatted = _.cloneDeep(rawContent);
192 if (formatted.description) {
193 formatted.description = marked(formatted.description);
195 if (formatted.comment) {
196 formatted.comment = marked(formatted.comment);
198 formatRefs(formatted.see);
202 $scope.fieldHelp = function(fieldName) {
203 var field = getField(fieldName, $scope.entity, $scope.action);
208 description: field.description,
209 type: field.data_type
211 if (field.default_value) {
212 info.default = field.default_value;
214 if (field.required_if) {
215 info.required_if = field.required_if;
216 } else if (field.required) {
217 info.required = 'true';
222 // Returns field list for write params (values, defaults)
223 $scope.fieldList = function(param) {
225 var fields = _.cloneDeep(getFieldList($scope.action === 'getFields
' ? ($scope.params.action || 'get') : $scope.action, ['name
']));
226 // Disable fields that are already in use
227 _.each($scope.params[param] || [], function(val) {
228 var usedField = val[0].replace(':name
', '');
229 (_.findWhere(fields, {id: usedField}) || {}).disabled = true;
230 (_.findWhere(fields, {id: usedField + ':name
'}) || {}).disabled = true;
232 return {results: fields};
236 $scope.formatSelect2Item = function(row) {
237 return _.escape(row.text) +
238 (row.required ? '<span
class="crm-marker"> *</span
>' : '') +
239 (row.description ? '<div
class="crm-select2-row-description"><p
>' + _.escape(row.description) + '</p></div>' : '');
242 $scope.clearParam = function(name, idx) {
243 if (typeof idx === 'undefined') {
244 $scope.params[name] = $scope.availableParams[name].default;
246 $scope.params[name].splice(idx, 1);
250 // Gets params that should be represented as generic input fields in the explorer
251 // This fn doesn't have to be particularly efficient as its output is cached
in one
-time bindings
252 $scope
.getGenericParams = function(paramType
, defaultNull
) {
253 // Returns undefined if params are not yet set; one-time bindings will stabilize when this function returns a value
254 if (_
.isEmpty($scope
.availableParams
)) {
257 var specialParams
= ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having', 'join'];
258 if ($scope
.availableParams
.limit
&& $scope
.availableParams
.offset
) {
259 specialParams
.push('limit', 'offset');
261 return _
.transform($scope
.availableParams
, function(genericParams
, param
, name
) {
262 if (!_
.contains(specialParams
, name
) &&
263 !(typeof paramType
!== 'undefined' && !_
.contains(paramType
, param
.type
[0])) &&
264 !(typeof defaultNull
!== 'undefined' && ((param
.default === null) !== defaultNull
))
266 genericParams
[name
] = param
;
271 $scope
.selectRowCount = function() {
272 if ($scope
.isSelectRowCount()) {
273 $scope
.params
.select
= [];
275 $scope
.params
.select
= ['row_count'];
277 if ($scope
.params
.limit
== 25) {
278 $scope
.params
.limit
= 0;
283 $scope
.isSelectRowCount = function() {
284 return isSelectRowCount($scope
.params
);
287 $scope
.selectLang = function(lang
) {
288 $scope
.selectedTab
.code
= lang
;
292 function isSelectRowCount(params
) {
293 return params
&& params
.select
&& params
.select
.length
=== 1 && params
.select
[0] === 'row_count';
296 function getEntity(entityName
) {
297 return _
.findWhere(schema
, {name
: entityName
|| $scope
.entity
});
300 // Get all params that have been set
301 function getParams() {
303 _
.each($scope
.params
, function(param
, key
) {
304 if (param
!= $scope
.availableParams
[key
].default && !(typeof param
=== 'object' && _
.isEmpty(param
))) {
305 if (_
.contains($scope
.availableParams
[key
].type
, 'array') && (typeof objectParams
[key
] === 'undefined')) {
306 params
[key
] = parseYaml(JSON
.parse(angular
.toJson(param
)));
312 _
.each(objectParams
, function(defaultVal
, key
) {
315 _
.each(params
[key
], function(item
) {
316 var val
= _
.cloneDeep(item
[1]);
317 // Remove blank items from "chain" array
318 if (_
.isArray(val
)) {
319 _
.eachRight(item
[1], function(v
, k
) {
326 newParam
[item
[0]] = parseYaml(val
);
328 params
[key
] = newParam
;
334 function parseYaml(input
) {
335 if (typeof input
=== 'undefined') {
341 if (_
.isObject(input
) || _
.isArray(input
)) {
342 _
.each(input
, function(item
, index
) {
343 input
[index
] = parseYaml(item
);
348 var output
= (input
=== '>') ? '>' : jsyaml
.safeLoad(input
);
349 // We don't want dates parsed to js objects
350 return _
.isDate(output
) ? input
: output
;
356 function selectAction() {
357 $scope
.action
= $routeParams
.api4action
;
358 $scope
.fieldsAndJoins
.length
= 0;
359 $scope
.fieldsAndJoinsAndFunctions
.length
= 0;
360 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.length
= 0;
361 if (!actions
.length
) {
362 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
365 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
366 $scope
.fields
= getFieldList($scope
.action
);
367 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
368 $scope
.fieldsAndJoins
= addJoins(getFieldList($scope
.action
, ['name']));
370 // SQL functions are supported if HAVING is
371 if (actionInfo
.params
.having
) {
373 text
: ts('FUNCTION'),
374 description
: ts('Calculate result of a SQL function'),
375 children
: _
.transform(CRM
.vars
.api4
.functions
, function(result
, fn
) {
377 id
: fn
.name
+ '() AS ' + fn
.name
.toLowerCase(),
378 text
: fn
.name
+ '()',
379 description
: fn
.name
+ '(' + describeSqlFn(fn
.params
) + ')'
384 $scope
.fieldsAndJoinsAndFunctions
= addJoins($scope
.fields
.concat(functions
), true);
385 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= addJoins(getFieldList($scope
.action
, ['name', 'label']).concat(functions
), true, ['name', 'label']);
387 $scope
.fieldsAndJoins
= getFieldList($scope
.action
, ['name']);
388 $scope
.fieldsAndJoinsAndFunctions
= $scope
.fields
;
389 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= getFieldList($scope
.action
, ['name', 'label']);
391 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
392 _
.each(actionInfo
.params
, function (param
, name
) {
394 defaultVal
= _
.cloneDeep(param
.default);
396 switch (param
.type
[0]) {
399 format
= param
.type
[0];
410 if (name
=== 'limit') {
413 if (name
=== 'debug') {
416 if (name
=== 'values') {
417 defaultVal
= defaultValues(defaultVal
);
419 if (name
=== 'loadOptions' && $scope
.action
=== 'getFields') {
423 ['id', 'name', 'label'],
424 ['id', 'name', 'label', 'abbr', 'description', 'color', 'icon']
428 param
.type
= ['string'];
430 $scope
.$bindToRoute({
431 expr
: 'params["' + name
+ '"]',
435 deep
: format
=== 'json'
438 if (typeof objectParams
[name
] !== 'undefined' && name
!== 'orderBy') {
439 $scope
.$watch('params.' + name
, function (values
) {
440 // Remove empty values
441 _
.each(values
, function (clause
, index
) {
442 if (!clause
|| !clause
[0]) {
443 $scope
.clearParam(name
, index
);
448 if (name
=== 'select' && actionInfo
.params
.having
) {
449 $scope
.$watchCollection('params.select', function(values
) {
450 $scope
.havingOptions
.length
= 0;
451 _
.each(values
, function(item
) {
452 var pieces
= item
.split(' AS '),
453 alias
= _
.trim(pieces
[pieces
.length
- 1]).replace(':label', ':name');
454 $scope
.havingOptions
.push({id
: alias
, text
: alias
});
458 if (typeof objectParams
[name
] !== 'undefined' || name
=== 'groupBy' || name
=== 'select' || name
=== 'join') {
459 $scope
.$watch('controls.' + name
, function(value
) {
461 $timeout(function() {
463 if (name
=== 'join') {
464 $scope
.params
[name
].push([field
+ ' AS ' + _
.snakeCase(field
), false, '[]']);
466 else if (typeof objectParams
[name
] === 'undefined') {
467 $scope
.params
[name
].push(field
);
469 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
470 if (name
=== 'chain') {
471 var num
= $scope
.params
.chain
.length
;
472 defaultOp
[0] = field
;
473 field
= 'name_me_' + num
;
475 $scope
.params
[name
].push([field
, defaultOp
]);
477 $scope
.controls
[name
] = null;
483 $scope
.availableParams
= actionInfo
.params
;
488 function describeSqlFn(params
) {
490 _
.each(params
, function(param
) {
493 desc
+= _
.filter(param
.prefix
).join('|') + ' ';
495 if (param
.expr
=== 1) {
497 } else if (param
.expr
> 1) {
498 desc
+= 'expr, ... ';
501 desc
+= ' ' + _
.filter(param
.suffix
).join('|') + ' ';
504 return desc
.replace(/[ ]+/g, ' ');
507 function defaultValues(defaultVal
) {
508 _
.each($scope
.fields
, function(field
) {
509 if (field
.required
) {
510 defaultVal
.push([field
.id
, '']);
516 function stringify(value
, trim
) {
517 if (typeof value
=== 'undefined') {
520 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
522 str
= str
.slice(1, -1);
527 function writeCode() {
529 entity
= $scope
.entity
,
530 action
= $scope
.action
,
531 params
= getParams(),
532 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
534 if ($scope
.entity
&& $scope
.action
) {
536 if (action
.slice(0, 3) === 'get') {
537 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
538 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
540 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
541 paramCount
= _
.size(params
),
544 if (isSelectRowCount(params
)) {
545 results
= result
+ 'Count';
548 switch ($scope
.selectedTab
.code
) {
552 var js
= "'" + entity
+ "', '" + action
+ "', {";
553 _
.each(params
, function(param
, key
) {
554 js
+= "\n " + key
+ ': ' + stringify(param
) +
555 (++i
< paramCount
? ',' : '');
556 if (key
=== 'checkPermissions') {
557 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
561 if (index
|| index
=== 0) {
562 js
+= ', ' + JSON
.stringify(index
);
564 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
565 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
566 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
567 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
572 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
573 _
.each(params
, function(param
, key
) {
574 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
577 if (index
|| index
=== 0) {
578 code
.php
+= ', ' + phpFormat(index
);
583 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
584 if (isSelectRowCount(params
)) {
585 code
.oop
+= "\n ->count()";
586 } else if (_
.isNumber(index
)) {
587 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
589 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
590 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
592 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
593 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
597 if (!_
.isNumber(index
) && !isSelectRowCount(params
)) {
598 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
604 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
607 _
.each($scope
.code
, function(vals
) {
608 _
.each(vals
, function(style
) {
609 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
615 function formatOOP(entity
, action
, params
, indent
) {
617 newLine
= "\n" + _
.repeat(' ', indent
);
618 if (entity
.substr(0, 7) !== 'Custom_') {
619 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
621 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
623 _
.each(params
, function(param
, key
) {
625 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
626 _
.each(param
, function(item
, index
) {
627 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
628 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
630 } else if (key
=== 'where') {
631 _
.each(param
, function (clause
) {
632 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
633 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
635 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
638 } else if (key
=== 'select') {
640 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
641 code
+= isSelectRowCount(params
) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
642 } else if (key
=== 'chain') {
643 _
.each(param
, function(chain
, name
) {
644 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
645 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
649 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
655 function isInt(value
) {
656 if (_
.isFinite(value
)) {
659 if (!_
.isString(value
)) {
662 return /^-{0,1}\d+$/.test(value
);
665 function formatMeta(resp
) {
667 _
.each(resp
, function(val
, key
) {
668 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
669 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
672 return prettyPrintOne(_
.escape(ret
));
675 $scope
.execute = function() {
676 $scope
.status
= 'info';
677 $scope
.loading
= true;
678 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
679 params
: angular
.toJson(getParams()),
680 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
683 'X-Requested-With': 'XMLHttpRequest'
685 }).then(function(resp
) {
686 $scope
.loading
= false;
687 $scope
.status
= resp
.data
&& resp
.data
.debug
&& resp
.data
.debug
.log
? 'warning' : 'success';
688 $scope
.debug
= debugFormat(resp
.data
);
689 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
691 $scope
.loading
= false;
692 $scope
.status
= 'danger';
693 $scope
.debug
= debugFormat(resp
.data
);
694 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
698 function debugFormat(data
) {
699 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
705 * Format value to look like php code
707 function phpFormat(val
, indent
) {
708 if (typeof val
=== 'undefined') {
711 if (val
=== null || val
=== true || val
=== false) {
712 return JSON
.stringify(val
).toUpperCase();
714 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
716 baseLine
= indent
? indent
.slice(0, -2) : '',
717 newLine
= indent
? '\n' : '',
718 trailingComma
= indent
? ',' : '';
719 if ($.isPlainObject(val
)) {
720 $.each(val
, function(k
, v
) {
721 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
723 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
725 if ($.isArray(val
)) {
726 $.each(val
, function(k
, v
) {
727 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
729 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
731 if (_
.isString(val
) && !_
.contains(val
, "'")) {
732 return "'" + val
+ "'";
734 return JSON
.stringify(val
).replace(/\$/g, '\\$');
737 function fetchMeta() {
738 crmApi4(getMetaParams
)
739 .then(function(data
) {
741 getEntity().actions
= data
.actions
;
747 // Help for an entity with no action selected
748 function showEntityHelp(entityName
) {
749 var entityInfo
= getEntity(entityName
);
750 setHelp($scope
.entity
, {
751 description
: entityInfo
.description
,
752 comment
: entityInfo
.comment
,
757 if (!$scope
.entity
) {
758 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
759 } else if (!actions
.length
&& !getEntity().actions
) {
760 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
767 showEntityHelp($scope
.entity
);
770 // Update route when changing entity
771 $scope
.$watch('entity', function(newVal
, oldVal
) {
772 if (oldVal
!== newVal
) {
773 // Flush actions cache to re-fetch for new entity
775 $location
.url('/explorer/' + newVal
);
779 // Update route when changing actions
780 $scope
.$watch('action', function(newVal
, oldVal
) {
781 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
782 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
784 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
788 $scope
.paramDoc = function(name
) {
789 return docs
.params
[name
];
792 $scope
.executeDoc = function() {
794 description
: ts('Runs API call on the CiviCRM database.'),
795 comment
: ts('Results and debugging info will be displayed below.')
797 if ($scope
.action
=== 'delete') {
798 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
800 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
801 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
806 $scope
.saveDoc = function() {
808 description
: ts('Save API call as a smart group.'),
809 comment
: ts('Create a SavedSearch using these API params to populate a smart group.') +
810 '\n\n' + ts('NOTE: you must select contact id as the only field.')
814 $scope
.$watch('params', writeCode
, true);
815 $scope
.$watch('index', writeCode
);
818 $scope
.save = function() {
819 $scope
.params
.limit
= $scope
.params
.offset
= 0;
820 if ($scope
.params
.chain
.length
) {
821 CRM
.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires
: 5000});
824 if ($scope
.params
.select
.length
!== 1 || !_
.includes($scope
.params
.select
[0], 'id')) {
825 CRM
.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires
: 5000});
831 visibility
: 'User and User Admin Only',
834 entity
: $scope
.entity
,
835 params
: JSON
.parse(angular
.toJson($scope
.params
))
837 model
.params
.version
= 4;
838 delete model
.params
.chain
;
839 delete model
.params
.debug
;
840 delete model
.params
.limit
;
841 delete model
.params
.offset
;
842 delete model
.params
.orderBy
;
843 delete model
.params
.checkPermissions
;
844 var options
= CRM
.utils
.adjustDialogDefaults({
847 title
: ts('Save smart group')
849 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
853 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
854 var ts
= $scope
.ts
= CRM
.ts(),
855 model
= $scope
.model
;
856 $scope
.groupEntityRefParams
= {
859 params
: {is_hidden
: 0, is_active
: 1, 'saved_search_id.api_entity': model
.entity
},
860 extra
: ['saved_search_id', 'description', 'visibility', 'group_type']
864 minimumInputLength
: 0,
865 placeholder
: ts('Select existing group')
868 if (!CRM
.checkPerm('administer reserved groups')) {
869 $scope
.groupEntityRefParams
.api
.params
.is_reserved
= 0;
872 administerReservedGroups
: CRM
.checkPerm('administer reserved groups')
874 $scope
.options
= CRM
.vars
.api4
.groupOptions
;
875 $scope
.$watch('model.id', function(id
) {
877 _
.assign(model
, $('#api-save-search-select-group').select2('data').extra
);
880 $scope
.cancel = function() {
881 dialogService
.cancel('saveSearchDialog');
883 $scope
.save = function() {
884 $('.ui-dialog:visible').block();
885 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
886 group
.description
= model
.description
;
887 group
.visibility
= model
.visibility
;
888 group
.group_type
= model
.group_type
;
889 group
.saved_search_id
= '$id';
891 api_entity
: model
.entity
,
892 api_params
: model
.params
895 savedSearch
.id
= model
.saved_search_id
;
897 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
898 .then(function(result
) {
899 dialogService
.close('saveSearchDialog', result
[0]);
904 angular
.module('api4Explorer').directive('crmApi4Clause', function($timeout
) {
907 data
: '=crmApi4Clause'
909 templateUrl
: '~/api4Explorer/Clause.html',
910 link: function (scope
, element
, attrs
) {
911 var ts
= scope
.ts
= CRM
.ts();
912 scope
.newClause
= '';
913 scope
.conjunctions
= ['AND', 'OR', 'NOT'];
914 scope
.operators
= CRM
.vars
.api4
.operators
;
916 scope
.addGroup = function(op
) {
917 scope
.data
.clauses
.push([op
, []]);
920 scope
.removeGroup = function() {
921 scope
.data
.groupParent
.splice(scope
.data
.groupIndex
, 1);
924 scope
.onSort = function(event
, ui
) {
925 $(element
).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
926 $('.api4-input.form-inline').css('margin-left', '');
929 // Indent clause while dragging between nested groups
930 scope
.onSortOver = function(event
, ui
) {
933 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
935 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
938 scope
.$watch('newClause', function(value
) {
940 $timeout(function() {
942 scope
.data
.clauses
.push([field
, '=', '']);
943 scope
.newClause
= null;
947 scope
.$watch('data.clauses', function(values
) {
948 // Remove empty values
949 _
.each(values
, function(clause
, index
) {
950 if (typeof clause
!== 'undefined' && !clause
[0]) {
951 values
.splice(index
, 1);
953 if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
955 } else if (typeof clause
[1] === 'string' && clause
.length
== 2) {
964 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
967 data
: '=api4ExpValue'
970 link: function (scope
, element
, attrs
, ctrl
) {
971 var ts
= scope
.ts
= CRM
.ts(),
972 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
973 entity
= $routeParams
.api4entity
,
974 action
= scope
.data
.action
|| $routeParams
.api4action
;
976 function destroyWidget() {
977 var $el
= $(element
);
978 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
979 $el
.crmDatepicker('destroy');
981 if ($el
.is('.select2-container + input')) {
982 $el
.crmEntityRef('destroy');
984 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
987 function makeWidget(field
, op
) {
988 var $el
= $(element
),
989 inputType
= field
.input_type
,
990 dataType
= field
.data_type
;
992 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
994 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
995 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
999 if (inputType
=== 'Date') {
1000 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
1001 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
1003 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
1004 if (field
.options
) {
1005 var id
= field
.pseudoconstant
|| 'id';
1006 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
1007 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
1008 var options
= _
.transform(data
[field
.name
].options
, function(options
, opt
) {
1009 options
.push({id
: opt
[id
], text
: opt
.label
, description
: opt
.description
, color
: opt
.color
, icon
: opt
.icon
});
1011 $el
.removeClass('loading').crmSelect2({data
: options
, multiple
: multi
});
1013 } else if (field
.fk_entity
) {
1014 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
1015 } else if (dataType
=== 'Boolean') {
1016 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
1017 {id
: 'true', text
: ts('Yes')},
1018 {id
: 'false', text
: ts('No')}
1021 } else if (dataType
=== 'Integer' && !multi
) {
1022 $el
.attr('type', 'number');
1026 function loadFieldOptions(entity
) {
1027 if (!fieldOptions
[entity
+ action
]) {
1028 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
1029 loadOptions
: ['id', 'name', 'label', 'description', 'color', 'icon'],
1031 where
: [['options', '!=', false]],
1035 return fieldOptions
[entity
+ action
];
1038 // Copied from ng-list but applied conditionally if field is multi-valued
1039 var parseList = function(viewValue
) {
1040 // If the viewValue is invalid (say required but empty) it will be `undefined`
1041 if (_
.isUndefined(viewValue
)) return;
1050 _
.each(viewValue
.split(','), function(value
) {
1051 if (value
) list
.push(_
.trim(value
));
1058 // Copied from ng-list
1059 ctrl
.$parsers
.push(parseList
);
1060 ctrl
.$formatters
.push(function(value
) {
1061 return _
.isArray(value
) ? value
.join(', ') : value
;
1064 // Copied from ng-list
1065 ctrl
.$isEmpty = function(value
) {
1066 return !value
|| !value
.length
;
1069 scope
.$watchCollection('data', function(data
) {
1071 var field
= getField(data
.field
, entity
, action
);
1073 makeWidget(field
, data
.op
);
1081 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
1084 chain
: '=api4ExpChain',
1088 templateUrl
: '~/api4Explorer/Chain.html',
1089 link: function (scope
, element
, attrs
) {
1090 var ts
= scope
.ts
= CRM
.ts();
1092 function changeEntity(newEntity
, oldEntity
) {
1093 // When clearing entity remove this chain
1095 scope
.chain
[0] = '';
1098 // Reset action && index
1099 if (newEntity
!== oldEntity
) {
1100 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
1102 if (getEntity(newEntity
).actions
) {
1105 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
1106 .then(function(data
) {
1107 getEntity(data
.entity
).actions
= data
;
1108 if (data
.entity
=== scope
.chain
[1][0]) {
1115 function setActions() {
1116 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
1119 // Set default params when choosing action
1120 function changeAction(newAction
, oldAction
) {
1122 // Prepopulate links
1123 if (newAction
&& newAction
!== oldAction
) {
1125 scope
.chain
[1][3] = '';
1126 // Look for links back to main entity
1127 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
1128 if (field
.fk_entity
=== scope
.mainEntity
) {
1129 link
= [field
.name
, '$id'];
1132 // Look for links from main entity
1133 if (!link
&& newAction
!== 'create') {
1134 _
.each(entityFields(scope
.mainEntity
), function(field
) {
1135 if (field
.fk_entity
=== scope
.chain
[1][0]) {
1136 link
= ['id', '$' + field
.name
];
1137 // Since we're specifying the id, set index to getsingle
1138 scope
.chain
[1][3] = '0';
1142 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1143 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1145 else if (link
&& _
.contains(['create'], newAction
)) {
1146 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1148 else if (link
&& _
.contains(['save'], newAction
)) {
1149 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1151 scope
.chain
[1][2] = '{}';
1156 scope
.$watch("chain[1][0]", changeEntity
);
1157 scope
.$watch("chain[1][1]", changeAction
);
1162 function getEntity(entityName
) {
1163 return _
.findWhere(schema
, {name
: entityName
});
1166 function entityFields(entityName
, action
) {
1167 var entity
= getEntity(entityName
);
1168 if (entity
&& action
&& entity
.actions
) {
1169 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1171 return _
.result(entity
, 'fields');
1174 function getField(fieldName
, entity
, action
) {
1175 var suffix
= fieldName
.split(':')[1];
1176 fieldName
= fieldName
.split(':')[0];
1177 var fieldNames
= fieldName
.split('.');
1178 var field
= get(entity
, fieldNames
);
1179 if (field
&& suffix
) {
1180 field
.pseudoconstant
= suffix
;
1184 function get(entity
, fieldNames
) {
1185 if (fieldNames
.length
=== 1) {
1186 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1188 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1192 var linkName
= fieldNames
.shift(),
1193 newEntity
= _
.findWhere(links
[entity
], {alias
: linkName
}).entity
;
1194 return get(newEntity
, fieldNames
);
1198 // Collapsible optgroups for select2
1201 .on('select2-open', function(e
) {
1202 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1204 .off('.collapseOptionGroup')
1205 .addClass('collapsible-optgroups-enabled')
1206 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1207 $(this).parent().toggleClass('optgroup-expanded');
1211 .on('select2-close', function() {
1212 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1215 })(angular
, CRM
.$, CRM
._
);