Bug 23838: Use $patron_to_html formater
[srvgit] / C4 / Reports / Guided.pm
1 package C4::Reports::Guided;
2
3 # Copyright 2007 Liblime Ltd
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21 use CGI qw ( -utf8 );
22 use Carp qw( carp croak );
23 use JSON qw( from_json );
24
25 use C4::Context;
26 use C4::Templates qw/themelanguage/;
27 use C4::Koha qw( GetAuthorisedValues );
28 use Koha::DateUtils qw( dt_from_string output_pref );
29 use Koha::Patrons;
30 use Koha::Reports;
31 use C4::Output;
32 use C4::Log qw( logaction );
33 use Koha::Notice::Templates;
34
35 use Koha::Database::Columns;
36 use Koha::Logger;
37 use Koha::AuthorisedValues;
38 use Koha::Patron::Categories;
39 use Koha::SharedContent;
40
41 our (@ISA, @EXPORT_OK);
42 BEGIN {
43     require Exporter;
44     @ISA    = qw(Exporter);
45     @EXPORT_OK = qw(
46       get_report_types get_report_areas get_report_groups get_columns build_query get_criteria
47       save_report get_saved_reports execute_query
48       get_column_type get_distinct_values save_dictionary get_from_dictionary
49       delete_definition delete_report store_results format_results get_sql get_results
50       nb_rows update_sql
51       strip_limit
52       convert_sql
53       GetReservedAuthorisedValues
54       GetParametersFromSQL
55       IsAuthorisedValueValid
56       ValidateSQLParameters
57       nb_rows update_sql
58       EmailReport
59     );
60 }
61
62 =head1 NAME
63
64 C4::Reports::Guided - Module for generating guided reports 
65
66 =head1 SYNOPSIS
67
68   use C4::Reports::Guided;
69
70 =head1 DESCRIPTION
71
72 =cut
73
74 =head1 METHODS
75
76 =head2 get_report_areas
77
78 This will return a list of all the available report areas
79
80 =cut
81
82 sub get_area_name_sql_snippet {
83     my @REPORT_AREA = (
84         [CIRC => "Circulation"],
85         [CAT  => "Catalogue"],
86         [PAT  => "Patrons"],
87         [ACQ  => "Acquisition"],
88         [ACC  => "Accounts"],
89         [SER  => "Serials"],
90     );
91
92     return "CASE report_area " .
93     join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
94     " END AS areaname";
95 }
96
97 sub get_report_areas {
98
99     my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
100
101     return $report_areas;
102 }
103
104 sub get_table_areas {
105     return (
106     CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
107     CAT  => [ 'items', 'biblioitems', 'biblio' ],
108     PAT  => ['borrowers'],
109     ACQ  => [ 'aqorders', 'biblio', 'items' ],
110     ACC  => [ 'borrowers', 'accountlines' ],
111     SER  => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
112     );
113 }
114
115 =head2 get_report_types
116
117 This will return a list of all the available report types
118
119 =cut
120
121 sub get_report_types {
122     my $dbh = C4::Context->dbh();
123
124     # FIXME these should be in the database perhaps
125     my @reports = ( 'Tabular', 'Summary', 'Matrix' );
126     my @reports2;
127     for ( my $i = 0 ; $i < 3 ; $i++ ) {
128         my %hashrep;
129         $hashrep{id}   = $i + 1;
130         $hashrep{name} = $reports[$i];
131         push @reports2, \%hashrep;
132     }
133     return ( \@reports2 );
134
135 }
136
137 =head2 get_report_groups
138
139 This will return a list of all the available report areas with groups
140
141 =cut
142
143 sub get_report_groups {
144     my $dbh = C4::Context->dbh();
145
146     my $groups = GetAuthorisedValues('REPORT_GROUP');
147     my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
148
149     my %groups_with_subgroups = map { $_->{authorised_value} => {
150                         name => $_->{lib},
151                         groups => {}
152                     } } @$groups;
153     foreach (@$subgroups) {
154         my $sg = $_->{authorised_value};
155         my $g = $_->{lib_opac}
156           or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
157              next;
158         my $g_sg = $groups_with_subgroups{$g}
159           or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
160              next;
161         $g_sg->{subgroups}{$sg} = $_->{lib};
162     }
163     return \%groups_with_subgroups
164 }
165
166 =head2 get_all_tables
167
168 This will return a list of all tables in the database 
169
170 =cut
171
172 sub get_all_tables {
173     my $dbh   = C4::Context->dbh();
174     my $query = "SHOW TABLES";
175     my $sth   = $dbh->prepare($query);
176     $sth->execute();
177     my @tables;
178     while ( my $data = $sth->fetchrow_arrayref() ) {
179         push @tables, $data->[0];
180     }
181     $sth->finish();
182     return ( \@tables );
183
184 }
185
186 =head2 get_columns($area)
187
188 This will return a list of all columns for a report area
189
190 =cut
191
192 sub get_columns {
193
194     # this calls the internal function _get_columns
195     my ( $area, $cgi ) = @_;
196     my %table_areas = get_table_areas;
197     my $tables = $table_areas{$area}
198       or die qq{Unsuported report area "$area"};
199
200     my @allcolumns;
201     my $first = 1;
202     foreach my $table (@$tables) {
203         my @columns = _get_columns($table,$cgi, $first);
204         $first = 0;
205         push @allcolumns, @columns;
206     }
207     return ( \@allcolumns );
208 }
209
210 sub _get_columns {
211     my ($tablename,$cgi, $first) = @_;
212     my $dbh         = C4::Context->dbh();
213     my $sth         = $dbh->prepare("show columns from $tablename");
214     $sth->execute();
215     my @columns;
216     my $columns = Koha::Database::Columns->columns;
217         my %tablehash;
218         $tablehash{'table'}=$tablename;
219     $tablehash{'__first__'} = $first;
220         push @columns, \%tablehash;
221     while ( my $data = $sth->fetchrow_arrayref() ) {
222         my %temphash;
223         $temphash{'name'}        = "$tablename.$data->[0]";
224         $temphash{'description'} = $columns->{$tablename}->{$data->[0]};
225         push @columns, \%temphash;
226     }
227     $sth->finish();
228     return (@columns);
229 }
230
231 =head2 build_query($columns,$criteria,$orderby,$area)
232
233 This will build the sql needed to return the results asked for, 
234 $columns is expected to be of the format tablename.columnname.
235 This is what get_columns returns.
236
237 =cut
238
239 sub build_query {
240     my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
241
242     my %keys = (
243         CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
244                   'items.itemnumber = statistics.itemnumber',
245                   'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
246         CAT  => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
247                   'biblioitems.biblionumber=biblio.biblionumber' ],
248         PAT  => [],
249         ACQ  => [ 'aqorders.biblionumber=biblio.biblionumber',
250                   'biblio.biblionumber=items.biblionumber' ],
251         ACC  => ['borrowers.borrowernumber=accountlines.borrowernumber'],
252         SER  => [ 'serial.serialid=serialitems.serialid', 'serial.subscriptionid=subscription.subscriptionid', 'serial.subscriptionid=subscriptionhistory.subscriptionid', 'serial.subscriptionid=subscriptionroutinglist.subscriptionid', 'biblioitems.biblionumber=serial.biblionumber', 'biblio.biblionumber=biblioitems.biblionumber', 'subscription.aqbooksellerid=aqbooksellers.id'],
253     );
254
255
256 ### $orderby
257     my $keys   = $keys{$area};
258     my %table_areas = get_table_areas;
259     my $tables = $table_areas{$area};
260
261     my $sql =
262       _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
263     return ($sql);
264 }
265
266 sub _build_query {
267     my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
268 ### $orderby
269     # $keys is an array of joining constraints
270     my $dbh           = C4::Context->dbh();
271     my $joinedtables  = join( ',', @$tables );
272     my $joinedcolumns = join( ',', @$columns );
273     my $query =
274       "SELECT $totals $joinedcolumns FROM $tables->[0] ";
275         for (my $i=1;$i<@$tables;$i++){
276                 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
277         }
278
279     if ($criteria) {
280                 $criteria =~ s/AND/WHERE/;
281         $query .= " $criteria";
282     }
283         if ($definition){
284                 my @definitions = split(',',$definition);
285                 my $deftext;
286                 foreach my $def (@definitions){
287                         my $defin=get_from_dictionary('',$def);
288                         $deftext .=" ".$defin->[0]->{'saved_sql'};
289                 }
290                 if ($query =~ /WHERE/i){
291                         $query .= $deftext;
292                 }
293                 else {
294                         $deftext  =~ s/AND/WHERE/;
295                         $query .= $deftext;                     
296                 }
297         }
298     if ($totals) {
299         my $groupby;
300         my @totcolumns = split( ',', $totals );
301         foreach my $total (@totcolumns) {
302             if ( $total =~ /\((.*)\)/ ) {
303                 if ( $groupby eq '' ) {
304                     $groupby = " GROUP BY $1";
305                 }
306                 else {
307                     $groupby .= ",$1";
308                 }
309             }
310         }
311         $query .= $groupby;
312     }
313     if ($orderby) {
314         $query .= $orderby;
315     }
316     return ($query);
317 }
318
319 =head2 get_criteria($area,$cgi);
320
321 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
322
323 =cut
324
325 sub get_criteria {
326     my ($area,$cgi) = @_;
327     my $dbh    = C4::Context->dbh();
328
329     # have to do someting here to know if its dropdown, free text, date etc
330     my %criteria = (
331         CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
332                   'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
333         CAT  => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
334                   'items.barcode|textrange', 'biblio.frameworkcode',
335                   'items.holdingbranch', 'items.homebranch',
336                   'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
337                   'items.onloan|daterange', 'items.ccode',
338                   'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
339                   'items.location' ],
340         PAT  => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
341         ACQ  => ['aqorders.datereceived|date'],
342         ACC  => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
343         SER  => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
344     );
345
346     # Adds itemtypes to criteria, according to the syspref
347     if ( C4::Context->preference('item-level_itypes') ) {
348         unshift @{ $criteria{'CIRC'} }, 'items.itype';
349         unshift @{ $criteria{'CAT'} }, 'items.itype';
350     } else {
351         unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
352         unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
353     }
354
355
356     my $crit   = $criteria{$area};
357     my $columns = Koha::Database::Columns->columns;
358     my @criteria_array;
359     foreach my $localcrit (@$crit) {
360         my ( $value, $type )   = split( /\|/, $localcrit );
361         my ( $table, $column ) = split( /\./, $value );
362         my $description = $columns->{$table}->{$column};
363         if ($type eq 'textrange') {
364             my %temp;
365             $temp{'name'}        = $value;
366             $temp{'from'}        = "from_" . $value;
367             $temp{'to'}          = "to_" . $value;
368             $temp{'textrange'}   = 1;
369             $temp{'description'} = $description;
370             push @criteria_array, \%temp;
371         }
372         elsif ($type eq 'date') {
373             my %temp;
374             $temp{'name'}        = $value;
375             $temp{'date'}        = 1;
376             $temp{'description'} = $description;
377             push @criteria_array, \%temp;
378         }
379         elsif ($type eq 'daterange') {
380             my %temp;
381             $temp{'name'}        = $value;
382             $temp{'from'}        = "from_" . $value;
383             $temp{'to'}          = "to_" . $value;
384             $temp{'daterange'}   = 1;
385             $temp{'description'} = $description;
386             push @criteria_array, \%temp;
387         }
388         else {
389             my $query =
390             "SELECT distinct($column) as availablevalues FROM $table";
391             my $sth = $dbh->prepare($query);
392             $sth->execute();
393             my @values;
394             # push the runtime choosing option
395             my $list;
396             $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
397             $list='categorycode' if $column eq 'categorycode';
398             $list='itemtypes' if $column eq 'itype';
399             $list='ccode' if $column eq 'ccode';
400             # TODO : improve to let the librarian choose the description at runtime
401             push @values, {
402                 availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
403                 display_value   => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
404             };
405             while ( my $row = $sth->fetchrow_hashref() ) {
406                 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
407                 else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); }
408                 push @values, $row;
409             }
410             $sth->finish();
411
412             push @criteria_array, {
413                 name        => $value,
414                 description => $description,
415                 values      => \@values,
416             };
417         }
418     }
419     return ( \@criteria_array );
420 }
421
422 sub nb_rows {
423     my $sql = shift or return;
424
425     my $derived_name = 'xxx';
426     # make sure the derived table name is not already used
427     while ( $sql =~ m/$derived_name/ ) {
428         $derived_name .= 'x';
429     }
430
431
432     my $dbh = C4::Context->dbh;
433     my $sth;
434     my $n = 0;
435
436     my $RaiseError = $dbh->{RaiseError};
437     my $PrintError = $dbh->{PrintError};
438     $dbh->{RaiseError} = 1;
439     $dbh->{PrintError} = 0;
440     eval {
441         $sth = $dbh->prepare(qq{
442             SELECT COUNT(*) FROM
443             ( $sql ) $derived_name
444         });
445
446         $sth->execute();
447     };
448     $dbh->{RaiseError} = $RaiseError;
449     $dbh->{PrintError} = $PrintError;
450     if ($@) { # To catch "Duplicate column name" caused by the derived table, or any other syntax error
451         eval {
452             $sth = $dbh->prepare($sql);
453             $sth->execute;
454         };
455         warn $@ if $@;
456         # Loop through the complete results, fetching 1,000 rows at a time.  This
457         # lowers memory requirements but increases execution time.
458         while (my $rows = $sth->fetchall_arrayref(undef, 1000)) {
459             $n += @$rows;
460         }
461         return $n;
462     }
463
464     my $results = $sth->fetch;
465     return $results ? $results->[0] : 0;
466 }
467
468 =head2 select_2_select_count
469
470  returns $sql, $offset, $limit
471  $sql returned will be transformed to:
472   ~ remove any LIMIT clause
473   ~ replace SELECT clause w/ SELECT count(*)
474
475 =cut
476
477 sub select_2_select_count {
478     # Modify the query passed in to create a count query... (I think this covers all cases -crn)
479     my ($sql) = strip_limit(shift) or return;
480     $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
481     return $sql;
482 }
483
484 =head2 strip_limit
485 This removes the LIMIT from the query so that a custom one can be specified.
486 Usage:
487    ($new_sql, $offset, $limit) = strip_limit($sql);
488
489 Where:
490   $sql is the query to modify
491   $new_sql is the resulting query
492   $offset is the offset value, if the LIMIT was the two-argument form,
493       0 if it wasn't otherwise given.
494   $limit is the limit value
495
496 Notes:
497   * This makes an effort to not break subqueries that have their own
498     LIMIT specified. It does that by only removing a LIMIT if it comes after
499     a WHERE clause (which isn't perfect, but at least should make more cases
500     work - subqueries with a limit in the WHERE will still break.)
501   * If your query doesn't have a WHERE clause then all LIMITs will be
502     removed. This may break some subqueries, but is hopefully rare enough
503     to not be a big issue.
504
505 =cut
506
507 sub strip_limit {
508     my ($sql) = @_;
509
510     return unless $sql;
511     return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
512
513     # Two options: if there's no WHERE clause in the SQL, we simply capture
514     # any LIMIT that's there. If there is a WHERE, we make sure that we only
515     # capture a LIMIT after the last one. This prevents stomping on subqueries.
516     if ($sql !~ /\bWHERE\b/i) {
517         (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
518         return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
519     } else {
520         my $res = $sql;
521         $res =~ m/.*\bWHERE\b/gsi;
522         $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
523         return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
524     }
525 }
526
527 =head2 execute_query
528
529   ($sth, $error) = execute_query({
530       sql => $sql,
531       offset => $offset,
532       limit => $limit
533       sql_params => \@sql_params],
534       report_id => $report_id
535   })
536
537
538 This function returns a DBI statement handler from which the caller can
539 fetch the results of the SQL passed via C<$sql>.
540
541 If passed any query other than a SELECT, or if there is a DB error,
542 C<$errors> is returned, and is a hashref containing the error after this
543 manner:
544
545 C<$error->{'sqlerr'}> contains the offending SQL keyword.
546 C<$error->{'queryerr'}> contains the native db engine error returned
547 for the query.
548
549 C<$offset>, and C<$limit> are required parameters.
550
551 C<\@sql_params> is an optional list of parameter values to paste in.
552 The caller is responsible for making sure that C<$sql> has placeholders
553 and that the number placeholders matches the number of parameters.
554
555 =cut
556
557 sub execute_query {
558
559     my $params     = shift;
560     my $sql        = $params->{sql};
561     my $offset     = $params->{offset} || 0;
562     my $limit      = $params->{limit}  || 999999;
563     my $sql_params = defined $params->{sql_params} ? $params->{sql_params} : [];
564     my $report_id  = $params->{report_id};
565
566     # check parameters
567     unless ($sql) {
568         carp "execute_query() called without SQL argument";
569         return;
570     }
571
572     Koha::Logger->get->debug("Report - execute_query($sql, $offset, $limit)");
573
574     my ( $is_sql_valid, $errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
575     return (undef, @{$errors}[0]) unless $is_sql_valid;
576
577     foreach my $sql_param ( @$sql_params ){
578         if ( $sql_param =~ m/\n/ ){
579             my @list = split /\n/, $sql_param;
580             my @quoted_list;
581             foreach my $item ( @list ){
582                 $item =~ s/\r//;
583               push @quoted_list, C4::Context->dbh->quote($item);
584             }
585             $sql_param = "(".join(",",@quoted_list).")";
586         }
587     }
588
589     my ($useroffset, $userlimit);
590
591     # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
592     ($sql, $useroffset, $userlimit) = strip_limit($sql);
593
594     Koha::Logger->get->debug(
595         sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
596         $useroffset, ( defined($userlimit) ? $userlimit : 'UNDEF' ) );
597
598     $offset += $useroffset;
599     if (defined($userlimit)) {
600         if ($offset + $limit > $userlimit ) {
601             $limit = $userlimit - $offset;
602         } elsif ( ! $offset && $limit < $userlimit ) {
603             $limit = $userlimit;
604         }
605     }
606     $sql .= " LIMIT ?, ?";
607
608     my $dbh = C4::Context->dbh;
609
610     $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
611
612     my $sth = $dbh->prepare($sql);
613     eval {
614         $sth->execute(@$sql_params, $offset, $limit);
615     };
616     warn $@ if $@;
617
618     return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
619     return ( $sth );
620 }
621
622 =head2 save_report($sql,$name,$type,$notes)
623
624 Given some sql and a name this will saved it so that it can reused
625 Returns id of the newly created report
626
627 =cut
628
629 sub save_report {
630     my ($fields) = @_;
631     my $borrowernumber = $fields->{borrowernumber};
632     my $sql = $fields->{sql};
633     my $name = $fields->{name};
634     my $type = $fields->{type};
635     my $notes = $fields->{notes};
636     my $area = $fields->{area};
637     my $group = $fields->{group};
638     my $subgroup = $fields->{subgroup};
639     my $cache_expiry = $fields->{cache_expiry};
640     my $public = $fields->{public};
641
642     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
643     my $now = dt_from_string;
644     my $report = Koha::Report->new(
645         {
646             borrowernumber  => $borrowernumber,
647             date_created    => $now, # Must be moved to Koha::Report->store
648             last_modified   => $now, # Must be moved to Koha::Report->store
649             savedsql        => $sql,
650             report_name     => $name,
651             report_area     => $area,
652             report_group    => $group,
653             report_subgroup => $subgroup,
654             type            => $type,
655             notes           => $notes,
656             cache_expiry    => $cache_expiry,
657             public          => $public,
658         }
659     )->store;
660
661     return $report->id;
662 }
663
664 sub update_sql {
665     my $id         = shift || croak "No Id given";
666     my $fields     = shift;
667     my $sql = $fields->{sql};
668     my $name = $fields->{name};
669     my $notes = $fields->{notes};
670     my $group = $fields->{group};
671     my $subgroup = $fields->{subgroup};
672     my $cache_expiry = $fields->{cache_expiry};
673     my $public = $fields->{public};
674
675     $sql =~ s/(\s*\;\s*)$// if defined $sql;    # removes trailing whitespace and /;/
676     my $report = Koha::Reports->find($id);
677     $report->last_modified(dt_from_string);
678     $report->savedsql($sql);
679     $report->report_name($name);
680     $report->notes($notes);
681     $report->report_group($group);
682     $report->report_subgroup($subgroup);
683     $report->cache_expiry($cache_expiry) if defined $cache_expiry;
684     $report->public($public);
685     $report->store();
686     if( $cache_expiry >= 2592000 ){
687       die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh
688     }
689
690     return $report;
691 }
692
693 sub store_results {
694     my ( $id, $json ) = @_;
695     my $dbh = C4::Context->dbh();
696     $dbh->do(q|
697         INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
698     |, undef, $id, $json );
699 }
700
701 sub format_results {
702     my ( $id ) = @_;
703     my $dbh = C4::Context->dbh();
704     my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
705        SELECT ss.report_name, ss.notes, sr.report, sr.date_run
706        FROM saved_sql ss
707        LEFT JOIN saved_reports sr ON sr.report_id = ss.id
708        WHERE sr.id = ?
709     |, undef, $id);
710     return {
711         report_name => $report_name,
712         notes => $notes,
713         results => from_json( $json ),
714         date_run => $date_run,
715     };
716 }
717
718 sub delete_report {
719     my (@ids) = @_;
720     return unless @ids;
721     foreach my $id (@ids) {
722         my $data = Koha::Reports->find($id);
723         logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
724     }
725     my $dbh = C4::Context->dbh;
726     my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
727     my $sth = $dbh->prepare($query);
728     return $sth->execute(@ids);
729 }
730
731 sub get_saved_reports_base_query {
732     my $area_name_sql_snippet = get_area_name_sql_snippet;
733     return <<EOQ;
734 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
735 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
736 FROM saved_sql s
737 LEFT JOIN saved_reports r ON r.report_id = s.id
738 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
739 LEFT OUTER JOIN authorised_values av_sg ON (av_sg.category = 'REPORT_SUBGROUP' AND av_sg.lib_opac = s.report_group AND av_sg.authorised_value = s.report_subgroup)
740 LEFT OUTER JOIN borrowers b USING (borrowernumber)
741 EOQ
742 }
743
744 sub get_saved_reports {
745 # $filter is either { date => $d, author => $a, keyword => $kw, }
746 # or $keyword. Optional.
747     my ($filter) = @_;
748     $filter = { keyword => $filter } if $filter && !ref( $filter );
749     my ($group, $subgroup) = @_;
750
751     my $dbh   = C4::Context->dbh();
752     my $query = get_saved_reports_base_query;
753     my (@cond,@args);
754     if ($filter) {
755         if (my $date = $filter->{date}) {
756             $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
757             push @cond, "DATE(last_modified) = ? OR
758                          DATE(last_run) = ?";
759             push @args, $date, $date;
760         }
761         if (my $author = $filter->{author}) {
762             $author = "%$author%";
763             push @cond, "surname LIKE ? OR
764                          firstname LIKE ?";
765             push @args, $author, $author;
766         }
767         if (my $keyword = $filter->{keyword}) {
768             push @cond, q|
769                        report LIKE ?
770                     OR report_name LIKE ?
771                     OR notes LIKE ?
772                     OR savedsql LIKE ?
773                     OR s.id = ?
774             |;
775             push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
776         }
777         if ($filter->{group}) {
778             push @cond, "report_group = ?";
779             push @args, $filter->{group};
780         }
781         if ($filter->{subgroup}) {
782             push @cond, "report_subgroup = ?";
783             push @args, $filter->{subgroup};
784         }
785     }
786     $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
787     $query .= " GROUP BY s.id, s.borrowernumber, s.date_created, s.last_modified, s.savedsql, s.last_run, s.report_name, s.type, s.notes, s.cache_expiry, s.public, s.report_area, s.report_group, s.report_subgroup, s.mana_id, av_g.lib, av_sg.lib, b.firstname, b.surname";
788     $query .= " ORDER by date_created";
789
790     my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
791
792     return $result;
793 }
794
795 =head2 get_column_type($column)
796
797 This takes a column name of the format table.column and will return what type it is
798 (free text, set values, date)
799
800 =cut
801
802 sub get_column_type {
803         my ($tablecolumn) = @_;
804         my ($table,$column) = split(/\./,$tablecolumn);
805         my $dbh = C4::Context->dbh();
806         my $catalog;
807         my $schema;
808
809     # mysql doesn't support a column selection, set column to %
810         my $tempcolumn='%';
811         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
812         while (my $info = $sth->fetchrow_hashref()){
813                 if ($info->{'COLUMN_NAME'} eq $column){
814                         #column we want
815                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
816                                 $info->{'TYPE_NAME'} = 'distinct';
817                         }
818                         return $info->{'TYPE_NAME'};            
819                 }
820         }
821 }
822
823 =head2 get_distinct_values($column)
824
825 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
826 with the distinct values of the column
827
828 =cut
829
830 sub get_distinct_values {
831         my ($tablecolumn) = @_;
832         my ($table,$column) = split(/\./,$tablecolumn);
833         my $dbh = C4::Context->dbh();
834         my $query =
835           "SELECT distinct($column) as availablevalues FROM $table";
836         my $sth = $dbh->prepare($query);
837         $sth->execute();
838     return $sth->fetchall_arrayref({});
839 }       
840
841 sub save_dictionary {
842     my ( $name, $description, $sql, $area ) = @_;
843     my $dbh   = C4::Context->dbh();
844     my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
845   VALUES (?,?,?,?,now(),now())";
846     my $sth = $dbh->prepare($query);
847     $sth->execute($name,$description,$sql,$area) || return 0;
848     return 1;
849 }
850
851 sub get_from_dictionary {
852     my ( $area, $id ) = @_;
853     my $dbh   = C4::Context->dbh();
854     my $area_name_sql_snippet = get_area_name_sql_snippet;
855     my $query = <<EOQ;
856 SELECT d.*, $area_name_sql_snippet
857 FROM reports_dictionary d
858 EOQ
859
860     if ($area) {
861         $query .= " WHERE report_area = ?";
862     } elsif ($id) {
863         $query .= " WHERE id = ?";
864     }
865     my $sth = $dbh->prepare($query);
866     if ($id) {
867         $sth->execute($id);
868     } elsif ($area) {
869         $sth->execute($area);
870     } else {
871         $sth->execute();
872     }
873     my @loop;
874     while ( my $data = $sth->fetchrow_hashref() ) {
875         push @loop, $data;
876     }
877     return ( \@loop );
878 }
879
880 sub delete_definition {
881         my ($id) = @_ or return;
882         my $dbh = C4::Context->dbh();
883         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
884         my $sth = $dbh->prepare($query);
885         $sth->execute($id);
886 }
887
888 =head2 get_sql($report_id)
889
890 Given a report id, return the SQL statement for that report.
891 Otherwise, it just returns.
892
893 =cut
894
895 sub get_sql {
896         my ($id) = @_ or return;
897         my $dbh = C4::Context->dbh();
898         my $query = "SELECT * FROM saved_sql WHERE id = ?";
899         my $sth = $dbh->prepare($query);
900         $sth->execute($id);
901         my $data=$sth->fetchrow_hashref();
902         return $data->{'savedsql'};
903 }
904
905 sub get_results {
906     my ( $report_id ) = @_;
907     my $dbh = C4::Context->dbh;
908     return $dbh->selectall_arrayref(q|
909         SELECT id, report, date_run
910         FROM saved_reports
911         WHERE report_id = ?
912     |, { Slice => {} }, $report_id);
913 }
914
915 =head2 GetReservedAuthorisedValues
916
917     my %reserved_authorised_values = GetReservedAuthorisedValues();
918
919 Returns a hash containig all reserved words
920
921 =cut
922
923 sub GetReservedAuthorisedValues {
924     my %reserved_authorised_values =
925             map { $_ => 1 } ( 'date',
926                               'list',
927                               'branches',
928                               'itemtypes',
929                               'cn_source',
930                               'categorycode',
931                               'biblio_framework',
932                               'cash_registers',
933                               'debit_types',
934                               'credit_types' );
935
936    return \%reserved_authorised_values;
937 }
938
939
940 =head2 IsAuthorisedValueValid
941
942     my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
943
944 Returns 1 if $authorised_value is on the reserved authorised values list or
945 in the authorised value categories defined in
946
947 =cut
948
949 sub IsAuthorisedValueValid {
950
951     my $authorised_value = shift;
952     my $reserved_authorised_values = GetReservedAuthorisedValues();
953
954     if ( exists $reserved_authorised_values->{$authorised_value} ||
955          Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
956         return 1;
957     }
958
959     return 0;
960 }
961
962 =head2 GetParametersFromSQL
963
964     my @sql_parameters = GetParametersFromSQL($sql)
965
966 Returns an arrayref of hashes containing the keys name and authval
967
968 =cut
969
970 sub GetParametersFromSQL {
971
972     my $sql = shift ;
973     my @split = split(/<<|>>/,$sql);
974     my @sql_parameters = ();
975
976     for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
977         my ($name,$authval) = split(/\|/,$split[$i*2+1]);
978         $authval =~ s/\:all$// if $authval;
979         push @sql_parameters, { 'name' => $name, 'authval' => $authval };
980     }
981
982     return \@sql_parameters;
983 }
984
985 =head2 ValidateSQLParameters
986
987     my @problematic_parameters = ValidateSQLParameters($sql)
988
989 Returns an arrayref of hashes containing the keys name and authval of
990 those SQL parameters that do not correspond to valid authorised names
991
992 =cut
993
994 sub ValidateSQLParameters {
995
996     my $sql = shift;
997     my @problematic_parameters = ();
998     my $sql_parameters = GetParametersFromSQL($sql);
999
1000     foreach my $sql_parameter (@$sql_parameters) {
1001         if ( defined $sql_parameter->{'authval'} ) {
1002             push @problematic_parameters, $sql_parameter unless
1003                 IsAuthorisedValueValid($sql_parameter->{'authval'});
1004         }
1005     }
1006
1007     return \@problematic_parameters;
1008 }
1009
1010 =head2 EmailReport
1011
1012     my ( $emails, $arrayrefs ) = EmailReport($report_id, $letter_code, $module, $branch, $email)
1013
1014 Take a report and use it to process a Template Toolkit formatted notice
1015 Returns arrayrefs containing prepared letters and errors respectively
1016
1017 =cut
1018
1019 sub EmailReport {
1020
1021     my $params     = shift;
1022     my $report_id  = $params->{report_id};
1023     my $from       = $params->{from};
1024     my $email_col  = $params->{email} || 'email';
1025     my $module     = $params->{module};
1026     my $code       = $params->{code};
1027     my $branch     = $params->{branch} || "";
1028
1029     my @errors = ();
1030     my @emails = ();
1031
1032     return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code);
1033
1034     return ( undef, [{ FATAL => "NO_LETTER" }] ) unless
1035     my $letter = Koha::Notice::Templates->find({
1036         module     => $module,
1037         code       => $code,
1038         branchcode => $branch,
1039         message_transport_type => 'email',
1040     });
1041     $letter = $letter->unblessed;
1042     $letter->{'content-type'} = 'text/html; charset="UTF-8"' if $letter->{'is_html'};
1043
1044     my $report = Koha::Reports->find( $report_id );
1045     my $sql = $report->savedsql;
1046     return ( { FATAL => "NO_REPORT" } ) unless $sql;
1047
1048     #don't pass offset or limit, hardcoded limit of 999,999 will be used
1049     my ( $sth, $errors ) = execute_query( { sql => $sql, report_id => $report_id } );
1050     return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors;
1051
1052     my $counter = 1;
1053     my $template = $letter->{content};
1054
1055     while ( my $row = $sth->fetchrow_hashref() ) {
1056         my $email;
1057         my $err_count = scalar @errors;
1058         push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
1059         push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} );
1060         push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
1061         push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
1062
1063         my $from_address = $from || $row->{from};
1064         my $to_address = $row->{$email_col};
1065         push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
1066         $counter++;
1067         next if scalar @errors > $err_count; #If any problems, try next
1068
1069         $letter->{content}       = $content;
1070         $email->{borrowernumber} = $row->{borrowernumber};
1071         $email->{letter}         = { %$letter };
1072         $email->{from_address}   = $from_address;
1073         $email->{to_address}     = $to_address;
1074
1075         push ( @emails, $email );
1076     }
1077
1078     return ( \@emails, \@errors );
1079
1080 }
1081
1082
1083
1084 =head2 ProcessRowTT
1085
1086    my $content = ProcessRowTT($row_hashref, $template);
1087
1088 Accepts a hashref containing values and processes them against Template Toolkit
1089 to produce content
1090
1091 =cut
1092
1093 sub _process_row_TT {
1094
1095     my ($row, $template) = @_;
1096
1097     return 0 unless ($row && $template);
1098     my $content;
1099     my $processor = Template->new();
1100     $processor->process( \$template, $row, \$content);
1101     return $content;
1102
1103 }
1104
1105 sub _get_display_value {
1106     my ( $original_value, $column ) = @_;
1107     if ( $column eq 'periodicity' ) {
1108         my $dbh = C4::Context->dbh();
1109         my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1110         my $sth   = $dbh->prepare($query);
1111         $sth->execute($original_value);
1112         return $sth->fetchrow;
1113     }
1114     return $original_value;
1115 }
1116
1117
1118 =head3 convert_sql
1119
1120 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
1121
1122 Convert a sql query using biblioitems.marcxml to use the new
1123 biblio_metadata.metadata field instead
1124
1125 =cut
1126
1127 sub convert_sql {
1128     my ( $sql ) = @_;
1129     my $updated_sql = $sql;
1130     if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
1131         $updated_sql =~ s|biblioitems|biblio_metadata|g;
1132         $updated_sql =~ s|marcxml|metadata|g;
1133     }
1134     return $updated_sql;
1135 }
1136
1137 1;
1138 __END__
1139
1140 =head1 AUTHOR
1141
1142 Chris Cormack <crc@liblime.com>
1143
1144 =cut