Bug 32030: Max document file size - client-side validation
[koha-ffzg.git] / Koha / Patrons.pm
index f02dfad..24e3d9d 100644 (file)
@@ -5,32 +5,29 @@ package Koha::Patrons;
 #
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 3 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along
-# with Koha; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 use Modern::Perl;
 
-use Carp;
 
 use Koha::Database;
-use Koha::DateUtils;
+use Koha::DateUtils qw( dt_from_string );
 
 use Koha::ArticleRequests;
-use Koha::ArticleRequest::Status;
 use Koha::Patron;
 use Koha::Exceptions::Patron;
 use Koha::Patron::Categories;
-use Date::Calc qw( Today Add_Delta_YMD );
 
 use base qw(Koha::Objects);
 
@@ -161,48 +158,9 @@ sub search_patrons_to_anonymise {
     return Koha::Patrons->_new_from_dbic($rs);
 }
 
-=head3 anonymise_issue_history
-
-    Koha::Patrons->search->anonymise_issue_history( { [ before => $older_than_date ] } );
-
-Anonymise issue history (old_issues) for all patrons older than the given date (optional).
-To make sure all the conditions are met, the caller has the responsibility to
-call search_patrons_to_anonymise to filter the Koha::Patrons set
-
-=cut
-
-sub anonymise_issue_history {
-    my ( $self, $params ) = @_;
-
-    my $older_than_date = $params->{before};
-
-    $older_than_date = dt_from_string $older_than_date if $older_than_date;
-
-    # The default of 0 does not work due to foreign key constraints
-    # The anonymisation should not fail quietly if AnonymousPatron is not a valid entry
-    # Set it to undef (NULL)
-    my $dtf = Koha::Database->new->schema->storage->datetime_parser;
-    my $nb_rows = 0;
-    while ( my $patron = $self->next ) {
-        my $old_issues_to_anonymise = $patron->old_checkouts->search(
-        {
-            (
-                $older_than_date
-                ? ( returndate =>
-                      { '<' => $dtf->format_datetime($older_than_date) } )
-                : ()
-            )
-        }
-        );
-        my $anonymous_patron = C4::Context->preference('AnonymousPatron') || undef;
-        $nb_rows += $old_issues_to_anonymise->update( { 'old_issues.borrowernumber' => $anonymous_patron } );
-    }
-    return $nb_rows;
-}
-
 =head3 delete
 
