Bug 22521: Update fines handling to use accountline.status
[koha.git] / misc / cronjobs / runreport.pl
1 #!/usr/bin/perl
2 #
3 # Copyright 2008 Liblime
4 # Copyright 2014 Foundations Bible College, Inc.
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22
23 use Koha::Script -cron;
24 use C4::Reports::Guided; # 0.12
25 use Koha::Reports;
26 use C4::Context;
27 use C4::Log;
28 use Koha::Email;
29 use Koha::DateUtils;
30
31 use Getopt::Long qw(:config auto_help auto_version);
32 use Pod::Usage;
33 use MIME::Lite;
34 use Text::CSV::Encoded;
35 use CGI qw ( -utf8 );
36 use Carp;
37 use Encode;
38 use JSON qw( to_json );
39
40 BEGIN {
41     # find Koha's Perl modules
42     # test carefully before changing this
43     use FindBin;
44     eval { require "$FindBin::Bin/../kohalib.pl" };
45 }
46
47 =head1 NAME
48
49 runreport.pl - Run pre-existing saved reports
50
51 =head1 SYNOPSIS
52
53 runreport.pl [ -h | -m ] [ -v ] reportID [ reportID ... ]
54
55  Options:
56    -h --help       brief help message
57    -m --man        full documentation, same as --help --verbose
58    -v --verbose    verbose output
59
60    --format=s      selects format. Choice of text, html, csv or tsv
61
62    -e --email      whether to use e-mail (implied by --to or --from)
63    -a --attachment additionally attach the report as a file. cannot be used with html format
64    --username      username to pass to the SMTP server for authentication
65    --password      password to pass to the SMTP server for authentication
66    --method        method is the type of authentication. Ie. LOGIN, DIGEST-MD5, etc.
67    --to=s          e-mail address to send report to
68    --from=s        e-mail address to send report from
69    --subject=s     subject for the e-mail
70    --store-results store the result of the report
71    --csv-header    add column names as first line of csv output
72
73
74  Arguments:
75    reportID        report ID Number from saved_sql.id, multiple ID's may be specified
76
77 =head1 OPTIONS
78
79 =over
80
81 =item B<--help>
82
83 Print a brief help message and exits.
84
85 =item B<--man>
86
87 Prints the manual page and exits.
88
89 =item B<-v>
90
91 Verbose. Without this flag set, only fatal errors are reported.
92
93 =item B<--format>
94
95 Current options are text, html, csv, and tsv. At the moment, text and tsv both produce tab-separated tab-separated output.
96
97 =item B<--email>
98
99 Whether to use e-mail (implied by --to or --from).
100
101 =item B<--username>
102
103 Username to pass to the SMTP server for authentication
104
105 =item B<--password>
106
107 Password to pass to the SMTP server for authentication
108
109 =item B<--method>
110
111 Method is the type of authentication. Ie. LOGIN, DIGEST-MD5, etc.
112
113 =item B<--to>
114
115 E-mail address to send report to. Defaults to KohaAdminEmailAddress.
116
117 =item B<--from>
118
119 E-mail address to send report from. Defaults to KohaAdminEmailAddress.
120
121 =item B<--subject>
122
123 Subject for the e-mail message. Defaults to "Koha Saved Report"
124
125 =item B<--store-results>
126
127 Store the result of the report into the saved_reports DB table.
128
129 To access the results, go on Reports > Guided reports > Saved report.
130
131 =back
132
133 =head1 DESCRIPTION
134
135 This script is designed to run existing Saved Reports.
136
137 =head1 USAGE EXAMPLES
138
139 B<runreport.pl 16>
140
141 In the most basic form, runs the report specified by ID number from 
142 saved_sql.id, in this case #16, outputting the results to STDOUT.  
143
144 B<runreport.pl 16 17>
145
146 Same as above, but also runs report #17. 
147
148 =head1 TO DO
149
150 =over
151
152
153 =item *
154
155 Allow Saved Results option.
156
157
158 =back
159
160 =head1 SEE ALSO
161
162 Reports - Guided Reports
163
164 =cut
165
166 # These variables can be set by command line options,
167 # initially set to default values.
168
169 my $help    = 0;
170 my $man     = 0;
171 my $verbose = 0;
172 my $email   = 0;
173 my $attachment = 0;
174 my $format  = "text";
175 my $to      = "";
176 my $from    = "";
177 my $subject = "";
178 my $separator = ',';
179 my $quote = '"';
180 my $store_results = 0;
181 my $csv_header = 0;
182
183 my $username = undef;
184 my $password = undef;
185 my $method = 'LOGIN';
186
187 GetOptions(
188     'help|?'            => \$help,
189     'man'               => \$man,
190     'verbose'           => \$verbose,
191     'format=s'          => \$format,
192     'to=s'              => \$to,
193     'from=s'            => \$from,
194     'subject=s'         => \$subject,
195     'email'             => \$email,
196     'a|attachment'      => \$attachment,
197     'username:s'        => \$username,
198     'password:s'        => \$password,
199     'method:s'          => \$method,
200     'store-results'     => \$store_results,
201     'csv-header'        => \$csv_header,
202
203 ) or pod2usage(2);
204 pod2usage( -verbose => 2 ) if ($man);
205 pod2usage( -verbose => 2 ) if ($help and $verbose);
206 pod2usage(1) if $help;
207
208 cronlogaction();
209
210 unless ($format) {
211     $verbose and print STDERR "No format specified, assuming 'text'\n";
212     $format = 'text';
213 }
214
215 if ($format eq 'tsv' || $format eq 'text') {
216     $format = 'csv';
217     $separator = "\t";
218 }
219
220 if ($to or $from or $email) {
221     $email = 1;
222     $from or $from = C4::Context->preference('KohaAdminEmailAddress');
223     $to   or $to   = C4::Context->preference('KohaAdminEmailAddress');
224 }
225
226 unless (scalar(@ARGV)) {
227     print STDERR "ERROR: No reportID(s) specified\n";
228     pod2usage(1);
229 }
230 ($verbose) and print scalar(@ARGV), " argument(s) after options: " . join(" ", @ARGV) . "\n";
231
232 my $today = dt_from_string();
233 my $date = $today->ymd();
234
235 foreach my $report_id (@ARGV) {
236     my $report = Koha::Reports->find( $report_id );
237     unless ($report) {
238         warn "ERROR: No saved report $report_id found";
239         next;
240     }
241     my $sql         = $report->savedsql;
242     my $report_name = $report->report_name;
243     my $type        = $report->type;
244
245     $verbose and print "SQL: $sql\n\n";
246     if ( $subject eq "" )
247     {
248         if ( defined($report_name) and $report_name ne "")
249         {
250             $subject = $report_name ;
251         }
252         else
253         {
254             $subject = 'Koha Saved Report';
255         }
256     }
257     my ($sth) = execute_query( $sql, undef, undef, undef, $report_id );
258     my $count = scalar($sth->rows);
259     unless ($count) {
260         print "NO OUTPUT: 0 results from execute_query\n";
261         next;
262     }
263     $verbose and print "$count results from execute_query\n";
264
265     my $message;
266     my @rows_to_store;
267     if ($format eq 'html') {
268         my $cgi = CGI->new();
269         my @rows;
270         while (my $line = $sth->fetchrow_arrayref) {
271             foreach (@$line) { defined($_) or $_ = ''; }    # catch undef values, replace w/ ''
272             push @rows, $cgi->TR( join('', $cgi->td($line)) ) . "\n";
273             push @rows_to_store, [@$line] if $store_results;
274         }
275         $message = $cgi->table(join "", @rows);
276     } elsif ($format eq 'csv') {
277         my $csv = Text::CSV::Encoded->new({
278             encoding_out => 'utf8',
279             binary      => 1,
280             quote_char  => $quote,
281             sep_char    => $separator,
282             });
283
284         if ( $csv_header ) {
285             my @fields = map { decode( 'utf8', $_ ) } @{ $sth->{NAME} };
286             $csv->combine( @fields );
287             $message .= $csv->string() . "\n";
288             push @rows_to_store, [@fields] if $store_results;
289         }
290
291         while (my $line = $sth->fetchrow_arrayref) {
292             $csv->combine(@$line);
293             $message .= $csv->string() . "\n";
294             push @rows_to_store, [@$line] if $store_results;
295         }
296     }
297     if ( $store_results ) {
298         my $json = to_json( \@rows_to_store );
299         C4::Reports::Guided::store_results( $report_id, $json );
300     }
301     if ($email) {
302         my $args = { to => $to, from => $from, subject => $subject };
303         if ( $format eq 'html' ) {
304             $message = "<html><head><style>tr:nth-child(2n+1) { background-color: #ccc;}</style></head><body>$message</body></html>";
305             $args->{contenttype} = 'text/html';
306         }
307         my $email = Koha::Email->new();
308         my %mail  = $email->create_message_headers($args);
309         $mail{Data} = $message;
310         $mail{Auth} = { user => $username, pass => $password, method => $method } if $username;
311
312         my $msg = MIME::Lite->new(%mail);
313
314         $msg->attach(
315             Type        => "text/$format",
316             Data        => encode( 'utf8', $message ),
317             Filename    => "report$report_id-$date.$format",
318             Disposition => 'attachment',
319         ) if $attachment;
320
321         $msg->send();
322         carp "Mail not sent" unless $msg->last_send_successful();
323     }
324     else {
325         print $message;
326     }
327 }