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
.fieldsAndJoins
= [];
29 $scope
.fieldsAndJoinsAndFunctions
= [];
30 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= [];
31 $scope
.availableParams
= {};
34 $scope
.selectedTab
= {result
: 'result', code
: 'php'};
36 accessDebugOutput
: CRM
.checkPerm('access debug output'),
37 editGroups
: CRM
.checkPerm('edit groups')
39 marked
.setOptions({highlight
: prettyPrintOne
});
40 var getMetaParams
= {},
41 objectParams
= {orderBy
: 'ASC', values
: '', defaults
: '', chain
: ['Entity', '', '{}']},
42 docs
= CRM
.vars
.api4
.docs
,
45 $scope
.helpTitle
= '';
46 $scope
.helpContent
= {};
47 $scope
.entity
= $routeParams
.api4entity
;
50 $scope
.status
= 'default';
51 $scope
.loading
= false;
57 {name
: 'oop', label
: ts('OOP Style'), code
: ''},
58 {name
: 'php', label
: ts('Traditional'), code
: ''}
64 {name
: 'js', label
: ts('Single Call'), code
: ''},
65 {name
: 'js2', label
: ts('Batch Calls'), code
: ''}
71 {name
: 'ang', label
: ts('Single Call'), code
: ''},
72 {name
: 'ang2', label
: ts('Batch Calls'), code
: ''}
78 {name
: 'cv', label
: ts('CV'), code
: ''}
83 if (!entities
.length
) {
84 formatForSelect2(schema
, entities
, 'name', ['description']);
93 function ucfirst(str
) {
94 return str
[0].toUpperCase() + str
.slice(1);
97 function lcfirst(str
) {
98 return str
[0].toLowerCase() + str
.slice(1);
101 function pluralize(str
) {
102 switch (str
[str
.length
-1]) {
106 return str
.slice(0, -1) + 'ies';
112 // Turn a flat array into a select2 array
113 function arrayToSelect2(array
) {
115 _
.each(array
, function(item
) {
116 out
.push({id
: item
, text
: item
});
121 // Reformat an existing array of objects for compatibility with select2
122 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
123 _
.each(input
, function(item
) {
124 var id
= (prefix
|| '') + item
[key
];
125 var formatted
= {id
: id
, text
: id
};
127 _
.merge(formatted
, _
.pick(item
, extra
));
129 container
.push(formatted
);
134 function getFieldList(action
) {
136 fieldInfo
= _
.findWhere(getEntity().actions
, {name
: action
}).fields
;
137 formatForSelect2(fieldInfo
, fields
, 'name', ['description', 'required', 'default_value']);
141 function addJoins(fieldList
, addWildcard
) {
142 var fields
= _
.cloneDeep(fieldList
),
143 fks
= _
.findWhere(links
, {entity
: $scope
.entity
}) || {};
144 _
.each(fks
.links
, function(link
) {
145 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
146 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
150 description
: 'Join to ' + link
.entity
,
151 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
158 $scope
.help = function(title
, content
) {
160 $scope
.helpTitle
= helpTitle
;
161 $scope
.helpContent
= helpContent
;
163 $scope
.helpTitle
= title
;
164 $scope
.helpContent
= formatHelp(content
);
168 // Sets the static help text (which gets overridden by mousing over other elements)
169 function setHelp(title
, content
) {
170 $scope
.helpTitle
= helpTitle
= title
;
171 $scope
.helpContent
= helpContent
= formatHelp(content
);
174 // Convert plain-text help to markdown; replace variables and format links
175 function formatHelp(rawContent
) {
176 function formatRefs(see
) {
177 _
.each(see
, function(ref
, idx
) {
178 var match
= ref
.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
180 ref
= '#/explorer/' + match
[1];
182 if (ref
[0] === '\\') {
183 ref
= 'https://github.com/civicrm/civicrm-core/blob/master' + ref
.replace(/\\/i, '/') + '.php
';
185 see[idx] = '<a target
="' + (ref[0] === '#' ? '_self' : '_blank') + '" href
="' + ref + '">' + see[idx] + '</a
>';
188 var formatted = _.cloneDeep(rawContent);
189 if (formatted.description) {
190 formatted.description = marked(formatted.description);
192 if (formatted.comment) {
193 formatted.comment = marked(formatted.comment);
195 formatRefs(formatted.see);
199 $scope.fieldHelp = function(fieldName) {
200 var field = getField(fieldName, $scope.entity, $scope.action);
205 description: field.description,
206 type: field.data_type
208 if (field.default_value) {
209 info.default = field.default_value;
211 if (field.required_if) {
212 info.required_if = field.required_if;
213 } else if (field.required) {
214 info.required = 'true';
219 $scope.fieldList = function(param) {
221 var fields = _.cloneDeep($scope.action === 'getFields
' ? getFieldList($scope.params.action || 'get') : $scope.fields);
222 // Disable fields that are already in use
223 _.each($scope.params[param] || [], function(val) {
224 (_.findWhere(fields, {id: val[0]}) || {}).disabled = true;
226 return {results: fields};
230 $scope.formatSelect2Item = function(row) {
231 return _.escape(row.text) +
232 (row.required ? '<span
class="crm-marker"> *</span
>' : '') +
233 (row.description ? '<div
class="crm-select2-row-description"><p
>' + _.escape(row.description) + '</p></div>' : '');
236 $scope.clearParam = function(name, idx) {
237 if (typeof idx === 'undefined') {
238 $scope.params[name] = $scope.availableParams[name].default;
240 $scope.params[name].splice(idx, 1);
244 $scope.isSpecial = function(name) {
245 var specialParams = ['select
', 'fields
', 'action
', 'where
', 'values
', 'defaults
', 'orderBy
', 'chain
', 'groupBy
'];
246 if ($scope.availableParams.limit && $scope.availableParams.offset) {
247 specialParams.push('limit
', 'offset
');
249 return _.contains(specialParams, name);
252 $scope.selectRowCount = function() {
253 if ($scope.isSelectRowCount()) {
254 $scope.params.select = [];
256 $scope.params.select = ['row_count
'];
258 if ($scope.params.limit == 25) {
259 $scope.params.limit = 0;
264 $scope.isSelectRowCount = function() {
265 return isSelectRowCount($scope.params);
268 function isSelectRowCount(params) {
269 return params && params.select && params.select.length === 1 && params.select[0] === 'row_count
';
272 function getEntity(entityName) {
273 return _.findWhere(schema, {name: entityName || $scope.entity});
276 // Get all params that have been set
277 function getParams() {
279 _.each($scope.params, function(param, key) {
280 if (param != $scope.availableParams[key].default && !(typeof param === 'object
' && _.isEmpty(param))) {
281 if (_.contains($scope.availableParams[key].type, 'array
') && (typeof objectParams[key] === 'undefined')) {
282 params[key] = parseYaml(JSON.parse(angular.toJson(param)));
288 _.each(objectParams, function(defaultVal, key) {
291 _.each(params[key], function(item) {
292 var val = _.cloneDeep(item[1]);
293 // Remove blank items from "chain" array
294 if (_.isArray(val)) {
295 _.eachRight(item[1], function(v, k) {
302 newParam[item[0]] = parseYaml(val);
304 params[key] = newParam;
310 function parseYaml(input) {
311 if (typeof input === 'undefined') {
317 if (_.isObject(input) || _.isArray(input)) {
318 _.each(input, function(item, index) {
319 input[index] = parseYaml(item);
324 var output = (input === '>') ? '>' : jsyaml.safeLoad(input);
325 // We don't want dates parsed to js objects
326 return _
.isDate(output
) ? input
: output
;
332 function selectAction() {
333 $scope
.action
= $routeParams
.api4action
;
334 $scope
.fieldsAndJoins
.length
= 0;
335 $scope
.fieldsAndJoinsAndFunctions
.length
= 0;
336 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.length
= 0;
337 if (!actions
.length
) {
338 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
341 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
342 $scope
.fields
= getFieldList($scope
.action
);
343 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
344 $scope
.fieldsAndJoins
= addJoins($scope
.fields
);
345 var fieldsAndFunctions
= _
.cloneDeep($scope
.fields
);
346 // SQL functions are supported if HAVING is
347 if (actionInfo
.params
.having
) {
348 fieldsAndFunctions
.push({
349 text
: ts('FUNCTION'),
350 description
: ts('Calculate result of a SQL function'),
351 children
: _
.transform(CRM
.vars
.api4
.functions
, function(result
, fn
) {
353 id
: fn
.name
+ '() AS ' + fn
.name
.toLowerCase(),
354 text
: fn
.name
+ '()',
355 description
: fn
.name
+ '(' + describeSqlFn(fn
.params
) + ')'
360 $scope
.fieldsAndJoinsAndFunctions
= addJoins(fieldsAndFunctions
, true);
361 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= addJoins(fieldsAndFunctions
, true);
363 $scope
.fieldsAndJoins
= $scope
.fields
;
364 $scope
.fieldsAndJoinsAndFunctions
= $scope
.fields
;
365 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= _
.cloneDeep($scope
.fields
);
367 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
368 _
.each(actionInfo
.params
, function (param
, name
) {
370 defaultVal
= _
.cloneDeep(param
.default);
372 switch (param
.type
[0]) {
375 format
= param
.type
[0];
386 if (name
=== 'limit') {
389 if (name
=== 'debug') {
392 if (name
=== 'values') {
393 defaultVal
= defaultValues(defaultVal
);
395 $scope
.$bindToRoute({
396 expr
: 'params["' + name
+ '"]',
400 deep
: format
=== 'json'
403 if (typeof objectParams
[name
] !== 'undefined' && name
!== 'orderBy') {
404 $scope
.$watch('params.' + name
, function (values
) {
405 // Remove empty values
406 _
.each(values
, function (clause
, index
) {
407 if (!clause
|| !clause
[0]) {
408 $scope
.clearParam(name
, index
);
413 if (typeof objectParams
[name
] !== 'undefined' || name
=== 'groupBy' || name
=== 'select') {
414 $scope
.$watch('controls.' + name
, function(value
) {
416 $timeout(function() {
418 if (typeof objectParams
[name
] === 'undefined') {
419 $scope
.params
[name
].push(field
);
421 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
422 if (name
=== 'chain') {
423 var num
= $scope
.params
.chain
.length
;
424 defaultOp
[0] = field
;
425 field
= 'name_me_' + num
;
427 $scope
.params
[name
].push([field
, defaultOp
]);
429 $scope
.controls
[name
] = null;
435 $scope
.availableParams
= actionInfo
.params
;
440 function describeSqlFn(params
) {
442 _
.each(params
, function(param
) {
445 desc
+= _
.filter(param
.prefix
).join('|') + ' ';
447 if (param
.expr
=== 1) {
449 } else if (param
.expr
> 1) {
450 desc
+= 'expr, ... ';
453 desc
+= ' ' + _
.filter(param
.suffix
).join('|') + ' ';
456 return desc
.replace(/[ ]+/g, ' ');
459 function defaultValues(defaultVal
) {
460 _
.each($scope
.fields
, function(field
) {
461 if (field
.required
) {
462 defaultVal
.push([field
.id
, '']);
468 function stringify(value
, trim
) {
469 if (typeof value
=== 'undefined') {
472 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
474 str
= str
.slice(1, -1);
479 function writeCode() {
481 entity
= $scope
.entity
,
482 action
= $scope
.action
,
483 params
= getParams(),
484 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
486 if ($scope
.entity
&& $scope
.action
) {
488 if (action
.slice(0, 3) === 'get') {
489 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
490 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
492 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
493 paramCount
= _
.size(params
),
496 if (isSelectRowCount(params
)) {
497 results
= result
+ 'Count';
501 var js
= "'" + entity
+ "', '" + action
+ "', {";
502 _
.each(params
, function(param
, key
) {
503 js
+= "\n " + key
+ ': ' + stringify(param
) +
504 (++i
< paramCount
? ',' : '');
505 if (key
=== 'checkPermissions') {
506 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
510 if (index
|| index
=== 0) {
511 js
+= ', ' + JSON
.stringify(index
);
513 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
514 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
515 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
516 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
519 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
520 _
.each(params
, function(param
, key
) {
521 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
524 if (index
|| index
=== 0) {
525 code
.php
+= ', ' + phpFormat(index
);
530 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
531 if (isSelectRowCount(params
)) {
532 code
.oop
+= "\n ->count()";
533 } else if (_
.isNumber(index
)) {
534 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
536 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
537 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
539 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
540 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
544 if (!_
.isNumber(index
) && !isSelectRowCount(params
)) {
545 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
549 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
551 _
.each($scope
.code
, function(vals
) {
552 _
.each(vals
.style
, function(style
) {
553 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
559 function formatOOP(entity
, action
, params
, indent
) {
561 newLine
= "\n" + _
.repeat(' ', indent
);
562 if (entity
.substr(0, 7) !== 'Custom_') {
563 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
565 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
567 _
.each(params
, function(param
, key
) {
569 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
570 _
.each(param
, function(item
, index
) {
571 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
572 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
574 } else if (key
=== 'where') {
575 _
.each(param
, function (clause
) {
576 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
577 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
579 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
582 } else if (key
=== 'select') {
584 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
585 code
+= isSelectRowCount(params
) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
586 } else if (key
=== 'chain') {
587 _
.each(param
, function(chain
, name
) {
588 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
589 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
593 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
599 function isInt(value
) {
600 if (_
.isFinite(value
)) {
603 if (!_
.isString(value
)) {
606 return /^-{0,1}\d+$/.test(value
);
609 function formatMeta(resp
) {
611 _
.each(resp
, function(val
, key
) {
612 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
613 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
616 return prettyPrintOne(_
.escape(ret
));
619 $scope
.execute = function() {
620 $scope
.status
= 'warning';
621 $scope
.loading
= true;
622 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
623 params
: angular
.toJson(getParams()),
624 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
627 'X-Requested-With': 'XMLHttpRequest'
629 }).then(function(resp
) {
630 $scope
.loading
= false;
631 $scope
.status
= 'success';
632 $scope
.debug
= debugFormat(resp
.data
);
633 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
635 $scope
.loading
= false;
636 $scope
.status
= 'danger';
637 $scope
.debug
= debugFormat(resp
.data
);
638 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
642 function debugFormat(data
) {
643 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
649 * Format value to look like php code
651 function phpFormat(val
, indent
) {
652 if (typeof val
=== 'undefined') {
655 if (val
=== null || val
=== true || val
=== false) {
656 return JSON
.stringify(val
).toUpperCase();
658 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
660 baseLine
= indent
? indent
.slice(0, -2) : '',
661 newLine
= indent
? '\n' : '',
662 trailingComma
= indent
? ',' : '';
663 if ($.isPlainObject(val
)) {
664 $.each(val
, function(k
, v
) {
665 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
667 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
669 if ($.isArray(val
)) {
670 $.each(val
, function(k
, v
) {
671 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
673 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
675 if (_
.isString(val
) && !_
.contains(val
, "'")) {
676 return "'" + val
+ "'";
678 return JSON
.stringify(val
).replace(/\$/g, '\\$');
681 function fetchMeta() {
682 crmApi4(getMetaParams
)
683 .then(function(data
) {
685 getEntity().actions
= data
.actions
;
691 // Help for an entity with no action selected
692 function showEntityHelp(entityName
) {
693 var entityInfo
= getEntity(entityName
);
694 setHelp($scope
.entity
, {
695 description
: entityInfo
.description
,
696 comment
: entityInfo
.comment
,
701 if (!$scope
.entity
) {
702 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
703 } else if (!actions
.length
&& !getEntity().actions
) {
704 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
711 showEntityHelp($scope
.entity
);
714 // Update route when changing entity
715 $scope
.$watch('entity', function(newVal
, oldVal
) {
716 if (oldVal
!== newVal
) {
717 // Flush actions cache to re-fetch for new entity
719 $location
.url('/explorer/' + newVal
);
723 // Update route when changing actions
724 $scope
.$watch('action', function(newVal
, oldVal
) {
725 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
726 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
728 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
732 $scope
.paramDoc = function(name
) {
733 return docs
.params
[name
];
736 $scope
.executeDoc = function() {
738 description
: ts('Runs API call on the CiviCRM database.'),
739 comment
: ts('Results and debugging info will be displayed below.')
741 if ($scope
.action
=== 'delete') {
742 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
744 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
745 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
750 $scope
.saveDoc = function() {
752 description
: ts('Save API call as a smart group.'),
753 comment
: ts('Allows you to create a SavedSearch containing the WHERE clause of this API call.'),
757 $scope
.$watch('params', writeCode
, true);
758 $scope
.$watch('index', writeCode
);
761 $scope
.save = function() {
765 visibility
: 'User and User Admin Only',
768 entity
: $scope
.entity
,
769 params
: JSON
.parse(angular
.toJson($scope
.params
))
771 model
.params
.version
= 4;
772 delete model
.params
.select
;
773 delete model
.params
.chain
;
774 delete model
.params
.debug
;
775 delete model
.params
.limit
;
776 delete model
.params
.checkPermissions
;
777 var options
= CRM
.utils
.adjustDialogDefaults({
780 title
: ts('Save smart group')
782 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
786 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
787 var ts
= $scope
.ts
= CRM
.ts(),
788 model
= $scope
.model
;
789 $scope
.groupEntityRefParams
= {
792 params
: {is_hidden
: 0, is_active
: 1, 'saved_search_id.api_entity': model
.entity
},
793 extra
: ['saved_search_id', 'description', 'visibility', 'group_type']
797 minimumInputLength
: 0,
798 placeholder
: ts('Select existing group')
801 if (!CRM
.checkPerm('administer reserved groups')) {
802 $scope
.groupEntityRefParams
.api
.params
.is_reserved
= 0;
805 administerReservedGroups
: CRM
.checkPerm('administer reserved groups')
807 $scope
.options
= CRM
.vars
.api4
.groupOptions
;
808 $scope
.$watch('model.id', function(id
) {
810 _
.assign(model
, $('#api-save-search-select-group').select2('data').extra
);
813 $scope
.cancel = function() {
814 dialogService
.cancel('saveSearchDialog');
816 $scope
.save = function() {
817 $('.ui-dialog:visible').block();
818 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
819 group
.description
= model
.description
;
820 group
.visibility
= model
.visibility
;
821 group
.group_type
= model
.group_type
;
822 group
.saved_search_id
= '$id';
824 api_entity
: model
.entity
,
825 api_params
: model
.params
828 savedSearch
.id
= model
.saved_search_id
;
830 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
831 .then(function(result
) {
832 dialogService
.close('saveSearchDialog', result
[0]);
837 angular
.module('api4Explorer').directive('crmApi4Clause', function($timeout
) {
840 data
: '=crmApi4Clause'
842 templateUrl
: '~/api4Explorer/Clause.html',
843 link: function (scope
, element
, attrs
) {
844 var ts
= scope
.ts
= CRM
.ts();
845 scope
.newClause
= '';
846 scope
.conjunctions
= ['AND', 'OR', 'NOT'];
847 scope
.operators
= CRM
.vars
.api4
.operators
;
849 scope
.addGroup = function(op
) {
850 scope
.data
.clauses
.push([op
, []]);
853 scope
.removeGroup = function() {
854 scope
.data
.groupParent
.splice(scope
.data
.groupIndex
, 1);
857 scope
.onSort = function(event
, ui
) {
858 $(element
).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
859 $('.api4-input.form-inline').css('margin-left', '');
862 // Indent clause while dragging between nested groups
863 scope
.onSortOver = function(event
, ui
) {
866 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
868 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
871 scope
.$watch('newClause', function(value
) {
873 $timeout(function() {
875 scope
.data
.clauses
.push([field
, '=', '']);
876 scope
.newClause
= null;
880 scope
.$watch('data.clauses', function(values
) {
881 // Remove empty values
882 _
.each(values
, function(clause
, index
) {
883 if (typeof clause
!== 'undefined' && !clause
[0]) {
884 values
.splice(index
, 1);
886 if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
888 } else if (typeof clause
[1] === 'string' && clause
.length
== 2) {
897 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
900 data
: '=api4ExpValue'
903 link: function (scope
, element
, attrs
, ctrl
) {
904 var ts
= scope
.ts
= CRM
.ts(),
905 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
906 entity
= $routeParams
.api4entity
,
907 action
= scope
.data
.action
|| $routeParams
.api4action
;
909 function destroyWidget() {
910 var $el
= $(element
);
911 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
912 $el
.crmDatepicker('destroy');
914 if ($el
.is('.select2-container + input')) {
915 $el
.crmEntityRef('destroy');
917 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
920 function makeWidget(field
, op
) {
921 var $el
= $(element
),
922 inputType
= field
.input_type
,
923 dataType
= field
.data_type
;
925 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
927 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
928 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
932 if (inputType
=== 'Date') {
933 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
934 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
936 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
937 if (field
.fk_entity
) {
938 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
939 } else if (field
.options
) {
940 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
941 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
943 _
.each(_
.findWhere(data
, {name
: field
.name
}).options
, function(val
, key
) {
944 options
.push({id
: key
, text
: val
});
946 $el
.removeClass('loading').select2({data
: options
, multiple
: multi
});
948 } else if (dataType
=== 'Boolean') {
949 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
950 {id
: 'true', text
: ts('Yes')},
951 {id
: 'false', text
: ts('No')}
954 } else if (dataType
=== 'Integer' && !multi
) {
955 $el
.attr('type', 'number');
959 function loadFieldOptions(entity
) {
960 if (!fieldOptions
[entity
+ action
]) {
961 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
964 where
: [["options", "!=", false]],
965 select
: ["name", "options"]
968 return fieldOptions
[entity
+ action
];
971 // Copied from ng-list but applied conditionally if field is multi-valued
972 var parseList = function(viewValue
) {
973 // If the viewValue is invalid (say required but empty) it will be `undefined`
974 if (_
.isUndefined(viewValue
)) return;
983 _
.each(viewValue
.split(','), function(value
) {
984 if (value
) list
.push(_
.trim(value
));
991 // Copied from ng-list
992 ctrl
.$parsers
.push(parseList
);
993 ctrl
.$formatters
.push(function(value
) {
994 return _
.isArray(value
) ? value
.join(', ') : value
;
997 // Copied from ng-list
998 ctrl
.$isEmpty = function(value
) {
999 return !value
|| !value
.length
;
1002 scope
.$watchCollection('data', function(data
) {
1004 var field
= getField(data
.field
, entity
, action
);
1006 makeWidget(field
, data
.op
);
1014 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
1017 chain
: '=api4ExpChain',
1021 templateUrl
: '~/api4Explorer/Chain.html',
1022 link: function (scope
, element
, attrs
) {
1023 var ts
= scope
.ts
= CRM
.ts();
1025 function changeEntity(newEntity
, oldEntity
) {
1026 // When clearing entity remove this chain
1028 scope
.chain
[0] = '';
1031 // Reset action && index
1032 if (newEntity
!== oldEntity
) {
1033 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
1035 if (getEntity(newEntity
).actions
) {
1038 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
1039 .then(function(data
) {
1040 getEntity(data
.entity
).actions
= data
;
1041 if (data
.entity
=== scope
.chain
[1][0]) {
1048 function setActions() {
1049 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
1052 // Set default params when choosing action
1053 function changeAction(newAction
, oldAction
) {
1055 // Prepopulate links
1056 if (newAction
&& newAction
!== oldAction
) {
1058 scope
.chain
[1][3] = '';
1059 // Look for links back to main entity
1060 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
1061 if (field
.fk_entity
=== scope
.mainEntity
) {
1062 link
= [field
.name
, '$id'];
1065 // Look for links from main entity
1066 if (!link
&& newAction
!== 'create') {
1067 _
.each(entityFields(scope
.mainEntity
), function(field
) {
1068 if (field
.fk_entity
=== scope
.chain
[1][0]) {
1069 link
= ['id', '$' + field
.name
];
1070 // Since we're specifying the id, set index to getsingle
1071 scope
.chain
[1][3] = '0';
1075 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1076 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1078 else if (link
&& _
.contains(['create'], newAction
)) {
1079 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1081 else if (link
&& _
.contains(['save'], newAction
)) {
1082 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1084 scope
.chain
[1][2] = '{}';
1089 scope
.$watch("chain[1][0]", changeEntity
);
1090 scope
.$watch("chain[1][1]", changeAction
);
1095 function getEntity(entityName
) {
1096 return _
.findWhere(schema
, {name
: entityName
});
1099 function entityFields(entityName
, action
) {
1100 var entity
= getEntity(entityName
);
1101 if (entity
&& action
&& entity
.actions
) {
1102 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1104 return _
.result(entity
, 'fields');
1107 function getField(fieldName
, entity
, action
) {
1108 var fieldNames
= fieldName
.split('.');
1109 return get(entity
, fieldNames
);
1111 function get(entity
, fieldNames
) {
1112 if (fieldNames
.length
=== 1) {
1113 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1115 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1119 var linkName
= fieldNames
.shift(),
1120 entityLinks
= _
.findWhere(links
, {entity
: entity
}).links
,
1121 newEntity
= _
.findWhere(entityLinks
, {alias
: linkName
}).entity
;
1122 return get(newEntity
, fieldNames
);
1126 // Collapsible optgroups for select2
1129 .on('select2-open', function(e
) {
1130 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1132 .off('.collapseOptionGroup')
1133 .addClass('collapsible-optgroups-enabled')
1134 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1135 $(this).parent().toggleClass('optgroup-expanded');
1139 .on('select2-close', function() {
1140 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1143 })(angular
, CRM
.$, CRM
._
);