Bug 32437: Add Objects for ImportAuths
[koha-ffzg.git] / cataloguing / additem.pl
index 7cf5c03..bbf801b 100755 (executable)
 use Modern::Perl;
 
 use CGI qw ( -utf8 );
+
 use C4::Auth qw( get_template_and_user haspermission );
-use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers );
-use C4::Biblio qw(
-    GetFrameworkCode
-    GetMarcBiblio
-    GetMarcFromKohaField
-    GetMarcStructure
-    IsMarcStructureInternal
-    ModBiblio
-);
-use C4::Context;
-use C4::Circulation qw( barcodedecode LostItem );
-use C4::Barcodes;
 use C4::Barcodes::ValueBuilder;
-use Koha::DateUtils qw( dt_from_string );
-use Koha::Items;
+use C4::Barcodes;
+use C4::Biblio qw( GetFrameworkCode GetMarcFromKohaField GetMarcStructure IsMarcStructureInternal ModBiblio );
+use C4::Circulation qw( barcodedecode LostItem );
+use C4::Context;
+use C4::Members;
+use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers );
+use C4::Search qw( enabled_staff_search_views );
+use Koha::Biblios;
+use Koha::Item::Templates;
 use Koha::ItemTypes;
 use Koha::Items;
+use Koha::Items;
 use Koha::Libraries;
 use Koha::Patrons;
 use Koha::SearchEngine::Indexer;
-use C4::Search qw( enabled_staff_search_views );
-use Storable qw( freeze thaw );
-use URI::Escape qw( uri_escape_utf8 );
-use C4::Members;
 use Koha::UI::Form::Builder::Item;
+use Koha::Result::Boolean;
 
-use MARC::File::XML;
-use URI::Escape qw( uri_escape_utf8 );
 use Encode qw( encode_utf8 );
-use MIME::Base64 qw( decode_base64url encode_base64url );
-use List::Util qw( first );
 use List::MoreUtils qw( any uniq );
+use List::Util qw( first );
+use MARC::File::XML;
+use MIME::Base64 qw( decode_base64url encode_base64url );
+use Storable qw( freeze thaw );
+use URI::Escape qw( uri_escape_utf8 );
 
 our $dbh = C4::Context->dbh;
 
@@ -86,6 +81,14 @@ sub add_item_to_item_group {
     )->store();
 }
 
+sub get_item_from_template {
+    my ( $template_id ) = @_;
+
+    my $template = Koha::Item::Templates->find($template_id);
+
+    return $template->decoded_contents if $template;
+}
+
 sub get_item_from_cookie {
     my ( $input ) = @_;
 
@@ -155,7 +158,15 @@ my ($template, $loggedinuser, $cookie)
 
 
 # Does the user have a restricted item editing permission?
-my $uid = Koha::Patrons->find( $loggedinuser )->userid;
+my $patron = Koha::Patrons->find( $loggedinuser );
+
+my $item = $itemnumber ? Koha::Items->find( $itemnumber ) : undef;
+if ( $item && !$patron->can_edit_items_from( $item->homebranch ) ) {
+    print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber");
+    exit;
+}
+
+my $uid = $patron->userid;
 my $restrictededition = $uid ? haspermission($uid,  {'editcatalogue' => 'edit_items_restricted'}) : undef;
 # In case user is a superlibrarian, editing is not restricted
 $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibrarian());
@@ -163,7 +174,7 @@ $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibra
 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
 
 our $tagslib = &GetMarcStructure(1,$frameworkcode);
-my $record = GetMarcBiblio({ biblionumber => $biblionumber });
+my $record = $biblio->metadata->record;
 
 output_and_exit_if_error( $input, $cookie, $template,
     { module => 'cataloguing', record => $record } );
@@ -175,12 +186,51 @@ my @errors; # store errors found while checking data BEFORE saving item.
 # Getting last created item cookie
 my $prefillitem = C4::Context->preference('PrefillItem');
 
