Bug 35248: Add unit tests for Koha::Item->check_booking
[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 min );
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                 biblio_id   => $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             item_id       => $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 $item_group             = $input->param('item_group');
138 my $item_group_description = $input->param('item_group_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 if ( $op eq 'edititem' || $op eq 'dupeitem' ) {
160     my $item = Koha::Items->find($itemnumber);
161     if ( !$item ) {
162         $template->param( biblio => $biblio, item_doesnt_exist => 1 );
163         output_and_exit( $input, $cookie, $template, 'unknown_item' );
164     }
165 }
166
167 # Does the user have a restricted item editing permission?
168 my $patron = Koha::Patrons->find( $loggedinuser );
169
170 my $item = $itemnumber ? Koha::Items->find( $itemnumber ) : undef;
171 if ( $item && !$patron->can_edit_items_from( $item->homebranch ) ) {
172     print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber");
173     exit;
174 }
175
176 my $uid = $patron->userid;
177 my $restrictededition = $uid ? haspermission($uid,  {'editcatalogue' => 'edit_items_restricted'}) : undef;
178 # In case user is a superlibrarian, editing is not restricted
179 $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibrarian());
180 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
181 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
182
183 our $tagslib = &GetMarcStructure(1,$frameworkcode);
184 my $record = $biblio->metadata->record;
185
186 output_and_exit_if_error( $input, $cookie, $template,
187     { module => 'cataloguing', record => $record } );
188
189 my $current_item;
190 my $nextop="additem";
191 my @errors; # store errors found while checking data BEFORE saving item.
192
193 # Getting last created item cookie
194 my $prefillitem = C4::Context->preference('PrefillItem');
195
196 my $load_template_submit = $input->param('load_template_submit');
197 my $delete_template_submit = $input->param('delete_template_submit');
198 my $unload_template_submit = $input->param('unload_template_submit');
199 my $use_template_for_session = $input->param('use_template_for_session') || $input->cookie('ItemEditorSessionTemplateId');
200 my $template_id = $input->param('template_id') || $input->cookie('ItemEditorSessionTemplateId');
201 if ( $delete_template_submit ) {
202     my $t = Koha::Item::Templates->find($template_id);
203     $t->delete if $t && ( $t->patron_id eq $loggedinuser || haspermission( $uid, { 'editcatalogue' => 'manage_item_editor_templates' } ) );
204     $template_id = undef;
205     $use_template_for_session = undef;
206 }
207 if ($load_template_submit || $unload_template_submit) {
208     $op = q{} if $template_id;
209
210     $template_id = undef if !$input->param('template_id');
211     $template_id = undef if $unload_template_submit;
212
213     # Unset the cookie if either no template id as submitted, or "use for session" checkbox as unchecked
214     my $cookie_value = $input->param('use_template_for_session') && $template_id ? $template_id : q{};
215     $use_template_for_session = $cookie_value;
216
217     # Update the cookie
218     my $template_cookie = $input->cookie(
219         -name     => 'ItemEditorSessionTemplateId',
220         -value    => $cookie_value,
221         -HttpOnly => 1,
222         -expires  => '',
223         -sameSite => 'Lax'
224     );
225
226     $cookie = [ $cookie, $template_cookie ];
227 }
228 $template->param(
229     template_id    => $template_id,
230     item_templates => Koha::Item::Templates->get_available($loggedinuser),
231     use_template_for_session => $use_template_for_session,
232 );
233
234 #-------------------------------------------------------------------------------
235 if ($op eq "additem") {
236
237     my $add_submit                 = $input->param('add_submit');
238     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
239     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
240     my $save_as_template_submit    = $input->param('save_as_template_submit');
241     my $number_of_copies           = min( scalar $input->param('number_of_copies') || 0, 1000 ); # TODO refine hardcoded maximum?
242
243     my @columns = Koha::Items->columns;
244     my $item = Koha::Item->new;
245     $item->biblionumber($biblio->biblionumber);
246     for my $c ( @columns ) {
247         if ( $c eq 'more_subfields_xml' ) {
248             my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
249             my @unlinked_item_subfields;
250             for my $subfield ( @more_subfields_xml ) {
251                 my $v = $input->param('items.more_subfields_xml_' . $subfield);
252                 push @unlinked_item_subfields, $subfield, $v;
253             }
254             if ( @unlinked_item_subfields ) {
255                 my $marc = MARC::Record->new();
256                 # use of tag 999 is arbitrary, and doesn't need to match the item tag
257                 # used in the framework
258                 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
259                 $marc->encoding("UTF-8");
260                 $item->more_subfields_xml($marc->as_xml("USMARC"));
261                 next;
262             }
263             $item->more_subfields_xml(undef);
264         } else {
265             next if $c eq 'itemnumber';
266             my @v = grep { $_ ne "" }
267                 uniq $input->multi_param( "items." . $c );
268
269             next unless @v;
270
271             if ( $c eq 'permanent_location' ) { # See 27837
272                 $item->make_column_dirty('permanent_location');
273             }
274
275             $item->$c(join ' | ', @v);
276         }
277     }
278
279     # if autoBarcode is set to 'incremental', calculate barcode...
280     my $submitted_barcode = $item->barcode;
281     if ( ! defined $item->barcode && C4::Context->preference('autoBarcode') eq 'incremental' ) {
282         my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
283         $item->barcode($barcode);
284     }
285
286     $item->barcode(barcodedecode($item->barcode));
287
288     if ($save_as_template_submit) {
289         my $template_name       = $input->param('template_name');
290         my $template_is_shared  = $input->param('template_is_shared');
291         my $replace_template_id = $input->param('replace_template_id');
292
293         my $contents = $item->unblessed;
294         $contents->{barcode} = $submitted_barcode; # Don't save the autobarcode in the template
295
296         if ($replace_template_id) {
297             my $template = Koha::Item::Templates->find($replace_template_id);
298             $template->update(
299                 {
300                     id             => $replace_template_id,
301                     is_shared      => $template_is_shared ? 1 : 0,
302                     contents       => $contents,
303                 }
304             ) if $template && (
305                 $template->patron_id eq $loggedinuser
306                 ||
307                 haspermission( $uid, { 'editcatalogue' => 'manage_item_editor_templates' } )
308             );
309         }
310         else {
311             my $template = Koha::Item::Template->new(
312                 {
313                     name      => $template_name,
314                     patron_id => $loggedinuser,
315                     is_shared => $template_is_shared ? 1 : 0,
316                     contents  => $contents,
317                 }
318             )->store();
319         }
320     }
321     # If we have to add or add & duplicate, we add the item
322     elsif ( $add_submit || $add_duplicate_submit || $prefillitem) {
323
324         # check for item barcode # being unique
325         if ( defined $item->barcode
326             && Koha::Items->search( { barcode => $item->barcode } )->count )
327         {
328             # if barcode exists, don't create, but report The problem.
329             push @errors, "barcode_not_unique";
330
331             $current_item = $item->unblessed; # Restore edit form for the same item
332         }
333         unless ( @errors ) {
334             $item->store->discard_changes;
335             add_item_to_item_group( $item->biblionumber, $item->itemnumber, $item_group, $item_group_description );
336
337             # This is a bit tricky : if there is a cookie for the last created item and
338             # we just added an item, the cookie value is not correct yet (it will be updated
339             # next page). To prevent the form from being filled with outdated values, we
340             # force the use of "add and duplicate" feature, so the form will be filled with
341             # correct values.
342
343             # Pushing the last created item cookie back
344             if ( $prefillitem ) {
345                 my $last_created_item_cookie = $input->cookie(
346                     -name => 'LastCreatedItem',
347                     # We encode_base64url the whole freezed structure so we're sure we won't have any encoding problems
348                     -value   => encode_base64url( freeze( { %{$item->unblessed}, itemnumber => undef } ) ),
349                     -HttpOnly => 1,
350                     -expires => '',
351                     -sameSite => 'Lax'
352                 );
353
354                 $cookie = [ $cookie, $last_created_item_cookie ];
355             }
356
357         }
358         $nextop = "additem";
359
360     }
361
362     # If we have to add & duplicate
363     if ($prefillitem || $add_duplicate_submit) {
364
365         $current_item = $item->unblessed;
366
367         if (C4::Context->preference('autoBarcode') eq 'incremental') {
368             my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
369             $current_item->{barcode} = $barcode;
370         }
371         else {
372             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
373             $current_item->{barcode} = undef; # FIXME or delete?
374         }
375
376         # Don't use the "prefill" feature if we want to generate the form with all the info from this item
377         # It will remove subfields that are not in SubfieldsToUseWhenPrefill.
378         $prefillitem = 0 if $add_duplicate_submit;
379     }
380
381     # If we have to add multiple copies
382     if ($add_multiple_copies_submit) {
383
384         $current_item = $item->unblessed;
385
386         my $copynumber = $current_item->{copynumber};
387         my $oldbarcode = $current_item->{barcode};
388
389         # If there is a barcode and we can't find their new values, we can't add multiple copies
390         my $testbarcode;
391         my $barcodeobj = C4::Barcodes->new;
392         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
393         if ( $oldbarcode && !$testbarcode ) {
394
395             push @errors, "no_next_barcode";
396
397         }
398         else {
399             # We add each item
400
401             # For the first iteration
402             my $barcodevalue = $oldbarcode;
403             my $exist_itemnumber;
404
405             for ( my $i = 0 ; $i < $number_of_copies ; ) {
406
407                 # If there is a barcode
408                 if ($barcodevalue) {
409
410 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
411                     $barcodevalue = $barcodeobj->next_value($oldbarcode)
412                       if ( $i > 0 || $exist_itemnumber );
413
414                     # Putting it into the record
415                     if ($barcodevalue) {
416                         if ( C4::Context->preference("autoBarcode") eq
417                             'hbyymmincr' && $i > 0 )
418                         { # The first copy already contains the homebranch prefix
419                              # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
420                              # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
421                              # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
422                              # But when adding multiple copies we need to prefix it here,
423                              # so we retrieve the homebranch from the item and prefix the barcode with it.
424                             my $homebranch = $current_item->{homebranch};
425                             $barcodevalue = $homebranch . $barcodevalue;
426                         }
427                         $current_item->{barcode} = $barcodevalue;
428                     }
429
430                     # Checking if the barcode already exists
431                     $exist_itemnumber = Koha::Items->search({ barcode => $barcodevalue })->count;
432                 }
433
434                 # Updating record with the new copynumber
435                 if ($copynumber) {
436                     $current_item->{copynumber} = $copynumber;
437                 }
438
439                 # Adding the item
440                 if ( !$exist_itemnumber ) {
441                     delete $current_item->{itemnumber};
442                     $current_item = Koha::Item->new($current_item)->store(
443                         { skip_record_index => 1 } );
444                     $current_item->discard_changes; # Cannot chain discard_changes
445                     $current_item = $current_item->unblessed;
446                     add_item_to_item_group(
447                         $item->biblionumber, $item->itemnumber, $item_group,
448                         $item_group_description
449                     );
450
451 # We count the item only if it was really added
452 # That way, all items are added, even if there was some already existing barcodes
453 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
454                     $i++;
455
456                     # Only increment copynumber if item was really added
457                     $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
458                 }
459
460                 # Preparing the next iteration
461                 $oldbarcode = $barcodevalue;
462             }
463
464             my $indexer = Koha::SearchEngine::Indexer->new(
465                 { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
466             $indexer->index_records( $biblionumber, "specialUpdate",
467                 "biblioserver" );
468
469             undef($current_item);
470         }
471     }
472     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
473         print $input->redirect(
474            '/cgi-bin/koha/circ/circulation.pl?'
475            .'borrowernumber='.$fa_circborrowernumber
476            .'&barcode='.uri_escape_utf8($fa_barcode)
477            .'&duedatespec='.$fa_duedatespec
478            .'&stickyduedate='.$fa_stickyduedate
479         );
480         exit;
481     }
482
483
484 #-------------------------------------------------------------------------------
485 } elsif ($op eq "edititem") {
486 #-------------------------------------------------------------------------------
487 # retrieve item if exist => then, it's a modif
488     $current_item = Koha::Items->find($itemnumber)->unblessed;
489     $nextop       = "saveitem";
490 #-------------------------------------------------------------------------------
491 } elsif ($op eq "dupeitem") {
492 #-------------------------------------------------------------------------------
493 # retrieve item if exist => then, it's a modif
494     $current_item = Koha::Items->find($itemnumber)->unblessed;
495     if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
496         my ($barcode) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
497         $current_item->{barcode} = $barcode;
498     }
499     else {
500         $current_item->{barcode} = undef;    # Don't save it!
501     }
502
503     $nextop = "additem";
504 #-------------------------------------------------------------------------------
505 } elsif ($op eq "delitem") {
506 #-------------------------------------------------------------------------------
507     # check that there is no issue on this item before deletion.
508     my $item = Koha::Items->find($itemnumber);
509     my $deleted;
510     if( $item ) {
511         $deleted = $item->safe_delete;
512     } else {
513         $deleted = Koha::Result::Boolean->new(0)->add_message({ message => 'item_not_found' });
514     }
515     if ( $deleted ) {
516         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
517         exit;
518     }
519     else {
520         push @errors, @{ $deleted->messages }[0]->message;
521         $nextop = "additem";
522     }
523 #-------------------------------------------------------------------------------
524 } elsif ($op eq "delallitems") {
525 #-------------------------------------------------------------------------------
526     my $items = Koha::Items->search({ biblionumber => $biblionumber });
527     while ( my $item = $items->next ) {
528         my $deleted = $item->safe_delete({ skip_record_index => 1 });
529         push @errors, @{$deleted->messages}[0]->message unless $deleted;
530     }
531     my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
532     $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
533     if ( @errors ) {
534         $nextop="additem";
535     } else {
536         my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
537         my $views = { C4::Search::enabled_staff_search_views };
538         if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
539             print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
540         } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
541             print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
542         } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
543             print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
544         } else {
545             print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
546         }
547         exit;
548     }
549 #-------------------------------------------------------------------------------
550 } elsif ($op eq "saveitem") {
551 #-------------------------------------------------------------------------------
552
553     my $itemnumber = $input->param('itemnumber');
554     my $item = Koha::Items->find($itemnumber);
555     unless ($item) {
556         C4::Output::output_error( $input, '404' );
557         exit;
558     }
559     my $olditemlost = $item->itemlost;
560     my @columns = Koha::Items->columns;
561     my $new_values = $item->unblessed;
562     for my $c ( @columns ) {
563         if ( $c eq 'more_subfields_xml' ) {
564             my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
565             my @unlinked_item_subfields;
566             for my $subfield ( uniq @more_subfields_xml ) {
567                 my @v = $input->multi_param('items.more_subfields_xml_' . encode_utf8($subfield));
568                 push @unlinked_item_subfields, $subfield, $_ for @v;
569             }
570             if ( @unlinked_item_subfields ) {
571                 my $marc = MARC::Record->new();
572                 # use of tag 999 is arbitrary, and doesn't need to match the item tag
573                 # used in the framework
574                 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
575                 $marc->encoding("UTF-8");
576                 $new_values->{more_subfields_xml} = $marc->as_xml("USMARC");
577                 next;
578             }
579             $item->more_subfields_xml(undef);
580         } else {
581             my @v = map { ( defined $_ && $_ eq '' ) ? undef : $_ } $input->multi_param( "items." . $c );
582             next unless @v;
583
584             if ( $c eq 'permanent_location' ) { # See 27837
585                 $item->make_column_dirty('permanent_location');
586             }
587
588             if ( scalar(@v) == 1 && not defined $v[0] ) {
589                 delete $new_values->{$c};
590             } else {
591                 $new_values->{$c} = join ' | ', @v;
592             }
593         }
594     }
595     $item = $item->set_or_blank($new_values);
596
597     # check that the barcode don't exist already
598     if (
599         defined $item->barcode
600         && Koha::Items->search(
601             {
602                 barcode    => $item->barcode,
603                 itemnumber => { '!=' => $item->itemnumber }
604             }
605         )->count
606       )
607     {
608         # FIXME We shouldn't need that, ->store would explode as there is a unique constraint on items.barcode
609         push @errors,"barcode_not_unique";
610         $current_item = $item->unblessed; # Restore edit form for the same item
611     } else {
612         my $newitemlost = $item->itemlost;
613         if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
614             LostItem( $item->itemnumber, 'additem' );
615         }
616         $item->store;
617     }
618
619     $nextop="additem";
620 } elsif ($op eq "delinkitem"){
621
622     my $analyticfield = '773';
623     if ($marcflavour  eq 'MARC21'){
624         $analyticfield = '773';
625     } elsif ($marcflavour eq 'UNIMARC') {
626         $analyticfield = '461';
627     }
628     foreach my $field ($record->field($analyticfield)){
629         if ($field->subfield('9') eq $hostitemnumber){
630             $record->delete_field($field);
631             last;
632         }
633     }
634         my $modbibresult = ModBiblio($record, $biblionumber,'');
635 }
636
637 # update OAI-PMH sets
638 if ($op) {
639     if (C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
640         C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
641     }
642 }
643
644 #
645 #-------------------------------------------------------------------------------
646 # build screen with existing items. and "new" one
647 #-------------------------------------------------------------------------------
648
649 # now, build existiing item list
650
651 my @items;
652 for my $item ( $biblio->items->as_list, $biblio->host_items->as_list ) {
653     my $i = $item->columns_to_str;
654     $i->{nomod} = 1 unless $patron->can_edit_items_from($item->homebranch);
655     push @items, $i;
656 }
657
658 my @witness_attributes = uniq map {
659     my $item = $_;
660     map { defined $item->{$_} && $item->{$_} ne "" ? $_ : () } keys %$item
661 } @items;
662
663 our ( $itemtagfield, $itemtagsubfield ) = GetMarcFromKohaField("items.itemnumber");
664
665 my $subfieldcode_attribute_mappings;
666 for my $subfield_code ( keys %{ $tagslib->{$itemtagfield} } ) {
667
668     my $subfield = $tagslib->{$itemtagfield}->{$subfield_code};
669
670     next if IsMarcStructureInternal( $subfield );
671     next unless $subfield->{tab} eq 10; # Is this really needed?
672
673     my $attribute;
674     if ( $subfield->{kohafield} ) {
675         ( $attribute = $subfield->{kohafield} ) =~ s|^items\.||;
676     } else {
677         $attribute = $subfield_code; # It's in more_subfields_xml
678     }
679     next unless grep { $attribute eq $_ } @witness_attributes;
680     $subfieldcode_attribute_mappings->{$subfield_code} = $attribute;
681 }
682
683 my @header_value_loop = map {
684     {
685         header_value  => $tagslib->{$itemtagfield}->{$_}->{lib},
686         attribute     => $subfieldcode_attribute_mappings->{$_},
687         subfield_code => $_,
688     }
689 } sort keys %$subfieldcode_attribute_mappings;
690
691 # Using last created item if it exists
692 if (
693     $op ne "additem"
694     && $op ne "edititem"
695     && $op ne "dupeitem" )
696 {
697     if ( $template_id ) {
698         my $item_from_template = get_item_from_template($template_id);
699         $current_item = $item_from_template if $item_from_template;
700     }
701     elsif ( $prefillitem ) {
702         my $item_from_cookie = get_item_from_cookie($input);
703         $current_item = $item_from_cookie if $item_from_cookie;
704     }
705 }
706
707 if ( $current_item->{more_subfields_xml} ) {
708     # FIXME Use Maybe MARC::Record::new_from_xml if encoding issues on subfield (??)
709     $current_item->{marc_more_subfields_xml} = MARC::Record->new_from_xml($current_item->{more_subfields_xml}, 'UTF-8');
710 }
711
712 my $branchcode = $input->param('branch') || C4::Context->userenv->{branch};
713
714 # If we are not adding a new item
715 # OR
716 # If the subfield must be prefilled with last catalogued item
717 my @subfields_to_prefill;
718 if ( $nextop eq 'additem' && $op ne 'dupeitem' && $prefillitem ) {
719     @subfields_to_prefill = split(' ', C4::Context->preference('SubfieldsToUseWhenPrefill'));
720 }
721
722 # Getting list of subfields to keep when restricted editing is enabled
723 my @subfields_to_allow = $restrictededition ? split ' ', C4::Context->preference('SubfieldsToAllowForRestrictedEditing') : ();
724
725 my $subfields =
726   Koha::UI::Form::Builder::Item->new(
727     { biblionumber => $biblionumber, item => $current_item } )->edit_form(
728     {
729         branchcode           => $branchcode,
730         restricted_editition => $restrictededition,
731         (
732             @subfields_to_allow
733             ? ( subfields_to_allow => \@subfields_to_allow )
734             : ()
735         ),
736         (
737             @subfields_to_prefill
738             ? ( subfields_to_prefill => \@subfields_to_prefill )
739             : ()
740         ),
741         prefill_with_default_values => 1,
742         branch_limit => C4::Context->userenv->{"branch"},
743         (
744             $op eq 'dupeitem'
745             ? ( ignore_invisible_subfields => 1 )
746             : ()
747         ),
748     }
749 );
750
751 if (   $frameworkcode eq 'FA' ) {
752     my ( $barcode_field ) = grep {$_->{kohafield} eq 'items.barcode'} @$subfields;
753     $barcode_field->{marc_value}->{value} ||= $input->param('barcode');
754 }
755
756 if( my $default_location = C4::Context->preference('NewItemsDefaultLocation') ) {
757     my ( $location_field ) = grep {$_->{kohafield} eq 'items.location'} @$subfields;
758     $location_field->{marc_value}->{value} ||= $default_location;
759 }
760
761 my @ig = Koha::Biblio::ItemGroups->search({ biblio_id => $biblionumber })->as_list();
762 #sort by display order
763 my @sorted_ig = sort { $a->display_order <=> $b->display_order } @ig;
764 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
765 $template->param(
766     biblio       => $biblio,
767     items        => \@items,
768     item_groups      => \@sorted_ig,
769     item_header_loop => \@header_value_loop,
770     subfields        => $subfields,
771     itemnumber       => $itemnumber,
772     barcode          => $current_item->{barcode},
773     op      => $nextop,
774     popup => scalar $input->param('popup') ? 1: 0,
775     C4::Search::enabled_staff_search_views,
776 );
777 $template->{'VARS'}->{'searchid'} = $searchid;
778
779 if ($frameworkcode eq 'FA'){
780     # fast cataloguing datas
781     $template->param(
782         'circborrowernumber' => $fa_circborrowernumber,
783         'barcode'            => $fa_barcode,
784         'branch'             => $fa_branch,
785         'stickyduedate'      => $fa_stickyduedate,
786         'duedatespec'        => $fa_duedatespec,
787     );
788 }
789
790 foreach my $error (@errors) {
791     $template->param($error => 1);
792 }
793 output_html_with_http_headers $input, $cookie, $template->output;