lib/CallBackery/GuiPlugin/AbstractTable.pm

filter: Statementstmt 81.5% 168 / 206 Branchbran 53.0% 35 / 66 Conditioncond 37.8% 28 / 74 MC/DCmcdc 15.2% 7 / 46 Subroutinesub 80.7% 21 / 26 Podpod 100% 4 / 4 totaltotal 62.3% 263 / 422 CC 69 SCAR 42.5
CC
69
Cov
67%
__ANON__
171.4
_exportColumnPlan
16.2
_qrEncoder
12.0
CRAP 70.2
« lib/CallBackery/GuiPlugin/UserForm.pm ↑ Summary lib/CallBackery/GuiPlugin/Abstract.pm »
1 package CallBackery::GuiPlugin::AbstractTable;
2 13 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
3 13 ▶use CallBackery::Translate qw(trm);
Subroutine BEGIN: called CC=1 SCAR=0.0
4 13 ▶use CallBackery::Exception qw(mkerror);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 13 ▶use Text::CSV;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 13 ▶use Excel::Writer::XLSX;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 13 ▶use Compress::Zlib ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 13 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 13 ▶use Mojo::Asset::Memory;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 13 ▶use Mojo::JSON qw(true false);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 13 ▶use Mojo::Util qw(encode);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 13 ▶use Time::Piece;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 # Text::QRCode is only pulled in when an export actually asks for a qrCode
15 # column, so that installations which never export QR codes do not have to
16 # carry libqrencode. See _qrEncoder below.
17 13 my $QR_ENCODER;
18  
19 # how _qrPng renders a matrix, and how large the result appears in the sheet
20 13 my $QR_MODULE_SIZE = 4; # pixels per qr module
21 13 my $QR_QUIET_ZONE = 4; # modules of mandatory light border
22 13 my $QR_DEFAULT_SIZE = 100; # pixels the image is scaled to in the cell
23  
24 =head1 NAME
25  
26 CallBackery::GuiPlugin::AbstractTable - Base Class for a table plugin
27  
28 =head1 SYNOPSIS
29  
30 use Mojo::Base 'CallBackery::GuiPlugin::AbstractTable';
31  
32 =head1 DESCRIPTION
33  
34 The base class for table plugins, derived from CallBackery::GuiPlugin::AbstractForm
35  
36 =cut
37  
38 13 ▶use Mojo::Base 'CallBackery::GuiPlugin::AbstractForm';
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 =head1 ATTRIBUTES
41  
42 The attributes of the L<CallBackery::GuiPlugin::AbstractForm> class and these:
43  
44 =cut
45  
46 0 ▶has screenCfg => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
47 0 my $self = shift;
48 0 my $screen = $self->SUPER::screenCfg;
49 0 $screen->{table} = $self->tableCfg;
50 0 $screen->{type} = 'table';
51 0 return $screen;
52 13 };
53  
54 =head2 tableCfg
55  
56 a table configuration
57  
58 return [
59 {
60 label => trm('Id'),
61 type => 'number',
62 flex => 1,
63 key => 'id',
64 sortable => true,
65 },
66 {
67 label => trm('Date'),
68 type => 'str',
69 flex => 2
70 key => 'date'
71 },
72 {
73 label => trm('Content'),
74 type => 'str',
75 flex => 8,
76 key => 'date'
77 },
78 ]
79  
80 =cut
81  
82 0 ▶has tableCfg => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
83 0 croak "the plugin must define its tableCfg property";
84 13 };
85  
86 =head1 METHODS
87  
88 All the methods of L<CallBackery::GuiPlugin::AbstractForm> plus:
89  
90 =cut
91  
92  
93 =head2 getData ('tableData|tableRowCount',tableDataRequest);
94  
95 Return the requested table data and pass other types of request on to the upper levels.
96  
97 =cut
98  
99 1 ▶sub getData {
Subroutine getData: called CC=4 SCAR=17.9
Pod documented
100 1 my $self = shift;
101 1 ▶ my $type = shift // '';
Condition50%1/2
shift() // ""
l!l
10
MC/DC0%0/1
shift() // ""
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
102 1 ▶ if ($type eq 'tableData'){
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'tableData') { } 1 0 1
elsif ($type eq 'tableRowCount') { } 0 0 0
103 1 return $self->getTableData(@_);
104 }
105 elsif ($type eq 'tableRowCount'){
106 0 return $self->getTableRowCount(@_);
107 }
108 else {
109 0 return $self->SUPER::getData($type,@_);
110 }
111 }
112  
113 =head2 getTableData({formData=>{},firstRow=>{},lastRow=>{},sortColumn=>'key',sortDesc=>true})
114  
115 return data appropriate for the remote table widget
116  
117 =cut
118  
119 0 ▶sub getTableData {
Subroutine getTableData: not called CC=1 SCAR=6.9
Pod documented
120 0 return [{}];
121 }
122  
123 =head2 getTableRowCount({formData=>{}})
124  
125 return the number of rows matching the given formData
126  
127 =cut
128  
129 0 ▶sub getTableRowCount {
Subroutine getTableRowCount: not called CC=1 SCAR=6.9
Pod documented
130 0 return 0;
131 }
132  
133 =head2 _exportColumnPlan($tableCfg,$extraCols)
134  
135 Merge the extra export columns into the table configuration and return the
136 resulting list of output columns. Each element is either
137  
138 { col => $tableCfgEntry }
139  
140 for a normal data column, or
141  
142 { extra => $extraColSpec }
143  
144 for a generated one. The C<insertAfter> indices of all extra columns refer to
145 the original C<$tableCfg>, so several extra columns cannot shift each other
146 around.
147  
148 =cut
149  
150 13 my %EXTRA_COL_TYPE = (qrCode => 1);
151  
152 10 ▶sub _exportColumnPlan {
Subroutine _exportColumnPlan: called CC=16 SCAR=27.8
153 10 my $self = shift;
154 10 my $tCfg = shift;
155 10 ▶ my $extraCols = shift // [];
Condition100%2/2
shift() // []
l!l
82
MC/DC100%1/1
shift() // []
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
156  
157 10 my %insertAfter;
158 10 for my $extra (@$extraCols) {
159 9 ▶ my $type = $extra->{type} // '';
Condition50%1/2
$extra->{"type"} // ""
l!l
90
MC/DC0%0/1
$extra->{"type"} // ""
$extra->{"type"}
Truth table50%1/2
A
A= $extra->{"type"}
Aresult
11
00
160 die mkerror(9930, "unknown extra export column type '$type'")
161 9 ▶ unless $EXTRA_COL_TYPE{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $EXTRA_COL_TYPE{$type} 1 8 9
162  
163 8 my $content = $extra->{content};
164 8 ▶ die mkerror(9931, "extra export column of type '$type' has no content")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 8 8
165 unless defined $content;
166  
167 8 my $idx = $extra->{insertAfter};
168 8 ▶ if (defined $idx) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $idx) { } 4 4 8
elsif (ref $content eq 'CODE') { } 1 3 4
169 4 ▶ die mkerror(9932,
Branch: 1 branch
BranchTrueFalseTotal
if not $idx =~ /^\d+$/u or $idx > $tCfg->$#* 1 3 4
Condition66%2/3
not $idx =~ /^\d+$/u or $idx > $tCfg->$#*
l!l&&r!l&&!r
013
MC/DC50%1/2
not $idx =~ /^\d+$/u or $idx > $tCfg->$#*
not $idx =~ /^\d+$/u $idx > $tCfg->$#*
Truth table66%2/3
not(A) or B
A= not $idx =~ /^\d+$/uB= $idx > $tCfg->$#*
ABresult
1X1
011
000
170 "insertAfter $idx of extra export column is out of range")
171 if $idx !~ /^\d+$/ or $idx > $#$tCfg;
172 }
173 elsif (ref $content eq 'CODE') {
174 1 die mkerror(9933,
175 "an extra export column with a code reference content "
176 ."requires an explicit insertAfter");
177 }
178  
179 # the column the content is taken from, if there is one. It supplies
180 # the default label, and with no insertAfter also the position.
181 6 my ($srcIdx);
182 6 ▶ if (ref $content ne 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $content ne "CODE") 6 0 6
183 6 ▶ ($srcIdx) = grep { ($tCfg->[$_]{key} // '') eq $content } 0..$#$tCfg;
Condition50%1/2
$tCfg->[$_]{"key"} // ""
l!l
180
MC/DC0%0/1
$tCfg->[$_]{"key"} // ""
$tCfg->[$_]{"key"}
Truth table50%1/2
A
A= $tCfg->[$_]{"key"}
Aresult
11
00
184 }
185 6 ▶ if (not defined $idx) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $idx) 3 3 6
186 3 ▶ die mkerror(9934,
Branch: 1 branch
BranchTrueFalseTotal
unless defined $srcIdx 1 2 3
187 "no table column with key '$content' to attach an extra "
188 ."export column to")
189 unless defined $srcIdx;
190 2 $idx = $srcIdx;
191 }
192 5 push @{$insertAfter{$idx}}, { extra => $extra, srcIdx => $srcIdx };
193 }
194  
195 6 my @plan;
196 6 for my $i (0..$#$tCfg) {
197 18 push @plan, { col => $tCfg->[$i] };
198 18 ▶ push @plan, @{$insertAfter{$i} // []};
Condition100%2/2
$insertAfter{$i} // []
l!l
513
MC/DC100%1/1
$insertAfter{$i} // []
$insertAfter{$i}
Truth table100%2/2
A
A= $insertAfter{$i}
Aresult
11
00
199 }
200 6 return \@plan;
201 }
202  
203 =head2 _qrEncoder()
204  
205 Return a shared L<Text::QRCode> instance, loading the module on first use.
206  
207 =cut
208  
209 0 ▶sub _qrEncoder {
Subroutine _qrEncoder: not called CC=3 SCAR=24.8
210 0 ▶ $QR_ENCODER //= do {
Condition0%0/3
$QR_ENCODER //= do { eval { do { require Text::QRCode; 1 } } or die mkerror(9935, "exporting QR codes requires the Text::QRCode module: $@"); "Text::QRCode"->new }
l!l&&r!l&&!r
000
MC/DC0%0/2
$QR_ENCODER //= do { eval { do { require Text::QRCode; 1 } } or die mkerror(9935, "exporting QR codes requires the Text::QRCode module: $@"); "Text::QRCode"->new }
$QR_ENCODER do { eval { do { require Text::QRCode; 1 } } or die mkerror(9935, "exporting QR codes requires the Text::QRCode module: $@"); "Text::QRCode"->new }
Truth table0%0/3
A //= B
A= $QR_ENCODERB= do { eval { do { require Text::QRCode; 1 } } or die mkerror(9935, "exporting QR codes requires the Text::QRCode module: $@"); "Text::QRCode"->new }
ABresult
1X1
011
000
211 0 ▶ eval { require Text::QRCode; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Text::QRCode; 1 } } or die mkerror(9935, "exporting QR codes requires the Text::QRCode module: $@") 0 0 0
212 or die mkerror(9935,
213 "exporting QR codes requires the Text::QRCode module: $@");
214 0 Text::QRCode->new;
215 };
216 0 return $QR_ENCODER;
217 }
218  
219 =head2 _qrPng($matrix,$moduleSize,$quietZone)
220  
221 Render a L<Text::QRCode> matrix (rows of C<*> and C<space>) into a 1 bit
222 greyscale PNG and return it as a byte string. C<$moduleSize> is the edge
223 length of one QR module in pixels (default 4) and C<$quietZone> the width of
224 the mandatory light border in modules (default 4).
225  
226 Writing the PNG by hand keeps this free of any image library.
227  
228 =cut
229  
230 1 ▶sub _qrPng {
Subroutine _qrPng: called CC=5 SCAR=16.2
231 1 my $self = shift;
232 1 my $matrix = shift;
233 1 ▶ my $moduleSize = shift // $QR_MODULE_SIZE;
Condition33%1/3
shift() // $QR_MODULE_SIZE
l!l&&r!l&&!r
100
MC/DC0%0/2
shift() // $QR_MODULE_SIZE
shift() $QR_MODULE_SIZE
Truth table33%1/3
A // B
A= shift()B= $QR_MODULE_SIZE
ABresult
1X1
011
000
234 1 ▶ my $quietZone = shift // $QR_QUIET_ZONE;
Condition33%1/3
shift() // $QR_QUIET_ZONE
l!l&&r!l&&!r
100
MC/DC0%0/2
shift() // $QR_QUIET_ZONE
shift() $QR_QUIET_ZONE
Truth table33%1/3
A // B
A= shift()B= $QR_QUIET_ZONE
ABresult
1X1
011
000
235  
236 1 my $modules = scalar @$matrix;
237 1 my $side = ($modules + 2 * $quietZone) * $moduleSize;
238 1 my $padding = (8 - $side % 8) % 8;
239  
240 # 0 is dark and 1 is light in a 1 bit greyscale image. The padding bits at
241 # the end of a scanline are ignored by the decoder, light keeps them tidy.
242 1 my $blank = pack 'B*', '1' x ($side + $padding);
243 1 my $quiet = '1' x ($quietZone * $moduleSize);
244  
245 1 my $raw = "\0$blank" x ($quietZone * $moduleSize);
246 1 for my $row (@$matrix) {
247 my $bits = $quiet
248 3 ▶ . join('', map { ($_ eq '*' ? '0' : '1') x $moduleSize } @$row)
Branch: 1 branch
BranchTrueFalseTotal
$_ eq '*' ? : 3 6 9
249 . $quiet . '1' x $padding;
250 3 my $line = "\0" . pack('B*', $bits);
251 3 $raw .= $line x $moduleSize;
252 }
253 1 $raw .= "\0$blank" x ($quietZone * $moduleSize);
254  
255 3 ▶ my $chunk = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
256 3 my ($type, $data) = @_;
257 3 return pack('N', length $data) . $type . $data
258 . pack('N', Compress::Zlib::crc32($type . $data));
259 1 };
260  
261 1 return "\x89PNG\r\n\x1a\n"
262 . $chunk->('IHDR', pack('N N C C C C C', $side, $side, 1, 0, 0, 0, 0))
263 . $chunk->('IDAT', Compress::Zlib::compress($raw))
264 . $chunk->('IEND', '');
265 }
266  
267 =head2 makeExportAction(type => 'XLSX', filename => 'export-"now"', label => 'Export')
268  
269 Create export button.
270 The default type is XLSX, also available is CSV.
271  
272 An XLSX export can carry extra generated columns next to the table data:
273  
274 $self->makeExportAction(
275 type => 'XLSX',
276 extraCols => [
277 { type => 'qrCode',
278 content => 'serial',
279 insertAfter => 1,
280 label => trm('QR'),
281 size => 100,
282 },
283 ],
284 );
285  
286 Every entry adds one column and takes these keys:
287  
288 =over
289  
290 =item type
291  
292 The kind of column to generate. Only C<qrCode> exists so far. It embeds the
293 content as a QR code image.
294  
295 =item content
296  
297 Where the content comes from: either the key of a field in the table data, or
298 a code reference which is called with the record hash reference and returns
299 the string to encode. A record whose content is undefined or empty gets no
300 image.
301  
302 =item insertAfter
303  
304 Optional. The zero based index in L</tableCfg> the new column is placed after.
305 The indices of all extra columns refer to the original L</tableCfg>, so
306 several extra columns cannot shift each other around. Without it the column
307 follows the column named by C<content>, which is therefore mandatory for a
308 code reference content.
309  
310 =item label
311  
312 Optional column heading, translated like any other label. It defaults to the
313 heading of the column named by C<content>.
314  
315 =item size
316  
317 Optional edge length of the image in pixels, 100 by default. The row height
318 and the column width are adjusted to fit.
319  
320 =back
321  
322 C<extraCols> is ignored for a CSV export, which has nowhere to put an image.
323  
324 A C<qrCode> column needs L<Text::QRCode>, which is loaded on first use so that
325 installations without QR code exports do not have to carry it.
326  
327 =cut
328  
329 # The rule xtr() applies in the frontend: an array is a message to
330 # translate, anything else is data. That covers a trm() made in this process
331 # and one that crossed JSON on its way here -- a status some other system
332 # reported, say -- which is a plain array by now. Handed to the writer as it
333 # was, the first came out in English and the second as "ARRAY(0x...)" in a
334 # csv, while Excel::Writer::XLSX spread it over the following cells and left
335 # the bare "%1" standing in this one. Arguments are rendered first, so a
336 # nested message gets its own msgid translated before it is substituted.
337 37 ▶sub _renderMessage {
Subroutine _renderMessage: called CC=6 SCAR=18.5
338 37 my $loc = shift;
339 37 my $value = shift;
340 37 ▶ return $value
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "CallBackery::Translate" or ref $value eq "ARRAY" 14 23 37
Condition100%3/3
ref $value eq "CallBackery::Translate" or ref $value eq "ARRAY"
l!l&&r!l&&!r
19414
MC/DC100%2/2
ref $value eq "CallBackery::Translate" or ref $value eq "ARRAY"
ref $value eq "CallBackery::Translate" ref $value eq "ARRAY"
Truth table100%3/3
A or B
A= ref $value eq "CallBackery::Translate"B= ref $value eq "ARRAY"
ABresult
1X1
011
000
341 unless ref $value eq 'CallBackery::Translate'
342 or ref $value eq 'ARRAY';
343 23 my ($str,@args) = @$value;
344 23 ▶ return '' unless defined $str and $str ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str and $str ne "" 0 23 23
Condition33%1/3
defined $str and $str ne ""
!ll&&!rl&&r
0023
MC/DC0%0/2
defined $str and $str ne ""
defined $str $str ne ""
Truth table33%1/3
A and B
A= defined $strB= $str ne ""
ABresult
0X0
100
111
345 23 ▶ return $loc->tra($str, map { _renderMessage($loc, $_) // '' } @args);
Condition50%1/2
_renderMessage($loc, $_) // ""
l!l
130
MC/DC0%0/1
_renderMessage($loc, $_) // ""
_renderMessage($loc, $_)
Truth table50%1/2
A
A= _renderMessage($loc, $_)
Aresult
11
00
346 }
347  
348 2 ▶sub makeExportAction {
Subroutine makeExportAction: called CC=4 SCAR=17.1
Pod documented
349 2 my $self = shift;
350 2 my %args = @_;
351 2 ▶ my $type = $args{type} // 'XLSX';
Condition50%1/2
$args{"type"} // "XLSX"
l!l
20
MC/DC0%0/1
$args{"type"} // "XLSX"
$args{"type"}
Truth table50%1/2
A
A= $args{"type"}
Aresult
11
00
352 2 my $extraCols = $args{extraCols};
353 2 ▶ my $label = $args{label} // trm("Export %1", $type);
Condition33%1/3
$args{"label"} // trm("Export %1", $type)
l!l&&r!l&&!r
020
MC/DC0%0/2
$args{"label"} // trm("Export %1", $type)
$args{"label"} trm("Export %1", $type)
Truth table33%1/3
A // B
A= $args{"label"}B= trm("Export %1", $type)
ABresult
1X1
011
000
354 my $filename = $args{filename}
355 2 ▶ // localtime->strftime('export-%Y-%m-%d-%H-%M-%S.').lc($type);
Condition50%1/2
$args{"filename"} // CallBackery::GuiPlugin::AbstractTable::localtime()->strftime("export-%Y-%m-%d-%H-%M-%S.") . lc($type)
l!l
02
MC/DC0%0/1
$args{"filename"} // CallBackery::GuiPlugin::AbstractTable::localtime()->strftime("export-%Y-%m-%d-%H-%M-%S.") . lc($type)
$args{"filename"}
Truth table50%1/2
A
A= $args{"filename"}
Aresult
11
00
356  
357 return {
358 label => $label,
359 action => 'download',
360 addToContextMenu => true,
361 key => 'export_csv',
362 2 ▶ actionHandler => sub {
Subroutine __ANON__: called CC=36 SCAR=51.4
363 2 my $self = shift;
364 2 my $args = shift;
365 2 my $data = $self->getTableData({
366 formData => $args,
367 firstRow => 0,
368 lastRow => $self->getTableRowCount({ formData=>$args })
369 });
370  
371 # Use the (translated) table headers in row 1.
372 # Or the keys if undefined.
373 2 my $loc = CallBackery::Translate->new(localeRoot=>$self->app->home->child("share"));
374 2 ▶ $loc->setLocale($self->user->userInfo->{lang} // 'en');
Condition50%1/2
$self->user->userInfo->{"lang"} // "en"
l!l
20
MC/DC0%0/1
$self->user->userInfo->{"lang"} // "en"
$self->user->userInfo->{"lang"}
Truth table50%1/2
A
A= $self->user->userInfo->{"lang"}
Aresult
11
00
375 2 my $tCfg = $self->tableCfg;
376  
377 2 ▶ my $tra = sub { _renderMessage($loc, shift) };
Subroutine __ANON__: called CC=1 SCAR=0.0
378  
379 2 ▶ my @titles = map { $tra->($_->{label}) // $_->{key} } @$tCfg;
Condition33%1/3
&$tra($_->{"label"}) // $_->{"key"}
l!l&&r!l&&!r
600
MC/DC0%0/2
&$tra($_->{"label"}) // $_->{"key"}
&$tra($_->{"label"}) $_->{"key"}
Truth table33%1/3
A // B
A= &$tra($_->{"label"})B= $_->{"key"}
ABresult
1X1
011
000
380  
381 2 ▶ if ($type eq 'CSV') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'CSV') { } 1 1 2
elsif ($type eq 'XLSX') { } 1 0 1
382 # Without binary mode Text::CSV refuses a line break or any
383 # character outside ASCII, and combine() then leaves an
384 # empty string behind: the row went missing without a word.
385 1 my $csv = Text::CSV->new({ binary => 1 });
386 4 ▶ my $line = sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
387 4 ▶ $csv->combine(@_)
Branch: 1 branch
BranchTrueFalseTotal
$csv->combine(@_) or die mkerror(9938, 'failed to write csv line: ' . $csv->error_diag) 4 0 4
388 or die mkerror(9938, "failed to write csv line: "
389 . $csv->error_diag);
390 4 return $csv->string . "\n";
391 1 };
392 1 my $csv_str = $line->(@titles);
393 1 for my $record (@$data) {
394 $csv_str .= $line->(map {
395 3 my $v = $record->{$_->{key}};
396 # an empty date is an empty cell, as in the xlsx
397 # export, not the start of 1970
398 9 ▶ if ($_->{type} eq 'date' and $v) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->{"type"} eq "date" and $v) 1 8 9
Condition100%3/3
$_->{"type"} eq "date" and $v
!ll&&!rl&&r
621
MC/DC100%2/2
$_->{"type"} eq "date" and $v
$_->{"type"} eq "date" $v
Truth table100%3/3
A and B
A= $_->{"type"} eq "date"B= $v
ABresult
0X0
100
111
399 1 $v= localtime($v/1000)->strftime("%Y-%m-%d %H:%M:%S %z");
400 }
401 9 $tra->($v)} @$tCfg);
402 }
403 1 my $asset = Mojo::Asset::Memory->new;
404 # an asset holds bytes; the text has to be encoded first
405 1 $asset->add_chunk(encode('UTF-8', $csv_str));
406 return {
407 1 asset => $asset,
408 type => 'text/csv; charset=UTF-8',
409 filename => $filename,
410 }
411 }
412 elsif ($type eq 'XLSX') {
413 # a spreadsheet is the only export that can hold images, so
414 # the extra columns exist here and are ignored for CSV
415 1 my $plan = $self->_exportColumnPlan($tCfg, $extraCols);
416  
417 1 ▶ open my $xh, '>', \my $xlsx or die "failed to open xlsx fh: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $xh, ">", \my $xlsx or die "failed to open xlsx fh: $!" 1 0 1
418 1 my $workbook = Excel::Writer::XLSX->new($xh);
419 1 my $worksheet = $workbook->add_worksheet();
420  
421 1 my $col = 0;
422 1 for my $p (@$plan) {
423 3 ▶ if (my $tc = $p->{col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tc = $p->{'col'}) { } 3 0 3
424 3 ▶ $worksheet->write(0, $col, $tra->($tc->{label}) // $tc->{key});
Condition33%1/3
&$tra($tc->{"label"}) // $tc->{"key"}
l!l&&r!l&&!r
300
MC/DC0%0/2
&$tra($tc->{"label"}) // $tc->{"key"}
&$tra($tc->{"label"}) $tc->{"key"}
Truth table33%1/3
A // B
A= &$tra($tc->{"label"})B= $tc->{"key"}
ABresult
1X1
011
000
425 }
426 else {
427 0 ▶ my $size = $p->{extra}{size} // $QR_DEFAULT_SIZE;
Condition0%0/3
$p->{"extra"}{"size"} // $QR_DEFAULT_SIZE
l!l&&r!l&&!r
000
MC/DC0%0/2
$p->{"extra"}{"size"} // $QR_DEFAULT_SIZE
$p->{"extra"}{"size"} $QR_DEFAULT_SIZE
Truth table0%0/3
A // B
A= $p->{"extra"}{"size"}B= $QR_DEFAULT_SIZE
ABresult
1X1
011
000
428 0 ▶ my $src = defined $p->{srcIdx} ? $tCfg->[$p->{srcIdx}] : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $p->{'srcIdx'} ? : 0 0 0
429 $worksheet->write(0, $col,
430 $tra->($p->{extra}{label})
431 0 ▶ // ($src ? $tra->($src->{label}) // $src->{key} : ''));
Branch: 1 branch
BranchTrueFalseTotal
$src ? : 0 0 0
Condition0%0/6
&$tra($p->{"extra"}{"label"}) // ($src ? &$tra($src->{"label"}) // $src->{"key"} : "")
l!l&&r!l&&!r
000
&$tra($src->{"label"}) // $src->{"key"}
l!l&&r!l&&!r
000
MC/DC0%0/2
&$tra($p->{"extra"}{"label"}) // ($src ? &$tra($src->{"label"}) // $src->{"key"} : "")
&$tra($p->{"extra"}{"label"}) ($src ? &$tra($src->{"label"}) // $src->{"key"} : "")
MC/DC0%0/2
&$tra($src->{"label"}) // $src->{"key"}
&$tra($src->{"label"}) $src->{"key"}
Truth table0%0/3
A // B
A= &$tra($p->{"extra"}{"label"})B= ($src ? &$tra($src->{"label"}) // $src->{"key"} : "")
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= &$tra($src->{"label"})B= $src->{"key"}
ABresult
1X1
011
000
432 # excel measures column width in characters of the
433 # default font, which is 7 pixels wide
434 0 $worksheet->set_column($col, $col, ($size + 5) / 7);
435 }
436 3 $col++;
437 }
438  
439 # Excel::Writer::XLSX only reads images from disk, and only
440 # when the workbook is closed, so the directory has to outlive
441 # the loop below
442 1 my $tmpDir;
443 1 my $qrCount = 0;
444 1 my %qrCache;
445  
446 1 my $row = 2;
447 1 my %date_format;
448 1 for my $record (@$data) {
449 3 $col = 0;
450 3 my $rowSize = 0;
451 3 for my $p (@$plan) {
452 9 ▶ if (my $tc = $p->{col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tc = $p->{'col'}) { } 9 0 9
453 9 my $v = $record->{$tc->{key}};
454 9 ▶ if ($tc->{type} eq 'date') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tc->{'type'} eq 'date') { } 3 6 9
455 3 ▶ my $fmt = $tc->{format} //'yyyy-mm-dd hh:mm:ss';
Condition50%1/2
$tc->{"format"} // "yyyy-mm-dd hh:mm:ss"
l!l
03
MC/DC0%0/1
$tc->{"format"} // "yyyy-mm-dd hh:mm:ss"
$tc->{"format"}
Truth table50%1/2
A
A= $tc->{"format"}
Aresult
11
00
456 3 ▶ $date_format{$fmt} //=
Condition66%2/3
$date_format{$fmt} //= $workbook->add_format("num_format", $fmt)
l!l&&r!l&&!r
210
MC/DC0%0/2
$date_format{$fmt} //= $workbook->add_format("num_format", $fmt)
$date_format{$fmt} $workbook->add_format("num_format", $fmt)
Truth table66%2/3
A //= B
A= $date_format{$fmt}B= $workbook->add_format("num_format", $fmt)
ABresult
1X1
011
000
457 $workbook->add_format(num_format => $fmt);
458 3 ▶ $worksheet->write_date_time($row,$col,localtime($v/1000)->strftime("%Y-%m-%dT%H:%M:%S"),$date_format{$fmt}) if $v;
Branch: 1 branch
BranchTrueFalseTotal
if $v 1 2 3
459 }
460 else {
461 6 $v = $tra->($v);
462 6 ▶ $worksheet->write($row, $col, $v) if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 6 0 6
463 }
464 }
465 else {
466 0 my $extra = $p->{extra};
467 0 my $content = $extra->{content};
468 my $text = ref $content eq 'CODE'
469 ? $content->($record)
470 0 ▶ : $record->{$content};
Branch: 1 branch
BranchTrueFalseTotal
ref $content eq 'CODE' ? : 0 0 0
471 0 ▶ if (defined $text and $text ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $text and $text ne "") 0 0 0
Condition0%0/3
defined $text and $text ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $text and $text ne ""
defined $text $text ne ""
Truth table0%0/3
A and B
A= defined $textB= $text ne ""
ABresult
0X0
100
111
472 0 ▶ my $size = $extra->{size} // $QR_DEFAULT_SIZE;
Condition0%0/3
$extra->{"size"} // $QR_DEFAULT_SIZE
l!l&&r!l&&!r
000
MC/DC0%0/2
$extra->{"size"} // $QR_DEFAULT_SIZE
$extra->{"size"} $QR_DEFAULT_SIZE
Truth table0%0/3
A // B
A= $extra->{"size"}B= $QR_DEFAULT_SIZE
ABresult
1X1
011
000
473 0 ▶ $tmpDir //= File::Temp->newdir;
Condition0%0/3
$tmpDir //= "File::Temp"->newdir
l!l&&r!l&&!r
000
MC/DC0%0/2
$tmpDir //= "File::Temp"->newdir
$tmpDir "File::Temp"->newdir
Truth table0%0/3
A //= B
A= $tmpDirB= "File::Temp"->newdir
ABresult
1X1
011
000
474 0 ▶ my $qr = $qrCache{$text} //= do {
Condition0%0/3
$qrCache{$text} //= do { my $matrix = eval { do { $self->_qrEncoder->plot($text) } } or die mkerror(9937, q[cannot encode '] . (length $text > 40 ? substr($text, 0, 40) . '...' : $text) . "' as a QR code: $@"); my $path = $tmpDir->dirname . '/qr-' . $qrCount++ . '.png'; open my $fh, ">:raw", $path or die mkerror(9936, "failed to open ${path}: $!"); print $fh $self->_qrPng($matrix); close $fh; +{"path", $path, "px", (scalar(@$matrix) + 2 * $QR_QUIET_ZONE) * $QR_MODULE_SIZE} }
l!l&&r!l&&!r
000
MC/DC0%0/2
$qrCache{$text} //= do { my $matrix = eval { do { $self->_qrEncoder->plot($text) } } or die mkerror(9937, q[cannot encode '] . (length $text > 40 ? substr($text, 0, 40) . '...' : $text) . "' as a QR code: $@"); my $path = $tmpDir->dirname . '/qr-' . $qrCount++ . '.png'; open my $fh, ">:raw", $path or die mkerror(9936, "failed to open ${path}: $!"); print $fh $self->_qrPng($matrix); close $fh; +{"path", $path, "px", (scalar(@$matrix) + 2 * $QR_QUIET_ZONE) * $QR_MODULE_SIZE} }
$qrCache{$text} do { my $matrix = eval { do { $self->_qrEncoder->plot($text) } } or die mkerror(9937, q[cannot encode '] . (length $text > 40 ? substr($text, 0, 40) . '...' : $text) . "' as a QR code: $@"); my $path = $tmpDir->dirname . '/qr-' . $qrCount++ . '.png'; open my $fh, ">:raw", $path or die mkerror(9936, "failed to open ${path}: $!"); print $fh $self->_qrPng($matrix); close $fh; +{"path", $path, "px", (scalar(@$matrix) + 2 * $QR_QUIET_ZONE) * $QR_MODULE_SIZE} }
Truth table0%0/3
A //= B
A= $qrCache{$text}B= do { my $matrix = eval { do { $self->_qrEncoder->plot($text) } } or die mkerror(9937, q[cannot encode '] . (length $text > 40 ? substr($text, 0, 40) . '...' : $text) . "' as a QR code: $@"); my $path = $tmpDir->dirname . '/qr-' . $qrCount++ . '.png'; open my $fh, ">:raw", $path or die mkerror(9936, "failed to open ${path}: $!"); print $fh $self->_qrPng($matrix); close $fh; +{"path", $path, "px", (scalar(@$matrix) + 2 * $QR_QUIET_ZONE) * $QR_MODULE_SIZE} }
ABresult
1X1
011
000
475 # a qr code has a capacity limit, and
476 # Text::QRCode reports going over it with
477 # a bare XS error
478 0 ▶ my $matrix = eval {
Branch: 1 branch
BranchTrueFalseTotal
my $matrix = eval { do { $self->_qrEncoder->plot($text) } } or die mkerror(9937, q[cannot encode '] . (length $text > 40 ? substr($text, 0, 40) . '...' : $text) . "' as a QR code: $@") 0 0 0
479 0 ▶ $self->_qrEncoder->plot($text) }
Branch: 1 branch
BranchTrueFalseTotal
length $text > 40 ? : 0 0 0
480 or die mkerror(9937,
481 "cannot encode '"
482 .(length($text) > 40
483 ? substr($text,0,40).'...'
484 : $text)
485 ."' as a QR code: $@");
486 0 my $path = $tmpDir->dirname
487 . '/qr-' . $qrCount++ . '.png';
488 0 ▶ open my $fh, '>:raw', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $path or die mkerror(9936, "failed to open ${path}: $!") 0 0 0
489 or die mkerror(9936,
490 "failed to open $path: $!");
491 0 print $fh $self->_qrPng($matrix);
492 0 close $fh;
493 0 { path => $path,
494 # what _qrPng made of it
495 px => (scalar(@$matrix) + 2 * $QR_QUIET_ZONE)
496 * $QR_MODULE_SIZE,
497 };
498 };
499 # excel scales an image against its natural
500 # size at 96 dpi
501 0 my $scale = $size / $qr->{px};
502 $worksheet->insert_image($row, $col, $qr->{path}, {
503 0 x_scale => $scale,
504 y_scale => $scale,
505 x_offset => 2,
506 y_offset => 2,
507 });
508 0 ▶ $rowSize = $size if $size > $rowSize;
Branch: 1 branch
BranchTrueFalseTotal
if $size > $rowSize 0 0 0
509 }
510 }
511 9 $col++;
512 }
513 # a point is 3/4 of a pixel
514 3 ▶ $worksheet->set_row($row, ($rowSize + 6) * 0.75) if $rowSize;
Branch: 1 branch
BranchTrueFalseTotal
if $rowSize 0 3 3
515 3 $row++;
516 }
517  
518 1 $workbook->close();
519 1 my $asset = Mojo::Asset::Memory->new;
520 1 $asset->add_chunk($xlsx);
521 return {
522 1 asset => $asset,
523 type => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
524 filename => $filename,
525 }
526  
527 }
528 else {
529 0 die mkerror(9999, "unknown export type $type");
530 }
531 }
532 2 };
533 }
534  
535 13 1;
536 __END__
« lib/CallBackery/GuiPlugin/UserForm.pm ↑ Summary lib/CallBackery/GuiPlugin/Abstract.pm »