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