Bug 27380: Move get_prepped_report to object and use for svc/reports
[koha-ffzg.git] / C4 / Reports / Guided.pm
index 6f77f5d..a76d86b 100644 (file)
@@ -425,19 +425,41 @@ sub nb_rows {
         $derived_name .= 'x';
     }
 
-    my $sth = C4::Context->dbh->prepare(qq{
-        SELECT COUNT(*) FROM
-        ( $sql ) $derived_name
-    });
 
-    $sth->execute();
+    my $dbh = C4::Context->dbh;
+    my $sth;
+    my $n = 0;
+
+    my $RaiseError = $dbh->{RaiseError};
+    my $PrintError = $dbh->{PrintError};
+    $dbh->{RaiseError} = 1;
+    $dbh->{PrintError} = 0;
+    eval {
+        $sth = $dbh->prepare(qq{
+            SELECT COUNT(*) FROM
+            ( $sql ) $derived_name
+        });
 
-    if ( $sth->errstr ) {
-        return 0;
-    }
-    else {
-       return $sth->fetch->[0];
+        $sth->execute();
+    };
+    $dbh->{RaiseError} = $RaiseError;
+    $dbh->{PrintError} = $PrintError;
+    if ($@) { # To catch "Duplicate column name" caused by the derived table, or any other syntax error
+        eval {
+            $sth = $dbh->prepare($sql);
+            $sth->execute;
+        };
+        warn $@ if $@;
+        # Loop through the complete results, fetching 1,000 rows at a time.  This
+        # lowers memory requirements but increases execution time.
+        while (my $rows = $sth->fetchall_arrayref(undef, 1000)) {
+            $n += @$rows;
+        }
+        return $n;
     }
+
+    my $results = $sth->fetch;
+    return $results ? $results->[0] : 0;
 }
 
 =head2 execute_query
@@ -535,6 +557,18 @@ sub execute_query {
         return (undef, { queryerr => 'Missing SELECT'} );
     }
 
+    foreach my $sql_param ( @$sql_params ){
+        if ( $sql_param =~ m/\n/ ){
+            my @list = split /\n/, $sql_param;
+            my @quoted_list;
+            foreach my $item ( @list ){
+                $item =~ s/\r//;
+              push @quoted_list, C4::Context->dbh->quote($item);
+            }
+            $sql_param = "(".join(",",@quoted_list).")";
+        }
+    }
+
     my ($useroffset, $userlimit);
 
     # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
@@ -557,7 +591,10 @@ sub execute_query {
     $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
 
     my $sth = $dbh->prepare($sql);
-    $sth->execute(@$sql_params, $offset, $limit);
+    eval {
+        $sth->execute(@$sql_params, $offset, $limit);
+    };
+    warn $@ if $@;
 
     return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
     return ( $sth );
@@ -580,17 +617,29 @@ sub save_report {
     my $area = $fields->{area};
     my $group = $fields->{group};
     my $subgroup = $fields->{subgroup};
-    my $cache_expiry = $fields->{cache_expiry} || 300;
+    my $cache_expiry = $fields->{cache_expiry};
     my $public = $fields->{public};
 
-    my $dbh = C4::Context->dbh();
     $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
-    my $query = "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,report_area,report_group,report_subgroup,type,notes,cache_expiry,public)  VALUES (?,now(),now(),?,?,?,?,?,?,?,?,?)";
-    $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
+    my $now = dt_from_string;
+    my $report = Koha::Report->new(
+        {
+            borrowernumber  => $borrowernumber,
+            date_created    => $now, # Must be moved to Koha::Report->store
+            last_modified   => $now, # Must be moved to Koha::Report->store
+            savedsql        => $sql,
+            report_name     => $name,
+            report_area     => $area,
+            report_group    => $group,
+            report_subgroup => $subgroup,
+            type            => $type,
+            notes           => $notes,
+            cache_expiry    => $cache_expiry,
+            public          => $public,
+        }
+    )->store;
 
-    my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
-                                   $borrowernumber, $name);
-    return $id;
+    return $report->id;
 }
 
 sub update_sql {
@@ -604,14 +653,22 @@ sub update_sql {
     my $cache_expiry = $fields->{cache_expiry};
     my $public = $fields->{public};
 
+    $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
+    my $report = Koha::Reports->find($id);
+    $report->last_modified(dt_from_string);
+    $report->savedsql($sql);
+    $report->report_name($name);
+    $report->notes($notes);
+    $report->report_group($group);
+    $report->report_subgroup($subgroup);
+    $report->cache_expiry($cache_expiry) if defined $cache_expiry;
+    $report->public($public);
+    $report->store();
     if( $cache_expiry >= 2592000 ){
-      die "Please specify a cache expiry less than 30 days\n";
+      die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh
     }
 
-    my $dbh        = C4::Context->dbh();
-    $sql =~ s/(\s*\;\s*)$//;    # removes trailing whitespace and /;/
-    my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
-    $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
+    return $report;
 }
 
 sub store_results {
@@ -871,6 +928,7 @@ Returns a hash containig all reserved words
 sub GetReservedAuthorisedValues {
     my %reserved_authorised_values =
             map { $_ => 1 } ( 'date',
+                              'list',
                               'branches',
                               'itemtypes',
                               'cn_source',
@@ -919,6 +977,7 @@ sub GetParametersFromSQL {
 
     for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
         my ($name,$authval) = split(/\|/,$split[$i*2+1]);
+        $authval =~ s/\:all$// if $authval;
         push @sql_parameters, { 'name' => $name, 'authval' => $authval };
     }
 
@@ -964,7 +1023,7 @@ sub EmailReport {
     my $params     = shift;
     my $report_id  = $params->{report_id};
     my $from       = $params->{from};
-    my $email      = $params->{email};
+    my $email_col  = $params->{email} || 'email';
     my $module     = $params->{module};
     my $code       = $params->{code};
     my $branch     = $params->{branch} || "";
@@ -997,19 +1056,19 @@ sub EmailReport {
         my $email;
         my $err_count = scalar @errors;
         push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
-        push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( (defined $email && defined $row->{$email}) || defined $row->{email} );
+        push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} );
         push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
         push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
 
         my $from_address = $from || $row->{from};
-        my $to_address = $email ? $row->{$email} : $row->{email};
+        my $to_address = $row->{$email_col};
         push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
         $counter++;
         next if scalar @errors > $err_count; #If any problems, try next
 
         $letter->{content}       = $content;
         $email->{borrowernumber} = $row->{borrowernumber};
-        $email->{letter}         = $letter;
+        $email->{letter}         = { %$letter };
         $email->{from_address}   = $from_address;
         $email->{to_address}     = $to_address;