Bugfix #2630 2nd attempt
[koha.git] / C4 / Serials.pm
index 8731434..4ca0312 100644 (file)
@@ -19,44 +19,25 @@ package C4::Serials;    #assumes C4/Serials.pm
 
 
 use strict;
-use C4::Date;
+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::Items;
 use C4::Search;
 use C4::Letters;
 use C4::Log; # logaction
-
-require Exporter;
+use C4::Debug;
 
 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
 
-# set the version for version checking
-$VERSION = do { my @v = '$Revision$' =~ /\d+/g;
-    shift(@v) . "." . join( "_", map { sprintf "%03d", $_ } @v );
-};
-
-=head1 NAME
-
-C4::Serials - Give functions for serializing.
-
-=head1 SYNOPSIS
-
-  use C4::Serials;
-
-=head1 DESCRIPTION
-
-Give all XYZ functions
-
-=head1 FUNCTIONS
-
-=cut
-
-@ISA    = qw(Exporter);
-@EXPORT = qw(
-    
+BEGIN {
+       $VERSION = 3.01;        # set version for version checking
+       require Exporter;
+       @ISA    = qw(Exporter);
+       @EXPORT = qw(
     &NewSubscription    &ModSubscription    &DelSubscription    &GetSubscriptions
     &GetSubscription    &CountSubscriptionFromBiblionumber      &GetSubscriptionsFromBiblionumber
     &GetFullSubscriptionsFromBiblionumber   &GetFullSubscription &ModSubscriptionHistory
@@ -66,7 +47,7 @@ Give all XYZ functions
     &GetLatestSerials   &ModSerialStatus    &GetNextDate       &GetSerials2
     &ReNewSubscription  &GetLateIssues      &GetLateOrMissingIssues
     &GetSerialInformation                   &AddItem2Serial
-    &PrepareSerialsData
+    &PrepareSerialsData &GetNextExpected    &ModNextExpected
     
     &UpdateClaimdateIssues
     &GetSuppliersWithLateIssues             &getsupplierbyserialid
@@ -76,10 +57,25 @@ Give all XYZ functions
     &check_routing &updateClaim &removeMissingIssue
     
     &old_newsubscription &old_modsubscription &old_getserials
-);
+       );
+}
 
 =head2 GetSuppliersWithLateIssues
 
+=head1 NAME
+
+C4::Serials - Give functions for serializing.
+
+=head1 SYNOPSIS
+
+  use C4::Serials;
+
+=head1 DESCRIPTION
+
+Give all XYZ functions
+
+=head1 FUNCTIONS
+
 =over 4
 
 %supplierlist = &GetSuppliersWithLateIssues
