Merge pull request #17843 from civicrm/5.28
[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 if (entity.substr(0, 7) !== 'Custom_') {
668 code = "\\Civi\\Api4\\" + entity + '::' + action + '()';
669 } else {
670 code = "\\Civi\\Api4\\CustomValue::" + action + "('" + entity.substr(7) + "')";
671 }
672 _.each(params, function(param, key) {
673 var val = '';
674 if (typeof objectParams[key] !== 'undefined' && key !== 'chain') {
675 _.each(param, function(item, index) {
676 val = phpFormat(index) + ', ' + phpFormat(item, 2 + indent);
677 code += newLine + "->add" + ucfirst(key).replace(/s$/, '') + '(' + val + ')';
678 });
679 } else if (key === 'where') {
680 _.each(param, function (clause) {
681 if (clause[0] === 'AND' || clause[0] === 'OR' || clause[0] === 'NOT') {
682 code += newLine + "->addClause(" + phpFormat(clause[0]) + ", " + phpFormat(clause[1]).slice(1, -1) + ')';
683 } else {
684 code += newLine + "->addWhere(" + phpFormat(clause).slice(1, -1) + ")";
685 }
686 });
687 } else if (key === 'select') {
688 // selectRowCount() is a shortcut for addSelect('row_count')
689 if (isSelectRowCount(params)) {
690 code += newLine + '->selectRowCount()';
691 param = _.without(param, 'row_count');
692 }
693 // addSelect() is a variadic function & can take multiple arguments
694 if (param.length) {
695 code += newLine + '->addSelect(' + phpFormat(param).slice(1, -1) + ')';
696 }
697 } else if (key === 'chain') {
698 _.each(param, function(chain, name) {
699 code += newLine + "->addChain('" + name + "', " + formatOOP(chain[0], chain[1], chain[2], 2 + indent);
700 code += (chain.length > 3 ? ',' : '') + (!_.isEmpty(chain[2]) ? newLine : ' ') + (chain.length > 3 ? phpFormat(chain[3]) : '') + ')';
701 });
702 }
703 else {
704 code += newLine + "->set" + ucfirst(key) + '(' + phpFormat(param, 2 + indent) + ')';
705 }
706 });
707 return code;
708 }
709
710 function isInt(value) {
711 if (_.isFinite(value)) {
712 return true;
713 }
714 if (!_.isString(value)) {
715 return false;
716 }
717 return /^-{0,1}\d+$/.test(value);
718 }
719
720 function formatMeta(resp) {
721 var ret = '';
722 _.each(resp, function(val, key) {
723 if (key !== 'values' && !_.isPlainObject(val) && !_.isFunction(val)) {
724 ret += (ret.length ? ', ' : '') + key + ': ' + (_.isArray(val) ? '[' + val + ']' : val);
725 }
726 });
727 return prettyPrintOne(_.escape(ret));
728 }
729
730 $scope.execute = function() {
731 $scope.status = 'info';
732 $scope.loading = true;
733 $http.post(CRM.url('civicrm/ajax/api4/' + $scope.entity + '/' + $scope.action, {
734 params: angular.toJson(getParams()),
735 index: isInt($scope.index) ? +$scope.index : parseYaml($scope.index)
736 }), null, {
737 headers: {
738 'X-Requested-With': 'XMLHttpRequest'
739 }
740 }).then(function(resp) {
741 $scope.loading = false;
742 $scope.status = resp.data && resp.data.debug && resp.data.debug.log ? 'warning' : 'success';
743 $scope.debug = debugFormat(resp.data);
744 $scope.result = [
745 formatMeta(resp.data),
746 prettyPrintOne('(' + resp.data.values.length + ') ' + _.escape(JSON.stringify(resp.data.values, null, 2)), 'js', 1)
747 ];
748 }, function(resp) {
749 $scope.loading = false;
750 $scope.status = 'danger';
751 $scope.debug = debugFormat(resp.data);
752 $scope.result = [
753 formatMeta(resp),
754 prettyPrintOne(_.escape(JSON.stringify(resp.data, null, 2)))
755 ];
756 });
757 };
758
759 function debugFormat(data) {
760 var debug = data.debug ? prettyPrintOne(_.escape(JSON.stringify(data.debug, null, 2)).replace(/\\n/g, "\n")) : null;
761 delete data.debug;
762 return debug;
763 }
764
765 /**
766 * Format value to look like php code
767 */
768 function phpFormat(val, indent) {
769 if (typeof val === 'undefined') {
770 return '';
771 }
772 if (val === null || val === true || val === false) {
773 return JSON.stringify(val).toUpperCase();
774 }
775 indent = (typeof indent === 'number') ? _.repeat(' ', indent) : (indent || '');
776 var ret = '',
777 baseLine = indent ? indent.slice(0, -2) : '',
778 newLine = indent ? '\n' : '',
779 trailingComma = indent ? ',' : '';
780 if ($.isPlainObject(val)) {
781 $.each(val, function(k, v) {
782 ret += (ret ? ', ' : '') + newLine + indent + "'" + k + "' => " + phpFormat(v);
783 });
784 return '[' + ret + trailingComma + newLine + baseLine + ']';
785 }
786 if ($.isArray(val)) {
787 $.each(val, function(k, v) {
788 ret += (ret ? ', ' : '') + newLine + indent + phpFormat(v);
789 });
790 return '[' + ret + trailingComma + newLine + baseLine + ']';
791 }
792 if (_.isString(val) && !_.contains(val, "'")) {
793 return "'" + val + "'";
794 }
795 return JSON.stringify(val).replace(/\$/g, '\\$');
796 }
797
798 function fetchMeta() {
799 crmApi4(getMetaParams)
800 .then(function(data) {
801 if (data.actions) {
802 getEntity().actions = data.actions;
803 selectAction();
804 }
805 });
806 }
807
808 // Help for an entity with no action selected
809 function showEntityHelp(entityName) {
810 var entityInfo = getEntity(entityName);
811 setHelp($scope.entity, {
812 description: entityInfo.description,
813 comment: entityInfo.comment,
814 see: entityInfo.see
815 });
816 }
817
818 if (!$scope.entity) {
819 setHelp(ts('APIv4 Explorer'), {description: docs.description, comment: docs.comment, see: docs.see});
820 } else if (!actions.length && !getEntity().actions) {
821 getMetaParams.actions = [$scope.entity, 'getActions', {chain: {fields: [$scope.entity, 'getFields', {action: '$name'}]}}];
822 fetchMeta();
823 } else {
824 selectAction();
825 }
826
827 if ($scope.entity) {
828 showEntityHelp($scope.entity);
829 }
830
831 // Update route when changing entity
832 $scope.$watch('entity', function(newVal, oldVal) {
833 if (oldVal !== newVal) {
834 // Flush actions cache to re-fetch for new entity
835 actions = [];
836 $location.url('/explorer/' + newVal);
837 }
838 });
839
840 // Update route when changing actions
841 $scope.$watch('action', function(newVal, oldVal) {
842 if ($scope.entity && $routeParams.api4action !== newVal && !_.isUndefined(newVal)) {
843 $location.url('/explorer/' + $scope.entity + '/' + newVal);
844 } else if (newVal) {
845 setHelp($scope.entity + '::' + newVal, _.pick(_.findWhere(getEntity().actions, {name: newVal}), ['description', 'comment', 'see']));
846 }
847 });
848
849 $scope.paramDoc = function(name) {
850 return docs.params[name];
851 };
852
853 $scope.executeDoc = function() {
854 var doc = {
855 description: ts('Runs API call on the CiviCRM database.'),
856 comment: ts('Results and debugging info will be displayed below.')
857 };
858 if ($scope.action === 'delete') {
859 doc.WARNING = ts('This API call will be executed on the real database. Deleting data cannot be undone.');
860 }
861 else if ($scope.action && $scope.action.slice(0, 3) !== 'get') {
862 doc.WARNING = ts('This API call will be executed on the real database. It cannot be undone.');
863 }
864 return doc;
865 };
866
867 $scope.saveDoc = function() {
868 return {
869 description: ts('Save API call as a smart group.'),
870 comment: ts('Create a SavedSearch using these API params to populate a smart group.') +
871 '\n\n' + ts('NOTE: you must select contact id as the only field.')
872 };
873 };
874
875 $scope.$watch('params', writeCode, true);
876 $scope.$watch('index', writeCode);
877 writeCode();
878
879 $scope.save = function() {
880 $scope.params.limit = $scope.params.offset = 0;
881 if ($scope.params.chain.length) {
882 CRM.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires: 5000});
883 return;
884 }
885 if ($scope.params.select.length !== 1 || !_.includes($scope.params.select[0], 'id')) {
886 CRM.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires: 5000});
887 return;
888 }
889 var model = {
890 title: '',
891 description: '',
892 visibility: 'User and User Admin Only',
893 group_type: [],
894 id: null,
895 entity: $scope.entity,
896 params: JSON.parse(angular.toJson($scope.params))
897 };
898 model.params.version = 4;
899 delete model.params.chain;
900 delete model.params.debug;
901 delete model.params.limit;
902 delete model.params.offset;
903 delete model.params.orderBy;
904 delete model.params.checkPermissions;
905 var options = CRM.utils.adjustDialogDefaults({
906 width: '500px',
907 autoOpen: false,
908 title: ts('Save smart group')
909 });
910 dialogService.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model, options);
911 };
912 });
913
914 angular.module('api4Explorer').controller('SaveSearchCtrl', function($scope, crmApi4, dialogService) {
915 var ts = $scope.ts = CRM.ts(),
916 model = $scope.model;
917 $scope.groupEntityRefParams = {
918 entity: 'Group',
919 api: {
920 params: {is_hidden: 0, is_active: 1, 'saved_search_id.api_entity': model.entity},
921 extra: ['saved_search_id', 'description', 'visibility', 'group_type']
922 },
923 select: {
924 allowClear: true,
925 minimumInputLength: 0,
926 placeholder: ts('Select existing group')
927 }
928 };
929 if (!CRM.checkPerm('administer reserved groups')) {
930 $scope.groupEntityRefParams.api.params.is_reserved = 0;
931 }
932 $scope.perm = {
933 administerReservedGroups: CRM.checkPerm('administer reserved groups')
934 };
935 $scope.options = CRM.vars.api4.groupOptions;
936 $scope.$watch('model.id', function(id) {
937 if (id) {
938 _.assign(model, $('#api-save-search-select-group').select2('data').extra);
939 }
940 });
941 $scope.cancel = function() {
942 dialogService.cancel('saveSearchDialog');
943 };
944 $scope.save = function() {
945 $('.ui-dialog:visible').block();
946 var group = model.id ? {id: model.id} : {title: model.title};
947 group.description = model.description;
948 group.visibility = model.visibility;
949 group.group_type = model.group_type;
950 group.saved_search_id = '$id';
951 var savedSearch = {
952 api_entity: model.entity,
953 api_params: model.params
954 };
955 if (group.id) {
956 savedSearch.id = model.saved_search_id;
957 }
958 crmApi4('SavedSearch', 'save', {records: [savedSearch], chain: {group: ['Group', 'save', {'records': [group]}]}})
959 .then(function(result) {
960 dialogService.close('saveSearchDialog', result[0]);
961 });
962 };
963 });
964
965 angular.module('api4Explorer').directive('crmApi4Clause', function() {
966 return {
967 scope: {
968 data: '<crmApi4Clause'
969 },
970 templateUrl: '~/api4Explorer/Clause.html',
971 controller: function ($scope, $element, $timeout) {
972 var ts = $scope.ts = CRM.ts(),
973 ctrl = $scope.$ctrl = this;
974 this.conjunctions = {AND: ts('And'), OR: ts('Or'), NOT: ts('Not')};
975 this.operators = CRM.vars.api4.operators;
976 this.sortOptions = {
977 axis: 'y',
978 connectWith: '.api4-clause-group-sortable',
979 containment: $element.closest('.api4-clause-fieldset'),
980 over: onSortOver,
981 start: onSort,
982 stop: onSort
983 };
984
985 this.addGroup = function(op) {
986 $scope.data.clauses.push([op, []]);
987 };
988
989 this.removeGroup = function() {
990 $scope.data.groupParent.splice($scope.data.groupIndex, 1);
991 };
992
993 function onSort(event, ui) {
994 $($element).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event.type === 'sortstart');
995 $('.api4-input.form-inline').css('margin-left', '');
996 }
997
998 // Indent clause while dragging between nested groups
999 function onSortOver(event, ui) {
1000 var offset = 0;
1001 if (ui.sender) {
1002 offset = $(ui.placeholder).offset().left - $(ui.sender).offset().left;
1003 }
1004 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset + 'px');
1005 }
1006
1007 this.addClause = function() {
1008 $timeout(function() {
1009 if (ctrl.newClause) {
1010 $scope.data.clauses.push([ctrl.newClause, '=', '']);
1011 ctrl.newClause = null;
1012 }
1013 });
1014 };
1015 $scope.$watch('data.clauses', function(values) {
1016 // Iterate in reverse order so index doesn't get out-of-sync during splice
1017 _.forEachRight(values, function(clause, index) {
1018 // Remove empty values
1019 if (index >= ($scope.data.skip || 0)) {
1020 if (typeof clause !== 'undefined' && !clause[0]) {
1021 values.splice(index, 1);
1022 }
1023 // Add/remove value if operator allows for one
1024 else if (typeof clause[1] === 'string' && _.contains(clause[1], 'NULL')) {
1025 clause.length = 2;
1026 } else if (typeof clause[1] === 'string' && clause.length === 2) {
1027 clause.push('');
1028 }
1029 }
1030 });
1031 }, true);
1032 }
1033 };
1034 });
1035
1036 angular.module('api4Explorer').directive('api4ExpValue', function($routeParams, crmApi4) {
1037 return {
1038 scope: {
1039 data: '=api4ExpValue'
1040 },
1041 require: 'ngModel',
1042 link: function (scope, element, attrs, ctrl) {
1043 var ts = scope.ts = CRM.ts(),
1044 multi = _.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope.data.op),
1045 entity = $routeParams.api4entity,
1046 action = scope.data.action || $routeParams.api4action;
1047
1048 function destroyWidget() {
1049 var $el = $(element);
1050 if ($el.is('.crm-form-date-wrapper .crm-hidden-date')) {
1051 $el.crmDatepicker('destroy');
1052 }
1053 if ($el.is('.select2-container + input')) {
1054 $el.crmEntityRef('destroy');
1055 }
1056 $(element).removeData().removeAttr('type').removeAttr('placeholder').show();
1057 }
1058
1059 function makeWidget(field, op) {
1060 var $el = $(element),
1061 inputType = field.input_type,
1062 dataType = field.data_type;
1063 if (!op) {
1064 op = field.serialize || dataType === 'Array' ? 'IN' : '=';
1065 }
1066 multi = _.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op);
1067 if (op === 'IS NULL' || op === 'IS NOT NULL') {
1068 $el.hide();
1069 return;
1070 }
1071 if (inputType === 'Date') {
1072 if (_.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op)) {
1073 $el.crmDatepicker({time: (field.input_attrs && field.input_attrs.time) || false});
1074 }
1075 } else if (_.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op) && (field.fk_entity || field.options || dataType === 'Boolean')) {
1076 if (field.options) {
1077 var id = field.pseudoconstant || 'id';
1078 $el.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple: multi, data: [{id: '', text: ''}]});
1079 loadFieldOptions(field.entity || entity).then(function(data) {
1080 var options = _.transform(data[field.name].options, function(options, opt) {
1081 options.push({id: opt[id], text: opt.label, description: opt.description, color: opt.color, icon: opt.icon});
1082 }, []);
1083 $el.removeClass('loading').crmSelect2({data: options, multiple: multi});
1084 });
1085 } else if (field.fk_entity) {
1086 $el.crmEntityRef({entity: field.fk_entity, select:{multiple: multi}});
1087 } else if (dataType === 'Boolean') {
1088 $el.attr('placeholder', ts('- select -')).crmSelect2({allowClear: false, multiple: multi, placeholder: ts('- select -'), data: [
1089 {id: 'true', text: ts('Yes')},
1090 {id: 'false', text: ts('No')}
1091 ]});
1092 }
1093 } else if (dataType === 'Integer' && !multi) {
1094 $el.attr('type', 'number');
1095 }
1096 }
1097
1098 function loadFieldOptions(entity) {
1099 if (!fieldOptions[entity + action]) {
1100 fieldOptions[entity + action] = crmApi4(entity, 'getFields', {
1101 loadOptions: ['id', 'name', 'label', 'description', 'color', 'icon'],
1102 action: action,
1103 where: [['options', '!=', false]],
1104 select: ['options']
1105 }, 'name');
1106 }
1107 return fieldOptions[entity + action];
1108 }
1109
1110 // Copied from ng-list but applied conditionally if field is multi-valued
1111 var parseList = function(viewValue) {
1112 // If the viewValue is invalid (say required but empty) it will be `undefined`
1113 if (_.isUndefined(viewValue)) return;
1114
1115 if (!multi) {
1116 return viewValue;
1117 }
1118
1119 var list = [];
1120
1121 if (viewValue) {
1122 _.each(viewValue.split(','), function(value) {
1123 if (value) list.push(_.trim(value));
1124 });
1125 }
1126
1127 return list;
1128 };
1129
1130 // Copied from ng-list
1131 ctrl.$parsers.push(parseList);
1132 ctrl.$formatters.push(function(value) {
1133 return _.isArray(value) ? value.join(', ') : value;
1134 });
1135
1136 // Copied from ng-list
1137 ctrl.$isEmpty = function(value) {
1138 return !value || !value.length;
1139 };
1140
1141 scope.$watchCollection('data', function(data) {
1142 destroyWidget();
1143 var field = getField(data.field, entity, action);
1144 if (field && data.format !== 'plain') {
1145 makeWidget(field, data.op);
1146 }
1147 });
1148 }
1149 };
1150 });
1151
1152
1153 angular.module('api4Explorer').directive('api4ExpChain', function(crmApi4) {
1154 return {
1155 scope: {
1156 chain: '=api4ExpChain',
1157 mainEntity: '=',
1158 entities: '='
1159 },
1160 templateUrl: '~/api4Explorer/Chain.html',
1161 link: function (scope, element, attrs) {
1162 var ts = scope.ts = CRM.ts();
1163
1164 function changeEntity(newEntity, oldEntity) {
1165 // When clearing entity remove this chain
1166 if (!newEntity) {
1167 scope.chain[0] = '';
1168 return;
1169 }
1170 // Reset action && index
1171 if (newEntity !== oldEntity) {
1172 scope.chain[1][1] = scope.chain[1][2] = '';
1173 }
1174 if (getEntity(newEntity).actions) {
1175 setActions();
1176 } else {
1177 crmApi4(newEntity, 'getActions', {chain: {fields: [newEntity, 'getFields', {action: '$name'}]}})
1178 .then(function(data) {
1179 getEntity(data.entity).actions = data;
1180 if (data.entity === scope.chain[1][0]) {
1181 setActions();
1182 }
1183 });
1184 }
1185 }
1186
1187 function setActions() {
1188 scope.actions = [''].concat(_.pluck(getEntity(scope.chain[1][0]).actions, 'name'));
1189 }
1190
1191 // Set default params when choosing action
1192 function changeAction(newAction, oldAction) {
1193 var link;
1194 // Prepopulate links
1195 if (newAction && newAction !== oldAction) {
1196 // Clear index
1197 scope.chain[1][3] = '';
1198 // Look for links back to main entity
1199 _.each(entityFields(scope.chain[1][0]), function(field) {
1200 if (field.fk_entity === scope.mainEntity) {
1201 link = [field.name, '$id'];
1202 }
1203 });
1204 // Look for links from main entity
1205 if (!link && newAction !== 'create') {
1206 _.each(entityFields(scope.mainEntity), function(field) {
1207 if (field.fk_entity === scope.chain[1][0]) {
1208 link = ['id', '$' + field.name];
1209 // Since we're specifying the id, set index to getsingle
1210 scope.chain[1][3] = '0';
1211 }
1212 });
1213 }
1214 if (link && _.contains(['get', 'update', 'replace', 'delete'], newAction)) {
1215 scope.chain[1][2] = '{where: [[' + link[0] + ', =, ' + link[1] + ']]}';
1216 }
1217 else if (link && _.contains(['create'], newAction)) {
1218 scope.chain[1][2] = '{values: {' + link[0] + ': ' + link[1] + '}}';
1219 }
1220 else if (link && _.contains(['save'], newAction)) {
1221 scope.chain[1][2] = '{records: [{' + link[0] + ': ' + link[1] + '}]}';
1222 } else {
1223 scope.chain[1][2] = '{}';
1224 }
1225 }
1226 }
1227
1228 scope.$watch("chain[1][0]", changeEntity);
1229 scope.$watch("chain[1][1]", changeAction);
1230 }
1231 };
1232 });
1233
1234 function getEntity(entityName) {
1235 return _.findWhere(schema, {name: entityName});
1236 }
1237
1238 function entityFields(entityName, action) {
1239 var entity = getEntity(entityName);
1240 if (entity && action && entity.actions) {
1241 return _.findWhere(entity.actions, {name: action}).fields;
1242 }
1243 return _.result(entity, 'fields');
1244 }
1245
1246 function getExplicitJoins() {
1247 return _.transform(params.join, function(joins, join) {
1248 var j = join[0].split(' AS '),
1249 joinEntity = _.trim(j[0]),
1250 joinAlias = _.trim(j[1]) || joinEntity.toLowerCase();
1251 joins[joinAlias] = joinEntity;
1252 }, {});
1253 }
1254
1255 function getField(fieldName, entity, action) {
1256 var suffix = fieldName.split(':')[1];
1257 fieldName = fieldName.split(':')[0];
1258 var fieldNames = fieldName.split('.');
1259 var field = get(entity, fieldNames);
1260 if (field && suffix) {
1261 field.pseudoconstant = suffix;
1262 }
1263 return field;
1264
1265 function get(entity, fieldNames) {
1266 if (fieldNames.length === 1) {
1267 return _.findWhere(entityFields(entity, action), {name: fieldNames[0]});
1268 }
1269 var comboName = _.findWhere(entityFields(entity, action), {name: fieldNames[0] + '.' + fieldNames[1]});
1270 if (comboName) {
1271 return comboName;
1272 }
1273 var linkName = fieldNames.shift(),
1274 newEntity = getExplicitJoins()[linkName] || _.findWhere(links[entity], {alias: linkName}).entity;
1275 return get(newEntity, fieldNames);
1276 }
1277 }
1278
1279 // Collapsible optgroups for select2
1280 $(function() {
1281 $('body')
1282 .on('select2-open', function(e) {
1283 if ($(e.target).hasClass('collapsible-optgroups')) {
1284 $('#select2-drop')
1285 .off('.collapseOptionGroup')
1286 .addClass('collapsible-optgroups-enabled')
1287 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1288 $(this).parent().toggleClass('optgroup-expanded');
1289 });
1290 }
1291 })
1292 .on('select2-close', function() {
1293 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1294 });
1295 });
1296 })(angular, CRM.$, CRM._);