Merge in 5.25
[civicrm-core.git] / ang / api4Explorer / Explorer.js
index 2affbcfdf2ca640caed9d1a3089a707e9ef51520..1db4d564f80503629b035488940bb9f78c762360 100644 (file)
     $scope.status = 'default';
     $scope.loading = false;
     $scope.controls = {};
-    $scope.code = [
-      {
-        lang: 'php',
-        style: [
-          {name: 'oop', label: ts('OOP Style'), code: ''},
-          {name: 'php', label: ts('Traditional'), code: ''}
-        ]
-      },
-      {
-        lang: 'js',
-        style: [
-          {name: 'js', label: ts('Single Call'), code: ''},
-          {name: 'js2', label: ts('Batch Calls'), code: ''}
-        ]
-      },
-      {
-        lang: 'ang',
-        style: [
-          {name: 'ang', label: ts('Single Call'), code: ''},
-          {name: 'ang2', label: ts('Batch Calls'), code: ''}
-        ]
-      },
-      {
-        lang: 'cli',
-        style: [
-          {name: 'cv', label: ts('CV'), code: ''}
-        ]
-      },
-    ];
+    $scope.langs = ['php', 'js', 'ang', 'cli'];
+    $scope.code = {
+      php: [
+        {name: 'oop', label: ts('OOP Style'), code: ''},
+        {name: 'php', label: ts('Traditional'), code: ''}
+      ],
+      js: [
+        {name: 'js', label: ts('Single Call'), code: ''},
+        {name: 'js2', label: ts('Batch Calls'), code: ''}
+      ],
+      ang: [
+        {name: 'ang', label: ts('Single Call'), code: ''},
+        {name: 'ang2', label: ts('Batch Calls'), code: ''}
+      ],
+      cli: [
+        {name: 'cv', label: ts('CV'), code: ''}
+      ]
+    };
 
     if (!entities.length) {
       formatForSelect2(schema, entities, 'name', ['description']);
     };
 
     $scope.isSpecial = function(name) {
-      var specialParams = ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having'];
-      if ($scope.availableParams.limit && $scope.availableParams.offset) {
-        specialParams.push('limit', 'offset');
-      }
+      var specialParams = ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain'];
       return _.contains(specialParams, name);
     };
 
       return isSelectRowCount($scope.params);
     };
 
+    $scope.selectLang = function(lang) {
+      $scope.selectedTab.code = lang;
+      writeCode();
+    };
+
     function isSelectRowCount(params) {
       return params && params.select && params.select.length === 1 && params.select[0] === 'row_count';
     }
               deep: format === 'json'
             });
           }
