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 );
28 GetAuthorisedValueDesc
33 IsMarcStructureInternal
38 use C4::Items qw( AddItemFromMarc ModItemFromMarc );
40 use C4::Circulation qw( LostItem );
41 use C4::Koha qw( GetAuthorisedValues );
42 use C4::ClassSource qw( GetClassSources GetClassSource );
43 use Koha::DateUtils qw( dt_from_string );
48 use Koha::SearchEngine::Indexer;
49 use List::MoreUtils qw( any );
50 use C4::Search qw( enabled_staff_search_views );
51 use Storable qw( freeze thaw );
52 use URI::Escape qw( uri_escape_utf8 );
56 use URI::Escape qw( uri_escape_utf8 );
57 use MIME::Base64 qw( decode_base64url encode_base64url );
59 our $dbh = C4::Context->dbh;
62 my ($tagfield,$insubfield,$record) = @_;
65 foreach my $field ($record->field($tagfield)) {
66 my @subfields = $field->subfields();
67 foreach my $subfield (@subfields) {
68 if (@$subfield[0] eq $insubfield) {
69 $result .= @$subfield[1];
70 $indicator = $field->indicator(1).$field->indicator(2);
74 return($indicator,$result);
77 sub get_item_from_barcode {
79 my $dbh=C4::Context->dbh;
81 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
82 $rq->execute($barcode);
83 ($result)=$rq->fetchrow;
87 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
88 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
89 sub _increment_barcode {
90 my ($record, $frameworkcode) = @_;
91 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
92 unless ($record->field($tagfield)->subfield($tagsubfield)) {
93 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
94 $sth_barcode->execute;
95 my ($newbarcode) = $sth_barcode->fetchrow;
97 # OK, we have the new barcode, now create the entry in MARC record
98 my $fieldItem = $record->field($tagfield);
99 $record->delete_field($fieldItem);
100 $fieldItem->add_subfields($tagsubfield => $newbarcode);
101 $record->insert_fields_ordered($fieldItem);
107 sub generate_subfield_form {
108 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition, $item) = @_;
110 my $frameworkcode = &GetFrameworkCode($biblionumber);
113 my $dbh = C4::Context->dbh;
115 my $index_subfield = int(rand(1000000));
116 if ($subfieldtag eq '@'){
117 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
119 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
122 $subfield_data{tag} = $tag;
123 $subfield_data{subfield} = $subfieldtag;
124 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
125 $subfield_data{mandatory} = $subfieldlib->{mandatory};
126 $subfield_data{important} = $subfieldlib->{important};
127 $subfield_data{repeatable} = $subfieldlib->{repeatable};
128 $subfield_data{maxlength} = $subfieldlib->{maxlength};
129 $subfield_data{display_order} = $subfieldlib->{display_order};
130 $subfield_data{kohafield} = $subfieldlib->{kohafield} || 'items.more_subfields_xml';
132 if ( ! defined( $value ) || $value eq '') {
133 $value = $subfieldlib->{defaultvalue};
135 # get today date & replace <<YYYY>>, <<YY>>, <<MM>>, <<DD>> if provided in the default value
136 my $today_dt = dt_from_string;
137 my $year = $today_dt->strftime('%Y');
138 my $shortyear = $today_dt->strftime('%y');
139 my $month = $today_dt->strftime('%m');
140 my $day = $today_dt->strftime('%d');
141 $value =~ s/<<YYYY>>/$year/g;
142 $value =~ s/<<YY>>/$shortyear/g;
143 $value =~ s/<<MM>>/$month/g;
144 $value =~ s/<<DD>>/$day/g;
145 # And <<USER>> with surname (?)
146 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
147 $value=~s/<<USER>>/$username/g;
151 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
153 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
154 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
155 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
156 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
157 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
158 $CNsubfields = undef if $CNsubfields eq '';
159 my $temp2 = $temp->field($CNtag);
162 $value = $temp2->as_string( $CNsubfields, ' ' );
167 my $default_location = C4::Context->preference('NewItemsDefaultLocation');
168 if ( !$value && $subfieldlib->{kohafield} eq 'items.location' && $default_location ) {
169 $value = $default_location;
172 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
173 my $input = CGI->new;
174 $value = $input->param('barcode');
177 if ( $subfieldlib->{authorised_value} ) {
178 my @authorised_values;
180 # builds list, depending on authorised value...
181 if ( $subfieldlib->{authorised_value} eq "LOST" ) {
182 my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue');
183 my $item_is_return_claim = $ClaimReturnedLostValue && $item && $item->itemlost && $ClaimReturnedLostValue eq $item->itemlost;
184 $subfield_data{IS_RETURN_CLAIM} = $item_is_return_claim;
186 $subfield_data{IS_LOST_AV} = 1;
188 push @authorised_values, qq{};
189 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
191 push @authorised_values, $r->{authorised_value};
192 $authorised_lib{$r->{authorised_value}} = $r->{lib};
195 elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
196 foreach my $thisbranch (@$branches) {
197 push @authorised_values, $thisbranch->{branchcode};
198 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
199 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
202 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
203 push @authorised_values, "";
204 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
207 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
209 $itemtypes = Koha::ItemTypes->search_with_localization;
211 while ( my $itemtype = $itemtypes->next ) {
212 push @authorised_values, $itemtype->itemtype;
213 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
217 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
218 $itype_sth->execute( $biblionumber );
219 ( $value ) = $itype_sth->fetchrow_array;
224 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
225 push @authorised_values, "";
227 my $class_sources = GetClassSources();
228 my $default_source = C4::Context->preference("DefaultClassificationSource");
230 foreach my $class_source (sort keys %$class_sources) {
231 next unless $class_sources->{$class_source}->{'used'} or
232 ($value and $class_source eq $value) or
233 ($class_source eq $default_source);
234 push @authorised_values, $class_source;
235 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
237 $value = $default_source unless ($value);
239 #---- "true" authorised value
242 push @authorised_values, qq{};
243 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
245 push @authorised_values, $r->{authorised_value};
246 $authorised_lib{$r->{authorised_value}} = $r->{lib};
250 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
251 $subfield_data{marc_value} = {
253 id => $subfield_data{id},
254 maxlength => $subfield_data{maxlength},
256 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
260 $subfield_data{marc_value} = {
262 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
263 values => \@authorised_values,
264 labels => \%authorised_lib,
266 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
270 # it's a thesaurus / authority field
271 elsif ( $subfieldlib->{authtypecode} ) {
272 $subfield_data{marc_value} = {
274 id => $subfield_data{id},
275 maxlength => $subfield_data{maxlength},
277 authtypecode => $subfieldlib->{authtypecode},
280 # it's a plugin field
281 elsif ( $subfieldlib->{value_builder} ) { # plugin
282 require Koha::FrameworkPlugin;
283 my $plugin = Koha::FrameworkPlugin->new({
284 name => $subfieldlib->{'value_builder'},
287 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
288 id => $subfield_data{id}, tabloop => $loop_data };
289 $plugin->build( $pars );
290 if( !$plugin->errstr ) {
291 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
292 $subfield_data{marc_value} = {
293 type => 'text_plugin',
294 id => $subfield_data{id},
295 maxlength => $subfield_data{maxlength},
298 nopopup => $plugin->noclick,
299 javascript => $plugin->javascript,
302 warn $plugin->errstr;
303 $subfield_data{marc_value} = {
305 id => $subfield_data{id},
306 maxlength => $subfield_data{maxlength},
308 }; # supply default input form
311 elsif ( $tag eq '' ) { # it's an hidden field
312 $subfield_data{marc_value} = {
314 id => $subfield_data{id},
315 maxlength => $subfield_data{maxlength},
319 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
320 $subfield_data{marc_value} = {
322 id => $subfield_data{id},
323 maxlength => $subfield_data{maxlength},
329 $value and length($value) > 100
332 C4::Context->preference("marcflavour") eq "UNIMARC"
333 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
336 C4::Context->preference("marcflavour") eq "MARC21"
337 and 500 <= $tag && $tag < 600
340 # oversize field (textarea)
341 $subfield_data{marc_value} = {
343 id => $subfield_data{id},
347 # it's a standard field
348 $subfield_data{marc_value} = {
350 id => $subfield_data{id},
351 maxlength => $subfield_data{maxlength},
356 # Getting list of subfields to keep when restricted editing is enabled
357 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
358 my $allowAllSubfields = (
359 not defined $subfieldsToAllowForRestrictedEditing
360 or $subfieldsToAllowForRestrictedEditing eq q||
362 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
364 # If we're on restricted editing, and our field is not in the list of subfields to allow,
365 # then it is read-only
366 $subfield_data{marc_value}->{readonly} = (
367 not $allowAllSubfields
368 and $restrictededition
369 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
372 return \%subfield_data;
375 # Removes some subfields when prefilling items
376 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
377 sub removeFieldsForPrefill {
382 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
384 # Getting list of subfields to keep
385 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
387 # Removing subfields that are not in the syspref
388 if ($tag && $subfieldsToUseWhenPrefill) {
389 my $field = $item->field($tag);
390 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
391 foreach my $subfield ($field->subfields()) {
392 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
393 $field->delete_subfield(code => $subfield->[0]);
403 my $input = CGI->new;
404 my $error = $input->param('error');
408 if( $input->param('itemnumber') && !$input->param('biblionumber') ){
409 $itemnumber = $input->param('itemnumber');
410 my $item = Koha::Items->find( $itemnumber );
411 $biblionumber = $item->biblionumber;
413 $biblionumber = $input->param('biblionumber');
414 $itemnumber = $input->param('itemnumber');
417 my $op = $input->param('op') || q{};
418 my $hostitemnumber = $input->param('hostitemnumber');
419 my $marcflavour = C4::Context->preference("marcflavour");
420 my $searchid = $input->param('searchid');
421 # fast cataloguing datas
422 my $fa_circborrowernumber = $input->param('circborrowernumber');
423 my $fa_barcode = $input->param('barcode');
424 my $fa_branch = $input->param('branch');
425 my $fa_stickyduedate = $input->param('stickyduedate');
426 my $fa_duedatespec = $input->param('duedatespec');
428 my $frameworkcode = &GetFrameworkCode($biblionumber);
430 # Defining which userflag is needing according to the framework currently used
432 if (defined $input->param('frameworkcode')) {
433 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
436 if (not defined $userflags) {
437 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
440 my ($template, $loggedinuser, $cookie)
441 = get_template_and_user({template_name => "cataloguing/additem.tt",
444 flagsrequired => {editcatalogue => $userflags},
448 # Does the user have a restricted item editing permission?
449 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
450 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
451 # In case user is a superlibrarian, editing is not restricted
452 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
453 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
454 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
456 my $tagslib = &GetMarcStructure(1,$frameworkcode);
457 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
459 output_and_exit_if_error( $input, $cookie, $template,
460 { module => 'cataloguing', record => $record } );
462 my $oldrecord = TransformMarcToKoha($record);
464 my $nextop="additem";
465 my @errors; # store errors found while checking data BEFORE saving item.
467 # Getting last created item cookie
468 my $prefillitem = C4::Context->preference('PrefillItem');
470 my $cookieitemrecord;
472 my $lastitemcookie = $input->cookie('LastCreatedItem');
473 if ($lastitemcookie) {
474 $lastitemcookie = decode_base64url($lastitemcookie);
476 if ( thaw($lastitemcookie) ) {
477 $cookieitemrecord = thaw($lastitemcookie);
478 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
482 $lastitemcookie = 'undef' unless $lastitemcookie;
483 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '".encode_base64url($lastitemcookie)."'. Caught error follows: '$@'";
488 #-------------------------------------------------------------------------------
489 if ($op eq "additem") {
491 #-------------------------------------------------------------------------------
493 my @tags = $input->multi_param('tag');
494 my @subfields = $input->multi_param('subfield');
495 my @values = $input->multi_param('field_value');
496 # build indicator hash.
497 my @ind_tag = $input->multi_param('ind_tag');
498 my @indicator = $input->multi_param('indicator');
499 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
500 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
503 my $add_submit = $input->param('add_submit');
504 my $add_duplicate_submit = $input->param('add_duplicate_submit');
505 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
506 my $number_of_copies = $input->param('number_of_copies');
508 # This is a bit tricky : if there is a cookie for the last created item and
509 # we just added an item, the cookie value is not correct yet (it will be updated
510 # next page). To prevent the form from being filled with outdated values, we
511 # force the use of "add and duplicate" feature, so the form will be filled with
513 $add_duplicate_submit = 1 if ($prefillitem);
516 # if autoBarcode is set to 'incremental', calculate barcode...
517 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
518 $record = _increment_barcode($record, $frameworkcode);
521 my $addedolditem = TransformMarcToKoha( $record );
523 # If we have to add or add & duplicate, we add the item
524 if ( $add_submit || $add_duplicate_submit ) {
526 # check for item barcode # being unique
527 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
528 push @errors, "barcode_not_unique" if ($exist_itemnumber);
530 # if barcode exists, don't create, but report The problem.
531 unless ($exist_itemnumber) {
532 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
534 # Pushing the last created item cookie back
535 if ($prefillitem && defined $record) {
536 my $itemcookie = $input->cookie(
537 -name => 'LastCreatedItem',
538 # We encode_base64url the whole freezed structure so we're sure we won't have any encoding problems
539 -value => encode_base64url( freeze( $record ) ),
544 $cookie = [ $cookie, $itemcookie ];
549 if ($exist_itemnumber) {
550 $itemrecord = $record;
554 # If we have to add & duplicate
555 if ($add_duplicate_submit) {
556 $itemrecord = $record;
557 if (C4::Context->preference('autoBarcode') eq 'incremental') {
558 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
561 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
562 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
563 my $fieldItem = $itemrecord->field($tagfield);
564 $itemrecord->delete_field($fieldItem);
565 $fieldItem->delete_subfields($tagsubfield);
566 $itemrecord->insert_fields_ordered($fieldItem);
568 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
571 # If we have to add multiple copies
572 if ($add_multiple_copies_submit) {
575 my $barcodeobj = C4::Barcodes->new;
576 my $copynumber = $addedolditem->{'copynumber'};
577 my $oldbarcode = $addedolditem->{'barcode'};
578 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
579 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
581 # If there is a barcode and we can't find their new values, we can't add multiple copies
583 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
584 if ($oldbarcode && !$testbarcode) {
586 push @errors, "no_next_barcode";
587 $itemrecord = $record;
592 # For the first iteration
593 my $barcodevalue = $oldbarcode;
594 my $exist_itemnumber;
597 for (my $i = 0; $i < $number_of_copies;) {
599 # If there is a barcode
602 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
603 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
605 # Putting it into the record
607 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
608 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
609 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
610 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
611 # But when adding multiple copies we need to prefix it here,
612 # so we retrieve the homebranch from the item and prefix the barcode with it.
613 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
614 my $homebranch = $record->subfield($hb_field, $hb_subfield);
615 $barcodevalue = $homebranch . $barcodevalue;
617 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
620 # Checking if the barcode already exists
621 $exist_itemnumber = get_item_from_barcode($barcodevalue);
623 # Updating record with the new copynumber
625 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
629 if (!$exist_itemnumber) {
630 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
631 AddItemFromMarc( $record, $biblionumber, { skip_record_index => 1 } );
633 # We count the item only if it was really added
634 # That way, all items are added, even if there was some already existing barcodes
635 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
637 # Only increment copynumber if item was really added
638 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
641 # Preparing the next iteration
642 $oldbarcode = $barcodevalue;
645 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
646 $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
651 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
652 print $input->redirect(
653 '/cgi-bin/koha/circ/circulation.pl?'
654 .'borrowernumber='.$fa_circborrowernumber
655 .'&barcode='.uri_escape_utf8($fa_barcode)
656 .'&duedatespec='.$fa_duedatespec
657 .'&stickyduedate='.$fa_stickyduedate
663 #-------------------------------------------------------------------------------
664 } elsif ($op eq "edititem") {
665 #-------------------------------------------------------------------------------
666 # retrieve item if exist => then, it's a modif
667 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
668 $nextop = "saveitem";
669 #-------------------------------------------------------------------------------
670 } elsif ($op eq "dupeitem") {
671 #-------------------------------------------------------------------------------
672 # retrieve item if exist => then, it's a modif
673 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
674 if (C4::Context->preference('autoBarcode') eq 'incremental') {
675 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
678 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
679 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
680 my $fieldItem = $itemrecord->field($tagfield);
681 $itemrecord->delete_field($fieldItem);
682 $fieldItem->delete_subfields($tagsubfield);
683 $itemrecord->insert_fields_ordered($fieldItem);
686 #check for hidden subfield and remove them for the duplicated item
687 foreach my $field ($itemrecord->fields()){
688 my $tag = $field->{_tag};
689 foreach my $subfield ($field->subfields()){
690 my $subfieldtag = $subfield->[0];
691 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
692 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
693 my $fieldItem = $itemrecord->field($tag);
694 $itemrecord->delete_field($fieldItem);
695 $fieldItem->delete_subfields($subfieldtag);
696 $itemrecord->insert_fields_ordered($fieldItem);
701 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
703 #-------------------------------------------------------------------------------
704 } elsif ($op eq "delitem") {
705 #-------------------------------------------------------------------------------
706 # check that there is no issue on this item before deletion.
707 my $item = Koha::Items->find($itemnumber);
708 $error = $item->safe_delete;
709 if(ref($error) eq 'Koha::Item'){
710 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
715 #-------------------------------------------------------------------------------
716 } elsif ($op eq "delallitems") {
717 #-------------------------------------------------------------------------------
718 my $items = Koha::Items->search({ biblionumber => $biblionumber });
719 while ( my $item = $items->next ) {
720 $error = $item->safe_delete({ skip_record_index => 1 });
721 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
724 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
725 $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
729 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
730 my $views = { C4::Search::enabled_staff_search_views };
731 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
732 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
733 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
734 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
735 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
736 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
738 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
742 #-------------------------------------------------------------------------------
743 } elsif ($op eq "saveitem") {
744 #-------------------------------------------------------------------------------
746 my $itemnumber = $input->param('itemnumber');
747 my $item = Koha::Items->find($itemnumber);
748 # FIXME Handle non existent item
749 my $olditemlost = $item->itemlost;
750 my @columns = Koha::Items->columns;
751 for my $c ( @columns ) {
752 if ( $c eq 'more_subfields_xml' ) {
753 my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
754 my @unlinked_item_subfields;
755 for my $subfield ( @more_subfields_xml ) {
756 my $v = $input->param('items.more_subfields_xml_' . $subfield);
757 push @unlinked_item_subfields, $subfield, $v;
759 if ( @unlinked_item_subfields ) {
760 my $marc = MARC::Record->new();
761 # use of tag 999 is arbitrary, and doesn't need to match the item tag
762 # used in the framework
763 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
764 $marc->encoding("UTF-8");
765 $item->more_subfields_xml($marc->as_xml("USMARC"));
768 $item->more_subfields_xml(undef);
770 my $v = $input->param("items.".$c);
771 next unless defined $v;
776 # check that the barcode don't exist already
777 if ( Koha::Items->search({ barcode => $item->barcode, itemnumber => { '!=' => $item->itemnumber } })->count ) {
778 # FIXME We shouldn't need that, ->store would explode as there is a unique constraint on items.barcode
779 push @errors,"barcode_not_unique";
781 my $newitemlost = $item->itemlost;
782 if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
783 LostItem( $item->itemnumber, 'additem' );
789 } elsif ($op eq "delinkitem"){
791 my $analyticfield = '773';
792 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
793 $analyticfield = '773';
794 } elsif ($marcflavour eq 'UNIMARC') {
795 $analyticfield = '461';
797 foreach my $field ($record->field($analyticfield)){
798 if ($field->subfield('9') eq $hostitemnumber){
799 $record->delete_field($field);
803 my $modbibresult = ModBiblio($record, $biblionumber,'');
806 # update OAI-PMH sets
808 if (C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
809 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
814 #-------------------------------------------------------------------------------
815 # build screen with existing items. and "new" one
816 #-------------------------------------------------------------------------------
818 # now, build existiing item list
819 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
820 #my @fields = $record->fields();
823 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
825 #---- finds where items.itemnumber is stored
826 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
827 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
828 C4::Biblio::EmbedItemsInMarcBiblio({
829 marc_record => $temp,
830 biblionumber => $biblionumber });
831 my @fields = $temp->fields();
835 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
836 my $analyticfield = '773';
837 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
838 $analyticfield = '773';
839 } elsif ($marcflavour eq 'UNIMARC') {
840 $analyticfield = '461';
842 foreach my $hostfield ($temp->field($analyticfield)){
843 my $hostbiblionumber = $hostfield->subfield('0');
844 if ($hostbiblionumber){
845 my $hostrecord = GetMarcBiblio({
846 biblionumber => $hostbiblionumber,
849 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
850 foreach my $hostitem ($hostrecord->field($itemfield)){
851 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
852 push (@fields, $hostitem);
853 push (@hostitemnumbers, $hostfield->subfield('9'));
861 foreach my $field (@fields) {
862 next if ( $field->tag() < 10 );
864 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
866 # loop through each subfield
868 foreach my $subfield (@subf){
869 my $subfieldcode = $subfield->[0];
870 my $subfieldvalue= $subfield->[1];
872 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
873 && ($field->tag() ne $itemtagfield
874 && $subfieldcode ne $itemtagsubfield));
875 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
876 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
877 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
878 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
879 $subfieldcode, $subfieldvalue, '', $tagslib)
883 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
885 my $userenv = C4::Context->userenv();
886 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
887 $this_row{'nomod'} = 1;
890 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
892 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
893 foreach my $hostitemnumber (@hostitemnumbers) {
894 my $item = Koha::Items->find( $hostitemnumber );
895 if ($this_row{itemnumber} eq $hostitemnumber) {
896 $this_row{hostitemflag} = 1;
897 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
904 push(@big_array, \%this_row);
908 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
909 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
911 # now, construct template !
912 # First, the existing items for display
914 my @header_value_loop;
915 for my $row ( @big_array ) {
918 foreach my $key (sort keys %witness){
921 $item_field->{field} = $row->{$key};
923 $item_field->{field} = '';
927 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
930 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
931 next unless $key eq $subfield;
932 $item_field->{datatype} = 'date';
935 push @item_fields, $item_field;
937 $row_data{item_value} = [ @item_fields ];
938 $row_data{itemnumber} = $row->{itemnumber};
939 #reporting this_row values
940 $row_data{'nomod'} = $row->{'nomod'};
941 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
942 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
943 # $row_data{'countanalytics'} = $row->{'countanalytics'};
944 push(@item_value_loop,\%row_data);
946 foreach my $subfield_code (sort keys(%witness)) {
948 $header_value{header_value} = $witness{$subfield_code};
950 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
951 my $kohafield = $subfieldlib->{kohafield};
952 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
953 $header_value{column_name} = $1;
956 push(@header_value_loop, \%header_value);
959 # now, build the item form for entering a new item
963 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
964 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
965 for my $library ( @$libraries ) {
966 $library->{selected} = 1 if $library->{branchcode} eq $branch
969 my $item = Koha::Items->find($itemnumber);
971 # We generate form, from actuel record
974 foreach my $field ($itemrecord->fields()){
975 my $tag = $field->{_tag};
976 foreach my $subfield ( $field->subfields() ){
978 my $subfieldtag = $subfield->[0];
979 my $value = $subfield->[1];
980 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
982 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
984 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
985 push @fields, "$tag$subfieldtag";
986 push (@loop_data, $subfield_data);
992 # and now we add fields that are empty
994 # Using last created item if it exists
996 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
998 # We generate form, and fill with values if defined
999 foreach my $tag ( keys %{$tagslib}){
1000 foreach my $subtag (keys %{$tagslib->{$tag}}){
1001 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
1002 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
1003 next if any { /^$tag$subtag$/ } @fields;
1005 my @values = (undef);
1006 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
1007 for my $value (@values){
1008 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
1009 push (@loop_data, $subfield_data);
1014 @loop_data = sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} } @loop_data;
1016 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
1018 biblionumber => $biblionumber,
1019 title => $oldrecord->{title},
1020 author => $oldrecord->{author},
1021 item_loop => \@item_value_loop,
1022 item_header_loop => \@header_value_loop,
1023 item => \@loop_data,
1024 itemnumber => $itemnumber,
1025 barcode => $item ? $item->barcode : undef,
1026 itemtagfield => $itemtagfield,
1027 itemtagsubfield => $itemtagsubfield,
1029 popup => scalar $input->param('popup') ? 1: 0,
1030 C4::Search::enabled_staff_search_views,
1032 $template->{'VARS'}->{'searchid'} = $searchid;
1034 if ($frameworkcode eq 'FA'){
1035 # fast cataloguing datas
1037 'circborrowernumber' => $fa_circborrowernumber,
1038 'barcode' => $fa_barcode,
1039 'branch' => $fa_branch,
1040 'stickyduedate' => $fa_stickyduedate,
1041 'duedatespec' => $fa_duedatespec,
1045 foreach my $error (@errors) {
1046 $template->param($error => 1);
1048 output_html_with_http_headers $input, $cookie, $template->output;