fng-reports 0.12.0-beta.31 → 0.12.0-beta.310

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,266 +1,530 @@
1
1
  'use strict';
2
2
 
3
- formsAngular.controller('AnalysisCtrl', ['$filter', '$scope', '$http', '$location', 'cssFrameworkService', 'routingService',
4
- function ($filter, $scope, $http, $location, cssFrameworkService, routingService) {
5
- /*jshint newcap: false */
6
- var firstTime = true,
7
- pdfPlugIn = new ngGridPdfExportPlugin({inhibitButton: true}),
8
- csvPlugIn = new ngGridCsvExportPlugin({inhibitButton: true});
9
- /*jshint newcap: true */
3
+ formsAngular.controller('AnalysisCtrl', ['$rootScope', '$window', '$q', '$filter', '$scope', '$http', '$location', 'CssFrameworkService', 'RoutingService', 'uiGridConstants',
4
+ function ($rootScope, $window, $q, $filter, $scope, $http, $location, CssFrameworkService, RoutingService, uiGridConstants) {
5
+ /*jshint newcap: false */
6
+ var firstTime = true,
7
+ pdfPlugIn = new ngGridPdfExportPlugin({inhibitButton: true}),
8
+ csvPlugIn = new ngGridCsvExportPlugin({inhibitButton: true});
9
+ /*jshint newcap: true */
10
10
 
11
- angular.extend($scope, routingService.parsePathFunc()($location.$$path));
11
+ angular.extend($scope, RoutingService.parsePathFunc()($location.$$path));
12
12
 
13
- $scope.reportSchema = {
14
- columnDefs: []
15
- };
16
- $scope.gridOptions = {
17
- data: 'report',
18
- columnDefs: $scope.reportSchema.columnDefs,
19
- showColumnMenu: true,
20
- enableRowHeaderSelection: false,
21
- showFilter: true,
22
- showFooter: true, // always set this to true so it works out the style
23
- reallyShowFooter: true, // this determines whether it is actually displayed or not
24
- showTotals: true,
25
- enableColumnResize: true,
26
- // enableColumnReordering: true,
27
- // jqueryUIDraggable: true,
28
- footerRowHeight: 65,
29
- multiSelect: false,
30
- plugins: [pdfPlugIn, csvPlugIn],
31
- onRegisterApi : function (gridApi) {
32
- $scope.gridApi = gridApi;
33
- gridApi.selection.on.rowSelectionChanged($scope, function afterSelectionChange(rowItem) {
34
- var url = $scope.reportSchema.drilldown;
35
- if (url) {
36
- url = routingService.buildUrl(url.replace(/\|.+?\|/g, function (match) {
37
- var param = match.slice(1, -1),
38
- isParamTest = /\((.+)\)/.exec(param);
39
- return isParamTest ? $scope.reportSchema.params[isParamTest[1]].value : rowItem.entity[param];
40
- }));
41
- window.location = url;
42
- }
43
- })
44
- },
45
- footerTemplate: '<div ng-show="gridOptions.reallyShowFooter" class="ngFooterPanel" ng-class="{\'ui-widget-content\': jqueryUITheme, \'ui-corner-bottom\': jqueryUITheme}" ' +
46
- 'ng-style="footerStyle()">' +
47
- '<div ng-show="gridOptions.showTotals" ng-style="{height: rowHeight+3}">' +
48
- '<div ng-style="{ \'cursor\': row.cursor }" ng-repeat="col in renderedColumns" ng-class="col.colIndex()" class="ngCell ngTotalCell {{col.cellClass}}">' +
49
- '<div class="ngVerticalBar" ng-style="{height: rowHeight}" ng-class="{ ngVerticalBarVisible: !$last }">&nbsp;</div>' +
50
- '<div ng-total-cell></div>' +
51
- ' </div>' +
52
- '</div>' +
53
- '<div class="ngTotalSelectContainer" >' +
54
- '<div class="ngFooterTotalItems" ng-class="{\'ngNoMultiSelect\': !multiSelect}" >' +
55
- '<span class="ngLabel">{{i18n.ngTotalItemsLabel}} {{maxRows()}}</span><span ng-show="filterText.length > 0" class="ngLabel">' +
56
- '({{i18n.ngShowingItemsLabel}} {{totalFilteredItemsLength()}})</span>' +
57
- '</div>' +
58
- '<div class="ngFooterSelectedItems" ng-show="multiSelect">' +
59
- ' <span class="ngLabel">{{i18n.ngSelectedItemsLabel}} {{selectedItems.length}}</span>' +
60
- '</div>' +
61
- '</div>' +
62
- '<div class="ngPagerContainer" style="float: right; margin-top: 10px;" ng-show="enablePaging" ng-class="{\'ngNoMultiSelect\': !multiSelect}">' +
63
- '<div style="float:left; margin-right: 10px;" class="ngRowCountPicker">' +
64
- '<span style="float: left; margin-top: 3px;" class="ngLabel">{{i18n.ngPageSizeLabel}}</span>' +
65
- '<select style="float: left;height: 27px; width: 100px" ng-model="pagingOptions.pageSize" >' +
66
- '<option ng-repeat="size in pagingOptions.pageSizes">{{size}}</option>' +
67
- '</select>' +
68
- '</div>' +
69
- '<div style="float:left; margin-right: 10px; line-height:25px;" class="ngPagerControl" style="float: left; min-width: 135px;">' +
70
- '<button class="ngPagerButton" ng-click="pageToFirst()" ng-disabled="cantPageBackward()" title="{{i18n.ngPagerFirstTitle}}">' +
71
- '<div class="ngPagerFirstTriangle"><div class="ngPagerFirstBar"></div></div></button>' +
72
- '<button class="ngPagerButton" ng-click="pageBackward()" ng-disabled="cantPageBackward()" title="{{i18n.ngPagerPrevTitle}}">' +
73
- '<div class="ngPagerFirstTriangle ngPagerPrevTriangle"></div></button>' +
74
- '<input class="ngPagerCurrent" min="1" max="{{maxPages()}}" type="number" style="width:50px; height: 24px; margin-top: 1px; padding: 0 4px;" ng-model="pagingOptions.currentPage"/>' +
75
- '<button class="ngPagerButton" ng-click="pageForward()" ng-disabled="cantPageForward()" title="{{i18n.ngPagerNextTitle}}">' +
76
- '<div class="ngPagerLastTriangle ngPagerNextTriangle"></div></button>' +
77
- '<button class="ngPagerButton" ng-click="pageToLast()" ng-disabled="cantPageToLast()" title="{{i18n.ngPagerLastTitle}}">' +
78
- '<div class="ngPagerLastTriangle"><div class="ngPagerLastBar"></div></div></button>' +
79
- '</div>' +
80
- '</div>' +
81
- '</div>'
82
- };
83
- $scope.report = [];
84
-
85
- if (!$scope.reportSchemaName && $location.$$search.r) {
86
- switch ($location.$$search.r.slice(0, 1)) {
87
- case '[' :
88
- $scope.reportSchema.pipeline = JSON.parse($location.$$search.r);
89
- break;
90
- case '{' :
91
- angular.extend($scope.reportSchema, JSON.parse($location.$$search.r));
92
- break;
93
- default :
94
- throw new Error('No report instructions specified');
95
- }
96
- }
97
-
98
- $scope.getTotalVal = function (field, filter) {
99
- var result = '',
100
- instructions = _.find($scope.reportSchema.columnDefs, function (col) {
101
- return col.field === field;
102
- });
13
+ $scope.reportSchema = {};
14
+ $scope.gridOptions = {
15
+ enableFiltering: false,
16
+ data: 'report',
17
+ columnDefs: $scope.reportSchema.columnDefs,
18
+ showColumnMenu: true,
19
+ enableRowHeaderSelection: false,
20
+ reallyShowFooter: false, // this determines whether it is actually displayed or not
21
+ showTotals: true,
22
+ enableColumnResizing: true,
23
+ footerRowHeight: 65,
24
+ multiSelect: false,
25
+ plugins: [pdfPlugIn, csvPlugIn],
26
+ onRegisterApi: function (gridApi) {
27
+ $scope.gridApi = gridApi;
28
+ $scope.gridOptions.plugins.forEach(function (p) {
29
+ p.init($scope, gridApi.grid, null);
30
+ });
31
+ gridApi.selection.on.rowSelectionChanged($scope, function afterSelectionChange(rowItem, event) {
32
+ var url = $scope.reportSchema.drilldown;
33
+ if (url) {
34
+ if (typeof url === 'string') {
35
+ // See if we are in an A tag, in which case we don't need to do anything
36
+ let inATag = event.target.tagName === 'A';
37
+ let elm = event.target;
38
+ do {
39
+ elm = elm.parentElement;
40
+ inATag = (elm && elm.tagName === 'A');
41
+ } while (elm && !inATag && elm !== rowItem);
42
+ if (!inATag) {
43
+ url = RoutingService.buildUrl(url.replace(/\|.+?\|/g, function (match) {
44
+ var param = match.slice(1, -1),
45
+ isParamTest = /\((.+)\)/.exec(param);
46
+ if (isParamTest) {
47
+ var instructions = $scope.reportSchema.params[isParamTest[1]];
48
+ if (instructions && $scope.record) {
49
+ $scope.param = $scope.record[isParamTest[1]];
50
+ if (instructions.conversionExpression) {
51
+ return $scope.$eval(instructions.conversionExpression);
52
+ } else {
53
+ return instructions.value;
54
+ }
55
+ } else {
56
+ if ($scope.reportSchema.params[isParamTest[1]]) {
57
+ return $scope.reportSchema.params[isParamTest[1]].value || '';
58
+ } else {
59
+ console.error('No value for ' + isParamTest[1]);
60
+ return 'ERR';
61
+ }
62
+ }
63
+ } else {
64
+ return rowItem.entity[param];
65
+ }
66
+ }));
67
+ window.location = url;
68
+ }
69
+ } else {
70
+ console.error('Was expecting drilldown to be string but it was ' + typeof url + ' (' + url + ')'); // trying to track down Sentry 3037641567
71
+ }
72
+ }
73
+ });
74
+ },
75
+ appScopeProvider: {
76
+ http: function ($event, method, url) {
77
+ /*
78
+ * This allows us to make an arbitrary http request from a cell template. Example:
79
+ * <div class="ui-grid-cell-contents">
80
+ * <button class="btn btn-small" data-ng-click="grid.appScope.http($event, 'GET', '/apix/queue/cancel/:id')" data-id="{{COL_FIELD}}" data-disable-button="true">
81
+ * <span class="glyphicon glyphicon-remove"></span> Cancel
82
+ * </button>
83
+ * </div>
84
+ * The value of any attribute beginning with data will replace the corresponding :attribute in the url,
85
+ * so in this case the :id in the url will be replaced by the value of the data-id attribute.
86
+ */
87
+ $event.currentTarget.getAttributeNames().forEach(a => {
88
+ if (a.startsWith('data-')) {
89
+ url = url.replace(`:${a.slice(5)}`, $event.currentTarget.getAttribute(a));
90
+ }
91
+ });
92
+ let disabledText = $event.currentTarget.getAttribute('data-disable-button');
93
+ if (disabledText) {
94
+ $event.currentTarget.setAttribute('disabled', 'disabled');
95
+ if (disabledText !== 'true') {
96
+ $event.currentTarget.innerText = disabledText;
97
+ }
98
+ }
99
+ var configObj = {
100
+ method: method,
101
+ url: url,
102
+ };
103
+ if (['POST', 'PUT', 'PATCH'].indexOf(method) !== -1) {
104
+ configObj.data = {val: $event.currentTarget.getAttribute('data-data') || {}};
105
+ }
106
+ $http(configObj)
107
+ .then(function (response) {
108
+ if (response.status !== 200) {
109
+ $scope.showError(response.statusText, 'Error');
110
+ }
111
+ });
112
+ $event.stopPropagation();
113
+ }
114
+ }
115
+ };
116
+ $scope.report = [];
103
117
 
104
- if (instructions) {
105
- switch (instructions.totalsRow) {
106
- case undefined :
107
- break;
108
- case '$SUM' :
109
- var sum = 0;
110
- for (var j = 0; j < $scope.report.length; j++) {
111
- sum += $scope.report[j][field];
118
+ function parseAndHandleError(str) {
119
+ try {
120
+ return JSON.parse(str);
121
+ } catch (e) {
122
+ throw new Error(`Invalid JSON ${str}
123
+ ${e.message}`);
112
124
  }
113
- result = sum;
114
- if (filter) {
115
- result = $filter(filter)(result);
125
+ }
126
+
127
+ if (!$scope.reportSchemaName && $location.$$search.r) {
128
+ switch ($location.$$search.r.slice(0, 1)) {
129
+ case '[' :
130
+ $scope.reportSchema.pipeline = parseAndHandleError($location.$$search.r);
131
+ break;
132
+ case '{' :
133
+ angular.extend($scope.reportSchema, parseAndHandleError($location.$$search.r));
134
+ break;
135
+ default :
136
+ throw new Error('No report instructions specified');
116
137
  }
117
- break;
118
- default :
119
- result = instructions.totalsRow;
120
- break;
121
138
  }
122
- }
123
139
 
124
- return result;
125
- };
140
+ $scope.getTotalVal = function (field, filter) {
141
+ var result = '',
142
+ instructions = _.find($scope.reportSchema.columnDefs, function (col) {
143
+ return col.field === field;
144
+ });
126
145
 
127
- $scope.$on('exportToPDF', function () {
128
- pdfPlugIn.createPDF();
129
- });
146
+ if (instructions) {
147
+ switch (instructions.totalsRow) {
148
+ case undefined :
149
+ break;
150
+ case '$SUM' :
151
+ var sum = 0;
152
+ for (var j = 0; j < $scope.report.length; j++) {
153
+ sum += $scope.report[j][field];
154
+ }
155
+ result = sum;
156
+ if (filter) {
157
+ result = $filter(filter)(result);
158
+ }
159
+ break;
160
+ default :
161
+ result = instructions.totalsRow;
162
+ break;
163
+ }
164
+ }
165
+
166
+ return result;
167
+ };
130
168
 
131
- $scope.$on('exportToCSV', function () {
132
- csvPlugIn.createCSV();
133
- });
169
+ $scope.$on('exportToPDF', function () {
170
+ pdfPlugIn.createPDF();
171
+ });
134
172
 
135
- $scope.refreshQuery = function () {
173
+ $scope.$on('exportToCSV', function () {
174
+ csvPlugIn.createCSV();
175
+ });
136
176
 
137
- var apiCall = '/api/report/' + $scope.modelName,
138
- connector = '?';
139
- if ($scope.reportSchemaName) {
140
- apiCall += '/' + $scope.reportSchemaName;
141
- }
177
+ $scope.extractFilter = function (col, filters) {
178
+ if (col.cellFilter) {
179
+ var filterName;
180
+ var filterParam;
181
+ var paramPos = col.cellFilter.indexOf(':');
182
+ if (paramPos === -1) {
183
+ filterName = col.cellFilter;
184
+ } else {
185
+ filterName = col.cellFilter.slice(0, paramPos).trim();
186
+ filterParam = col.cellFilter.slice(paramPos + 1, 999).trim();
187
+ if (filterParam[0] === '\'' || filterParam[0] === '"') {
188
+ filterParam = filterParam.slice(1, -1);
189
+ }
190
+ }
191
+ var filter = angular.element(document.body).injector().get('$filter')(filterName.trim());
192
+ filters[col.field] = {filter: filter, filterParam: filterParam};
193
+ }
194
+ };
142
195
 
143
- if ($scope.paramSchema) {
144
- // we are using the params form
145
- for (var paramVal in $scope.record) {
146
- if ($scope.record.hasOwnProperty(paramVal)) {
147
- var instructions = $scope.reportSchema.params[paramVal];
148
- if ($scope.record[paramVal] && $scope.record[paramVal] !== '') {
149
- $scope.param = $scope.record[paramVal];
150
- if (instructions.conversionExpression) {
151
- $scope.param = $scope.$eval(instructions.conversionExpression);
152
- }
153
- apiCall += connector + paramVal + '=' + $scope.param;
154
- connector = '&';
155
- } else if (instructions.required) {
156
- // Don't do a round trip if a required field is empty - it will show up red
157
- return;
196
+ function setupParamsForm(params) {
197
+ $scope.paramSchema = [];
198
+ // set up parameters
199
+ $scope.record = {};
200
+ for (var param in params) {
201
+ if (params.hasOwnProperty(param)) {
202
+ var thisPart = params[param];
203
+ // if noInput then this value will be inferred from another parameter
204
+ if (!thisPart.noInput) {
205
+ var newLen = $scope.paramSchema.push({
206
+ name: param,
207
+ id: 'fp_' + param,
208
+ label: thisPart.label || $filter('titleCase')(param),
209
+ type: thisPart.type || 'text',
210
+ required: true,
211
+ add: thisPart.add || undefined,
212
+ size: thisPart.size || (CssFrameworkService.frameWork === 'bs3' ? 'large' : 'medium')
213
+ });
214
+ if (thisPart.type === 'select') {
215
+ // TODO: Remove when select and select2 is modified during the restructure
216
+ $scope[param + '_Opts'] = thisPart.enum;
217
+ $scope.paramSchema[newLen - 1].options = param + '_Opts';
218
+ }
219
+ }
220
+ var dateTest = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3})(Z|[+ -]\d{4})$/.exec(thisPart.value);
221
+ if (dateTest) {
222
+ thisPart.value = new Date(dateTest[0]);
223
+ }
224
+ $scope.record[param] = thisPart.value;
225
+ }
158
226
  }
159
- }
227
+ $scope.$watch('record', function (newValue, oldValue) {
228
+ if (oldValue !== newValue) {
229
+ $scope.refreshQuery();
230
+ }
231
+ }, true);
160
232
  }
161
- } else {
162
- // take params of the URL
163
- var query = $location.$$url.match(/\?.*/);
164
- if (query) {
165
- apiCall += connector + query[0].slice(1);
233
+
234
+ var container = document.querySelector('div.report-grow');
235
+ if (container) {
236
+ var margin = container.offsetLeft; // let's have the same top and bottom margins as we have side margin
237
+ var topOffset = container.offsetTop + margin;
238
+ var header = document.querySelector('div.ui-grid-header');
239
+ var headerHeight = header ? header.clientHeight : 31;
240
+ var availRows = Math.floor(($window.innerHeight - topOffset - headerHeight - margin) / 30);
241
+ angular.element(container).css('height', '' + availRows * 30 + 'px');
166
242
  }
167
- }
168
- $http.get(apiCall).then(function (response) {
169
- var data = response.data;
170
- if (data.success) {
171
- $scope.report = data.report;
172
- $scope.reportSchema = data.schema;
173
- $scope.reportSchema.title = $scope.reportSchema.title || $scope.modelName;
174
- $scope.reportSchema.title = $scope.reportSchema.title.replace(/\|.+?\|/g, function (match) {
175
- var param = match.slice(1, -1);
176
- var isParamTest = /\((.+)\)/.exec(param);
177
- return isParamTest ? $scope.reportSchema.params[isParamTest[1]].value : '';
178
- });
179
243
 
180
- if (firstTime) {
181
- firstTime = false;
244
+ var navScope = $rootScope.navScope;
245
+ navScope.items = [
246
+ {
247
+ fn: pdfPlugIn.createPDF,
248
+ text: 'Save as PDF'
249
+ },
250
+ {
251
+ fn: csvPlugIn.createCSV,
252
+ text: 'Export as CSV'
253
+ }
254
+ ];
255
+ navScope.contextMenu = 'Report';
256
+ navScope.contextMenuId = 'reportMenu';
257
+ $scope.titleWithSubstitutions = $scope.reportSchema.title;
258
+
259
+ // inhibitRefresh can be set by a controller, for example if report data is being provided as part of the URL
260
+ if (!$scope.inhibitRefresh) {
261
+
262
+ $scope.refreshQuery = function () {
182
263
 
183
- $scope.$watch('reportSchema.columnDefs', function (newValue) {
184
- var columnTotals = false;
185
- if (newValue) {
186
- for (var i = 0; i < newValue.length; i++) {
187
- if (newValue[i].totalsRow) {
188
- columnTotals = true;
189
- }
190
- if (newValue[i].align) {
191
- var alignClass = 'fng-' + newValue[i].align;
192
- newValue[i].cellClass = newValue[i].cellClass || '';
193
- if (newValue[i].cellClass.indexOf(alignClass) === -1) {
194
- newValue[i].cellClass = newValue[i].cellClass + ' ' + alignClass;
264
+ function substituteParams(str) {
265
+ function toTextValue(obj, conversionExpression) {
266
+ let retVal;
267
+ if (!(obj instanceof Date)) {
268
+ if (typeof obj === 'string' && obj.match(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3} \d{4}/)) {
269
+ obj = new Date(obj.replace(' ', '+'));
270
+ }
271
+ }
272
+ if (obj instanceof Date) {
273
+ if (conversionExpression) {
274
+ $scope.param = obj;
275
+ retVal = $scope.$eval(conversionExpression);
276
+ } else {
277
+ retVal = obj.toISOString();
278
+ }
279
+ } else {
280
+ return obj;
281
+ }
282
+ return retVal;
195
283
  }
196
- }
284
+ return $q(function (resolve) {
285
+ let promises = [];
286
+ str.replace(/\|.+?\|/g, function (match) {
287
+ var param = match.slice(1, -1);
288
+ // See if we have a function to run (check for brackets)
289
+ var hasBrackets = /(.*)\((.+)\)/.exec(param);
290
+ let promise;
291
+ if (hasBrackets) {
292
+ try {
293
+ const paramsObj = $scope.reportSchema.params[hasBrackets[2]];
294
+ const paramValue = paramsObj.value;
295
+ if (hasBrackets.length > 2) {
296
+ // We may have a title function to run
297
+ if (hasBrackets[1] !== '') {
298
+ promise = $http.get(`/api/${hasBrackets[1]}/${paramValue}/list`).then(function (response) {
299
+ if (response && response.status === 200 && response.data) {
300
+ return response.data.list;
301
+ } else {
302
+ return '';
303
+ }
304
+ });
305
+ }
306
+ }
307
+ if (promise) {
308
+ promises.push(promise);
309
+ } else {
310
+ promises.push(Promise.resolve(toTextValue(paramValue, paramsObj.conversionExpression)));
311
+ }
312
+ } catch(e) {
313
+ console.error(e);
314
+ promises.push('Error in fng-reports: ' + e.message);
315
+ }
316
+ } else {
317
+ const paramsObj = $scope.reportSchema.params[param];
318
+ if (paramsObj) {
319
+ promises.push(Promise.resolve(toTextValue(paramsObj.value, paramsObj.conversionExpression)));
320
+ } else {
321
+ console.log('Cannot find param ' + param);
322
+ promises.push(Promise.resolve('ERR'));
323
+ }
324
+ }
325
+ return match;
326
+ });
327
+ Promise.all(promises).then(function (results) {
328
+ let index = 0;
329
+ resolve(str.replace(/\|.+?\|/g, function () {
330
+ let retVal = results[index];
331
+ index += 1;
332
+ return retVal;
333
+ }));
334
+ });
335
+ });
197
336
  }
198
- // Auto-upgrade from ng-grid to ui-grid
199
- newValue.forEach(function(def) {
200
- // Remove px from column widths
201
- if (def.width && typeof def.width === 'string' && def.width.indexOf('px') !== -1) {
202
- def.width = parseInt(def.width.slice(0, -2));
203
- }
204
- });
205
- $scope.gridOptions.columnDefs = newValue;
206
- }
207
- $scope.gridOptions.showTotals = columnTotals;
208
- $scope.gridOptions.reallyShowFooter = columnTotals;
209
- $scope.gridOptions.footerRowHeight = 55 + (columnTotals ? 10 : 0);
210
- }, true);
211
337
 
212
- if (!$scope.paramSchema && data.schema.params) {
213
- $scope.paramSchema = [];
214
- // set up parameters
215
- $scope.record = {};
216
- for (var param in data.schema.params) {
217
- if (data.schema.params.hasOwnProperty(param)) {
218
- var thisPart = data.schema.params[param];
219
- // if noInput then this value will be inferred from another parameter
220
- if (!thisPart.noInput) {
221
- var newLen = $scope.paramSchema.push({
222
- name: param,
223
- id: 'fp_' + param,
224
- label: thisPart.label || $filter('titleCase')(param),
225
- type: thisPart.type || 'text',
226
- required: true,
227
- add: thisPart.add || undefined,
228
- size: thisPart.size || (cssFrameworkService.frameWork === 'bs3' ? 'large' : 'medium')
229
- });
230
- if (thisPart.type === 'select') {
231
- // TODO: Remove when select and select2 is modified during the restructure
232
- $scope[param + '_Opts'] = thisPart.enum;
233
- $scope.paramSchema[newLen - 1].options = param + '_Opts';
338
+ var apiCall = '/api/report/' + $scope.modelName;
339
+ var connector = '?';
340
+ var haveUrlParams = false;
341
+ var query = $location.$$url.match(/\?.*/);
342
+
343
+ if ($scope.reportSchemaName) {
344
+ apiCall += '/' + $scope.reportSchemaName;
345
+ } else if (query) {
346
+ if (firstTime) {
347
+ // See if we have params in the URL (rather than going through schemaName)
348
+ $scope.paramSchema = JSON.parse($location.search().r).params;
349
+ setupParamsForm($scope.paramSchema);
234
350
  }
235
- }
236
- var dateTest = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3})(Z|[+ -]\d{4})$/.exec(thisPart.value);
237
- if (dateTest) {
238
- thisPart.value = (moment(dateTest[1]).format('YYYY-MM-DDTHH:mm:ss.SSS')) + 'Z';
239
- }
240
- $scope.record[param] = thisPart.value;
351
+ apiCall += connector + query[0].slice(1);
352
+ connector = '&';
353
+ haveUrlParams = true;
241
354
  }
242
- }
243
- $scope.$watch('record', function (newValue, oldValue) {
244
- if (oldValue !== newValue) {
245
- $scope.refreshQuery();
355
+
356
+ if ($scope.paramSchema) {
357
+ // we are using the params form
358
+ for (var paramVal in $scope.record) {
359
+ if ($scope.record.hasOwnProperty(paramVal)) {
360
+ var instructions = $scope.reportSchema.params[paramVal];
361
+ if ($scope.record[paramVal] && $scope.record[paramVal] !== '') {
362
+ $scope.param = $scope.record[paramVal];
363
+ if (instructions.conversionExpression) {
364
+ $scope.param = $scope.$eval(instructions.conversionExpression);
365
+ }
366
+ apiCall += connector + paramVal + '=' + $scope.param;
367
+ connector = '&';
368
+ } else if (instructions.required) {
369
+ // Don't do a round trip if a required field is empty - it will show up red
370
+ return;
371
+ }
372
+ }
373
+ }
374
+ } else {
375
+ if (!haveUrlParams && query) {
376
+ apiCall += connector + query[0].slice(1);
377
+ connector = '&';
378
+ }
246
379
  }
247
- }, true);
380
+ return $http.get(apiCall).then(function (response) {
381
+ if (response && response.data && response.data.success) {
382
+ var data = response.data;
383
+ $scope.report = data.report;
384
+ $scope.reportSchema = data.schema;
385
+ if (firstTime) {
386
+ firstTime = false;
387
+ if (data.schema.columnDefs && data.schema.columnDefs.length > 0) {
388
+ for (const colDef of data.schema.columnDefs) {
389
+ if (colDef.align) {
390
+ var alignClass = 'fng-' + colDef.align;
391
+ colDef.cellClass = colDef.cellClass || '';
392
+ if (colDef.cellClass.indexOf(alignClass) === -1) {
393
+ colDef.cellClass = colDef.cellClass + ' ' + alignClass;
394
+ }
395
+ }
396
+ if (colDef.aggregationTypeStr) {
397
+ $scope.gridOptions.showColumnFooter = true;
398
+ colDef.aggregationType = uiGridConstants.aggregationTypes[colDef.aggregationTypeStr];
399
+ if (!colDef.aggregationType) {
400
+ colDef.aggregationType = function() {return eval(colDef.aggregationTypeStr)};
401
+ }
402
+ colDef.aggregationHideLabel = colDef.aggregationTypeStr === 'sum';
403
+ colDef.footerCellFilter = colDef.cellFilter;
404
+ colDef.footerCellClass = colDef.cellClass;
405
+ }
406
+ $scope.gridOptions.columnDefs.push(colDef);
407
+ // Remove px from column widths
408
+ if (colDef.width && typeof colDef.width === 'string' && colDef.width.indexOf('px') !== -1) {
409
+ colDef.width = parseInt(colDef.width.slice(0, -2));
410
+ }
411
+ }
412
+ } else {
413
+ // Need to generate columnDefs from the data, including every field (by default the grid gets upset by records with missing data)
414
+ var allFields = new Set();
415
+ data.report.forEach(function(row) {
416
+ for (var field in row) {
417
+ allFields.add(field);
418
+ }
419
+ });
420
+ data.schema.columnDefs = Array.from(allFields).map(function(field) {
421
+ {
422
+ const colDef = { name: field };
423
+ $scope.gridOptions.columnDefs.push(colDef);
424
+ return colDef;
425
+ }
426
+ });
427
+ }
248
428
 
249
- }
250
- }
251
- } else {
252
- console.log(JSON.stringify(data));
253
- $scope.reportSchema.title = 'Error - see console log';
429
+ if (!$scope.paramSchema && data.schema.params && $location.$$search.noinput !== '1') {
430
+ setupParamsForm(data.schema.params);
431
+ }
432
+
433
+ }
434
+ $scope.reportSchema.title = $scope.reportSchema.title || $scope.modelName;
435
+ substituteParams($scope.reportSchema.title)
436
+ .then(function (str) {
437
+ $scope.titleWithSubstitutions = str;
438
+ });
439
+ $scope.gridOptions.enableFiltering = !!$scope.reportSchema.filter;
440
+ if (navScope && navScope.items) {
441
+ navScope.items.length = 2;
442
+ if ($scope.reportSchema.menu) {
443
+ $scope.reportSchema.menu.forEach(function (m) {
444
+ substituteParams(JSON.stringify(m)).then(function (str) {
445
+ navScope.items.push(JSON.parse(str));
446
+ });
447
+ });
448
+ }
449
+ }
450
+ } else {
451
+ $scope.showError(JSON.stringify(response.data.error), 'Invalid Response Error');
452
+ $scope.reportSchema.title = 'Error - see console log';
453
+ }
454
+ }, function (error) {
455
+ let body, title;
456
+ if (error.status === 403) {
457
+ body = 'You do not have permission to run this report (permission to GET all ' + $scope.modelName + ' records is required)';
458
+ title = 'Permission denied';
459
+ } else {
460
+ body = `The server could not process the request<br />Details:<br />${error.data}`;
461
+ title = 'Error';
462
+ }
463
+ $scope.showError(body, title);
464
+ });
465
+ };
466
+
467
+ $scope.refreshQuery();
254
468
  }
255
- }, function (response) {
256
- console.log(JSON.stringify(response));
257
- $location.path('/404');
258
- });
259
- };
260
469
 
261
- $scope.refreshQuery();
470
+ // Check whether a cell template shows the content (in which case we want to output it) or does something funky
471
+ // (for example displays an image)
472
+ $scope.showsContent = function (template, col) {
473
+ if (/{{[\s]*COL_FIELD[\s]*}}/.test(template.replace(/(<([^>]+)>)/gi, ''))) {
474
+ return true;
475
+ } else if (template.indexOf('ng-bind-html="row.entity.' + col) !== -1) {
476
+ return 'HTML';
477
+ }
478
+ };
479
+
480
+ $scope.$on('$locationChangeStart', function () {
481
+ navScope.clearContextMenu();
482
+ });
262
483
 
263
- }]);
484
+ // Error handling, stolen quickly from forms-angular record-handler
485
+ $scope.showError = function (error, alertTitle) {
486
+ $scope.alertTitle = alertTitle ? alertTitle : 'Error!';
487
+ if (typeof error === 'string') {
488
+ $scope.errorMessage = error;
489
+ } else if (!error) {
490
+ $scope.errorMessage = `An error occurred - that's all we got. Sorry.`;
491
+ } else if (error.message && typeof error.message === 'string') {
492
+ $scope.errorMessage = error.message;
493
+ } else if (error.data && error.data.message) {
494
+ $scope.errorMessage = error.data.message;
495
+ } else {
496
+ try {
497
+ $scope.errorMessage = JSON.stringify(error);
498
+ } catch (e) {
499
+ $scope.errorMessage = error;
500
+ }
501
+ }
502
+ $scope.errorHideTimer = window.setTimeout(function () {
503
+ $scope.dismissError();
504
+ $scope.$digest();
505
+ }, 3500 + (1000 * ($scope.alertTitle + $scope.errorMessage).length / 50));
506
+ $scope.errorVisible = true;
507
+ window.setTimeout(() => {
508
+ $scope.$digest();
509
+ });
510
+ };
511
+
512
+ $scope.clearTimeout = function () {
513
+ if ($scope.errorHideTimer) {
514
+ clearTimeout($scope.errorHideTimer);
515
+ delete $scope.errorHideTimer;
516
+ }
517
+ };
264
518
 
519
+ $scope.dismissError = function () {
520
+ $scope.clearTimeout;
521
+ $scope.errorVisible = false;
522
+ delete $scope.errorMessage;
523
+ delete $scope.alertTitle;
524
+ };
265
525
 
526
+ $scope.stickError = function () {
527
+ clearTimeout($scope.errorHideTimer);
528
+ };
266
529
 
530
+ }]);