From ad3f6603cceb6fa2cfb55d1073c18fb7b1d34e33 Mon Sep 17 00:00:00 2001 From: Marcel de Rooy Date: Thu, 15 Feb 2018 12:00:30 +0100 Subject: [PATCH] Bug 20206: Add leading zeroes in GetItemnumberFromBarcode Content-Type: text/plain; charset=utf-8 --- C4/Items.pm | 19 ++++++++++++++----- t/db_dependent/Items.t | 22 +++++++++++++++++++++- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/C4/Items.pm b/C4/Items.pm index a7154be..54046f4 100644 --- a/C4/Items.pm +++ b/C4/Items.pm @@ -1365,11 +1365,20 @@ sub GetItemnumberFromBarcode { my ($barcode) = @_; my $dbh = C4::Context->dbh; - my $rq = - $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?"); - $rq->execute($barcode); - my ($result) = $rq->fetchrow; - return ($result); + my @result = $dbh->selectrow_array( + "SELECT itemnumber FROM items WHERE items.barcode=?", undef, $barcode, + ); + if( !@result && $barcode !~ /^0/ ) { + # Bit arbitrary: try one, two or three leading zeroes + # But RLIKE ^0+[barcode] is seriously slower + my @barcodes = map { ( '0' x $_ ). $barcode } 1..3; + @result = $dbh->selectrow_array( + "SELECT itemnumber FROM items WHERE items.barcode IN (?,?,?)", + undef, + @barcodes, + ); + } + return @result ? $result[0] : undef; } =head2 GetBarcodeFromItemnumber diff --git a/t/db_dependent/Items.t b/t/db_dependent/Items.t index 8c85959..496395c 100755 --- a/t/db_dependent/Items.t +++ b/t/db_dependent/Items.t @@ -30,7 +30,7 @@ use t::lib::TestBuilder; use Koha::MarcSubfieldStructures; use Koha::Caches; -use Test::More tests => 12; +use Test::More tests => 13; use Test::Warn; @@ -758,6 +758,26 @@ subtest 'get_hostitemnumbers_of' => sub { is( @itemnumbers, 0, ); }; +subtest 'GetItemnumberFromBarcode' => sub { + plan tests => 4; + + $schema->storage->txn_begin; + my $barcode = '20180215000'; + my $builder = t::lib::TestBuilder->new; + my $item1 = $builder->build({ source => 'Item', value => { barcode => $barcode }}); + is( GetItemnumberFromBarcode( $barcode ), $item1->{itemnumber}, + 'Barcode without leading zeroes found' ); + ModItem( { barcode => "00$barcode" }, undef, $item1->{itemnumber} ); + is( GetItemnumberFromBarcode( $barcode ), $item1->{itemnumber}, + 'Barcode found by prefixing parameter' ); + is( GetItemnumberFromBarcode( "0$barcode" ), undef, + 'Barcode with one leading zero not found' ); + is( GetItemnumberFromBarcode( "00$barcode" ), $item1->{itemnumber}, + 'Barcode with two leading zeroes found' ); + + $schema->storage->txn_rollback; +}; + # Helper method to set up a Biblio. sub get_biblio { my ( $frameworkcode ) = @_; -- 2.1.4