3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
7 # This file is part of Koha.
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.
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.
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>.
25 use C4::Auth qw( get_template_and_user haspermission );
26 use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers );
32 IsMarcStructureInternal
36 use C4::Circulation qw( barcodedecode LostItem );
38 use C4::Barcodes::ValueBuilder;
39 use Koha::DateUtils qw( dt_from_string );
45 use Koha::SearchEngine::Indexer;
46 use C4::Search qw( enabled_staff_search_views );
47 use Storable qw( freeze thaw );
48 use URI::Escape qw( uri_escape_utf8 );
50 use Koha::UI::Form::Builder::Item;
53 use URI::Escape qw( uri_escape_utf8 );
54 use Encode qw( encode_utf8 );
55 use MIME::Base64 qw( decode_base64url encode_base64url );
56 use List::Util qw( first );
57 use List::MoreUtils qw( any uniq );
59 our $dbh = C4::Context->dbh;
61 sub add_item_to_item_group {
62 my ( $biblionumber, $itemnumber, $item_group, $item_group_description ) = @_;
64 return unless $item_group;
67 if ( $item_group eq 'create' ) {
68 my $item_group = Koha::Biblio::ItemGroup->new(
70 biblionumber => $biblionumber,
71 description => $item_group_description,
75 $item_group_id = $item_group->id;
78 $item_group_id = $item_group;
81 my $item_group_item = Koha::Biblio::ItemGroup::Item->new(
83 itemnumber => $itemnumber,
84 item_group_id => $item_group_id,
89 sub get_item_from_cookie {
93 my $lastitemcookie = $input->cookie('LastCreatedItem');
94 if ($lastitemcookie) {
95 $lastitemcookie = decode_base64url($lastitemcookie);
97 if ( thaw($lastitemcookie) ) {
98 $item_from_cookie = thaw($lastitemcookie);
102 $lastitemcookie ||= 'undef';
103 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '".encode_base64url($lastitemcookie)."'. Caught error follows: '$@'";
106 return $item_from_cookie;
109 my $input = CGI->new;
113 if( $input->param('itemnumber') && !$input->param('biblionumber') ){
114 $itemnumber = $input->param('itemnumber');
115 my $item = Koha::Items->find( $itemnumber );
116 $biblionumber = $item->biblionumber;
118 $biblionumber = $input->param('biblionumber');
119 $itemnumber = $input->param('itemnumber');
122 my $biblio = Koha::Biblios->find($biblionumber);
124 my $op = $input->param('op') || q{};
125 my $hostitemnumber = $input->param('hostitemnumber');
126 my $marcflavour = C4::Context->preference("marcflavour");
127 my $searchid = $input->param('searchid');
128 # fast cataloguing datas
129 my $fa_circborrowernumber = $input->param('circborrowernumber');
130 my $fa_barcode = $input->param('barcode');
131 my $fa_branch = $input->param('branch');
132 my $fa_stickyduedate = $input->param('stickyduedate');
133 my $fa_duedatespec = $input->param('duedatespec');
134 my $volume = $input->param('volume');
135 my $volume_description = $input->param('volume_description');
137 our $frameworkcode = &GetFrameworkCode($biblionumber);
139 # Defining which userflag is needing according to the framework currently used
141 if (defined $input->param('frameworkcode')) {
142 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
145 if (not defined $userflags) {
146 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
149 my ($template, $loggedinuser, $cookie)
150 = get_template_and_user({template_name => "cataloguing/additem.tt",
153 flagsrequired => {editcatalogue => $userflags},
157 # Does the user have a restricted item editing permission?
158 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
159 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
160 # In case user is a superlibrarian, editing is not restricted
161 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
162 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
163 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
165 our $tagslib = &GetMarcStructure(1,$frameworkcode);
166 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
168 output_and_exit_if_error( $input, $cookie, $template,
169 { module => 'cataloguing', record => $record } );
172 my $nextop="additem";
173 my @errors; # store errors found while checking data BEFORE saving item.
175 # Getting last created item cookie
176 my $prefillitem = C4::Context->preference('PrefillItem');
178 #-------------------------------------------------------------------------------
179 if ($op eq "additem") {
181 my $add_submit = $input->param('add_submit');
182 my $add_duplicate_submit = $input->param('add_duplicate_submit');
183 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
184 my $number_of_copies = $input->param('number_of_copies');
186 my @columns = Koha::Items->columns;
187 my $item = Koha::Item->new;
188 $item->biblionumber($biblio->biblionumber);
189 for my $c ( @columns ) {
190 if ( $c eq 'more_subfields_xml' ) {
191 my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
192 my @unlinked_item_subfields;
193 for my $subfield ( @more_subfields_xml ) {
194 my $v = $input->param('items.more_subfields_xml_' . $subfield);
195 push @unlinked_item_subfields, $subfield, $v;
197 if ( @unlinked_item_subfields ) {
198 my $marc = MARC::Record->new();
199 # use of tag 999 is arbitrary, and doesn't need to match the item tag
200 # used in the framework
201 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
202 $marc->encoding("UTF-8");
203 $item->more_subfields_xml($marc->as_xml("USMARC"));
206 $item->more_subfields_xml(undef);
208 my @v = grep { $_ ne "" }
209 uniq $input->multi_param( "items." . $c );
212 && $c ne 'permanent_location'; # See 27837
214 $item->$c(join ' | ', @v);
218 # if autoBarcode is set to 'incremental', calculate barcode...
219 if ( ! defined $item->barcode && C4::Context->preference('autoBarcode') eq 'incremental' ) {
220 my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
221 $item->barcode($barcode);
224 $item->barcode(barcodedecode($item->barcode));
226 # If we have to add or add & duplicate, we add the item
227 if ( $add_submit || $add_duplicate_submit || $prefillitem) {
229 # check for item barcode # being unique
230 if ( defined $item->barcode
231 && Koha::Items->search( { barcode => $item->barcode } )->count )
233 # if barcode exists, don't create, but report The problem.
234 push @errors, "barcode_not_unique";
236 $current_item = $item->unblessed; # Restore edit form for the same item
239 $item->store->discard_changes;
240 add_item_to_item_group( $item->biblionumber, $item->biblioitemnumber, $volume, $volume_description );
242 # This is a bit tricky : if there is a cookie for the last created item and
243 # we just added an item, the cookie value is not correct yet (it will be updated
244 # next page). To prevent the form from being filled with outdated values, we
245 # force the use of "add and duplicate" feature, so the form will be filled with
248 # Pushing the last created item cookie back
249 if ( $prefillitem ) {
250 my $last_created_item_cookie = $input->cookie(
251 -name => 'LastCreatedItem',
252 # We encode_base64url the whole freezed structure so we're sure we won't have any encoding problems
253 -value => encode_base64url( freeze( { %{$item->unblessed}, itemnumber => undef } ) ),
259 $cookie = [ $cookie, $last_created_item_cookie ];
267 # If we have to add & duplicate
268 if ($prefillitem || $add_duplicate_submit) {
270 $current_item = $item->unblessed;
272 if (C4::Context->preference('autoBarcode') eq 'incremental') {
273 my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
274 $current_item->{barcode} = $barcode;
277 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
278 $current_item->{barcode} = undef; # FIXME or delete?
281 # Don't use the "prefill" feature if we want to generate the form with all the info from this item
282 # It will remove subfields that are not in SubfieldsToUseWhenPrefill.
283 $prefillitem = 0 if $add_duplicate_submit;
286 # If we have to add multiple copies
287 if ($add_multiple_copies_submit) {
289 $current_item = $item->unblessed;
291 my $copynumber = $current_item->{copynumber};
292 my $oldbarcode = $current_item->{barcode};
294 # If there is a barcode and we can't find their new values, we can't add multiple copies
296 my $barcodeobj = C4::Barcodes->new;
297 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
298 if ( $oldbarcode && !$testbarcode ) {
300 push @errors, "no_next_barcode";
306 # For the first iteration
307 my $barcodevalue = $oldbarcode;
308 my $exist_itemnumber;
310 for ( my $i = 0 ; $i < $number_of_copies ; ) {
312 # If there is a barcode
315 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
316 $barcodevalue = $barcodeobj->next_value($oldbarcode)
317 if ( $i > 0 || $exist_itemnumber );
319 # Putting it into the record
321 if ( C4::Context->preference("autoBarcode") eq
322 'hbyymmincr' && $i > 0 )
323 { # The first copy already contains the homebranch prefix
324 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
325 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
326 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
327 # But when adding multiple copies we need to prefix it here,
328 # so we retrieve the homebranch from the item and prefix the barcode with it.
329 my $homebranch = $current_item->{homebranch};
330 $barcodevalue = $homebranch . $barcodevalue;
332 $current_item->{barcode} = $barcodevalue;
335 # Checking if the barcode already exists
336 $exist_itemnumber = Koha::Items->search({ barcode => $barcodevalue })->count;
339 # Updating record with the new copynumber
341 $current_item->{copynumber} = $copynumber;
345 if ( !$exist_itemnumber ) {
346 delete $current_item->{itemnumber};
347 $current_item = Koha::Item->new($current_item)->store(
348 { skip_record_index => 1 } );
349 $current_item->discard_changes; # Cannot chain discard_changes
350 $current_item = $current_item->unblessed;
351 add_item_to_item_group( $item->biblionumber, $item->biblioitemnumber, $volume, $volume_description );
353 # We count the item only if it was really added
354 # That way, all items are added, even if there was some already existing barcodes
355 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
358 # Only increment copynumber if item was really added
359 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
362 # Preparing the next iteration
363 $oldbarcode = $barcodevalue;
366 my $indexer = Koha::SearchEngine::Indexer->new(
367 { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
368 $indexer->index_records( $biblionumber, "specialUpdate",
371 undef($current_item);
374 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
375 print $input->redirect(
376 '/cgi-bin/koha/circ/circulation.pl?'
377 .'borrowernumber='.$fa_circborrowernumber
378 .'&barcode='.uri_escape_utf8($fa_barcode)
379 .'&duedatespec='.$fa_duedatespec
380 .'&stickyduedate='.$fa_stickyduedate
386 #-------------------------------------------------------------------------------
387 } elsif ($op eq "edititem") {
388 #-------------------------------------------------------------------------------
389 # retrieve item if exist => then, it's a modif
390 $current_item = Koha::Items->find($itemnumber)->unblessed;
391 # FIXME Handle non existent item
392 $nextop = "saveitem";
393 #-------------------------------------------------------------------------------
394 } elsif ($op eq "dupeitem") {
395 #-------------------------------------------------------------------------------
396 # retrieve item if exist => then, it's a modif
397 $current_item = Koha::Items->find($itemnumber)->unblessed;
398 # FIXME Handle non existent item
399 if (C4::Context->preference('autoBarcode') eq 'incremental') {
400 my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
401 $current_item->{barcode} = $barcode;
404 $current_item->{barcode} = undef; # Don't save it!
408 #-------------------------------------------------------------------------------
409 } elsif ($op eq "delitem") {
410 #-------------------------------------------------------------------------------
411 # check that there is no issue on this item before deletion.
412 my $item = Koha::Items->find($itemnumber);
413 my $deleted = $item->safe_delete;
415 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
419 push @errors, @{ $deleted->messages }[0]->message;
422 #-------------------------------------------------------------------------------
423 } elsif ($op eq "delallitems") {
424 #-------------------------------------------------------------------------------
425 my $items = Koha::Items->search({ biblionumber => $biblionumber });
426 while ( my $item = $items->next ) {
427 my $deleted = $item->safe_delete({ skip_record_index => 1 });
428 push @errors, @{$deleted->messages}[0]->message unless $deleted;
430 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
431 $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
435 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
436 my $views = { C4::Search::enabled_staff_search_views };
437 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
438 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
439 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
440 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
441 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
442 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
444 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
448 #-------------------------------------------------------------------------------
449 } elsif ($op eq "saveitem") {
450 #-------------------------------------------------------------------------------
452 my $itemnumber = $input->param('itemnumber');
453 my $item = Koha::Items->find($itemnumber);
454 # FIXME Handle non existent item
455 my $olditemlost = $item->itemlost;
456 my @columns = Koha::Items->columns;
457 my $new_values = $item->unblessed;
458 for my $c ( @columns ) {
459 if ( $c eq 'more_subfields_xml' ) {
460 my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
461 my @unlinked_item_subfields;
462 for my $subfield ( uniq @more_subfields_xml ) {
463 my @v = $input->multi_param('items.more_subfields_xml_' . encode_utf8($subfield));
464 push @unlinked_item_subfields, $subfield, $_ for @v;
466 if ( @unlinked_item_subfields ) {
467 my $marc = MARC::Record->new();
468 # use of tag 999 is arbitrary, and doesn't need to match the item tag
469 # used in the framework
470 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
471 $marc->encoding("UTF-8");
472 $new_values->{more_subfields_xml} = $marc->as_xml("USMARC");
475 $item->more_subfields_xml(undef);
477 my @v = map { ( defined $_ && $_ eq '' ) ? undef : $_ } $input->multi_param( "items." . $c );
480 if ( scalar(@v) == 1 && not defined $v[0] ) {
481 delete $new_values->{$c};
483 $new_values->{$c} = join ' | ', @v;
487 $item = $item->set_or_blank($new_values);
489 # check that the barcode don't exist already
491 defined $item->barcode
492 && Koha::Items->search(
494 barcode => $item->barcode,
495 itemnumber => { '!=' => $item->itemnumber }
500 # FIXME We shouldn't need that, ->store would explode as there is a unique constraint on items.barcode
501 push @errors,"barcode_not_unique";
502 $current_item = $item->unblessed; # Restore edit form for the same item
504 my $newitemlost = $item->itemlost;
505 if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
506 LostItem( $item->itemnumber, 'additem' );
512 } elsif ($op eq "delinkitem"){
514 my $analyticfield = '773';
515 if ($marcflavour eq 'MARC21'){
516 $analyticfield = '773';
517 } elsif ($marcflavour eq 'UNIMARC') {
518 $analyticfield = '461';
520 foreach my $field ($record->field($analyticfield)){
521 if ($field->subfield('9') eq $hostitemnumber){
522 $record->delete_field($field);
526 my $modbibresult = ModBiblio($record, $biblionumber,'');
529 # update OAI-PMH sets
531 if (C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
532 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
537 #-------------------------------------------------------------------------------
538 # build screen with existing items. and "new" one
539 #-------------------------------------------------------------------------------
541 # now, build existiing item list
544 for my $item ( $biblio->items->as_list, $biblio->host_items->as_list ) {
545 push @items, $item->columns_to_str;
548 my @witness_attributes = uniq map {
550 map { defined $item->{$_} && $item->{$_} ne "" ? $_ : () } keys %$item
553 our ( $itemtagfield, $itemtagsubfield ) = GetMarcFromKohaField("items.itemnumber");
555 my $subfieldcode_attribute_mappings;
556 for my $subfield_code ( keys %{ $tagslib->{$itemtagfield} } ) {
558 my $subfield = $tagslib->{$itemtagfield}->{$subfield_code};
560 next if IsMarcStructureInternal( $subfield );
561 next unless $subfield->{tab} eq 10; # Is this really needed?
564 if ( $subfield->{kohafield} ) {
565 ( $attribute = $subfield->{kohafield} ) =~ s|^items\.||;
567 $attribute = $subfield_code; # It's in more_subfields_xml
569 next unless grep { $attribute eq $_ } @witness_attributes;
570 $subfieldcode_attribute_mappings->{$subfield_code} = $attribute;
573 my @header_value_loop = map {
575 header_value => $tagslib->{$itemtagfield}->{$_}->{lib},
576 attribute => $subfieldcode_attribute_mappings->{$_},
579 } sort keys %$subfieldcode_attribute_mappings;
581 # Using last created item if it exists
585 && $op ne "dupeitem" )
587 my $item_from_cookie = get_item_from_cookie($input);
588 $current_item = $item_from_cookie if $item_from_cookie;
591 if ( $current_item->{more_subfields_xml} ) {
592 # FIXME Use Maybe MARC::Record::new_from_xml if encoding issues on subfield (??)
593 $current_item->{marc_more_subfields_xml} = MARC::Record->new_from_xml($current_item->{more_subfields_xml}, 'UTF-8');
596 my $branchcode = $input->param('branch') || C4::Context->userenv->{branch};
598 # If we are not adding a new item
600 # If the subfield must be prefilled with last catalogued item
601 my @subfields_to_prefill;
602 if ( $nextop eq 'additem' && $op ne 'dupeitem' && $prefillitem ) {
603 @subfields_to_prefill = split(' ', C4::Context->preference('SubfieldsToUseWhenPrefill'));
604 # Setting to 1 element if SubfieldsToUseWhenPrefill is empty to prevent all the subfields to be prefilled
605 @subfields_to_prefill = ("") unless @subfields_to_prefill;
608 # Getting list of subfields to keep when restricted editing is enabled
609 my @subfields_to_allow = $restrictededition ? split ' ', C4::Context->preference('SubfieldsToAllowForRestrictedEditing') : ();
612 Koha::UI::Form::Builder::Item->new(
613 { biblionumber => $biblionumber, item => $current_item } )->edit_form(
615 branchcode => $branchcode,
616 restricted_editition => $restrictededition,
619 ? ( subfields_to_allow => \@subfields_to_allow )
623 @subfields_to_prefill
624 ? ( subfields_to_prefill => \@subfields_to_prefill )
627 prefill_with_default_values => 1,
628 branch_limit => C4::Context->userenv->{"branch"},
632 if ( $frameworkcode eq 'FA' ) {
633 my ( $barcode_field ) = grep {$_->{kohafield} eq 'items.barcode'} @$subfields;
634 $barcode_field->{marc_value}->{value} ||= $input->param('barcode');
637 if( my $default_location = C4::Context->preference('NewItemsDefaultLocation') ) {
638 my ( $location_field ) = grep {$_->{kohafield} eq 'items.location'} @$subfields;
639 $location_field->{marc_value}->{value} ||= $default_location;
642 my @ig = Koha::Biblio::ItemGroups->search({ biblio_id => $biblionumber })->as_list();
643 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
648 item_header_loop => \@header_value_loop,
649 subfields => $subfields,
650 itemnumber => $itemnumber,
651 barcode => $current_item->{barcode},
653 popup => scalar $input->param('popup') ? 1: 0,
654 C4::Search::enabled_staff_search_views,
656 $template->{'VARS'}->{'searchid'} = $searchid;
658 if ($frameworkcode eq 'FA'){
659 # fast cataloguing datas
661 'circborrowernumber' => $fa_circborrowernumber,
662 'barcode' => $fa_barcode,
663 'branch' => $fa_branch,
664 'stickyduedate' => $fa_stickyduedate,
665 'duedatespec' => $fa_duedatespec,
669 foreach my $error (@errors) {
670 $template->param($error => 1);
672 output_html_with_http_headers $input, $cookie, $template->output;