Bug 21560: create Koha::Util::OpenDocument with subroutine for ODS generation
[koha.git] / misc / cronjobs / gather_print_notices.pl
1 #!/usr/bin/perl -w
2
3 use Modern::Perl;
4
5 BEGIN {
6     # find Koha's Perl modules
7     # test carefully before changing this
8     use FindBin;
9     eval { require "$FindBin::Bin/../kohalib.pl" };
10 }
11
12 use CGI qw( utf8 ); # NOT a CGI script, this is just to keep C4::Templates::gettemplate happy
13 use C4::Context;
14 use C4::Debug;
15 use C4::Letters;
16 use C4::Templates;
17 use File::Spec;
18 use Pod::Usage;
19 use Getopt::Long;
20 use C4::Log;
21
22 use Koha::DateUtils;
23 use MIME::Lite;
24
25 my (
26     $stylesheet,
27     $help,
28     $split,
29     $html,
30     $csv,
31     $ods,
32     $delimiter,
33     @letter_codes,
34     $send,
35     @emails,
36 );
37
38 $send = 1;
39 GetOptions(
40     'h|help'  => \$help,
41     's|split' => \$split,
42     'html'    => \$html,
43     'csv'     => \$csv,
44     'ods'     => \$ods,
45     'd|delimiter:s' => \$delimiter,
46     'letter_code:s' => \@letter_codes,
47     'send!'         => \$send,
48     'e|email:s'     => \@emails,
49 ) || pod2usage(1);
50
51 pod2usage(0) if $help;
52
53 my $output_directory = $ARGV[0];
54
55 if ( !$output_directory || !-d $output_directory || !-w $output_directory ) {
56     pod2usage({
57         -exitval => 1,
58         -msg => qq{\nError: You must specify a valid and writeable directory to dump the print notices in.\n},
59     });
60 }
61
62 # Default value is html
63 $html = 1 if not $html and not $csv and not $ods;
64
65 if ( $csv and @letter_codes != 1 ) {
66     pod2usage({
67         -exitval => 1,
68         -msg => qq{\nIt is not consistent to use --csv without one (and only one) letter_code\n},
69     });
70 }
71
72 if ( $ods and @letter_codes != 1 ) {
73     pod2usage({
74         -exitval => 1,
75         -msg => qq{\nIt is not consistent to use --ods without one (and only one) letter_code\n},
76     });
77 }
78
79 $delimiter ||= q|,|;
80
81 cronlogaction();
82
83 my $today_iso     = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) ;
84 my $today_syspref = output_pref( { dt => dt_from_string, dateonly => 1 } );
85
86 my @all_messages = @{ GetPrintMessages() };
87
88 # Filter by letter_code
89 @all_messages = map {
90     my $letter_code = $_->{letter_code};
91     (
92         grep { /^$letter_code$/ } @letter_codes
93     ) ? $_ : ()
94 } @all_messages if @letter_codes;
95 exit unless @all_messages;
96
97 my ( $html_filenames, $csv_filenames, $ods_filenames );
98 $csv_filenames = print_notices({
99     messages => \@all_messages,
100     split => $split,
101     output_directory => $output_directory,
102     format => 'csv',
103 }) if $csv;
104
105 $ods_filenames = print_notices({
106     messages => \@all_messages,
107     split => $split,
108     output_directory => $output_directory,
109     format => 'ods',
110 }) if $ods;
111
112 if ( $html ) {
113     ## carriage return replaced by <br/> as output is html
114     foreach my $message (@all_messages) {
115         local $_ = $message->{'content'};
116         s/\n/<br \/>/g;
117         s/\r//g;
118         $message->{'content'} = $_;
119     }
120
121     $html_filenames = print_notices({
122         messages => \@all_messages,
123         split => $split,
124         output_directory => $output_directory,
125         format => 'html',
126     });
127 }
128
129 if ( @emails ) {
130     my $files = {
131         html => $html_filenames,
132         csv  => $csv_filenames,
133         ods  => $ods_filenames,
134     };
135     for my $email ( @emails ) {
136         send_files({
137             directory => $output_directory,
138             files => $files,
139             to => $email,
140             from => C4::Context->preference('KohaAdminEmailAddress'), # Should be replaced if bug 8000 is pushed
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         new CGI );
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 ( @csv_lines, $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     use Koha::Util::OpenDocument;
280     generate_ods($ods_filepath, $ods_content);
281 }
282
283 sub send_files {
284     my ( $params ) = @_;
285     my $directory = $params->{directory};
286     my $files = $params->{files};
287     my $to = $params->{to};
288     my $from = $params->{from};
289     return unless $to and $from;
290
291     my $mail = MIME::Lite->new(
292         From     => $from,
293         To       => $to,
294         Subject  => 'Print notices for ' . $today_syspref,
295         Type     => 'multipart/mixed',
296     );
297
298     while ( my ( $type, $filenames ) = each %$files ) {
299         for my $filename ( @$filenames ) {
300             my $mimetype = $type eq 'html'
301                 ? 'text/html'
302                 : $type eq 'csv'
303                     ? 'text/csv'
304                     : $type eq 'ods'
305                         ? 'application/vnd.oasis.opendocument.spreadsheet'
306                         : undef;
307
308             next unless $mimetype;
309
310             my $filepath = File::Spec->catdir( $directory, $filename );
311
312             next unless $filepath or -f $filepath;
313
314             $mail->attach(
315               Type     => $mimetype,
316               Path     => $filepath,
317               Filename => $filename,
318               Encoding => 'base64',
319             );
320         }
321     }
322
323     $mail->send;
324 }
325
326 =head1 NAME
327
328 gather_print_notices - Print waiting print notices
329
330 =head1 SYNOPSIS
331
332 gather_print_notices output_directory [-s|--split] [--html] [--csv] [--ods] [--letter_code=LETTER_CODE] [-e|--email=your_email@example.org] [-h|--help]
333
334 Will print all waiting print notices to the output_directory.
335
336 The generated filename will be notices-TODAY.[csv|html|ods] or notices-TODAY-BRANCHCODE.[csv|html|ods] if the --split parameter is given.
337
338 =head1 OPTIONS
339
340 =over
341
342 =item B<output_directory>
343
344 Define the output directory where the files will be generated.
345
346 =item B<--send|--nosend>
347
348 After files have been generated, messages status is changed from 'pending' to
349 'sent'. This is the default action, without this parameter or with --send.
350 Using --nosend, the message status is not changed.
351
352 =item B<-s|--split>
353
354 Split messages into separate files by borrower home library to OUTPUT_DIRECTORY/notices-CURRENT_DATE-BRANCHCODE.[csv|html|ods]
355
356 =item B<--html>
357
358 Generate the print notices in a html file (default is --html, if --csv and --ods are not given).
359
360 =item B<--csv>
361
362 Generate the print notices in a csv file.
363 If you use this parameter, the template should contain 2 lines.
364 The first one the csv headers and the second one the value list.
365
366 For example:
367 cardnumber:patron:email:item
368 <<borrowers.cardnumber>>:<<borrowers.firstname>> <<borrowers.surname>>:<<borrowers.email>>:<<items.barcode>>
369
370 You have to combine this option with one (and only one) letter_code.
371
372 =item B<--ods>
373
374 Generate the print notices in a ods file.
375
376 This is the same as the csv parameter but using csv2odf to generate an ods file instead of a csv file.
377
378 =item B<--letter_code>
379
380 Filter print messages by letter_code.
381 Several letter_code parameters can be given.
382
383 =item B<-e|--email>
384
385 Repeatable.
386 E-mail address to send generated files to.
387
388 =item B<-h|--help>
389
390 Print a brief help message
391
392 =back
393
394 =head1 AUTHOR
395
396 Jesse Weaver <pianohacker@gmail.com>
397
398 Jonathan Druart <jonathan.druart@biblibre.com>
399
400 =head1 COPYRIGHT
401
402 Copyright 2009 Jesse Weaver
403
404 Copyright 2014 BibLibre
405
406 =head1 LICENSE
407 This file is part of Koha.
408
409 Koha is free software; you can redistribute it and/or modify it
410 under the terms of the GNU General Public License as published by
411 the Free Software Foundation; either version 3 of the License, or
412 (at your option) any later version.
413
414 Koha is distributed in the hope that it will be useful, but
415 WITHOUT ANY WARRANTY; without even the implied warranty of
416 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
417 GNU General Public License for more details.
418
419 You should have received a copy of the GNU General Public License
420 along with Koha; if not, see <http://www.gnu.org/licenses>.
421
422 =cut