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