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