Merge pull request #17621 from colemanw/sortOptions
[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 if ($scope.isSelectRowCount()) {
291 $scope.params.select = [];
292 } else {
293 $scope.params.select = ['row_count'];
294 $scope.index = '';
295 if ($scope.params.limit == 25) {
296 $scope.params.limit = 0;
297 }
298 }
299 };
300
301 $scope.isSelectRowCount = function() {
302 return isSelectRowCount($scope.params);
303 };
304
305 $scope.selectLang = function(lang) {
306 $scope.selectedTab.code = lang;
307 writeCode();
308 };
309
310 function isSelectRowCount(params) {
311 return params && params.select && params.select.length === 1 && params.select[0] === 'row_count';
312 }
313
314 function getEntity(entityName) {
315 return _.findWhere(schema, {name: entityName || $scope.entity});
316 }
317
318 // Get all params that have been set
319 function getParams() {
320 var params = {};
321 _.each($scope.params, function(param, key) {
322 if (param != $scope.availableParams[key].default && !(typeof param === 'object' && _.isEmpty(param))) {
323 if (_.contains($scope.availableParams[key].type, 'array') && (typeof objectParams[key] === 'undefined')) {
324 params[key] = parseYaml(JSON.parse(angular.toJson(param)));
325 } else {
326 params[key] = param;
327 }
328 }
329 });
330 _.each(objectParams, function(defaultVal, key) {
331 if (params[key]) {
332 var newParam = {};
333 _.each(params[key], function(item) {
334 var val = _.cloneDeep(item[1]);
335 // Remove blank items from "chain" array
336 if (_.isArray(val)) {
337 _.eachRight(item[1], function(v, k) {
338 if (v) {
339 return false;
340 }
341 val.length--;
342 });
343 }
344 newParam[item[0]] = parseYaml(val);
345 });
346 params[key] = newParam;
347 }
348 });
349 return params;
350 }
351
352 function parseYaml(input) {
353 if (typeof input === 'undefined' || input === '') {
354 return input;
355 }
356 // Return literal quoted string without removing quotes - for the sake of JOIN ON clauses
357 if (_.isString(input) && input[0] === input[input.length - 1] && _.includes(["'", '"'], input[0])) {
358 return input;
359 }
360 if (_.isObject(input) || _.isArray(input)) {
361 _.each(input, function(item, index) {
362 input[index] = parseYaml(item);
363 });
364 return input;
365 }
366 try {
367 var output = (input === '>') ? '>' : jsyaml.safeLoad(input);
368 // We don't want dates parsed to js objects
369 return _.isDate(output) ? input : output;
370 } catch (e) {
371 return input;
372 }
373 }
374
375 this.buildFieldList = function() {
376 var actionInfo = _.findWhere(actions, {id: $scope.action});
377 getFieldList($scope.fields, $scope.action);
378 getFieldList($scope.fieldsAndJoins, $scope.action, ['name']);
379 getFieldList($scope.fieldsAndJoinsAndFunctions, $scope.action);
380 getFieldList($scope.fieldsAndJoinsAndFunctionsWithSuffixes, $scope.action, ['name', 'label']);
381 getFieldList($scope.fieldsAndJoinsAndFunctionsAndWildcards, $scope.action, ['name', 'label']);
382 if (_.contains(['get', 'update', 'delete', 'replace'], $scope.action)) {
383 addJoins($scope.fieldsAndJoins);
384 // SQL functions are supported if HAVING is
385 if (actionInfo.params.having) {
386 var functions = {
387 text: ts('FUNCTION'),
388 description: ts('Calculate result of a SQL function'),
389 children: _.transform(CRM.vars.api4.functions, function(result, fn) {
390 result.push({
391 id: fn.name + '() AS ' + fn.name.toLowerCase(),
392 text: fn.name + '()',
393 description: fn.name + '(' + describeSqlFn(fn.params) + ')'
394 });
395 })
396 };
397 $scope.fieldsAndJoinsAndFunctions.push(functions);
398 $scope.fieldsAndJoinsAndFunctionsWithSuffixes.push(functions);
399 $scope.fieldsAndJoinsAndFunctionsAndWildcards.push(functions);
400 }
401 addJoins($scope.fieldsAndJoinsAndFunctions, true);
402 addJoins($scope.fieldsAndJoinsAndFunctionsWithSuffixes, false, ['name', 'label']);
403 addJoins($scope.fieldsAndJoinsAndFunctionsAndWildcards, true, ['name', 'label']);
404 }
405 $scope.fieldsAndJoinsAndFunctionsAndWildcards.unshift({id: '*', text: '*', 'description': 'All core ' + $scope.entity + ' fields'});
406 };
407
408 function selectAction() {
409 $scope.action = $routeParams.api4action;
410 if (!actions.length) {
411 formatForSelect2(getEntity().actions, actions, 'name', ['description', 'params']);
412 }
413 if ($scope.action) {
414 var actionInfo = _.findWhere(actions, {id: $scope.action});
415 _.each(actionInfo.params, function (param, name) {
416 var format,
417 defaultVal = _.cloneDeep(param.default);
418 if (param.type) {
419 switch (param.type[0]) {
420 case 'int':
421 case 'bool':
422 format = param.type[0];
423 break;
424
425 case 'array':
426 case 'object':
427 format = 'json';
428 break;
429
430 default:
431 format = 'raw';
432 }
433 if (name === 'limit') {
434 defaultVal = 25;
435 }
436 if (name === 'debug') {
437 defaultVal = true;
438 }
439 if (name === 'values') {
440 defaultVal = defaultValues(defaultVal);
441 }
442 if (name === 'loadOptions' && $scope.action === 'getFields') {
443 param.options = [
444 false,
445 true,
446 ['id', 'name', 'label'],
447 ['id', 'name', 'label', 'abbr', 'description', 'color', 'icon']
448 ];
449 format = 'json';
450 defaultVal = false;
451 param.type = ['string'];
452 }
453 $scope.$bindToRoute({
454 expr: 'params["' + name + '"]',
455 param: name,
456 format: format,
457 default: defaultVal,
458 deep: format === 'json'
459 });
460 }
461 if (typeof objectParams[name] !== 'undefined' && name !== 'orderBy') {
462 $scope.$watch('params.' + name, function (values) {
463 // Remove empty values
464 _.each(values, function (clause, index) {
465 if (!clause || !clause[0]) {
466 $scope.clearParam(name, index);
467 }
468 });
469 }, true);
470 }
471 if (name === 'select' && actionInfo.params.having) {
472 $scope.$watchCollection('params.select', function(values) {
473 $scope.havingOptions.length = 0;
474 _.each(values, function(item) {
475 var pieces = item.split(' AS '),
476 alias = _.trim(pieces[pieces.length - 1]).replace(':label', ':name');
477 $scope.havingOptions.push({id: alias, text: alias});
478 });
479 });
480 }
481 if (typeof objectParams[name] !== 'undefined' || name === 'groupBy' || name === 'select' || name === 'join') {
482 $scope.$watch('controls.' + name, function(value) {
483 var field = value;
484 $timeout(function() {
485 if (field) {
486 if (name === 'join') {
487 $scope.params[name].push([field + ' AS ' + _.snakeCase(field), false]);
488 ctrl.buildFieldList();
489 }
490 else if (typeof objectParams[name] === 'undefined') {
491 $scope.params[name].push(field);
492 } else {
493 var defaultOp = _.cloneDeep(objectParams[name]);
494 if (name === 'chain') {
495 var num = $scope.params.chain.length;
496 defaultOp[0] = field;
497 field = 'name_me_' + num;
498 }
499 $scope.params[name].push([field, defaultOp]);
500 }
501 $scope.controls[name] = null;
502 }
503 });
504 });
505 }
506 });
507 ctrl.buildFieldList();
508 $scope.availableParams = actionInfo.params;
509 }
510 writeCode();
511 }
512
513 function describeSqlFn(params) {
514 var desc = ' ';
515 _.each(params, function(param) {
516 desc += ' ';
517 if (param.prefix) {
518 desc += _.filter(param.prefix).join('|') + ' ';
519 }
520 if (param.expr === 1) {
521 desc += 'expr ';
522 } else if (param.expr > 1) {
523 desc += 'expr, ... ';
524 }
525 if (param.suffix) {
526 desc += ' ' + _.filter(param.suffix).join('|') + ' ';
527 }
528 });
529 return desc.replace(/[ ]+/g, ' ');
530 }
531
532 function defaultValues(defaultVal) {
533 _.each($scope.fields, function(field) {
534 if (field.required) {
535 defaultVal.push([field.id, '']);
536 }
537 });
538 return defaultVal;
539 }
540
541 function stringify(value, trim) {
542 if (typeof value === 'undefined') {
543 return '';
544 }
545 var str = JSON.stringify(value).replace(/,/g, ', ');
546 if (trim) {
547 str = str.slice(1, -1);
548 }
549 return str.trim();
550 }
551
552 function writeCode() {
553 var code = {},
554 entity = $scope.entity,
555 action = $scope.action,
556 params = getParams(),
557 index = isInt($scope.index) ? +$scope.index : parseYaml($scope.index),
558 result = 'result';
559 if ($scope.entity && $scope.action) {
560 delete params.debug;
561 if (action.slice(0, 3) === 'get') {
562 result = entity.substr(0, 7) === 'Custom_' ? _.camelCase(entity.substr(7)) : entity;
563 result = lcfirst(action.replace(/s$/, '').slice(3) || result);
564 }
565 var results = lcfirst(_.isNumber(index) ? result : pluralize(result)),
566 paramCount = _.size(params),
567 i = 0;
568
569 if (isSelectRowCount(params)) {
570 results = result + 'Count';
571 }
572
573 switch ($scope.selectedTab.code) {
574 case 'js':
575 case 'ang':
576 // Write javascript
577 var js = "'" + entity + "', '" + action + "', {";
578 _.each(params, function(param, key) {
579 js += "\n " + key + ': ' + stringify(param) +
580 (++i < paramCount ? ',' : '');
581 if (key === 'checkPermissions') {
582 js += ' // IGNORED: permissions are always enforced from client-side requests';
583 }
584 });
585 js += "\n}";
586 if (index || index === 0) {
587 js += ', ' + JSON.stringify(index);
588 }
589 code.js = "CRM.api4(" + js + ").then(function(" + results + ") {\n // do something with " + results + " array\n}, function(failure) {\n // handle failure\n});";
590 code.js2 = "CRM.api4({" + results + ': [' + js + "]}).then(function(batch) {\n // do something with batch." + results + " array\n}, function(failure) {\n // handle failure\n});";
591 code.ang = "crmApi4(" + js + ").then(function(" + results + ") {\n // do something with " + results + " array\n}, function(failure) {\n // handle failure\n});";
592 code.ang2 = "crmApi4({" + results + ': [' + js + "]}).then(function(batch) {\n // do something with batch." + results + " array\n}, function(failure) {\n // handle failure\n});";
593 break;
594
595 case 'php':
596 // Write php code
597 code.php = '$' + results + " = civicrm_api4('" + entity + "', '" + action + "', [";
598 _.each(params, function(param, key) {
599 code.php += "\n '" + key + "' => " + phpFormat(param, 4) + ',';
600 });
601 code.php += "\n]";
602 if (index || index === 0) {
603 code.php += ', ' + phpFormat(index);
604 }
605 code.php += ");";
606
607 // Write oop code
608 code.oop = '$' + results + " = " + formatOOP(entity, action, params, 2) + "\n ->execute()";
609 if (isSelectRowCount(params)) {
610 code.oop += "\n ->count()";
611 } else if (_.isNumber(index)) {
612 code.oop += !index ? '\n ->first()' : (index === -1 ? '\n ->last()' : '\n ->itemAt(' + index + ')');
613 } else if (index) {
614 if (_.isString(index) || (_.isPlainObject(index) && !index[0] && !index['0'])) {
615 code.oop += "\n ->indexBy('" + (_.isPlainObject(index) ? _.keys(index)[0] : index) + "')";
616 }
617 if (_.isArray(index) || _.isPlainObject(index)) {
618 code.oop += "\n ->column('" + (_.isArray(index) ? index[0] : _.values(index)[0]) + "')";
619 }
620 }
621 code.oop += ";\n";
622 if (!_.isNumber(index) && !isSelectRowCount(params)) {
623 code.oop += "foreach ($" + results + ' as $' + ((_.isString(index) && index) ? index + ' => $' : '') + result + ') {\n // do something\n}';
624 }
625 break;
626
627 case 'cli':
628 // Write cli code
629 code.cv = 'cv api4 ' + entity + '.' + action + " '" + stringify(params) + "'";
630 }
631 }
632 _.each($scope.code, function(vals) {
633 _.each(vals, function(style) {
634 style.code = code[style.name] ? prettyPrintOne(code[style.name]) : '';
635 });
636 });
637 }
638
639 // Format oop params
640 function formatOOP(entity, action, params, indent) {
641 var code = '',
642 newLine = "\n" + _.repeat(' ', indent);
643 if (entity.substr(0, 7) !== 'Custom_') {
644 code = "\\Civi\\Api4\\" + entity + '::' + action + '()';
645 } else {
646 code = "\\Civi\\Api4\\CustomValue::" + action + "('" + entity.substr(7) + "')";
647 }
648 _.each(params, function(param, key) {
649 var val = '';
650 if (typeof objectParams[key] !== 'undefined' && key !== 'chain') {
651 _.each(param, function(item, index) {
652 val = phpFormat(index) + ', ' + phpFormat(item, 2 + indent);
653 code += newLine + "->add" + ucfirst(key).replace(/s$/, '') + '(' + val + ')';
654 });
655 } else if (key === 'where') {
656 _.each(param, function (clause) {
657 if (clause[0] === 'AND' || clause[0] === 'OR' || clause[0] === 'NOT') {
658 code += newLine + "->addClause(" + phpFormat(clause[0]) + ", " + phpFormat(clause[1]).slice(1, -1) + ')';
659 } else {
660 code += newLine + "->addWhere(" + phpFormat(clause).slice(1, -1) + ")";
661 }
662 });
663 } else if (key === 'select') {
664 code += newLine;
665 // addSelect() is a variadic function & can take multiple arguments; selectRowCount() is a shortcut for addSelect('row_count')
666 code += isSelectRowCount(params) ? '->selectRowCount()' : '->addSelect(' + phpFormat(param).slice(1, -1) + ')';
667 } else if (key === 'chain') {
668 _.each(param, function(chain, name) {
669 code += newLine + "->addChain('" + name + "', " + formatOOP(chain[0], chain[1], chain[2], 2 + indent);
670 code += (chain.length > 3 ? ',' : '') + (!_.isEmpty(chain[2]) ? newLine : ' ') + (chain.length > 3 ? phpFormat(chain[3]) : '') + ')';
671 });
672 }
673 else {
674 code += newLine + "->set" + ucfirst(key) + '(' + phpFormat(param, 2 + indent) + ')';
675 }
676 });
677 return code;
678 }
679
680 function isInt(value) {
681 if (_.isFinite(value)) {
682 return true;
683 }
684 if (!_.isString(value)) {
685 return false;
686 }
687 return /^-{0,1}\d+$/.test(value);
688 }
689
690 function formatMeta(resp) {
691 var ret = '';
692 _.each(resp, function(val, key) {
693 if (key !== 'values' && !_.isPlainObject(val) && !_.isFunction(val)) {
694 ret += (ret.length ? ', ' : '') + key + ': ' + (_.isArray(val) ? '[' + val + ']' : val);
695 }
696 });
697 return prettyPrintOne(_.escape(ret));
698 }
699
700 $scope.execute = function() {
701 $scope.status = 'info';
702 $scope.loading = true;
703 $http.post(CRM.url('civicrm/ajax/api4/' + $scope.entity + '/' + $scope.action, {
704 params: angular.toJson(getParams()),
705 index: isInt($scope.index) ? +$scope.index : parseYaml($scope.index)
706 }), null, {
707 headers: {
708 'X-Requested-With': 'XMLHttpRequest'
709 }
710 }).then(function(resp) {
711 $scope.loading = false;
712 $scope.status = resp.data && resp.data.debug && resp.data.debug.log ? 'warning' : 'success';
713 $scope.debug = debugFormat(resp.data);
714 $scope.result = [formatMeta(resp.data), prettyPrintOne(_.escape(JSON.stringify(resp.data.values, null, 2)), 'js', 1)];
715 }, function(resp) {
716 $scope.loading = false;
717 $scope.status = 'danger';
718 $scope.debug = debugFormat(resp.data);
719 $scope.result = [formatMeta(resp), prettyPrintOne(_.escape(JSON.stringify(resp.data, null, 2)))];
720 });
721 };
722
723 function debugFormat(data) {
724 var debug = data.debug ? prettyPrintOne(_.escape(JSON.stringify(data.debug, null, 2)).replace(/\\n/g, "\n")) : null;
725 delete data.debug;
726 return debug;
727 }
728
729 /**
730 * Format value to look like php code
731 */
732 function phpFormat(val, indent) {
733 if (typeof val === 'undefined') {
734 return '';
735 }
736 if (val === null || val === true || val === false) {
737 return JSON.stringify(val).toUpperCase();
738 }
739 indent = (typeof indent === 'number') ? _.repeat(' ', indent) : (indent || '');
740 var ret = '',
741 baseLine = indent ? indent.slice(0, -2) : '',
742 newLine = indent ? '\n' : '',
743 trailingComma = indent ? ',' : '';
744 if ($.isPlainObject(val)) {
745 $.each(val, function(k, v) {
746 ret += (ret ? ', ' : '') + newLine + indent + "'" + k + "' => " + phpFormat(v);
747 });
748 return '[' + ret + trailingComma + newLine + baseLine + ']';
749 }
750 if ($.isArray(val)) {
751 $.each(val, function(k, v) {
752 ret += (ret ? ', ' : '') + newLine + indent + phpFormat(v);
753 });
754 return '[' + ret + trailingComma + newLine + baseLine + ']';
755 }
756 if (_.isString(val) && !_.contains(val, "'")) {
757 return "'" + val + "'";
758 }
759 return JSON.stringify(val).replace(/\$/g, '\\$');
760 }
761
762 function fetchMeta() {
763 crmApi4(getMetaParams)
764 .then(function(data) {
765 if (data.actions) {
766 getEntity().actions = data.actions;
767 selectAction();
768 }
769 });
770 }
771
772 // Help for an entity with no action selected
773 function showEntityHelp(entityName) {
774 var entityInfo = getEntity(entityName);
775 setHelp($scope.entity, {
776 description: entityInfo.description,
777 comment: entityInfo.comment,
778 see: entityInfo.see
779 });
780 }
781
782 if (!$scope.entity) {
783 setHelp(ts('APIv4 Explorer'), {description: docs.description, comment: docs.comment, see: docs.see});
784 } else if (!actions.length && !getEntity().actions) {
785 getMetaParams.actions = [$scope.entity, 'getActions', {chain: {fields: [$scope.entity, 'getFields', {action: '$name'}]}}];
786 fetchMeta();
787 } else {
788 selectAction();
789 }
790
791 if ($scope.entity) {
792 showEntityHelp($scope.entity);
793 }
794
795 // Update route when changing entity
796 $scope.$watch('entity', function(newVal, oldVal) {
797 if (oldVal !== newVal) {
798 // Flush actions cache to re-fetch for new entity
799 actions = [];
800 $location.url('/explorer/' + newVal);
801 }
802 });
803
804 // Update route when changing actions
805 $scope.$watch('action', function(newVal, oldVal) {
806 if ($scope.entity && $routeParams.api4action !== newVal && !_.isUndefined(newVal)) {
807 $location.url('/explorer/' + $scope.entity + '/' + newVal);
808 } else if (newVal) {
809 setHelp($scope.entity + '::' + newVal, _.pick(_.findWhere(getEntity().actions, {name: newVal}), ['description', 'comment', 'see']));
810 }
811 });
812
813 $scope.paramDoc = function(name) {
814 return docs.params[name];
815 };
816
817 $scope.executeDoc = function() {
818 var doc = {
819 description: ts('Runs API call on the CiviCRM database.'),
820 comment: ts('Results and debugging info will be displayed below.')
821 };
822 if ($scope.action === 'delete') {
823 doc.WARNING = ts('This API call will be executed on the real database. Deleting data cannot be undone.');
824 }
825 else if ($scope.action && $scope.action.slice(0, 3) !== 'get') {
826 doc.WARNING = ts('This API call will be executed on the real database. It cannot be undone.');
827 }
828 return doc;
829 };
830
831 $scope.saveDoc = function() {
832 return {
833 description: ts('Save API call as a smart group.'),
834 comment: ts('Create a SavedSearch using these API params to populate a smart group.') +
835 '\n\n' + ts('NOTE: you must select contact id as the only field.')
836 };
837 };
838
839 $scope.$watch('params', writeCode, true);
840 $scope.$watch('index', writeCode);
841 writeCode();
842
843 $scope.save = function() {
844 $scope.params.limit = $scope.params.offset = 0;
845 if ($scope.params.chain.length) {
846 CRM.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires: 5000});
847 return;
848 }
849 if ($scope.params.select.length !== 1 || !_.includes($scope.params.select[0], 'id')) {
850 CRM.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires: 5000});
851 return;
852 }
853 var model = {
854 title: '',
855 description: '',
856 visibility: 'User and User Admin Only',
857 group_type: [],
858 id: null,
859 entity: $scope.entity,
860 params: JSON.parse(angular.toJson($scope.params))
861 };
862 model.params.version = 4;
863 delete model.params.chain;
864 delete model.params.debug;
865 delete model.params.limit;
866 delete model.params.offset;
867 delete model.params.orderBy;
868 delete model.params.checkPermissions;
869 var options = CRM.utils.adjustDialogDefaults({
870 width: '500px',
871 autoOpen: false,
872 title: ts('Save smart group')
873 });
874 dialogService.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model, options);
875 };
876 });
877
878 angular.module('api4Explorer').controller('SaveSearchCtrl', function($scope, crmApi4, dialogService) {
879 var ts = $scope.ts = CRM.ts(),
880 model = $scope.model;
881 $scope.groupEntityRefParams = {
882 entity: 'Group',
883 api: {
884 params: {is_hidden: 0, is_active: 1, 'saved_search_id.api_entity': model.entity},
885 extra: ['saved_search_id', 'description', 'visibility', 'group_type']
886 },
887 select: {
888 allowClear: true,
889 minimumInputLength: 0,
890 placeholder: ts('Select existing group')
891 }
892 };
893 if (!CRM.checkPerm('administer reserved groups')) {
894 $scope.groupEntityRefParams.api.params.is_reserved = 0;
895 }
896 $scope.perm = {
897 administerReservedGroups: CRM.checkPerm('administer reserved groups')
898 };
899 $scope.options = CRM.vars.api4.groupOptions;
900 $scope.$watch('model.id', function(id) {
901 if (id) {
902 _.assign(model, $('#api-save-search-select-group').select2('data').extra);
903 }
904 });
905 $scope.cancel = function() {
906 dialogService.cancel('saveSearchDialog');
907 };
908 $scope.save = function() {
909 $('.ui-dialog:visible').block();
910 var group = model.id ? {id: model.id} : {title: model.title};
911 group.description = model.description;
912 group.visibility = model.visibility;
913 group.group_type = model.group_type;
914 group.saved_search_id = '$id';
915 var savedSearch = {
916 api_entity: model.entity,
917 api_params: model.params
918 };
919 if (group.id) {
920 savedSearch.id = model.saved_search_id;
921 }
922 crmApi4('SavedSearch', 'save', {records: [savedSearch], chain: {group: ['Group', 'save', {'records': [group]}]}})
923 .then(function(result) {
924 dialogService.close('saveSearchDialog', result[0]);
925 });
926 };
927 });
928
929 angular.module('api4Explorer').directive('crmApi4Clause', function() {
930 return {
931 scope: {
932 data: '<crmApi4Clause'
933 },
934 templateUrl: '~/api4Explorer/Clause.html',
935 controller: function ($scope, $element, $timeout) {
936 var ts = $scope.ts = CRM.ts(),
937 ctrl = $scope.$ctrl = this;
938 this.conjunctions = {AND: ts('And'), OR: ts('Or'), NOT: ts('Not')};
939 this.operators = CRM.vars.api4.operators;
940 this.sortOptions = {
941 axis: 'y',
942 connectWith: '.api4-clause-group-sortable',
943 containment: $element.closest('.api4-clause-fieldset'),
944 over: onSortOver,
945 start: onSort,
946 stop: onSort
947 };
948
949 this.addGroup = function(op) {
950 $scope.data.clauses.push([op, []]);
951 };
952
953 this.removeGroup = function() {
954 $scope.data.groupParent.splice($scope.data.groupIndex, 1);
955 };
956
957 function onSort(event, ui) {
958 $($element).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event.type === 'sortstart');
959 $('.api4-input.form-inline').css('margin-left', '');
960 }
961
962 // Indent clause while dragging between nested groups
963 function onSortOver(event, ui) {
964 var offset = 0;
965 if (ui.sender) {
966 offset = $(ui.placeholder).offset().left - $(ui.sender).offset().left;
967 }
968 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset + 'px');
969 }
970
971 this.addClause = function() {
972 $timeout(function() {
973 if (ctrl.newClause) {
974 $scope.data.clauses.push([ctrl.newClause, '=', '']);
975 ctrl.newClause = null;
976 }
977 });
978 };
979 $scope.$watch('data.clauses', function(values) {
980 // Iterate in reverse order so index doesn't get out-of-sync during splice
981 _.forEachRight(values, function(clause, index) {
982 // Remove empty values
983 if (index >= ($scope.data.skip || 0)) {
984 if (typeof clause !== 'undefined' && !clause[0]) {
985 values.splice(index, 1);
986 }
987 // Add/remove value if operator allows for one
988 else if (typeof clause[1] === 'string' && _.contains(clause[1], 'NULL')) {
989 clause.length = 2;
990 } else if (typeof clause[1] === 'string' && clause.length === 2) {
991 clause.push('');
992 }
993 }
994 });
995 }, true);
996 }
997 };
998 });
999
1000 angular.module('api4Explorer').directive('api4ExpValue', function($routeParams, crmApi4) {
1001 return {
1002 scope: {
1003 data: '=api4ExpValue'
1004 },
1005 require: 'ngModel',
1006 link: function (scope, element, attrs, ctrl) {
1007 var ts = scope.ts = CRM.ts(),
1008 multi = _.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope.data.op),
1009 entity = $routeParams.api4entity,
1010 action = scope.data.action || $routeParams.api4action;
1011
1012 function destroyWidget() {
1013 var $el = $(element);
1014 if ($el.is('.crm-form-date-wrapper .crm-hidden-date')) {
1015 $el.crmDatepicker('destroy');
1016 }
1017 if ($el.is('.select2-container + input')) {
1018 $el.crmEntityRef('destroy');
1019 }
1020 $(element).removeData().removeAttr('type').removeAttr('placeholder').show();
1021 }
1022
1023 function makeWidget(field, op) {
1024 var $el = $(element),
1025 inputType = field.input_type,
1026 dataType = field.data_type;
1027 if (!op) {
1028 op = field.serialize || dataType === 'Array' ? 'IN' : '=';
1029 }
1030 multi = _.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op);
1031 if (op === 'IS NULL' || op === 'IS NOT NULL') {
1032 $el.hide();
1033 return;
1034 }
1035 if (inputType === 'Date') {
1036 if (_.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op)) {
1037 $el.crmDatepicker({time: (field.input_attrs && field.input_attrs.time) || false});
1038 }
1039 } else if (_.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op) && (field.fk_entity || field.options || dataType === 'Boolean')) {
1040 if (field.options) {
1041 var id = field.pseudoconstant || 'id';
1042 $el.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple: multi, data: [{id: '', text: ''}]});
1043 loadFieldOptions(field.entity || entity).then(function(data) {
1044 var options = _.transform(data[field.name].options, function(options, opt) {
1045 options.push({id: opt[id], text: opt.label, description: opt.description, color: opt.color, icon: opt.icon});
1046 }, []);
1047 $el.removeClass('loading').crmSelect2({data: options, multiple: multi});
1048 });
1049 } else if (field.fk_entity) {
1050 $el.crmEntityRef({entity: field.fk_entity, select:{multiple: multi}});
1051 } else if (dataType === 'Boolean') {
1052 $el.attr('placeholder', ts('- select -')).crmSelect2({allowClear: false, multiple: multi, placeholder: ts('- select -'), data: [
1053 {id: 'true', text: ts('Yes')},
1054 {id: 'false', text: ts('No')}
1055 ]});
1056 }
1057 } else if (dataType === 'Integer' && !multi) {
1058 $el.attr('type', 'number');
1059 }
1060 }
1061
1062 function loadFieldOptions(entity) {
1063 if (!fieldOptions[entity + action]) {
1064 fieldOptions[entity + action] = crmApi4(entity, 'getFields', {
1065 loadOptions: ['id', 'name', 'label', 'description', 'color', 'icon'],
1066 action: action,
1067 where: [['options', '!=', false]],
1068 select: ['options']
1069 }, 'name');
1070 }
1071 return fieldOptions[entity + action];
1072 }
1073
1074 // Copied from ng-list but applied conditionally if field is multi-valued
1075 var parseList = function(viewValue) {
1076 // If the viewValue is invalid (say required but empty) it will be `undefined`
1077 if (_.isUndefined(viewValue)) return;
1078
1079 if (!multi) {
1080 return viewValue;
1081 }
1082
1083 var list = [];
1084
1085 if (viewValue) {
1086 _.each(viewValue.split(','), function(value) {
1087 if (value) list.push(_.trim(value));
1088 });
1089 }
1090
1091 return list;
1092 };
1093
1094 // Copied from ng-list
1095 ctrl.$parsers.push(parseList);
1096 ctrl.$formatters.push(function(value) {
1097 return _.isArray(value) ? value.join(', ') : value;
1098 });
1099
1100 // Copied from ng-list
1101 ctrl.$isEmpty = function(value) {
1102 return !value || !value.length;
1103 };
1104
1105 scope.$watchCollection('data', function(data) {
1106 destroyWidget();
1107 var field = getField(data.field, entity, action);
1108 if (field && data.format !== 'plain') {
1109 makeWidget(field, data.op);
1110 }
1111 });
1112 }
1113 };
1114 });
1115
1116
1117 angular.module('api4Explorer').directive('api4ExpChain', function(crmApi4) {
1118 return {
1119 scope: {
1120 chain: '=api4ExpChain',
1121 mainEntity: '=',
1122 entities: '='
1123 },
1124 templateUrl: '~/api4Explorer/Chain.html',
1125 link: function (scope, element, attrs) {
1126 var ts = scope.ts = CRM.ts();
1127
1128 function changeEntity(newEntity, oldEntity) {
1129 // When clearing entity remove this chain
1130 if (!newEntity) {
1131 scope.chain[0] = '';
1132 return;
1133 }
1134 // Reset action && index
1135 if (newEntity !== oldEntity) {
1136 scope.chain[1][1] = scope.chain[1][2] = '';
1137 }
1138 if (getEntity(newEntity).actions) {
1139 setActions();
1140 } else {
1141 crmApi4(newEntity, 'getActions', {chain: {fields: [newEntity, 'getFields', {action: '$name'}]}})
1142 .then(function(data) {
1143 getEntity(data.entity).actions = data;
1144 if (data.entity === scope.chain[1][0]) {
1145 setActions();
1146 }
1147 });
1148 }
1149 }
1150
1151 function setActions() {
1152 scope.actions = [''].concat(_.pluck(getEntity(scope.chain[1][0]).actions, 'name'));
1153 }
1154
1155 // Set default params when choosing action
1156 function changeAction(newAction, oldAction) {
1157 var link;
1158 // Prepopulate links
1159 if (newAction && newAction !== oldAction) {
1160 // Clear index
1161 scope.chain[1][3] = '';
1162 // Look for links back to main entity
1163 _.each(entityFields(scope.chain[1][0]), function(field) {
1164 if (field.fk_entity === scope.mainEntity) {
1165 link = [field.name, '$id'];
1166 }
1167 });
1168 // Look for links from main entity
1169 if (!link && newAction !== 'create') {
1170 _.each(entityFields(scope.mainEntity), function(field) {
1171 if (field.fk_entity === scope.chain[1][0]) {
1172 link = ['id', '$' + field.name];
1173 // Since we're specifying the id, set index to getsingle
1174 scope.chain[1][3] = '0';
1175 }
1176 });
1177 }
1178 if (link && _.contains(['get', 'update', 'replace', 'delete'], newAction)) {
1179 scope.chain[1][2] = '{where: [[' + link[0] + ', =, ' + link[1] + ']]}';
1180 }
1181 else if (link && _.contains(['create'], newAction)) {
1182 scope.chain[1][2] = '{values: {' + link[0] + ': ' + link[1] + '}}';
1183 }
1184 else if (link && _.contains(['save'], newAction)) {
1185 scope.chain[1][2] = '{records: [{' + link[0] + ': ' + link[1] + '}]}';
1186 } else {
1187 scope.chain[1][2] = '{}';
1188 }
1189 }
1190 }
1191
1192 scope.$watch("chain[1][0]", changeEntity);
1193 scope.$watch("chain[1][1]", changeAction);
1194 }
1195 };
1196 });
1197
1198 function getEntity(entityName) {
1199 return _.findWhere(schema, {name: entityName});
1200 }
1201
1202 function entityFields(entityName, action) {
1203 var entity = getEntity(entityName);
1204 if (entity && action && entity.actions) {
1205 return _.findWhere(entity.actions, {name: action}).fields;
1206 }
1207 return _.result(entity, 'fields');
1208 }
1209
1210 function getExplicitJoins() {
1211 return _.transform(params.join, function(joins, join) {
1212 var j = join[0].split(' AS '),
1213 joinEntity = _.trim(j[0]),
1214 joinAlias = _.trim(j[1]) || joinEntity.toLowerCase();
1215 joins[joinAlias] = joinEntity;
1216 }, {});
1217 }
1218
1219 function getField(fieldName, entity, action) {
1220 var suffix = fieldName.split(':')[1];
1221 fieldName = fieldName.split(':')[0];
1222 var fieldNames = fieldName.split('.');
1223 var field = get(entity, fieldNames);
1224 if (field && suffix) {
1225 field.pseudoconstant = suffix;
1226 }
1227 return field;
1228
1229 function get(entity, fieldNames) {
1230 if (fieldNames.length === 1) {
1231 return _.findWhere(entityFields(entity, action), {name: fieldNames[0]});
1232 }
1233 var comboName = _.findWhere(entityFields(entity, action), {name: fieldNames[0] + '.' + fieldNames[1]});
1234 if (comboName) {
1235 return comboName;
1236 }
1237 var linkName = fieldNames.shift(),
1238 newEntity = getExplicitJoins()[linkName] || _.findWhere(links[entity], {alias: linkName}).entity;
1239 return get(newEntity, fieldNames);
1240 }
1241 }
1242
1243 // Collapsible optgroups for select2
1244 $(function() {
1245 $('body')
1246 .on('select2-open', function(e) {
1247 if ($(e.target).hasClass('collapsible-optgroups')) {
1248 $('#select2-drop')
1249 .off('.collapseOptionGroup')
1250 .addClass('collapsible-optgroups-enabled')
1251 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1252 $(this).parent().toggleClass('optgroup-expanded');
1253 });
1254 }
1255 })
1256 .on('select2-close', function() {
1257 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1258 });
1259 });
1260 })(angular, CRM.$, CRM._);