Bug 32843: Fix cataloguing/value_builder/unimarc_field_124a.pl
[koha-ffzg.git] / reports / borrowers_stats.pl
index 342dad4..4e0f645 100755 (executable)
 
 use Modern::Perl;
 use CGI qw ( -utf8 );
-use List::MoreUtils qw/uniq/;
 
-use C4::Auth;
+use C4::Auth qw( get_template_and_user );
 use C4::Context;
-use C4::Branch; # GetBranches
-use C4::Koha;
-use Koha::DateUtils;
-use C4::Acquisition;
-use C4::Output;
-use C4::Reports;
-use C4::Circulation;
-use C4::Members::AttributeTypes;
+use C4::Koha qw( GetAuthorisedValues );
+use C4::Output qw( output_html_with_http_headers );
+use C4::Reports qw( GetDelimiterChoices );
 
+use Koha::AuthorisedValues;
+use Koha::Libraries;
+use Koha::Patron::Attribute::Types;
 use Koha::Patron::Categories;
 
-use Date::Calc qw(
-  Today
-  Add_Delta_YM
-  );
+use Date::Calc qw( Add_Delta_YM Today );
 
 =head1 NAME
 
@@ -47,35 +41,25 @@ plugin that shows a stats on borrowers
 
 =cut
 
-my $input = new CGI;
+my $input = CGI->new;
 my $do_it=$input->param('do_it');
 my $fullreportname = "reports/borrowers_stats.tt";
 my $line = $input->param("Line");
 my $column = $input->param("Column");
 my @filters = $input->multi_param("Filter");
-$filters[3] = eval { output_pref( { dt => dt_from_string( $filters[3]), dateonly => 1, dateformat => 'iso' } ); }
-    if ( $filters[3] );
-$filters[4] = eval { output_pref ({ dt => dt_from_string( $filters[4]), dateonly => 1, dateformat => 'iso' } ); }
-    if ( $filters[4] );
 my $digits = $input->param("digits");
 our $period = $input->param("period");
 my $borstat = $input->param("status");
 my $borstat1 = $input->param("activity");
 my $output = $input->param("output");
 my $basename = $input->param("basename");
