Bug 18181: Can't tell which subscriptions already have a routing list if seeing all...
[koha.git] / serials / subscription-add.pl
index fd338b0..f66b650 100755 (executable)
@@ -2,36 +2,36 @@
 
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 2 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY 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.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 use strict;
 use warnings;
 
-use CGI;
+use CGI qw ( -utf8 );
 use Date::Calc qw(Today Day_of_Year Week_of_Year Add_Delta_Days Add_Delta_YM);
 use C4::Koha;
 use C4::Biblio;
 use C4::Auth;
-use C4::Dates qw/format_date format_date_in_iso/;
 use C4::Acquisition;
 use C4::Output;
 use C4::Context;
-use C4::Branch; # GetBranches
 use C4::Serials;
 use C4::Serials::Frequency;
 use C4::Serials::Numberpattern;
 use C4::Letters;
+use Koha::AdditionalField;
+use Koha::DateUtils;
 use Carp;
 
 #use Smart::Comments;
@@ -41,7 +41,6 @@ my $op = $query->param('op') || '';
 my $dbh = C4::Context->dbh;
 my $sub_length;
 
-my @budgets;
 
 # Permission needed if it is a modification : edit_subscription
 # Permission needed otherwise (nothing or dup) : create_subscription
@@ -59,8 +58,6 @@ my ($template, $loggedinuser, $cookie)
 
 
 my $sub_on;
-my @subscription_types = (qw(issues weeks months));
-my @sub_type_data;
 
 my $subs;
 our $firstissuedate;
@@ -69,7 +66,8 @@ if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
 
     my $subscriptionid = $query->param('subscriptionid');
     $subs = GetSubscription($subscriptionid);
-## FIXME : Check rights to edit if mod. Could/Should display an error message.
+
+    ## FIXME : Check rights to edit if mod. Could/Should display an error message.
     if ($subs->{'cannotedit'} && $op eq 'modify'){
       carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
       print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
@@ -87,7 +85,6 @@ if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
       if (!defined $subs->{letter}) {
           $subs->{letter}= q{};
       }
-    letter_loop($subs->{'letter'}, $template);
     my $nextexpected = GetNextExpected($subscriptionid);
     $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
     $subs->{nextacquidate} = $nextexpected->{planneddate}  if($op eq 'modify');
@@ -122,32 +119,47 @@ if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
         my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
         $template->param( dont_export_field_loop => \@fields_id );
     }
+
+    my $letters = get_letter_loop( $subs->{letter} );
+    $template->param( letterloop => $letters );
+
 }
 
