bug 7016 further followup: clarify return of GetItemnumbersForBiblio
[koha_gimpoz] / C4 / Serials.pm
index 03d2e5e..8aa6ebc 100644 (file)
@@ -1,6 +1,7 @@
-package C4::Serials;    #assumes C4/Serials.pm
+package C4::Serials;
 
 # Copyright 2000-2002 Katipo Communications
+# Parts Copyright 2010 Biblibre
 #
 # This file is part of Koha.
 #
@@ -13,17 +14,19 @@ package C4::Serials;    #assumes C4/Serials.pm
 # 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., 59 Temple Place,
-# Suite 330, Boston, MA  02111-1307 USA
+# 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.
 
 use strict;
-use C4::Dates qw(format_date);
+use warnings;
+use C4::Dates qw(format_date format_date_in_iso);
 use Date::Calc qw(:all);
 use POSIX qw(strftime);
 use C4::Suggestions;
 use C4::Koha;
 use C4::Biblio;
+use C4::Branch;
 use C4::Items;
 use C4::Search;
 use C4::Letters;
@@ -55,15 +58,14 @@ BEGIN {
       &reorder_members
       &check_routing &updateClaim &removeMissingIssue
       &CountIssues
+      HasItems
 
     );
 }
 
-=head2 GetSuppliersWithLateIssues
-
 =head1 NAME
 
-C4::Serials - Give functions for serializing.
+C4::Serials - Serials Module Functions
 
 =head1 SYNOPSIS
 
@@ -71,22 +73,20 @@ C4::Serials - Give functions for serializing.
 
 =head1 DESCRIPTION
 
-Give all XYZ functions
+Functions for handling subscriptions, claims routing etc.
+
 
-=head1 FUNCTIONS
+=head1 SUBROUTINES
 
-=over 4
+=head2 GetSuppliersWithLateIssues
 
-%supplierlist = &GetSuppliersWithLateIssues
+$supplierlist = GetSuppliersWithLateIssues()
 
 this function get all suppliers with late issues.
 
 return :
-the supplierlist into a hash. this hash containts id & name of the supplier
-Only valid suppliers are returned. Late subscriptions lacking a supplier are
-ignored.
-
-=back
+an array_ref of suppliers each entry is a hash_ref containing id and name
+the array is in name order
 
 =cut
 
@@ -94,37 +94,23 @@ sub GetSuppliersWithLateIssues {
     my $dbh   = C4::Context->dbh;
     my $query = qq|
         SELECT DISTINCT id, name
-        FROM            subscription 
-        LEFT JOIN       serial ON serial.subscriptionid=subscription.subscriptionid
-        LEFT JOIN       aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
-        WHERE           subscription.subscriptionid = serial.subscriptionid
-        AND             (planneddate < now() OR serial.STATUS = 3 OR serial.STATUS = 4)
-        ORDER BY name
-    |;
-    my $sth = $dbh->prepare($query);
-    $sth->execute;
-    my %supplierlist;
-    while ( my ( $id, $name ) = $sth->fetchrow ) {
-        next if !defined $id;
-        $supplierlist{$id} = $name;
-    }
-    return %supplierlist;
+    FROM            subscription
+    LEFT JOIN       serial ON serial.subscriptionid=subscription.subscriptionid
+    LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
+    WHERE id > 0 AND ((planneddate < now() AND serial.status=1) OR serial.STATUS = 3 OR serial.STATUS = 4) ORDER BY name|;
+    return $dbh->selectall_arrayref($query, { Slice => {} });
 }
 
 =head2 GetLateIssues
 
-=over 4
+@issuelist = GetLateIssues($supplierid)
 
-@issuelist = &GetLateIssues($supplierid)
-
-this function select late issues on database
+this function selects late issues from the database
 
 return :
-the issuelist into an table. Each line of this table containts a ref to a hash which it containts
+the issuelist as an array. Each element of this array contains a hashi_ref containing
 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
 