+my $load_template_submit = $input->param('load_template_submit');
+my $delete_template_submit = $input->param('delete_template_submit');
+my $unload_template_submit = $input->param('unload_template_submit');
+my $use_template_for_session = $input->param('use_template_for_session') || $input->cookie('ItemEditorSessionTemplateId');
+my $template_id = $input->param('template_id') || $input->cookie('ItemEditorSessionTemplateId');
+if ( $delete_template_submit ) {
+    my $t = Koha::Item::Templates->find($template_id);
+    $t->delete if $t && ( $t->patron_id eq $loggedinuser || haspermission( $uid, { 'editcatalogue' => 'manage_item_editor_templates' } ) );
+    $template_id = undef;
+    $use_template_for_session = undef;
+}
+if ($load_template_submit || $unload_template_submit) {
+    $op = q{} if $template_id;
+
+    $template_id = undef if !$input->param('template_id');
+    $template_id = undef if $unload_template_submit;
+
+    # Unset the cookie if either no template id as submitted, or "use for session" checkbox as unchecked
+    my $cookie_value = $input->param('use_template_for_session') && $template_id ? $template_id : q{};
+    $use_template_for_session = $cookie_value;
+
+    # Update the cookie
+    my $template_cookie = $input->cookie(
+        -name     => 'ItemEditorSessionTemplateId',
+        -value    => $cookie_value,
+        -HttpOnly => 1,
+        -expires  => '',
+        -sameSite => 'Lax'
+    );
+
+    $cookie = [ $cookie, $template_cookie ];
+}
+$template->param(
+    template_id    => $template_id,
+    item_templates => Koha::Item::Templates->get_available($loggedinuser),
+    use_template_for_session => $use_template_for_session,
+);
+
 #-------------------------------------------------------------------------------
 if ($op eq "additem") {
 
     my $add_submit                 = $input->param('add_submit');
     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
+    my $save_as_template_submit    = $input->param('save_as_template_submit');
     my $number_of_copies           = $input->param('number_of_copies');
 
     my @columns = Koha::Items->columns;
@@ -208,8 +258,11 @@ if ($op eq "additem") {
             my @v = grep { $_ ne "" }
                 uniq $input->multi_param( "items." . $c );
 
-            next if !@v
-                && $c ne 'permanent_location'; # See 27837
+            next unless @v;
+
+            if ( $c eq 'permanent_location' ) { # See 27837
+                $item->make_column_dirty('permanent_location');
+            }
 
             $item->$c(join ' | ', @v);
         }
@@ -223,8 +276,38 @@ if ($op eq "additem") {
 
     $item->barcode(barcodedecode($item->barcode));
 
+    if ($save_as_template_submit) {
+        my $template_name       = $input->param('template_name');
+        my $template_is_shared  = $input->param('template_is_shared');
+        my $replace_template_id = $input->param('replace_template_id');
+
+        if ($replace_template_id) {
+            my $template = Koha::Item::Templates->find($replace_template_id);
+            $template->update(
+                {
+                    id             => $replace_template_id,
+                    is_shared      => $template_is_shared ? 1 : 0,
+                    contents       => $item->unblessed,
+                }
+            ) if $template && (
+                $template->patron_id eq $loggedinuser
+                ||
+                haspermission( $uid, { 'editcatalogue' => 'manage_item_editor_templates' } )
+            );
+        }
+        else {
+            my $template = Koha::Item::Template->new(
+                {
+                    name      => $template_name,
+                    patron_id => $loggedinuser,
+                    is_shared => $template_is_shared ? 1 : 0,
+                    contents  => $item->unblessed,
+                }
+            )->store();
+        }
+    }
     # If we have to add or add & duplicate, we add the item
-    if ( $add_submit || $add_duplicate_submit || $prefillitem) {
+    elsif ( $add_submit || $add_duplicate_submit || $prefillitem) {
 
         # check for item barcode # being unique
         if ( defined $item->barcode
@@ -410,7 +493,12 @@ if ($op eq "additem") {
 #-------------------------------------------------------------------------------
     # check that there is no issue on this item before deletion.
     my $item = Koha::Items->find($itemnumber);
-    my $deleted = $item->safe_delete;
+    my $deleted;
+    if( $item ) {
+        $deleted = $item->safe_delete;
+    } else {
+        $deleted = Koha::Result::Boolean->new(0)->add_message({ message => 'item_not_found' });
+    }
     if ( $deleted ) {
         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
         exit;
@@ -477,6 +565,10 @@ if ($op eq "additem") {
             my @v = map { ( defined $_ && $_ eq '' ) ? undef : $_ } $input->multi_param( "items." . $c );
             next unless @v;
 
+            if ( $c eq 'permanent_location' ) { # See 27837
+                $item->make_column_dirty('permanent_location');
+            }
+
             if ( scalar(@v) == 1 && not defined $v[0] ) {
                 delete $new_values->{$c};
             } else {
@@ -542,7 +634,9 @@ if ($op) {
 
 my @items;
 for my $item ( $biblio->items->as_list, $biblio->host_items->as_list ) {
-    push @items, $item->columns_to_str;
+    my $i = $item->columns_to_str;
+    $i->{nomod} = 1 unless $patron->can_edit_items_from($item->homebranch);
+    push @items, $i;
 }
 
 my @witness_attributes = uniq map {
@@ -579,13 +673,19 @@ my @header_value_loop = map {
 } sort keys %$subfieldcode_attribute_mappings;
 
 # Using last created item if it exists
-if (   $prefillitem
-    && $op ne "additem"
+if (
+    $op ne "additem"
     && $op ne "edititem"
     && $op ne "dupeitem" )
 {
-    my $item_from_cookie = get_item_from_cookie($input);
-    $current_item = $item_from_cookie if $item_from_cookie;
+    if ( $template_id ) {
+        my $item_from_template = get_item_from_template($template_id);
+        $current_item = $item_from_template if $item_from_template;
+    }
+    elsif ( $prefillitem ) {
+        my $item_from_cookie = get_item_from_cookie($input);
+        $current_item = $item_from_cookie if $item_from_cookie;
+    }
 }
 
 if ( $current_item->{more_subfields_xml} ) {
@@ -601,8 +701,6 @@ my $branchcode = $input->param('branch') || C4::Context->userenv->{branch};
 my @subfields_to_prefill;
 if ( $nextop eq 'additem' && $op ne 'dupeitem' && $prefillitem ) {
     @subfields_to_prefill = split(' ', C4::Context->preference('SubfieldsToUseWhenPrefill'));
-    # Setting to 1 element if SubfieldsToUseWhenPrefill is empty to prevent all the subfields to be prefilled
-    @subfields_to_prefill = ("") unless @subfields_to_prefill;
 }
 
 # Getting list of subfields to keep when restricted editing is enabled
@@ -626,6 +724,11 @@ my $subfields =
         ),
         prefill_with_default_values => 1,
         branch_limit => C4::Context->userenv->{"branch"},
+        (
+            $op eq 'dupeitem'
+            ? ( ignore_invisible_subfields => 1 )
+            : ()
+        ),
     }
 );