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')
37 marked
.setOptions({highlight
: prettyPrintOne
});
38 var getMetaParams
= {},
39 objectParams
= {orderBy
: 'ASC', values
: '', defaults
: '', chain
: ['Entity', '', '{}']},
40 docs
= CRM
.vars
.api4
.docs
,
43 $scope
.helpTitle
= '';
44 $scope
.helpContent
= {};
45 $scope
.entity
= $routeParams
.api4entity
;
48 $scope
.status
= 'default';
49 $scope
.loading
= false;
55 {name
: 'oop', label
: ts('OOP Style'), code
: ''},
56 {name
: 'php', label
: ts('Traditional'), code
: ''}
62 {name
: 'js', label
: ts('Single Call'), code
: ''},
63 {name
: 'js2', label
: ts('Batch Calls'), code
: ''}
69 {name
: 'ang', label
: ts('Single Call'), code
: ''},
70 {name
: 'ang2', label
: ts('Batch Calls'), code
: ''}
76 {name
: 'cv', label
: ts('CV'), code
: ''}
81 if (!entities
.length
) {
82 formatForSelect2(schema
, entities
, 'name', ['description']);
91 function ucfirst(str
) {
92 return str
[0].toUpperCase() + str
.slice(1);
95 function lcfirst(str
) {
96 return str
[0].toLowerCase() + str
.slice(1);
99 function pluralize(str
) {
100 switch (str
[str
.length
-1]) {
104 return str
.slice(0, -1) + 'ies';
110 // Turn a flat array into a select2 array
111 function arrayToSelect2(array
) {
113 _
.each(array
, function(item
) {
114 out
.push({id
: item
, text
: item
});
119 // Reformat an existing array of objects for compatibility with select2
120 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
121 _
.each(input
, function(item
) {
122 var id
= (prefix
|| '') + item
[key
];
123 var formatted
= {id
: id
, text
: id
};
125 _
.merge(formatted
, _
.pick(item
, extra
));
127 container
.push(formatted
);
132 function getFieldList(action
) {
134 fieldInfo
= _
.findWhere(getEntity().actions
, {name
: action
}).fields
;
135 formatForSelect2(fieldInfo
, fields
, 'name', ['description', 'required', 'default_value']);
139 function addJoins(fieldList
, addWildcard
) {
140 var fields
= _
.cloneDeep(fieldList
),
141 fks
= _
.findWhere(links
, {entity
: $scope
.entity
}) || {};
142 _
.each(fks
.links
, function(link
) {
143 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
144 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
148 description
: 'Join to ' + link
.entity
,
149 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
156 $scope
.help = function(title
, content
) {
158 $scope
.helpTitle
= helpTitle
;
159 $scope
.helpContent
= helpContent
;
161 $scope
.helpTitle
= title
;
162 $scope
.helpContent
= formatHelp(content
);
166 // Sets the static help text (which gets overridden by mousing over other elements)
167 function setHelp(title
, content
) {
168 $scope
.helpTitle
= helpTitle
= title
;
169 $scope
.helpContent
= helpContent
= formatHelp(content
);
172 // Convert plain-text help to markdown; replace variables and format links
173 function formatHelp(rawContent
) {
174 function formatRefs(see
) {
175 _
.each(see
, function(ref
, idx
) {
176 var match
= ref
.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
178 ref
= '#/explorer/' + match
[1];
180 if (ref
[0] === '\\') {
181 ref
= 'https://github.com/civicrm/civicrm-core/blob/master' + ref
.replace(/\\/i, '/') + '.php
';
183 see[idx] = '<a target
="' + (ref[0] === '#' ? '_self' : '_blank') + '" href
="' + ref + '">' + see[idx] + '</a
>';
186 var formatted = _.cloneDeep(rawContent);
187 if (formatted.description) {
188 formatted.description = marked(formatted.description);
190 if (formatted.comment) {
191 formatted.comment = marked(formatted.comment);
193 formatRefs(formatted.see);
197 $scope.fieldHelp = function(fieldName) {
198 var field = getField(fieldName, $scope.entity, $scope.action);
203 description: field.description,
204 type: field.data_type
206 if (field.default_value) {
207 info.default = field.default_value;
209 if (field.required_if) {
210 info.required_if = field.required_if;
211 } else if (field.required) {
212 info.required = 'true';
217 $scope.fieldList = function(param) {
219 var fields = _.cloneDeep($scope.action === 'getFields
' ? getFieldList($scope.params.action || 'get') : $scope.fields);
220 // Disable fields that are already in use
221 _.each($scope.params[param] || [], function(val) {
222 (_.findWhere(fields, {id: val[0]}) || {}).disabled = true;
224 return {results: fields};
228 $scope.formatSelect2Item = function(row) {
229 return _.escape(row.text) +
230 (row.required ? '<span
class="crm-marker"> *</span
>' : '') +
231 (row.description ? '<div
class="crm-select2-row-description"><p
>' + _.escape(row.description) + '</p></div>' : '');
234 $scope.clearParam = function(name) {
235 $scope.params[name] = $scope.availableParams[name].default;
238 $scope.isSpecial = function(name) {
239 var specialParams = ['select
', 'fields
', 'action
', 'where
', 'values
', 'defaults
', 'orderBy
', 'chain
'];
240 return _.contains(specialParams, name);
243 $scope.selectRowCount = function() {
244 if ($scope.isSelectRowCount()) {
245 $scope.params.select = [];
247 $scope.params.select = ['row_count
'];
249 if ($scope.params.limit == 25) {
250 $scope.params.limit = 0;
255 $scope.isSelectRowCount = function() {
256 return isSelectRowCount($scope.params);
259 function isSelectRowCount(params) {
260 return params && params.select && params.select.length === 1 && params.select[0] === 'row_count
';
263 function getEntity(entityName) {
264 return _.findWhere(schema, {name: entityName || $scope.entity});
267 // Get all params that have been set
268 function getParams() {
270 _.each($scope.params, function(param, key) {
271 if (param != $scope.availableParams[key].default && !(typeof param === 'object
' && _.isEmpty(param))) {
272 if (_.contains($scope.availableParams[key].type, 'array
') && (typeof objectParams[key] === 'undefined')) {
273 params[key] = parseYaml(JSON.parse(angular.toJson(param)));
279 _.each(objectParams, function(defaultVal, key) {
282 _.each(params[key], function(item) {
283 var val = _.cloneDeep(item[1]);
284 // Remove blank items from "chain" array
285 if (_.isArray(val)) {
286 _.eachRight(item[1], function(v, k) {
293 newParam[item[0]] = parseYaml(val);
295 params[key] = newParam;
301 function parseYaml(input) {
302 if (typeof input === 'undefined') {
308 if (_.isObject(input) || _.isArray(input)) {
309 _.each(input, function(item, index) {
310 input[index] = parseYaml(item);
315 var output = (input === '>') ? '>' : jsyaml.safeLoad(input);
316 // We don't want dates parsed to js objects
317 return _
.isDate(output
) ? input
: output
;
323 function selectAction() {
324 $scope
.action
= $routeParams
.api4action
;
325 $scope
.fieldsAndJoins
.length
= 0;
326 $scope
.selectFieldsAndJoins
.length
= 0;
327 if (!actions
.length
) {
328 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
331 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
332 $scope
.fields
= getFieldList($scope
.action
);
333 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
334 $scope
.fieldsAndJoins
= addJoins($scope
.fields
);
335 $scope
.selectFieldsAndJoins
= addJoins($scope
.fields
, true);
337 $scope
.fieldsAndJoins
= $scope
.fields
;
338 $scope
.selectFieldsAndJoins
= _
.cloneDeep($scope
.fields
);
340 $scope
.selectFieldsAndJoins
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
341 _
.each(actionInfo
.params
, function (param
, name
) {
343 defaultVal
= _
.cloneDeep(param
.default);
345 switch (param
.type
[0]) {
348 format
= param
.type
[0];
359 if (name
=== 'limit') {
362 if (name
=== 'debug') {
365 if (name
=== 'values') {
366 defaultVal
= defaultValues(defaultVal
);
368 $scope
.$bindToRoute({
369 expr
: 'params["' + name
+ '"]',
373 deep
: format
=== 'json'
376 if (typeof objectParams
[name
] !== 'undefined') {
377 $scope
.$watch('params.' + name
, function(values
) {
378 // Remove empty values
379 _
.each(values
, function(clause
, index
) {
380 if (!clause
|| !clause
[0]) {
381 $scope
.params
[name
].splice(index
, 1);
385 $scope
.$watch('controls.' + name
, function(value
) {
387 $timeout(function() {
389 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
390 if (name
=== 'chain') {
391 var num
= $scope
.params
.chain
.length
;
392 defaultOp
[0] = field
;
393 field
= 'name_me_' + num
;
395 $scope
.params
[name
].push([field
, defaultOp
]);
396 $scope
.controls
[name
] = null;
402 $scope
.availableParams
= actionInfo
.params
;
407 function defaultValues(defaultVal
) {
408 _
.each($scope
.fields
, function(field
) {
409 if (field
.required
) {
410 defaultVal
.push([field
.id
, '']);
416 function stringify(value
, trim
) {
417 if (typeof value
=== 'undefined') {
420 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
422 str
= str
.slice(1, -1);
427 function writeCode() {
429 entity
= $scope
.entity
,
430 action
= $scope
.action
,
431 params
= getParams(),
432 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
434 if ($scope
.entity
&& $scope
.action
) {
436 if (action
.slice(0, 3) === 'get') {
437 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
438 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
440 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
441 paramCount
= _
.size(params
),
444 if (isSelectRowCount(params
)) {
445 results
= result
+ 'Count';
449 var js
= "'" + entity
+ "', '" + action
+ "', {";
450 _
.each(params
, function(param
, key
) {
451 js
+= "\n " + key
+ ': ' + stringify(param
) +
452 (++i
< paramCount
? ',' : '');
453 if (key
=== 'checkPermissions') {
454 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
458 if (index
|| index
=== 0) {
459 js
+= ', ' + JSON
.stringify(index
);
461 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
462 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
463 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
464 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
467 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
468 _
.each(params
, function(param
, key
) {
469 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
472 if (index
|| index
=== 0) {
473 code
.php
+= ', ' + phpFormat(index
);
478 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
479 if (isSelectRowCount(params
)) {
480 code
.oop
+= "\n ->count()";
481 } else if (_
.isNumber(index
)) {
482 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
484 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
485 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
487 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
488 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
492 if (!_
.isNumber(index
) && !isSelectRowCount(params
)) {
493 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
497 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
499 _
.each($scope
.code
, function(vals
) {
500 _
.each(vals
.style
, function(style
) {
501 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
507 function formatOOP(entity
, action
, params
, indent
) {
509 newLine
= "\n" + _
.repeat(' ', indent
);
510 if (entity
.substr(0, 7) !== 'Custom_') {
511 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '()';
513 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "')";
515 _
.each(params
, function(param
, key
) {
517 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
518 _
.each(param
, function(item
, index
) {
519 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
520 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
522 } else if (key
=== 'where') {
523 _
.each(param
, function (clause
) {
524 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
525 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
527 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
530 } else if (key
=== 'select') {
532 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
533 code
+= isSelectRowCount(params
) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
534 } else if (key
=== 'chain') {
535 _
.each(param
, function(chain
, name
) {
536 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
537 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
541 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
547 function isInt(value
) {
548 if (_
.isFinite(value
)) {
551 if (!_
.isString(value
)) {
554 return /^-{0,1}\d+$/.test(value
);
557 function formatMeta(resp
) {
559 _
.each(resp
, function(val
, key
) {
560 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
561 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
564 return prettyPrintOne(_
.escape(ret
));
567 $scope
.execute = function() {
568 $scope
.status
= 'warning';
569 $scope
.loading
= true;
570 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
571 params
: angular
.toJson(getParams()),
572 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
575 'X-Requested-With': 'XMLHttpRequest'
577 }).then(function(resp
) {
578 $scope
.loading
= false;
579 $scope
.status
= 'success';
580 $scope
.debug
= debugFormat(resp
.data
);
581 $scope
.result
= [formatMeta(resp
.data
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)];
583 $scope
.loading
= false;
584 $scope
.status
= 'danger';
585 $scope
.debug
= debugFormat(resp
.data
);
586 $scope
.result
= [formatMeta(resp
), prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))];
590 function debugFormat(data
) {
591 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
597 * Format value to look like php code
599 function phpFormat(val
, indent
) {
600 if (typeof val
=== 'undefined') {
603 if (val
=== null || val
=== true || val
=== false) {
604 return JSON
.stringify(val
).toUpperCase();
606 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
608 baseLine
= indent
? indent
.slice(0, -2) : '',
609 newLine
= indent
? '\n' : '',
610 trailingComma
= indent
? ',' : '';
611 if ($.isPlainObject(val
)) {
612 $.each(val
, function(k
, v
) {
613 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
615 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
617 if ($.isArray(val
)) {
618 $.each(val
, function(k
, v
) {
619 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
621 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
623 if (_
.isString(val
) && !_
.contains(val
, "'")) {
624 return "'" + val
+ "'";
626 return JSON
.stringify(val
).replace(/\$/g, '\\$');
629 function fetchMeta() {
630 crmApi4(getMetaParams
)
631 .then(function(data
) {
633 getEntity().actions
= data
.actions
;
639 // Help for an entity with no action selected
640 function showEntityHelp(entityName
) {
641 var entityInfo
= getEntity(entityName
);
642 setHelp($scope
.entity
, {
643 description
: entityInfo
.description
,
644 comment
: entityInfo
.comment
,
649 if (!$scope
.entity
) {
650 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
651 } else if (!actions
.length
&& !getEntity().actions
) {
652 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
659 showEntityHelp($scope
.entity
);
662 // Update route when changing entity
663 $scope
.$watch('entity', function(newVal
, oldVal
) {
664 if (oldVal
!== newVal
) {
665 // Flush actions cache to re-fetch for new entity
667 $location
.url('/explorer/' + newVal
);
671 // Update route when changing actions
672 $scope
.$watch('action', function(newVal
, oldVal
) {
673 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
674 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
676 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
680 $scope
.paramDoc = function(name
) {
681 return docs
.params
[name
];
684 $scope
.executeDoc = function() {
686 description
: ts('Runs API call on the CiviCRM database.'),
687 comment
: ts('Results and debugging info will be displayed below.')
689 if ($scope
.action
=== 'delete') {
690 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
692 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
693 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
698 $scope
.saveDoc = function() {
700 description
: ts('Save API call as a smart group.'),
701 comment
: ts('Allows you to create a SavedSearch containing the WHERE clause of this API call.'),
705 $scope
.$watch('params', writeCode
, true);
706 $scope
.$watch('index', writeCode
);
709 $scope
.save = function() {
713 entity
: $scope
.entity
,
714 params
: JSON
.parse(angular
.toJson($scope
.params
))
716 model
.params
.version
= 4;
717 delete model
.params
.select
;
718 delete model
.params
.chain
;
719 delete model
.params
.debug
;
720 delete model
.params
.limit
;
721 delete model
.params
.checkPermissions
;
722 var options
= CRM
.utils
.adjustDialogDefaults({
725 title
: ts('Save smart group')
727 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
731 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
732 var ts
= $scope
.ts
= CRM
.ts(),
733 model
= $scope
.model
;
734 $scope
.$watch('model.id', function(id
) {
736 model
.description
= $('#api-save-search-select-group').select2('data').extra
.description
;
739 $scope
.cancel = function() {
740 dialogService
.cancel('saveSearchDialog');
742 $scope
.save = function() {
743 $('.ui-dialog:visible').block();
744 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
745 group
.description
= model
.description
;
746 group
.saved_search_id
= '$id';
748 api_entity
: model
.entity
,
749 api_params
: model
.params
752 savedSearch
.id
= $('#api-save-search-select-group').select2('data').extra
.saved_search_id
;
754 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
755 .then(function(result
) {
756 dialogService
.close('saveSearchDialog', result
[0]);
761 angular
.module('api4Explorer').directive('crmApi4WhereClause', function($timeout
) {
764 data
: '=crmApi4WhereClause'
766 templateUrl
: '~/api4Explorer/WhereClause.html',
767 link: function (scope
, element
, attrs
) {
768 var ts
= scope
.ts
= CRM
.ts();
769 scope
.newClause
= '';
770 scope
.conjunctions
= ['AND', 'OR', 'NOT'];
771 scope
.operators
= CRM
.vars
.api4
.operators
;
773 scope
.addGroup = function(op
) {
774 scope
.data
.where
.push([op
, []]);
777 scope
.removeGroup = function() {
778 scope
.data
.groupParent
.splice(scope
.data
.groupIndex
, 1);
781 scope
.onSort = function(event
, ui
) {
782 $('.api4-where-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
783 $('.api4-input.form-inline').css('margin-left', '');
786 // Indent clause while dragging between nested groups
787 scope
.onSortOver = function(event
, ui
) {
790 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
792 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
795 scope
.$watch('newClause', function(value
) {
797 $timeout(function() {
799 scope
.data
.where
.push([field
, '=', '']);
800 scope
.newClause
= null;
804 scope
.$watch('data.where', function(values
) {
805 // Remove empty values
806 _
.each(values
, function(clause
, index
) {
807 if (typeof clause
!== 'undefined' && !clause
[0]) {
808 values
.splice(index
, 1);
810 if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
812 } else if (typeof clause
[1] === 'string' && clause
.length
== 2) {
821 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
824 data
: '=api4ExpValue'
827 link: function (scope
, element
, attrs
, ctrl
) {
828 var ts
= scope
.ts
= CRM
.ts(),
829 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
830 entity
= $routeParams
.api4entity
,
831 action
= scope
.data
.action
|| $routeParams
.api4action
;
833 function destroyWidget() {
834 var $el
= $(element
);
835 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
836 $el
.crmDatepicker('destroy');
838 if ($el
.is('.select2-container + input')) {
839 $el
.crmEntityRef('destroy');
841 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
844 function makeWidget(field
, op
) {
845 var $el
= $(element
),
846 inputType
= field
.input_type
,
847 dataType
= field
.data_type
;
849 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
851 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
852 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
856 if (inputType
=== 'Date') {
857 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
858 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
860 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
861 if (field
.fk_entity
) {
862 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
863 } else if (field
.options
) {
864 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
865 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
867 _
.each(_
.findWhere(data
, {name
: field
.name
}).options
, function(val
, key
) {
868 options
.push({id
: key
, text
: val
});
870 $el
.removeClass('loading').select2({data
: options
, multiple
: multi
});
872 } else if (dataType
=== 'Boolean') {
873 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
874 {id
: 'true', text
: ts('Yes')},
875 {id
: 'false', text
: ts('No')}
878 } else if (dataType
=== 'Integer' && !multi
) {
879 $el
.attr('type', 'number');
883 function loadFieldOptions(entity
) {
884 if (!fieldOptions
[entity
+ action
]) {
885 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
888 where
: [["options", "!=", false]],
889 select
: ["name", "options"]
892 return fieldOptions
[entity
+ action
];
895 // Copied from ng-list but applied conditionally if field is multi-valued
896 var parseList = function(viewValue
) {
897 // If the viewValue is invalid (say required but empty) it will be `undefined`
898 if (_
.isUndefined(viewValue
)) return;
907 _
.each(viewValue
.split(','), function(value
) {
908 if (value
) list
.push(_
.trim(value
));
915 // Copied from ng-list
916 ctrl
.$parsers
.push(parseList
);
917 ctrl
.$formatters
.push(function(value
) {
918 return _
.isArray(value
) ? value
.join(', ') : value
;
921 // Copied from ng-list
922 ctrl
.$isEmpty = function(value
) {
923 return !value
|| !value
.length
;
926 scope
.$watchCollection('data', function(data
) {
928 var field
= getField(data
.field
, entity
, action
);
930 makeWidget(field
, data
.op
);
938 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
941 chain
: '=api4ExpChain',
945 templateUrl
: '~/api4Explorer/Chain.html',
946 link: function (scope
, element
, attrs
) {
947 var ts
= scope
.ts
= CRM
.ts();
949 function changeEntity(newEntity
, oldEntity
) {
950 // When clearing entity remove this chain
955 // Reset action && index
956 if (newEntity
!== oldEntity
) {
957 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
959 if (getEntity(newEntity
).actions
) {
962 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
963 .then(function(data
) {
964 getEntity(data
.entity
).actions
= data
;
965 if (data
.entity
=== scope
.chain
[1][0]) {
972 function setActions() {
973 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
976 // Set default params when choosing action
977 function changeAction(newAction
, oldAction
) {
980 if (newAction
&& newAction
!== oldAction
) {
982 scope
.chain
[1][3] = '';
983 // Look for links back to main entity
984 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
985 if (field
.fk_entity
=== scope
.mainEntity
) {
986 link
= [field
.name
, '$id'];
989 // Look for links from main entity
990 if (!link
&& newAction
!== 'create') {
991 _
.each(entityFields(scope
.mainEntity
), function(field
) {
992 if (field
.fk_entity
=== scope
.chain
[1][0]) {
993 link
= ['id', '$' + field
.name
];
994 // Since we're specifying the id, set index to getsingle
995 scope
.chain
[1][3] = '0';
999 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1000 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1002 else if (link
&& _
.contains(['create'], newAction
)) {
1003 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1005 else if (link
&& _
.contains(['save'], newAction
)) {
1006 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1008 scope
.chain
[1][2] = '{}';
1013 scope
.$watch("chain[1][0]", changeEntity
);
1014 scope
.$watch("chain[1][1]", changeAction
);
1019 function getEntity(entityName
) {
1020 return _
.findWhere(schema
, {name
: entityName
});
1023 function entityFields(entityName
, action
) {
1024 var entity
= getEntity(entityName
);
1025 if (entity
&& action
&& entity
.actions
) {
1026 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1028 return _
.result(entity
, 'fields');
1031 function getField(fieldName
, entity
, action
) {
1032 var fieldNames
= fieldName
.split('.');
1033 return get(entity
, fieldNames
);
1035 function get(entity
, fieldNames
) {
1036 if (fieldNames
.length
=== 1) {
1037 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1039 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1043 var linkName
= fieldNames
.shift(),
1044 entityLinks
= _
.findWhere(links
, {entity
: entity
}).links
,
1045 newEntity
= _
.findWhere(entityLinks
, {alias
: linkName
}).entity
;
1046 return get(newEntity
, fieldNames
);
1050 // Collapsible optgroups for select2
1053 .on('select2-open', function(e
) {
1054 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1056 .off('.collapseOptionGroup')
1057 .addClass('collapsible-optgroups-enabled')
1058 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1059 $(this).parent().toggleClass('optgroup-expanded');
1063 .on('select2-close', function() {
1064 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1067 })(angular
, CRM
.$, CRM
._
);