-my $onlymine=C4::Context->preference('IndependantBranches') &&
-             C4::Context->userenv &&
-             C4::Context->userenv->{flags} % 2 !=1 &&
-             C4::Context->userenv->{branch};
-my $branches = GetBranches($onlymine);
-my $branchloop;
-for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %{$branches}) {
-    my $selected = 0;
-    $selected = 1 if (defined($subs) && $thisbranch eq $subs->{'branchcode'});
-    push @{$branchloop}, {
-        value => $thisbranch,
-        selected => $selected,
-        branchname => $branches->{$thisbranch}->{'branchname'},
-    };
+my $locations_loop = GetAuthorisedValues("LOC");
+
+$template->param(
+    branchcode => $subs->{branchcode},
+    locations_loop=>$locations_loop,
+);
+
+
+my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
+for my $field ( @$additional_fields ) {
+    if ( $field->{authorised_value_category} ) {
+        $field->{authorised_value_choices} = GetAuthorisedValues( $field->{authorised_value_category} );
+    }
 }
+$template->param( additional_fields_for_subscription => $additional_fields );
+
+my $typeloop = GetItemTypes();
 
-my $locations_loop = GetAuthorisedValues("LOC",$subs->{'location'});
+my @typearg =
+    map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{itemtype} and $_ eq $subs->{itemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
+my @previoustypearg =
+    map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{previousitemtype} and $_ eq $subs->{previousitemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
 
-$template->param(branchloop => $branchloop,
+$template->param(
+    typeloop                 => \@typearg,
+    previoustypeloop         => \@previoustypearg,
     locations_loop=>$locations_loop,
 );
+
 # prepare template variables common to all $op conditions:
+$template->param('makePreviousSerialAvailable' => 1) if (C4::Context->preference('makePreviousSerialAvailable'));
+
 if ($op!~/^mod/) {
-    letter_loop(q{}, $template);
+    my $letters = get_letter_loop();
+    $template->param( letterloop => $letters );
 }
 
 if ($op eq 'addsubscription') {
@@ -155,19 +167,16 @@ if ($op eq 'addsubscription') {
 } elsif ($op eq 'modsubscription') {
     redirect_mod_subscription();
 } else {
-        while (@subscription_types) {
-           my $sub_type = shift @subscription_types;
-           my %row = ( 'name' => $sub_type );
-           if ( defined $sub_on and $sub_on eq $sub_type ) {
-            $row{'selected'} = ' selected';
-           } else {
-            $row{'selected'} = '';
-           }
-           push( @sub_type_data, \%row );
-        }
-    $template->param(subtype => \@sub_type_data);
 
-    letter_loop( '', $template ) if ($op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify');
+    $template->param(
+        subtypes => [ qw( numberlength weeklength monthlength ) ],
+        subtype => $sub_on,
+    );
+
+    if ( $op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify' ) {
+        my $letters = get_letter_loop();
+        $template->param( letterloop => $letters );
+    }
 
     my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
     if (defined $new_biblionumber) {
@@ -208,32 +217,31 @@ if ($op eq 'addsubscription') {
     }
     $template->param(numberpatterns => \@numberpatternloop);
 
-    # Get installed locales
-    # FIXME this will not work with all environments.
-    # If call to locale fails, @locales will be an empty array, which is fine.
-    my @locales = map {
-        chomp;
-        # we don't want POSIX and C locales
-        /^C|^POSIX$/ ? () : $_
-    } `locale -a`;
-    $template->param(locales => \@locales);
+    my $languages = [ map {
+        {
+            language => $_->{iso639_2_code},
+            description => $_->{language_description} || $_->{language}
+        }
+    } @{ C4::Languages::getAllLanguages() } ];
+
+    $template->param( locales => $languages );
 
     output_html_with_http_headers $query, $cookie, $template->output;
 }
 
-sub letter_loop {
-    my ($selected_letter, $templte) = @_;
-    my $letters = GetLetters('serial');
-    my $letterloop;
-    foreach my $thisletter (keys %{$letters}) {
-        push @{$letterloop}, {
-            value => $thisletter,
-            selected => $thisletter eq $selected_letter,
-            lettername => $letters->{$thisletter},
-        };
-    }
-    $templte->param(letterloop => $letterloop);
-    return;
+sub get_letter_loop {
+    my ($selected_lettercode) = @_;
+    $selected_lettercode //= '';
+    my $letters = GetLetters({ module => 'serial' });
+    return [
+        map {
+            {
+                value      => $_->{code},
+                lettername => $_->{name},
+                ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
+            }
+          } @$letters
+    ];
 }
 
 sub _get_sub_length {
@@ -281,7 +289,7 @@ sub redirect_add_subscription {
     my $cost           = $query->param('cost');
     my $aqbudgetid     = $query->param('aqbudgetid');
     my $periodicity    = $query->param('frequency');
-    my @irregularity   = $query->param('irregularity');
+    my @irregularity   = $query->multi_param('irregularity');
     my $numberpattern  = $query->param('numbering_pattern');
     my $locale         = $query->param('locale');
     my $graceperiod    = $query->param('graceperiod') || 0;
@@ -308,15 +316,19 @@ sub redirect_add_subscription {
     my $staffdisplaycount = $query->param('staffdisplaycount');
     my $opacdisplaycount  = $query->param('opacdisplaycount');
     my $location          = $query->param('location');
+    my $itemtype          = $query->param('itemtype');
+    my $previousitemtype  = $query->param('previousitemtype');
     my $skip_serialseq    = $query->param('skip_serialseq');
-    my $startdate = format_date_in_iso( $query->param('startdate') );
-    my $enddate = format_date_in_iso( $query->param('enddate') );
-    my $firstacquidate  = format_date_in_iso($query->param('firstacquidate'));
+
+    my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
+    my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
+    my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
+
     if(!defined $enddate || $enddate eq '') {
         if($subtype eq "issues") {
-            $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
+            $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
         } else {
-            $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
+            $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
         }
     }
 
@@ -331,26 +343,33 @@ sub redirect_add_subscription {
         $skip_serialseq
     );
 
+    my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
+    insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
+
     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
     return;
 }
 
 sub redirect_mod_subscription {
     my $subscriptionid = $query->param('subscriptionid');
-    my @irregularity = $query->param('irregularity');
+    my @irregularity = $query->multi_param('irregularity');
     my $auser = $query->param('user');
-    my $librarian => $query->param('librarian'),
+    my $librarian => scalar $query->param('librarian'),
     my $branchcode = $query->param('branchcode');
     my $cost = $query->param('cost');
     my $aqbooksellerid = $query->param('aqbooksellerid');
     my $biblionumber = $query->param('biblionumber');
     my $aqbudgetid = $query->param('aqbudgetid');
-    my $startdate = format_date_in_iso($query->param('startdate'));
-    my $firstacquidate = format_date_in_iso( $query->param('firstacquidate') );
-    my $nextacquidate = $query->param('nextacquidate') ?
-                            format_date_in_iso($query->param('nextacquidate')):
-                            $firstacquidate;
-    my $enddate = format_date_in_iso($query->param('enddate'));
+
+    my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
+    my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
+    my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
+
+    my $nextacquidate  = $query->param('nextacquidate');
+    $nextacquidate = $nextacquidate
+        ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
+        : $firstacquidate;
+
     my $periodicity = $query->param('frequency');
 
     my $subtype = $query->param('subtype');
@@ -376,6 +395,8 @@ sub redirect_mod_subscription {
        my $opacdisplaycount = $query->param('opacdisplaycount');
     my $graceperiod     = $query->param('graceperiod') || 0;
     my $location = $query->param('location');
+    my $itemtype          = $query->param('itemtype');
+    my $previousitemtype  = $query->param('previousitemtype');
     my $skip_serialseq    = $query->param('skip_serialseq');
 
     # Guess end date
@@ -403,9 +424,35 @@ sub redirect_mod_subscription {
         $status, $biblionumber, $callnumber, $notes, $letter,
         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
-        $skip_serialseq
+        $skip_serialseq, $itemtype, $previousitemtype
     );
 
+    my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
+    insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
+
     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
     return;
 }
+
+sub insert_additional_fields {
+    my ( $additional_fields, $biblionumber, $subscriptionid ) = @_;
+    my $record = GetMarcBiblio( $biblionumber, 1 );
+    for my $field ( @$additional_fields ) {
+        my $af = Koha::AdditionalField->new({ id => $field->{id} })->fetch;
+        if ( $af->{marcfield} ) {
+            my ( $field, $subfield ) = split /\$/, $af->{marcfield};
+            $af->{values} = undef;
+            if ( $field and $subfield ) {
+                my $value = $record->subfield( $field, $subfield );
+                $af->{values} = {
+                    $subscriptionid => $value
+                };
+            }
+        } else {
+            $af->{values} = {
+                $subscriptionid => scalar $query->param('additional_field_' . $field->{id})
+            } if defined $query->param('additional_field_' . $field->{id});
+        }
+        $af->insert_values;
+    }
+}