-our $sep     = $input->param("sep");
-$sep = "\t" if ($sep and $sep eq 'tabulation');
-my $selected_branch; # = $input->param("?");
-
-our $branches = GetBranches;
+our $sep     = C4::Context->csv_delimiter(scalar $input->param("sep"));
 
 my ($template, $borrowernumber, $cookie)
        = get_template_and_user({template_name => $fullreportname,
                                query => $input,
                                type => "intranet",
-                               authnotrequired => 0,
                                flagsrequired => {reports => '*'},
-                               debug => 1,
                                });
 $template->param(do_it => $do_it);
 if ($do_it) {
@@ -121,13 +105,6 @@ if ($do_it) {
        my $req;
     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']});
     $template->param( patron_categories => $patron_categories );
-       my @branchloop;
-       foreach (sort {$branches->{$a}->{branchname} cmp $branches->{$b}->{branchname}} keys %$branches) {
-               my $line = {branchcode => $_, branchname => $branches->{$_}->{branchname} || 'UNKNOWN'};
-               $line->{selected} = 'selected' if ($selected_branch and $selected_branch eq $_);
-               push @branchloop, $line;
-       }
-       $template->param(BRANCH_LOOP => \@branchloop);
        $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode");
        $req->execute;
        $template->param(   ZIP_LOOP => $req->fetchall_arrayref({}));
@@ -135,7 +112,7 @@ if ($do_it) {
        $req->execute;
        $template->param( SORT1_LOOP => $req->fetchall_arrayref({}));
        $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200");
-               # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destory DB performance.
+    # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destroy DB performance.
        $req->execute;
        $template->param( SORT2_LOOP => $req->fetchall_arrayref({}));
        
@@ -146,7 +123,6 @@ if ($do_it) {
                CGIsepChoice => $CGIsepChoice,
     );
     if (C4::Context->preference('ExtendedPatronAttributes')) {
-        $template->param(ExtendedPatronAttributes => 1);
         patron_attributes_form($template);
     }
 }
@@ -167,22 +143,21 @@ sub calculate {
 
     # check parameters
     my @valid_names = qw(categorycode zipcode branchcode sex sort1 sort2);
-    my @attribute_types = C4::Members::AttributeTypes::GetAttributeTypes;
     if ($line =~ /^patron_attr\.(.*)/) {
         my $attribute_type = $1;
-        return unless (grep {$attribute_type eq $_->{code}} @attribute_types);
+        return unless Koha::Patron::Attribute::Types->find($attribute_type);
     } else {
-        return unless (grep /^$line$/, @valid_names);
+        return unless (grep { $_ eq $line } @valid_names);
     }
     if ($column =~ /^patron_attr\.(.*)/) {
         my $attribute_type = $1;
-        return unless (grep {$attribute_type eq $_->{code}} @attribute_types);
+        return unless Koha::Patron::Attribute::Types->find($attribute_type);
     } else {
-        return unless (grep /^$column$/, @valid_names);
+        return unless (grep { $_ eq $column } @valid_names);
     }
     return if ($digits and $digits !~ /^\d+$/);
-    return if ($status and (grep /^$status$/, qw(debarred gonenoaddress lost)) == 0);
-    return if ($activity and (grep /^$activity$/, qw(active nonactive)) == 0);
+    return if ($status and (grep { $_ eq $status } qw(debarred gonenoaddress lost)) == 0);
+    return if ($activity and (grep { $_ eq $activity } qw(active nonactive)) == 0);
 
     # Filters
     my $linefilter;
@@ -209,13 +184,6 @@ sub calculate {
     foreach my $i (0 .. scalar @$filters) {
         my %cell;
         if ( @$filters[$i] ) {
-            if ($i == 3 or $i == 4) {
-                $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
-                    if ( @$filters[$i] );
-            } else {
-                $cell{filter} = @$filters[$i];
-            }
-
             if    ( $i == 0)  { $cell{crit} = "Cat code"; }
             elsif ( $i == 1 ) { $cell{crit} = "ZIP/Postal code"; }
             elsif ( $i == 2 ) { $cell{crit} = "Branch code"; }
@@ -238,10 +206,9 @@ sub calculate {
         }
     }
 
+    my @branchcodes = Koha::Libraries->search->get_column('branchcode');
        ($status  ) and push @loopfilter,{crit=>"Status",  filter=>$status  };
        ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity};
-       push @loopfilter,{debug=>1, crit=>"Branches",filter=>join(" ", sort keys %$branches)};
-       push @loopfilter,{debug=>1, crit=>"(line, column)", filter=>"($line,$column)"};
 # year of activity
        my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
        my $newperioddate=$period_year."-".$period_month."-".$period_day;
@@ -260,7 +227,6 @@ sub calculate {
         $linefield = $line;
     }
     my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']});
-    push @loopfilter, {debug=>1, crit=>"\%cathash", filter=>join(", ", map { $_->categorycode . ' (' . ( $_->description || 'NO_DESCRIPTION' ) . ')'} $patron_categories->as_list )};
 
     my $strsth;
     my @strparams; # bind parameters for the query
@@ -281,7 +247,6 @@ sub calculate {
        $strsth .= " AND $status='1' " if ($status);
     $strsth .=" order by $linefield";
        
-       push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth};
        my $sth = $dbh->prepare($strsth);
     $sth->execute(@strparams);
        while (my ($celvalue) = $sth->fetchrow) {
@@ -328,7 +293,6 @@ sub calculate {
        $strsth2 .= " AND $status='1' " if ($status);
 
     $strsth2 .= " order by $colfield";
-       push @loopfilter, {sql=>1, crit=>"Query", filter=>$strsth2};
        my $sth2 = $dbh->prepare($strsth2);
     $sth2->execute(@strparams2);
        while (my ($celvalue) = $sth2->fetchrow) {
@@ -409,8 +373,8 @@ sub calculate {
             $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' ";
         }
     }
-       $strcalc .= " AND borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
-       $strcalc .= " AND borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'nonactive');
+    $strcalc .= " AND borrowers.borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
+    $strcalc .= " AND borrowers.borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "' AND borrowernumber IS NOT NULL)" if ($activity eq 'nonactive');
        $strcalc .= " AND $status='1' " if ($status);
 
     $strcalc .= " GROUP BY ";
@@ -425,7 +389,6 @@ sub calculate {
         $strcalc .= " $colfield ";
     }
 
-       push @loopfilter, {sql=>1, crit=>"Query", filter=>$strcalc};
        my $dbcalc = $dbh->prepare($strcalc);
        (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute();
        
@@ -511,11 +474,12 @@ sub parse_extended_patron_attributes {
 sub patron_attributes_form {
     my $template = shift;
 
-    my @types = C4::Members::AttributeTypes::GetAttributeTypes();
+    my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
+    my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
 
     my %items_by_class;
-    foreach my $type (@types) {
-        my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
+    while ( my $attr_type = $attribute_types->next ) {
+        # TODO The following can be simplified easily
         my $entry = {
             class             => $attr_type->class(),
             code              => $attr_type->code(),
@@ -537,7 +501,8 @@ sub patron_attributes_form {
 
     my @attribute_loop;
     foreach my $class ( sort keys %items_by_class ) {
-        my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
+        my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
+        my $lib = $av->count ? $av->next->lib : $class;
         push @attribute_loop, {
             class => $class,
             items => $items_by_class{$class},