CRM-17795 - Add unit test for api joins
[civicrm-core.git] / templates / CRM / Admin / Page / APIExplorer.js
CommitLineData
e4176358 1(function($, _, undefined) {
89ee60d5
CW
2 "use strict";
3 /* jshint validthis: true */
e4176358
CW
4 var
5 entity,
6 action,
a14e9d08 7 actions = {values: ['get']},
e4176358 8 fields = [],
fc6a6a51 9 getFieldData = {},
e4176358 10 params = {},
11a28852 11 smartyPhp,
65f22b4b 12 entityDoc,
8ffa1387 13 fieldTpl = _.template($('#api-param-tpl').html()),
c275764e 14 optionsTpl = _.template($('#api-options-tpl').html()),
b07af612 15 returnTpl = _.template($('#api-return-tpl').html()),
77099ee0 16 chainTpl = _.template($('#api-chain-tpl').html()),
bc4aa590 17 docCodeTpl = _.template($('#doc-code-tpl').html()),
77099ee0 18
f76eb8ae 19 // These types of entityRef don't require any input to open
a39f2446 20 // FIXME: ought to be in getfields metadata
f76eb8ae
CW
21 OPEN_IMMEDIATELY = ['RelationshipType', 'Event', 'Group', 'Tag'],
22
65b8c1db
CW
23 // Actions that don't support fancy operators
24 NO_OPERATORS = ['create', 'update', 'delete', 'setvalue', 'getoptions', 'getactions', 'getfields'],
25
5bd06c36 26 // Actions that don't support multiple values
26a700db 27 NO_MULTI = ['delete', 'getoptions', 'getactions', 'getfields', 'getfield', 'setvalue'],
5bd06c36 28
77099ee0
CW
29 // Operators with special properties
30 BOOL = ['IS NULL', 'IS NOT NULL'],
31 TEXT = ['LIKE', 'NOT LIKE'],
32 MULTI = ['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'];
0c3a6e64 33
1080dff4
CW
34 /**
35 * Call prettyPrint function and perform additional formatting
36 * @param ele
37 */
38 function prettyPrint(ele) {
39 if (typeof window.prettyPrint === 'function') {
40 $(ele).removeClass('prettyprinted').addClass('prettyprint');
41
42 window.prettyPrint();
43
44 // Highlight errors in api result
45 $('span:contains("error_code"),span:contains("error_message")', '#api-result')
46 .siblings('span.str').css('color', '#B00');
47 }
48 }
49
b07af612
CW
50 /**
51 * Add a "fields" row
52 * @param name
53 */
e4176358 54 function addField(name) {
65b8c1db 55 $('#api-params').append($(fieldTpl({name: name || '', noOps: _.includes(NO_OPERATORS, action)})));
e4176358 56 var $row = $('tr:last-child', '#api-params');
77099ee0 57 $('input.api-param-name', $row).crmSelect2({
5c7169eb 58 data: fields.concat({id: '-', text: ts('Other') + '...', description: ts('Choose a field not in this list')}),
29956c59
CW
59 formatSelection: function(field) {
60 return field.text +
61 (field.required ? ' <span class="crm-marker">*</span>' : '');
62 },
5c7169eb 63 formatResult: function(field) {
29956c59
CW
64 return field.text +
65 (field.required ? ' <span class="crm-marker">*</span>' : '') +
66 '<div class="api-field-desc">' + field.description + '</div>';
5c7169eb 67 }
b07af612 68 }).change();
8ffa1387
CW
69 }
70
c275764e
CW
71 /**
72 * Add a new "options" row
c275764e 73 */
cb6d8859 74 function addOptionField() {
c275764e
CW
75 if ($('.api-options-row', '#api-params').length) {
76 $('.api-options-row:last', '#api-params').after($(optionsTpl({})));
77 } else {
78 $('#api-params').append($(optionsTpl({})));
79 }
80 var $row = $('.api-options-row:last', '#api-params');
81 $('.api-option-name', $row).crmSelect2({data: [
82 {id: 'limit', text: 'limit'},
83 {id: 'offset', text: 'offset'},
84 {id: 'sort', text: 'sort'},
85 {id: 'metadata', text: 'metadata'},
86 {id: '-', text: ts('Other') + '...'}
87 ]});
88 }
89
b07af612
CW
90 /**
91 * Add an "api chain" row
92 */
8ffa1387
CW
93 function addChainField() {
94 $('#api-params').append($(chainTpl({})));
95 var $row = $('tr:last-child', '#api-params');
96 $('.api-chain-entity', $row).crmSelect2({
97 formatSelection: function(item) {
41d0b881 98 return '<i class="crm-i fa-link"></i> API ' +
3d9f5b7f 99 ($(item.element).hasClass('strikethrough') ? '<span class="strikethrough">' + item.text + '</span>' : item.text);
2b6e1174 100 },
41d0b881 101 placeholder: '<i class="crm-i fa-link"></i> ' + ts('Entity'),
ff887074 102 escapeMarkup: function(m) {return m;}
8ffa1387 103 });
0c3a6e64
CW
104 }
105
3d9f5b7f
CW
106 /**
107 * Fetch available actions for selected chained entity
108 */
109 function getChainedAction() {
110 var
111 $selector = $(this),
112 entity = $selector.val(),
113 $row = $selector.closest('tr');
114 if (entity) {
115 $selector.prop('disabled', true);
116 CRM.api3(entity, 'getactions')
117 .done(function(actions) {
118 $selector.prop('disabled', false);
ff887074 119 CRM.utils.setOptions($('.api-chain-action', $row), _.transform(actions.values, function(ret, item) {ret.push({value: item, key: item});}));
3d9f5b7f
CW
120 });
121 }
122 }
123
b07af612
CW
124 /**
125 * Fetch fields for entity+action
126 */
a14e9d08 127 function getFields(changedElement) {
e4176358
CW
128 var required = [];
129 fields = [];
932630fd 130 getFieldData = {};
e4176358
CW
131 // Special case for getfields
132 if (action === 'getfields') {
133 fields.push({
134 id: 'api_action',
b8aee616
CW
135 text: ts('Action')
136 });
137 getFieldData.api_action = {
a39f2446
CW
138 options: _.reduce(actions.values, function(ret, item) {
139 ret[item] = item;
140 return ret;
141 }, {})
b8aee616 142 };
e4176358 143 showFields(['api_action']);
0c3a6e64
CW
144 return;
145 }
b432ddaa 146 CRM.api3(entity, 'getfields', {'api_action': action, options: {get_options: 'all', get_options_context: 'match'}}).done(function(data) {
e4176358
CW
147 _.each(data.values, function(field) {
148 if (field.name) {
932630fd 149 getFieldData[field.name] = field;
e4176358
CW
150 fields.push({
151 id: field.name,
152 text: field.title || field.name,
7b6c5043 153 multi: !!field['api.multiple'],
5c7169eb 154 description: field.description || '',
7b6c5043 155 required: !(!field['api.required'] || field['api.required'] === '0')
e4176358 156 });
7b6c5043 157 if (field['api.required'] && field['api.required'] !== '0') {
e4176358
CW
158 required.push(field.name);
159 }
e4176358
CW
160 }
161 });
a14e9d08
CW
162 if ($(changedElement).is('#api-entity') && data.deprecated) {
163 CRM.alert(data.deprecated, entity + ' Deprecated');
164 }
e4176358 165 showFields(required);
3a721dfc
CW
166 if (action === 'get' || action === 'getsingle' || action == 'getvalue' || action === 'getstat') {
167 showReturn();
b07af612 168 }
0c3a6e64
CW
169 });
170 }
171
b07af612
CW
172 /**
173 * For "get" actions show the "return" options
3a721dfc
CW
174 *
175 * TODO: Too many hard-coded actions here. Need a way to fetch this from metadata
b07af612 176 */
3a721dfc
CW
177 function showReturn() {
178 var title = ts('Fields to return'),
179 params = {
180 data: fields,
181 multiple: true,
182 placeholder: ts('Leave blank for default')
183 };
184 if (action == 'getstat') {
185 title = ts('Group by');
186 }
187 if (action == 'getvalue') {
188 title = ts('Return Value');
189 params.placeholder = ts('Select field');
190 params.multiple = false;
191 }
29956c59 192 $('#api-params').prepend($(returnTpl({title: title, required: action == 'getvalue'})));
3a721dfc 193 $('#api-return-value').crmSelect2(params);
b07af612
CW
194 }
195
196 /**
197 * Fetch actions for entity
198 */
2b6e1174
CW
199 function getActions() {
200 if (entity) {
754927e4 201 $('#api-action').addClass('loading');
2b6e1174 202 CRM.api3(entity, 'getactions').done(function(data) {
a14e9d08 203 actions = data;
2b6e1174
CW
204 populateActions();
205 });
206 } else {
a14e9d08 207 actions = {values: ['get']};
2b6e1174
CW
208 populateActions();
209 }
210 }
211
7231faaf
CW
212 /**
213 * Test whether an action is deprecated
214 * @param action
215 * @returns {boolean}
216 */
15cbe793
CW
217 function isActionDeprecated(action) {
218 return !!(typeof actions.deprecated === 'object' && actions.deprecated[action]);
219 }
220
7231faaf
CW
221 /**
222 * Render action text depending on deprecation status
223 * @param option
224 * @returns {string}
225 */
a14e9d08 226 function renderAction(option) {
15cbe793 227 return isActionDeprecated(option.id) ? '<span class="strikethrough">' + option.text + '</span>' : option.text;
a14e9d08
CW
228 }
229
b07af612
CW
230 /**
231 * Called after getActions to populate action list
b07af612 232 */
cb6d8859 233 function populateActions() {
2f929504 234 var val = $('#api-action').val();
754927e4 235 $('#api-action').removeClass('loading').select2({
ff887074 236 data: _.transform(actions.values, function(ret, item) {ret.push({text: item, id: item});}),
a14e9d08
CW
237 formatSelection: renderAction,
238 formatResult: renderAction
2b6e1174 239 });
2f929504 240 // If previously selected action is not available, set it to 'get' if possible
ed0eaccc
CW
241 if (!_.includes(actions.values, val)) {
242 $('#api-action').select2('val', !_.includes(actions.values, 'get') ? actions.values[0] : 'get', true);
a14e9d08
CW
243 }
244 }
245
7231faaf
CW
246 /**
247 * Check for and display action-specific deprecation notices
248 * @param action
249 */
a14e9d08 250 function onChangeAction(action) {
15cbe793 251 if (isActionDeprecated(action)) {
a14e9d08 252 CRM.alert(actions.deprecated[action], action + ' deprecated');
2f929504 253 }
2b6e1174
CW
254 }
255
b07af612
CW
256 /**
257 * Called after getfields to show buttons and required fields
258 * @param required
259 */
e4176358 260 function showFields(required) {
e4176358 261 $('#api-params').empty();
8ffa1387 262 $('#api-param-buttons').show();
e4176358
CW
263 if (required.length) {
264 _.each(required, addField);
265 } else {
266 addField();
0c3a6e64
CW
267 }
268 }
269
4aed36b2
CW
270 function isYesNo(fieldName) {
271 return getFieldData[fieldName] && getFieldData[fieldName].type === 16;
272 }
273
d5a9020d
CW
274 /**
275 * Should we render a select or textfield?
276 *
277 * @param fieldName
278 * @param operator
279 * @returns boolean
280 */
281 function isSelect(fieldName, operator) {
a39f2446
CW
282 var fieldSpec = getFieldData[fieldName] || {};
283 return (isYesNo(fieldName) || fieldSpec.options || fieldSpec.FKApiName) && !_.includes(TEXT, operator);
d5a9020d
CW
284 }
285
286 /**
287 * Should we render a select as single or multi?
288 *
289 * @param fieldName
290 * @param operator
291 * @returns boolean
292 */
7b6c5043 293 function isMultiSelect(fieldName, operator) {
5bd06c36 294 if (isYesNo(fieldName) || _.includes(NO_MULTI, action)) {
4aed36b2
CW
295 return false;
296 }
ed0eaccc 297 if (_.includes(MULTI, operator)) {
d5a9020d
CW
298 return true;
299 }
300 // The = operator is ambiguous but all others can be safely assumed to be single
301 if (operator !== '=') {
302 return false;
303 }
304 return true;
305 /*
306 * Attempt to resolve the ambiguity of the = operator using metadata
307 * commented out because there is not enough metadata in the api at this time
308 * to accurately figure it out.
309 */
310 // var field = fieldName && _.find(fields, 'id', fieldName);
311 // return field && field.multi;
7b6c5043
CW
312 }
313
c275764e 314 /**
fc6a6a51 315 * Render value input as a textfield, option list, entityRef, or hidden,
77099ee0 316 * Depending on selected param name and operator
c275764e 317 */
77099ee0
CW
318 function renderValueField() {
319 var $row = $(this).closest('tr'),
320 name = $('input.api-param-name', $row).val(),
321 operator = $('.api-param-op', $row).val(),
77099ee0 322 $valField = $('input.api-param-value', $row),
7b6c5043 323 multiSelect = isMultiSelect(name, operator),
6e29772f
CW
324 currentVal = $valField.val(),
325 wasSelect = $valField.data('select2');
326 if (wasSelect) {
327 $valField.crmEntityRef('destroy');
328 }
329 $valField.attr('placeholder', ts('Value'));
77099ee0 330 // Boolean fields only have 1 possible value
ed0eaccc 331 if (_.includes(BOOL, operator)) {
77099ee0
CW
332 $valField.css('visibility', 'hidden').val('1');
333 return;
334 }
335 $valField.css('visibility', '');
fc6a6a51 336 // Option list or entityRef input
d5a9020d 337 if (isSelect(name, operator)) {
6e29772f 338 $valField.attr('placeholder', ts('- select -'));
77099ee0 339 // Reset value before switching to a select from something else
6e29772f 340 if ($(this).is('.api-param-name') || !wasSelect) {
77099ee0
CW
341 $valField.val('');
342 }
343 // When switching from multi-select to single select
ed0eaccc 344 else if (!multiSelect && _.includes(currentVal, ',')) {
77099ee0
CW
345 $valField.val(currentVal.split(',')[0]);
346 }
4aed36b2
CW
347 // Yes-No options
348 if (isYesNo(name)) {
349 $valField.select2({
350 data: [{id: 1, text: ts('Yes')}, {id: 0, text: ts('No')}]
351 });
352 }
fc6a6a51 353 // Select options
a39f2446 354 else if (getFieldData[name].options) {
fc6a6a51 355 $valField.select2({
7b6c5043 356 multiple: multiSelect,
a39f2446 357 data: _.map(getFieldData[name].options, function (value, key) {
fc6a6a51
CW
358 return {id: key, text: value};
359 })
360 });
361 }
362 // EntityRef
363 else {
6e29772f
CW
364 var entity = getFieldData[name].FKApiName;
365 $valField.attr('placeholder', entity == 'Contact' ? '[' + ts('Auto-Select Current User') + ']' : ts('- select -'));
fc6a6a51 366 $valField.crmEntityRef({
6e29772f 367 entity: entity,
f76eb8ae 368 select: {
7b6c5043 369 multiple: multiSelect,
e6de5a11
CW
370 minimumInputLength: _.includes(OPEN_IMMEDIATELY, entity) ? 0 : 1,
371 // If user types a numeric id, allow it as a choice
372 createSearchChoice: function(input) {
373 var match = /[1-9][0-9]*/.exec(input);
374 if (match && match[0] === input) {
375 return {id: input, label: input};
376 }
377 }
f76eb8ae 378 }
fc6a6a51
CW
379 });
380 }
e4176358 381 }
e4176358 382 }
0c3a6e64 383
e4176358
CW
384 /**
385 * Attempt to parse a string into a value of the intended type
babf9678
CW
386 * @param val string
387 * @param makeArray bool
e4176358
CW
388 */
389 function evaluate(val, makeArray) {
390 try {
391 if (!val.length) {
77099ee0 392 return makeArray ? [] : '';
e4176358
CW
393 }
394 var first = val.charAt(0),
395 last = val.slice(-1);
396 // Simple types
51f197bf 397 if (val === 'true' || val === 'false' || val === 'null') {
cb6d8859 398 /* jshint evil: true */
e4176358
CW
399 return eval(val);
400 }
401 // Quoted strings
402 if ((first === '"' || first === "'") && last === first) {
403 return val.slice(1, -1);
0c3a6e64 404 }
7231faaf 405 // Parse json - use eval rather than $.parseJSON because it's less strict about formatting
e4176358
CW
406 if ((first === '[' && last === ']') || (first === '{' && last === '}')) {
407 return eval('(' + val + ')');
408 }
409 // Transform csv to array
77099ee0
CW
410 if (makeArray) {
411 var result = [];
412 $.each(val.split(','), function(k, v) {
413 result.push(evaluate($.trim(v)) || v);
414 });
415 return result;
416 }
7231faaf 417 // Integers - skip any multidigit number that starts with 0 to avoid oddities (it will be treated as a string below)
77099ee0
CW
418 if (!isNaN(val) && val.search(/[^\d]/) < 0 && (val.length === 1 || first !== '0')) {
419 return parseInt(val, 10);
e4176358
CW
420 }
421 // Ok ok it's really a string
422 return val;
423 } catch(e) {
424 // If eval crashed return undefined
425 return undefined;
0c3a6e64 426 }
e4176358 427 }
0c3a6e64 428
e4176358
CW
429 /**
430 * Format value to look like php code
6e29772f 431 * TODO: Use short array syntax when we drop support for php 5.3
e4176358
CW
432 * @param val
433 */
434 function phpFormat(val) {
435 var ret = '';
436 if ($.isPlainObject(val)) {
437 $.each(val, function(k, v) {
c275764e 438 ret += (ret ? ', ' : '') + "'" + k + "' => " + phpFormat(v);
e4176358
CW
439 });
440 return 'array(' + ret + ')';
0c3a6e64 441 }
e4176358
CW
442 if ($.isArray(val)) {
443 $.each(val, function(k, v) {
444 ret += (ret ? ', ' : '') + phpFormat(v);
445 });
446 return 'array(' + ret + ')';
447 }
54c512e0 448 return JSON.stringify(val).replace(/\$/g, '\\$');
e4176358
CW
449 }
450
451 /**
11a28852 452 * @param value string
e4176358 453 * @param js string
d5a9020d 454 * @param key string
e4176358 455 */
11a28852
CW
456 function smartyFormat(value, js, key) {
457 var varName = 'param_' + key.replace(/[. -]/g, '_').toLowerCase();
458 // Can't pass array literals directly into smarty so we add a php snippet
ed0eaccc 459 if (_.includes(js, '[') || _.includes(js, '{')) {
11a28852
CW
460 smartyPhp.push('$this->assign("'+ varName + '", '+ phpFormat(value) +');');
461 return '$' + varName;
e4176358
CW
462 }
463 return js;
464 }
465
c275764e
CW
466 /**
467 * Create the params array from user input
468 * @param e
469 */
e4176358
CW
470 function buildParams(e) {
471 params = {};
472 $('.api-param-checkbox:checked').each(function() {
473 params[this.name] = 1;
474 });
c275764e 475 $('input.api-param-value, input.api-option-value').each(function() {
e4176358 476 var $row = $(this).closest('tr'),
d5a9020d 477 input = $(this).val(),
77099ee0 478 op = $('select.api-param-op', $row).val() || '=',
e4176358 479 name = $('input.api-param-name', $row).val(),
d5a9020d 480 // Workaround for ambiguity of the = operator
ed0eaccc 481 makeArray = (op === '=' && isSelect(name, op)) ? _.includes(input, ',') : op !== '=' && isMultiSelect(name, op),
d5a9020d 482 val = evaluate(input, makeArray);
b07af612
CW
483
484 // Ignore blank values for the return field
485 if ($(this).is('#api-return-value') && !val) {
486 return;
487 }
8ffa1387
CW
488 // Special syntax for api chaining
489 if (!name && $('select.api-chain-entity', $row).val()) {
490 name = 'api.' + $('select.api-chain-entity', $row).val() + '.' + $('select.api-chain-action', $row).val();
491 }
c275764e
CW
492 // Special handling for options
493 if ($(this).is('.api-option-value')) {
494 op = $('input.api-option-name', $row).val();
495 if (op) {
496 name = 'options';
497 }
498 }
6e29772f
CW
499 // Default for contact ref fields
500 if ($(this).is('.crm-contact-ref') && input === '') {
501 val = evaluate('user_contact_id', makeArray);
502 }
e4176358 503 if (name && val !== undefined) {
c275764e 504 params[name] = op === '=' ? val : (params[name] || {});
e4176358
CW
505 if (op !== '=') {
506 params[name][op] = val;
507 }
babf9678
CW
508 if ($(this).hasClass('crm-error')) {
509 clearError(this);
510 }
e4176358
CW
511 }
512 else if (name && (!e || e.type !== 'keyup')) {
513 setError(this);
514 }
515 });
516 if (entity && action) {
517 formatQuery();
0c3a6e64 518 }
e4176358 519 }
0c3a6e64 520
7231faaf
CW
521 /**
522 * Display error message on incorrectly-formatted params
523 * @param el
524 */
e4176358
CW
525 function setError(el) {
526 if (!$(el).hasClass('crm-error')) {
babf9678 527 var msg = ts('Syntax error: input should be valid JSON or a quoted string.');
e4176358
CW
528 $(el)
529 .addClass('crm-error')
2b6e1174 530 .css('width', '82%')
babf9678 531 .attr('title', msg)
bc8360e1 532 .before('<i class="crm-i fa-exclamation-triangle crm-i-red" title="'+msg+'"></i> ')
babf9678 533 .tooltip();
e4176358
CW
534 }
535 }
0c3a6e64 536
7231faaf
CW
537 /**
538 * Remove error message
539 * @param el
540 */
e4176358
CW
541 function clearError(el) {
542 $(el)
543 .removeClass('crm-error')
544 .attr('title', '')
2b6e1174 545 .css('width', '85%')
babf9678 546 .tooltip('destroy')
8777ffd1 547 .siblings('.fa-exclamation-triangle').remove();
e4176358 548 }
0c3a6e64 549
7231faaf
CW
550 /**
551 * Render the api request in various formats
552 */
e4176358
CW
553 function formatQuery() {
554 var i = 0, q = {
11a28852 555 smarty: "{crmAPI var='result' entity='" + entity + "' action='" + action + "'" + (params.sequential ? '' : ' sequential=0'),
e4176358
CW
556 php: "$result = civicrm_api3('" + entity + "', '" + action + "'",
557 json: "CRM.api3('" + entity + "', '" + action + "'",
2dad2b26
TO
558 drush: "drush cvapi " + entity + '.' + action + ' ',
559 wpcli: "wp cv api " + entity + '.' + action + ' ',
de69691f 560 rest: CRM.config.resourceBase + "extern/rest.php?entity=" + entity + "&action=" + action + "&api_key=userkey&key=sitekey&json=" + JSON.stringify(params)
e4176358 561 };
11a28852 562 smartyPhp = [];
e4176358 563 $.each(params, function(key, value) {
a2ea6df9
CW
564 var json = JSON.stringify(value),
565 // Encourage 'return' to be an array - at least in php & js
566 js = key === 'return' ? JSON.stringify(evaluate(value, true)) : json,
567 php = key === 'return' ? phpFormat(evaluate(value, true)) : phpFormat(value);
cb6d8859 568 if (!(i++)) {
e4176358
CW
569 q.php += ", array(\n";
570 q.json += ", {\n";
571 } else {
572 q.json += ",\n";
573 }
a2ea6df9 574 q.php += " '" + key + "' => " + php + ",\n";
e4176358 575 q.json += " \"" + key + '": ' + js;
11a28852
CW
576 // smarty already defaults to sequential
577 if (key !== 'sequential') {
a2ea6df9 578 q.smarty += ' ' + key + '=' + smartyFormat(value, json, key);
11a28852 579 }
77099ee0 580 // FIXME: This is not totally correct cli syntax
a2ea6df9
CW
581 q.drush += key + '=' + json + ' ';
582 q.wpcli += key + '=' + json + ' ';
e4176358
CW
583 });
584 if (i) {
585 q.php += ")";
586 q.json += "\n}";
587 }
588 q.php += ");";
589 q.json += ").done(function(result) {\n // do something\n});";
590 q.smarty += "}\n{foreach from=$result.values item=" + entity.toLowerCase() + "}\n {$" + entity.toLowerCase() + ".some_field}\n{/foreach}";
ed0eaccc 591 if (!_.includes(action, 'get')) {
e4176358 592 q.smarty = '{* Smarty API only works with get actions *}';
11a28852
CW
593 } else if (smartyPhp.length) {
594 q.smarty = "{php}\n " + smartyPhp.join("\n ") + "\n{/php}\n" + q.smarty;
e4176358
CW
595 }
596 $.each(q, function(type, val) {
1080dff4 597 $('#api-' + type).text(val);
e4176358 598 });
1080dff4 599 prettyPrint('#api-generated pre');
e4176358 600 }
0c3a6e64 601
7231faaf
CW
602 /**
603 * Submit button handler
604 * @param e
605 */
e4176358
CW
606 function submit(e) {
607 e.preventDefault();
608 if (!entity || !action) {
2b6e1174 609 alert(ts('Select an entity.'));
e4176358
CW
610 return;
611 }
ed0eaccc 612 if (!_.includes(action, 'get') && action != 'check') {
e4176358
CW
613 var msg = action === 'delete' ? ts('This will delete data from CiviCRM. Are you sure?') : ts('This will write to the database. Continue?');
614 CRM.confirm({title: ts('Confirm %1', {1: action}), message: msg}).on('crmConfirm:yes', execute);
0c3a6e64 615 } else {
e4176358 616 execute();
0c3a6e64 617 }
0c3a6e64
CW
618 }
619
77099ee0
CW
620 /**
621 * Execute api call and display the results
622 * Note: We have to manually execute the ajax in order to add the secret extra "prettyprint" param
623 */
e4176358 624 function execute() {
b308e50d 625 var footer;
e4176358
CW
626 $('#api-result').html('<div class="crm-loading-element"></div>');
627 $.ajax({
628 url: CRM.url('civicrm/ajax/rest'),
629 data: {
630 entity: entity,
631 action: action,
632 prettyprint: 1,
633 json: JSON.stringify(params)
634 },
ed0eaccc 635 type: _.includes(action, 'get') ? 'GET' : 'POST',
e4176358
CW
636 dataType: 'text'
637 }).done(function(text) {
b308e50d
CW
638 // There may be debug information appended to the end of the json string
639 var footerPos = text.indexOf("\n}<");
640 if (footerPos) {
641 footer = text.substr(footerPos + 2);
642 text = text.substr(0, footerPos + 2);
643 }
1080dff4
CW
644 $('#api-result').text(text);
645 prettyPrint('#api-result');
b308e50d
CW
646 if (footer) {
647 $('#api-result').append(footer);
648 }
e4176358 649 });
0c3a6e64 650 }
e4176358 651
89ee60d5
CW
652 /**
653 * Fetch list of example files for a given entity
654 */
655 function getExamples() {
656 CRM.utils.setOptions($('#example-action').prop('disabled', true).addClass('loading'), []);
657 $.getJSON(CRM.url('civicrm/ajax/apiexample', {entity: $(this).val()}))
658 .done(function(result) {
659 CRM.utils.setOptions($('#example-action').prop('disabled', false).removeClass('loading'), result);
660 });
661 }
662
663 /**
664 * Fetch and display an example file
665 */
666 function getExample() {
667 var
668 entity = $('#example-entity').val(),
669 action = $('#example-action').val();
670 if (entity && action) {
671 $('#example-result').block();
672 $.get(CRM.url('civicrm/ajax/apiexample', {file: entity + '/' + action}))
673 .done(function(result) {
1080dff4
CW
674 $('#example-result').unblock().text(result);
675 prettyPrint('#example-result');
89ee60d5
CW
676 });
677 } else {
65f22b4b 678 $('#example-result').text($('#example-result').attr('placeholder'));
89ee60d5
CW
679 }
680 }
681
bc4aa590
CW
682 /**
683 * Fetch entity docs & actions
684 */
685 function getDocEntity() {
686 CRM.utils.setOptions($('#doc-action').prop('disabled', true).addClass('loading'), []);
687 $.getJSON(CRM.url('civicrm/ajax/apidoc', {entity: $(this).val()}))
688 .done(function(result) {
65f22b4b 689 entityDoc = result.doc;
bc4aa590
CW
690 CRM.utils.setOptions($('#doc-action').prop('disabled', false).removeClass('loading'), result.actions);
691 $('#doc-result').html(result.doc);
fea52a54 692 prettyPrint('#doc-result pre');
bc4aa590
CW
693 });
694 }
695
696 /**
697 * Fetch entity+action docs & code
698 */
699 function getDocAction() {
700 var
701 entity = $('#doc-entity').val(),
702 action = $('#doc-action').val();
703 if (entity && action) {
704 $('#doc-result').block();
705 $.get(CRM.url('civicrm/ajax/apidoc', {entity: entity, action: action}))
706 .done(function(result) {
707 $('#doc-result').unblock().html(result.doc);
708 if (result.code) {
709 $('#doc-result').append(docCodeTpl(result));
710 }
fea52a54 711 prettyPrint('#doc-result pre');
bc4aa590
CW
712 });
713 } else {
65f22b4b 714 $('#doc-result').html(entityDoc);
fea52a54 715 prettyPrint('#doc-result pre');
bc4aa590 716 }
85470f85
PN
717 checkBookKeepingEntity(entity, action);
718 }
8777ffd1 719
85470f85
PN
720 /**
721 * Check if entity is Financial Trxn and Entity Financial Trxn
722 * and Action is Create, delete, update etc then display warning
723 */
8777ffd1 724 function checkBookKeepingEntity(entity, action) {
23989f49 725 if ($.inArray(entity, ['EntityFinancialTrxn', 'FinancialTrxn']) > -1 && $.inArray(action, ['delete', 'setvalue', 'replace', 'create']) > -1) {
85470f85
PN
726 var msg = ts('Given the importance of auditability, extension developers are strongly discouraged from writing code to add, update or delete entries in the civicrm_financial_item, civicrm_entity_financial_trxn, and civicrm_financial_trxn tables. Before publishing an extension on civicrm.org that does any of this, please ask for a special bookkeeping code review for the extension.');
727 CRM.alert(msg, 'warning');
728 }
bc4aa590
CW
729 }
730
e4176358 731 $(document).ready(function() {
89ee60d5
CW
732 // Set up tabs - bind active tab to document hash because... it's cool?
733 document.location.hash = document.location.hash || 'explorer';
734 $('#mainTabContainer')
735 .tabs({
736 active: $(document.location.hash + '-tab').index() - 1
737 })
738 .on('tabsactivate', function(e, ui) {
739 if (ui.newPanel) {
740 document.location.hash = ui.newPanel.attr('id').replace('-tab', '');
741 }
742 });
bc4aa590
CW
743 $(window).on('hashchange', function() {
744 $('#mainTabContainer').tabs('option', 'active', $(document.location.hash + '-tab').index() - 1);
745 });
89ee60d5
CW
746
747 // Initialize widgets
bc4aa590 748 $('#api-entity, #example-entity, #doc-entity').crmSelect2({
a14e9d08
CW
749 // Add strikethough class to selection to indicate deprecated apis
750 formatSelection: function(option) {
751 return $(option.element).hasClass('strikethrough') ? '<span class="strikethrough">' + option.text + '</span>' : option.text;
752 }
753 });
e4176358
CW
754 $('form#api-explorer')
755 .on('change', '#api-entity, #api-action', function() {
756 entity = $('#api-entity').val();
a14e9d08 757 action = $('#api-action').val();
2b6e1174 758 if ($(this).is('#api-entity')) {
2b6e1174 759 getActions();
a14e9d08
CW
760 } else {
761 onChangeAction(action);
2b6e1174 762 }
e4176358
CW
763 if (entity && action) {
764 $('#api-params').html('<tr><td colspan="4" class="crm-loading-element"></td></tr>');
765 $('#api-params-table thead').show();
a14e9d08 766 getFields(this);
b84efe30
CW
767 buildParams();
768 checkBookKeepingEntity(entity, action);
e4176358
CW
769 } else {
770 $('#api-params, #api-generated pre').empty();
8ffa1387 771 $('#api-param-buttons, #api-params-table thead').hide();
e4176358
CW
772 }
773 })
2b6e1174 774 .on('change keyup', 'input.api-input, #api-params select', buildParams)
e4176358
CW
775 .on('submit', submit);
776 $('#api-params')
77099ee0
CW
777 .on('change', 'input.api-param-name, select.api-param-op', renderValueField)
778 .on('change', 'input.api-param-name, .api-option-name', function() {
f76eb8ae 779 if ($(this).val() === '-' && $(this).data('select2')) {
6e29772f
CW
780 $(this)
781 .crmSelect2('destroy')
782 .val('')
783 .focus();
c275764e
CW
784 }
785 })
e4176358
CW
786 .on('click', '.api-param-remove', function(e) {
787 e.preventDefault();
788 $(this).closest('tr').remove();
789 buildParams();
3d9f5b7f
CW
790 })
791 .on('change', 'select.api-chain-entity', getChainedAction);
89ee60d5
CW
792 $('#example-entity').on('change', getExamples);
793 $('#example-action').on('change', getExample);
bc4aa590
CW
794 $('#doc-entity').on('change', getDocEntity);
795 $('#doc-action').on('change', getDocAction);
e4176358 796 $('#api-params-add').on('click', function(e) {
8ffa1387 797 e.preventDefault();
e4176358 798 addField();
8ffa1387 799 });
c275764e
CW
800 $('#api-option-add').on('click', function(e) {
801 e.preventDefault();
802 addOptionField();
803 });
8ffa1387 804 $('#api-chain-add').on('click', function(e) {
e4176358 805 e.preventDefault();
8ffa1387 806 addChainField();
e4176358
CW
807 });
808 $('#api-entity').change();
0c3a6e64 809 });
e4176358 810}(CRM.$, CRM._));