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