-    Koha::Patrons->search({ some filters here })->delete({ move => 1, verbose => 1 });
+    Koha::Patrons->search({ some filters here })->delete({ move => 1 });
 
     Delete passed set of patron objects.
     Wrapper for Koha::Patron->delete. (We do not want to bypass Koha::Patron
@@ -220,16 +178,39 @@ sub delete {
     $self->_resultset->result_source->schema->txn_do( sub {
         my ( $set, $params ) = @_;
         my $count = $set->count;
-        while( my $patron = $set->next ) {
+        while ( my $patron = $set->next ) {
+
+            next unless $patron->in_storage;
+
             $patron->move_to_deleted if $params->{move};
-            $patron->delete == 1 || Koha::Exceptions::Patron::FailedDelete->throw;
+            $patron->delete;
+
             $patrons_deleted++;
         }
-        warn "Deleted $count patrons\n" if $params->{verbose};
     }, $self, $params );
     return $patrons_deleted;
 }
 
+=head3 filter_by_expiration_date
+
+    Koha::Patrons->filter_by_expiration_date{{ days => $x });
+
+    Returns set of Koha patron objects expired $x days.
+
+=cut
+
+sub filter_by_expiration_date {
+    my ( $class, $params ) = @_;
+
+    return $class->filter_by_last_update(
+        {
+            timestamp_column_name => 'dateexpiry',
+            days                  => $params->{days} || 0,
+            days_inclusive        => 1,
+        }
+    );
+}
+
 =head3 search_unsubscribed
 
     Koha::Patrons->search_unsubscribed;
@@ -287,7 +268,7 @@ sub search_anonymize_candidates {
     $cond->{dateexpiry} = { '<=' => $str };
     $cond->{anonymized} = 0; # not yet done
     if( $params->{locked} ) {
-        my $fails = C4::Context->preference('FailedLoginAttempts');
+        my $fails = C4::Context->preference('FailedLoginAttempts') || 0;
         $cond->{login_attempts} = [ -and => { '!=' => undef }, { -not_in => [0, 1..$fails-1 ] } ]; # -not_in does not like undef
     }
     return $class->search( $cond );
@@ -322,10 +303,9 @@ sub search_anonymized {
 
 =head3 lock
 
-    Koha::Patrons->search({ some filters })->lock({ expire => 1, remove => 1, verbose => 1 })
+    Koha::Patrons->search({ some filters })->lock({ expire => 1, remove => 1 })
 
     Lock the passed set of patron objects. Optionally expire and remove holds.
-    Optional verbose flag is used in cron job.
     Wrapper around Koha::Patron->lock.
 
 =cut
@@ -336,123 +316,255 @@ sub lock {
     while( my $patron = $self->next ) {
         $patron->lock($params);
     }
-    if( $params->{verbose} ) {
-        warn "Locked $count patrons\n";
-    }
 }
 
 =head3 anonymize
 
-    Koha::Patrons->search({ some filters })->anonymize({ verbose => 1 });
+    Koha::Patrons->search({ some filters })->anonymize();
 
     Anonymize passed set of patron objects.
-    Optional verbose flag is used in cron job.
     Wrapper around Koha::Patron->anonymize.
 
 =cut
 
 sub anonymize {
-    my ( $self, $params ) = @_;
+    my ( $self ) = @_;
     my $count = $self->count;
     while( my $patron = $self->next ) {
         $patron->anonymize;
     }
-    if( $params->{verbose} ) {
-        warn "Anonymized $count patrons\n";
-    }
+}
 
-=head3 search_patrons_to_update
+=head3 search_patrons_to_update_category
 
-    my $patrons = Koha::Patrons->search_patrons_to_anonymise( {
-                      from => $from_category,
-                      fine_max => $fine_max,
-                      fine_min  => $fin_min,
-                      au     => $au,
-                      ao    => $ao,
+    my $patrons = Koha::Patrons->search_patrons_to_update_category( {
+                      from          => $from_category,
+                      fine_max      => $fine_max,
+                      fine_min      => $fin_min,
+                      too_young     => $too_young,
+                      too_old      => $too_old,
                   });
 
-This method returns all patron who should be updated form one category to another meeting criteria:
+This method returns all patron who should be updated from one category to another meeting criteria:
 
-from - original category
-fine_min - with fines totaling at least this amount
-fine_max - with fines above this amount
-au - under the age limit for 'from'
-ao - over the agelimit for 'from'
+from          - borrower categorycode
+fine_min      - with fines totaling at least this amount
+fine_max      - with fines above this amount
+too_young     - if passed, select patrons who are under the age limit for the current category
+too_old       - if passed, select patrons who are over the age limit for the current category
 
 =cut
 
-sub search_patrons_to_update {
+sub search_patrons_to_update_category {
     my ( $self, $params ) = @_;
     my %query;
-    my $search_params = $params->{search_params};;
+    my $search_params;
 
     my $cat_from = Koha::Patron::Categories->find($params->{from});
     $search_params->{categorycode}=$params->{from};
-    if ($params->{ageover} || $params->{ageunder}){
-        if( $cat_from->dateofbirthrequired && $params->{ageunder} ) {
-            my $date_after = output_pref({
-                dt         => dt_from_string()->subtract( years => $cat_from->dateofbirthrequired),
-                dateonly   => 1,
-                dateformat => 'sql'
-            });
-            $search_params->{dateofbirth}{'>'} = $date_after;
+    if ($params->{too_young} || $params->{too_old}){
+        my $dtf = Koha::Database->new->schema->storage->datetime_parser;
+        if( $cat_from->dateofbirthrequired && $params->{too_young} ) {
+            my $date_after = dt_from_string()->subtract( years => $cat_from->dateofbirthrequired);
+            $search_params->{dateofbirth}{'>'} = $dtf->format_datetime( $date_after );
         }
-        if( $cat_from->upperagelimit && $params->{ageover} ) {
-            my $date_before = output_pref({
-                dt         => dt_from_string()->subtract( years => $cat_from->upperagelimit),
-                dateonly   => 1,
-                dateformat => 'sql'
-            });
-            $search_params->{dateofbirth}{'<'} = $date_before;
+        if( $cat_from->upperagelimit && $params->{too_old} ) {
+            my $date_before = dt_from_string()->subtract( years => $cat_from->upperagelimit);
+            $search_params->{dateofbirth}{'<'} = $dtf->format_datetime( $date_before );
         }
     }
     if ($params->{fine_min} || $params->{fine_max}) {
         $query{join} = ["accountlines"];
-        $query{select} = ["borrowernumber", { sum => 'amountoutstanding', -as => 'total_fines'} ];
-        $query{as} = [qw/borrowernumber  total_fines/];
+        $query{columns} = ["borrowernumber"];
         $query{group_by} = ["borrowernumber"];
-        $query{having}{total_fines}{'<='}=$params->{fine_max} if defined $params->{fine_max};
-        $query{having}{total_fines}{'>='}=$params->{fine_min} if defined $params->{fine_min};
+        $query{having} = \['COALESCE(sum(accountlines.amountoutstanding),0) <= ?',$params->{fine_max}] if defined $params->{fine_max};
+        $query{having} = \['COALESCE(sum(accountlines.amountoutstanding),0) >= ?',$params->{fine_min}] if defined $params->{fine_min};
     }
-    return Koha::Patrons->search($search_params,\%query);
+    return $self->search($search_params,\%query);
 }
 
-=head3 update_category
+=head3 update_category_to
 
-    Koha::Patrons->search->update_category( {
-            to   => $to,
+    Koha::Patrons->search->update_category_to( {
+            category   => $to_category,
         });
 
-Update supplied patrons from one category to another and take care of guarantor info.
+Update supplied patrons from current category to another and take care of guarantor info.
 To make sure all the conditions are met, the caller has the responsibility to
 call search_patrons_to_update to filter the Koha::Patrons set
 
 =cut
 
-sub update_category {
+sub update_category_to {
     my ( $self, $params ) = @_;
-    my $to = $params->{to};
-
-    my $to_cat = Koha::Patron::Categories->find($to);
-    return unless $to_cat;
-
     my $counter = 0;
-    my $remove_guarantor = ( $to_cat->category_type ne 'C' || $to_cat->category_type ne 'P' ) ? 1 : 0;
     while( my $patron = $self->next ) {
         $counter++;
-        if ( $remove_guarantor && ($patron->category->category_type eq 'C' || $patron->category->category_type eq 'P') ) {
-            $patron->guarantorid(0);
-            $patron->contactname('');
-            $patron->contactfirstname('');
-            $patron->contacttitle('');
-            $patron->relationship('');
-        }
-        $patron->categorycode($to);
-        $patron->store();
+        $patron->categorycode($params->{category})->store();
     }
     return $counter;
 }
 
+=head3 filter_by_attribute_type
+
+my $patrons = Koha::Patrons->filter_by_attribute_type($attribute_type_code);
+
+Return a Koha::Patrons set with patrons having the attribute defined.
+
+=cut
+
+sub filter_by_attribute_type {
+    my ( $self, $attribute_type ) = @_;
+    my $rs = Koha::Patron::Attributes->search( { code => $attribute_type } )
+      ->_resultset()->search_related('borrowernumber');
+    return Koha::Patrons->_new_from_dbic($rs);
+}
+
+=head3 filter_by_attribute_value
+
+my $patrons = Koha::Patrons->filter_by_attribute_value($attribute_value);
+
+Return a Koha::Patrons set with patrong having the attribute value passed in parameter.
+
+=cut
+
+sub filter_by_attribute_value {
+    my ( $self, $attribute_value ) = @_;
+    my $rs = Koha::Patron::Attributes->search(
+        {
+            'borrower_attribute_types.staff_searchable' => 1,
+            attribute => { like => "%$attribute_value%" }
+        },
+        { join => 'borrower_attribute_types' }
+    )->_resultset()->search_related('borrowernumber');
+    return Koha::Patrons->_new_from_dbic($rs);
+}
+
+=head3 filter_by_amount_owed
+
+    Koha::Patrons->filter_by_amount_owed(
+        {
+            less_than  => '2.00',
+            more_than  => '0.50',
+            debit_type => $debit_type_code,
+            library    => $branchcode
+        }
+    );
+
+Returns patrons filtered by how much money they owe, between passed limits.
+
+Optionally limit to debts of a particular debit_type or/and owed to a particular library.
+
+=head4 arguments hashref
+
+=over 4
+
+=item less_than (optional)  - filter out patrons who owe less than Amount
+
+=item more_than (optional)  - filter out patrons who owe more than Amount
+
+=item debit_type (optional) - filter the amount owed by debit type
+
+=item library (optional)    - filter the amount owed to a particular branch
+
+=back
+
+=cut
+
+sub filter_by_amount_owed {
+    my ( $self, $options ) = @_;
+
+    return $self
+      unless (
+        defined($options)
+        && (   defined( $options->{less_than} )
+            || defined( $options->{more_than} ) )
+      );
+
+    my $where = {};
+    my $group_by =
+      [ map { 'me.' . $_ } $self->_resultset->result_source->columns ];
+
+    my $attrs = {
+        join     => 'accountlines',
+        group_by => $group_by,
+        '+select' =>
+          { sum => 'accountlines.amountoutstanding', '-as' => 'outstanding' },
+        '+as' => 'outstanding'
+    };
+
+    $where->{'accountlines.debit_type_code'} = $options->{debit_type}
+      if defined( $options->{debit_type} );
+
+    $where->{'accountlines.branchcode'} = $options->{library}
+      if defined( $options->{library} );
+
+    $attrs->{'having'} = [
+        { 'outstanding' => { '<' => $options->{less_than} } },
+        { 'outstanding' => undef }
+      ]
+      if ( defined( $options->{less_than} )
+        && !defined( $options->{more_than} ) );
+
+    $attrs->{'having'} = { 'outstanding' => { '>' => $options->{more_than} } }
+      if (!defined( $options->{less_than} )
+        && defined( $options->{more_than} ) );
+
+    $attrs->{'having'}->{'-and'} = [
+        { 'outstanding' => { '>' => $options->{more_than} } },
+        { 'outstanding' => { '<' => $options->{less_than} } }
+      ]
+      if ( defined( $options->{less_than} )
+        && defined( $options->{more_than} ) );
+
+    return $self->search( $where, $attrs );
+}
+
+=head3 filter_by_have_permission
+
+    my $patrons = Koha::Patrons->search->filter_by_have_permission('suggestions.suggestions_manage');
+
+    my $patrons = Koha::Patrons->search->filter_by_have_permission('suggestions');
+
+Filter patrons who have a given subpermission or the whole permission.
+
+=cut
+
+sub filter_by_have_permission {
+    my ($self, $subpermission) = @_;
+
+    my ($p, $sp) = split '\.', $subpermission;
+
+    my $perm = Koha::Database->new()->schema()->resultset('Userflag')->find({flag => $p});
+
+    Koha::Exceptions::ObjectNotFound->throw( sprintf( "Permission %s not found", $p ) )
+      unless $perm;
+
+    my $bit = $perm->bit;
+
+    return $self->search(
+        {
+            -and => [
+                -or => [
+                    \"me.flags & (1 << $bit)",
+                    { 'me.flags' => 1 },
+                    (
+                        $sp
+                        ? {
+                            -and => [
+                                { 'user_permissions.module_bit' => $bit },
+                                { 'user_permissions.code'       => $sp }
+                            ]
+                          }
+                        : ()
+                    )
+                ]
+            ]
+        },
+        { prefetch => 'user_permissions' }
+    );
+}
+
 =head3 _type
 
 =cut