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