-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
fluentReports.js
5400 lines (4847 loc) · 200 KB
/
fluentReports.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
--------------------------------------
(c)2012-2016, Kellpro, Inc.
--------------------------------------
FluentReports is under The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//noinspection ThisExpressionReferencesGlobalObjectJS
/**
* @module fluentReports
* @author Nathanael Anderson
* @contributors Mark Getz, Alan Henager, Beau West, Marcus Christensson
* @copyright 2012-2016, Kellpro Inc.
* @license MIT
*/
(function (_global) {
"use strict";
// Layout:
/*
Report ->
Section ->
DataSet ->
Group ->
(Optional) DataSet (or Sub-Report) ->
Group ->
...
*/
// ------------------------------------------------------
// Helper Functions
// ------------------------------------------------------
/**
* Gets a setting from a setting collection, checks for the normal case; and then a lower case version
* @param settingsObject
* @param setting
* @param defaultValue
* @return {*} defaultValue if no setting exists
*/
function getSettings(settingsObject, setting, defaultValue) {
if (!settingsObject) {
return (defaultValue);
}
if (settingsObject[setting]) {
return settingsObject[setting];
} else {
var lsetting = setting.toLowerCase();
if (settingsObject[lsetting]) {
return settingsObject[lsetting];
}
}
return defaultValue;
}
/**
* This creates a lower case version of the prototypes
* @param prototype
*/
function lowerPrototypes(prototype) {
var proto, lowerProto;
for (proto in prototype) {
if (prototype.hasOwnProperty(proto)) {
// Don't lowercase internal prototypes
if (proto[0] === '_') {
continue;
}
lowerProto = proto.toLowerCase();
// If the prototype is already lowercased, then we skip
if (lowerProto === proto) {
continue;
}
// verify it is a function
if (typeof prototype[proto] === "function") {
prototype[lowerProto] = prototype[proto];
}
}
}
}
/** Debug Code **/
function printStructure(reportObject, level, outputType) {
if (reportObject === null) {
return;
}
var i, j, added = (2 * level), pad = "", spad = '';
for (i = 0; i < added; i++) {
pad += "-";
spad += " ";
}
var loopChildren = function() {
if (reportObject._child) {
printStructure(reportObject._child, level + 1, outputType);
} else if (reportObject._children) {
for (j = 0; j < reportObject._children.length; j++) {
printStructure(reportObject._children[j], level + 1, outputType);
}
}
};
if (reportObject._isReport) {
if (reportObject._parent) {
console.log(pad + "> Subreport");
} else {
console.log(pad + "> Report");
}
} else if (reportObject._isSection) {
console.log(pad + "> Section");
} else if (reportObject._isDataSet) {
console.log(pad + "> DataSet");
} else if (reportObject._isGroup) {
console.log(pad + "> Group = " + reportObject._groupOnField);
} else {
console.log(pad + "> Unknown");
}
if (reportObject._theader !== null && reportObject._theader !== undefined) {
console.log(spad + " | Has Title Header ", typeof reportObject._theader._part === "function" ? reportObject._theader._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._theader._partHeight > 0 ? reportObject._theader._partHeight : '', reportObject._theader._isHeightExempt);
}
if (reportObject._header !== null && reportObject._header !== undefined) {
if (reportObject._isReport) {
console.log(spad + " | Has Page Header", typeof reportObject._header._part === "function" ? reportObject._header._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._header._partHeight > 0 ? reportObject._header._partHeight : '', reportObject._header._isHeightExempt);
} else {
console.log(spad + " | Has Header", typeof reportObject._header._part === "function" ? reportObject._header._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._header._partHeight > 0 ? reportObject._header._partHeight : '', reportObject._header._isHeightExempt);
}
}
if (reportObject._detail !== null && reportObject._detail !== undefined) {
console.log(spad + " | Has Detail", reportObject._renderDetail === reportObject._renderAsyncDetail ? "(Async)" : reportObject._renderDetail === reportObject._renderSyncDetail ? "(Sync)" : reportObject._renderDetail === reportObject._renderBandDetail ? "(Auto Band)" : reportObject._renderDetail === reportObject._renderStringDetail ? "(Auto String)" : "Unknown");
}
if (outputType) { loopChildren(); }
if (reportObject._footer !== null && reportObject._footer !== undefined) {
if (reportObject._isReport) {
console.log(spad + " | Has Page Footer", typeof reportObject._footer._part === "function" ? reportObject._footer._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._footer._partHeight > 0 ? reportObject._footer._partHeight : '', reportObject._footer._isHeightExempt);
} else {
console.log(spad + " | Has Footer", typeof reportObject._footer._part === "function" ? reportObject._footer._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._footer._partHeight > 0 ? reportObject._footer._partHeight : '', reportObject._footer._isHeightExempt);
}
}
if (reportObject._tfooter !== null && reportObject._tfooter !== undefined) {
console.log(spad + " | Has Summary Footer", typeof reportObject._tfooter._part === "function" ? reportObject._tfooter._part.length === 4 ? "(Async)" : "(Sync)" : "(Auto)", reportObject._tfooter._partHeight > 0 ? reportObject._tfooter._partHeight : '', reportObject._tfooter._isHeightExempt);
}
if (!outputType) { loopChildren(); }
}
/**
* Returns true if object is an array object
* @param obj
* @return {Boolean} True or False
*/
function isArray(obj) {
return (Object.prototype.toString.apply(obj) === '[object Array]');
}
/**
* returns true if this is a number
* @param num
* @return {Boolean}
*/
function isNumber(num) {
return ((typeof num === 'string' || typeof num === 'number') && num !== null && !isNaN((num - 0)) && num !== '' );
}
/**
* Clones the data -- this is a simple clone, it does *NOT* do any really DEEP copies;
* but nothing in the report module needs a deep copy.
* @param value
* @return {*}
*/
function clone(value) {
var key, target = {}, i, aTarget = [];
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || Object.prototype.toString.call(value) === '[object Date]') {
return value;
}
if (isArray(value)) {
for (i = 0; i < value.length; i++) {
aTarget.push(clone(value[i]));
}
return (aTarget);
} else if (typeof aTarget === "object") {
for (key in value) {
if (value.hasOwnProperty(key)) {
target[key] = value[key];
}
}
return target;
} else {
// Currently this path is not used in the clone...
return JSON.parse(JSON.stringify(value));
}
}
/**
* Generic Error function that can be overridden with your own error code
*/
function error() {
if (!console || !console.error || arguments.length === 0) {
return;
}
console.error.apply(console, arguments);
}
/**
* This is a callback that just prints any errors, used for places a callback may not have been passed in.
* @param err
*/
function dummyCallback(err) {
if (err) {
Report.error(err);
}
}
/**
* This does a loop, used for Async code
* @param total number of loops
* @param runFunction - this is the function that will be called for each iteration
* @param doneCallback - this is called when the loop is done
*/
function startLoopingAsync(total, runFunction, doneCallback) {
var counter = -1;
var callbackLoop = function() {
counter++;
if (counter < total) {
// Unwind this stack every so often
if (counter % 10 === 0) {
setImmediate(function() { runFunction(counter, callbackLoop); });
} else {
runFunction(counter, callbackLoop);
}
} else {
doneCallback();
}
};
callbackLoop();
}
/**
* This does a loop, used for Sync code
* @param total number of loops
* @param runFunction - this is the function that will be called for each iteration
* @param doneCallback - this is called when the loop is done
*/
function startLoopingSync(total, runFunction, doneCallback) {
var counter= 0;
var hasAnotherLoop = true;
var callbackLoop = function(skipInc) {
if (skipInc !== true) { counter++; }
if (counter < total) {
// Unwind this stack every so ofter
if (skipInc !== true && counter % 10 === 0) {
// Technically we don't have to reset this to true; as it is already true; but this is so that
// this function is readable by use mere humans several months from here.
hasAnotherLoop = true;
} else {
runFunction(counter, callbackLoop);
}
} else {
hasAnotherLoop = false;
}
};
while (hasAnotherLoop) {
callbackLoop(true);
}
doneCallback();
}
var reportRenderingMode = {UNDEFINED: 0, SYNC: 1, ASYNC: 2};
// If any are added to this, you need to add the function, and update _calcTotals and _clearTotals,
var mathTypes = {SUM: 1, AVERAGE: 2, MIN: 3, MAX: 4, COUNT: 5};
var dataTypes = {NORMAL: 0, PAGEABLE: 1, FUNCTIONAL: 2, PLAINOLDDATA: 3};
// -------------------------------------------------------
// Report Objects
// -------------------------------------------------------
/**
* ReportSection
* @class ReportSection
* @desc This is a Report Section that allows multiple DataSets for laying out a report.
* @param parent object, typically another section, group or report object
* @constructor
* @alias ReportSection
* @memberof Report
*/
function ReportSection(parent) {
this._children = [];
this._parent = parent;
}
/**
* ReportRenderer
* @class ReportRenderer
* @desc This is the Wrapper around the PDFKit, and could be used to wrap any output library.
* @classdesc this is the RENDERER class passed into your callbacks during report generation.
* @constructor
* @alias ReportRenderer
* @memberof Report
*/
function ReportRenderer(primaryReport, options) {
this.totals = {};
this._priorValues = {};
this._pageHasRendering = 0;
this._pageHeaderRendering = 0;
this._curBand = [];
this._curBandOffset = 0;
this._primaryReport = primaryReport;
this._pageBreaking = false;
this._landscape = false;
this._paper = "letter";
this._margins = 72;
this._lineWidth = 1;
this._level = 0;
this._totalLevels = 0;
this._negativeParentheses = false;
this._heightOfString = 0;
this._graphicState = [];
this._fillColor = "black";
this._strokeColor = "black";
this._fillOpacity = 1;
this._rotated = 0;
this._height = 0;
this._reportHeight = 0;
this._printedLines = [];
this._pageNumbers = [];
this._reportRenderMode = reportRenderingMode.UNDEFINED;
var opt = {};
if (options) {
if (options.paper) {
this._paper = options.paper;
if (this._paper !== "letter") {
opt.size = this._paper;
}
}
if (options.landscape) {
this._landscape = true;
opt.layout = "landscape";
}
if (options.margins && options.margins !== this._margins) {
this._margins = options.margins;
if (typeof options.margins === 'number') {
opt.margin = options.margins;
} else {
opt.margins = options.margins;
}
}
if (options.fonts) {
this._fonts = options.fonts;
}
if (options.registeredFonts) {
this._registeredFonts = options.registeredFonts;
}
if (options.info) {
opt.info = options.info;
}
}
if (!this._fonts) {
this._fonts = clone(Report._indexedFonts);
}
if (!this._registeredFonts) {
this._registeredFonts = {};
}
this._PDF = new this._PDFKit(opt);
this._heightOfString = this._PDF.currentLineHeight(true);
this._height = this._reportHeight = this._PDF.page.maxY();
this._PDF.page.height = 99999;
var self = this;
//noinspection JSHint
for (var key in this._registeredFonts) {
if (!this._registeredFonts.hasOwnProperty(key)) { continue; }
//noinspection JSHint
for (var style in this._registeredFonts[key]) {
if (!this._registeredFonts[key].hasOwnProperty(style)) { continue; }
if (style === 'normal') {
this._PDF.registerFont(key, this._registeredFonts[key][style], key);
} else {
this._PDF.registerFont(key+'-'+style, this._registeredFonts[key][style], key+'-'+style);
}
}
}
// This is a PDFDoc emulated page wrapper so that we can detect how it will wrap things.
var lwDoc = this._LWDoc = {
count: 0, pages: 1, x: this._PDF.page.margins.left, y: this._PDF.page.margins.top, page: this._PDF.page, _PDF: this._PDF,
currentLineHeight: function (val) { //noinspection JSPotentiallyInvalidUsageOfThis
return this._PDF.currentLineHeight(val); },
widthOfString: function (d, o) { //noinspection JSPotentiallyInvalidUsageOfThis
return this._PDF.widthOfString(d, o); },
addPage: function () { this.pages++;
//noinspection JSPotentiallyInvalidUsageOfThis
this.x = this._PDF.page.margins.left;
//noinspection JSPotentiallyInvalidUsageOfThis
this.y = this._PDF.page.margins.top; },
reset: function () { this.count = 0; this.pages = 0; this.addPage(); }
};
// Create a new Line Wrapper Object, this allows us to handle Bands
this._LineWrapper = new this._LineWrapperObject(lwDoc,{width:this._PDF.page.width - this._PDF.page.margins.right - this._PDF.page.margins.left, columns:1, columnGap: 18});
this._LineWrapper.on('line', function () {
lwDoc.count++;
});
// Create the Print wrapper; this allows us to wrap long print() calls onto multiple sheed.
this._PrintWrapper = new this._LineWrapperObject(lwDoc,{width:this._PDF.page.width - this._PDF.page.margins.right - this._PDF.page.margins.left, columns:1, columnGap: 18});
this._PrintWrapper.on('line', function (line, options) {
self._printedLines.push({L:line, O: options});
});
}
/**
* @class ReportHeaderFooter
* @desc Creates a Object for tracking Header/Footer instances
* @constructor
* @alias ReportHeaderFooter
* @memberof Report
* @param isHeader
* @param {boolean} [isSizeExempt] - is Size Exempt, this ONLY applies to page footers; as we don't want to "break" the page on a page footer.
*/
function ReportHeaderFooter(isHeader, isSizeExempt) {
this._part = null;
this._isFunction = false;
this._partHeight = -1;
//noinspection JSUnusedGlobalSymbols
this._partWidth = -1;
this._pageBreakBefore = false;
this._pageBreakAfter = false;
this._isHeader = isHeader;
// This only applies to Page FOOTERS, and the final summary FOOTER. These are the only items that won't cause a page-break before/during printing.
// Normally this is not a issue; but some people might use absolute Y coords and end up overflowing the page in the footer;
// which then causes a major glitch in the rendering. So instead we are just going to let the footer overflow the page and ignore the rest of the footer.
// This is a much "cleaner" looking solution.
this._isHeightExempt = !(isHeader && !isSizeExempt);
}
/**
* ReportGroup
* @class ReportGroup
* @desc This creates a Report Grouping Section
* @classdesc This Creates a new Report Grouping (This is the basic Building Block of the Report before you start rendering)
* @constructor
* @alias ReportGroup
* @memberof Report
* @param parent
*/
function ReportGroup(parent) {
this._parent = parent;
this._header = null;
this._footer = null;
this._detail = null;
this._groupOnField = null;
this._groupChecked = false;
this._groupLastValue = null;
this._child = null;
this._hasRanHeader = false;
this._runDetailAfterSubgroup = false;
this._runHeaderWhen = Report.show.newPageOnly;
this._lastData = {};
this._currentData = null;
this._math = [];
this._totals = {};
this._curBandWidth = [];
this._curBandOffset = 0;
this._level = -1;
}
/**
* ReportDataSet
* @class ReportDataSet
* @desc This creates a Dataset Element for the Report
* @param {ReportSection} parent - ReportSection element that is the parent of this object
* @constructor
* @alias ReportDataSet
* @memberof Report
* @return {ReportGroup} - Returns a auto-generated ReportGroup tied to this reportDataSet
*/
function ReportDataSet(parent) {
this._parent = parent;
this._data = null;
this._keys = null;
this._dataType = dataTypes.NORMAL;
this._recordCountCallback = null;
this._child = new ReportGroup(this);
if (this._parent && this._parent._parent === null) {
this._child.header = this._child.pageHeader;
this._child.footer = this._child.pageFooter;
}
this._totalFormatter = function (data, callback) {
callback(null, data);
};
return (this._child);
}
/*
* This can be used as an a example method that is a paged data object.
* This is a linked to internal Kellpro data and functions;
* but you can base your own page-able data object off of it (see prototype)
* @private
**/
function ScopedDataObject(data, scope, formattingState) {
this._scope = scope;
this._data = data;
this._dataType = dataTypes.NORMAL;
this._formatters = null;
this._result = null;
if (formattingState !== null && formattingState !== undefined) {
this._formattingState = formattingState;
} else {
this._formattingState = 0;
}
if (data._isQuery || data._isquery || typeof data === "string") {
this._dataType = dataTypes.FUNCTIONAL;
}
else if (data.isRows) {
this._dataType = dataTypes.PAGEABLE;
this.isPaged = true;
}
else {
if (this.error) {
this.error(scope, null, 'warn', "Unknown scoped data type: " + Object.prototype.toString.apply(data));
} else {
error("Unknown data type: ", Object.prototype.toString.apply(data), data);
}
}
}
/**
* Report
* @class Report
* @desc Primary Report Creation Class
* @param {(string|object|Report)} [parent] - Either the string name of the report to output to disk, "buffer" to output a buffer or a [Report, Group, or Section] that this is to be a child report of.
* @param {object} [options] - default options for this report; landscape, paper, font, fontSize, autoPrint, fullScreen, negativeParentheses, autoCreate
* @returns {ReportGroup|Report} - Normally returns a ReportGroup, or it can return itself if options.autoCreate is set to false
*/
function Report(parent, options) {
options = options || {};
this._reportName = "report.pdf";
this._outputType = Report.renderType.file;
this._runHeaderWhen = Report.show.always;
if (arguments.length) {
if (typeof parent === "string" || typeof parent === "number") {
this._parent = null;
if (parent.toString() === "buffer") {
this._outputType = Report.renderType.buffer;
} else {
this._reportName = parent.toString();
}
} else if (typeof parent === "object" && typeof parent.write === "function" && typeof parent.end === "function") {
this._parent = null;
this._outputType = Report.renderType.pipe;
this._pipe = parent;
} else {
if (parent == null) {
this._parent = null;
} else if (parent._isReport) {
if (parent._child === null) {
parent._child = this;
this._parent = parent;
} else if (parent._child._isSection) {
parent._child.addReport(this);
this._parent = parent._child;
} else {
Report.error("REPORTAPI: Report was passed an invalid parent; resetting parent to none");
this._parent = null;
}
} else if (parent._isSection || parent._isGroup) {
if (options.isSibling === true) {
var parentReport = parent;
while (!parentReport._isReport) {
parentReport = parentReport._parent;
}
parentReport._child.addReport(this);
this._parent = parentReport;
} else {
parent.addReport(this);
this._parent = parent;
}
} else {
Report.error("REPORTAPI: Report was passed an invalid parent; resetting parent to none.");
this._parent = null;
}
}
} else {
this._parent = null;
}
this._reportMode = reportRenderingMode.UNDEFINED;
this._theader = null;
this._tfooter = null;
this._header = null;
this._footer = null;
this._userdata = null;
this._curBandWidth = [];
this._curBandOffset = 0;
this._state = {};
this._landscape = options.landscape || false;
this._paper = options.paper || "letter";
this._font = options.font || "Helvetica";
this._fontSize = options.fontSize || options.fontsize || 12;
this._margins = options.margins || 72;
this._autoPrint = options.autoPrint || options.autoprint || false;
this._fullScreen = options.fullScreen || options.fullscreen || false;
this._negativeParentheses = options.negativeParentheses || false;
this._registeredFonts = {};
this._fonts = clone(Report._indexedFonts);
this._info = options.info || {};
// We want to return a fully developed simple report (Report->Section->DataSet->Group) so we create it and then return the Group Object
if (options.autocreate === false || options.autoCreate === false) {
// TODO: This path might need to be deleted/modified; it doesn't setup _child or _detailGroup which will break code later in the code base.
this._child = null;
return this;
} else {
this._child = new ReportSection(this);
this._detailGroup = this._child.addDataSet();
return (this._detailGroup);
}
}
Report.prototype =
/** @lends Report */
{
_isReport: true,
/**
* is this the Root Report
* @desc Returns if this is the primary root report of the entire report set
* @returns {boolean}
*/
isRootReport: function () {
return (this._parent === null);
},
/**
* toggle pdf fullScreen
* @desc Attempts to make the report full screen when enabled
* @param value {boolean} - true to try and force the screen full size
* @returns {*}
*/
fullScreen: function(value) {
if (arguments.length) {
this._fullScreen = value;
return this;
}
return this._fullScreen;
},
/**
* Toggle auto print on open
* @param {boolean} value - true to enable
* @returns {*}
*/
autoPrint: function (value) {
if (arguments.length) {
this._autoPrint = value;
return this;
}
return this._autoPrint;
},
/**
* Enables negative numbers to be autowrapped in (parans)
* @param {boolean} value - true to enable
* @returns {*}
*/
negativeParentheses: function(value) {
if (arguments.length) {
this._negativeParentheses = value;
return this;
}
return this._negativeParentheses;
},
/**
* set the output Type
* @param type {Report.renderType} - Type of output
* @param to - Pipe or Filename
*/
outputType: function(type, to) {
if (arguments.length === 0) {
return this._outputType;
}
if (typeof type === 'string') {
if (type.toLowerCase() === 'buffer') {
this._outputType = Report.renderType.buffer;
} else {
this._outputType = Report.renderType.file;
this._reportName = type;
}
return this;
}
if (typeof type === 'object' && typeof type.write === 'function' && typeof type.end === 'function') {
this._outputType = Report.renderType.pipe;
this._pipe = type;
return this;
}
if (type === Report.renderType.pipe) {
this._outputType = Report.renderType.pipe;
this._pipe = to;
} else if (type === Report.renderType.buffer) {
this._outputType = Report.renderType.buffer;
} else if (type === Report.renderType.file) {
this._outputType = Report.renderType.file;
} else {
this._outputType = Report.renderType.file;
}
return this;
},
/**
* Start the Rendering process
* @param {function} callback - the callback to call when completed
* @returns {*}
*/
render: function (callback) {
if (this.isRootReport()) {
var self = this;
this._state = { isTitle: false, isFinal: false, headerSize: 0, footerSize: 0, additionalHeaderSize: 0, isCalc: false, cancelled: false,
resetGroups: true, startX: 0, startY: 0, currentX: 0, currentY: 0, priorStart: [], parentData: {}, report: this, currentGroup: null, reportRenderMode: this._reportRenderMode()};
this._info.Producer = "fluentReports 1.00";
if (Report.trace) {
console.error("Starting Tracing on Report to a ",this._outputType === Report.renderType.buffer ? "Buffer" : this._outputType === Report.renderType.pipe ? "Pipe" : "File "+this._reportName);
if (Report.callbackDebugging) {
console.error(" - Render callback is ", callback && typeof callback === "function" ? "valid" : "invalid");
}
}
// These get passed into the two page Wrappers for Page building information
var pageDefaults = {paper: this._paper, landscape: this._landscape, margins: this._margins, fonts: this._fonts, registeredFonts: this._registeredFonts, info: this._info};
// Set the rendering mode if no functions are defined
if (this._reportRenderMode() === reportRenderingMode.UNDEFINED) {
this._reportRenderMode(reportRenderingMode.ASYNC);
}
// Find out Sizes of all the Headers/Footers
var testit = new ReportRenderer(this, pageDefaults);
testit._reportRenderMode = this._reportRenderMode();
testit.font(this._font, this._fontSize);
testit.saveState();
// Catch the Printing so that we can see if we can track the "offset" of the Footer in case the footer
// is moved to a literal Y position (without it being based on the prior Y position)
var oPrint = testit.print;
var oBand = testit.band;
var oAddPage = testit._addPage;
var onewLine = testit.newLine;
// We are eliminating the height restriction for our sizing tests
testit._height = 90000;
testit._addPage = function() {
oAddPage.call(this);
this._height = 90000;
};
testit.newLine = function(lines, callback) {
this._firstMoveState = true;
onewLine.call(this, lines, callback);
};
testit.checkY = function(opt) {
if (opt == null) { return; }
var cY, y;
y = cY = this.getCurrentY();
if (opt.y) {
y = opt.y;
}
if (opt.addy) {
y += opt.addy;
}
if (opt.addY) {
y += opt.addY;
}
if (y > cY + (this._reportHeight / 3)) {
// Did our move - move us over a 1/3 of the page down? If so then, it is something we need to track.
if (!this._firstMoveState && !this._savedFirstMove) {
this._savedFirstMove = y;
} else if (this._firstMoveState && y < this._savedFirstMove) {
// You never know, a user might do a print: y = 700; then a band: y: 680. So we actually want to save the 680 as the smallest coord.
this._savedFirstMove = y;
} else if (!this._savedFirstMove) {
opt.addY = 0;
opt.y = 0;
Report.error("REPORTAPI: Your footer starts with printing some text, then uses an absolute move of greater than a third of the page. Please move first, then print!");
}
}
this._firstMoveState = true;
//return y > cY + (this._reportHeight / 3);
};
testit.band = function(data, options, callback) {
this.checkY(options);
oBand.call(this,data, options, callback);
};
testit.print = function(data, options, callback) {
this.checkY(options);
oPrint.call(this,data, options, callback);
};
testit.setCurrentY = function(y) {
this.checkY({y: y});
ReportRenderer.prototype.setCurrentY.call(this, y);
};
// Start the Calculation for the Test Report -> Then run the actual report.
this._calculateFixedSizes(testit, "",
function() {
// Eliminate the testit code so it can be garbage collected.
testit = null; oPrint = null; oBand = null; oAddPage = null;
if (self._footer !== null) {
self._state.footerSize = self._footer._partHeight;
}
if (self._header !== null) {
self._state.headerSize = self._header._partHeight;
}
if (Report.trace) {
console.error("Generating real report", self._reportName);
}
// Lets Run the Real Report Header
var renderedReport = new ReportRenderer(self, pageDefaults);
renderedReport._reportRenderMode = self._reportRenderMode();
renderedReport.font(self._font, self._fontSize);
renderedReport.saveState();
//noinspection JSAccessibilityCheck
renderedReport._setAutoPrint(self._autoPrint);
renderedReport._setFullScreen(self._fullScreen);
renderedReport.setNegativeParentheses(self._negativeParentheses);
self._renderIt(renderedReport, self._state, null,
function () {
if (Report.trace) {
console.error("Report Writing to ", self._outputType === Report.renderType.buffer ? "Buffer" : self._outputType === Report.renderType.pipe ? "Pipe" : "File " + self._reportName);
}
if (self._state.cancelled) {
if (callback) { callback(null, false); }
return;
}
renderedReport._finishPageNumbers();
switch (self._outputType) {
case Report.renderType.pipe:
//noinspection JSAccessibilityCheck
renderedReport._pipe(self._pipe, callback);
break;
case Report.renderType.buffer:
//noinspection JSAccessibilityCheck
renderedReport._output(function (data) {
if (callback) {
callback(null, data);
} else {
Report.error("REPORTAPI: callback missing; asked for a PDF buffer to be generated.");
}
});
break;
default:
//noinspection JSAccessibilityCheck
renderedReport._write(self._reportName, function (err) {
if (callback) {
callback(err, self._reportName);
}
});
break;
}
});
});
return (this._reportName);
} else {
return this._parent.render(callback);
}
},
/**
* Add your own user data to be passed around in the report
* @param value
* @returns {*}
*/
userData: function (value) {
if (arguments.length) {
this._userdata = value;
return this;
}
return this._userdata;
},
/**
* The current state of the report engine
* @param value
* @returns {object}
*/
state: function (value) {
if (arguments.length) {
this._state = value;
}
return this._state;
},
/**
* Set the paper size in pixels
* @param {number} value
* @returns {number}
*/
paper: function (value) {
if (arguments.length) {
this._paper = value;
}
return this._paper;
},
/**
* Set the paper into Landscape mode
* @param value - True = Landscape, False = Portrait
* @returns {boolean}
*/
landscape: function (value) {
if (arguments.length) {
this._landscape = value;
}
return this._landscape;
},
font: function (value) {
if (arguments.length) {
this._font = value;
}
return this._font;
},
/**
* Set or Get the current font size
* @param {number} [value] - set fontSize if this value is set
* @returns {number} - the Font Size
*/
fontSize: function (value) {
if (arguments.length) {
this._fontSize = value;
}
return this._fontSize;
},
fontBold: function () {
var font = this._fonts[this._font];
switch (this._font) {
case font.italic:
case font.bolditalic:
if (font.bolditalic) {
this._font = font.bolditalic;
} else if (font.bold) {
this._font = font.bold;
}
break;
default:
if (font.bold) {
this._font = font.bold;
}