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
.selectFieldsAndJoins
= [];
30 $scope
.availableParams
= {};
33 $scope
.selectedTab
= {result
: 'result', code
: 'php'};
35 accessDebugOutput
: CRM
.checkPerm('access debug output'),
36 editGroups
: CRM
.checkPerm('edit groups')
38 marked
.setOptions({highlight
: prettyPrintOne
});
39 var getMetaParams
= {},
40 objectParams
= {orderBy
: 'ASC', values
: '', defaults
: '', chain
: ['Entity', '', '{}']},
41 docs
= CRM
.vars
.api4
.docs
,
44 $scope
.helpTitle
= '';
45 $scope
.helpContent
= {};
46 $scope
.entity
= $routeParams
.api4entity
;
49 $scope
.status
= 'default';
50 $scope
.loading
= false;
56 {name
: 'oop', label
: ts('OOP Style'), code
: ''},
57 {name
: 'php', label
: ts('Traditional'), code
: ''}
63 {name
: 'js', label
: ts('Single Call'), code
: ''},
64 {name
: 'js2', label
: ts('Batch Calls'), code
: ''}
70 {name
: 'ang', label
: ts('Single Call'), code
: ''},
71 {name
: 'ang2', label
: ts('Batch Calls'), code
: ''}
77 {name
: 'cv', label
: ts('CV'), code
: ''}
82 if (!entities
.length
) {
83 formatForSelect2(schema
, entities
, 'name', ['description']);
92 function ucfirst(str
) {
93 return str
[0].toUpperCase() + str
.slice(1);
96 function lcfirst(str
) {
97 return str
[0].toLowerCase() + str
.slice(1);
100 function pluralize(str
) {
101 switch (str
[str
.length
-1]) {
105 return str
.slice(0, -1) + 'ies';
111 // Turn a flat array into a select2 array
112 function arrayToSelect2(array
) {
114 _
.each(array
, function(item
) {
115 out
.push({id
: item
, text
: item
});
120 // Reformat an existing array of objects for compatibility with select2
121 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
122 _
.each(input
, function(item
) {
123 var id
= (prefix
|| '') + item
[key
];
124 var formatted
= {id
: id
, text
: id
};
126 _
.merge(formatted
, _
.pick(item
, extra
));
128 container
.push(formatted
);
133 function getFieldList(action
) {
135 fieldInfo
= _
.findWhere(getEntity().actions
, {name
: action
}).fields
;
136 formatForSelect2(fieldInfo
, fields
, 'name', ['description', 'required', 'default_value']);
140 function addJoins(fieldList
, addWildcard
) {
141 var fields
= _
.cloneDeep(fieldList
),
142 fks
= _
.findWhere(links
, {entity
: $scope
.entity
}) || {};
143 _
.each(fks
.links
, function(link
) {
144 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
145 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
149 description
: 'Join to ' + link
.entity
,
150 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
157 $scope
.help = function(title
, content
) {
159 $scope
.helpTitle
= helpTitle
;
160 $scope
.helpContent
= helpContent
;
162 $scope
.helpTitle
= title
;
163 $scope
.helpContent
= formatHelp(content
);
167 // Sets the static help text (which gets overridden by mousing over other elements)
168 function setHelp(title
, content
) {
169 $scope
.helpTitle
= helpTitle
= title
;
170 $scope
.helpContent
= helpContent
= formatHelp(content
);
173 // Convert plain-text help to markdown; replace variables and format links
174 function formatHelp(rawContent
) {
175 function formatRefs(see
) {
176 _
.each(see
, function(ref
, idx
) {
177 var match
= ref
.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
179 ref
= '#/explorer/' + match
[1];
181 if (ref
[0] === '\\') {
182 ref
= 'https://github.com/civicrm/civicrm-core/blob/master' + ref
.replace(/\\/i, '/') + '.php
';
184 see[idx] = '<a target
="' + (ref[0] === '#' ? '_self' : '_blank') + '" href
="' + ref + '">' + see[idx] + '</a
>';
187 var formatted = _.cloneDeep(rawContent);
188 if (formatted.description) {
189 formatted.description = marked(formatted.description);
191 if (formatted.comment) {
192 formatted.comment = marked(formatted.comment);
194 formatRefs(formatted.see);
198 $scope.fieldHelp = function(fieldName) {
199 var field = getField(fieldName, $scope.entity, $scope.action);
204 description: field.description,
205 type: field.data_type
207 if (field.default_value) {
208 info.default = field.default_value;
210 if (field.required_if) {
211 info.required_if = field.required_if;
212 } else if (field.required) {
213 info.required = 'true';
218 $scope.fieldList = function(param) {
220 var fields = _.cloneDeep($scope.action === 'getFields
' ? getFieldList($scope.params.action || 'get') : $scope.fields);
221 // Disable fields that are already in use
222 _.each($scope.params[param] || [], function(val) {
223 (_.findWhere(fields, {id: val[0]}) || {}).disabled = true;
225 return {results: fields};
229 $scope.formatSelect2Item = function(row) {
230 return _.escape(row.text) +
231 (row.required ? '<span
class="crm-marker"> *</span
>' : '') +
232 (row.description ? '<div
class="crm-select2-row-description"><p
>' + _.escape(row.description) + '</p></div>' : '');
235 $scope.clearParam = function(name) {
236 $scope.params[name] = $scope.availableParams[name].default;
239 $scope.isSpecial = function(name) {
240 var specialParams = ['select
', 'fields
', 'action
', 'where
', 'values
', 'defaults
', 'orderBy
', 'chain
', 'groupBy
'];
241 if ($scope.availableParams.limit && $scope.availableParams.offset) {
242 specialParams.push('limit
', 'offset
');
244 return _.contains(specialParams, name);
247 $scope.selectRowCount = function() {
248 if ($scope.isSelectRowCount()) {
249 $scope.params.select = [];
251 $scope.params.select = ['row_count
'];
253 if ($scope.params.limit == 25) {
254 $scope.params.limit = 0;
259 $scope.isSelectRowCount = function() {
260 return isSelectRowCount($scope.params);
263 function isSelectRowCount(params) {
264 return params && params.select && params.select.length === 1 && params.select[0] === 'row_count
';
267 function getEntity(entityName) {
268 return _.findWhere(schema, {name: entityName || $scope.entity});
271 // Get all params that have been set
272 function getParams() {
274 _.each($scope.params, function(param, key) {
275 if (param != $scope.availableParams[key].default && !(typeof param === 'object
' && _.isEmpty(param))) {
276 if (_.contains($scope.availableParams[key].type, 'array
') && (typeof objectParams[key] === 'undefined')) {
277 params[key] = parseYaml(JSON.parse(angular.toJson(param)));
283 _.each(objectParams, function(defaultVal, key) {
286 _.each(params[key], function(item) {
287 var val = _.cloneDeep(item[1]);
288 // Remove blank items from "chain" array
289 if (_.isArray(val)) {
290 _.eachRight(item[1], function(v, k) {
297 newParam[item[0]] = parseYaml(val);
299 params[key] = newParam;
305 function parseYaml(input) {
306 if (typeof input === 'undefined') {
312 if (_.isObject(input) || _.isArray(input)) {
313 _.each(input, function(item, index) {
314 input[index] = parseYaml(item);
319 var output = (input === '>') ? '>' : jsyaml.safeLoad(input);
320 // We don't want dates parsed to js objects
321 return _
.isDate(output
) ? input
: output
;
327 function selectAction() {
328 $scope
.action
= $routeParams
.api4action
;
329 $scope
.fieldsAndJoins
.length
= 0;
330 $scope
.selectFieldsAndJoins
.length
= 0;
331 if (!actions
.length
) {
332 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
335 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
336 $scope
.fields
= getFieldList($scope
.action
);
337 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
338 $scope
.fieldsAndJoins
= addJoins($scope
.fields
);
339 $scope
.selectFieldsAndJoins
= addJoins($scope
.fields
, true);
341 $scope
.fieldsAndJoins
= $scope
.fields
;
342 $scope
.selectFieldsAndJoins
= _
.cloneDeep($scope
.fields
);
344 $scope
.selectFieldsAndJoins
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
345 _
.each(actionInfo
.params
, function (param
, name
) {
347 defaultVal
= _
.cloneDeep(param
.default);
349 switch (param
.type
[0]) {
352 format
= param
.type
[0];
363 if (name
=== 'limit') {
366 if (name
=== 'debug') {
369 if (name
=== 'values') {
370 defaultVal
= defaultValues(defaultVal
);
372 $scope
.$bindToRoute({
373 expr
: 'params["' + name
+ '"]',
377 deep
: format
=== 'json'
380 if (typeof objectParams
[name
] !== 'undefined' || name
=== 'groupBy' || name
=== 'select') {
381 $scope
.$watch('params.' + name
, function(values
) {
382 // Remove empty values
383 _
.each(values
, function(clause
, index
) {
384 if (!clause
|| !clause
[0]) {
385 $scope
.params
[name
].splice(index
, 1);
389 $scope
.$watch('controls.' + name
, function(value
) {
391 $timeout(function() {
393 if (name
=== 'groupBy' || name
=== 'select') {
394 $scope
.params
[name
].push(field
);
396 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
397 if (name
=== 'chain') {
398 var num
= $scope
.params
.chain
.length
;
399 defaultOp
[0] = field
;
400 field
= 'name_me_' + num
;
402 $scope
.params
[name
].push([field
, defaultOp
]);
404 $scope
.controls
[name
] = null;
410 $scope
.availableParams
= actionInfo
.params
;
415 function defaultValues(defaultVal
) {
416 _
.each($scope
.fields
, function(field
) {
417 if (field
.required
) {
418 defaultVal
.push([field
.id
, '']);
424 function stringify(value
, trim
) {
425 if (typeof value
=== 'undefined') {
428 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
430 str
= str
.slice(1, -1);
435 function writeCode() {
437 entity
= $scope
.entity
,
438 action
= $scope
.action
,
439 params
= getParams(),
440 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
442 if ($scope
.entity
&& $scope
.action
) {
444 if (action
.slice(0, 3) === 'get') {
445 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
446 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
448 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
449 paramCount
= _
.size(params
),
452 if (isSelectRowCount(params
)) {
453 results
= result
+ 'Count';
457 var js
= "'" + entity
+ "', '" + action
+ "', {";
458 _
.each(params
, function(param
, key
) {
459 js
+= "\n " + key
+ ': ' + stringify(param
) +
460 (++i
< paramCount
? ',' : '');
461 if (key
=== 'checkPermissions') {
462 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
466 if (index
|| index
=== 0) {
467 js
+= ', ' + JSON
.stringify(index
);
469 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
470 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
471 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
472 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
475 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
476 _
.each(params
, function(param
, key
) {
477 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
480 if (index
|| index
=== 0) {
481 code
.php
+= ', ' + phpFormat(index
);
486 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
487 if (isSelectRowCount(params
)) {
488 code
.oop
+= "\n ->count()";
489 } else if (_
.isNumber(index
)) {
490 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
492 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
493 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
495 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
496 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
500 if (!_
.isNumber(index
) && !isSelectRowCount(params
)) {
501 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
505 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
507 _
.each($scope
.code
, function(vals
) {
508 _
.each(vals
.style
, function(style
) {
509 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
515 function formatOOP(entity
, action
, params
, indent
) {
517 newLine
= "\n" + _
.repeat(' ', indent
);
518 if (entity
.substr(0, 7) !== 'Custom_') {
519 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
521 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
523 _
.each(params
, function(param
, key
) {
525 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
526 _
.each(param
, function(item
, index
) {
527 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
528 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
530 } else if (key
=== 'where') {
531 _
.each(param
, function (clause
) {
532 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
533 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
535 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
538 } else if (key
=== 'select') {
540 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
541 code
+= isSelectRowCount(params
) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
542 } else if (key
=== 'chain') {
543 _
.each(param
, function(chain
, name
) {
544 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
545 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
549 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
555 function isInt(value
) {
556 if (_
.isFinite(value
)) {
559 if (!_
.isString(value
)) {
562 return /^-{0,1}\d+$/.test(value
);
565 function formatMeta(resp
) {
567 _
.each(resp
, function(val
, key
) {
568 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
569 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
572 return prettyPrintOne(_
.escape(ret
));
575 $scope
.execute = function() {
576 $scope
.status
= 'warning';
577 $scope
.loading
= true;
578 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
579 params
: angular
.toJson(getParams()),
580 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
583 'X-Requested-With': 'XMLHttpRequest'
585 }).then(function(resp
) {
586 $scope
.loading
= false;
587 $scope
.status
= 'success';
588 $scope
.debug
= debugFormat(resp
.data
);
589 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
591 $scope
.loading
= false;
592 $scope
.status
= 'danger';
593 $scope
.debug
= debugFormat(resp
.data
);
594 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
598 function debugFormat(data
) {
599 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
605 * Format value to look like php code
607 function phpFormat(val
, indent
) {
608 if (typeof val
=== 'undefined') {
611 if (val
=== null || val
=== true || val
=== false) {
612 return JSON
.stringify(val
).toUpperCase();
614 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
616 baseLine
= indent
? indent
.slice(0, -2) : '',
617 newLine
= indent
? '\n' : '',
618 trailingComma
= indent
? ',' : '';
619 if ($.isPlainObject(val
)) {
620 $.each(val
, function(k
, v
) {
621 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
623 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
625 if ($.isArray(val
)) {
626 $.each(val
, function(k
, v
) {
627 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
629 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
631 if (_
.isString(val
) && !_
.contains(val
, "'")) {
632 return "'" + val
+ "'";
634 return JSON
.stringify(val
).replace(/\$/g, '\\$');
637 function fetchMeta() {
638 crmApi4(getMetaParams
)
639 .then(function(data
) {
641 getEntity().actions
= data
.actions
;
647 // Help for an entity with no action selected
648 function showEntityHelp(entityName
) {
649 var entityInfo
= getEntity(entityName
);
650 setHelp($scope
.entity
, {
651 description
: entityInfo
.description
,
652 comment
: entityInfo
.comment
,
657 if (!$scope
.entity
) {
658 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
659 } else if (!actions
.length
&& !getEntity().actions
) {
660 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
667 showEntityHelp($scope
.entity
);
670 // Update route when changing entity
671 $scope
.$watch('entity', function(newVal
, oldVal
) {
672 if (oldVal
!== newVal
) {
673 // Flush actions cache to re-fetch for new entity
675 $location
.url('/explorer/' + newVal
);
679 // Update route when changing actions
680 $scope
.$watch('action', function(newVal
, oldVal
) {
681 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
682 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
684 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
688 $scope
.paramDoc = function(name
) {
689 return docs
.params
[name
];
692 $scope
.executeDoc = function() {
694 description
: ts('Runs API call on the CiviCRM database.'),
695 comment
: ts('Results and debugging info will be displayed below.')
697 if ($scope
.action
=== 'delete') {
698 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
700 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
701 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
706 $scope
.saveDoc = function() {
708 description
: ts('Save API call as a smart group.'),
709 comment
: ts('Allows you to create a SavedSearch containing the WHERE clause of this API call.'),
713 $scope
.$watch('params', writeCode
, true);
714 $scope
.$watch('index', writeCode
);
717 $scope
.save = function() {
721 visibility
: 'User and User Admin Only',
724 entity
: $scope
.entity
,
725 params
: JSON
.parse(angular
.toJson($scope
.params
))
727 model
.params
.version
= 4;
728 delete model
.params
.select
;
729 delete model
.params
.chain
;
730 delete model
.params
.debug
;
731 delete model
.params
.limit
;
732 delete model
.params
.checkPermissions
;
733 var options
= CRM
.utils
.adjustDialogDefaults({
736 title
: ts('Save smart group')
738 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
742 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
743 var ts
= $scope
.ts
= CRM
.ts(),
744 model
= $scope
.model
;
745 $scope
.groupEntityRefParams
= {
748 params
: {is_hidden
: 0, is_active
: 1, 'saved_search_id.api_entity': model
.entity
},
749 extra
: ['saved_search_id', 'description', 'visibility', 'group_type']
753 minimumInputLength
: 0,
754 placeholder
: ts('Select existing group')
757 if (!CRM
.checkPerm('administer reserved groups')) {
758 $scope
.groupEntityRefParams
.api
.params
.is_reserved
= 0;
761 administerReservedGroups
: CRM
.checkPerm('administer reserved groups')
763 $scope
.options
= CRM
.vars
.api4
.groupOptions
;
764 $scope
.$watch('model.id', function(id
) {
766 _
.assign(model
, $('#api-save-search-select-group').select2('data').extra
);
769 $scope
.cancel = function() {
770 dialogService
.cancel('saveSearchDialog');
772 $scope
.save = function() {
773 $('.ui-dialog:visible').block();
774 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
775 group
.description
= model
.description
;
776 group
.visibility
= model
.visibility
;
777 group
.group_type
= model
.group_type
;
778 group
.saved_search_id
= '$id';
780 api_entity
: model
.entity
,
781 api_params
: model
.params
784 savedSearch
.id
= model
.saved_search_id
;
786 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
787 .then(function(result
) {
788 dialogService
.close('saveSearchDialog', result
[0]);
793 angular
.module('api4Explorer').directive('crmApi4Clause', function($timeout
) {
796 data
: '=crmApi4Clause'
798 templateUrl
: '~/api4Explorer/Clause.html',
799 link: function (scope
, element
, attrs
) {
800 var ts
= scope
.ts
= CRM
.ts();
801 scope
.newClause
= '';
802 scope
.conjunctions
= ['AND', 'OR', 'NOT'];
803 scope
.operators
= CRM
.vars
.api4
.operators
;
805 scope
.addGroup = function(op
) {
806 scope
.data
.clauses
.push([op
, []]);
809 scope
.removeGroup = function() {
810 scope
.data
.groupParent
.splice(scope
.data
.groupIndex
, 1);
813 scope
.onSort = function(event
, ui
) {
814 $(element
).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
815 $('.api4-input.form-inline').css('margin-left', '');
818 // Indent clause while dragging between nested groups
819 scope
.onSortOver = function(event
, ui
) {
822 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
824 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
827 scope
.$watch('newClause', function(value
) {
829 $timeout(function() {
831 scope
.data
.clauses
.push([field
, '=', '']);
832 scope
.newClause
= null;
836 scope
.$watch('data.clauses', function(values
) {
837 // Remove empty values
838 _
.each(values
, function(clause
, index
) {
839 if (typeof clause
!== 'undefined' && !clause
[0]) {
840 values
.splice(index
, 1);
842 if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
844 } else if (typeof clause
[1] === 'string' && clause
.length
== 2) {
853 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
856 data
: '=api4ExpValue'
859 link: function (scope
, element
, attrs
, ctrl
) {
860 var ts
= scope
.ts
= CRM
.ts(),
861 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
862 entity
= $routeParams
.api4entity
,
863 action
= scope
.data
.action
|| $routeParams
.api4action
;
865 function destroyWidget() {
866 var $el
= $(element
);
867 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
868 $el
.crmDatepicker('destroy');
870 if ($el
.is('.select2-container + input')) {
871 $el
.crmEntityRef('destroy');
873 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
876 function makeWidget(field
, op
) {
877 var $el
= $(element
),
878 inputType
= field
.input_type
,
879 dataType
= field
.data_type
;
881 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
883 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
884 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
888 if (inputType
=== 'Date') {
889 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
890 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
892 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
893 if (field
.fk_entity
) {
894 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
895 } else if (field
.options
) {
896 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
897 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
899 _
.each(_
.findWhere(data
, {name
: field
.name
}).options
, function(val
, key
) {
900 options
.push({id
: key
, text
: val
});
902 $el
.removeClass('loading').select2({data
: options
, multiple
: multi
});
904 } else if (dataType
=== 'Boolean') {
905 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
906 {id
: 'true', text
: ts('Yes')},
907 {id
: 'false', text
: ts('No')}
910 } else if (dataType
=== 'Integer' && !multi
) {
911 $el
.attr('type', 'number');
915 function loadFieldOptions(entity
) {
916 if (!fieldOptions
[entity
+ action
]) {
917 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
920 where
: [["options", "!=", false]],
921 select
: ["name", "options"]
924 return fieldOptions
[entity
+ action
];
927 // Copied from ng-list but applied conditionally if field is multi-valued
928 var parseList = function(viewValue
) {
929 // If the viewValue is invalid (say required but empty) it will be `undefined`
930 if (_
.isUndefined(viewValue
)) return;
939 _
.each(viewValue
.split(','), function(value
) {
940 if (value
) list
.push(_
.trim(value
));
947 // Copied from ng-list
948 ctrl
.$parsers
.push(parseList
);
949 ctrl
.$formatters
.push(function(value
) {
950 return _
.isArray(value
) ? value
.join(', ') : value
;
953 // Copied from ng-list
954 ctrl
.$isEmpty = function(value
) {
955 return !value
|| !value
.length
;
958 scope
.$watchCollection('data', function(data
) {
960 var field
= getField(data
.field
, entity
, action
);
962 makeWidget(field
, data
.op
);
970 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
973 chain
: '=api4ExpChain',
977 templateUrl
: '~/api4Explorer/Chain.html',
978 link: function (scope
, element
, attrs
) {
979 var ts
= scope
.ts
= CRM
.ts();
981 function changeEntity(newEntity
, oldEntity
) {
982 // When clearing entity remove this chain
987 // Reset action && index
988 if (newEntity
!== oldEntity
) {
989 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
991 if (getEntity(newEntity
).actions
) {
994 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
995 .then(function(data
) {
996 getEntity(data
.entity
).actions
= data
;
997 if (data
.entity
=== scope
.chain
[1][0]) {
1004 function setActions() {
1005 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
1008 // Set default params when choosing action
1009 function changeAction(newAction
, oldAction
) {
1011 // Prepopulate links
1012 if (newAction
&& newAction
!== oldAction
) {
1014 scope
.chain
[1][3] = '';
1015 // Look for links back to main entity
1016 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
1017 if (field
.fk_entity
=== scope
.mainEntity
) {
1018 link
= [field
.name
, '$id'];
1021 // Look for links from main entity
1022 if (!link
&& newAction
!== 'create') {
1023 _
.each(entityFields(scope
.mainEntity
), function(field
) {
1024 if (field
.fk_entity
=== scope
.chain
[1][0]) {
1025 link
= ['id', '$' + field
.name
];
1026 // Since we're specifying the id, set index to getsingle
1027 scope
.chain
[1][3] = '0';
1031 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1032 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1034 else if (link
&& _
.contains(['create'], newAction
)) {
1035 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1037 else if (link
&& _
.contains(['save'], newAction
)) {
1038 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1040 scope
.chain
[1][2] = '{}';
1045 scope
.$watch("chain[1][0]", changeEntity
);
1046 scope
.$watch("chain[1][1]", changeAction
);
1051 function getEntity(entityName
) {
1052 return _
.findWhere(schema
, {name
: entityName
});
1055 function entityFields(entityName
, action
) {
1056 var entity
= getEntity(entityName
);
1057 if (entity
&& action
&& entity
.actions
) {
1058 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1060 return _
.result(entity
, 'fields');
1063 function getField(fieldName
, entity
, action
) {
1064 var fieldNames
= fieldName
.split('.');
1065 return get(entity
, fieldNames
);
1067 function get(entity
, fieldNames
) {
1068 if (fieldNames
.length
=== 1) {
1069 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1071 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1075 var linkName
= fieldNames
.shift(),
1076 entityLinks
= _
.findWhere(links
, {entity
: entity
}).links
,
1077 newEntity
= _
.findWhere(entityLinks
, {alias
: linkName
}).entity
;
1078 return get(newEntity
, fieldNames
);
1082 // Collapsible optgroups for select2
1085 .on('select2-open', function(e
) {
1086 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1088 .off('.collapseOptionGroup')
1089 .addClass('collapsible-optgroups-enabled')
1090 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1091 $(this).parent().toggleClass('optgroup-expanded');
1095 .on('select2-close', function() {
1096 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1099 })(angular
, CRM
.$, CRM
._
);