@@ -244,26 +240,34 @@ 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'}){
+                $query.="
+      , ((subscription.branchcode <>\"".C4::Context->userenv->{'branch'}."\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
+        }
+            $query .= qq|             
         FROM   serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
         WHERE  serialid = ?
     |;
     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;
@@ -271,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'};
@@ -287,12 +291,13 @@ sub GetSerialInformation {
     return $data;
 }
 
-=head2 GetSerialInformation
+=head2 AddItem2Serial
 
 =over 4
 
 $data = AddItem2Serial($serialid,$itemnumber);
 Adds an itemnumber to Serial record
+
 =back
 
 =cut
@@ -300,12 +305,8 @@ Adds an itemnumber to Serial record
 sub AddItem2Serial {
     my ( $serialid, $itemnumber ) = @_;
     my $dbh   = C4::Context->dbh;
-    my $query = qq|
-        UPDATE serial SET itemnumber=IF(itemnumber IS NULL, $itemnumber, CONCAT(itemnumber,",",$itemnumber))
-        WHERE  serialid = ?
-    |;
-    my $rq = $dbh->prepare($query);
-    $rq->execute($serialid);
+    my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
+    $rq->execute($serialid, $itemnumber);
     return $rq->rows;
 }
 
@@ -317,6 +318,7 @@ UpdateClaimdateIssues($serialids,[$date]);
 
 Update Claimdate for issues in @$serialids list with date $date 
 (Take Today if none)
+
 =back
 
 =cut
@@ -354,10 +356,18 @@ sub GetSubscription {
     my $query            = qq(
         SELECT  subscription.*,
                 subscriptionhistory.*,
+                subscriptionhistory.enddate as histenddate,
                 aqbudget.bookfundid,
                 aqbooksellers.name AS aqbooksellername,
                 biblio.title AS bibliotitle,
-                subscription.biblionumber as bibnum
+                subscription.biblionumber as bibnum);
+       if (C4::Context->preference('IndependantBranches') && 
+              C4::Context->userenv && 
+              C4::Context->userenv->{'flags'} != 1 && C4::Context->userenv->{'branch'}){
+                $query.="
+      , ((subscription.branchcode <>\"".C4::Context->userenv->{'branch'}."\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
+        }
+            $query .= qq(             
        FROM subscription
        LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
        LEFT JOIN aqbudget ON subscription.aqbudgetid=aqbudget.aqbudgetid
@@ -368,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
@@ -404,29 +412,29 @@ sub GetFullSubscription {
             aqbudget.bookfundid,aqbooksellers.name as aqbooksellername,
             biblio.title as bibliotitle,
             subscription.branchcode AS branchcode,
-            subscription.subscriptionid AS subscriptionid
+            subscription.subscriptionid AS subscriptionid |;
+    if (C4::Context->preference('IndependantBranches') && 
+        C4::Context->userenv && 
+        C4::Context->userenv->{'flags'} != 1 && C4::Context->userenv->{'branch'}){
+      $query.="
+      , ((subscription.branchcode <>\"".C4::Context->userenv->{'branch'}."\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
+    }
+    $query.=qq|
   FROM      serial 
   LEFT JOIN subscription ON 
-          (serial.subscriptionid=subscription.subscriptionid AND subscription.biblionumber=serial.biblionumber)
+          (serial.subscriptionid=subscription.subscriptionid )
   LEFT JOIN aqbudget ON subscription.aqbudgetid=aqbudget.aqbudgetid 
   LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id 
   LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber 
-  WHERE     serial.subscriptionid = ? |;
-    if (C4::Context->preference('IndependantBranches') && 
-        C4::Context->userenv && 
-        C4::Context->userenv->{'flags'} != 1){
-      $query.="
-  AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"''\")";
-    }
-    $query .=qq|
+  WHERE     serial.subscriptionid = ? 
   ORDER BY year DESC,
           IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
           serial.subscriptionid
           |;
+       $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({});
 }
 
 
@@ -480,8 +488,8 @@ sub PrepareSerialsData{
                 'bibliotitle'      => $subs->{'bibliotitle'},
                 'serials'          => [$subs],
                 'first'            => $first,
-                'branchcode'       => $subs->{'branchcode'},
-                'subscriptionid'   => $subs->{'subscriptionid'},
+                'branchcode'       => $subs->{'branchcode'},
+                'subscriptionid'   => $subs->{'subscriptionid'},
             };
         }
 
@@ -512,6 +520,7 @@ sub GetSubscriptionsFromBiblionumber {
         SELECT subscription.*,
                branches.branchname,
                subscriptionhistory.*,
+               subscriptionhistory.enddate as histenddate, 
                aqbudget.bookfundid,
                aqbooksellers.name AS aqbooksellername,
                biblio.title AS bibliotitle
@@ -523,23 +532,29 @@ sub GetSubscriptionsFromBiblionumber {
        LEFT JOIN branches ON branches.branchcode=subscription.branchcode
        WHERE subscription.biblionumber = ?
     );
-    if (C4::Context->preference('IndependantBranches') && 
-        C4::Context->userenv && 
-        C4::Context->userenv->{'flags'} != 1){
-       $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
-    }
+    if (C4::Context->preference('IndependantBranches') && 
+        C4::Context->userenv && 
+        C4::Context->userenv->{'flags'} != 1){
+       $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
+    }
     my $sth = $dbh->prepare($query);
     $sth->execute($biblionumber);
     my @res;
     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;
         $subs->{ "periodicity" . $subs->{periodicity} } = 1;
         $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
         $subs->{ "status" . $subs->{'status'} } = 1;
+        $subs->{'cannotedit'}=(C4::Context->preference('IndependantBranches') && 
+                C4::Context->userenv && 
+                C4::Context->userenv->{flags} !=1  && 
+                C4::Context->userenv->{branch} && $subs->{branchcode} &&
+                (C4::Context->userenv->{branch} ne $subs->{branchcode}));
         if ( $subs->{enddate} eq '0000-00-00' ) {
             $subs->{enddate} = '';
         }
@@ -578,29 +593,29 @@ sub GetFullSubscriptionsFromBiblionumber {
             aqbudget.bookfundid,aqbooksellers.name as aqbooksellername,
             biblio.title as bibliotitle,
             subscription.branchcode AS branchcode,
-            subscription.subscriptionid AS subscriptionid
+            subscription.subscriptionid AS subscriptionid|;
+     if (C4::Context->preference('IndependantBranches') && 
+        C4::Context->userenv && 
+        C4::Context->userenv->{'flags'} != 1 && C4::Context->userenv->{'branch'}){
+      $query.="
+      , ((subscription.branchcode <>\"".C4::Context->userenv->{'branch'}."\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
+     }
+      
+     $query.=qq|      
   FROM      serial 
   LEFT JOIN subscription ON 
-          (serial.subscriptionid=subscription.subscriptionid AND subscription.biblionumber=serial.biblionumber)
+          (serial.subscriptionid=subscription.subscriptionid)
   LEFT JOIN aqbudget ON subscription.aqbudgetid=aqbudget.aqbudgetid 
   LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id 
   LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber 
-  WHERE     subscription.biblionumber = ? |;
-    if (C4::Context->preference('IndependantBranches') && 
-        C4::Context->userenv && 
-        C4::Context->userenv->{'flags'} != 1){
-      $query.="
-  AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"''\")";
-    }
-    $query .=qq|
+  WHERE     subscription.biblionumber = ? 
   ORDER BY year DESC,
           IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
           serial.subscriptionid
           |;
     my $sth = $dbh->prepare($query);
     $sth->execute($biblionumber);
-    my $subs= $sth->fetchall_arrayref({});
-    return $subs;
+    return $sth->fetchall_arrayref({});
 }
 
 =head2 GetSubscriptions
@@ -629,69 +644,49 @@ sub GetSubscriptions {
             LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
             WHERE biblio.biblionumber=?
         );
-        if (C4::Context->preference('IndependantBranches') && 
-            C4::Context->userenv && 
-            C4::Context->userenv->{'flags'} != 1){
-          $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"''\")";
-        }
         $query.=" ORDER BY title";
-#         warn "query :$query";
+        $debug and warn "GetSubscriptions query: $query";
         $sth = $dbh->prepare($query);
         $sth->execute($biblionumber);
     }
     else {
         if ( $ISSN and $title ) {
             my $query = qq|
-                SELECT subscription.*,biblio.title,biblioitems.issn,biblio.biblionumber
-                    FROM   subscription
-                    LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
-                    LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
-                    WHERE (biblioitems.issn = ? or|. join('and ',map{"biblio.title LIKE \"%$_%\""}split (" ",$title))." )";
-            
-            if (C4::Context->preference('IndependantBranches') && 
-                C4::Context->userenv && 
-                C4::Context->userenv->{'flags'} != 1){
-              $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"''\")";
-            }
+                SELECT subscription.*,biblio.title,biblioitems.issn,biblio.biblionumber        
+                FROM   subscription
+                LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
+                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 );
         }
         else {
             if ($ISSN) {
                 my $query = qq(
-                    SELECT subscription.*,biblio.title,biblioitems.issn,,biblio.biblionumber
-                        FROM   subscription
-                        LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
-                        LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
-                        WHERE biblioitems.issn LIKE ?
+                    SELECT subscription.*,biblio.title,biblioitems.issn,biblio.biblionumber
+                    FROM   subscription
+                    LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
+                    LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
+                    WHERE biblioitems.issn LIKE ?
                 );
-                if (C4::Context->preference('IndependantBranches') && 
-                    C4::Context->userenv && 
-                    C4::Context->userenv->{'flags'} != 1){
-                  $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"''\")";
-                }
                 $query.=" ORDER BY title";
-#         warn "query :$query";
+                       $debug and warn "GetSubscriptions query: $query";
                 $sth = $dbh->prepare($query);
                 $sth->execute( "%" . $ISSN . "%" );
             }
             else {
                 my $query = qq(
                     SELECT subscription.*,biblio.title,biblioitems.issn,biblio.biblionumber
-                        FROM   subscription
-                        LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
-                        LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
-                        WHERE 1
-                        ).($title?" and ":""). join('and ',map{"biblio.title LIKE \"%$_%\""} split (" ",$title) );
+                    FROM   subscription
+                    LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
+                    LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
+                    WHERE 1
+                    ).($title?" and ":""). join('and ',map{"biblio.title LIKE \"%$_%\""} split (" ",$title) );
                 
-                warn $query;       
-                if (C4::Context->preference('IndependantBranches') && 
-                    C4::Context->userenv && 
-                    C4::Context->userenv->{'flags'} != 1){
-                  $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"''\")";
-                }
                 $query.=" ORDER BY title";
+                       $debug and warn "GetSubscriptions query: $query";
                 $sth = $dbh->prepare($query);
                 $sth->execute;
             }
@@ -704,13 +699,17 @@ 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  && 
+                C4::Context->userenv->{branch} && $line->{branchcode} &&
+                (C4::Context->userenv->{branch} ne $line->{branchcode}));
         push @results, $line;
     }
     return @results;
@@ -725,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
@@ -738,7 +739,7 @@ sub GetSerials {
     $count=5 unless ($count);
     my @serials;
     my $query =
-      "SELECT serialid,serialseq, status, publisheddate, planneddate,notes 
+      "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
                         FROM   serial
                         WHERE  subscriptionid = ? AND status NOT IN (2,4,5) 
                         ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
@@ -753,7 +754,7 @@ sub GetSerials {
     }
     # OK, now add the last 5 issues arrives/missing
     $query =
-      "SELECT   serialid,serialseq, status, planneddate, publisheddate,notes
+      "SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
        FROM     serial
        WHERE    subscriptionid = ?
        AND      (status in (2,4,5))
@@ -793,12 +794,12 @@ sub GetSerials2 {
     my ($subscription,$status) = @_;
     my $dbh = C4::Context->dbh;
     my $query = qq|
-                 SELECT   serialid,serialseq, status, planneddate, publisheddate,notes
+                 SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
                  FROM     serial 
                  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;
@@ -936,10 +937,9 @@ sub GetNextSeq {
     $newlastvalue1 = $val->{lastvalue1};
     $newlastvalue2 = $val->{lastvalue2};
     $newlastvalue3 = $val->{lastvalue3};
-
   $newlastvalue1 = $val->{lastvalue1};
   # check if we have to increase the new value.
-  $newinnerloop1 = $val->{innerloop1}+1;
+  $newinnerloop1 = $val->{innerloop1} + 1;
   $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
   $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
   $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
@@ -947,7 +947,7 @@ sub GetNextSeq {
   
   $newlastvalue2 = $val->{lastvalue2};
   # check if we have to increase the new value.
-  $newinnerloop2 = $val->{innerloop2}+1;
+  $newinnerloop2 = $val->{innerloop2} + 1;
   $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
   $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
   $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
@@ -968,7 +968,7 @@ sub GetNextSeq {
   
   $newlastvalue3 = $val->{lastvalue3};
   # check if we have to increase the new value.
-  $newinnerloop3 = $val->{innerloop3}+1;
+  $newinnerloop3 = $val->{innerloop3} + 1;
   $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
   $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
   $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
@@ -1037,7 +1037,7 @@ sub GetExpirationDate {
     my $enddate          = $subscription->{startdate};
 
 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
-    if ($subscription->{periodicity}){
+    if (($subscription->{periodicity} % 16) >0){
       if ( $subscription->{numberlength} ) {
           #calculate the date of the last issue.
           my $length = $subscription->{numberlength};
@@ -1219,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
@@ -1241,7 +1296,7 @@ sub ModSubscription {
         $whenmorethan3,   $setto3,       $lastvalue3,     $innerloop3,
         $numberingmethod, $status,       $biblionumber,   $callnumber,
         $notes,           $letter,       $hemisphere,     $manualhistory,
-        $internalnotes,
+        $internalnotes,   $serialsadditems,
         $subscriptionid
     ) = @_;
 #     warn $irregularity;
@@ -1252,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);
@@ -1267,14 +1322,13 @@ sub ModSubscription {
         $whenmorethan3,   $setto3,       $lastvalue3,     $innerloop3,
         $numberingmethod, $status,       $biblionumber,   $callnumber,
         $notes,           $letter,       $hemisphere,     ($manualhistory?$manualhistory:0),
-        $internalnotes,
+        $internalnotes,   $serialsadditems,
         $subscriptionid
     );
     my $rows=$sth->rows;
     $sth->finish;
     
-    &logaction(C4::Context->userenv->{'number'},"SERIAL","MODIFY",$subscriptionid,"") 
-        if C4::Context->preference("SubscriptionLog");
+    logaction("SERIAL", "MODIFY", $subscriptionid, "") if C4::Context->preference("SubscriptionLog");
     return $rows;
 }
 
@@ -1287,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.
 
@@ -1310,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;
 
@@ -1323,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(
@@ -1345,23 +1399,23 @@ sub NewSubscription {
         $lastvalue3,                    $innerloop3,
         $numberingmethod,               "$status",
         $notes,                         $letter,
-        $firstacquidate,                $irregularity,
+        format_date_in_iso($firstacquidate),                $irregularity,
         $numberpattern,                 $callnumber,
         $hemisphere,                    $manualhistory,
-        $internalnotes
+        $internalnotes,                 $serialsadditems,
     );
 
     #then create the 1st waited number
     my $subscriptionid = $dbh->{'mysql_insertid'};
     $query             = qq(
         INSERT INTO subscriptionhistory
-            (biblionumber, subscriptionid, histstartdate, enddate, missinglist, recievedlist, opacnote, librariannote)
-        VALUES (?,?,?,?,?,?,?,?)
+            (biblionumber, subscriptionid, histstartdate,  opacnote, librariannote)
+        VALUES (?,?,?,?,?)
         );
     $sth = $dbh->prepare($query);
     $sth->execute( $biblionumber, $subscriptionid,
         format_date_in_iso($startdate),
-        0, "", "", "", "$notes" );
+        $notes,$internalnotes );
 
    # reread subscription to get a hash (for calculation of the 1st issue number)
     $query = qq(
@@ -1383,13 +1437,24 @@ 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(C4::Context->userenv->{'number'},"SERIAL","ADD",$subscriptionid,"") 
-        if C4::Context->preference("SubscriptionLog");
+    logaction("SERIAL", "ADD", $subscriptionid, "") if C4::Context->preference("SubscriptionLog");
     
+#set serial flag on biblio if not already set.
+    my ($null, ($bib)) = GetBiblio($biblionumber);
+    if( ! $bib->{'serial'} ) {
+        my $record = GetMarcBiblio($biblionumber);
+        my ($tag,$subf) = GetMarcFromKohaField('biblio.serial',$bib->{'frameworkcode'});
+        if($tag) {
+            eval {
+            $record->field($tag)->update( $subf => 1 );
+            };
+        }
+        ModBiblio($record,$biblionumber,$bib->{'frameworkcode'});
+    }    
     return $subscriptionid;
 }
 
@@ -1420,27 +1485,28 @@ 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
-    my $query = qq|
+    $query = qq|
         UPDATE subscription
         SET    startdate=?,numberlength=?,weeklength=?,monthlength=?
         WHERE  subscriptionid=?
     |;
-    my $sth = $dbh->prepare($query);
+    $sth = $dbh->prepare($query);
     $sth->execute( format_date_in_iso($startdate),
         $numberlength, $weeklength, $monthlength, $subscriptionid );
         
-    &logaction(C4::Context->userenv->{'number'},"SERIAL","RENEW",$subscriptionid,"") 
-        if C4::Context->preference("SubscriptionLog");
+    logaction("SERIAL", "RENEW", $subscriptionid, "") if C4::Context->preference("SubscriptionLog");
 }
 
 =head2 NewIssue
@@ -1694,7 +1760,7 @@ sub ItemizeSerials {
                     $marcrecord->insert_fields_ordered($newField);
                 }
             }
-            AddItem( $marcrecord, $data->{'biblionumber'} );
+            AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
             return 1;
         }
         return ( 0, @errors );
@@ -1720,7 +1786,7 @@ sub HasSubscriptionExpired {
     my ($subscriptionid) = @_;
     my $dbh              = C4::Context->dbh;
     my $subscription     = GetSubscription($subscriptionid);
-    if ($subscription->{periodicity}>0){
+    if (($subscription->{periodicity} % 16)>0){
       my $expirationdate   = GetExpirationDate($subscriptionid);
       my $query = qq|
             SELECT max(planneddate)
@@ -1740,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
@@ -1792,8 +1858,7 @@ sub DelSubscription {
         "DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
     $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
     
-    &logaction(C4::Context->userenv->{'number'},"SERIAL","DELETE",$subscriptionid,"") 
-        if C4::Context->preference("SubscriptionLog");
+    logaction("SERIAL", "DELETE", $subscriptionid, "") if C4::Context->preference("SubscriptionLog");
 }
 
 =head2 DelIssue
@@ -1891,7 +1956,7 @@ sub GetLateOrMissingIssues {
    claimdate
 FROM      serial 
 LEFT JOIN subscription  ON serial.subscriptionid=subscription.subscriptionid 
-LEFT JOIN biblio        ON serial.biblionumber=biblio.biblionumber
+LEFT JOIN biblio        ON subscription.biblionumber=biblio.biblionumber
 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
 WHERE subscription.subscriptionid = serial.subscriptionid 
 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3))
@@ -1916,13 +1981,12 @@ FROM serial
 LEFT JOIN subscription 
 ON serial.subscriptionid=subscription.subscriptionid 
 LEFT JOIN biblio 
-ON serial.biblionumber=biblio.biblionumber
+ON subscription.biblionumber=biblio.biblionumber
 LEFT JOIN aqbooksellers 
 ON subscription.aqbooksellerid = aqbooksellers.id
 WHERE 
    subscription.subscriptionid = serial.subscriptionid 
 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3))
-AND biblio.biblionumber = subscription.biblionumber 
 $byserial
 ORDER BY $order"
         );
@@ -2052,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
@@ -2285,7 +2350,7 @@ sub abouttoexpire {
     my $dbh              = C4::Context->dbh;
     my $subscription     = GetSubscription($subscriptionid);
     my $per = $subscription->{'periodicity'};
-    if ($per>0){
+    if ($per % 16>0){
       my $expirationdate   = GetExpirationDate($subscriptionid);
       my $sth =
         $dbh->prepare(
@@ -2296,7 +2361,6 @@ sub abouttoexpire {
       my @res=split /-/,$res;
       @res=Date::Calc::Today if ($res[0]*$res[1]==0);
       my @endofsubscriptiondate=split/-/,$expirationdate;
-      my $per = $subscription->{'periodicity'};
       my $x;
       if ( $per == 1 ) {$x=7;}
       if ( $per == 2 ) {$x=7; }
@@ -2309,7 +2373,7 @@ sub abouttoexpire {
       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);
+                    - (3 * $x)) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
               # warn "DATE BEFORE END: $datebeforeend";
       return 1 if ( @res && 
                     (@datebeforeend && 
@@ -2318,7 +2382,7 @@ sub abouttoexpire {
                     (@endofsubscriptiondate && 
                         Delta_Days($res[0],$res[1],$res[2],
                         $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
-      return 0;
+    return 0;
    } elsif ($subscription->{numberlength}>0) {
     return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
    } else {return 0}
@@ -2589,69 +2653,89 @@ sub GetNextDate(@) {
     my @resultdate;
 
     #       warn "DOW $dayofweek";
-    if ( $subscription->{periodicity} == 0 ) {
+    if ( $subscription->{periodicity} % 16 == 0 ) {  # 'without regularity' || 'irregular'
       return 0;
     }  
-    if ( $subscription->{periodicity} == 1 ) {
-        my $dayofweek = Day_of_Week( $year,$month, $day );
-        for ( my $i = 0 ; $i < @irreg ; $i++ ) {
-            $dayofweek = 0 if ( $dayofweek == 7 ); 
-            if ( in_array( ($dayofweek + 1), @irreg ) ) {
-                ($year,$month,$day) = Add_Delta_Days($year,$month, $day , 1 );
-                $dayofweek++;
-            }
-        }
-        @resultdate = Add_Delta_Days($year,$month, $day , 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 {    
+          for ( my $i = 0 ; $i < @irreg ; $i++ ) {
+              $dayofweek = 0 if ( $dayofweek == 7 ); 
+              if ( in_array( ($dayofweek + 1), @irreg ) ) {
+                  ($year,$month,$day) = Add_Delta_Days($year,$month, $day , 1 );
+                  $dayofweek++;
+              }
+          }
+          @resultdate = Add_Delta_Days($year,$month, $day , 1 );
+        }    
     }
+    #   1  week
     if ( $subscription->{periodicity} == 2 ) {
-        my ($wkno,$year) = Week_of_Year( $year,$month, $day );
-        for ( my $i = 0 ; $i < @irreg ; $i++ ) {
-            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);
-            }
-        }
-        @resultdate = Add_Delta_Days( $year,$month, $day, 7);
+        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);
+              }
+          }
+          @resultdate = Add_Delta_Days( $year,$month, $day, 7);
+        }        
     }
-    if ( $subscription->{periodicity} == 3 ) {
-        my ($wkno,$year) = Week_of_Year( $year,$month, $day );
-        for ( my $i = 0 ; $i < @irreg ; $i++ ) {
-            if ( $irreg[$i] == (($wkno!=50)?($wkno +2) % 52 :52)) {
-            ### BUGFIX was previously +1 ^
-                ($year,$month,$day) = Add_Delta_Days($year,$month, $day , 14 );
-                $wkno=(($wkno!=50)?($wkno +2) % 52 :52);
-            }
-        }
-        @resultdate = Add_Delta_Days($year,$month, $day , 14 );
+    #   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} : $@";}
+        else {    
+          for ( my $i = 0 ; $i < @irreg ; $i++ ) {
+              if ( $irreg[$i] == (($wkno!=50)?($wkno +2) % 52 :52)) {
+              ### BUGFIX was previously +1 ^
+                  ($year,$month,$day) = Add_Delta_Days($year,$month, $day , 14 );
+                  $wkno=(($wkno!=50)?($wkno +2) % 52 :52);
+              }
+          }
+          @resultdate = Add_Delta_Days($year,$month, $day , 14 );
+        }        
     }
+    #   1 / 3 weeks
     if ( $subscription->{periodicity} == 4 ) {
-        my ($wkno,$year) = Week_of_Year( $year,$month, $day );
-        for ( my $i = 0 ; $i < @irreg ; $i++ ) {
-            if ( $irreg[$i] == (($wkno!=49)?($wkno +3) % 52 :52)) {
-                ($year,$month,$day) = Add_Delta_Days($year,$month, $day , 21 );
-                $wkno=(($wkno!=49)?($wkno +3) % 52 :52);
-            }
-        }
-        @resultdate = Add_Delta_Days($year,$month, $day , 21 );
+        my ($wkno,$year) = eval {Week_of_Year( $year,$month, $day )};
+        if ($@){warn "annĂ©e mois jour : $year $month $day $subscription->{subscriptionid} : $@";}
+        else {    
+          for ( my $i = 0 ; $i < @irreg ; $i++ ) {
+              if ( $irreg[$i] == (($wkno!=49)?($wkno +3) % 52 :52)) {
+                  ($year,$month,$day) = Add_Delta_Days($year,$month, $day , 21 );
+                  $wkno=(($wkno!=49)?($wkno +3) % 52 :52);
+              }
+          }
+          @resultdate = Add_Delta_Days($year,$month, $day , 21 );
+        }        
     }
     my $tmpmonth=$month;
+    if ($year && $month && $day){
     if ( $subscription->{periodicity} == 5 ) {
-        for ( my $i = 0 ; $i < @irreg ; $i++ ) {
-            if ( $irreg[$i] == (($tmpmonth!=11)?($tmpmonth +1) % 12 :12)) {
-                ($year,$month,$day) = Add_Delta_YMD($year,$month, $day ,0,1,0 );
-                $tmpmonth=(($tmpmonth!=11)?($tmpmonth +1) % 12 :12);
-            }
-        }
-        @resultdate = Add_Delta_YMD($year,$month, $day ,0,1,0 );
+          for ( my $i = 0 ; $i < @irreg ; $i++ ) {
+              if ( $irreg[$i] == (($tmpmonth!=11)?($tmpmonth +1) % 12 :12)) {
+                  ($year,$month,$day) = Add_Delta_YMD($year,$month, $day ,0,1,0 );
+                  $tmpmonth=(($tmpmonth!=11)?($tmpmonth +1) % 12 :12);
+              }
+          }        
+          @resultdate = Add_Delta_YMD($year,$month, $day ,0,1,0 );
     }
     if ( $subscription->{periodicity} == 6 ) {
-        for ( my $i = 0 ; $i < @irreg ; $i++ ) {
-            if ( $irreg[$i] == (($tmpmonth!=10)?($tmpmonth +2) % 12 :12)) {
-                ($year,$month,$day) = Add_Delta_YMD($year,$month, $day ,0,2,0 );
-                $tmpmonth=(($tmpmonth!=10)?($tmpmonth + 2) % 12 :12);
-            }
-        }
-        @resultdate = Add_Delta_YMD($year,$month, $day, 0, 2,0 );
+          for ( my $i = 0 ; $i < @irreg ; $i++ ) {
+              if ( $irreg[$i] == (($tmpmonth!=10)?($tmpmonth +2) % 12 :12)) {
+                  ($year,$month,$day) = Add_Delta_YMD($year,$month, $day ,0,2,0 );
+                  $tmpmonth=(($tmpmonth!=10)?($tmpmonth + 2) % 12 :12);
+              }
+          }
+          @resultdate = Add_Delta_YMD($year,$month, $day, 0, 2,0 );
     }
     if ( $subscription->{periodicity} == 7 ) {
         for ( my $i = 0 ; $i < @irreg ; $i++ ) {
@@ -2687,7 +2771,9 @@ sub GetNextDate(@) {
     if ( $subscription->{periodicity} == 11 ) {
         @resultdate = Add_Delta_YM($year,$month, $day, 2, 0 );
     }
+    }  
     my $resultdate=sprintf("%04d-%02d-%02d",$resultdate[0],$resultdate[1],$resultdate[2]);
+      
 #     warn "dateNEXTSEQ : ".$resultdate;
     return "$resultdate";
 }
@@ -2717,11 +2803,8 @@ sub itemdata {
     return ($data);
 }
 
-END { }    # module clean-up code here (global destructor)
-
 1;
-
-=back
+__END__
 
 =head1 AUTHOR