Bug 6448 [2/3] Barcodes::EAN13 autoBarcode
[koha.git] / cataloguing / value_builder / barcode.pl
index c05ec48..0ec6b62 100755 (executable)
@@ -24,6 +24,8 @@ no warnings 'redefine'; # otherwise loading up multiple plugins fills the log wi
 use C4::Context;
 require C4::Dates;
 
+use Algorithm::CheckDigits;
+
 my $DEBUG = 0;
 
 =head1
@@ -102,7 +104,7 @@ sub plugin_javascript {
         $year = substr($year, -2);
         $query = "SELECT MAX(CAST(SUBSTRING(barcode,-4) AS signed)) AS number FROM items WHERE barcode REGEXP ?";
         my $sth = $dbh->prepare($query);
-        $sth->execute("^[a-zA-Z]{1,}$year");
+        $sth->execute("^[-a-zA-Z]{1,}$year");
         while (my ($count)= $sth->fetchrow_array) {
             $nextnum = $count if $count;
             $nextnum = 0 if $nextnum == 9999; # this sequence only allows for cataloging 10000 books per month
@@ -123,6 +125,27 @@ sub plugin_javascript {
         }
         ";
     }
+    elsif ($autoBarcodeType eq 'EAN13') {
+        # not the best, two catalogers could add the same barcode easily this way :/
+        $query = "select max(abs(barcode)) from items";
+        my $sth = $dbh->prepare($query);
+        $sth->execute();
+        while (my ($last)= $sth->fetchrow_array) {
+            $nextnum = $last;
+        }
+        my $ean = CheckDigits('ean');
+        if ( $ean->is_valid($nextnum) ) {
+            my $next = $ean->basenumber( $nextnum ) + 1;
+            $nextnum = $ean->complete( $next );
+            $nextnum = '0' x ( 13 - length($nextnum) ) . $nextnum; # pad zeros
+        } else {
+            warn "ERROR: invalid EAN-13 $nextnum, using increment";
+            $nextnum++;
+        }
+    }
+    else {
+        warn "ERROR: unknown autoBarcode: $autoBarcodeType";
+    }
 
     # default js body (if not filled by hbyymmincr)
     $scr or $scr = <<END_OF_JS;