Bug 32401: Remove x-koha-query support
[koha.git] / cataloguing / additem.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use Modern::Perl;
23
24 use CGI qw ( -utf8 );
25
26 use C4::Auth qw( get_template_and_user haspermission );
27 use C4::Barcodes::ValueBuilder;
28 use C4::Barcodes;
29 use C4::Biblio qw( GetFrameworkCode GetMarcFromKohaField GetMarcStructure IsMarcStructureInternal ModBiblio );
30 use C4::Circulation qw( barcodedecode LostItem );
31 use C4::Context;
32 use C4::Members;
33 use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers );
34 use C4::Search qw( enabled_staff_search_views );
35 use Koha::Biblios;
36 use Koha::Item::Templates;
37 use Koha::ItemTypes;
38 use Koha::Items;
39 use Koha::Items;
40 use Koha::Libraries;
41 use Koha::Patrons;
42 use Koha::SearchEngine::Indexer;
43 use Koha::UI::Form::Builder::Item;
44 use Koha::Result::Boolean;
45
46 use Encode qw( encode_utf8 );
47 use List::MoreUtils qw( any uniq );
48 use List::Util qw( first );
49 use MARC::File::XML;
50 use MIME::Base64 qw( decode_base64url encode_base64url );
51 use Storable qw( freeze thaw );
52 use URI::Escape qw( uri_escape_utf8 );
53
54 our $dbh = C4::Context->dbh;
55
56 sub add_item_to_item_group {
57     my ( $biblionumber, $itemnumber, $item_group, $item_group_description ) = @_;
58
59     return unless $item_group;
60
61     my $item_group_id;
62     if ( $item_group eq 'create' ) {
63         my $item_group = Koha::Biblio::ItemGroup->new(
64             {
65                 biblionumber => $biblionumber,
66                 description  => $item_group_description,
67             }
68         )->store();
69
70         $item_group_id = $item_group->id;
71     }
72     else {
73         $item_group_id = $item_group;
74     }
75
76     my $item_group_item = Koha::Biblio::ItemGroup::Item->new(
77         {
78             itemnumber => $itemnumber,
79             item_group_id  => $item_group_id,
80         }
81     )->store();
82 }
83
84 sub get_item_from_template {
85     my ( $template_id ) = @_;
86
87     my $template = Koha::Item::Templates->find($template_id);
88
89     return $template->decoded_contents if $template;
90 }
91
92 sub get_item_from_cookie {
93     my ( $input ) = @_;
94
95     my $item_from_cookie;
96     my $lastitemcookie = $input->cookie('LastCreatedItem');
97     if ($lastitemcookie) {
98         $lastitemcookie = decode_base64url($lastitemcookie);
99         eval {
100             if ( thaw($lastitemcookie) ) {
101                 $item_from_cookie = thaw($lastitemcookie);
102             }
103         };
104         if ($@) {
105             $lastitemcookie ||= 'undef';
106             warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '".encode_base64url($lastitemcookie)."'. Caught error follows: '$@'";
107         }
108     }
109     return $item_from_cookie;
110 }
111
112 my $input        = CGI->new;
113
114 my $biblionumber;
115 my $itemnumber;
116 if( $input->param('itemnumber') && !$input->param('biblionumber') ){
117     $itemnumber = $input->param('itemnumber');
118     my $item = Koha::Items->find( $itemnumber );
119     $biblionumber = $item->biblionumber;
120 } else {
121     $biblionumber = $input->param('biblionumber');
122     $itemnumber = $input->param('itemnumber');
123 }
124
125 my $biblio = Koha::Biblios->find($biblionumber);
126
127 my $op           = $input->param('op') || q{};
128 my $hostitemnumber = $input->param('hostitemnumber');
129 my $marcflavour  = C4::Context->preference("marcflavour");
130 my $searchid     = $input->param('searchid');
131 # fast cataloguing datas
132 my $fa_circborrowernumber = $input->param('circborrowernumber');
133 my $fa_barcode            = $input->param('barcode');
134 my $fa_branch             = $input->param('branch');
135 my $fa_stickyduedate      = $input->param('stickyduedate');
136 my $fa_duedatespec        = $input->param('duedatespec');
137 my $volume                = $input->param('volume');
138 my $volume_description    = $input->param('volume_description');
139
140 our $frameworkcode = &GetFrameworkCode($biblionumber);
141
142 # Defining which userflag is needing according to the framework currently used
143 my $userflags;
144 if (defined $input->param('frameworkcode')) {
145     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
146 }
147
148 if (not defined $userflags) {
149     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
150 }
151
152 my ($template, $loggedinuser, $cookie)
153     = get_template_and_user({template_name => "cataloguing/additem.tt",
154                  query => $input,
155                  type => "intranet",
156                  flagsrequired => {editcatalogue => $userflags},
157                  });
158
159
160 # Does the user have a restricted item editing permission?
161 my $patron = Koha::Patrons->find( $loggedinuser );
162
163 my $item = $itemnumber ? Koha::Items->find( $itemnumber ) : undef;
164 if ( $item && !$patron->can_edit_item( $item ) ) {
165     print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber");
166     exit;
167 }
168
169 my $uid = $patron->userid;
170 my $restrictededition = $uid ? haspermission($uid,  {'editcatalogue' => 'edit_items_restricted'}) : undef;
171 # In case user is a superlibrarian, editing is not restricted
172 $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibrarian());
173 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
174 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
175
176 our $tagslib = &GetMarcStructure(1,$frameworkcode);
177 my $record = $biblio->metadata->record;
178
179 output_and_exit_if_error( $input, $cookie, $template,
180     { module => 'cataloguing', record => $record } );
181
182 my $current_item;
183 my $nextop="additem";
184 my @errors; # store errors found while checking data BEFORE saving item.
185
186 # Getting last created item cookie
187 my $prefillitem = C4::Context->preference('PrefillItem');
188
189 my $load_template_submit = $input->param('load_template_submit');
190 my $delete_template_submit = $input->param('delete_template_submit');
191 my $unload_template_submit = $input->param('unload_template_submit');
192 my $use_template_for_session = $input->param('use_template_for_session') || $input->cookie('ItemEditorSessionTemplateId');
193 my $template_id = $input->param('template_id') || $input->cookie('ItemEditorSessionTemplateId');
194 if ( $delete_template_submit ) {
195     my $t = Koha::Item::Templates->find($template_id);
196     $t->delete if $t && ( $t->patron_id eq $loggedinuser || haspermission( $uid, { 'editcatalogue' => 'manage_item_editor_templates' } ) );
197     $template_id = undef;
198     $use_template_for_session = undef;
199 }
200 if ($load_template_submit || $unload_template_submit) {
201     $op = q{} if $template_id;
202
203     $template_id = undef if !$input->param('template_id');
204     $template_id = undef if $unload_template_submit;
205
206     # Unset the cookie if either no template id as submitted, or "use for session" checkbox as unchecked
207     my $cookie_value = $input->param('use_template_for_session') && $template_id ? $template_id : q{};
208     $use_template_for_session = $cookie_value;
209
210     # Update the cookie
211     my $template_cookie = $input->cookie(
212         -name     => 'ItemEditorSessionTemplateId',
213         -value    => $cookie_value,
214         -HttpOnly => 1,
215         -expires  => '',
216         -sameSite => 'Lax'
217     );
218
219     $cookie = [ $cookie, $template_cookie ];
220 }
221 $template->param(
222     template_id    => $template_id,
223     item_templates => Koha::Item::Templates->get_available($loggedinuser),
224     use_template_for_session => $use_template_for_session,
225 );
226
227 #-------------------------------------------------------------------------------
228 if ($op eq "additem") {
229
230     my $add_submit                 = $input->param('add_submit');
231     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
232     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
233     my $save_as_template_submit    = $input->param('save_as_template_submit');
234     my $number_of_copies           = $input->param('number_of_copies');
235
236     my @columns = Koha::Items->columns;
237     my $item = Koha::Item->new;
238     $item->biblionumber($biblio->biblionumber);
239     for my $c ( @columns ) {
240         if ( $c eq 'more_subfields_xml' ) {
241             my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
242             my @unlinked_item_subfields;
243             for my $subfield ( @more_subfields_xml ) {
244                 my $v = $input->param('items.more_subfields_xml_' . $subfield);
245                 push @unlinked_item_subfields, $subfield, $v;
246             }
247             if ( @unlinked_item_subfields ) {
248                 my $marc = MARC::Record->new();
249                 # use of tag 999 is arbitrary, and doesn't need to match the item tag
250                 # used in the framework
251                 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
252                 $marc->encoding("UTF-8");
253                 $item->more_subfields_xml($marc->as_xml("USMARC"));
254                 next;
255             }
256             $item->more_subfields_xml(undef);
257         } else {
258             my @v = grep { $_ ne "" }
259                 uniq $input->multi_param( "items." . $c );
260
261             next unless @v;
262
263             if ( $c eq 'permanent_location' ) { # See 27837
264                 $item->make_column_dirty('permanent_location');
265             }
266
267             $item->$c(join ' | ', @v);
268         }
269     }
270
271     # if autoBarcode is set to 'incremental', calculate barcode...
272     if ( ! defined $item->barcode && C4::Context->preference('autoBarcode') eq 'incremental' ) {
273         my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
274         $item->barcode($barcode);
275     }
276
277     $item->barcode(barcodedecode($item->barcode));
278
279     if ($save_as_template_submit) {
280         my $template_name       = $input->param('template_name');
281         my $template_is_shared  = $input->param('template_is_shared');
282         my $replace_template_id = $input->param('replace_template_id');
283
284         if ($replace_template_id) {
285             my $template = Koha::Item::Templates->find($replace_template_id);
286             $template->update(
287                 {
288                     id             => $replace_template_id,
289                     is_shared      => $template_is_shared ? 1 : 0,
290                     contents       => $item->unblessed,
291                 }
292             ) if $template && (
293                 $template->patron_id eq $loggedinuser
294                 ||
295                 haspermission( $uid, { 'editcatalogue' => 'manage_item_editor_templates' } )
296             );
297         }
298         else {
299             my $template = Koha::Item::Template->new(
300                 {
301                     name      => $template_name,
302                     patron_id => $loggedinuser,
303                     is_shared => $template_is_shared ? 1 : 0,
304                     contents  => $item->unblessed,
305                 }
306             )->store();
307         }
308     }
309     # If we have to add or add & duplicate, we add the item
310     elsif ( $add_submit || $add_duplicate_submit || $prefillitem) {
311
312         # check for item barcode # being unique
313         if ( defined $item->barcode
314             && Koha::Items->search( { barcode => $item->barcode } )->count )
315         {
316             # if barcode exists, don't create, but report The problem.
317             push @errors, "barcode_not_unique";
318
319             $current_item = $item->unblessed; # Restore edit form for the same item
320         }
321         else {
322             $item->store->discard_changes;
323             add_item_to_item_group( $item->biblionumber, $item->biblioitemnumber, $volume, $volume_description );
324
325             # This is a bit tricky : if there is a cookie for the last created item and
326             # we just added an item, the cookie value is not correct yet (it will be updated
327             # next page). To prevent the form from being filled with outdated values, we
328             # force the use of "add and duplicate" feature, so the form will be filled with
329             # correct values.
330
331             # Pushing the last created item cookie back
332             if ( $prefillitem ) {
333                 my $last_created_item_cookie = $input->cookie(
334                     -name => 'LastCreatedItem',
335                     # We encode_base64url the whole freezed structure so we're sure we won't have any encoding problems
336                     -value   => encode_base64url( freeze( { %{$item->unblessed}, itemnumber => undef } ) ),
337                     -HttpOnly => 1,
338                     -expires => '',
339                     -sameSite => 'Lax'
340                 );
341
342                 $cookie = [ $cookie, $last_created_item_cookie ];
343             }
344
345         }
346         $nextop = "additem";
347
348     }
349
350     # If we have to add & duplicate
351     if ($prefillitem || $add_duplicate_submit) {
352
353         $current_item = $item->unblessed;
354
355         if (C4::Context->preference('autoBarcode') eq 'incremental') {
356             my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
357             $current_item->{barcode} = $barcode;
358         }
359         else {
360             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
361             $current_item->{barcode} = undef; # FIXME or delete?
362         }
363
364         # Don't use the "prefill" feature if we want to generate the form with all the info from this item
365         # It will remove subfields that are not in SubfieldsToUseWhenPrefill.
366         $prefillitem = 0 if $add_duplicate_submit;
367     }
368
369     # If we have to add multiple copies
370     if ($add_multiple_copies_submit) {
371
372         $current_item = $item->unblessed;
373
374         my $copynumber = $current_item->{copynumber};
375         my $oldbarcode = $current_item->{barcode};
376
377         # If there is a barcode and we can't find their new values, we can't add multiple copies
378         my $testbarcode;
379         my $barcodeobj = C4::Barcodes->new;
380         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
381         if ( $oldbarcode && !$testbarcode ) {
382
383             push @errors, "no_next_barcode";
384
385         }
386         else {
387             # We add each item
388
389             # For the first iteration
390             my $barcodevalue = $oldbarcode;
391             my $exist_itemnumber;
392
393             for ( my $i = 0 ; $i < $number_of_copies ; ) {
394
395                 # If there is a barcode
396                 if ($barcodevalue) {
397
398 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
399                     $barcodevalue = $barcodeobj->next_value($oldbarcode)
400                       if ( $i > 0 || $exist_itemnumber );
401
402                     # Putting it into the record
403                     if ($barcodevalue) {
404                         if ( C4::Context->preference("autoBarcode") eq
405                             'hbyymmincr' && $i > 0 )
406                         { # The first copy already contains the homebranch prefix
407                              # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
408                              # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
409                              # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
410                              # But when adding multiple copies we need to prefix it here,
411                              # so we retrieve the homebranch from the item and prefix the barcode with it.
412                             my $homebranch = $current_item->{homebranch};
413                             $barcodevalue = $homebranch . $barcodevalue;
414                         }
415                         $current_item->{barcode} = $barcodevalue;
416                     }
417
418                     # Checking if the barcode already exists
419                     $exist_itemnumber = Koha::Items->search({ barcode => $barcodevalue })->count;
420                 }
421
422                 # Updating record with the new copynumber
423                 if ($copynumber) {
424                     $current_item->{copynumber} = $copynumber;
425                 }
426
427                 # Adding the item
428                 if ( !$exist_itemnumber ) {
429                     delete $current_item->{itemnumber};
430                     $current_item = Koha::Item->new($current_item)->store(
431                         { skip_record_index => 1 } );
432                     $current_item->discard_changes; # Cannot chain discard_changes
433                     $current_item = $current_item->unblessed;
434                     add_item_to_item_group( $item->biblionumber, $item->biblioitemnumber, $volume, $volume_description );
435
436 # We count the item only if it was really added
437 # That way, all items are added, even if there was some already existing barcodes
438 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
439                     $i++;
440
441                     # Only increment copynumber if item was really added
442                     $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
443                 }
444
445                 # Preparing the next iteration
446                 $oldbarcode = $barcodevalue;
447             }
448
449             my $indexer = Koha::SearchEngine::Indexer->new(
450                 { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
451             $indexer->index_records( $biblionumber, "specialUpdate",
452                 "biblioserver" );
453
454             undef($current_item);
455         }
456     }
457     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
458         print $input->redirect(
459            '/cgi-bin/koha/circ/circulation.pl?'
460            .'borrowernumber='.$fa_circborrowernumber
461            .'&barcode='.uri_escape_utf8($fa_barcode)
462            .'&duedatespec='.$fa_duedatespec
463            .'&stickyduedate='.$fa_stickyduedate
464         );
465         exit;
466     }
467
468
469 #-------------------------------------------------------------------------------
470 } elsif ($op eq "edititem") {
471 #-------------------------------------------------------------------------------
472 # retrieve item if exist => then, it's a modif
473     $current_item = Koha::Items->find($itemnumber)->unblessed;
474     # FIXME Handle non existent item
475     $nextop = "saveitem";
476 #-------------------------------------------------------------------------------
477 } elsif ($op eq "dupeitem") {
478 #-------------------------------------------------------------------------------
479 # retrieve item if exist => then, it's a modif
480     $current_item = Koha::Items->find($itemnumber)->unblessed;
481     # FIXME Handle non existent item
482     if (C4::Context->preference('autoBarcode') eq 'incremental') {
483         my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
484         $current_item->{barcode} = $barcode;
485     }
486     else {
487         $current_item->{barcode} = undef; # Don't save it!
488     }
489
490     $nextop = "additem";
491 #-------------------------------------------------------------------------------
492 } elsif ($op eq "delitem") {
493 #-------------------------------------------------------------------------------
494     # check that there is no issue on this item before deletion.
495     my $item = Koha::Items->find($itemnumber);
496     my $deleted;
497     if( $item ) {
498         $deleted = $item->safe_delete;
499     } else {
500         $deleted = Koha::Result::Boolean->new(0)->add_message({ message => 'item_not_found' });
501     }
502     if ( $deleted ) {
503         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
504         exit;
505     }
506     else {
507         push @errors, @{ $deleted->messages }[0]->message;
508         $nextop = "additem";
509     }
510 #-------------------------------------------------------------------------------
511 } elsif ($op eq "delallitems") {
512 #-------------------------------------------------------------------------------
513     my $items = Koha::Items->search({ biblionumber => $biblionumber });
514     while ( my $item = $items->next ) {
515         my $deleted = $item->safe_delete({ skip_record_index => 1 });
516         push @errors, @{$deleted->messages}[0]->message unless $deleted;
517     }
518     my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
519     $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
520     if ( @errors ) {
521         $nextop="additem";
522     } else {
523         my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
524         my $views = { C4::Search::enabled_staff_search_views };
525         if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
526             print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
527         } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
528             print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
529         } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
530             print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
531         } else {
532             print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
533         }
534         exit;
535     }
536 #-------------------------------------------------------------------------------
537 } elsif ($op eq "saveitem") {
538 #-------------------------------------------------------------------------------
539
540     my $itemnumber = $input->param('itemnumber');
541     my $item = Koha::Items->find($itemnumber);
542     # FIXME Handle non existent item
543     my $olditemlost = $item->itemlost;
544     my @columns = Koha::Items->columns;
545     my $new_values = $item->unblessed;
546     for my $c ( @columns ) {
547         if ( $c eq 'more_subfields_xml' ) {
548             my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
549             my @unlinked_item_subfields;
550             for my $subfield ( uniq @more_subfields_xml ) {
551                 my @v = $input->multi_param('items.more_subfields_xml_' . encode_utf8($subfield));
552                 push @unlinked_item_subfields, $subfield, $_ for @v;
553             }
554             if ( @unlinked_item_subfields ) {
555                 my $marc = MARC::Record->new();
556                 # use of tag 999 is arbitrary, and doesn't need to match the item tag
557                 # used in the framework
558                 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
559                 $marc->encoding("UTF-8");
560                 $new_values->{more_subfields_xml} = $marc->as_xml("USMARC");
561                 next;
562             }
563             $item->more_subfields_xml(undef);
564         } else {
565             my @v = map { ( defined $_ && $_ eq '' ) ? undef : $_ } $input->multi_param( "items." . $c );
566             next unless @v;
567
568             if ( $c eq 'permanent_location' ) { # See 27837
569                 $item->make_column_dirty('permanent_location');
570             }
571
572             if ( scalar(@v) == 1 && not defined $v[0] ) {
573                 delete $new_values->{$c};
574             } else {
575                 $new_values->{$c} = join ' | ', @v;
576             }
577         }
578     }
579     $item = $item->set_or_blank($new_values);
580
581     # check that the barcode don't exist already
582     if (
583         defined $item->barcode
584         && Koha::Items->search(
585             {
586                 barcode    => $item->barcode,
587                 itemnumber => { '!=' => $item->itemnumber }
588             }
589         )->count
590       )
591     {
592         # FIXME We shouldn't need that, ->store would explode as there is a unique constraint on items.barcode
593         push @errors,"barcode_not_unique";
594         $current_item = $item->unblessed; # Restore edit form for the same item
595     } else {
596         my $newitemlost = $item->itemlost;
597         if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
598             LostItem( $item->itemnumber, 'additem' );
599         }
600         $item->store;
601     }
602
603     $nextop="additem";
604 } elsif ($op eq "delinkitem"){
605
606     my $analyticfield = '773';
607     if ($marcflavour  eq 'MARC21'){
608         $analyticfield = '773';
609     } elsif ($marcflavour eq 'UNIMARC') {
610         $analyticfield = '461';
611     }
612     foreach my $field ($record->field($analyticfield)){
613         if ($field->subfield('9') eq $hostitemnumber){
614             $record->delete_field($field);
615             last;
616         }
617     }
618         my $modbibresult = ModBiblio($record, $biblionumber,'');
619 }
620
621 # update OAI-PMH sets
622 if ($op) {
623     if (C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
624         C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
625     }
626 }
627
628 #
629 #-------------------------------------------------------------------------------
630 # build screen with existing items. and "new" one
631 #-------------------------------------------------------------------------------
632
633 # now, build existiing item list
634
635 my @items;
636 for my $item ( $biblio->items->as_list, $biblio->host_items->as_list ) {
637     my $i = $item->columns_to_str;
638     $i->{nomod} = 1 unless $patron->can_edit_item($item);
639     push @items, $i;
640 }
641
642 my @witness_attributes = uniq map {
643     my $item = $_;
644     map { defined $item->{$_} && $item->{$_} ne "" ? $_ : () } keys %$item
645 } @items;
646
647 our ( $itemtagfield, $itemtagsubfield ) = GetMarcFromKohaField("items.itemnumber");
648
649 my $subfieldcode_attribute_mappings;
650 for my $subfield_code ( keys %{ $tagslib->{$itemtagfield} } ) {
651
652     my $subfield = $tagslib->{$itemtagfield}->{$subfield_code};
653
654     next if IsMarcStructureInternal( $subfield );
655     next unless $subfield->{tab} eq 10; # Is this really needed?
656
657     my $attribute;
658     if ( $subfield->{kohafield} ) {
659         ( $attribute = $subfield->{kohafield} ) =~ s|^items\.||;
660     } else {
661         $attribute = $subfield_code; # It's in more_subfields_xml
662     }
663     next unless grep { $attribute eq $_ } @witness_attributes;
664     $subfieldcode_attribute_mappings->{$subfield_code} = $attribute;
665 }
666
667 my @header_value_loop = map {
668     {
669         header_value  => $tagslib->{$itemtagfield}->{$_}->{lib},
670         attribute     => $subfieldcode_attribute_mappings->{$_},
671         subfield_code => $_,
672     }
673 } sort keys %$subfieldcode_attribute_mappings;
674
675 # Using last created item if it exists
676 if (
677     $op ne "additem"
678     && $op ne "edititem"
679     && $op ne "dupeitem" )
680 {
681     if ( $template_id ) {
682         my $item_from_template = get_item_from_template($template_id);
683         $current_item = $item_from_template if $item_from_template;
684     }
685     elsif ( $prefillitem ) {
686         my $item_from_cookie = get_item_from_cookie($input);
687         $current_item = $item_from_cookie if $item_from_cookie;
688     }
689 }
690
691 if ( $current_item->{more_subfields_xml} ) {
692     # FIXME Use Maybe MARC::Record::new_from_xml if encoding issues on subfield (??)
693     $current_item->{marc_more_subfields_xml} = MARC::Record->new_from_xml($current_item->{more_subfields_xml}, 'UTF-8');
694 }
695
696 my $branchcode = $input->param('branch') || C4::Context->userenv->{branch};
697
698 # If we are not adding a new item
699 # OR
700 # If the subfield must be prefilled with last catalogued item
701 my @subfields_to_prefill;
702 if ( $nextop eq 'additem' && $op ne 'dupeitem' && $prefillitem ) {
703     @subfields_to_prefill = split(' ', C4::Context->preference('SubfieldsToUseWhenPrefill'));
704 }
705
706 # Getting list of subfields to keep when restricted editing is enabled
707 my @subfields_to_allow = $restrictededition ? split ' ', C4::Context->preference('SubfieldsToAllowForRestrictedEditing') : ();
708
709 my $subfields =
710   Koha::UI::Form::Builder::Item->new(
711     { biblionumber => $biblionumber, item => $current_item } )->edit_form(
712     {
713         branchcode           => $branchcode,
714         restricted_editition => $restrictededition,
715         (
716             @subfields_to_allow
717             ? ( subfields_to_allow => \@subfields_to_allow )
718             : ()
719         ),
720         (
721             @subfields_to_prefill
722             ? ( subfields_to_prefill => \@subfields_to_prefill )
723             : ()
724         ),
725         prefill_with_default_values => 1,
726         branch_limit => C4::Context->userenv->{"branch"},
727         (
728             $op eq 'dupeitem'
729             ? ( ignore_invisible_subfields => 1 )
730             : ()
731         ),
732     }
733 );
734
735 if (   $frameworkcode eq 'FA' ) {
736     my ( $barcode_field ) = grep {$_->{kohafield} eq 'items.barcode'} @$subfields;
737     $barcode_field->{marc_value}->{value} ||= $input->param('barcode');
738 }
739
740 if( my $default_location = C4::Context->preference('NewItemsDefaultLocation') ) {
741     my ( $location_field ) = grep {$_->{kohafield} eq 'items.location'} @$subfields;
742     $location_field->{marc_value}->{value} ||= $default_location;
743 }
744
745 my @ig = Koha::Biblio::ItemGroups->search({ biblio_id => $biblionumber })->as_list();
746 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
747 $template->param(
748     biblio       => $biblio,
749     items        => \@items,
750     item_groups      => \@ig,
751     item_header_loop => \@header_value_loop,
752     subfields        => $subfields,
753     itemnumber       => $itemnumber,
754     barcode          => $current_item->{barcode},
755     op      => $nextop,
756     popup => scalar $input->param('popup') ? 1: 0,
757     C4::Search::enabled_staff_search_views,
758 );
759 $template->{'VARS'}->{'searchid'} = $searchid;
760
761 if ($frameworkcode eq 'FA'){
762     # fast cataloguing datas
763     $template->param(
764         'circborrowernumber' => $fa_circborrowernumber,
765         'barcode'            => $fa_barcode,
766         'branch'             => $fa_branch,
767         'stickyduedate'      => $fa_stickyduedate,
768         'duedatespec'        => $fa_duedatespec,
769     );
770 }
771
772 foreach my $error (@errors) {
773     $template->param($error => 1);
774 }
775 output_html_with_http_headers $input, $cookie, $template->output;