-          if (typeof objectParams[name] !== 'undefined' && name !== 'orderBy') {
-            $scope.$watch('params.' + name, function (values) {
+          if (typeof objectParams[name] !== 'undefined') {
+            $scope.$watch('params.' + name, function(values) {
               // Remove empty values
               _.each(values, function (clause, index) {
                 if (!clause || !clause[0]) {
               var field = value;
               $timeout(function() {
                 if (field) {
-                  if (typeof objectParams[name] === 'undefined') {
-                    $scope.params[name].push(field);
-                  } else {
-                    var defaultOp = _.cloneDeep(objectParams[name]);
-                    if (name === 'chain') {
-                      var num = $scope.params.chain.length;
-                      defaultOp[0] = field;
-                      field = 'name_me_' + num;
-                    }
-                    $scope.params[name].push([field, defaultOp]);
+                  var defaultOp = _.cloneDeep(objectParams[name]);
+                  if (name === 'chain') {
+                    var num = $scope.params.chain.length;
+                    defaultOp[0] = field;
+                    field = 'name_me_' + num;
                   }
+                  $scope.params[name].push([field, defaultOp]);
                   $scope.controls[name] = null;
                 }
               });
           results = result + 'Count';
         }
 
-        // Write javascript
-        var js = "'" + entity + "', '" + action + "', {";
-        _.each(params, function(param, key) {
-          js += "\n  " + key + ': ' + stringify(param) +
-            (++i < paramCount ? ',' : '');
-          if (key === 'checkPermissions') {
-            js += ' // IGNORED: permissions are always enforced from client-side requests';
-          }
-        });
-        js += "\n}";
-        if (index || index === 0) {
-          js += ', ' + JSON.stringify(index);
-        }
-        code.js = "CRM.api4(" + js + ").then(function(" + results + ") {\n  // do something with " + results + " array\n}, function(failure) {\n  // handle failure\n});";
-        code.js2 = "CRM.api4({" + results + ': [' + js + "]}).then(function(batch) {\n  // do something with batch." + results + " array\n}, function(failure) {\n  // handle failure\n});";
-        code.ang = "crmApi4(" + js + ").then(function(" + results + ") {\n  // do something with " + results + " array\n}, function(failure) {\n  // handle failure\n});";
-        code.ang2 = "crmApi4({" + results + ': [' + js + "]}).then(function(batch) {\n  // do something with batch." + results + " array\n}, function(failure) {\n  // handle failure\n});";
-
-        // Write php code
-        code.php = '$' + results + " = civicrm_api4('" + entity + "', '" + action + "', [";
-        _.each(params, function(param, key) {
-          code.php += "\n  '" + key + "' => " + phpFormat(param, 4) + ',';
-        });
-        code.php += "\n]";
-        if (index || index === 0) {
-          code.php += ', ' + phpFormat(index);
-        }
-        code.php += ");";
+        switch ($scope.selectedTab.code) {
+          case 'js':
+          case 'ang':
+            // Write javascript
+            var js = "'" + entity + "', '" + action + "', {";
+            _.each(params, function(param, key) {
+              js += "\n  " + key + ': ' + stringify(param) +
+                (++i < paramCount ? ',' : '');
+              if (key === 'checkPermissions') {
+                js += ' // IGNORED: permissions are always enforced from client-side requests';
+              }
+            });
+            js += "\n}";
+            if (index || index === 0) {
+              js += ', ' + JSON.stringify(index);
+            }
+            code.js = "CRM.api4(" + js + ").then(function(" + results + ") {\n  // do something with " + results + " array\n}, function(failure) {\n  // handle failure\n});";
+            code.js2 = "CRM.api4({" + results + ': [' + js + "]}).then(function(batch) {\n  // do something with batch." + results + " array\n}, function(failure) {\n  // handle failure\n});";
+            code.ang = "crmApi4(" + js + ").then(function(" + results + ") {\n  // do something with " + results + " array\n}, function(failure) {\n  // handle failure\n});";
+            code.ang2 = "crmApi4({" + results + ': [' + js + "]}).then(function(batch) {\n  // do something with batch." + results + " array\n}, function(failure) {\n  // handle failure\n});";
+            break;
+
+          case 'php':
+            // Write php code
+            code.php = '$' + results + " = civicrm_api4('" + entity + "', '" + action + "', [";
+            _.each(params, function(param, key) {
+              code.php += "\n  '" + key + "' => " + phpFormat(param, 4) + ',';
+            });
+            code.php += "\n]";
+            if (index || index === 0) {
+              code.php += ', ' + phpFormat(index);
+            }
+            code.php += ");";
+
+            // Write oop code
+            code.oop = '$' + results + " = " + formatOOP(entity, action, params, 2) + "\n  ->execute()";
+            if (isSelectRowCount(params)) {
+              code.oop += "\n  ->count()";
+            } else if (_.isNumber(index)) {
+              code.oop += !index ? '\n  ->first()' : (index === -1 ? '\n  ->last()' : '\n  ->itemAt(' + index + ')');
+            } else if (index) {
+              if (_.isString(index) || (_.isPlainObject(index) && !index[0] && !index['0'])) {
+                code.oop += "\n  ->indexBy('" + (_.isPlainObject(index) ? _.keys(index)[0] : index) + "')";
+              }
+              if (_.isArray(index) || _.isPlainObject(index)) {
+                code.oop += "\n  ->column('" + (_.isArray(index) ? index[0] : _.values(index)[0]) + "')";
+              }
+            }
+            code.oop += ";\n";
+            if (!_.isNumber(index) && !isSelectRowCount(params)) {
+              code.oop += "foreach ($" + results + ' as $' + ((_.isString(index) && index) ? index + ' => $' : '') + result + ') {\n  // do something\n}';
+            }
+            break;
 
-        // Write oop code
-        code.oop = '$' + results + " = " + formatOOP(entity, action, params, 2) + "\n  ->execute()";
-        if (isSelectRowCount(params)) {
-          code.oop += "\n  ->count()";
-        } else if (_.isNumber(index)) {
-          code.oop += !index ? '\n  ->first()' : (index === -1 ? '\n  ->last()' : '\n  ->itemAt(' + index + ')');
-        } else if (index) {
-          if (_.isString(index) || (_.isPlainObject(index) && !index[0] && !index['0'])) {
-            code.oop += "\n  ->indexBy('" + (_.isPlainObject(index) ? _.keys(index)[0] : index) + "')";
-          }
-          if (_.isArray(index) || _.isPlainObject(index)) {
-            code.oop += "\n  ->column('" + (_.isArray(index) ? index[0] : _.values(index)[0]) + "')";
-          }
+          case 'cli':
+            // Write cli code
+            code.cv = 'cv api4 ' + entity + '.' + action + " '" + stringify(params) + "'";
         }
-        code.oop += ";\n";
-        if (!_.isNumber(index) && !isSelectRowCount(params)) {
-          code.oop += "foreach ($" + results + ' as $' + ((_.isString(index) && index) ? index + ' => $' : '') + result + ') {\n  // do something\n}';
-        }
-
-        // Write cli code
-        code.cv = 'cv api4 ' + entity + '.' + action + " '" + stringify(params) + "'";
       }
       _.each($scope.code, function(vals) {
-        _.each(vals.style, function(style) {
+        _.each(vals, function(style) {
           style.code = code[style.name] ? prettyPrintOne(code[style.name]) : '';
         });
       });
     $scope.saveDoc = function() {
       return {
         description: ts('Save API call as a smart group.'),
-        comment: ts('Allows you to create a SavedSearch containing the WHERE clause of this API call.'),
+        comment: ts('Create a SavedSearch using these API params to populate a smart group.') +
+          '\n\n' + ts('NOTE: you must select contact id as the only field.')
       };
     };
 
     writeCode();
 
     $scope.save = function() {
+      $scope.params.limit = $scope.params.offset = 0;
+      if ($scope.params.chain.length) {
+        CRM.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires: 5000});
+        return;
+      }
+      if ($scope.params.select.length !== 1 || !_.includes($scope.params.select[0], 'id')) {
+        CRM.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires: 5000});
+        return;
+      }
       var model = {
         title: '',
         description: '',
         params: JSON.parse(angular.toJson($scope.params))
       };
       model.params.version = 4;
-      delete model.params.select;
       delete model.params.chain;
       delete model.params.debug;
       delete model.params.limit;
+      delete model.params.offset;
+      delete model.params.orderBy;
       delete model.params.checkPermissions;
       var options = CRM.utils.adjustDialogDefaults({
         width: '500px',