Bug 40275: Introduce `Koha::Patrons->find_by_identifier()`

In our codebase, there's a pattern we tend to use for searching patrons
by userid and falling back to find them by cardnumber:

* C4::Auth
* C4::SIP::ILS::Patron
* (slightly different) Koha::REST::V1::Auth::Password
* (slightly different) Koha::REST::V1::Auth
* C4::Circulation
* C4::Auth_with_cas

It generally uses the following pattern:

```perl
my $patron = Koha::Patrons->find( { userid => $identifier } );
$patron //= Koha::Patrons->find( { cardnumber => $identifier } );
```

The problem with this is that `find` actually produces a DBIX::Class
warn because `find` is being called without primary key parameters. I
haven't seen it in the wild, until the latest change in
`checkpw_internal` which made it throw warnings in SIP. My
interpretation is that SIP's special approach with the Trapper.pm class
made it show where other places just get it hidden.

That said, I implemented this using `search()` to overcome this.

To test:
1. Apply the patches
2. Run:
   $ ktd --shell
  k$ prove t/db_dependent/Koha/Patrons.t
=> SUCCESS: Tests pass!
3. Sign off :-D

Signed-off-by: David Nind <david@davidnind.com>

Signed-off-by: Kyle M Hall <kyle@bywatersolutions.com>
Signed-off-by: Martin Renvoize <martin.renvoize@openfifth.co.uk>
Signed-off-by: Lucas Gass <lucas@bywatersolutions.com>
(cherry picked from commit 3f19d4bf85)
Signed-off-by: Paul Derscheid <paul.derscheid@lmscloud.de>
This commit is contained in:
Tomas Cohen Arazi 2025-06-30 10:51:14 -03:00 committed by Paul Derscheid
parent 1d0ba36aec
commit 3e2551a956
No known key found for this signature in database
GPG Key ID: C25F9FD44CED595B
1 changed files with 26 additions and 1 deletions

View File

@ -37,10 +37,35 @@ Koha::Patron - Koha Patron Object class
=head1 API
=head2 Class Methods
=head2 Class methods
=cut
=head3 find_by_identifier
my $patron = Koha::Patrons->find_by_identifier($identifier);
Find a patron by either userid or cardnumber. Returns the first patron found
or undef if no patron matches the identifier.
This method searches first by userid, then by cardnumber if no match is found.
=cut
sub find_by_identifier {
my ( $self, $identifier ) = @_;
return unless defined $identifier && $identifier ne '';
# First try to find by userid
my $patron = $self->search( { userid => $identifier } )->next;
# If not found by userid, try cardnumber
$patron = $self->search( { cardnumber => $identifier } )->next unless $patron;
return $patron;
}
=head3 search_limited
my $patrons = Koha::Patrons->search_limit( $params, $attributes );