APIv4 - Add shorthand for setCheckPermissions()
[civicrm-core.git] / ang / api4Explorer / Explorer.js
1 (function(angular, $, _, undefined) {
2
3 // Schema metadata
4 var schema = CRM.vars.api4.schema;
5 // FK schema data
6 var links = CRM.vars.api4.links;
7 // Cache list of entities
8 var entities = [];
9 // Cache list of actions
10 var actions = [];
11 // Field options
12 var fieldOptions = {};
13 // Api params
14 var params;
15
16
17 angular.module('api4Explorer').config(function($routeProvider) {
18 $routeProvider.when('/explorer/:api4entity?/:api4action?', {
19 controller: 'Api4Explorer',
20 templateUrl: '~/api4Explorer/Explorer.html',
21 reloadOnSearch: false
22 });
23 });
24
25 angular.module('api4Explorer').controller('Api4Explorer', function($scope, $routeParams, $location, $timeout, $http, crmUiHelp, crmApi4, dialogService) {
26 var ts = $scope.ts = CRM.ts(),
27 ctrl = $scope.$ctrl = this;
28 $scope.entities = entities;
29 $scope.actions = actions;
30 $scope.fields = [];
31 $scope.havingOptions = [];
32 $scope.fieldsAndJoins = [];
33 $scope.fieldsAndJoinsAndFunctions = [];
34 $scope.fieldsAndJoinsAndFunctionsWithSuffixes = [];
35 $scope.fieldsAndJoinsAndFunctionsAndWildcards = [];
36 $scope.availableParams = {};
37 params = $scope.params = {};
38 $scope.index = '';
39 $scope.selectedTab = {result: 'result', code: 'php'};
40 $scope.perm = {
41 accessDebugOutput: CRM.checkPerm('access debug output'),
42 editGroups: CRM.checkPerm('edit groups')
43 };
44 marked.setOptions({highlight: prettyPrintOne});
45 var getMetaParams = {},
46 objectParams = {orderBy: 'ASC', values: '', defaults: '', chain: ['Entity', '', '{}']},
47 docs = CRM.vars.api4.docs,
48 helpTitle = '',
49 helpContent = {};
50 $scope.helpTitle = '';
51 $scope.helpContent = {};
52 $scope.entity = $routeParams.api4entity;
53 $scope.result = [];
54 $scope.debug = null;
55 $scope.status = 'default';
56 $scope.loading = false;
57 $scope.controls = {};
58 $scope.langs = ['php', 'js', 'ang', 'cli'];
59 $scope.joinTypes = [{k: false, v: ts('Optional')}, {k: true, v: ts('Required')}];
60 $scope.code = {
61 php: [
62 {name: 'oop', label: ts('OOP Style'), code: ''},
63 {name: 'php', label: ts('Traditional'), code: ''}
64 ],
65 js: [
66 {name: 'js', label: ts('Single Call'), code: ''},
67 {name: 'js2', label: ts('Batch Calls'), code: ''}
68 ],
69 ang: [
70 {name: 'ang', label: ts('Single Call'), code: ''},
71 {name: 'ang2', label: ts('Batch Calls'), code: ''}
72 ],
73 cli: [
74 {name: 'cv', label: ts('CV'), code: ''}
75 ]
76 };
77
78 if (!entities.length) {
79 formatForSelect2(schema, entities, 'name', ['description', 'icon']);
80 }
81
82 $scope.$bindToRoute({
83 expr: 'index',
84 param: 'index',
85 default: ''
86 });
87
88 function ucfirst(str) {
89 return str[0].toUpperCase() + str.slice(1);
90 }
91
92 function lcfirst(str) {
93 return str[0].toLowerCase() + str.slice(1);
94 }
95
96 function pluralize(str) {
97 var lastLetter = str[str.length - 1],
98 lastTwo = str[str.length - 2] + lastLetter;
99 if (lastLetter === 's' || lastTwo === 'ch') {
100 return str + 'es';
101 }
102 if (lastLetter === 'y' && lastTwo !== 'ey') {
103 return str.slice(0, -1) + 'ies';
104 }
105 return str + 's';
106 }
107
108 // Reformat an existing array of objects for compatibility with select2
109 function formatForSelect2(input, container, key, extra, prefix) {
110 _.each(input, function(item) {
111 var id = (prefix || '') + item[key];
112 var formatted = {id: id, text: id};
113 if (extra) {
114 _.merge(formatted, _.pick(item, extra));
115 }
116 container.push(formatted);
117 });
118 return container;
119 }
120
121 // Replaces contents of fieldList array with current fields formatted for select2
122 function getFieldList(fieldList, action, addPseudoconstant) {
123 var fieldInfo = _.cloneDeep(_.findWhere(getEntity().actions, {name: action}).fields);
124 fieldList.length = 0;
125 if (addPseudoconstant) {
126 addPseudoconstants(fieldInfo, addPseudoconstant);
127 }
128 formatForSelect2(fieldInfo, fieldList, 'name', ['description', 'required', 'default_value']);
129 }
130
131 // Note: this function expects fieldList to be select2-formatted already
132 function addJoins(fieldList, addWildcard, addPseudoconstant) {
133 // Add entities specified by the join param
134 _.each(getExplicitJoins(), function(joinEntity, joinAlias) {
135 var wildCard = addWildcard ? [{id: joinAlias + '.*', text: joinAlias + '.*', 'description': 'All core ' + joinEntity + ' fields'}] : [],
136 joinFields = _.cloneDeep(entityFields(joinEntity));
137 if (joinFields) {
138 if (addPseudoconstant) {
139 addPseudoconstants(joinFields, addPseudoconstant);
140 }
141 fieldList.push({
142 text: joinEntity + ' AS ' + joinAlias,
143 description: 'Explicit join to ' + joinEntity,
144 children: wildCard.concat(formatForSelect2(joinFields, [], 'name', ['description'], joinAlias + '.'))
145 });
146 }
147 });
148 // Add implicit joins based on schema links
149 _.each(links[$scope.entity], function(link) {
150 var linkFields = _.cloneDeep(entityFields(link.entity)),
151 wildCard = addWildcard ? [{id: link.alias + '.*', text: link.alias + '.*', 'description': 'All core ' + link.entity + ' fields'}] : [];
152 if (linkFields) {
153 if (addPseudoconstant) {
154 addPseudoconstants(linkFields, addPseudoconstant);
155 }
156 fieldList.push({
157 text: link.alias,
158 description: 'Implicit join to ' + link.entity,
159 children: wildCard.concat(formatForSelect2(linkFields, [], 'name', ['description'], link.alias + '.'))
160 });
161 }
162 });
163 }
164
165 // Note: this function transforms a raw list a-la getFields; not a select2-formatted list
166 function addPseudoconstants(fieldList, toAdd) {
167 var optionFields = _.filter(fieldList, 'options');
168 _.each(optionFields, function(field) {
169 var pos = _.findIndex(fieldList, {name: field.name}) + 1;
170 _.each(toAdd, function(suffix) {
171 var newField = _.cloneDeep(field);
172 newField.name += ':' + suffix;
173 fieldList.splice(pos, 0, newField);
174 });
175 });
176 }
177
178 $scope.help = function(title, content) {
179 if (!content) {
180 $scope.helpTitle = helpTitle;
181 $scope.helpContent = helpContent;
182 } else {
183 $scope.helpTitle = title;
184 $scope.helpContent = formatHelp(content);
185 }
186 };
187
188 // Sets the static help text (which gets overridden by mousing over other elements)
189 function setHelp(title, content) {
190 $scope.helpTitle = helpTitle = title;
191 $scope.helpContent = helpContent = formatHelp(content);
192 }
193
194 // Convert plain-text help to markdown; replace variables and format links
195 function formatHelp(rawContent) {
196 function formatRefs(see) {
197 _.each(see, function(ref, idx) {
198 var match = ref.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
199 if (match) {
200 ref = '#/explorer/' + match[1];
201 }
202 if (ref[0] === '\\') {
203 ref = 'https://github.com/civicrm/civicrm-core/blob/master' + ref.replace(/\\/i, '/') + '.php';
204 }
205 see[idx] = '<a target="' + (ref[0] === '#' ? '_self' : '_blank') + '" href="' + ref + '">' + see[idx] + '</a>';
206 });
207 }
208 var formatted = _.cloneDeep(rawContent);
209 if (formatted.description) {
210 formatted.description = marked(formatted.description);
211 }
212 if (formatted.comment) {
213 formatted.comment = marked(formatted.comment);
214 }
215 formatRefs(formatted.see);
216 return formatted;
217 }
218
219 $scope.fieldHelp = function(fieldName) {
220 var field = getField(fieldName, $scope.entity, $scope.action);
221 if (!field) {
222 return;
223 }
224 var info = {
225 description: field.description,
226 type: field.data_type
227 };
228 if (field.default_value) {
229 info.default = field.default_value;
230 }
231 if (field.required_if) {
232 info.required_if = field.required_if;
233 } else if (field.required) {
234 info.required = 'true';
235 }
236 return info;
237 };
238
239 // Returns field list for write params (values, defaults)
240 $scope.fieldList = function(param) {
241 return function() {
242 var fields = [];
243 getFieldList(fields, $scope.action === 'getFields' ? ($scope.params.action || 'get') : $scope.action, ['name']);
244 // Disable fields that are already in use
245 _.each($scope.params[param] || [], function(val) {
246 var usedField = val[0].replace(':name', '');
247 (_.findWhere(fields, {id: usedField}) || {}).disabled = true;
248 (_.findWhere(fields, {id: usedField + ':name'}) || {}).disabled = true;
249 });
250 return {results: fields};
251 };
252 };
253
254 $scope.formatSelect2Item = function(row) {
255 return _.escape(row.text) +
256 (row.required ? '<span class="crm-marker"> *</span>' : '') +
257 (row.description ? '<div class="crm-select2-row-description"><p>' + _.escape(row.description) + '</p></div>' : '');
258 };
259
260 $scope.clearParam = function(name, idx) {
261 if (typeof idx === 'undefined') {
262 $scope.params[name] = $scope.availableParams[name].default;
263 } else {
264 $scope.params[name].splice(idx, 1);
265 }
266 };
267
268 // Gets params that should be represented as generic input fields in the explorer
269 // This fn doesn't have to be particularly efficient as its output is cached in one-time bindings
270 $scope.getGenericParams = function(paramType, defaultNull) {
271 // Returns undefined if params are not yet set; one-time bindings will stabilize when this function returns a value
272 if (_.isEmpty($scope.availableParams)) {
273 return;
274 }
275 var specialParams = ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having', 'join'];
276 if ($scope.availableParams.limit && $scope.availableParams.offset) {
277 specialParams.push('limit', 'offset');
278 }
279 return _.transform($scope.availableParams, function(genericParams, param, name) {
280 if (!_.contains(specialParams, name) &&
281 !(typeof paramType !== 'undefined' && !_.contains(paramType, param.type[0])) &&
282 !(typeof defaultNull !== 'undefined' && ((param.default === null) !== defaultNull))
283 ) {
284 genericParams[name] = param;
285 }
286 });
287 };
288
289 $scope.selectRowCount = function() {
290 var index = params.select.indexOf('row_count');
291 if (index < 0) {
292 $scope.params.select.push('row_count');
293 } else {
294 $scope.params.select.splice(index, 1);
295 }
296 };
297
298 $scope.isSelectRowCount = function() {
299 return isSelectRowCount($scope.params);
300 };
301
302 $scope.selectLang = function(lang) {
303 $scope.selectedTab.code = lang;
304 writeCode();
305 };
306
307 function isSelectRowCount(params) {
308 return params && params.select && params.select.indexOf('row_count') >= 0;
309 }
310
311 function getEntity(entityName) {
312 return _.findWhere(schema, {name: entityName || $scope.entity});
313 }
314
315 // Get name of entity given join alias
316 function entityNameFromAlias(alias) {
317 var joins = getExplicitJoins(),
318 entity = $scope.entity,
319 path = alias.split('.');
320 // First check explicit joins
321 if (joins[alias]) {
322 return joins[alias];
323 }
324 // Then lookup implicit links
325 _.each(path, function(node) {
326 entity = _.find(links[entity], {alias: node}).entity;
327 });
328 return entity;
329 }
330
331 // Get all params that have been set
332 function getParams() {
333 var params = {};
334 _.each($scope.params, function(param, key) {
335 if (param != $scope.availableParams[key].default && !(typeof param === 'object' && _.isEmpty(param))) {
336 if (_.contains($scope.availableParams[key].type, 'array') && (typeof objectParams[key] === 'undefined')) {
337 params[key] = parseYaml(JSON.parse(angular.toJson(param)));
338 } else {
339 params[key] = param;
340 }
341 }
342 });
343 _.each(objectParams, function(defaultVal, key) {
344 if (params[key]) {
345 var newParam = {};
346 _.each(params[key], function(item) {
347 var val = _.cloneDeep(item[1]);
348 // Remove blank items from "chain" array
349 if (_.isArray(val)) {
350 _.eachRight(item[1], function(v, k) {
351 if (v) {
352 return false;
353 }
354 val.length--;
355 });
356 }
357 newParam[item[0]] = parseYaml(val);
358 });
359 params[key] = newParam;
360 }
361 });
362 return params;
363 }
364
365 function parseYaml(input) {
366 if (typeof input === 'undefined' || input === '') {
367 return input;
368 }
369 // Return literal quoted string without removing quotes - for the sake of JOIN ON clauses
370 if (_.isString(input) && input[0] === input[input.length - 1] && _.includes(["'", '"'], input[0])) {
371 return input;
372 }
373 if (_.isObject(input) || _.isArray(input)) {
374 _.each(input, function(item, index) {
375 input[index] = parseYaml(item);
376 });
377 return input;
378 }
379 try {
380 var output = (input === '>') ? '>' : jsyaml.safeLoad(input);
381 // We don't want dates parsed to js objects
382 return _.isDate(output) ? input : output;
383 } catch (e) {
384 return input;
385 }
386 }
387
388 this.buildFieldList = function() {
389 var actionInfo = _.findWhere(actions, {id: $scope.action});
390 getFieldList($scope.fields, $scope.action);
391 getFieldList($scope.fieldsAndJoins, $scope.action, ['name']);
392 getFieldList($scope.fieldsAndJoinsAndFunctions, $scope.action);
393 getFieldList($scope.fieldsAndJoinsAndFunctionsWithSuffixes, $scope.action, ['name', 'label']);
394 getFieldList($scope.fieldsAndJoinsAndFunctionsAndWildcards, $scope.action, ['name', 'label']);
395 if (_.contains(['get', 'update', 'delete', 'replace'], $scope.action)) {
396 addJoins($scope.fieldsAndJoins);
397 // SQL functions are supported if HAVING is
398 if (actionInfo.params.having) {
399 var functions = {
400 text: ts('FUNCTION'),
401 description: ts('Calculate result of a SQL function'),
402 children: _.transform(CRM.vars.api4.functions, function(result, fn) {
403 result.push({
404 id: fn.name + '() AS ' + fn.name.toLowerCase(),
405 text: fn.name + '()',
406 description: fn.name + '(' + describeSqlFn(fn.params) + ')'
407 });
408 })
409 };
410 $scope.fieldsAndJoinsAndFunctions.push(functions);
411 $scope.fieldsAndJoinsAndFunctionsWithSuffixes.push(functions);
412 $scope.fieldsAndJoinsAndFunctionsAndWildcards.push(functions);
413 }
414 addJoins($scope.fieldsAndJoinsAndFunctions, true);
415 addJoins($scope.fieldsAndJoinsAndFunctionsWithSuffixes, false, ['name', 'label']);
416 addJoins($scope.fieldsAndJoinsAndFunctionsAndWildcards, true, ['name', 'label']);
417 }
418 $scope.fieldsAndJoinsAndFunctionsAndWildcards.unshift({id: '*', text: '*', 'description': 'All core ' + $scope.entity + ' fields'});
419 };
420
421 function selectAction() {
422 $scope.action = $routeParams.api4action;
423 if (!actions.length) {
424 formatForSelect2(getEntity().actions, actions, 'name', ['description', 'params']);
425 }
426 if ($scope.action) {
427 var actionInfo = _.findWhere(actions, {id: $scope.action});
428 _.each(actionInfo.params, function (param, name) {
429 var format,
430 defaultVal = _.cloneDeep(param.default);
431 if (param.type) {
432 switch (param.type[0]) {
433 case 'int':
434 case 'bool':
435 format = param.type[0];
436 break;
437
438 case 'array':
439 case 'object':
440 format = 'json';
441 break;
442
443 default:
444 format = 'raw';
445 }
446 if (name === 'limit') {
447 defaultVal = 25;
448 }
449 if (name === 'debug') {
450 defaultVal = true;
451 }
452 if (name === 'values') {
453 defaultVal = defaultValues(defaultVal);
454 }
455 if (name === 'loadOptions' && $scope.action === 'getFields') {
456 param.options = [
457 false,
458 true,
459 ['id', 'name', 'label'],
460 ['id', 'name', 'label', 'abbr', 'description', 'color', 'icon']
461 ];
462 format = 'json';
463 defaultVal = false;
464 param.type = ['string'];
465 }
466 $scope.$bindToRoute({
467 expr: 'params["' + name + '"]',
468 param: name,
469 format: format,
470 default: defaultVal,
471 deep: format === 'json'
472 });
473 }
474 if (typeof objectParams[name] !== 'undefined' && name !== 'orderBy') {
475 $scope.$watch('params.' + name, function (values) {
476 // Remove empty values
477 _.each(values, function (clause, index) {
478 if (!clause || !clause[0]) {
479 $scope.clearParam(name, index);
480 }
481 });
482 }, true);
483 }
484 if (name === 'select' && actionInfo.params.having) {
485 $scope.$watchCollection('params.select', function(newSelect) {
486 // Ignore row_count, it can't be used in HAVING clause
487 var select = _.without(newSelect, 'row_count');
488 $scope.havingOptions.length = 0;
489 // An empty select is an implicit *
490 if (!select.length) {
491 select.push('*');
492 }
493 _.each(select, function(item) {
494 var joinEntity,
495 pieces = item.split(' AS '),
496 alias = _.trim(pieces[pieces.length - 1]).replace(':label', ':name');
497 // Expand wildcards
498 if (alias[alias.length - 1] === '*') {
499 if (alias.length > 1) {
500 joinEntity = entityNameFromAlias(alias.slice(0, -2));
501 }
502 var fieldList = _.filter(getEntity(joinEntity).fields, {custom_field_id: null});
503 formatForSelect2(fieldList, $scope.havingOptions, 'name', ['description', 'required', 'default_value'], alias.slice(0, -1));
504 }
505 else {
506 $scope.havingOptions.push({id: alias, text: alias});
507 }
508 });
509 });
510 }
511 if (typeof objectParams[name] !== 'undefined' || name === 'groupBy' || name === 'select' || name === 'join') {
512 $scope.$watch('controls.' + name, function(value) {
513 var field = value;
514 $timeout(function() {
515 if (field) {
516 if (name === 'join') {
517 $scope.params[name].push([field + ' AS ' + _.snakeCase(field), false]);
518 ctrl.buildFieldList();
519 }
520 else if (typeof objectParams[name] === 'undefined') {
521 $scope.params[name].push(field);
522 } else {
523 var defaultOp = _.cloneDeep(objectParams[name]);
524 if (name === 'chain') {
525 var num = $scope.params.chain.length;
526 defaultOp[0] = field;
527 field = 'name_me_' + num;
528 }
529 $scope.params[name].push([field, defaultOp]);
530 }
531 $scope.controls[name] = null;
532 }
533 });
534 });
535 }
536 });
537 ctrl.buildFieldList();
538 $scope.availableParams = actionInfo.params;
539 }
540 writeCode();
541 }
542
543 function describeSqlFn(params) {
544 var desc = ' ';
545 _.each(params, function(param) {
546 desc += ' ';
547 if (param.prefix) {
548 desc += _.filter(param.prefix).join('|') + ' ';
549 }
550 if (param.expr === 1) {
551 desc += 'expr ';
552 } else if (param.expr > 1) {
553 desc += 'expr, ... ';
554 }
555 if (param.suffix) {
556 desc += ' ' + _.filter(param.suffix).join('|') + ' ';
557 }
558 });
559 return desc.replace(/[ ]+/g, ' ');
560 }
561
562 function defaultValues(defaultVal) {
563 _.each($scope.fields, function(field) {
564 if (field.required) {
565 defaultVal.push([field.id, '']);
566 }
567 });
568 return defaultVal;
569 }
570
571 function stringify(value, trim) {
572 if (typeof value === 'undefined') {
573 return '';
574 }
575 var str = JSON.stringify(value).replace(/,/g, ', ');
576 if (trim) {
577 str = str.slice(1, -1);
578 }
579 return str.trim();
580 }
581
582 function writeCode() {
583 var code = {},
584 entity = $scope.entity,
585 action = $scope.action,
586 params = getParams(),
587 index = isInt($scope.index) ? +$scope.index : parseYaml($scope.index),
588 result = 'result';
589 if ($scope.entity && $scope.action) {
590 delete params.debug;
591 if (action.slice(0, 3) === 'get') {
592 result = entity.substr(0, 7) === 'Custom_' ? _.camelCase(entity.substr(7)) : entity;
593 result = lcfirst(action.replace(/s$/, '').slice(3) || result);
594 }
595 var results = lcfirst(_.isNumber(index) ? result : pluralize(result)),
596 paramCount = _.size(params),
597 i = 0;
598
599 switch ($scope.selectedTab.code) {
600 case 'js':
601 case 'ang':
602 // Write javascript
603 var js = "'" + entity + "', '" + action + "', {";
604 _.each(params, function(param, key) {
605 js += "\n " + key + ': ' + stringify(param) +
606 (++i < paramCount ? ',' : '');
607 if (key === 'checkPermissions') {
608 js += ' // IGNORED: permissions are always enforced from client-side requests';
609 }
610 });
611 js += "\n}";
612 if (index || index === 0) {
613 js += ', ' + JSON.stringify(index);
614 }
615 code.js = "CRM.api4(" + js + ").then(function(" + results + ") {\n // do something with " + results + " array\n}, function(failure) {\n // handle failure\n});";
616 code.js2 = "CRM.api4({" + results + ': [' + js + "]}).then(function(batch) {\n // do something with batch." + results + " array\n}, function(failure) {\n // handle failure\n});";
617 code.ang = "crmApi4(" + js + ").then(function(" + results + ") {\n // do something with " + results + " array\n}, function(failure) {\n // handle failure\n});";
618 code.ang2 = "crmApi4({" + results + ': [' + js + "]}).then(function(batch) {\n // do something with batch." + results + " array\n}, function(failure) {\n // handle failure\n});";
619 break;
620
621 case 'php':
622 // Write php code
623 code.php = '$' + results + " = civicrm_api4('" + entity + "', '" + action + "', [";
624 _.each(params, function(param, key) {
625 code.php += "\n '" + key + "' => " + phpFormat(param, 4) + ',';
626 });
627 code.php += "\n]";
628 if (index || index === 0) {
629 code.php += ', ' + phpFormat(index);
630 }
631 code.php += ");";
632
633 // Write oop code
634 code.oop = '$' + results + " = " + formatOOP(entity, action, params, 2) + "\n ->execute()";
635 if (_.isNumber(index)) {
636 code.oop += !index ? '\n ->first()' : (index === -1 ? '\n ->last()' : '\n ->itemAt(' + index + ')');
637 } else if (index) {
638 if (_.isString(index) || (_.isPlainObject(index) && !index[0] && !index['0'])) {
639 code.oop += "\n ->indexBy('" + (_.isPlainObject(index) ? _.keys(index)[0] : index) + "')";
640 }
641 if (_.isArray(index) || _.isPlainObject(index)) {
642 code.oop += "\n ->column('" + (_.isArray(index) ? index[0] : _.values(index)[0]) + "')";
643 }
644 }
645 code.oop += ";\n";
646 if (!_.isNumber(index)) {
647 code.oop += "foreach ($" + results + ' as $' + ((_.isString(index) && index) ? index + ' => $' : '') + result + ') {\n // do something\n}';
648 }
649 break;
650
651 case 'cli':
652 // Write cli code
653 code.cv = 'cv api4 ' + entity + '.' + action + " '" + stringify(params) + "'";
654 }
655 }
656 _.each($scope.code, function(vals) {
657 _.each(vals, function(style) {
658 style.code = code[style.name] ? prettyPrintOne(code[style.name]) : '';
659 });
660 });
661 }
662
663 // Format oop params
664 function formatOOP(entity, action, params, indent) {
665 var code = '',
666 newLine = "\n" + _.repeat(' ', indent),
667 perm = params.checkPermissions === false ? 'FALSE' : '';
668 if (entity.substr(0, 7) !== 'Custom_') {
669 code = "\\Civi\\Api4\\" + entity + '::' + action + '(' + perm + ')';
670 } else {
671 code = "\\Civi\\Api4\\CustomValue::" + action + "('" + entity.substr(7) + "'" + (perm ? ', ' : '') + perm + ")";
672 }
673 _.each(params, function(param, key) {
674 var val = '';
675 if (typeof objectParams[key] !== 'undefined' && key !== 'chain') {
676 _.each(param, function(item, index) {
677 val = phpFormat(index) + ', ' + phpFormat(item, 2 + indent);
678 code += newLine + "->add" + ucfirst(key).replace(/s$/, '') + '(' + val + ')';
679 });
680 } else if (key === 'where') {
681 _.each(param, function (clause) {
682 if (clause[0] === 'AND' || clause[0] === 'OR' || clause[0] === 'NOT') {
683 code += newLine + "->addClause(" + phpFormat(clause[0]) + ", " + phpFormat(clause[1]).slice(1, -1) + ')';
684 } else {
685 code += newLine + "->addWhere(" + phpFormat(clause).slice(1, -1) + ")";
686 }
687 });
688 } else if (key === 'select') {
689 // selectRowCount() is a shortcut for addSelect('row_count')
690 if (isSelectRowCount(params)) {
691 code += newLine + '->selectRowCount()';
692 param = _.without(param, 'row_count');
693 }
694 // addSelect() is a variadic function & can take multiple arguments
695 if (param.length) {
696 code += newLine + '->addSelect(' + phpFormat(param).slice(1, -1) + ')';
697 }
698 } else if (key === 'chain') {
699 _.each(param, function(chain, name) {
700 code += newLine + "->addChain('" + name + "', " + formatOOP(chain[0], chain[1], chain[2], 2 + indent);
701 code += (chain.length > 3 ? ',' : '') + (!_.isEmpty(chain[2]) ? newLine : ' ') + (chain.length > 3 ? phpFormat(chain[3]) : '') + ')';
702 });
703 }
704 else if (key !== 'checkPermissions') {
705 code += newLine + "->set" + ucfirst(key) + '(' + phpFormat(param, 2 + indent) + ')';
706 }
707 });
708 return code;
709 }
710
711 function isInt(value) {
712 if (_.isFinite(value)) {
713 return true;
714 }
715 if (!_.isString(value)) {
716 return false;
717 }
718 return /^-{0,1}\d+$/.test(value);
719 }
720
721 function formatMeta(resp) {
722 var ret = '';
723 _.each(resp, function(val, key) {
724 if (key !== 'values' && !_.isPlainObject(val) && !_.isFunction(val)) {
725 ret += (ret.length ? ', ' : '') + key + ': ' + (_.isArray(val) ? '[' + val + ']' : val);
726 }
727 });
728 return prettyPrintOne(_.escape(ret));
729 }
730
731 $scope.execute = function() {
732 $scope.status = 'info';
733 $scope.loading = true;
734 $http.post(CRM.url('civicrm/ajax/api4/' + $scope.entity + '/' + $scope.action, {
735 params: angular.toJson(getParams()),
736 index: isInt($scope.index) ? +$scope.index : parseYaml($scope.index)
737 }), null, {
738 headers: {
739 'X-Requested-With': 'XMLHttpRequest'
740 }
741 }).then(function(resp) {
742 $scope.loading = false;
743 $scope.status = resp.data && resp.data.debug && resp.data.debug.log ? 'warning' : 'success';
744 $scope.debug = debugFormat(resp.data);
745 $scope.result = [
746 formatMeta(resp.data),
747 prettyPrintOne('(' + resp.data.values.length + ') ' + _.escape(JSON.stringify(resp.data.values, null, 2)), 'js', 1)
748 ];
749 }, function(resp) {
750 $scope.loading = false;
751 $scope.status = 'danger';
752 $scope.debug = debugFormat(resp.data);
753 $scope.result = [
754 formatMeta(resp),
755 prettyPrintOne(_.escape(JSON.stringify(resp.data, null, 2)))
756 ];
757 });
758 };
759
760 function debugFormat(data) {
761 var debug = data.debug ? prettyPrintOne(_.escape(JSON.stringify(data.debug, null, 2)).replace(/\\n/g, "\n")) : null;
762 delete data.debug;
763 return debug;
764 }
765
766 /**
767 * Format value to look like php code
768 */
769 function phpFormat(val, indent) {
770 if (typeof val === 'undefined') {
771 return '';
772 }
773 if (val === null || val === true || val === false) {
774 return JSON.stringify(val).toUpperCase();
775 }
776 indent = (typeof indent === 'number') ? _.repeat(' ', indent) : (indent || '');
777 var ret = '',
778 baseLine = indent ? indent.slice(0, -2) : '',
779 newLine = indent ? '\n' : '',
780 trailingComma = indent ? ',' : '';
781 if ($.isPlainObject(val)) {
782 $.each(val, function(k, v) {
783 ret += (ret ? ', ' : '') + newLine + indent + "'" + k + "' => " + phpFormat(v);
784 });
785 return '[' + ret + trailingComma + newLine + baseLine + ']';
786 }
787 if ($.isArray(val)) {
788 $.each(val, function(k, v) {
789 ret += (ret ? ', ' : '') + newLine + indent + phpFormat(v);
790 });
791 return '[' + ret + trailingComma + newLine + baseLine + ']';
792 }
793 if (_.isString(val) && !_.contains(val, "'")) {
794 return "'" + val + "'";
795 }
796 return JSON.stringify(val).replace(/\$/g, '\\$');
797 }
798
799 function fetchMeta() {
800 crmApi4(getMetaParams)
801 .then(function(data) {
802 if (data.actions) {
803 getEntity().actions = data.actions;
804 selectAction();
805 }
806 });
807 }
808
809 // Help for an entity with no action selected
810 function showEntityHelp(entityName) {
811 var entityInfo = getEntity(entityName);
812 setHelp($scope.entity, {
813 description: entityInfo.description,
814 comment: entityInfo.comment,
815 see: entityInfo.see
816 });
817 }
818
819 if (!$scope.entity) {
820 setHelp(ts('APIv4 Explorer'), {description: docs.description, comment: docs.comment, see: docs.see});
821 } else if (!actions.length && !getEntity().actions) {
822 getMetaParams.actions = [$scope.entity, 'getActions', {chain: {fields: [$scope.entity, 'getFields', {action: '$name'}]}}];
823 fetchMeta();
824 } else {
825 selectAction();
826 }
827
828 if ($scope.entity) {
829 showEntityHelp($scope.entity);
830 }
831
832 // Update route when changing entity
833 $scope.$watch('entity', function(newVal, oldVal) {
834 if (oldVal !== newVal) {
835 // Flush actions cache to re-fetch for new entity
836 actions = [];
837 $location.url('/explorer/' + newVal);
838 }
839 });
840
841 // Update route when changing actions
842 $scope.$watch('action', function(newVal, oldVal) {
843 if ($scope.entity && $routeParams.api4action !== newVal && !_.isUndefined(newVal)) {
844 $location.url('/explorer/' + $scope.entity + '/' + newVal);
845 } else if (newVal) {
846 setHelp($scope.entity + '::' + newVal, _.pick(_.findWhere(getEntity().actions, {name: newVal}), ['description', 'comment', 'see']));
847 }
848 });
849
850 $scope.paramDoc = function(name) {
851 return docs.params[name];
852 };
853
854 $scope.executeDoc = function() {
855 var doc = {
856 description: ts('Runs API call on the CiviCRM database.'),
857 comment: ts('Results and debugging info will be displayed below.')
858 };
859 if ($scope.action === 'delete') {
860 doc.WARNING = ts('This API call will be executed on the real database. Deleting data cannot be undone.');
861 }
862 else if ($scope.action && $scope.action.slice(0, 3) !== 'get') {
863 doc.WARNING = ts('This API call will be executed on the real database. It cannot be undone.');
864 }
865 return doc;
866 };
867
868 $scope.saveDoc = function() {
869 return {
870 description: ts('Save API call as a smart group.'),
871 comment: ts('Create a SavedSearch using these API params to populate a smart group.') +
872 '\n\n' + ts('NOTE: you must select contact id as the only field.')
873 };
874 };
875
876 $scope.$watch('params', writeCode, true);
877 $scope.$watch('index', writeCode);
878 writeCode();
879
880 $scope.save = function() {
881 $scope.params.limit = $scope.params.offset = 0;
882 if ($scope.params.chain.length) {
883 CRM.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires: 5000});
884 return;
885 }
886 if ($scope.params.select.length !== 1 || !_.includes($scope.params.select[0], 'id')) {
887 CRM.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires: 5000});
888 return;
889 }
890 var model = {
891 title: '',
892 description: '',
893 visibility: 'User and User Admin Only',
894 group_type: [],
895 id: null,
896 entity: $scope.entity,
897 params: JSON.parse(angular.toJson($scope.params))
898 };
899 model.params.version = 4;
900 delete model.params.chain;
901 delete model.params.debug;
902 delete model.params.limit;
903 delete model.params.offset;
904 delete model.params.orderBy;
905 delete model.params.checkPermissions;
906 var options = CRM.utils.adjustDialogDefaults({
907 width: '500px',
908 autoOpen: false,
909 title: ts('Save smart group')
910 });
911 dialogService.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model, options);
912 };
913 });
914
915 angular.module('api4Explorer').controller('SaveSearchCtrl', function($scope, crmApi4, dialogService) {
916 var ts = $scope.ts = CRM.ts(),
917 model = $scope.model;
918 $scope.groupEntityRefParams = {
919 entity: 'Group',
920 api: {
921 params: {is_hidden: 0, is_active: 1, 'saved_search_id.api_entity': model.entity},
922 extra: ['saved_search_id', 'description', 'visibility', 'group_type']
923 },
924 select: {
925 allowClear: true,
926 minimumInputLength: 0,
927 placeholder: ts('Select existing group')
928 }
929 };
930 if (!CRM.checkPerm('administer reserved groups')) {
931 $scope.groupEntityRefParams.api.params.is_reserved = 0;
932 }
933 $scope.perm = {
934 administerReservedGroups: CRM.checkPerm('administer reserved groups')
935 };
936 $scope.options = CRM.vars.api4.groupOptions;
937 $scope.$watch('model.id', function(id) {
938 if (id) {
939 _.assign(model, $('#api-save-search-select-group').select2('data').extra);
940 }
941 });
942 $scope.cancel = function() {
943 dialogService.cancel('saveSearchDialog');
944 };
945 $scope.save = function() {
946 $('.ui-dialog:visible').block();
947 var group = model.id ? {id: model.id} : {title: model.title};
948 group.description = model.description;
949 group.visibility = model.visibility;
950 group.group_type = model.group_type;
951 group.saved_search_id = '$id';
952 var savedSearch = {
953 api_entity: model.entity,
954 api_params: model.params
955 };
956 if (group.id) {
957 savedSearch.id = model.saved_search_id;
958 }
959 crmApi4('SavedSearch', 'save', {records: [savedSearch], chain: {group: ['Group', 'save', {'records': [group]}]}})
960 .then(function(result) {
961 dialogService.close('saveSearchDialog', result[0]);
962 });
963 };
964 });
965
966 angular.module('api4Explorer').directive('crmApi4Clause', function() {
967 return {
968 scope: {
969 data: '<crmApi4Clause'
970 },
971 templateUrl: '~/api4Explorer/Clause.html',
972 controller: function ($scope, $element, $timeout) {
973 var ts = $scope.ts = CRM.ts(),
974 ctrl = $scope.$ctrl = this;
975 this.conjunctions = {AND: ts('And'), OR: ts('Or'), NOT: ts('Not')};
976 this.operators = CRM.vars.api4.operators;
977 this.sortOptions = {
978 axis: 'y',
979 connectWith: '.api4-clause-group-sortable',
980 containment: $element.closest('.api4-clause-fieldset'),
981 over: onSortOver,
982 start: onSort,
983 stop: onSort
984 };
985
986 this.addGroup = function(op) {
987 $scope.data.clauses.push([op, []]);
988 };
989
990 this.removeGroup = function() {
991 $scope.data.groupParent.splice($scope.data.groupIndex, 1);
992 };
993
994 function onSort(event, ui) {
995 $($element).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event.type === 'sortstart');
996 $('.api4-input.form-inline').css('margin-left', '');
997 }
998
999 // Indent clause while dragging between nested groups
1000 function onSortOver(event, ui) {
1001 var offset = 0;
1002 if (ui.sender) {
1003 offset = $(ui.placeholder).offset().left - $(ui.sender).offset().left;
1004 }
1005 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset + 'px');
1006 }
1007
1008 this.addClause = function() {
1009 $timeout(function() {
1010 if (ctrl.newClause) {
1011 $scope.data.clauses.push([ctrl.newClause, '=', '']);
1012 ctrl.newClause = null;
1013 }
1014 });
1015 };
1016 $scope.$watch('data.clauses', function(values) {
1017 // Iterate in reverse order so index doesn't get out-of-sync during splice
1018 _.forEachRight(values, function(clause, index) {
1019 // Remove empty values
1020 if (index >= ($scope.data.skip || 0)) {
1021 if (typeof clause !== 'undefined' && !clause[0]) {
1022 values.splice(index, 1);
1023 }
1024 // Add/remove value if operator allows for one
1025 else if (typeof clause[1] === 'string' && _.contains(clause[1], 'NULL')) {
1026 clause.length = 2;
1027 } else if (typeof clause[1] === 'string' && clause.length === 2) {
1028 clause.push('');
1029 }
1030 }
1031 });
1032 }, true);
1033 }
1034 };
1035 });
1036
1037 angular.module('api4Explorer').directive('api4ExpValue', function($routeParams, crmApi4) {
1038 return {
1039 scope: {
1040 data: '=api4ExpValue'
1041 },
1042 require: 'ngModel',
1043 link: function (scope, element, attrs, ctrl) {
1044 var ts = scope.ts = CRM.ts(),
1045 multi = _.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope.data.op),
1046 entity = $routeParams.api4entity,
1047 action = scope.data.action || $routeParams.api4action;
1048
1049 function destroyWidget() {
1050 var $el = $(element);
1051 if ($el.is('.crm-form-date-wrapper .crm-hidden-date')) {
1052 $el.crmDatepicker('destroy');
1053 }
1054 if ($el.is('.select2-container + input')) {
1055 $el.crmEntityRef('destroy');
1056 }
1057 $(element).removeData().removeAttr('type').removeAttr('placeholder').show();
1058 }
1059
1060 function makeWidget(field, op) {
1061 var $el = $(element),
1062 inputType = field.input_type,
1063 dataType = field.data_type;
1064 if (!op) {
1065 op = field.serialize || dataType === 'Array' ? 'IN' : '=';
1066 }
1067 multi = _.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op);
1068 if (op === 'IS NULL' || op === 'IS NOT NULL') {
1069 $el.hide();
1070 return;
1071 }
1072 if (inputType === 'Date') {
1073 if (_.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op)) {
1074 $el.crmDatepicker({time: (field.input_attrs && field.input_attrs.time) || false});
1075 }
1076 } else if (_.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op) && (field.fk_entity || field.options || dataType === 'Boolean')) {
1077 if (field.options) {
1078 var id = field.pseudoconstant || 'id';
1079 $el.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple: multi, data: [{id: '', text: ''}]});
1080 loadFieldOptions(field.entity || entity).then(function(data) {
1081 var options = _.transform(data[field.name].options, function(options, opt) {
1082 options.push({id: opt[id], text: opt.label, description: opt.description, color: opt.color, icon: opt.icon});
1083 }, []);
1084 $el.removeClass('loading').crmSelect2({data: options, multiple: multi});
1085 });
1086 } else if (field.fk_entity) {
1087 $el.crmEntityRef({entity: field.fk_entity, select:{multiple: multi}});
1088 } else if (dataType === 'Boolean') {
1089 $el.attr('placeholder', ts('- select -')).crmSelect2({allowClear: false, multiple: multi, placeholder: ts('- select -'), data: [
1090 {id: 'true', text: ts('Yes')},
1091 {id: 'false', text: ts('No')}
1092 ]});
1093 }
1094 } else if (dataType === 'Integer' && !multi) {
1095 $el.attr('type', 'number');
1096 }
1097 }
1098
1099 function loadFieldOptions(entity) {
1100 if (!fieldOptions[entity + action]) {
1101 fieldOptions[entity + action] = crmApi4(entity, 'getFields', {
1102 loadOptions: ['id', 'name', 'label', 'description', 'color', 'icon'],
1103 action: action,
1104 where: [['options', '!=', false]],
1105 select: ['options']
1106 }, 'name');
1107 }
1108 return fieldOptions[entity + action];
1109 }
1110
1111 // Copied from ng-list but applied conditionally if field is multi-valued
1112 var parseList = function(viewValue) {
1113 // If the viewValue is invalid (say required but empty) it will be `undefined`
1114 if (_.isUndefined(viewValue)) return;
1115
1116 if (!multi) {
1117 return viewValue;
1118 }
1119
1120 var list = [];
1121
1122 if (viewValue) {
1123 _.each(viewValue.split(','), function(value) {
1124 if (value) list.push(_.trim(value));
1125 });
1126 }
1127
1128 return list;
1129 };
1130
1131 // Copied from ng-list
1132 ctrl.$parsers.push(parseList);
1133 ctrl.$formatters.push(function(value) {
1134 return _.isArray(value) ? value.join(', ') : value;
1135 });
1136
1137 // Copied from ng-list
1138 ctrl.$isEmpty = function(value) {
1139 return !value || !value.length;
1140 };
1141
1142 scope.$watchCollection('data', function(data) {
1143 destroyWidget();
1144 var field = getField(data.field, entity, action);
1145 if (field && data.format !== 'plain') {
1146 makeWidget(field, data.op);
1147 }
1148 });
1149 }
1150 };
1151 });
1152
1153
1154 angular.module('api4Explorer').directive('api4ExpChain', function(crmApi4) {
1155 return {
1156 scope: {
1157 chain: '=api4ExpChain',
1158 mainEntity: '=',
1159 entities: '='
1160 },
1161 templateUrl: '~/api4Explorer/Chain.html',
1162 link: function (scope, element, attrs) {
1163 var ts = scope.ts = CRM.ts();
1164
1165 function changeEntity(newEntity, oldEntity) {
1166 // When clearing entity remove this chain
1167 if (!newEntity) {
1168 scope.chain[0] = '';
1169 return;
1170 }
1171 // Reset action && index
1172 if (newEntity !== oldEntity) {
1173 scope.chain[1][1] = scope.chain[1][2] = '';
1174 }
1175 if (getEntity(newEntity).actions) {
1176 setActions();
1177 } else {
1178 crmApi4(newEntity, 'getActions', {chain: {fields: [newEntity, 'getFields', {action: '$name'}]}})
1179 .then(function(data) {
1180 getEntity(data.entity).actions = data;
1181 if (data.entity === scope.chain[1][0]) {
1182 setActions();
1183 }
1184 });
1185 }
1186 }
1187
1188 function setActions() {
1189 scope.actions = [''].concat(_.pluck(getEntity(scope.chain[1][0]).actions, 'name'));
1190 }
1191
1192 // Set default params when choosing action
1193 function changeAction(newAction, oldAction) {
1194 var link;
1195 // Prepopulate links
1196 if (newAction && newAction !== oldAction) {
1197 // Clear index
1198 scope.chain[1][3] = '';
1199 // Look for links back to main entity
1200 _.each(entityFields(scope.chain[1][0]), function(field) {
1201 if (field.fk_entity === scope.mainEntity) {
1202 link = [field.name, '$id'];
1203 }
1204 });
1205 // Look for links from main entity
1206 if (!link && newAction !== 'create') {
1207 _.each(entityFields(scope.mainEntity), function(field) {
1208 if (field.fk_entity === scope.chain[1][0]) {
1209 link = ['id', '$' + field.name];
1210 // Since we're specifying the id, set index to getsingle
1211 scope.chain[1][3] = '0';
1212 }
1213 });
1214 }
1215 if (link && _.contains(['get', 'update', 'replace', 'delete'], newAction)) {
1216 scope.chain[1][2] = '{where: [[' + link[0] + ', =, ' + link[1] + ']]}';
1217 }
1218 else if (link && _.contains(['create'], newAction)) {
1219 scope.chain[1][2] = '{values: {' + link[0] + ': ' + link[1] + '}}';
1220 }
1221 else if (link && _.contains(['save'], newAction)) {
1222 scope.chain[1][2] = '{records: [{' + link[0] + ': ' + link[1] + '}]}';
1223 } else {
1224 scope.chain[1][2] = '{}';
1225 }
1226 }
1227 }
1228
1229 scope.$watch("chain[1][0]", changeEntity);
1230 scope.$watch("chain[1][1]", changeAction);
1231 }
1232 };
1233 });
1234
1235 function getEntity(entityName) {
1236 return _.findWhere(schema, {name: entityName});
1237 }
1238
1239 function entityFields(entityName, action) {
1240 var entity = getEntity(entityName);
1241 if (entity && action && entity.actions) {
1242 return _.findWhere(entity.actions, {name: action}).fields;
1243 }
1244 return _.result(entity, 'fields');
1245 }
1246
1247 function getExplicitJoins() {
1248 return _.transform(params.join, function(joins, join) {
1249 var j = join[0].split(' AS '),
1250 joinEntity = _.trim(j[0]),
1251 joinAlias = _.trim(j[1]) || joinEntity.toLowerCase();
1252 joins[joinAlias] = joinEntity;
1253 }, {});
1254 }
1255
1256 function getField(fieldName, entity, action) {
1257 var suffix = fieldName.split(':')[1];
1258 fieldName = fieldName.split(':')[0];
1259 var fieldNames = fieldName.split('.');
1260 var field = get(entity, fieldNames);
1261 if (field && suffix) {
1262 field.pseudoconstant = suffix;
1263 }
1264 return field;
1265
1266 function get(entity, fieldNames) {
1267 if (fieldNames.length === 1) {
1268 return _.findWhere(entityFields(entity, action), {name: fieldNames[0]});
1269 }
1270 var comboName = _.findWhere(entityFields(entity, action), {name: fieldNames[0] + '.' + fieldNames[1]});
1271 if (comboName) {
1272 return comboName;
1273 }
1274 var linkName = fieldNames.shift(),
1275 newEntity = getExplicitJoins()[linkName] || _.findWhere(links[entity], {alias: linkName}).entity;
1276 return get(newEntity, fieldNames);
1277 }
1278 }
1279
1280 // Collapsible optgroups for select2
1281 $(function() {
1282 $('body')
1283 .on('select2-open', function(e) {
1284 if ($(e.target).hasClass('collapsible-optgroups')) {
1285 $('#select2-drop')
1286 .off('.collapseOptionGroup')
1287 .addClass('collapsible-optgroups-enabled')
1288 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1289 $(this).parent().toggleClass('optgroup-expanded');
1290 });
1291 }
1292 })
1293 .on('select2-close', function() {
1294 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1295 });
1296 });
1297 })(angular, CRM.$, CRM._);