1 package Koha::Policy::Patrons::Cardnumber;
3 # Copyright 2023 Koha Development team
5 # This file is part of Koha.
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.
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.
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>.
25 use Koha::Result::Boolean;
29 Koha::Policy::Patrons::Cardnumber - module to deal with cardnumbers policy
40 return bless {}, shift;
45 my $is_valid = Koha::Policy::Patrons::Cardnumber->is_valid( $cardnumber, [$patron] );
47 Returns whether a cardnumber is valid of not for a given I<Koha::Patron> object.
52 my ( $class, $cardnumber, $patron ) = @_;
54 return Koha::Result::Boolean->new(0)->add_message( { message => "is_empty" } )
55 unless defined $cardnumber;
57 return Koha::Result::Boolean->new(0)->add_message( { message => "already_exists" } )
58 if Koha::Patrons->search(
60 cardnumber => $cardnumber,
61 ( $patron ? ( borrowernumber => { '!=' => $patron->borrowernumber } ) : () )
65 my ( $min_length, $max_length ) = $class->get_valid_length();
66 return Koha::Result::Boolean->new(0)->add_message( { message => "invalid_length" } )
67 if length $cardnumber > $max_length
68 or length $cardnumber < $min_length;
70 return Koha::Result::Boolean->new(1);
73 =head2 get_valid_length
75 my ($min, $max) = Koha::Policy::Patrons::Cardnumber::get_valid_length();
77 Returns the minimum and maximum length for patron cardnumbers as
78 determined by the CardnumberLength system preference, the
79 BorrowerMandatoryField system preference, and the width of the
84 sub get_valid_length {
86 my $borrower = Koha::Database->new->schema->resultset('Borrower');
87 my $field_size = $borrower->result_source->column_info('cardnumber')->{size};
88 my ( $min, $max ) = ( 0, $field_size ); # borrowers.cardnumber is a nullable varchar(20)
89 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
90 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
92 # Is integer and length match
93 if ( $cardnumber_length =~ m|^\d+$| ) {
94 $min = $max = $cardnumber_length
95 if $cardnumber_length >= $min
96 and $cardnumber_length <= $max;
99 # Else assuming it is a range
100 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
101 $min = $1 if $1 and $min < $1;
102 $max = $2 if $2 and $max > $2;
106 $min = $max if $min > $max;
107 return ( $min, $max );