Bug 31239: (QA follow-up) Fixing ternary formatting
[koha.git] / misc / cronjobs / gather_print_notices.pl
1 #!/usr/bin/perl -w
2
3 use Modern::Perl;
4
5 use CGI; # NOT a CGI script, this is just to keep C4::Templates::gettemplate happy
6 use Koha::Script -cron;
7 use C4::Context;
8 use C4::Letters qw( GetPrintMessages );
9 use C4::Templates;
10 use File::Spec;
11 use Pod::Usage qw( pod2usage );
12 use Getopt::Long qw( GetOptions );
13 use C4::Log qw( cronlogaction );
14
15 use Koha::DateUtils qw( dt_from_string output_pref );
16 use Koha::Email;
17 use Koha::Util::OpenDocument qw( generate_ods );
18 use Koha::SMTP::Servers;
19
20 my (
21     $help,
22     $split,
23     $html,
24     $csv,
25     $ods,
26     $delimiter,
27     @letter_codes,
28     $send,
29     @emails,
30 );
31
32 $send = 1;
33 GetOptions(
34     'h|help'  => \$help,
35     's|split' => \$split,
36     'html'    => \$html,
37     'csv'     => \$csv,
38     'ods'     => \$ods,
39     'd|delimiter:s' => \$delimiter,
40     'letter_code:s' => \@letter_codes,
41     'send!'         => \$send,
42     'e|email:s'     => \@emails,
43 ) || pod2usage(1);
44
45 pod2usage(0) if $help;
46
47 my $output_directory = $ARGV[0];
48
49 if ( !$output_directory || !-d $output_directory || !-w $output_directory ) {
50     pod2usage({
51         -exitval => 1,
52         -msg => qq{\nError: You must specify a valid and writeable directory to dump the print notices in.\n},
53     });
54 }
55
56 # Default value is html
57 $html = 1 if not $html and not $csv and not $ods;
58
59 if ( $csv and @letter_codes != 1 ) {
60     pod2usage({
61         -exitval => 1,
62         -msg => qq{\nIt is not consistent to use --csv without one (and only one) letter_code\n},
63     });
64 }
65
66 if ( $ods and @letter_codes != 1 ) {
67     pod2usage({
68         -exitval => 1,
69         -msg => qq{\nIt is not consistent to use --ods without one (and only one) letter_code\n},
70     });
71 }
72
73 $delimiter ||= q|,|;
74
75 cronlogaction();
76
77 my $today_iso     = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) ;
78 my $today_syspref = output_pref( { dt => dt_from_string, dateonly => 1 } );
79
80 my @all_messages = @{ GetPrintMessages() };
81
82 # Filter by letter_code
83 @all_messages = map {
84     my $letter_code = $_->{letter_code};
85     (
86         grep { $_ eq $letter_code } @letter_codes
87     ) ? $_ : ()
88 } @all_messages if @letter_codes;
89 exit unless @all_messages;
90
91 my ( $html_filenames, $csv_filenames, $ods_filenames );
92 $csv_filenames = print_notices({
93     messages => \@all_messages,
94     split => $split,
95     output_directory => $output_directory,
96     format => 'csv',
97 }) if $csv;
98
99 $ods_filenames = print_notices({
100     messages => \@all_messages,
101     split => $split,
102     output_directory => $output_directory,
103     format => 'ods',
104 }) if $ods;
105
106 if ( $html ) {
107     ## carriage return replaced by <br/> as output is html
108     foreach my $message (@all_messages) {
109         local $_ = $message->{'content'};
110         s/\n/<br \/>/g;
111         s/\r//g;
112         $message->{'content'} = $_;
113     }
114
115     $html_filenames = print_notices({
116         messages => \@all_messages,
117         split => $split,
118         output_directory => $output_directory,
119         format => 'html',
120     });
121 }
122
123 if ( @emails ) {
124     my $files = {
125         html => $html_filenames,
126         csv  => $csv_filenames,
127         ods  => $ods_filenames,
128     };
129
130     my $transport = Koha::SMTP::Servers->get_default->transport;
131
132     for my $email ( @emails ) {
133         send_files(
134             {
135                 directory => $output_directory,
136                 files     => $files,
137                 from      => C4::Context->preference('KohaAdminEmailAddress'),    # Should be replaced if bug 8000 is pushed
138                 to        => $email,
139                 transport => $transport,
140             }
141         );
142     }
143 }
144
145 sub print_notices {
146     my ( $params ) = @_;
147
148     my $messages = $params->{messages};
149     my $split = $params->{split};
150     my $output_directory = $params->{output_directory};
151     my $format = $params->{format} // 'html';
152
153     die "Format $format is not known"
154         unless $format =~ m[^html$|^csv$|^ods$];
155
156     my ( @filenames, $messages_by_branch );
157
158     if ( $split ) {
159         foreach my $message (@$messages) {
160             push( @{ $messages_by_branch->{ $message->{'branchcode'} } }, $message );
161         }
162     } else {
163         $messages_by_branch->{all_branches} = $messages;
164     }
165
166     while ( my ( $branchcode, $branch_messages ) = each %$messages_by_branch ) {
167         my $letter_codes = @letter_codes == 0 ? 'all' : join '_', @letter_codes;
168         my $filename = $split
169             ? "notices_$letter_codes-" . $today_iso . "-$branchcode.$format"
170             : "notices_$letter_codes-" . $today_iso . ".$format";
171         my $filepath = File::Spec->catdir( $output_directory, $filename );
172         if ( $format eq 'html' ) {
173             generate_html({
174                 messages => $branch_messages,
175                 filepath => $filepath,
176             });
177         } elsif ( $format eq 'csv' ) {
178             generate_csv ({
179                 messages => $branch_messages,
180                 filepath => $filepath,
181             });
182         } elsif ( $format eq 'ods' ) {
183             _generate_ods ({
184                 messages => $branch_messages,
185                 filepath => $filepath,
186             });
187         }
188
189         if ( $send ) {
190             foreach my $message ( @$branch_messages ) {
191                 C4::Letters::_set_message_status(
192                     {
193                         message_id => $message->{'message_id'},
194                         status => 'sent'
195                     }
196                 );
197             }
198         }
199         push @filenames, $filename;
200     }
201     return \@filenames;
202 }
203
204 sub generate_html {
205     my ( $params ) = @_;
206     my $messages = $params->{messages};
207     my $filepath = $params->{filepath};
208
209     my $template =
210       C4::Templates::gettemplate( 'batch/print-notices.tt', 'intranet',
211         CGI->new );
212
213     $template->param(
214         stylesheet => C4::Context->preference("NoticeCSS"),
215         today      => $today_syspref,
216         messages   => $messages,
217     );
218
219     open my $OUTPUT, '>encoding(utf-8)', $filepath
220         or die "Could not open $filepath: $!";
221     print $OUTPUT $template->output;
222     close $OUTPUT;
223 }
224
225 sub generate_csv {
226     my ( $params ) = @_;
227     my $messages = $params->{messages};
228     my $filepath = $params->{filepath};
229
230     open my $OUTPUT, '>encoding(utf-8)', $filepath
231         or die "Could not open $filepath: $!";
232     my $headers;
233     foreach my $message ( @$messages ) {
234         my @lines = split /\n/, $message->{content};
235         chomp for @lines;
236
237         # We don't have headers, get them
238         unless ( $headers ) {
239             $headers = $lines[0];
240             say $OUTPUT $headers;
241         }
242
243         shift @lines;
244         for my $line ( @lines ) {
245             next if $line =~ /^\s$/;
246             say $OUTPUT $line;
247         }
248     }
249 }
250
251 sub _generate_ods {
252     my ( $params ) = @_;
253     my $messages = $params->{messages};
254     my $ods_filepath = $params->{filepath};
255
256     # Prepare sheet
257     my $ods_content;
258     my $has_headers;
259     foreach my $message ( @$messages ) {
260         my @message_lines = split /\n/, $message->{content};
261         chomp for @message_lines;
262         # Get headers from first message
263         if ($has_headers) {
264             shift @message_lines;
265         } else {
266             $has_headers = 1;
267         }
268         foreach my $message_line ( @message_lines ) {
269             my @content_row;
270             my @message_cells = split $delimiter, $message_line;
271             foreach ( @message_cells ) {
272                 push @content_row, Encode::encode( 'UTF8', $_ );
273             }
274             push @$ods_content, \@content_row;
275         }
276     }
277
278     # Process
279     generate_ods($ods_filepath, $ods_content);
280 }
281
282 sub send_files {
283     my ( $params ) = @_;
284     my $directory = $params->{directory};
285     my $files     = $params->{files};
286     my $to        = $params->{to};
287     my $from      = $params->{from};
288     my $transport = $params->{transport};
289
290     return unless $to and $from and $transport;
291
292     my $email = Koha::Email->create(
293         {
294             from    => $from,
295             to      => $to,
296             subject => 'Print notices for ' . $today_syspref,
297         }
298     );
299
300     while ( my ( $type, $filenames ) = each %$files ) {
301         for my $filename ( @$filenames ) {
302             my $mimetype = $type eq 'html'
303                 ? 'text/html'
304                 : $type eq 'csv'
305                     ? 'text/csv'
306                     : $type eq 'ods'
307                         ? 'application/vnd.oasis.opendocument.spreadsheet'
308                         : undef;
309
310             next unless $mimetype;
311
312             my $filepath = File::Spec->catfile( $directory, $filename );
313
314             next unless $filepath or -f $filepath;
315
316             $email->attach_file(
317                 $filepath,
318                 content_type => $mimetype,
319                 name         => $filename,
320                 disposition  => 'attachment',
321             );
322         }
323     }
324
325     $email->send_or_die( { transport => $transport } );
326
327 }
328
329 =head1 NAME
330
331 gather_print_notices - Print waiting print notices
332
333 =head1 SYNOPSIS
334
335 gather_print_notices output_directory [-s|--split] [--html] [--csv] [--ods] [--letter_code=LETTER_CODE] [-e|--email=your_email@example.org] [-h|--help]
336
337 Will print all waiting print notices to the output_directory.
338
339 The generated filename will be notices-TODAY.[csv|html|ods] or notices-TODAY-BRANCHCODE.[csv|html|ods] if the --split parameter is given.
340
341 =head1 OPTIONS
342
343 =over
344
345 =item B<output_directory>
346
347 Define the output directory where the files will be generated.
348
349 =item B<--send|--nosend>
350
351 After files have been generated, messages status is changed from 'pending' to
352 'sent'. This is the default action, without this parameter or with --send.
353 Using --nosend, the message status is not changed.
354
355 =item B<-s|--split>
356
357 Split messages into separate files by borrower home library to OUTPUT_DIRECTORY/notices-CURRENT_DATE-BRANCHCODE.[csv|html|ods]
358
359 =item B<--html>
360
361 Generate the print notices in a html file (default is --html, if --csv and --ods are not given).
362
363 =item B<--csv>
364
365 Generate the print notices in a csv file.
366 If you use this parameter, the template should contain 2 lines.
367 The first one the csv headers and the second one the value list.
368
369 For example:
370 cardnumber:patron:email:item
371 <<borrowers.cardnumber>>:<<borrowers.firstname>> <<borrowers.surname>>:<<borrowers.email>>:<<items.barcode>>
372
373 You have to combine this option with one (and only one) letter_code.
374
375 =item B<--ods>
376
377 Generate the print notices in a ods file.
378
379 This is the same as the csv parameter but using csv2odf to generate an ods file instead of a csv file.
380
381 =item B<--letter_code>
382
383 Filter print messages by letter_code.
384 Several letter_code parameters can be given.
385
386 =item B<-e|--email>
387
388 Repeatable.
389 E-mail address to send generated files to.
390
391 =item B<-h|--help>
392
393 Print a brief help message
394
395 =back
396
397 =head1 AUTHOR
398
399 Jesse Weaver <pianohacker@gmail.com>
400
401 Jonathan Druart <jonathan.druart@biblibre.com>
402
403 =head1 COPYRIGHT
404
405 Copyright 2009 Jesse Weaver
406
407 Copyright 2014 BibLibre
408
409 =head1 LICENSE
410 This file is part of Koha.
411
412 Koha is free software; you can redistribute it and/or modify it
413 under the terms of the GNU General Public License as published by
414 the Free Software Foundation; either version 3 of the License, or
415 (at your option) any later version.
416
417 Koha is distributed in the hope that it will be useful, but
418 WITHOUT ANY WARRANTY; without even the implied warranty of
419 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
420 GNU General Public License for more details.
421
422 You should have received a copy of the GNU General Public License
423 along with Koha; if not, see <http://www.gnu.org/licenses>.
424
425 =cut