Bug 2555 : label batch_id not properly incremented after batch num 10.
[koha.git] / C4 / Serials.pm
index c5d14cf..4ca0312 100644 (file)
@@ -29,6 +29,7 @@ use C4::Items;
 use C4::Search;
 use C4::Letters;
 use C4::Log; # logaction
+use C4::Debug;
 
 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
 
@@ -46,7 +47,7 @@ BEGIN {
     &GetLatestSerials   &ModSerialStatus    &GetNextDate       &GetSerials2
     &ReNewSubscription  &GetLateIssues      &GetLateOrMissingIssues
     &GetSerialInformation                   &AddItem2Serial
-    &PrepareSerialsData
+    &PrepareSerialsData &GetNextExpected    &ModNextExpected
     
     &UpdateClaimdateIssues
     &GetSuppliersWithLateIssues             &getsupplierbyserialid
@@ -239,7 +240,7 @@ sub GetSerialInformation {
     my ($serialid) = @_;
     my $dbh        = C4::Context->dbh;
     my $query      = qq|
-        SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid|;
+        SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
        if (C4::Context->preference('IndependantBranches') && 
               C4::Context->userenv && 
               C4::Context->userenv->{'flags'} != 1 && C4::Context->userenv->{'branch'}){
@@ -253,19 +254,20 @@ sub GetSerialInformation {
     my $rq = $dbh->prepare($query);
     $rq->execute($serialid);
     my $data = $rq->fetchrow_hashref;
-
-    if ( C4::Context->preference("serialsadditems") ) {
-        if ( $data->{'itemnumber'} ) {
-            my @itemnumbers = split /,/, $data->{'itemnumber'};
-            foreach my $itemnum (@itemnumbers) {
-
+    # create item information if we have serialsadditems for this subscription
+    if ( $data->{'serialsadditems'} ) {
+        my $queryitem=$dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
+        $queryitem->execute($serialid);
+        my $itemnumbers=$queryitem->fetchall_arrayref([0]);
+        if (scalar(@$itemnumbers)>0){
+            foreach my $itemnum (@$itemnumbers) {
                 #It is ASSUMED that GetMarcItem ALWAYS WORK...
                 #Maybe GetMarcItem should return values on failure
-#                 warn "itemnumber :$itemnum, bibnum :".$data->{'biblionumber'};
+                $debug and warn "itemnumber :$itemnum->[0], bibnum :".$data->{'biblionumber'};
                 my $itemprocessed =
-                  PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum );
-                $itemprocessed->{'itemnumber'}   = $itemnum;
-                $itemprocessed->{'itemid'}       = $itemnum;
+                  PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0] , $data );
+                $itemprocessed->{'itemnumber'}   = $itemnum->[0];
+                $itemprocessed->{'itemid'}       = $itemnum->[0];
                 $itemprocessed->{'serialid'}     = $serialid;
                 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
                 push @{ $data->{'items'} }, $itemprocessed;
@@ -273,7 +275,7 @@ sub GetSerialInformation {
         }
         else {
             my $itemprocessed =
-              PrepareItemrecordDisplay( $data->{'biblionumber'} );
+              PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
             $itemprocessed->{'itemid'}       = "N$serialid";
             $itemprocessed->{'serialid'}     = $serialid;
             $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
@@ -295,6 +297,7 @@ sub GetSerialInformation {
 
 $data = AddItem2Serial($serialid,$itemnumber);
 Adds an itemnumber to Serial record
+
 =back
 
 =cut
@@ -315,6 +318,7 @@ UpdateClaimdateIssues($serialids,[$date]);
 
 Update Claimdate for issues in @$serialids list with date $date 
 (Take Today if none)
+
 =back
 
 =cut
@@ -352,6 +356,7 @@ sub GetSubscription {
     my $query            = qq(
         SELECT  subscription.*,
                 subscriptionhistory.*,
+                subscriptionhistory.enddate as histenddate,
                 aqbudget.bookfundid,
                 aqbooksellers.name AS aqbooksellername,
                 biblio.title AS bibliotitle,
@@ -373,15 +378,13 @@ sub GetSubscription {
 #     if (C4::Context->preference('IndependantBranches') && 
 #         C4::Context->userenv && 
 #         C4::Context->userenv->{'flags'} != 1){
-# #       warn "flags: ".C4::Context->userenv->{'flags'};
+# #       $debug and warn "flags: ".C4::Context->userenv->{'flags'};
 #       $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
 #     }
-#        warn "query : $query";
+       $debug and warn "query : $query\nsubsid :$subscriptionid";
     my $sth = $dbh->prepare($query);
-#       warn "subsid :$subscriptionid";
     $sth->execute($subscriptionid);
-    my $subs = $sth->fetchrow_hashref;
-    return $subs;
+    return $sth->fetchrow_hashref;
 }
 
 =head2 GetFullSubscription
@@ -428,11 +431,10 @@ sub GetFullSubscription {
           IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
           serial.subscriptionid
           |;
-#     warn $query;   
+       $debug and warn "GetFullSubscription query: $query";   
     my $sth = $dbh->prepare($query);
     $sth->execute($subscriptionid);
-    my $subs = $sth->fetchall_arrayref({});
-    return $subs;
+    return $sth->fetchall_arrayref({});
 }
 
 
@@ -518,6 +520,7 @@ sub GetSubscriptionsFromBiblionumber {
         SELECT subscription.*,
                branches.branchname,
                subscriptionhistory.*,
+               subscriptionhistory.enddate as histenddate, 
                aqbudget.bookfundid,
                aqbooksellers.name AS aqbooksellername,
                biblio.title AS bibliotitle
@@ -540,6 +543,7 @@ sub GetSubscriptionsFromBiblionumber {
     while ( my $subs = $sth->fetchrow_hashref ) {
         $subs->{startdate}     = format_date( $subs->{startdate} );
         $subs->{histstartdate} = format_date( $subs->{histstartdate} );
+        $subs->{histenddate} = format_date( $subs->{histenddate} );
         $subs->{opacnote}     =~ s/\n/\<br\/\>/g;
         $subs->{missinglist}  =~ s/\n/\<br\/\>/g;
         $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
@@ -611,8 +615,7 @@ sub GetFullSubscriptionsFromBiblionumber {
           |;
     my $sth = $dbh->prepare($query);
     $sth->execute($biblionumber);
-    my $subs= $sth->fetchall_arrayref({});
-    return $subs;
+    return $sth->fetchall_arrayref({});
 }
 
 =head2 GetSubscriptions
@@ -642,7 +645,7 @@ sub GetSubscriptions {
             WHERE biblio.biblionumber=?
         );
         $query.=" ORDER BY title";
-#         warn "query :$query";
+        $debug and warn "GetSubscriptions query: $query";
         $sth = $dbh->prepare($query);
         $sth->execute($biblionumber);
     }
@@ -655,6 +658,7 @@ sub GetSubscriptions {
                 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
                 WHERE (biblioitems.issn = ? or|. join('and ',map{"biblio.title LIKE \"%$_%\""}split (" ",$title))." )";
             $query.=" ORDER BY title";
+               $debug and warn "GetSubscriptions query: $query";
             $sth = $dbh->prepare($query);
             $sth->execute( $ISSN );
         }
@@ -668,7 +672,7 @@ sub GetSubscriptions {
                     WHERE biblioitems.issn LIKE ?
                 );
                 $query.=" ORDER BY title";
-#         warn "query :$query";
+                       $debug and warn "GetSubscriptions query: $query";
                 $sth = $dbh->prepare($query);
                 $sth->execute( "%" . $ISSN . "%" );
             }
@@ -682,7 +686,7 @@ sub GetSubscriptions {
                     ).($title?" and ":""). join('and ',map{"biblio.title LIKE \"%$_%\""} split (" ",$title) );
                 
                 $query.=" ORDER BY title";
-#                 warn $query;       
+                       $debug and warn "GetSubscriptions query: $query";
                 $sth = $dbh->prepare($query);
                 $sth->execute;
             }
@@ -695,13 +699,12 @@ sub GetSubscriptions {
         if ( $previoustitle eq $line->{title} ) {
             $line->{title}  = "";
             $line->{issn}   = "";
-            $line->{toggle} = 1 if $odd == 1;
         }
         else {
             $previoustitle = $line->{title};
             $odd           = -$odd;
-            $line->{toggle} = 1 if $odd == 1;
         }
+        $line->{toggle} = 1 if $odd == 1;
         $line->{'cannotedit'}=(C4::Context->preference('IndependantBranches') && 
                 C4::Context->userenv && 
                 C4::Context->userenv->{flags} !=1  && 
@@ -721,6 +724,8 @@ this function get 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
@@ -794,7 +799,7 @@ sub GetSerials2 {
                  WHERE    subscriptionid=$subscription AND status IN ($status)
                  ORDER BY publisheddate,serialid DESC
                     |;
-#     warn $query;
+       $debug and warn "GetSerials2 query: $query";
     my $sth=$dbh->prepare($query);
     $sth->execute;
     my @serials;
@@ -1214,6 +1219,61 @@ sub ModSerialStatus {
     }
 }
 
+=head2 GetNextExpected
+
+=over 4
+
+$nextexpected = GetNextExpected($subscriptionid)
+
+Get the planneddate for the current expected issue of the subscription.
+
+returns a hashref:
+
+$nextexepected = {
+    serialid => int
+    planneddate => C4::Dates object
+    }
+
+=back
+
+=cut
+
+sub GetNextExpected($) {
+    my ($subscriptionid) = @_;
+    my $dbh = C4::Context->dbh;
+    my $sth = $dbh->prepare('SELECT serialid, planneddate FROM serial WHERE subscriptionid=? AND status=?');
+    # Each subscription has only one 'expected' issue, with serial.status==1.
+    $sth->execute( $subscriptionid, 1 );
+    my ( $nextissue ) = $sth->fetchrow_hashref;
+    $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.
+This will modify all future prediction results.  
+
+C<$date> is a C4::Dates object.
+
+=back
+
+=cut
+
+sub ModNextExpected($$) {
+    my ($subscriptionid,$date) = @_;
+    my $dbh = C4::Context->dbh;
+    #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
+    my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
+    # Each subscription has only one 'expected' issue, with serial.status==1.
+    $sth->execute( $date->output('iso'),$date->output('iso'), $subscriptionid, 1);
+    return 0;
+
+}
+
 =head2 ModSubscription
 
 =over 4
@@ -1236,7 +1296,7 @@ sub ModSubscription {
         $whenmorethan3,   $setto3,       $lastvalue3,     $innerloop3,
         $numberingmethod, $status,       $biblionumber,   $callnumber,
         $notes,           $letter,       $hemisphere,     $manualhistory,
-        $internalnotes,
+        $internalnotes,   $serialsadditems,
         $subscriptionid
     ) = @_;
 #     warn $irregularity;
@@ -1247,7 +1307,7 @@ sub ModSubscription {
                         add1=?,every1=?,whenmorethan1=?,setto1=?,lastvalue1=?,innerloop1=?,
                         add2=?,every2=?,whenmorethan2=?,setto2=?,lastvalue2=?,innerloop2=?,
                         add3=?,every3=?,whenmorethan3=?,setto3=?,lastvalue3=?,innerloop3=?,
-                        numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?, letter=?, hemisphere=?,manualhistory=?,internalnotes=?
+                        numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?, letter=?, hemisphere=?,manualhistory=?,internalnotes=?,serialsadditems=?
                     WHERE subscriptionid = ?";
 #     warn "query :".$query;
     my $sth = $dbh->prepare($query);
@@ -1262,7 +1322,7 @@ sub ModSubscription {
         $whenmorethan3,   $setto3,       $lastvalue3,     $innerloop3,
         $numberingmethod, $status,       $biblionumber,   $callnumber,
         $notes,           $letter,       $hemisphere,     ($manualhistory?$manualhistory:0),
-        $internalnotes,
+        $internalnotes,   $serialsadditems,
         $subscriptionid
     );
     my $rows=$sth->rows;
@@ -1281,7 +1341,7 @@ $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbu
     $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
     $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
     $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
-    $numberingmethod, $status, $notes)
+    $numberingmethod, $status, $notes, $serialsadditems)
 
 Create a new subscription with value given on input args.
 
@@ -1304,7 +1364,7 @@ sub NewSubscription {
         $lastvalue3,    $innerloop3,   $numberingmethod, $status,
         $notes,         $letter,       $firstacquidate,  $irregularity,
         $numberpattern, $callnumber,   $hemisphere,      $manualhistory,
-        $internalnotes
+        $internalnotes, $serialsadditems,
     ) = @_;
     my $dbh = C4::Context->dbh;
 
@@ -1317,8 +1377,8 @@ sub NewSubscription {
             add2,every2,whenmorethan2,setto2,lastvalue2,innerloop2,
             add3,every3,whenmorethan3,setto3,lastvalue3,innerloop3,
             numberingmethod, status, notes, letter,firstacquidate,irregularity,
-            numberpattern, callnumber, hemisphere,manualhistory,internalnotes)
-        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+            numberpattern, callnumber, hemisphere,manualhistory,internalnotes,serialsadditems)
+        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
         |;
     my $sth = $dbh->prepare($query);
     $sth->execute(
@@ -1342,7 +1402,7 @@ sub NewSubscription {
         format_date_in_iso($firstacquidate),                $irregularity,
         $numberpattern,                 $callnumber,
         $hemisphere,                    $manualhistory,
-        $internalnotes
+        $internalnotes,                 $serialsadditems,
     );
 
     #then create the 1st waited number
@@ -1350,7 +1410,7 @@ sub NewSubscription {
     $query             = qq(
         INSERT INTO subscriptionhistory
             (biblionumber, subscriptionid, histstartdate,  opacnote, librariannote)
-        VALUES (?,?,?,?,?,?,?,?)
+        VALUES (?,?,?,?,?)
         );
     $sth = $dbh->prepare($query);
     $sth->execute( $biblionumber, $subscriptionid,
@@ -1377,8 +1437,8 @@ sub NewSubscription {
     $sth = $dbh->prepare($query);
     $sth->execute(
         "$serialseq", $subscriptionid, $biblionumber, 1,
-        format_date_in_iso($startdate),
-        format_date_in_iso($startdate)
+        format_date_in_iso($firstacquidate),
+        format_date_in_iso($firstacquidate)
     );
     
     logaction("SERIAL", "ADD", $subscriptionid, "") if C4::Context->preference("SubscriptionLog");
@@ -1425,14 +1485,16 @@ sub ReNewSubscription {
      my $sth = $dbh->prepare($query);
      $sth->execute( $subscription->{biblionumber} );
      my $biblio = $sth->fetchrow_hashref;
-     NewSuggestion(
-         $user,             $subscription->{bibliotitle},
-         $biblio->{author}, $biblio->{publishercode},
-         $biblio->{note},   '',
-         '',                '',
-         '',                '',
-         $subscription->{biblionumber}
-     );
+     if (C4::Context->preference("RenewSerialAddsSuggestion")){
+        NewSuggestion(
+            $user,             $subscription->{bibliotitle},
+            $biblio->{author}, $biblio->{publishercode},
+            $biblio->{note},   '',
+            '',                '',
+            '',                '',
+            $subscription->{biblionumber}
+        );
+    }
 
     # renew subscription
     $query = qq|
@@ -1744,13 +1806,13 @@ sub HasSubscriptionExpired {
     } else {
       if ($subscription->{'numberlength'}){
         my $countreceived=countissuesfrom($subscriptionid,$subscription->{'startdate'});
-       return 1 if ($countreceived >$subscription->{'numberlentgh'});
+       return 1 if ($countreceived >$subscription->{'numberlength'});
              return 0;
       } else {
              return 0;
       }
     }
-    return 0;
+    return 0;  # Notice that you'll never get here.
 }
 
 =head2 SetDistributedto
@@ -2054,6 +2116,7 @@ sub getsupplierbyserialid {
 
 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
@@ -2590,10 +2653,13 @@ sub GetNextDate(@) {
     my @resultdate;
 
     #       warn "DOW $dayofweek";
-    if ( $subscription->{periodicity} % 16 == 0 ) {
+    if ( $subscription->{periodicity} % 16 == 0 ) {  # 'without regularity' || 'irregular'
       return 0;
     }  
-    if ( $subscription->{periodicity} == 1 ) {
+    #   daily : n / week
+    #   Since we're interpreting irregularity here as which days of the week to skip an issue,
+    #   renaming this pattern from 1/day to " n / week ".
+    if ( $subscription->{periodicity} == 1 ) {  
         my $dayofweek = eval{Day_of_Week( $year,$month, $day )};
         if ($@){warn "year month day : $year $month $day $subscription->{subscriptionid} : $@";}
         else {    
@@ -2607,11 +2673,13 @@ sub GetNextDate(@) {
           @resultdate = Add_Delta_Days($year,$month, $day , 1 );
         }    
     }
+    #   1  week
     if ( $subscription->{periodicity} == 2 ) {
         my ($wkno,$year) = eval {Week_of_Year( $year,$month, $day )};
         if ($@){warn "year month day : $year $month $day $subscription->{subscriptionid} : $@";}
         else {    
           for ( my $i = 0 ; $i < @irreg ; $i++ ) {
+          #FIXME: if two consecutive irreg, do we only skip one?
               if ( $irreg[$i] == (($wkno!=51)?($wkno +1) % 52 :52)) {
                   ($year,$month,$day) = Add_Delta_Days($year,$month, $day , 7 );
                   $wkno=(($wkno!=51)?($wkno +1) % 52 :52);
@@ -2620,6 +2688,7 @@ sub GetNextDate(@) {
           @resultdate = Add_Delta_Days( $year,$month, $day, 7);
         }        
     }
+    #   1 / 2 weeks
     if ( $subscription->{periodicity} == 3 ) {        
         my ($wkno,$year) = eval {Week_of_Year( $year,$month, $day )};
         if ($@){warn "year month day : $year $month $day $subscription->{subscriptionid} : $@";}
@@ -2634,6 +2703,7 @@ sub GetNextDate(@) {
           @resultdate = Add_Delta_Days($year,$month, $day , 14 );
         }        
     }
+    #   1 / 3 weeks
     if ( $subscription->{periodicity} == 4 ) {
         my ($wkno,$year) = eval {Week_of_Year( $year,$month, $day )};
         if ($@){warn "annĂ©e mois jour : $year $month $day $subscription->{subscriptionid} : $@";}
@@ -2736,8 +2806,6 @@ sub itemdata {
 1;
 __END__
 
-=back
-
 =head1 AUTHOR
 
 Koha Developement team <info@koha.org>