-=back
-
 =cut
 
 sub GetLateIssues {
@@ -139,10 +125,11 @@ sub GetLateIssues {
             LEFT JOIN  biblio ON biblio.biblionumber = subscription.biblionumber
             LEFT JOIN  aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
             WHERE      ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
-            AND        subscription.aqbooksellerid=$supplierid
+            AND        subscription.aqbooksellerid=?
             ORDER BY   title
         |;
         $sth = $dbh->prepare($query);
+        $sth->execute($supplierid);
     } else {
         my $query = qq|
             SELECT     name,title,planneddate,serialseq,serial.subscriptionid
@@ -154,34 +141,26 @@ sub GetLateIssues {
             ORDER BY   title
         |;
         $sth = $dbh->prepare($query);
+        $sth->execute;
     }
-    $sth->execute;
     my @issuelist;
     my $last_title;
     my $odd   = 0;
-    my $count = 0;
     while ( my $line = $sth->fetchrow_hashref ) {
         $odd++ unless $line->{title} eq $last_title;
         $line->{title} = "" if $line->{title} eq $last_title;
         $last_title = $line->{title} if ( $line->{title} );
         $line->{planneddate} = format_date( $line->{planneddate} );
-        $count++;
         push @issuelist, $line;
     }
-    return $count, @issuelist;
+    return @issuelist;
 }
 
 =head2 GetSubscriptionHistoryFromSubscriptionId
 
-=over 4
-
 $sth = GetSubscriptionHistoryFromSubscriptionId()
-this function just prepare the SQL request.
+this function prepares the SQL request and returns the statement handle
 After this function, don't forget to execute it by using $sth->execute($subscriptionid)
-return :
-$sth = $dbh->prepare($query).
-
-=back
 
 =cut
 
@@ -197,16 +176,12 @@ sub GetSubscriptionHistoryFromSubscriptionId() {
 
 =head2 GetSerialStatusFromSerialId
 
-=over 4
-
 $sth = GetSerialStatusFromSerialId();
-this function just prepare the SQL request.
+this function returns a statement handle
 After this function, don't forget to execute it by using $sth->execute($serialid)
 return :
 $sth = $dbh->prepare($query).
 
-=back
-
 =cut
 
 sub GetSerialStatusFromSerialId() {
@@ -221,16 +196,13 @@ sub GetSerialStatusFromSerialId() {
 
 =head2 GetSerialInformation
 
-=over 4
 
 $data = GetSerialInformation($serialid);
-returns a hash containing :
+returns a hash_ref containing :
   items : items marcrecord (can be an array)
   serial table field
   subscription table field
   + information about subscription expiration
-  
-=back
 
 =cut
 
@@ -289,12 +261,9 @@ sub GetSerialInformation {
 
 =head2 AddItem2Serial
 
-=over 4
-
-$data = AddItem2Serial($serialid,$itemnumber);
+$rows = AddItem2Serial($serialid,$itemnumber);
 Adds an itemnumber to Serial record
-
-=back
+returns the number of rows affected
 
 =cut
 
@@ -308,15 +277,11 @@ sub AddItem2Serial {
 
 =head2 UpdateClaimdateIssues
 
-=over 4
-
 UpdateClaimdateIssues($serialids,[$date]);
 
-Update Claimdate for issues in @$serialids list with date $date 
+Update Claimdate for issues in @$serialids list with date $date
 (Take Today if none)
 
-=back
-
 =cut
 
 sub UpdateClaimdateIssues {
@@ -324,25 +289,21 @@ sub UpdateClaimdateIssues {
     my $dbh = C4::Context->dbh;
     $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
     my $query = "
-        UPDATE serial SET claimdate=$date,status=7
-        WHERE  serialid in (" . join( ",", @$serialids ) . ")";
+        UPDATE serial SET claimdate = ?, status = 7
+        WHERE  serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
     my $rq = $dbh->prepare($query);
-    $rq->execute;
+    $rq->execute($date, @$serialids);
     return $rq->rows;
 }
 
 =head2 GetSubscription
 
-=over 4
-
 $subs = GetSubscription($subscriptionid)
-this function get the subscription which has $subscriptionid as id.
+this function returns the subscription which has $subscriptionid as id.
 return :
 a hashref. This hash containts
 subscription, subscriptionhistory, aqbudget.bookfundid, biblio.title
 
-=back
-
 =cut
 
 sub GetSubscription {
@@ -383,12 +344,8 @@ sub GetSubscription {
 
 =head2 GetFullSubscription
 
-=over 4
-
-   \@res = GetFullSubscription($subscriptionid)
-   this function read on serial table.
-
-=back
+   $array_ref = GetFullSubscription($subscriptionid)
+   this function reads the serial table.
 
 =cut
 
@@ -433,13 +390,9 @@ sub GetFullSubscription {
 
 =head2 PrepareSerialsData
 
-=over 4
-
-   \@res = PrepareSerialsData($serialinfomation)
+   $array_ref = PrepareSerialsData($serialinfomation)
    where serialinformation is a hashref array
 
-=back
-
 =cut
 
 sub PrepareSerialsData {
@@ -454,13 +407,17 @@ sub PrepareSerialsData {
     my $first;
     my $previousnote = "";
 
-    foreach my $subs (@$lines) {
-        $subs->{'publisheddate'} = (
-            $subs->{'publisheddate'}
-            ? format_date( $subs->{'publisheddate'} )
-            : "XXX"
-        );
-        $subs->{'planneddate'}                  = format_date( $subs->{'planneddate'} );
+    foreach my $subs (@{$lines}) {
+        for my $datefield ( qw(publisheddate planneddate) ) {
+            # handle both undef and undef returned as 0000-00-00
+            if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
+                $subs->{$datefield} = 'XXX';
+            }
+            else {
+                $subs->{$datefield} = format_date( $subs->{$datefield}  );
+            }
+        }
+        $subs->{'branchname'} = GetBranchName( $subs->{'branchcode'} );
         $subs->{ "status" . $subs->{'status'} } = 1;
         $subs->{"checked"}                      = $subs->{'status'} =~ /1|3|4|7/;
 
@@ -484,17 +441,16 @@ sub PrepareSerialsData {
     foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
         push @res, $tmpresults{$key};
     }
-    $res[0]->{'first'} = 1;
     return \@res;
 }
 
 =head2 GetSubscriptionsFromBiblionumber
 
-\@res = GetSubscriptionsFromBiblionumber($biblionumber)
-this function get the subscription list. it reads on subscription table.
+$array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
+this function get the subscription list. it reads the subscription table.
 return :
-table of subscription which has the biblionumber given on input arg.
-each line of this table is a hashref. All hashes containt
+reference to an array of subscriptions which have the biblionumber given on input arg.
+each element of this array is a hashref containing
 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
 
 =cut
@@ -550,12 +506,8 @@ sub GetSubscriptionsFromBiblionumber {
 
 =head2 GetFullSubscriptionsFromBiblionumber
 
-=over 4
-
-   \@res = GetFullSubscriptionsFromBiblionumber($biblionumber)
-   this function read on serial table.
-
-=back
+   $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
+   this function reads the serial table.
 
 =cut
 
@@ -599,15 +551,11 @@ sub GetFullSubscriptionsFromBiblionumber {
 
 =head2 GetSubscriptions
 
-=over 4
-
 @results = GetSubscriptions($title,$ISSN,$biblionumber);
-this function get all subscriptions which has title like $title,ISSN like $ISSN and biblionumber like $biblionumber.
+this function gets all subscriptions which have title like $title,ISSN like $ISSN and biblionumber like $biblionumber.
 return:
 a table of hashref. Each hash containt the subscription.
 
-=back
-
 =cut
 
 sub GetSubscriptions {
@@ -633,7 +581,7 @@ sub GetSubscriptions {
         my @sqlstrings;
         my @strings_to_search;
         @strings_to_search = map { "%$_%" } split( / /, $string );
-        foreach my $index qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes) {
+        foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
             push @bind_params, @strings_to_search;
             my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
             $debug && warn "$tmpstring";
@@ -646,7 +594,7 @@ sub GetSubscriptions {
         my @sqlstrings;
         my @strings_to_search;
         @strings_to_search = map { "%$_%" } split( / /, $issn );
-        foreach my $index qw(biblioitems.issn subscription.callnumber) {
+        foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
             push @bind_params, @strings_to_search;
             my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
             $debug && warn "$tmpstring";
@@ -660,15 +608,15 @@ sub GetSubscriptions {
     $sth = $dbh->prepare($sql);
     $sth->execute(@bind_params);
     my @results;
-    my $previoustitle = "";
+    my $previousbiblio = "";
     my $odd           = 1;
 
     while ( my $line = $sth->fetchrow_hashref ) {
-        if ( $previoustitle eq $line->{title} ) {
+        if ( $previousbiblio eq $line->{biblionumber} ) {
             $line->{title} = "";
             $line->{issn}  = "";
         } else {
-            $previoustitle = $line->{title};
+            $previousbiblio = $line->{biblionumber};
             $odd           = -$odd;
         }
         $line->{toggle} = 1 if $odd == 1;
@@ -686,17 +634,13 @@ sub GetSubscriptions {
 
 =head2 GetSerials
 
-=over 4
-
 ($totalissues,@serials) = GetSerials($subscriptionid);
-this function get every serial not arrived for a given subscription
+this function gets every serial not arrived for a given subscription
 as well as the number of issues registered in the database (all types)
 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
 
 FIXME: We should return \@serials.
 
-=back
-
 =cut
 
 sub GetSerials {
@@ -716,8 +660,13 @@ sub GetSerials {
 
     while ( my $line = $sth->fetchrow_hashref ) {
         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
-        $line->{"publisheddate"}              = format_date( $line->{"publisheddate"} );
-        $line->{"planneddate"}                = format_date( $line->{"planneddate"} );
+        for my $datefield ( qw( planneddate publisheddate) ) {
+            if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
+                $line->{$datefield} = format_date( $line->{$datefield});
+            } else {
+                $line->{$datefield} = q{};
+            }
+        }
         push @serials, $line;
     }
 
@@ -733,8 +682,14 @@ sub GetSerials {
     while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
         $counter++;
         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
-        $line->{"planneddate"}                = format_date( $line->{"planneddate"} );
-        $line->{"publisheddate"}              = format_date( $line->{"publisheddate"} );
+        for my $datefield ( qw( planneddate publisheddate) ) {
+            if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
+                $line->{$datefield} = format_date( $line->{$datefield});
+            } else {
+                $line->{$datefield} = q{};
+            }
+        }
+
         push @serials, $line;
     }
 
@@ -747,15 +702,11 @@ sub GetSerials {
 
 =head2 GetSerials2
 
-=over 4
-
-($totalissues,@serials) = GetSerials2($subscriptionid,$status);
-this function get every serial waited for a given subscription
+@serials = GetSerials2($subscriptionid,$status);
+this function returns every serial waited for a given subscription
 as well as the number of issues registered in the database (all types)
 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
 
-=back
-
 =cut
 
 sub GetSerials2 {
@@ -773,25 +724,27 @@ sub GetSerials2 {
     my @serials;
 
     while ( my $line = $sth->fetchrow_hashref ) {
-        $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
-        $line->{"planneddate"}                = format_date( $line->{"planneddate"} );
-        $line->{"publisheddate"}              = format_date( $line->{"publisheddate"} );
+        $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
+        # Format dates for display
+        for my $datefield ( qw( planneddate publisheddate ) ) {
+            if ($line->{$datefield} =~m/^00/) {
+                $line->{$datefield} = q{};
+            }
+            else {
+                $line->{$datefield} = format_date( $line->{$datefield} );
+            }
+        }
         push @serials, $line;
     }
-    my ($totalissues) = scalar(@serials);
-    return ( $totalissues, @serials );
+    return @serials;
 }
 
 =head2 GetLatestSerials
 
-=over 4
-
 \@serials = GetLatestSerials($subscriptionid,$limit)
 get the $limit's latest serials arrived or missing for a given subscription
 return :
-a ref to a table which it containts all of the latest serials stored into a hash.
-
-=back
+a ref to an array which contains all of the latest serials stored into a hash.
 
 =cut
 
@@ -815,25 +768,13 @@ sub GetLatestSerials {
         push @serials, $line;
     }
 
-    #     my $query = qq|
-    #         SELECT count(*)
-    #         FROM   serial
-    #         WHERE  subscriptionid=?
-    #     |;
-    #     $sth=$dbh->prepare($query);
-    #     $sth->execute($subscriptionid);
-    #     my ($totalissues) = $sth->fetchrow;
     return \@serials;
 }
 
 =head2 GetDistributedTo
 
-=over 4
-
 $distributedto=GetDistributedTo($subscriptionid)
-This function select the old previous value of distributedto in the database.
-
-=back
+This function returns the field distributedto for the subscription matching subscriptionid
 
 =cut
 
@@ -849,15 +790,11 @@ sub GetDistributedTo {
 
 =head2 GetNextSeq
 
-=over 4
-
 GetNextSeq($val)
 $val is a hashref containing all the attributes of the table 'subscription'
 This function get the next issue for the subscription given on input arg
 return:
-all the input params updated.
-
-=back
+a list containing all the input params updated.
 
 =cut
 
@@ -944,16 +881,12 @@ sub GetNextSeq {
 
 =head2 GetSeq
 
-=over 4
-
 $calculated = GetSeq($val)
 $val is a hashref containing all the attributes of the table 'subscription'
 this function transforms {X},{Y},{Z} to 150,0,0 for example.
 return:
 the sequence in integer format
 
-=back
-
 =cut
 
 sub GetSeq {
@@ -984,12 +917,12 @@ sub GetSeq {
 
 =head2 GetExpirationDate
 
-$sensddate = GetExpirationDate($subscriptionid)
+$enddate = GetExpirationDate($subscriptionid, [$startdate])
 
 this function return the next expiration date for a subscription given on input args.
 
 return
-the enddate
+the enddate or undef
 
 =cut
 
@@ -1032,14 +965,10 @@ sub GetExpirationDate {
 
 =head2 CountSubscriptionFromBiblionumber
 
-=over 4
-
 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
-this count the number of subscription for a biblionumber given.
+this returns a count of the subscriptions for a given biblionumber
 return :
-the number of subscriptions with biblionumber given on input arg.
-
-=back
+the number of subscriptions
 
 =cut
 
@@ -1055,13 +984,10 @@ sub CountSubscriptionFromBiblionumber {
 
 =head2 ModSubscriptionHistory
 
-=over 4
-
 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
 
-this function modify the history of a subscription. Put your new values on input arg.
-
-=back
+this function modifies the history of a subscription. Put your new values on input arg.
+returns the number of rows affected
 
 =cut
 
@@ -1082,15 +1008,11 @@ sub ModSubscriptionHistory {
 
 =head2 ModSerialStatus
 
-=over 4
-
 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
 
 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
 
-=back
-
 =cut
 
 sub ModSerialStatus {
@@ -1106,10 +1028,12 @@ sub ModSerialStatus {
 
     # change status & update subscriptionhistory
     my $val;
-    if ( $status eq 6 ) {
-        DelIssue( { 'serialid' => $serialid, 'subscriptionid' => $subscriptionid, 'serialseq' => $serialseq } );
-    } else {
-        my $query = "UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE  serialid = ?";
+    if ( $status == 6 ) {
+        DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
+    }
+    else {
+        my $query =
+'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE  serialid = ?';
         $sth = $dbh->prepare($query);
         $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
         $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
@@ -1121,7 +1045,7 @@ sub ModSerialStatus {
             $sth   = $dbh->prepare($query);
             $sth->execute($subscriptionid);
             my ( $missinglist, $recievedlist ) = $sth->fetchrow;
-            if ( $status eq 2 ) {
+            if ( $status == 2 ) {
 
                 $recievedlist .= "; $serialseq"
                   unless ( index( "$recievedlist", "$serialseq" ) >= 0 );
@@ -1129,10 +1053,10 @@ sub ModSerialStatus {
 
             #         warn "missinglist : $missinglist serialseq :$serialseq, ".index("$missinglist","$serialseq");
             $missinglist .= "; $serialseq"
-              if ( $status eq 4
+              if ( $status == 4
                 and not index( "$missinglist", "$serialseq" ) >= 0 );
-            $missinglist .= "; $serialseq"
-              if ( $status eq 5
+            $missinglist .= "; not issued $serialseq"
+              if ( $status == 5
                 and index( "$missinglist", "$serialseq" ) >= 0 );
             $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE  subscriptionid=?";
             $sth   = $dbh->prepare($query);
@@ -1143,20 +1067,19 @@ sub ModSerialStatus {
     }
 
     # create new waited entry if needed (ie : was a "waited" and has changed)
-    if ( $oldstatus eq 1 && $status ne 1 ) {
+    if ( $oldstatus == 1 && $status != 1 ) {
         my $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
         $sth = $dbh->prepare($query);
         $sth->execute($subscriptionid);
         my $val = $sth->fetchrow_hashref;
 
         # next issue number
-        #     warn "Next Seq";
-        my ( $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 ) = GetNextSeq($val);
-
-        #     warn "Next Seq End";
+        my (
+            $newserialseq,  $newlastvalue1, $newlastvalue2, $newlastvalue3,
+            $newinnerloop1, $newinnerloop2, $newinnerloop3
+        ) = GetNextSeq($val);
 
         # next date (calculated from actual date & frequency parameters)
-        #         warn "publisheddate :$publisheddate ";
         my $nextpublisheddate = GetNextDate( $publisheddate, $val );
         NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
         $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
@@ -1164,17 +1087,16 @@ sub ModSerialStatus {
         $sth = $dbh->prepare($query);
         $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
 
-        # check if an alert must be sent... (= a letter is defined & status became "arrived"
-        if ( $val->{letter} && $status eq 2 && $oldstatus ne 2 ) {
+# check if an alert must be sent... (= a letter is defined & status became "arrived"
+        if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
             SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
         }
     }
+    return;
 }
 
 =head2 GetNextExpected
 
-=over 4
-
 $nextexpected = GetNextExpected($subscriptionid)
 
 Get the planneddate for the current expected issue of the subscription.
@@ -1186,8 +1108,6 @@ $nextexepected = {
     planneddate => C4::Dates object
     }
 
-=back
-
 =cut
 
 sub GetNextExpected($) {
@@ -1197,21 +1117,23 @@ sub GetNextExpected($) {
 
     # Each subscription has only one 'expected' issue, with serial.status==1.
     $sth->execute( $subscriptionid, 1 );
-    my ($nextissue) = $sth->fetchrow_hashref;
-    if ( not $nextissue ) {
-        $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid  = ? ORDER BY planneddate DESC LIMIT 1');
-        $sth->execute($subscriptionid);
-        $nextissue = $sth->fetchrow_hashref;
+    my ( $nextissue ) = $sth->fetchrow_hashref;
+    if( !$nextissue){
+         $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid  = ? ORDER BY planneddate DESC LIMIT 1');
+         $sth->execute( $subscriptionid );  
+         $nextissue = $sth->fetchrow_hashref;       
+    }
+    if (!defined $nextissue->{planneddate}) {
+        # or should this default to 1st Jan ???
+        $nextissue->{planneddate} = strftime('%Y-%m-%d',localtime);
     }
-    $nextissue->{planneddate} = C4::Dates->new( $nextissue->{planneddate}, 'iso' );
+    $nextissue->{planneddate} = C4::Dates->new($nextissue->{planneddate},'iso');
     return $nextissue;
 
 }
 
 =head2 ModNextExpected
 
-=over 4
-
 ModNextExpected($subscriptionid,$date)
 
 Update the planneddate for the current expected issue of the subscription.
@@ -1219,7 +1141,7 @@ This will modify all future prediction results.
 
 C<$date> is a C4::Dates object.
 
-=back
+returns 0
 
 =cut
 
@@ -1238,11 +1160,8 @@ sub ModNextExpected($$) {
 
 =head2 ModSubscription
 
-=over 4
-
-this function modify a subscription. Put all new values on input args.
-
-=back
+this function modifies a subscription. Put all new values on input args.
+returns the number of rows affected
 
 =cut
 
@@ -1286,7 +1205,6 @@ sub ModSubscription {
         $graceperiod,   $location,        $enddate,           $subscriptionid
     );
     my $rows = $sth->rows;
-    $sth->finish;
 
     logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
     return $rows;
@@ -1294,8 +1212,6 @@ sub ModSubscription {
 
 =head2 NewSubscription
 
-=over 4
-
 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
     $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
     $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
@@ -1309,8 +1225,6 @@ Create a new subscription with value given on input args.
 return :
 the id of this new subscription
 
-=back
-
 =cut
 
 sub NewSubscription {
@@ -1346,8 +1260,18 @@ sub NewSubscription {
         $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,   $location,     $enddate
     );
 
-    #then create the 1st waited number
     my $subscriptionid = $dbh->{'mysql_insertid'};
+    unless ($enddate){
+       $enddate = GetExpirationDate($subscriptionid,$startdate);
+        $query = q|
+            UPDATE subscription
+            SET    enddate=?
+            WHERE  subscriptionid=?
+        |;
+        $sth = $dbh->prepare($query);
+        $sth->execute( $enddate, $subscriptionid );
+    }
+    #then create the 1st waited number
     $query = qq(
         INSERT INTO subscriptionhistory
             (biblionumber, subscriptionid, histstartdate,  opacnote, librariannote)
@@ -1393,14 +1317,10 @@ sub NewSubscription {
 
 =head2 ReNewSubscription
 
-=over 4
-
 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
 
 this function renew a subscription with values given on input args.
 
-=back
-
 =cut
 
 sub ReNewSubscription {
@@ -1456,18 +1376,16 @@ sub ReNewSubscription {
     $sth->execute( $enddate, $subscriptionid );
 
     logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
+    return;
 }
 
 =head2 NewIssue
 
-=over 4
-
 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate,  $notes)
 
 Create a new issue stored on the database.
 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
-
-=back
+returns the serial id
 
 =cut
 
@@ -1493,14 +1411,14 @@ sub NewIssue {
     $sth->execute($subscriptionid);
     my ( $missinglist, $recievedlist ) = $sth->fetchrow;
 
-    if ( $status eq 2 ) {
-        ### TODO Add a feature that improves recognition and description.
-        ### As such count (serialseq) i.e. : N18,2(N19),N20
-        ### Would use substr and index But be careful to previous presence of ()
-        $recievedlist .= "; $serialseq" unless ( index( $recievedlist, $serialseq ) > 0 );
+    if ( $status == 2 ) {
+      ### TODO Add a feature that improves recognition and description.
+      ### As such count (serialseq) i.e. : N18,2(N19),N20
+      ### Would use substr and index But be careful to previous presence of ()
+        $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
     }
-    if ( $status eq 4 ) {
-        $missinglist .= "; $serialseq" unless ( index( $missinglist, $serialseq ) > 0 );
+    if ( $status == 4 ) {
+        $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
     }
     $query = qq|
         UPDATE subscriptionhistory
@@ -1516,16 +1434,12 @@ sub NewIssue {
 
 =head2 ItemizeSerials
 
-=over 4
-
 ItemizeSerials($serialid, $info);
 $info is a hashref containing  barcode branch, itemcallnumber, status, location
 $serialid the serialid
 return :
 1 if the itemize is a succes.
-0 and @error else. @error containts the list of errors found.
-
-=back
+0 and @error otherwise. @error containts the list of errors found.
 
 =cut
 
@@ -1566,9 +1480,9 @@ sub ItemizeSerials {
     my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
     if ( $info->{barcode} ) {
         my @errors;
-        my $exists = itemdata( $info->{'barcode'} );
-        push @errors, "barcode_not_unique" if ($exists);
-        unless ($exists) {
+        if ( is_barcode_in_use( $info->{barcode} ) ) {
+            push @errors, 'barcode_not_unique';
+        } else {
             my $marcrecord = MARC::Record->new();
             my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
             my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
@@ -1651,8 +1565,6 @@ sub ItemizeSerials {
 
 =head2 HasSubscriptionStrictlyExpired
 
-=over 4
-
 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
 
 the subscription has stricly expired when today > the end subscription date 
@@ -1660,8 +1572,6 @@ the subscription has stricly expired when today > the end subscription date
 return :
 1 if true, 0 if false, -1 if the expiration date is not set.
 
-=back
-
 =cut
 
 sub HasSubscriptionStrictlyExpired {
@@ -1696,8 +1606,6 @@ sub HasSubscriptionStrictlyExpired {
 
 =head2 HasSubscriptionExpired
 
-=over 4
-
 $has_expired = HasSubscriptionExpired($subscriptionid)
 
 the subscription has expired when the next issue to arrive is out of subscription limit.
@@ -1707,8 +1615,6 @@ return :
 1 if the subscription has expired
 2 if has subscription does not have a valid expiration date set
 
-=back
-
 =cut
 
 sub HasSubscriptionExpired {
@@ -1716,7 +1622,10 @@ sub HasSubscriptionExpired {
     my $dbh              = C4::Context->dbh;
     my $subscription     = GetSubscription($subscriptionid);
     if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
-        my $expirationdate = $subscription->{enddate};
+        my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
+        if (!defined $expirationdate) {
+            $expirationdate = q{};
+        }
         my $query          = qq|
             SELECT max(planneddate)
             FROM   serial
@@ -1725,7 +1634,9 @@ sub HasSubscriptionExpired {
         my $sth = $dbh->prepare($query);
         $sth->execute($subscriptionid);
         my ($res) = $sth->fetchrow;
-        return 0 unless $res;
+        if (!$res || $res=~m/^0000/) {
+            return 0;
+        }
         my @res                   = split( /-/, $res );
         my @endofsubscriptiondate = split( /-/, $expirationdate );
         return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
@@ -1747,13 +1658,9 @@ sub HasSubscriptionExpired {
 
 =head2 SetDistributedto
 
-=over 4
-
 SetDistributedto($distributedto,$subscriptionid);
 This function update the value of distributedto for a subscription given on input arg.
 
-=back
-
 =cut
 
 sub SetDistributedto {
@@ -1766,16 +1673,13 @@ sub SetDistributedto {
     |;
     my $sth = $dbh->prepare($query);
     $sth->execute( $distributedto, $subscriptionid );
+    return;
 }
 
 =head2 DelSubscription
 
-=over 4
-
 DelSubscription($subscriptionid)
-this function delete the subscription which has $subscriptionid as id.
-
-=back
+this function deletes subscription which has $subscriptionid as id.
 
 =cut
 
@@ -1792,12 +1696,10 @@ sub DelSubscription {
 
 =head2 DelIssue
 
-=over 4
-
 DelIssue($serialseq,$subscriptionid)
-this function delete an issue which has $serialseq and $subscriptionid given on input arg.
+this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
 
-=back
+returns the number of rows affected
 
 =cut
 
@@ -1840,19 +1742,14 @@ sub DelIssue {
 
 =head2 GetLateOrMissingIssues
 
-=over 4
-
-($count,@issuelist) = &GetLateMissingIssues($supplierid,$serialid)
+@issuelist = GetLateMissingIssues($supplierid,$serialid)
 
-this function select missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
+this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
 
 return :
-a count of the number of missing issues
-the issuelist into a table. Each line of this table containts a ref to a hash which it containts
+the issuelist as an array of hash refs. Each element of this array contains 
 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
 
-=back
-
 =cut
 
 sub GetLateOrMissingIssues {
@@ -1873,7 +1770,8 @@ sub GetLateOrMissingIssues {
             "SELECT
                 serialid,      aqbooksellerid,        name,
                 biblio.title,  planneddate,           serialseq,
-                serial.status, serial.subscriptionid, claimdate
+                serial.status, serial.subscriptionid, claimdate,
+                subscription.branchcode
             FROM      serial 
                 LEFT JOIN subscription  ON serial.subscriptionid=subscription.subscriptionid 
                 LEFT JOIN biblio        ON subscription.biblionumber=biblio.biblionumber
@@ -1889,7 +1787,8 @@ sub GetLateOrMissingIssues {
             "SELECT 
             serialid,      aqbooksellerid,         name,
             biblio.title,  planneddate,           serialseq,
-            serial.status, serial.subscriptionid, claimdate
+                serial.status, serial.subscriptionid, claimdate,
+                subscription.branchcode
             FROM serial 
                 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid 
                 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
@@ -1902,26 +1801,22 @@ sub GetLateOrMissingIssues {
     }
     $sth->execute;
     my @issuelist;
-    my $last_title;
-    my $odd   = 0;
-    my $count = 0;
     while ( my $line = $sth->fetchrow_hashref ) {
-        $odd++ unless $line->{title} eq $last_title;
-        $last_title = $line->{title} if ( $line->{title} );
-        $line->{planneddate}                  = format_date( $line->{planneddate} );
-        $line->{claimdate}                    = format_date( $line->{claimdate} );
-        $line->{ "status" . $line->{status} } = 1;
-        $line->{'odd'} = 1 if $odd % 2;
-        $count++;
+
+        if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
+            $line->{planneddate} = format_date( $line->{planneddate} );
+        }
+        if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
+            $line->{claimdate}   = format_date( $line->{claimdate} );
+        }
+        $line->{"status".$line->{status}}   = 1;
         push @issuelist, $line;
     }
-    return $count, @issuelist;
+    return @issuelist;
 }
 
 =head2 removeMissingIssue
 
-=over 4
-
 removeMissingIssue($subscriptionid)
 
 this function removes an issue from being part of the missing string in 
@@ -1929,8 +1824,6 @@ subscriptionlist.missinglist column
 
 called when a missing issue is found from the serials-recieve.pl file
 
-=back
-
 =cut
 
 sub removeMissingIssue {
@@ -1957,20 +1850,17 @@ sub removeMissingIssue {
         );
         $sth2->execute( $missinglist, $subscriptionid );
     }
+    return;
 }
 
 =head2 updateClaim
 
-=over 4
-
 &updateClaim($serialid)
 
 this function updates the time when a claim is issued for late/missing items
 
 called from claims.pl file
 
-=back
-
 =cut
 
 sub updateClaim {
@@ -1982,21 +1872,18 @@ sub updateClaim {
         "
     );
     $sth->execute($serialid);
+    return;
 }
 
 =head2 getsupplierbyserialid
 
-=over 4
-
-($result) = &getsupplierbyserialid($serialid)
+$result = getsupplierbyserialid($serialid)
 
 this function is used to find the supplier id given a serial id
 
 return :
 hashref containing serialid, subscriptionid, and aqbooksellerid
 
-=back
-
 =cut
 
 sub getsupplierbyserialid {
@@ -2017,15 +1904,11 @@ sub getsupplierbyserialid {
 
 =head2 check_routing
 
-=over 4
-
-($result) = &check_routing($subscriptionid)
+$result = &check_routing($subscriptionid)
 
 this function checks to see if a serial has a routing list and returns the count of routingid
 used to show either an 'add' or 'edit' link
 
-=back
-
 =cut
 
 sub check_routing {
@@ -2045,16 +1928,12 @@ sub check_routing {
 
 =head2 addroutingmember
 
-=over 4
-
-&addroutingmember($borrowernumber,$subscriptionid)
+addroutingmember($borrowernumber,$subscriptionid)
 
-this function takes a borrowernumber and subscriptionid and add the member to the
+this function takes a borrowernumber and subscriptionid and adds the member to the
 routing list for that serial subscription and gives them a rank on the list
 of either 1 or highest current rank + 1
 
-=back
-
 =cut
 
 sub addroutingmember {
@@ -2076,9 +1955,7 @@ sub addroutingmember {
 
 =head2 reorder_members
 
-=over 4
-
-&reorder_members($subscriptionid,$routingid,$rank)
+reorder_members($subscriptionid,$routingid,$rank)
 
 this function is used to reorder the routing list
 
@@ -2088,8 +1965,6 @@ it takes the routingid of the member one wants to re-rank and the rank it is to
 - then reinjects $routingid at point indicated by $rank
 - then update the database with the routingids in the new order
 
-=back
-
 =cut
 
 sub reorder_members {
@@ -2122,19 +1997,16 @@ sub reorder_members {
         my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
         $sth->execute;
     }
+    return;
 }
 
 =head2 delroutingmember
 
-=over 4
-
-&delroutingmember($routingid,$subscriptionid)
+delroutingmember($routingid,$subscriptionid)
 
 this function either deletes one member from routing list if $routingid exists otherwise
 deletes all members from the routing list
 
-=back
-
 =cut
 
 sub delroutingmember {
@@ -2150,23 +2022,20 @@ sub delroutingmember {
         my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
         $sth->execute($subscriptionid);
     }
+    return;
 }
 
 =head2 getroutinglist
 
-=over 4
-
-($count,@routinglist) = &getroutinglist($subscriptionid)
+($count,@routinglist) = getroutinglist($subscriptionid)
 
 this gets the info from the subscriptionroutinglist for $subscriptionid
 
 return :
 a count of the number of members on routinglist
-the routinglist into a table. Each line of this table containts a ref to a hash which containts
+the routinglist as an array. Each element of the array contains a hash_ref containing
 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
 
-=back
-
 =cut
 
 sub getroutinglist {
@@ -2175,7 +2044,7 @@ sub getroutinglist {
     my $sth              = $dbh->prepare(
         "SELECT routingid, borrowernumber, ranking, biblionumber 
             FROM subscription 
-            LEFT JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
+            JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
             WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
                               "
     );
@@ -2191,12 +2060,10 @@ sub getroutinglist {
 
 =head2 countissuesfrom
 
-=over 4
-
-$result = &countissuesfrom($subscriptionid,$startdate)
-
+$result = countissuesfrom($subscriptionid,$startdate)
 
-=back
+Returns a count of serial rows matching the given subsctiptionid
+with published date greater than startdate
 
 =cut
 
@@ -2217,12 +2084,9 @@ sub countissuesfrom {
 
 =head2 CountIssues
 
-=over 4
+$result = CountIssues($subscriptionid)
 
-$result = &CountIssues($subscriptionid)
-
-
-=back
+Returns a count of serial rows matching the given subsctiptionid
 
 =cut
 
@@ -2242,96 +2106,87 @@ sub CountIssues {
 
 =head2 HasItems
 
-=over 4
-
-$result = &HasItems($subscriptionid)
+$result = HasItems($subscriptionid)
 
-
-=back
+returns a count of items from serial matching the subscriptionid
 
 =cut
 
 sub HasItems {
     my ($subscriptionid) = @_;
     my $dbh              = C4::Context->dbh;
-    my $query = qq|
+    my $query = q|
             SELECT COUNT(serialitems.itemnumber)
             FROM   serial 
                        LEFT JOIN serialitems USING(serialid)
-            WHERE  subscriptionid=? AND serialitems.serialid NOT NULL
+            WHERE  subscriptionid=? AND serialitems.serialid IS NOT NULL
         |;
     my $sth=$dbh->prepare($query);
     $sth->execute($subscriptionid);
-    my ($countitems)=$sth->fetchrow;
+    my ($countitems)=$sth->fetchrow_array();
     return $countitems;  
 }
 
 =head2 abouttoexpire
 
-=over 4
-
-$result = &abouttoexpire($subscriptionid)
+$result = abouttoexpire($subscriptionid)
 
 this function alerts you to the penultimate issue for a serial subscription
 
 returns 1 - if this is the penultimate issue
 returns 0 - if not
 
-=back
-
 =cut
 
 sub abouttoexpire {
     my ($subscriptionid) = @_;
     my $dbh              = C4::Context->dbh;
     my $subscription     = GetSubscription($subscriptionid);
-    my $per              = $subscription->{'periodicity'};
-    if ( $per % 16 > 0 ) {
-        my $expirationdate = $subscription->{enddate};
-        my $sth            = $dbh->prepare("select max(planneddate) from serial where subscriptionid=?");
-        $sth->execute($subscriptionid);
-        my ($res) = $sth->fetchrow;
-        my @res = split( /-/, $res );
-        @res = Date::Calc::Today if ( $res[0] * $res[1] == 0 );
-        my @endofsubscriptiondate = split( /-/, $expirationdate );
-        my $x;
-        if ( $per == 1 ) { $x = 7; }
-        if ( $per == 2 ) { $x = 7; }
-        if ( $per == 3 ) { $x = 14; }
-        if ( $per == 4 ) { $x = 21; }
-        if ( $per == 5 ) { $x = 31; }
-        if ( $per == 6 ) { $x = 62; }
-        if ( $per == 7 || $per == 8 ) { $x = 93; }
-        if ( $per == 9 )  { $x = 190; }
-        if ( $per == 10 ) { $x = 365; }
-        if ( $per == 11 ) { $x = 730; }
-        my @datebeforeend = Add_Delta_Days( $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2], -( 3 * $x ) )
-          if ( @endofsubscriptiondate && $endofsubscriptiondate[0] * $endofsubscriptiondate[1] * $endofsubscriptiondate[2] );
-
-        # warn "DATE BEFORE END: $datebeforeend";
-        return 1
-          if (
-            @res
-            && ( @datebeforeend
-                && Delta_Days( $res[0], $res[1], $res[2], $datebeforeend[0], $datebeforeend[1], $datebeforeend[2] ) <= 0 )
-            && ( @endofsubscriptiondate
-                && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) >= 0 )
-          );
-        return 0;
-    } elsif ( $subscription->{numberlength} > 0 ) {
-        return ( countissuesfrom( $subscriptionid, $subscription->{'startdate'} ) >= $subscription->{numberlength} - 1 );
-    } else {
+    my $per = $subscription->{'periodicity'};
+    if ($per && $per % 16 > 0){
+        my $expirationdate   = GetExpirationDate($subscriptionid);
+        my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
+        my @res;
+        if (defined $res) {
+            @res=split (/-/,$res);
+            @res=Date::Calc::Today if ($res[0]*$res[1]==0);
+        } else { # default an undefined value
+            @res=Date::Calc::Today;
+        }
+        my @endofsubscriptiondate=split(/-/,$expirationdate);
+        my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 0, 0, 0);
+        my @datebeforeend;
+        @datebeforeend = Add_Delta_Days(  $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
+            - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
+        return 1 if ( @res &&
+            (@datebeforeend &&
+                Delta_Days($res[0],$res[1],$res[2],
+                    $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
+            (@endofsubscriptiondate &&
+                Delta_Days($res[0],$res[1],$res[2],
+                    $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
         return 0;
+    } elsif ($subscription->{numberlength}>0) {
+        return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
     }
+    return 0;
 }
 
-=head2 GetNextDate
+sub in_array {    # used in next sub down
+    my ( $val, @elements ) = @_;
+    foreach my $elem (@elements) {
+        if ( $val == $elem ) {
+            return 1;
+        }
+    }
+    return 0;
+}
 
-($resultdate) = &GetNextDate($planneddate,$subscription)
+=head2 GetNextDate
 
-this function is an extension of GetNextDate which allows for checking for irregularity
+$resultdate = GetNextDate($planneddate,$subscription)
 
-it takes the planneddate and will return the next issue's date and will skip dates if there
+this function it takes the planneddate and will return the next issue's date and will skip dates if there
 exists an irregularity
 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be 
 skipped then the returned date will be 2007-05-10
@@ -2343,16 +2198,6 @@ Return 0 if periodicity==0
 
 =cut
 
-sub in_array {    # used in next sub down
-    my ( $val, @elements ) = @_;
-    foreach my $elem (@elements) {
-        if ( $val == $elem ) {
-            return 1;
-        }
-    }
-    return 0;
-}
-
 sub GetNextDate(@) {
     my ( $planneddate, $subscription ) = @_;
     my @irreg = split( /\,/, $subscription->{irregularity} );
@@ -2494,29 +2339,24 @@ sub GetNextDate(@) {
     return "$resultdate";
 }
 
-=head2 itemdata
-
-  $item = &itemdata($barcode);
+=head2 is_barcode_in_use
 
-Looks up the item with the given barcode, and returns a
-reference-to-hash containing information about that item. The keys of
-the hash are the fields from the C<items> and C<biblioitems> tables in
-the Koha database.
+Returns number of occurence of the barcode in the items table
+Can be used as a boolean test of whether the barcode has
+been deployed as yet
 
 =cut
 
-#'
-sub itemdata {
-    my ($barcode) = @_;
+sub is_barcode_in_use {
+    my $barcode = shift;
     my $dbh       = C4::Context->dbh;
-    my $sth       = $dbh->prepare(
-        "Select * from items LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber 
-        WHERE barcode=?"
+    my $occurences = $dbh->selectall_arrayref(
+        'SELECT itemnumber from items where barcode = ?',
+        {}, $barcode
+
     );
-    $sth->execute($barcode);
-    my $data = $sth->fetchrow_hashref;
-    $sth->finish;
-    return ($data);
+
+    return @{$occurences};
 }
 
 1;
@@ -2524,6 +2364,6 @@ __END__
 
 =head1 AUTHOR
 
-Koha Developement team <info@koha.org>
+Koha Development Team <http://koha-community.org/>
 
 =cut