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