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,270 +1,534 @@
1
- /*! forms-angular 2019-02-09 */
1
+ /*! forms-angular 2025-02-09 */
2
2
  'use strict';
3
3
 
4
- formsAngular.controller('AnalysisCtrl', ['$filter', '$scope', '$http', '$location', 'cssFrameworkService', 'routingService',
5
- function ($filter, $scope, $http, $location, cssFrameworkService, routingService) {
6
- /*jshint newcap: false */
7
- var firstTime = true,
8
- pdfPlugIn = new ngGridPdfExportPlugin({inhibitButton: true}),
9
- csvPlugIn = new ngGridCsvExportPlugin({inhibitButton: true});
10
- /*jshint newcap: true */
11
-
12
- angular.extend($scope, routingService.parsePathFunc()($location.$$path));
13
-
14
- $scope.reportSchema = {
15
- columnDefs: []
16
- };
17
- $scope.gridOptions = {
18
- data: 'report',
19
- columnDefs: $scope.reportSchema.columnDefs,
20
- showColumnMenu: true,
21
- enableRowHeaderSelection: false,
22
- showFilter: true,
23
- showFooter: true, // always set this to true so it works out the style
24
- reallyShowFooter: true, // this determines whether it is actually displayed or not
25
- showTotals: true,
26
- enableColumnResize: true,
27
- // enableColumnReordering: true,
28
- // jqueryUIDraggable: true,
29
- footerRowHeight: 65,
30
- multiSelect: false,
31
- plugins: [pdfPlugIn, csvPlugIn],
32
- onRegisterApi : function (gridApi) {
33
- $scope.gridApi = gridApi;
34
- gridApi.selection.on.rowSelectionChanged($scope, function afterSelectionChange(rowItem) {
35
- var url = $scope.reportSchema.drilldown;
36
- if (url) {
37
- url = routingService.buildUrl(url.replace(/\|.+?\|/g, function (match) {
38
- var param = match.slice(1, -1),
39
- isParamTest = /\((.+)\)/.exec(param);
40
- return isParamTest ? $scope.reportSchema.params[isParamTest[1]].value : rowItem.entity[param];
41
- }));
42
- window.location = url;
43
- }
44
- })
45
- },
46
- footerTemplate: '<div ng-show="gridOptions.reallyShowFooter" class="ngFooterPanel" ng-class="{\'ui-widget-content\': jqueryUITheme, \'ui-corner-bottom\': jqueryUITheme}" ' +
47
- 'ng-style="footerStyle()">' +
48
- '<div ng-show="gridOptions.showTotals" ng-style="{height: rowHeight+3}">' +
49
- '<div ng-style="{ \'cursor\': row.cursor }" ng-repeat="col in renderedColumns" ng-class="col.colIndex()" class="ngCell ngTotalCell {{col.cellClass}}">' +
50
- '<div class="ngVerticalBar" ng-style="{height: rowHeight}" ng-class="{ ngVerticalBarVisible: !$last }">&nbsp;</div>' +
51
- '<div ng-total-cell></div>' +
52
- ' </div>' +
53
- '</div>' +
54
- '<div class="ngTotalSelectContainer" >' +
55
- '<div class="ngFooterTotalItems" ng-class="{\'ngNoMultiSelect\': !multiSelect}" >' +
56
- '<span class="ngLabel">{{i18n.ngTotalItemsLabel}} {{maxRows()}}</span><span ng-show="filterText.length > 0" class="ngLabel">' +
57
- '({{i18n.ngShowingItemsLabel}} {{totalFilteredItemsLength()}})</span>' +
58
- '</div>' +
59
- '<div class="ngFooterSelectedItems" ng-show="multiSelect">' +
60
- ' <span class="ngLabel">{{i18n.ngSelectedItemsLabel}} {{selectedItems.length}}</span>' +
61
- '</div>' +
62
- '</div>' +
63
- '<div class="ngPagerContainer" style="float: right; margin-top: 10px;" ng-show="enablePaging" ng-class="{\'ngNoMultiSelect\': !multiSelect}">' +
64
- '<div style="float:left; margin-right: 10px;" class="ngRowCountPicker">' +
65
- '<span style="float: left; margin-top: 3px;" class="ngLabel">{{i18n.ngPageSizeLabel}}</span>' +
66
- '<select style="float: left;height: 27px; width: 100px" ng-model="pagingOptions.pageSize" >' +
67
- '<option ng-repeat="size in pagingOptions.pageSizes">{{size}}</option>' +
68
- '</select>' +
69
- '</div>' +
70
- '<div style="float:left; margin-right: 10px; line-height:25px;" class="ngPagerControl" style="float: left; min-width: 135px;">' +
71
- '<button class="ngPagerButton" ng-click="pageToFirst()" ng-disabled="cantPageBackward()" title="{{i18n.ngPagerFirstTitle}}">' +
72
- '<div class="ngPagerFirstTriangle"><div class="ngPagerFirstBar"></div></div></button>' +
73
- '<button class="ngPagerButton" ng-click="pageBackward()" ng-disabled="cantPageBackward()" title="{{i18n.ngPagerPrevTitle}}">' +
74
- '<div class="ngPagerFirstTriangle ngPagerPrevTriangle"></div></button>' +
75
- '<input class="ngPagerCurrent" min="1" max="{{maxPages()}}" type="number" style="width:50px; height: 24px; margin-top: 1px; padding: 0 4px;" ng-model="pagingOptions.currentPage"/>' +
76
- '<button class="ngPagerButton" ng-click="pageForward()" ng-disabled="cantPageForward()" title="{{i18n.ngPagerNextTitle}}">' +
77
- '<div class="ngPagerLastTriangle ngPagerNextTriangle"></div></button>' +
78
- '<button class="ngPagerButton" ng-click="pageToLast()" ng-disabled="cantPageToLast()" title="{{i18n.ngPagerLastTitle}}">' +
79
- '<div class="ngPagerLastTriangle"><div class="ngPagerLastBar"></div></div></button>' +
80
- '</div>' +
81
- '</div>' +
82
- '</div>'
83
- };
84
- $scope.report = [];
85
-
86
- if (!$scope.reportSchemaName && $location.$$search.r) {
87
- switch ($location.$$search.r.slice(0, 1)) {
88
- case '[' :
89
- $scope.reportSchema.pipeline = JSON.parse($location.$$search.r);
90
- break;
91
- case '{' :
92
- angular.extend($scope.reportSchema, JSON.parse($location.$$search.r));
93
- break;
94
- default :
95
- throw new Error('No report instructions specified');
96
- }
97
- }
98
-
99
- $scope.getTotalVal = function (field, filter) {
100
- var result = '',
101
- instructions = _.find($scope.reportSchema.columnDefs, function (col) {
102
- return col.field === field;
103
- });
104
-
105
- if (instructions) {
106
- switch (instructions.totalsRow) {
107
- case undefined :
108
- break;
109
- case '$SUM' :
110
- var sum = 0;
111
- for (var j = 0; j < $scope.report.length; j++) {
112
- sum += $scope.report[j][field];
4
+ formsAngular.controller('AnalysisCtrl', ['$rootScope', '$window', '$q', '$filter', '$scope', '$http', '$location', 'CssFrameworkService', 'RoutingService', 'uiGridConstants',
5
+ function ($rootScope, $window, $q, $filter, $scope, $http, $location, CssFrameworkService, RoutingService, uiGridConstants) {
6
+ /*jshint newcap: false */
7
+ var firstTime = true,
8
+ pdfPlugIn = new ngGridPdfExportPlugin({inhibitButton: true}),
9
+ csvPlugIn = new ngGridCsvExportPlugin({inhibitButton: true});
10
+ /*jshint newcap: true */
11
+
12
+ angular.extend($scope, RoutingService.parsePathFunc()($location.$$path));
13
+
14
+ $scope.reportSchema = {};
15
+ $scope.gridOptions = {
16
+ enableFiltering: false,
17
+ data: 'report',
18
+ columnDefs: $scope.reportSchema.columnDefs,
19
+ showColumnMenu: true,
20
+ enableRowHeaderSelection: false,
21
+ reallyShowFooter: false, // this determines whether it is actually displayed or not
22
+ showTotals: true,
23
+ enableColumnResizing: true,
24
+ footerRowHeight: 65,
25
+ multiSelect: false,
26
+ plugins: [pdfPlugIn, csvPlugIn],
27
+ onRegisterApi: function (gridApi) {
28
+ $scope.gridApi = gridApi;
29
+ $scope.gridOptions.plugins.forEach(function (p) {
30
+ p.init($scope, gridApi.grid, null);
31
+ });
32
+ gridApi.selection.on.rowSelectionChanged($scope, function afterSelectionChange(rowItem, event) {
33
+ var url = $scope.reportSchema.drilldown;
34
+ if (url) {
35
+ if (typeof url === 'string') {
36
+ // See if we are in an A tag, in which case we don't need to do anything
37
+ let inATag = event.target.tagName === 'A';
38
+ let elm = event.target;
39
+ do {
40
+ elm = elm.parentElement;
41
+ inATag = (elm && elm.tagName === 'A');
42
+ } while (elm && !inATag && elm !== rowItem);
43
+ if (!inATag) {
44
+ url = RoutingService.buildUrl(url.replace(/\|.+?\|/g, function (match) {
45
+ var param = match.slice(1, -1),
46
+ isParamTest = /\((.+)\)/.exec(param);
47
+ if (isParamTest) {
48
+ var instructions = $scope.reportSchema.params[isParamTest[1]];
49
+ if (instructions && $scope.record) {
50
+ $scope.param = $scope.record[isParamTest[1]];
51
+ if (instructions.conversionExpression) {
52
+ return $scope.$eval(instructions.conversionExpression);
53
+ } else {
54
+ return instructions.value;
55
+ }
56
+ } else {
57
+ if ($scope.reportSchema.params[isParamTest[1]]) {
58
+ return $scope.reportSchema.params[isParamTest[1]].value || '';
59
+ } else {
60
+ console.error('No value for ' + isParamTest[1]);
61
+ return 'ERR';
62
+ }
63
+ }
64
+ } else {
65
+ return rowItem.entity[param];
66
+ }
67
+ }));
68
+ window.location = url;
69
+ }
70
+ } else {
71
+ console.error('Was expecting drilldown to be string but it was ' + typeof url + ' (' + url + ')'); // trying to track down Sentry 3037641567
72
+ }
73
+ }
74
+ });
75
+ },
76
+ appScopeProvider: {
77
+ http: function ($event, method, url) {
78
+ /*
79
+ * This allows us to make an arbitrary http request from a cell template. Example:
80
+ * <div class="ui-grid-cell-contents">
81
+ * <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">
82
+ * <span class="glyphicon glyphicon-remove"></span> Cancel
83
+ * </button>
84
+ * </div>
85
+ * The value of any attribute beginning with data will replace the corresponding :attribute in the url,
86
+ * so in this case the :id in the url will be replaced by the value of the data-id attribute.
87
+ */
88
+ $event.currentTarget.getAttributeNames().forEach(a => {
89
+ if (a.startsWith('data-')) {
90
+ url = url.replace(`:${a.slice(5)}`, $event.currentTarget.getAttribute(a));
91
+ }
92
+ });
93
+ let disabledText = $event.currentTarget.getAttribute('data-disable-button');
94
+ if (disabledText) {
95
+ $event.currentTarget.setAttribute('disabled', 'disabled');
96
+ if (disabledText !== 'true') {
97
+ $event.currentTarget.innerText = disabledText;
98
+ }
99
+ }
100
+ var configObj = {
101
+ method: method,
102
+ url: url,
103
+ };
104
+ if (['POST', 'PUT', 'PATCH'].indexOf(method) !== -1) {
105
+ configObj.data = {val: $event.currentTarget.getAttribute('data-data') || {}};
106
+ }
107
+ $http(configObj)
108
+ .then(function (response) {
109
+ if (response.status !== 200) {
110
+ $scope.showError(response.statusText, 'Error');
111
+ }
112
+ });
113
+ $event.stopPropagation();
114
+ }
113
115
  }
114
- result = sum;
115
- if (filter) {
116
- result = $filter(filter)(result);
116
+ };
117
+ $scope.report = [];
118
+
119
+ function parseAndHandleError(str) {
120
+ try {
121
+ return JSON.parse(str);
122
+ } catch (e) {
123
+ throw new Error(`Invalid JSON ${str}
124
+ ${e.message}`);
117
125
  }
118
- break;
119
- default :
120
- result = instructions.totalsRow;
121
- break;
122
126
  }
123
- }
124
127
 
125
- return result;
126
- };
128
+ if (!$scope.reportSchemaName && $location.$$search.r) {
129
+ switch ($location.$$search.r.slice(0, 1)) {
130
+ case '[' :
131
+ $scope.reportSchema.pipeline = parseAndHandleError($location.$$search.r);
132
+ break;
133
+ case '{' :
134
+ angular.extend($scope.reportSchema, parseAndHandleError($location.$$search.r));
135
+ break;
136
+ default :
137
+ throw new Error('No report instructions specified');
138
+ }
139
+ }
127
140
 
128
- $scope.$on('exportToPDF', function () {
129
- pdfPlugIn.createPDF();
130
- });
141
+ $scope.getTotalVal = function (field, filter) {
142
+ var result = '',
143
+ instructions = _.find($scope.reportSchema.columnDefs, function (col) {
144
+ return col.field === field;
145
+ });
131
146
 
132
- $scope.$on('exportToCSV', function () {
133
- csvPlugIn.createCSV();
134
- });
147
+ if (instructions) {
148
+ switch (instructions.totalsRow) {
149
+ case undefined :
150
+ break;
151
+ case '$SUM' :
152
+ var sum = 0;
153
+ for (var j = 0; j < $scope.report.length; j++) {
154
+ sum += $scope.report[j][field];
155
+ }
156
+ result = sum;
157
+ if (filter) {
158
+ result = $filter(filter)(result);
159
+ }
160
+ break;
161
+ default :
162
+ result = instructions.totalsRow;
163
+ break;
164
+ }
165
+ }
135
166
 
136
- $scope.refreshQuery = function () {
167
+ return result;
168
+ };
137
169
 
138
- var apiCall = '/api/report/' + $scope.modelName,
139
- connector = '?';
140
- if ($scope.reportSchemaName) {
141
- apiCall += '/' + $scope.reportSchemaName;
142
- }
170
+ $scope.$on('exportToPDF', function () {
171
+ pdfPlugIn.createPDF();
172
+ });
143
173
 
144
- if ($scope.paramSchema) {
145
- // we are using the params form
146
- for (var paramVal in $scope.record) {
147
- if ($scope.record.hasOwnProperty(paramVal)) {
148
- var instructions = $scope.reportSchema.params[paramVal];
149
- if ($scope.record[paramVal] && $scope.record[paramVal] !== '') {
150
- $scope.param = $scope.record[paramVal];
151
- if (instructions.conversionExpression) {
152
- $scope.param = $scope.$eval(instructions.conversionExpression);
153
- }
154
- apiCall += connector + paramVal + '=' + $scope.param;
155
- connector = '&';
156
- } else if (instructions.required) {
157
- // Don't do a round trip if a required field is empty - it will show up red
158
- return;
159
- }
160
- }
161
- }
162
- } else {
163
- // take params of the URL
164
- var query = $location.$$url.match(/\?.*/);
165
- if (query) {
166
- apiCall += connector + query[0].slice(1);
167
- }
168
- }
169
- $http.get(apiCall).then(function (response) {
170
- var data = response.data;
171
- if (data.success) {
172
- $scope.report = data.report;
173
- $scope.reportSchema = data.schema;
174
- $scope.reportSchema.title = $scope.reportSchema.title || $scope.modelName;
175
- $scope.reportSchema.title = $scope.reportSchema.title.replace(/\|.+?\|/g, function (match) {
176
- var param = match.slice(1, -1);
177
- var isParamTest = /\((.+)\)/.exec(param);
178
- return isParamTest ? $scope.reportSchema.params[isParamTest[1]].value : '';
179
- });
174
+ $scope.$on('exportToCSV', function () {
175
+ csvPlugIn.createCSV();
176
+ });
180
177
 
181
- if (firstTime) {
182
- firstTime = false;
183
-
184
- $scope.$watch('reportSchema.columnDefs', function (newValue) {
185
- var columnTotals = false;
186
- if (newValue) {
187
- for (var i = 0; i < newValue.length; i++) {
188
- if (newValue[i].totalsRow) {
189
- columnTotals = true;
190
- }
191
- if (newValue[i].align) {
192
- var alignClass = 'fng-' + newValue[i].align;
193
- newValue[i].cellClass = newValue[i].cellClass || '';
194
- if (newValue[i].cellClass.indexOf(alignClass) === -1) {
195
- newValue[i].cellClass = newValue[i].cellClass + ' ' + alignClass;
178
+ $scope.extractFilter = function (col, filters) {
179
+ if (col.cellFilter) {
180
+ var filterName;
181
+ var filterParam;
182
+ var paramPos = col.cellFilter.indexOf(':');
183
+ if (paramPos === -1) {
184
+ filterName = col.cellFilter;
185
+ } else {
186
+ filterName = col.cellFilter.slice(0, paramPos).trim();
187
+ filterParam = col.cellFilter.slice(paramPos + 1, 999).trim();
188
+ if (filterParam[0] === '\'' || filterParam[0] === '"') {
189
+ filterParam = filterParam.slice(1, -1);
196
190
  }
197
- }
198
191
  }
199
- // Auto-upgrade from ng-grid to ui-grid
200
- newValue.forEach(function(def) {
201
- // Remove px from column widths
202
- if (def.width && typeof def.width === 'string' && def.width.indexOf('px') !== -1) {
203
- def.width = parseInt(def.width.slice(0, -2));
192
+ var filter = angular.element(document.body).injector().get('$filter')(filterName.trim());
193
+ filters[col.field] = {filter: filter, filterParam: filterParam};
194
+ }
195
+ };
196
+
197
+ function setupParamsForm(params) {
198
+ $scope.paramSchema = [];
199
+ // set up parameters
200
+ $scope.record = {};
201
+ for (var param in params) {
202
+ if (params.hasOwnProperty(param)) {
203
+ var thisPart = params[param];
204
+ // if noInput then this value will be inferred from another parameter
205
+ if (!thisPart.noInput) {
206
+ var newLen = $scope.paramSchema.push({
207
+ name: param,
208
+ id: 'fp_' + param,
209
+ label: thisPart.label || $filter('titleCase')(param),
210
+ type: thisPart.type || 'text',
211
+ required: true,
212
+ add: thisPart.add || undefined,
213
+ size: thisPart.size || (CssFrameworkService.frameWork === 'bs3' ? 'large' : 'medium')
214
+ });
215
+ if (thisPart.type === 'select') {
216
+ // TODO: Remove when select and select2 is modified during the restructure
217
+ $scope[param + '_Opts'] = thisPart.enum;
218
+ $scope.paramSchema[newLen - 1].options = param + '_Opts';
219
+ }
204
220
  }
205
- });
206
- $scope.gridOptions.columnDefs = newValue;
207
- }
208
- $scope.gridOptions.showTotals = columnTotals;
209
- $scope.gridOptions.reallyShowFooter = columnTotals;
210
- $scope.gridOptions.footerRowHeight = 55 + (columnTotals ? 10 : 0);
221
+ var dateTest = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3})(Z|[+ -]\d{4})$/.exec(thisPart.value);
222
+ if (dateTest) {
223
+ thisPart.value = new Date(dateTest[0]);
224
+ }
225
+ $scope.record[param] = thisPart.value;
226
+ }
227
+ }
228
+ $scope.$watch('record', function (newValue, oldValue) {
229
+ if (oldValue !== newValue) {
230
+ $scope.refreshQuery();
231
+ }
211
232
  }, true);
233
+ }
212
234
 
213
- if (!$scope.paramSchema && data.schema.params) {
214
- $scope.paramSchema = [];
215
- // set up parameters
216
- $scope.record = {};
217
- for (var param in data.schema.params) {
218
- if (data.schema.params.hasOwnProperty(param)) {
219
- var thisPart = data.schema.params[param];
220
- // if noInput then this value will be inferred from another parameter
221
- if (!thisPart.noInput) {
222
- var newLen = $scope.paramSchema.push({
223
- name: param,
224
- id: 'fp_' + param,
225
- label: thisPart.label || $filter('titleCase')(param),
226
- type: thisPart.type || 'text',
227
- required: true,
228
- add: thisPart.add || undefined,
229
- size: thisPart.size || (cssFrameworkService.frameWork === 'bs3' ? 'large' : 'medium')
235
+ var container = document.querySelector('div.report-grow');
236
+ if (container) {
237
+ var margin = container.offsetLeft; // let's have the same top and bottom margins as we have side margin
238
+ var topOffset = container.offsetTop + margin;
239
+ var header = document.querySelector('div.ui-grid-header');
240
+ var headerHeight = header ? header.clientHeight : 31;
241
+ var availRows = Math.floor(($window.innerHeight - topOffset - headerHeight - margin) / 30);
242
+ angular.element(container).css('height', '' + availRows * 30 + 'px');
243
+ }
244
+
245
+ var navScope = $rootScope.navScope;
246
+ navScope.items = [
247
+ {
248
+ fn: pdfPlugIn.createPDF,
249
+ text: 'Save as PDF'
250
+ },
251
+ {
252
+ fn: csvPlugIn.createCSV,
253
+ text: 'Export as CSV'
254
+ }
255
+ ];
256
+ navScope.contextMenu = 'Report';
257
+ navScope.contextMenuId = 'reportMenu';
258
+ $scope.titleWithSubstitutions = $scope.reportSchema.title;
259
+
260
+ // inhibitRefresh can be set by a controller, for example if report data is being provided as part of the URL
261
+ if (!$scope.inhibitRefresh) {
262
+
263
+ $scope.refreshQuery = function () {
264
+
265
+ function substituteParams(str) {
266
+ function toTextValue(obj, conversionExpression) {
267
+ let retVal;
268
+ if (!(obj instanceof Date)) {
269
+ if (typeof obj === 'string' && obj.match(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3} \d{4}/)) {
270
+ obj = new Date(obj.replace(' ', '+'));
271
+ }
272
+ }
273
+ if (obj instanceof Date) {
274
+ if (conversionExpression) {
275
+ $scope.param = obj;
276
+ retVal = $scope.$eval(conversionExpression);
277
+ } else {
278
+ retVal = obj.toISOString();
279
+ }
280
+ } else {
281
+ return obj;
282
+ }
283
+ return retVal;
284
+ }
285
+ return $q(function (resolve) {
286
+ let promises = [];
287
+ str.replace(/\|.+?\|/g, function (match) {
288
+ var param = match.slice(1, -1);
289
+ // See if we have a function to run (check for brackets)
290
+ var hasBrackets = /(.*)\((.+)\)/.exec(param);
291
+ let promise;
292
+ if (hasBrackets) {
293
+ try {
294
+ const paramsObj = $scope.reportSchema.params[hasBrackets[2]];
295
+ const paramValue = paramsObj.value;
296
+ if (hasBrackets.length > 2) {
297
+ // We may have a title function to run
298
+ if (hasBrackets[1] !== '') {
299
+ promise = $http.get(`/api/${hasBrackets[1]}/${paramValue}/list`).then(function (response) {
300
+ if (response && response.status === 200 && response.data) {
301
+ return response.data.list;
302
+ } else {
303
+ return '';
304
+ }
305
+ });
306
+ }
307
+ }
308
+ if (promise) {
309
+ promises.push(promise);
310
+ } else {
311
+ promises.push(Promise.resolve(toTextValue(paramValue, paramsObj.conversionExpression)));
312
+ }
313
+ } catch(e) {
314
+ console.error(e);
315
+ promises.push('Error in fng-reports: ' + e.message);
316
+ }
317
+ } else {
318
+ const paramsObj = $scope.reportSchema.params[param];
319
+ if (paramsObj) {
320
+ promises.push(Promise.resolve(toTextValue(paramsObj.value, paramsObj.conversionExpression)));
321
+ } else {
322
+ console.log('Cannot find param ' + param);
323
+ promises.push(Promise.resolve('ERR'));
324
+ }
325
+ }
326
+ return match;
327
+ });
328
+ Promise.all(promises).then(function (results) {
329
+ let index = 0;
330
+ resolve(str.replace(/\|.+?\|/g, function () {
331
+ let retVal = results[index];
332
+ index += 1;
333
+ return retVal;
334
+ }));
335
+ });
230
336
  });
231
- if (thisPart.type === 'select') {
232
- // TODO: Remove when select and select2 is modified during the restructure
233
- $scope[param + '_Opts'] = thisPart.enum;
234
- $scope.paramSchema[newLen - 1].options = param + '_Opts';
337
+ }
338
+
339
+ var apiCall = '/api/report/' + $scope.modelName;
340
+ var connector = '?';
341
+ var haveUrlParams = false;
342
+ var query = $location.$$url.match(/\?.*/);
343
+
344
+ if ($scope.reportSchemaName) {
345
+ apiCall += '/' + $scope.reportSchemaName;
346
+ } else if (query) {
347
+ if (firstTime) {
348
+ // See if we have params in the URL (rather than going through schemaName)
349
+ $scope.paramSchema = JSON.parse($location.search().r).params;
350
+ setupParamsForm($scope.paramSchema);
235
351
  }
236
- }
237
- var dateTest = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3})(Z|[+ -]\d{4})$/.exec(thisPart.value);
238
- if (dateTest) {
239
- thisPart.value = (moment(dateTest[1]).format('YYYY-MM-DDTHH:mm:ss.SSS')) + 'Z';
240
- }
241
- $scope.record[param] = thisPart.value;
352
+ apiCall += connector + query[0].slice(1);
353
+ connector = '&';
354
+ haveUrlParams = true;
242
355
  }
243
- }
244
- $scope.$watch('record', function (newValue, oldValue) {
245
- if (oldValue !== newValue) {
246
- $scope.refreshQuery();
356
+
357
+ if ($scope.paramSchema) {
358
+ // we are using the params form
359
+ for (var paramVal in $scope.record) {
360
+ if ($scope.record.hasOwnProperty(paramVal)) {
361
+ var instructions = $scope.reportSchema.params[paramVal];
362
+ if ($scope.record[paramVal] && $scope.record[paramVal] !== '') {
363
+ $scope.param = $scope.record[paramVal];
364
+ if (instructions.conversionExpression) {
365
+ $scope.param = $scope.$eval(instructions.conversionExpression);
366
+ }
367
+ apiCall += connector + paramVal + '=' + $scope.param;
368
+ connector = '&';
369
+ } else if (instructions.required) {
370
+ // Don't do a round trip if a required field is empty - it will show up red
371
+ return;
372
+ }
373
+ }
374
+ }
375
+ } else {
376
+ if (!haveUrlParams && query) {
377
+ apiCall += connector + query[0].slice(1);
378
+ connector = '&';
379
+ }
247
380
  }
248
- }, true);
381
+ return $http.get(apiCall).then(function (response) {
382
+ if (response && response.data && response.data.success) {
383
+ var data = response.data;
384
+ $scope.report = data.report;
385
+ $scope.reportSchema = data.schema;
386
+ if (firstTime) {
387
+ firstTime = false;
388
+ if (data.schema.columnDefs && data.schema.columnDefs.length > 0) {
389
+ for (const colDef of data.schema.columnDefs) {
390
+ if (colDef.align) {
391
+ var alignClass = 'fng-' + colDef.align;
392
+ colDef.cellClass = colDef.cellClass || '';
393
+ if (colDef.cellClass.indexOf(alignClass) === -1) {
394
+ colDef.cellClass = colDef.cellClass + ' ' + alignClass;
395
+ }
396
+ }
397
+ if (colDef.aggregationTypeStr) {
398
+ $scope.gridOptions.showColumnFooter = true;
399
+ colDef.aggregationType = uiGridConstants.aggregationTypes[colDef.aggregationTypeStr];
400
+ if (!colDef.aggregationType) {
401
+ colDef.aggregationType = function() {return eval(colDef.aggregationTypeStr)};
402
+ }
403
+ colDef.aggregationHideLabel = colDef.aggregationTypeStr === 'sum';
404
+ colDef.footerCellFilter = colDef.cellFilter;
405
+ colDef.footerCellClass = colDef.cellClass;
406
+ }
407
+ $scope.gridOptions.columnDefs.push(colDef);
408
+ // Remove px from column widths
409
+ if (colDef.width && typeof colDef.width === 'string' && colDef.width.indexOf('px') !== -1) {
410
+ colDef.width = parseInt(colDef.width.slice(0, -2));
411
+ }
412
+ }
413
+ } else {
414
+ // Need to generate columnDefs from the data, including every field (by default the grid gets upset by records with missing data)
415
+ var allFields = new Set();
416
+ data.report.forEach(function(row) {
417
+ for (var field in row) {
418
+ allFields.add(field);
419
+ }
420
+ });
421
+ data.schema.columnDefs = Array.from(allFields).map(function(field) {
422
+ {
423
+ const colDef = { name: field };
424
+ $scope.gridOptions.columnDefs.push(colDef);
425
+ return colDef;
426
+ }
427
+ });
428
+ }
429
+
430
+ if (!$scope.paramSchema && data.schema.params && $location.$$search.noinput !== '1') {
431
+ setupParamsForm(data.schema.params);
432
+ }
433
+
434
+ }
435
+ $scope.reportSchema.title = $scope.reportSchema.title || $scope.modelName;
436
+ substituteParams($scope.reportSchema.title)
437
+ .then(function (str) {
438
+ $scope.titleWithSubstitutions = str;
439
+ });
440
+ $scope.gridOptions.enableFiltering = !!$scope.reportSchema.filter;
441
+ if (navScope && navScope.items) {
442
+ navScope.items.length = 2;
443
+ if ($scope.reportSchema.menu) {
444
+ $scope.reportSchema.menu.forEach(function (m) {
445
+ substituteParams(JSON.stringify(m)).then(function (str) {
446
+ navScope.items.push(JSON.parse(str));
447
+ });
448
+ });
449
+ }
450
+ }
451
+ } else {
452
+ $scope.showError(JSON.stringify(response.data.error), 'Invalid Response Error');
453
+ $scope.reportSchema.title = 'Error - see console log';
454
+ }
455
+ }, function (error) {
456
+ let body, title;
457
+ if (error.status === 403) {
458
+ body = 'You do not have permission to run this report (permission to GET all ' + $scope.modelName + ' records is required)';
459
+ title = 'Permission denied';
460
+ } else {
461
+ body = `The server could not process the request<br />Details:<br />${error.data}`;
462
+ title = 'Error';
463
+ }
464
+ $scope.showError(body, title);
465
+ });
466
+ };
249
467
 
250
- }
251
- }
252
- } else {
253
- console.log(JSON.stringify(data));
254
- $scope.reportSchema.title = 'Error - see console log';
468
+ $scope.refreshQuery();
255
469
  }
256
- }, function (response) {
257
- console.log(JSON.stringify(response));
258
- $location.path('/404');
259
- });
260
- };
261
470
 
262
- $scope.refreshQuery();
471
+ // Check whether a cell template shows the content (in which case we want to output it) or does something funky
472
+ // (for example displays an image)
473
+ $scope.showsContent = function (template, col) {
474
+ if (/{{[\s]*COL_FIELD[\s]*}}/.test(template.replace(/(<([^>]+)>)/gi, ''))) {
475
+ return true;
476
+ } else if (template.indexOf('ng-bind-html="row.entity.' + col) !== -1) {
477
+ return 'HTML';
478
+ }
479
+ };
263
480
 
264
- }]);
481
+ $scope.$on('$locationChangeStart', function () {
482
+ navScope.clearContextMenu();
483
+ });
265
484
 
485
+ // Error handling, stolen quickly from forms-angular record-handler
486
+ $scope.showError = function (error, alertTitle) {
487
+ $scope.alertTitle = alertTitle ? alertTitle : 'Error!';
488
+ if (typeof error === 'string') {
489
+ $scope.errorMessage = error;
490
+ } else if (!error) {
491
+ $scope.errorMessage = `An error occurred - that's all we got. Sorry.`;
492
+ } else if (error.message && typeof error.message === 'string') {
493
+ $scope.errorMessage = error.message;
494
+ } else if (error.data && error.data.message) {
495
+ $scope.errorMessage = error.data.message;
496
+ } else {
497
+ try {
498
+ $scope.errorMessage = JSON.stringify(error);
499
+ } catch (e) {
500
+ $scope.errorMessage = error;
501
+ }
502
+ }
503
+ $scope.errorHideTimer = window.setTimeout(function () {
504
+ $scope.dismissError();
505
+ $scope.$digest();
506
+ }, 3500 + (1000 * ($scope.alertTitle + $scope.errorMessage).length / 50));
507
+ $scope.errorVisible = true;
508
+ window.setTimeout(() => {
509
+ $scope.$digest();
510
+ });
511
+ };
512
+
513
+ $scope.clearTimeout = function () {
514
+ if ($scope.errorHideTimer) {
515
+ clearTimeout($scope.errorHideTimer);
516
+ delete $scope.errorHideTimer;
517
+ }
518
+ };
519
+
520
+ $scope.dismissError = function () {
521
+ $scope.clearTimeout;
522
+ $scope.errorVisible = false;
523
+ delete $scope.errorMessage;
524
+ delete $scope.alertTitle;
525
+ };
266
526
 
527
+ $scope.stickError = function () {
528
+ clearTimeout($scope.errorHideTimer);
529
+ };
267
530
 
531
+ }]);
268
532
 
269
533
  'use strict';
270
534
  var COL_FIELD = /COL_FIELD/g;
@@ -323,57 +587,46 @@ function ngGridCsvExportPlugin(opts) {
323
587
  var self = this;
324
588
  self.grid = null;
325
589
  self.scope = null;
590
+ self.services = null;
326
591
 
327
592
  self.init = function (scope, grid, services) {
328
-
329
- function doDownloadButton() {
330
- var fp = angular.element('h1').parent();
331
- var csvDataLinkPrevious = angular.element('#csv-data-link');
332
- if (csvDataLinkPrevious != null) {
333
- csvDataLinkPrevious.remove();
334
- }
335
- var csvDataLinkHtml = "<button id=\"csv-data-link\" class=\"btn\"><a href=\"data:text/csv;charset=UTF-8,";
336
- csvDataLinkHtml += encodeURIComponent(self.prepareCSV());
337
- csvDataLinkHtml += "\" download=\"Export.csv\">CSV Export</button>";
338
- fp.append(csvDataLinkHtml);
339
- }
340
-
341
593
  self.grid = grid;
342
594
  self.scope = scope;
343
-
344
- if (!opts.inhibitButton) {
345
- setTimeout(doDownloadButton, 0);
346
- scope.catHashKeys = function () {
347
- var hash = '';
348
- for (var idx in scope.renderedRows) {
349
- hash += scope.renderedRows[idx].$$hashKey;
350
- }
351
- return hash;
352
- };
353
- scope.$watch('catHashKeys()', doDownloadButton);
354
- }
595
+ self.services = services;
355
596
  };
356
597
 
598
+ function downloadFile(fileName, urlData) {
599
+
600
+ var aLink = document.createElement('a');
601
+ aLink.download = fileName;
602
+ aLink.href = urlData;
603
+
604
+ var event = new MouseEvent('click');
605
+ aLink.dispatchEvent(event);
606
+ }
607
+
357
608
  self.createCSV = function () {
358
- window.open('data:text/csv;charset=UTF-8,' + encodeURIComponent(self.prepareCSV()));
609
+ downloadFile((self.scope.titleWithSubstitutions || self.scope.reportSchema.title) + '.csv','data:text/csv;charset=UTF-8,' + encodeURIComponent(self.prepareCSV()));
359
610
  };
360
611
 
361
612
  self.prepareCSV = function () {
362
613
 
363
- function csvStringify(str) {
614
+ function csvStringify(str, filter) {
364
615
  if (str == null) { // we want to catch anything null-ish, hence just == not ===
365
616
  return '';
366
617
  }
367
- if (typeof(str) === 'number') {
618
+ if (filter) {
619
+ return filter.filter(str, filter.filterParam);
620
+ }
621
+ if (typeof (str) === 'number') {
368
622
  return '' + str;
369
623
  }
370
- if (typeof(str) === 'boolean') {
624
+ if (typeof (str) === 'boolean') {
371
625
  return (str ? 'TRUE' : 'FALSE');
372
626
  }
373
- if (typeof(str) === 'string') {
627
+ if (typeof (str) === 'string') {
374
628
  return str.replace(/"/g, '""');
375
629
  }
376
-
377
630
  return JSON.stringify(str).replace(/"/g, '""');
378
631
  }
379
632
 
@@ -383,21 +636,60 @@ function ngGridCsvExportPlugin(opts) {
383
636
  }
384
637
 
385
638
  var csvData = '';
386
- angular.forEach(self.scope.columns, function (col) {
387
- if (col.visible && (col.width === undefined || col.width > 0)) {
388
- csvData += '"' + csvStringify(col.displayName) + '",';
639
+ var filters = {};
640
+ angular.forEach(self.grid.columns, function (col) {
641
+ self.scope.extractFilter(col, filters);
642
+ if (col.visible && (col.width === undefined || col.width === '*' || col.width > 0)) {
643
+ if (col.field.indexOf('.') !== -1) {
644
+ console.error(`Cannot export nested fields such as ${col.field}. Use $project to simplify.`);
645
+ } else {
646
+ if (!col.colDef || !col.colDef.cellTemplate) {
647
+ csvData += '"' + csvStringify(col.displayName) + '",';
648
+ col.doCSVExport = true;
649
+ } else {
650
+ const templateResp = self.scope.showsContent(col.colDef.cellTemplate, col.field);
651
+ // Third party apps can override showContent and return a function
652
+ if (typeof templateResp === 'function') {
653
+ csvData += '"' + csvStringify(col.displayName) + '",';
654
+ col.doCSVExport = templateResp;
655
+ } else if (templateResp === 'HTML') {
656
+ csvData += '"' + csvStringify(col.displayName) + '",';
657
+ col.doCSVExport = function (value) {
658
+ value = value.replace(/<p>/g, '\n\n');
659
+ value = value.replace(/<\/p>/g, '');
660
+ value = value.replace(/<\s?br\s?\/?>/g, '\n');
661
+ value = value.replace(/<[^>]+>/g, '');
662
+ value = value.replaceAll('&nbsp;', ' ').trim();
663
+ value = value.replaceAll('\n\n \n\n', '\n\n');
664
+ value = value.replaceAll('\n\n\n', '\n\n');
665
+ return value;
666
+ };
667
+ } else if (templateResp) {
668
+ csvData += '"' + csvStringify(col.displayName) + '",';
669
+ col.doCSVExport = true;
670
+ } else {
671
+ col.doCSVExport = false;
672
+ }
673
+ }
674
+ }
389
675
  }
390
676
  });
391
677
 
392
678
  csvData = swapLastCommaForNewline(csvData);
393
679
 
394
- angular.forEach(self.grid.filteredRows, function (row) {
395
- angular.forEach(self.scope.columns, function (col) {
396
- if (col.visible) {
397
- csvData += '"' + csvStringify(row.entity[col.field]) + '",';
398
- }
399
- });
400
- csvData = swapLastCommaForNewline(csvData);
680
+ angular.forEach(self.scope.gridApi.core.getVisibleRows(), function (row) {
681
+ if (row.visible) {
682
+ angular.forEach(self.grid.columns, function (col) {
683
+ if (col.doCSVExport) {
684
+ let value = row.entity[col.field];
685
+ if (typeof col.doCSVExport === 'function') {
686
+ value = col.doCSVExport(value, row.entity, col);
687
+ }
688
+ csvData += '"' + csvStringify(value, filters[col.field]) + '",';
689
+ }
690
+ });
691
+ csvData = swapLastCommaForNewline(csvData);
692
+ }
401
693
  });
402
694
 
403
695
  return csvData;
@@ -411,6 +703,10 @@ function ngGridCsvExportPlugin(opts) {
411
703
  but that would require putting the totals (ngGridTotalCell.js) into a plugin.
412
704
  */
413
705
 
706
+ /**
707
+ * FOOTER NO LONGER SUPPORTED
708
+ */
709
+
414
710
  function ngGridPdfExportPlugin(options) {
415
711
  var self = this;
416
712
  self.grid = null;
@@ -439,475 +735,527 @@ function ngGridPdfExportPlugin(options) {
439
735
 
440
736
  self.createPDF = function () {
441
737
  var headers = [],
442
- data = [],
443
- footers = {},
444
- gridWidth = self.scope.totalRowWidth(),
445
- margin = 15; // mm defined as unit when setting up jsPDF
446
-
447
- angular.forEach(self.scope.columns, function (col) {
448
- if (col.visible && (col.width === undefined || col.width > 0)) {
449
- headers.push({name: col.field, prompt: col.displayName, width: col.width * (185 / gridWidth), align: (col.colDef.align || 'left')});
450
- if (col.colDef.totalsRow) {
451
- footers[col.field] = self.scope.getTotalVal(col.field, col.filter).toString();
452
- }
453
- }
454
- });
455
-
456
- angular.forEach(self.grid.filteredRows, function (row) {
457
- data.push(angular.copy(row.entity));
458
- });
459
-
460
- var doc = new jsPDF('landscape', 'mm', 'a4');
461
- doc.setFontStyle('bold');
462
- doc.setFontSize(24);
463
- doc.text(self.scope.reportSchema.title, margin, margin);
464
- doc.setFontStyle('normal');
465
- doc.setFontSize(12);
466
- doc.cellInitialize();
467
- doc.table(margin, 24, data, {headers: headers, footers: footers, printHeaders: true, autoSize: false, margins: {left: margin, top: margin, bottom: margin, width: doc.internal.pageSize - margin}});
468
- doc.output('dataurlnewwindow');
469
- };
470
- }
738
+ headerNames = [],
739
+ footers = [],
740
+ data = [],
741
+ filters = {},
742
+ transformers = {};
471
743
 
472
744
 
473
- /** ====================================================================
474
- * jsPDF Cell plugin
475
- * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
476
- * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
477
- * 2013 Lee Driscoll, https://github.com/lsdriscoll
478
- * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
479
- * 2014 James Hall, james@parall.ax
480
- *
481
- * Permission is hereby granted, free of charge, to any person obtaining
482
- * a copy of this software and associated documentation files (the
483
- * "Software"), to deal in the Software without restriction, including
484
- * without limitation the rights to use, copy, modify, merge, publish,
485
- * distribute, sublicense, and/or sell copies of the Software, and to
486
- * permit persons to whom the Software is furnished to do so, subject to
487
- * the following conditions:
488
- *
489
- * The above copyright notice and this permission notice shall be
490
- * included in all copies or substantial portions of the Software.
491
- *
492
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
493
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
494
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
495
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
496
- * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
497
- * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
498
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
499
- * ====================================================================
500
- */
501
-
502
- (function (jsPDFAPI) {
503
- 'use strict';
504
- /*jslint browser:true */
505
- /*global document: false, jsPDF */
506
-
507
- var fontName,
508
- fontSize,
509
- fontStyle,
510
- padding = 3,
511
- margin = 13,
512
- headerFunction,
513
- lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
514
- pages = 1,
515
- setLastCellPosition = function (x, y, w, h, ln) {
516
- lastCellPos = { 'x': x, 'y': y, 'w': w, 'h': h, 'ln': ln };
517
- },
518
- getLastCellPosition = function () {
519
- return lastCellPos;
520
- };
521
-
522
- jsPDFAPI.setHeaderFunction = function (func) {
523
- headerFunction = func;
524
- };
525
-
526
- jsPDFAPI.getTextDimensions = function (txt) {
527
- fontName = this.internal.getFont().fontName;
528
- fontSize = this.table_font_size || this.internal.getFontSize();
529
- fontStyle = this.internal.getFont().fontStyle;
530
- // 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
531
- var px2pt = 0.264583 * 72 / 25.4,
532
- dimensions,
533
- text;
534
-
535
- text = document.createElement('font');
536
- text.id = "jsPDFCell";
537
- text.style.fontStyle = fontStyle;
538
- text.style.fontName = fontName;
539
- text.style.fontSize = fontSize + 'pt';
540
- text.innerText = txt;
541
-
542
- document.body.appendChild(text);
543
-
544
- dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt};
545
-
546
- document.body.removeChild(text);
547
-
548
- return dimensions;
549
- };
550
-
551
- jsPDFAPI.cellAddPage = function () {
552
- this.addPage();
553
-
554
- setLastCellPosition(this.margins.left, this.margins.top, undefined, undefined);
555
- //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
556
- pages += 1;
557
- };
558
-
559
- jsPDFAPI.cellInitialize = function () {
560
- lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
561
- pages = 1;
562
- };
563
-
564
- jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
565
- var curCell = getLastCellPosition();
566
-
567
- // If this is not the first cell, we must change its position
568
- if (curCell.ln !== undefined) {
569
- if (curCell.ln === ln) {
570
- //Same line
571
- x = curCell.x + curCell.w;
572
- y = curCell.y;
573
- } else {
574
- //New line
575
- if ((curCell.y + curCell.h + h + margin) >= this.internal.pageSize.height - this.margins.bottom) {
576
- this.cellAddPage();
577
- if (this.printHeaders && this.tableHeaderRow) {
578
- this.printHeaderRow(ln, true);
579
- }
580
- }
581
- //We ignore the passed y: the lines may have diferent heights
582
- y = (getLastCellPosition().y + getLastCellPosition().h);
583
-
584
- }
585
- }
586
-
587
- if (txt[0] !== undefined) {
588
- if (this.printingHeaderRow) {
589
- this.rect(x, y, w, h, 'FD');
590
- } else {
591
- this.rect(x, y, w, h);
592
- }
593
- if (align === 'right') {
594
- var textSize;
595
- if (txt instanceof Array) {
596
- for (var i = 0; i < txt.length; i++) {
597
- var currentLine = txt[i];
598
- textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize() / (72 / 25.6);
599
- this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
600
- }
745
+ angular.forEach(self.grid.columns, function (col) {
746
+ if (col.visible) {
747
+ if (col.field.indexOf('.') !== -1) {
748
+ console.error(`Cannot export nested fields such as ${col.field}. Use $project to simplify.`);
601
749
  } else {
602
- textSize = this.getStringUnitWidth(txt) * this.internal.getFontSize() / (72 / 25.6);
603
- this.text(txt, x + w - textSize - padding, y + this.internal.getLineHeight());
604
- }
605
- } else {
606
- this.text(txt, x + padding, y + this.internal.getLineHeight());
607
- }
608
- }
609
- setLastCellPosition(x, y, w, h, ln);
610
- return this;
611
- };
612
-
613
- /**
614
- * Return an array containing all of the owned keys of an Object
615
- * @type {Function}
616
- * @return {String[]} of Object keys
617
- */
618
- jsPDFAPI.getKeys = (typeof Object.keys === 'function')
619
- ? function (object) {
620
- if (!object) {
621
- return [];
622
- }
623
- return Object.keys(object);
624
- }
625
- : function (object) {
626
- var keys = [],
627
- property;
628
-
629
- for (property in object) {
630
- if (object.hasOwnProperty(property)) {
631
- keys.push(property);
632
- }
633
- }
634
-
635
- return keys;
636
- };
637
-
638
- /**
639
- * Return the maximum value from an array
640
- * @param array
641
- * @param comparisonFn
642
- * @returns {*}
643
- */
644
- jsPDFAPI.arrayMax = function (array, comparisonFn) {
645
- var max = array[0],
646
- i,
647
- ln,
648
- item;
649
-
650
- for (i = 0, ln = array.length; i < ln; i += 1) {
651
- item = array[i];
652
-
653
- if (comparisonFn) {
654
- if (comparisonFn(max, item) === -1) {
655
- max = item;
656
- }
657
- } else {
658
- if (item > max) {
659
- max = item;
660
- }
661
- }
662
- }
663
-
664
- return max;
665
- };
666
-
667
- /**
668
- * Create a table from a set of data.
669
- * @param {Integer} [x] : left-position for top-left corner of table
670
- * @param {Integer} [y] top-position for top-left corner of table
671
- * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
672
- * @param {Object} [config.headers] String[] Omit or null to auto-generate headers at a performance cost
673
- * @param {Object} [config.footers] Object containing key-value pairs. Omit or null if not required
674
- * @param {Object} [config.printHeaders] True to print column headers at the top of every page
675
- * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
676
- * @param {Object} [config.margins] margin values for left, top, bottom, and width
677
- * @param {Object} [config.fontSize] Integer fontSize to use (optional)
678
- */
679
-
680
- jsPDFAPI.table = function (x, y, data, config) {
681
- if (!data) {
682
- throw 'No data for PDF table';
683
- }
684
-
685
- var headerNames = [],
686
- headerPrompts = [],
687
- header,
688
- i,
689
- ln,
690
- cln,
691
- columnMatrix = {},
692
- columnWidths = {},
693
- columnData,
694
- column,
695
- columnMinWidths = [],
696
- columnAligns = [],
697
- j,
698
- tableHeaderConfigs = [],
699
- model,
700
- jln,
701
- func,
702
-
703
- //set up defaults. If a value is provided in config, defaults will be overwritten:
704
- autoSize = false,
705
- printHeaders = true,
706
- fontSize = 12,
707
- headers = null,
708
- footers = null,
709
- margins = {left: 0, top: 0, bottom: 0, width: this.internal.pageSize.width};
710
-
711
- if (config) {
712
- //override config defaults if the user has specified non-default behavior:
713
- if (config.autoSize === true) {
714
- autoSize = true;
715
- }
716
- if (config.printHeaders === false) {
717
- printHeaders = false;
718
- }
719
- if (config.fontSize) {
720
- fontSize = config.fontSize;
721
- }
722
- if (config.margins) {
723
- margins = config.margins;
724
- }
725
- if (config.headers) {
726
- headers = config.headers;
727
- }
728
- if (config.footers) {
729
- footers = config.footers;
730
- }
731
- }
732
-
733
- /**
734
- * @property {Number} lnMod
735
- * Keep track of the current line number modifier used when creating cells
736
- */
737
- this.lnMod = 0;
738
- lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
739
- pages = 1;
740
-
741
- this.printHeaders = printHeaders;
742
- this.margins = margins;
743
- this.setFontSize(fontSize);
744
- this.table_font_size = fontSize;
745
-
746
- // Set header values
747
- if (headers === undefined || (headers === null)) {
748
- // No headers defined so we derive from data
749
- headerNames = this.getKeys(data[0]);
750
-
751
- } else if (headers[0] && (typeof headers[0] !== 'string')) {
752
- // var px2pt = 0.264583 * 72 / 25.4;
753
- var constant = 1.5; // arrived at by trial and error
754
-
755
- // Split header configs into names and prompts
756
- for (i = 0, ln = headers.length; i < ln; i += 1) {
757
- header = headers[i];
758
- headerNames.push(header.name);
759
- headerPrompts.push(header.prompt);
760
- columnWidths[header.name] = header.width * constant;
761
- columnAligns[header.name] = header.align;
762
- }
763
-
764
- } else {
765
- headerNames = headers;
766
- }
767
- if (autoSize) {
768
- // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
769
- func = function (rec) {
770
- return rec[header];
771
- };
772
-
773
- for (i = 0, ln = headerNames.length; i < ln; i += 1) {
774
- header = headerNames[i];
775
-
776
- columnMatrix[header] = data.map(
777
- func
778
- );
779
-
780
- // get header width
781
- columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
782
- column = columnMatrix[header];
783
-
784
- // get cell widths
785
- for (j = 0, cln = column.length; j < cln; j += 1) {
786
- columnData = column[j];
787
- columnMinWidths.push(this.getTextDimensions(columnData).w);
788
- }
789
-
790
- // get footer width
791
- if (footers) {
792
- columnMinWidths.push(this.getTextDimensions(footers[i]).w);
750
+ if (!col.colDef || !col.colDef.cellTemplate) {
751
+ headers.push(col.displayName);
752
+ headerNames.push(col.field);
753
+ } else {
754
+ const templateResp = self.scope.showsContent(col.colDef.cellTemplate, col.field);
755
+ if (templateResp === 'HTML') {
756
+ headers.push(col.displayName);
757
+ headerNames.push(col.field);
758
+ transformers[col.field] = function (value) {
759
+ value = value.replace(/<p>/g, '\n\n');
760
+ value = value.replace(/<\/p>/g, '');
761
+ value = value.replace(/<\s?br\s?\/?>/g, '\n');
762
+ value = value.replace(/<[^>]+>/g, '');
763
+ value = value.replaceAll('&nbsp;', ' ').trim();
764
+ value = value.replaceAll('\n\n \n\n', '\n\n');
765
+ value = value.replaceAll('\n\n\n', '\n\n');
766
+ return value;
767
+ };
768
+ } else if (templateResp) {
769
+ headers.push(col.displayName);
770
+ headerNames.push(col.field);
771
+ }
772
+ }
793
773
  }
794
-
795
- // get final column width
796
- columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
797
774
  }
798
- }
799
-
800
- // -- Construct the table
801
-
802
- if (printHeaders) {
803
- var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames);
804
-
805
- // Construct the header row
806
- for (i = 0, ln = headerNames.length; i < ln; i += 1) {
807
- header = headerNames[i];
808
- tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header), 0, columnAligns[header]]);
775
+ if (col.colDef && col.colDef.totalsRow) {
776
+ footers[col.field] = self.grid.getTotalVal(col.field, col.filter).toString();
809
777
  }
778
+ self.scope.extractFilter(col, filters);
779
+ });
810
780
 
811
- // Store the table header config
812
- this.setTableHeaderRow(tableHeaderConfigs);
813
-
814
- // Print the header for the start of the table
815
- this.printHeaderRow(1, false);
816
- }
817
-
818
- // Construct the data rows
819
- for (i = 0, ln = data.length; i < ln; i += 1) {
820
- var lineHeight;
821
- model = data[i];
822
- lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
823
-
824
- for (j = 0, jln = headerNames.length; j < jln; j += 1) {
825
- header = headerNames[j];
826
- this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, columnAligns[header]);
827
- }
828
- }
829
-
830
- if (footers) {
831
- // Construct the header row
832
- for (var fi = 0; fi < headerNames.length; fi++) {
833
- header = headerNames[fi];
834
- tableHeaderConfigs[fi][4] = footers[header] || ' ';
781
+ angular.forEach(self.scope.gridApi.core.getVisibleRows(), function (row) {
782
+ var output = [];
783
+ if (row.visible) {
784
+ headerNames.forEach(function(h) {
785
+ var val = row.entity[h];
786
+ if (filters[h]) {
787
+ val = filters[h].filter(val, filters[h].filterParam);
788
+ }
789
+ if (transformers[h]) {
790
+ val = transformers[h](val);
791
+ }
792
+ if (typeof val === 'string') {
793
+ // chars > 255 cause BOM characters - see https://reallycare.freshdesk.com/a/tickets/2370
794
+ // first replace the predictable chars
795
+ val = val.replace(/\u2019/g,'\'');
796
+ val = val.replace(/\u2018/g,'\'');
797
+ val = val.replace(/\u201c/g,'"');
798
+ val = val.replace(/\u201d/g,'"');
799
+
800
+ // Then strip out anything left over 255
801
+ val = val.replace(/[^\x00-\xFF]/g, '');
802
+ }
803
+ output.push(val);
804
+ });
805
+ data.push(output);
835
806
  }
807
+ });
836
808
 
837
- // Print the header for the start of the table
838
- this.printHeaderRow(i + 2, false);
839
- }
840
- this.table_x = x;
841
- this.table_y = y;
842
- return this;
843
- };
844
- /**
845
- * Calculate the height for containing the highest column
846
- * @param {String[]} headerNames is the header, used as keys to the data
847
- * @param {Integer[]} columnWidths is size of each column
848
- * @param {Object[]} model is the line of data we want to calculate the height of
849
- */
850
- jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
851
- var header, lineHeight = 0;
852
- for (var j = 0; j < headerNames.length; j++) {
853
- header = headerNames[j];
854
- model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
855
- var h = this.internal.getLineHeight() * model[header].length + padding;
856
- if (h > lineHeight)
857
- lineHeight = h;
858
- }
859
- return lineHeight;
860
- };
861
-
862
- /**
863
- * Store the config for outputting a table header
864
- * @param {Object[]} config
865
- * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
866
- * except the ln parameter is excluded
867
- */
868
- jsPDFAPI.setTableHeaderRow = function (config) {
869
- this.tableHeaderRow = config;
870
- };
871
-
872
- /**
873
- * Output the store header row
874
- * @param lineNumber The line number to output the header at
875
- */
876
- jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
877
- if (!this.tableHeaderRow) {
878
- throw 'Property tableHeaderRow does not exist.';
879
- }
880
-
881
- var tableHeaderCell,
882
- tmpArray,
883
- i,
884
- ln;
809
+ // var doc = new jsPDF('landscape', 'mm', 'a4');
810
+ var doc = new jspdf.jsPDF('landscape', 'mm', 'a4');
811
+ doc.autoTable({
812
+ head: [headers],
813
+ body: data
814
+ });
885
815
 
886
- this.printingHeaderRow = true;
887
- if (headerFunction !== undefined) {
888
- var position = headerFunction(this, pages);
889
- setLastCellPosition(position[0], position[1], position[2], position[3], -1);
890
- }
891
- this.setFontStyle('bold');
892
- var tempHeaderConf = [];
893
- for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
894
- this.setFillColor(200, 200, 200);
895
-
896
- tableHeaderCell = this.tableHeaderRow[i];
897
- if (new_page) {
898
- tableHeaderCell[1] = this.margins.top;
899
- tempHeaderConf.push(tableHeaderCell);
900
- }
901
- tmpArray = [].concat(tableHeaderCell);
902
- tmpArray[5] = lineNumber;
903
- this.cell.apply(this, tmpArray);
904
- }
905
- if (tempHeaderConf.length > 0) {
906
- this.setTableHeaderRow(tempHeaderConf);
907
- }
908
- this.setFontStyle('normal');
909
- this.printingHeaderRow = false;
816
+ window.open(doc.output('bloburl'));
910
817
  };
818
+ }
911
819
 
912
- })(jsPDF.API);
913
820
 
821
+ // /** ====================================================================
822
+ // * jsPDF Cell plugin
823
+ // * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
824
+ // * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
825
+ // * 2013 Lee Driscoll, https://github.com/lsdriscoll
826
+ // * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
827
+ // * 2014 James Hall, james@parall.ax
828
+ // *
829
+ // * Permission is hereby granted, free of charge, to any person obtaining
830
+ // * a copy of this software and associated documentation files (the
831
+ // * "Software"), to deal in the Software without restriction, including
832
+ // * without limitation the rights to use, copy, modify, merge, publish,
833
+ // * distribute, sublicense, and/or sell copies of the Software, and to
834
+ // * permit persons to whom the Software is furnished to do so, subject to
835
+ // * the following conditions:
836
+ // *
837
+ // * The above copyright notice and this permission notice shall be
838
+ // * included in all copies or substantial portions of the Software.
839
+ // *
840
+ // * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
841
+ // * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
842
+ // * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
843
+ // * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
844
+ // * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
845
+ // * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
846
+ // * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
847
+ // * ====================================================================
848
+ // */
849
+ //
850
+ // (function (jsPDFAPI) {
851
+ // 'use strict';
852
+ // /*jslint browser:true */
853
+ // /*global document: false, jsPDF */
854
+ //
855
+ // var fontName,
856
+ // fontSize,
857
+ // fontStyle,
858
+ // padding = 3,
859
+ // margin = 13,
860
+ // headerFunction,
861
+ // lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
862
+ // pages = 1,
863
+ // setLastCellPosition = function (x, y, w, h, ln) {
864
+ // lastCellPos = { 'x': x, 'y': y, 'w': w, 'h': h, 'ln': ln };
865
+ // },
866
+ // getLastCellPosition = function () {
867
+ // return lastCellPos;
868
+ // };
869
+ //
870
+ // jsPDFAPI.setHeaderFunction = function (func) {
871
+ // headerFunction = func;
872
+ // };
873
+ //
874
+ // jsPDFAPI.getTextDimensions = function (txt) {
875
+ // fontName = this.internal.getFont().fontName;
876
+ // fontSize = this.table_font_size || this.internal.getFontSize();
877
+ // fontStyle = this.internal.getFont().fontStyle;
878
+ // // 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
879
+ // var px2pt = 0.264583 * 72 / 25.4,
880
+ // dimensions,
881
+ // text;
882
+ //
883
+ // text = document.createElement('font');
884
+ // text.id = "jsPDFCell";
885
+ // text.style.fontStyle = fontStyle;
886
+ // text.style.fontName = fontName;
887
+ // text.style.fontSize = fontSize + 'pt';
888
+ // text.innerText = txt;
889
+ //
890
+ // document.body.appendChild(text);
891
+ //
892
+ // dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt};
893
+ //
894
+ // document.body.removeChild(text);
895
+ //
896
+ // return dimensions;
897
+ // };
898
+ //
899
+ // jsPDFAPI.cellAddPage = function () {
900
+ // this.addPage();
901
+ //
902
+ // setLastCellPosition(this.margins.left, this.margins.top, undefined, undefined);
903
+ // //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
904
+ // pages += 1;
905
+ // };
906
+ //
907
+ // jsPDFAPI.cellInitialize = function () {
908
+ // lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
909
+ // pages = 1;
910
+ // };
911
+ //
912
+ // jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
913
+ // var curCell = getLastCellPosition();
914
+ //
915
+ // // If this is not the first cell, we must change its position
916
+ // if (curCell.ln !== undefined) {
917
+ // if (curCell.ln === ln) {
918
+ // //Same line
919
+ // x = curCell.x + curCell.w;
920
+ // y = curCell.y;
921
+ // } else {
922
+ // //New line
923
+ // if ((curCell.y + curCell.h + h + margin) >= this.internal.pageSize.height - this.margins.bottom) {
924
+ // this.cellAddPage();
925
+ // if (this.printHeaders && this.tableHeaderRow) {
926
+ // this.printHeaderRow(ln, true);
927
+ // }
928
+ // }
929
+ // //We ignore the passed y: the lines may have diferent heights
930
+ // y = (getLastCellPosition().y + getLastCellPosition().h);
931
+ //
932
+ // }
933
+ // }
934
+ //
935
+ // if (txt[0] !== undefined) {
936
+ // if (this.printingHeaderRow) {
937
+ // this.rect(x, y, w, h, 'FD');
938
+ // } else {
939
+ // this.rect(x, y, w, h);
940
+ // }
941
+ // if (align === 'right') {
942
+ // var textSize;
943
+ // if (txt instanceof Array) {
944
+ // for (var i = 0; i < txt.length; i++) {
945
+ // var currentLine = txt[i];
946
+ // textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize() / (72 / 25.6);
947
+ // this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
948
+ // }
949
+ // } else {
950
+ // textSize = this.getStringUnitWidth(txt) * this.internal.getFontSize() / (72 / 25.6);
951
+ // this.text(txt, x + w - textSize - padding, y + this.internal.getLineHeight());
952
+ // }
953
+ // } else {
954
+ // this.text(txt, x + padding, y + this.internal.getLineHeight());
955
+ // }
956
+ // }
957
+ // setLastCellPosition(x, y, w, h, ln);
958
+ // return this;
959
+ // };
960
+ //
961
+ // /**
962
+ // * Return an array containing all of the owned keys of an Object
963
+ // * @type {Function}
964
+ // * @return {String[]} of Object keys
965
+ // */
966
+ // jsPDFAPI.getKeys = (typeof Object.keys === 'function')
967
+ // ? function (object) {
968
+ // if (!object) {
969
+ // return [];
970
+ // }
971
+ // return Object.keys(object);
972
+ // }
973
+ // : function (object) {
974
+ // var keys = [],
975
+ // property;
976
+ //
977
+ // for (property in object) {
978
+ // if (object.hasOwnProperty(property)) {
979
+ // keys.push(property);
980
+ // }
981
+ // }
982
+ //
983
+ // return keys;
984
+ // };
985
+ //
986
+ // /**
987
+ // * Return the maximum value from an array
988
+ // * @param array
989
+ // * @param comparisonFn
990
+ // * @returns {*}
991
+ // */
992
+ // jsPDFAPI.arrayMax = function (array, comparisonFn) {
993
+ // var max = array[0],
994
+ // i,
995
+ // ln,
996
+ // item;
997
+ //
998
+ // for (i = 0, ln = array.length; i < ln; i += 1) {
999
+ // item = array[i];
1000
+ //
1001
+ // if (comparisonFn) {
1002
+ // if (comparisonFn(max, item) === -1) {
1003
+ // max = item;
1004
+ // }
1005
+ // } else {
1006
+ // if (item > max) {
1007
+ // max = item;
1008
+ // }
1009
+ // }
1010
+ // }
1011
+ //
1012
+ // return max;
1013
+ // };
1014
+ //
1015
+ // /**
1016
+ // * Create a table from a set of data.
1017
+ // * @param {Integer} [x] : left-position for top-left corner of table
1018
+ // * @param {Integer} [y] top-position for top-left corner of table
1019
+ // * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
1020
+ // * @param {Object} [config.headers] String[] Omit or null to auto-generate headers at a performance cost
1021
+ // * @param {Object} [config.footers] Object containing key-value pairs. Omit or null if not required
1022
+ // * @param {Object} [config.printHeaders] True to print column headers at the top of every page
1023
+ // * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
1024
+ // * @param {Object} [config.margins] margin values for left, top, bottom, and width
1025
+ // * @param {Object} [config.fontSize] Integer fontSize to use (optional)
1026
+ // */
1027
+ //
1028
+ // jsPDFAPI.table = function (x, y, data, config) {
1029
+ // if (!data) {
1030
+ // throw 'No data for PDF table';
1031
+ // }
1032
+ //
1033
+ // var headerNames = [],
1034
+ // headerPrompts = [],
1035
+ // header,
1036
+ // i,
1037
+ // ln,
1038
+ // cln,
1039
+ // columnMatrix = {},
1040
+ // columnWidths = {},
1041
+ // columnData,
1042
+ // column,
1043
+ // columnMinWidths = [],
1044
+ // columnAligns = [],
1045
+ // j,
1046
+ // tableHeaderConfigs = [],
1047
+ // model,
1048
+ // jln,
1049
+ // func,
1050
+ //
1051
+ // //set up defaults. If a value is provided in config, defaults will be overwritten:
1052
+ // autoSize = false,
1053
+ // printHeaders = true,
1054
+ // fontSize = 12,
1055
+ // headers = null,
1056
+ // footers = null,
1057
+ // margins = {left: 0, top: 0, bottom: 0, width: this.internal.pageSize.width};
1058
+ //
1059
+ // if (config) {
1060
+ // //override config defaults if the user has specified non-default behavior:
1061
+ // if (config.autoSize === true) {
1062
+ // autoSize = true;
1063
+ // }
1064
+ // if (config.printHeaders === false) {
1065
+ // printHeaders = false;
1066
+ // }
1067
+ // if (config.fontSize) {
1068
+ // fontSize = config.fontSize;
1069
+ // }
1070
+ // if (config.margins) {
1071
+ // margins = config.margins;
1072
+ // }
1073
+ // if (config.headers) {
1074
+ // headers = config.headers;
1075
+ // }
1076
+ // if (config.footers) {
1077
+ // footers = config.footers;
1078
+ // }
1079
+ // }
1080
+ //
1081
+ // /**
1082
+ // * @property {Number} lnMod
1083
+ // * Keep track of the current line number modifier used when creating cells
1084
+ // */
1085
+ // this.lnMod = 0;
1086
+ // lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
1087
+ // pages = 1;
1088
+ //
1089
+ // this.printHeaders = printHeaders;
1090
+ // this.margins = margins;
1091
+ // this.setFontSize(fontSize);
1092
+ // this.table_font_size = fontSize;
1093
+ //
1094
+ // // Set header values
1095
+ // if (headers === undefined || (headers === null)) {
1096
+ // // No headers defined so we derive from data
1097
+ // headerNames = this.getKeys(data[0]);
1098
+ //
1099
+ // } else if (headers[0] && (typeof headers[0] !== 'string')) {
1100
+ // // var px2pt = 0.264583 * 72 / 25.4;
1101
+ // var constant = 1.5; // arrived at by trial and error
1102
+ //
1103
+ // // Split header configs into names and prompts
1104
+ // for (i = 0, ln = headers.length; i < ln; i += 1) {
1105
+ // header = headers[i];
1106
+ // headerNames.push(header.name);
1107
+ // headerPrompts.push(header.prompt);
1108
+ // columnWidths[header.name] = header.width * constant;
1109
+ // columnAligns[header.name] = header.align;
1110
+ // }
1111
+ //
1112
+ // } else {
1113
+ // headerNames = headers;
1114
+ // }
1115
+ // if (autoSize) {
1116
+ // // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
1117
+ // func = function (rec) {
1118
+ // return rec[header];
1119
+ // };
1120
+ //
1121
+ // for (i = 0, ln = headerNames.length; i < ln; i += 1) {
1122
+ // header = headerNames[i];
1123
+ //
1124
+ // columnMatrix[header] = data.map(
1125
+ // func
1126
+ // );
1127
+ //
1128
+ // // get header width
1129
+ // columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
1130
+ // column = columnMatrix[header];
1131
+ //
1132
+ // // get cell widths
1133
+ // for (j = 0, cln = column.length; j < cln; j += 1) {
1134
+ // columnData = column[j];
1135
+ // columnMinWidths.push(this.getTextDimensions(columnData).w);
1136
+ // }
1137
+ //
1138
+ // // get footer width
1139
+ // if (footers) {
1140
+ // columnMinWidths.push(this.getTextDimensions(footers[i]).w);
1141
+ // }
1142
+ //
1143
+ // // get final column width
1144
+ // columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
1145
+ // }
1146
+ // }
1147
+ //
1148
+ // // -- Construct the table
1149
+ //
1150
+ // if (printHeaders) {
1151
+ // var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames);
1152
+ //
1153
+ // // Construct the header row
1154
+ // for (i = 0, ln = headerNames.length; i < ln; i += 1) {
1155
+ // header = headerNames[i];
1156
+ // tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header), 0, columnAligns[header]]);
1157
+ // }
1158
+ //
1159
+ // // Store the table header config
1160
+ // this.setTableHeaderRow(tableHeaderConfigs);
1161
+ //
1162
+ // // Print the header for the start of the table
1163
+ // this.printHeaderRow(1, false);
1164
+ // }
1165
+ //
1166
+ // // Construct the data rows
1167
+ // for (i = 0, ln = data.length; i < ln; i += 1) {
1168
+ // var lineHeight;
1169
+ // model = data[i];
1170
+ // lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
1171
+ //
1172
+ // for (j = 0, jln = headerNames.length; j < jln; j += 1) {
1173
+ // header = headerNames[j];
1174
+ // this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, columnAligns[header]);
1175
+ // }
1176
+ // }
1177
+ //
1178
+ // if (footers) {
1179
+ // // Construct the header row
1180
+ // for (var fi = 0; fi < headerNames.length; fi++) {
1181
+ // header = headerNames[fi];
1182
+ // tableHeaderConfigs[fi][4] = footers[header] || ' ';
1183
+ // }
1184
+ //
1185
+ // // Print the header for the start of the table
1186
+ // this.printHeaderRow(i + 2, false);
1187
+ // }
1188
+ // this.table_x = x;
1189
+ // this.table_y = y;
1190
+ // return this;
1191
+ // };
1192
+ // /**
1193
+ // * Calculate the height for containing the highest column
1194
+ // * @param {String[]} headerNames is the header, used as keys to the data
1195
+ // * @param {Integer[]} columnWidths is size of each column
1196
+ // * @param {Object[]} model is the line of data we want to calculate the height of
1197
+ // */
1198
+ // jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
1199
+ // var header, lineHeight = 0;
1200
+ // for (var j = 0; j < headerNames.length; j++) {
1201
+ // header = headerNames[j];
1202
+ // model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
1203
+ // var h = this.internal.getLineHeight() * model[header].length + padding;
1204
+ // if (h > lineHeight)
1205
+ // lineHeight = h;
1206
+ // }
1207
+ // return lineHeight;
1208
+ // };
1209
+ //
1210
+ // /**
1211
+ // * Store the config for outputting a table header
1212
+ // * @param {Object[]} config
1213
+ // * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
1214
+ // * except the ln parameter is excluded
1215
+ // */
1216
+ // jsPDFAPI.setTableHeaderRow = function (config) {
1217
+ // this.tableHeaderRow = config;
1218
+ // };
1219
+ //
1220
+ // /**
1221
+ // * Output the store header row
1222
+ // * @param lineNumber The line number to output the header at
1223
+ // */
1224
+ // jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
1225
+ // if (!this.tableHeaderRow) {
1226
+ // throw 'Property tableHeaderRow does not exist.';
1227
+ // }
1228
+ //
1229
+ // var tableHeaderCell,
1230
+ // tmpArray,
1231
+ // i,
1232
+ // ln;
1233
+ //
1234
+ // this.printingHeaderRow = true;
1235
+ // if (headerFunction !== undefined) {
1236
+ // var position = headerFunction(this, pages);
1237
+ // setLastCellPosition(position[0], position[1], position[2], position[3], -1);
1238
+ // }
1239
+ // this.setFontStyle('bold');
1240
+ // var tempHeaderConf = [];
1241
+ // for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
1242
+ // this.setFillColor(200, 200, 200);
1243
+ //
1244
+ // tableHeaderCell = this.tableHeaderRow[i];
1245
+ // if (new_page) {
1246
+ // tableHeaderCell[1] = this.margins.top;
1247
+ // tempHeaderConf.push(tableHeaderCell);
1248
+ // }
1249
+ // tmpArray = [].concat(tableHeaderCell);
1250
+ // tmpArray[5] = lineNumber;
1251
+ // this.cell.apply(this, tmpArray);
1252
+ // }
1253
+ // if (tempHeaderConf.length > 0) {
1254
+ // this.setTableHeaderRow(tempHeaderConf);
1255
+ // }
1256
+ // this.setFontStyle('normal');
1257
+ // this.printingHeaderRow = false;
1258
+ // };
1259
+ //
1260
+ // })(jsPDF.API);
1261
+ //