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
'];
241 return _.contains(specialParams, name);
244 $scope.selectRowCount = function() {
245 if ($scope.isSelectRowCount()) {
246 $scope.params.select = [];
248 $scope.params.select = ['row_count
'];
250 if ($scope.params.limit == 25) {
251 $scope.params.limit = 0;
256 $scope.isSelectRowCount = function() {
257 return isSelectRowCount($scope.params);
260 function isSelectRowCount(params) {
261 return params && params.select && params.select.length === 1 && params.select[0] === 'row_count
';
264 function getEntity(entityName) {
265 return _.findWhere(schema, {name: entityName || $scope.entity});
268 // Get all params that have been set
269 function getParams() {
271 _.each($scope.params, function(param, key) {
272 if (param != $scope.availableParams[key].default && !(typeof param === 'object
' && _.isEmpty(param))) {
273 if (_.contains($scope.availableParams[key].type, 'array
') && (typeof objectParams[key] === 'undefined')) {
274 params[key] = parseYaml(JSON.parse(angular.toJson(param)));
280 _.each(objectParams, function(defaultVal, key) {
283 _.each(params[key], function(item) {
284 var val = _.cloneDeep(item[1]);
285 // Remove blank items from "chain" array
286 if (_.isArray(val)) {
287 _.eachRight(item[1], function(v, k) {
294 newParam[item[0]] = parseYaml(val);
296 params[key] = newParam;
302 function parseYaml(input) {
303 if (typeof input === 'undefined') {
309 if (_.isObject(input) || _.isArray(input)) {
310 _.each(input, function(item, index) {
311 input[index] = parseYaml(item);
316 var output = (input === '>') ? '>' : jsyaml.safeLoad(input);
317 // We don't want dates parsed to js objects
318 return _
.isDate(output
) ? input
: output
;
324 function selectAction() {
325 $scope
.action
= $routeParams
.api4action
;
326 $scope
.fieldsAndJoins
.length
= 0;
327 $scope
.selectFieldsAndJoins
.length
= 0;
328 if (!actions
.length
) {
329 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
332 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
333 $scope
.fields
= getFieldList($scope
.action
);
334 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
335 $scope
.fieldsAndJoins
= addJoins($scope
.fields
);
336 $scope
.selectFieldsAndJoins
= addJoins($scope
.fields
, true);
338 $scope
.fieldsAndJoins
= $scope
.fields
;
339 $scope
.selectFieldsAndJoins
= _
.cloneDeep($scope
.fields
);
341 $scope
.selectFieldsAndJoins
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
342 _
.each(actionInfo
.params
, function (param
, name
) {
344 defaultVal
= _
.cloneDeep(param
.default);
346 switch (param
.type
[0]) {
349 format
= param
.type
[0];
360 if (name
=== 'limit') {
363 if (name
=== 'debug') {
366 if (name
=== 'values') {
367 defaultVal
= defaultValues(defaultVal
);
369 $scope
.$bindToRoute({
370 expr
: 'params["' + name
+ '"]',
374 deep
: format
=== 'json'
377 if (typeof objectParams
[name
] !== 'undefined') {
378 $scope
.$watch('params.' + name
, function(values
) {
379 // Remove empty values
380 _
.each(values
, function(clause
, index
) {
381 if (!clause
|| !clause
[0]) {
382 $scope
.params
[name
].splice(index
, 1);
386 $scope
.$watch('controls.' + name
, function(value
) {
388 $timeout(function() {
390 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
391 if (name
=== 'chain') {
392 var num
= $scope
.params
.chain
.length
;
393 defaultOp
[0] = field
;
394 field
= 'name_me_' + num
;
396 $scope
.params
[name
].push([field
, defaultOp
]);
397 $scope
.controls
[name
] = null;
403 $scope
.availableParams
= actionInfo
.params
;
408 function defaultValues(defaultVal
) {
409 _
.each($scope
.fields
, function(field
) {
410 if (field
.required
) {
411 defaultVal
.push([field
.id
, '']);
417 function stringify(value
, trim
) {
418 if (typeof value
=== 'undefined') {
421 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
423 str
= str
.slice(1, -1);
428 function writeCode() {
430 entity
= $scope
.entity
,
431 action
= $scope
.action
,
432 params
= getParams(),
433 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
435 if ($scope
.entity
&& $scope
.action
) {
437 if (action
.slice(0, 3) === 'get') {
438 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
439 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
441 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
442 paramCount
= _
.size(params
),
445 if (isSelectRowCount(params
)) {
446 results
= result
+ 'Count';
450 var js
= "'" + entity
+ "', '" + action
+ "', {";
451 _
.each(params
, function(param
, key
) {
452 js
+= "\n " + key
+ ': ' + stringify(param
) +
453 (++i
< paramCount
? ',' : '');
454 if (key
=== 'checkPermissions') {
455 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
459 if (index
|| index
=== 0) {
460 js
+= ', ' + JSON
.stringify(index
);
462 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
463 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
464 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
465 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
468 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
469 _
.each(params
, function(param
, key
) {
470 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
473 if (index
|| index
=== 0) {
474 code
.php
+= ', ' + phpFormat(index
);
479 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
480 if (isSelectRowCount(params
)) {
481 code
.oop
+= "\n ->count()";
482 } else if (_
.isNumber(index
)) {
483 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
485 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
486 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
488 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
489 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
493 if (!_
.isNumber(index
) && !isSelectRowCount(params
)) {
494 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
498 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
500 _
.each($scope
.code
, function(vals
) {
501 _
.each(vals
.style
, function(style
) {
502 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
508 function formatOOP(entity
, action
, params
, indent
) {
510 newLine
= "\n" + _
.repeat(' ', indent
);
511 if (entity
.substr(0, 7) !== 'Custom_') {
512 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
514 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
516 _
.each(params
, function(param
, key
) {
518 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
519 _
.each(param
, function(item
, index
) {
520 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
521 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
523 } else if (key
=== 'where') {
524 _
.each(param
, function (clause
) {
525 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
526 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
528 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
531 } else if (key
=== 'select') {
533 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
534 code
+= isSelectRowCount(params
) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
535 } else if (key
=== 'chain') {
536 _
.each(param
, function(chain
, name
) {
537 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
538 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
542 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
548 function isInt(value
) {
549 if (_
.isFinite(value
)) {
552 if (!_
.isString(value
)) {
555 return /^-{0,1}\d+$/.test(value
);
558 function formatMeta(resp
) {
560 _
.each(resp
, function(val
, key
) {
561 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
562 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
565 return prettyPrintOne(_
.escape(ret
));
568 $scope
.execute = function() {
569 $scope
.status
= 'warning';
570 $scope
.loading
= true;
571 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
572 params
: angular
.toJson(getParams()),
573 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
576 'X-Requested-With': 'XMLHttpRequest'
578 }).then(function(resp
) {
579 $scope
.loading
= false;
580 $scope
.status
= 'success';
581 $scope
.debug
= debugFormat(resp
.data
);
582 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
584 $scope
.loading
= false;
585 $scope
.status
= 'danger';
586 $scope
.debug
= debugFormat(resp
.data
);
587 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
591 function debugFormat(data
) {
592 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
598 * Format value to look like php code
600 function phpFormat(val
, indent
) {
601 if (typeof val
=== 'undefined') {
604 if (val
=== null || val
=== true || val
=== false) {
605 return JSON
.stringify(val
).toUpperCase();
607 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
609 baseLine
= indent
? indent
.slice(0, -2) : '',
610 newLine
= indent
? '\n' : '',
611 trailingComma
= indent
? ',' : '';
612 if ($.isPlainObject(val
)) {
613 $.each(val
, function(k
, v
) {
614 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
616 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
618 if ($.isArray(val
)) {
619 $.each(val
, function(k
, v
) {
620 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
622 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
624 if (_
.isString(val
) && !_
.contains(val
, "'")) {
625 return "'" + val
+ "'";
627 return JSON
.stringify(val
).replace(/\$/g, '\\$');
630 function fetchMeta() {
631 crmApi4(getMetaParams
)
632 .then(function(data
) {
634 getEntity().actions
= data
.actions
;
640 // Help for an entity with no action selected
641 function showEntityHelp(entityName
) {
642 var entityInfo
= getEntity(entityName
);
643 setHelp($scope
.entity
, {
644 description
: entityInfo
.description
,
645 comment
: entityInfo
.comment
,
650 if (!$scope
.entity
) {
651 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
652 } else if (!actions
.length
&& !getEntity().actions
) {
653 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
660 showEntityHelp($scope
.entity
);
663 // Update route when changing entity
664 $scope
.$watch('entity', function(newVal
, oldVal
) {
665 if (oldVal
!== newVal
) {
666 // Flush actions cache to re-fetch for new entity
668 $location
.url('/explorer/' + newVal
);
672 // Update route when changing actions
673 $scope
.$watch('action', function(newVal
, oldVal
) {
674 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
675 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
677 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
681 $scope
.paramDoc = function(name
) {
682 return docs
.params
[name
];
685 $scope
.executeDoc = function() {
687 description
: ts('Runs API call on the CiviCRM database.'),
688 comment
: ts('Results and debugging info will be displayed below.')
690 if ($scope
.action
=== 'delete') {
691 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
693 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
694 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
699 $scope
.saveDoc = function() {
701 description
: ts('Save API call as a smart group.'),
702 comment
: ts('Allows you to create a SavedSearch containing the WHERE clause of this API call.'),
706 $scope
.$watch('params', writeCode
, true);
707 $scope
.$watch('index', writeCode
);
710 $scope
.save = function() {
714 visibility
: 'User and User Admin Only',
717 entity
: $scope
.entity
,
718 params
: JSON
.parse(angular
.toJson($scope
.params
))
720 model
.params
.version
= 4;
721 delete model
.params
.select
;
722 delete model
.params
.chain
;
723 delete model
.params
.debug
;
724 delete model
.params
.limit
;
725 delete model
.params
.checkPermissions
;
726 var options
= CRM
.utils
.adjustDialogDefaults({
729 title
: ts('Save smart group')
731 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
735 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
736 var ts
= $scope
.ts
= CRM
.ts(),
737 model
= $scope
.model
;
738 $scope
.groupEntityRefParams
= {
741 params
: {is_hidden
: 0, is_active
: 1, 'saved_search_id.api_entity': model
.entity
},
742 extra
: ['saved_search_id', 'description', 'visibility', 'group_type']
746 minimumInputLength
: 0,
747 placeholder
: ts('Select existing group')
750 if (!CRM
.checkPerm('administer reserved groups')) {
751 $scope
.groupEntityRefParams
.api
.params
.is_reserved
= 0;
754 administerReservedGroups
: CRM
.checkPerm('administer reserved groups')
756 $scope
.options
= CRM
.vars
.api4
.groupOptions
;
757 $scope
.$watch('model.id', function(id
) {
759 _
.assign(model
, $('#api-save-search-select-group').select2('data').extra
);
762 $scope
.cancel = function() {
763 dialogService
.cancel('saveSearchDialog');
765 $scope
.save = function() {
766 $('.ui-dialog:visible').block();
767 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
768 group
.description
= model
.description
;
769 group
.visibility
= model
.visibility
;
770 group
.group_type
= model
.group_type
;
771 group
.saved_search_id
= '$id';
773 api_entity
: model
.entity
,
774 api_params
: model
.params
777 savedSearch
.id
= model
.saved_search_id
;
779 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
780 .then(function(result
) {
781 dialogService
.close('saveSearchDialog', result
[0]);
786 angular
.module('api4Explorer').directive('crmApi4WhereClause', function($timeout
) {
789 data
: '=crmApi4WhereClause'
791 templateUrl
: '~/api4Explorer/WhereClause.html',
792 link: function (scope
, element
, attrs
) {
793 var ts
= scope
.ts
= CRM
.ts();
794 scope
.newClause
= '';
795 scope
.conjunctions
= ['AND', 'OR', 'NOT'];
796 scope
.operators
= CRM
.vars
.api4
.operators
;
798 scope
.addGroup = function(op
) {
799 scope
.data
.where
.push([op
, []]);
802 scope
.removeGroup = function() {
803 scope
.data
.groupParent
.splice(scope
.data
.groupIndex
, 1);
806 scope
.onSort = function(event
, ui
) {
807 $('.api4-where-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
808 $('.api4-input.form-inline').css('margin-left', '');
811 // Indent clause while dragging between nested groups
812 scope
.onSortOver = function(event
, ui
) {
815 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
817 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
820 scope
.$watch('newClause', function(value
) {
822 $timeout(function() {
824 scope
.data
.where
.push([field
, '=', '']);
825 scope
.newClause
= null;
829 scope
.$watch('data.where', function(values
) {
830 // Remove empty values
831 _
.each(values
, function(clause
, index
) {
832 if (typeof clause
!== 'undefined' && !clause
[0]) {
833 values
.splice(index
, 1);
835 if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
837 } else if (typeof clause
[1] === 'string' && clause
.length
== 2) {
846 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
849 data
: '=api4ExpValue'
852 link: function (scope
, element
, attrs
, ctrl
) {
853 var ts
= scope
.ts
= CRM
.ts(),
854 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
855 entity
= $routeParams
.api4entity
,
856 action
= scope
.data
.action
|| $routeParams
.api4action
;
858 function destroyWidget() {
859 var $el
= $(element
);
860 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
861 $el
.crmDatepicker('destroy');
863 if ($el
.is('.select2-container + input')) {
864 $el
.crmEntityRef('destroy');
866 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
869 function makeWidget(field
, op
) {
870 var $el
= $(element
),
871 inputType
= field
.input_type
,
872 dataType
= field
.data_type
;
874 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
876 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
877 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
881 if (inputType
=== 'Date') {
882 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
883 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
885 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
886 if (field
.fk_entity
) {
887 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
888 } else if (field
.options
) {
889 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
890 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
892 _
.each(_
.findWhere(data
, {name
: field
.name
}).options
, function(val
, key
) {
893 options
.push({id
: key
, text
: val
});
895 $el
.removeClass('loading').select2({data
: options
, multiple
: multi
});
897 } else if (dataType
=== 'Boolean') {
898 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
899 {id
: 'true', text
: ts('Yes')},
900 {id
: 'false', text
: ts('No')}
903 } else if (dataType
=== 'Integer' && !multi
) {
904 $el
.attr('type', 'number');
908 function loadFieldOptions(entity
) {
909 if (!fieldOptions
[entity
+ action
]) {
910 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
913 where
: [["options", "!=", false]],
914 select
: ["name", "options"]
917 return fieldOptions
[entity
+ action
];
920 // Copied from ng-list but applied conditionally if field is multi-valued
921 var parseList = function(viewValue
) {
922 // If the viewValue is invalid (say required but empty) it will be `undefined`
923 if (_
.isUndefined(viewValue
)) return;
932 _
.each(viewValue
.split(','), function(value
) {
933 if (value
) list
.push(_
.trim(value
));
940 // Copied from ng-list
941 ctrl
.$parsers
.push(parseList
);
942 ctrl
.$formatters
.push(function(value
) {
943 return _
.isArray(value
) ? value
.join(', ') : value
;
946 // Copied from ng-list
947 ctrl
.$isEmpty = function(value
) {
948 return !value
|| !value
.length
;
951 scope
.$watchCollection('data', function(data
) {
953 var field
= getField(data
.field
, entity
, action
);
955 makeWidget(field
, data
.op
);
963 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
966 chain
: '=api4ExpChain',
970 templateUrl
: '~/api4Explorer/Chain.html',
971 link: function (scope
, element
, attrs
) {
972 var ts
= scope
.ts
= CRM
.ts();
974 function changeEntity(newEntity
, oldEntity
) {
975 // When clearing entity remove this chain
980 // Reset action && index
981 if (newEntity
!== oldEntity
) {
982 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
984 if (getEntity(newEntity
).actions
) {
987 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
988 .then(function(data
) {
989 getEntity(data
.entity
).actions
= data
;
990 if (data
.entity
=== scope
.chain
[1][0]) {
997 function setActions() {
998 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
1001 // Set default params when choosing action
1002 function changeAction(newAction
, oldAction
) {
1004 // Prepopulate links
1005 if (newAction
&& newAction
!== oldAction
) {
1007 scope
.chain
[1][3] = '';
1008 // Look for links back to main entity
1009 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
1010 if (field
.fk_entity
=== scope
.mainEntity
) {
1011 link
= [field
.name
, '$id'];
1014 // Look for links from main entity
1015 if (!link
&& newAction
!== 'create') {
1016 _
.each(entityFields(scope
.mainEntity
), function(field
) {
1017 if (field
.fk_entity
=== scope
.chain
[1][0]) {
1018 link
= ['id', '$' + field
.name
];
1019 // Since we're specifying the id, set index to getsingle
1020 scope
.chain
[1][3] = '0';
1024 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1025 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1027 else if (link
&& _
.contains(['create'], newAction
)) {
1028 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1030 else if (link
&& _
.contains(['save'], newAction
)) {
1031 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1033 scope
.chain
[1][2] = '{}';
1038 scope
.$watch("chain[1][0]", changeEntity
);
1039 scope
.$watch("chain[1][1]", changeAction
);
1044 function getEntity(entityName
) {
1045 return _
.findWhere(schema
, {name
: entityName
});
1048 function entityFields(entityName
, action
) {
1049 var entity
= getEntity(entityName
);
1050 if (entity
&& action
&& entity
.actions
) {
1051 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1053 return _
.result(entity
, 'fields');
1056 function getField(fieldName
, entity
, action
) {
1057 var fieldNames
= fieldName
.split('.');
1058 return get(entity
, fieldNames
);
1060 function get(entity
, fieldNames
) {
1061 if (fieldNames
.length
=== 1) {
1062 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1064 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1068 var linkName
= fieldNames
.shift(),
1069 entityLinks
= _
.findWhere(links
, {entity
: entity
}).links
,
1070 newEntity
= _
.findWhere(entityLinks
, {alias
: linkName
}).entity
;
1071 return get(newEntity
, fieldNames
);
1075 // Collapsible optgroups for select2
1078 .on('select2-open', function(e
) {
1079 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1081 .off('.collapseOptionGroup')
1082 .addClass('collapsible-optgroups-enabled')
1083 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1084 $(this).parent().toggleClass('optgroup-expanded');
1088 .on('select2-close', function() {
1089 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1092 })(angular
, CRM
.$, CRM
._
);