fng-reports 0.12.0-beta.247 → 0.12.0-beta.248

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