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>.
38 use Koha::SearchEngine::Indexer;
39 use List::MoreUtils qw/any/;
41 use Storable qw(thaw freeze);
48 our $dbh = C4::Context->dbh;
51 my ($tagfield,$insubfield,$record) = @_;
54 foreach my $field ($record->field($tagfield)) {
55 my @subfields = $field->subfields();
56 foreach my $subfield (@subfields) {
57 if (@$subfield[0] eq $insubfield) {
58 $result .= @$subfield[1];
59 $indicator = $field->indicator(1).$field->indicator(2);
63 return($indicator,$result);
66 sub get_item_from_barcode {
68 my $dbh=C4::Context->dbh;
70 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
71 $rq->execute($barcode);
72 ($result)=$rq->fetchrow;
76 sub set_item_default_location {
77 my $itemnumber = shift;
78 my $item = Koha::Items->find($itemnumber);
79 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
80 $item->permanent_location($item->location);
81 $item->location(C4::Context->preference('NewItemsDefaultLocation'));
84 # It seems that we are dealing with that in too many places
85 $item->permanent_location($item->location) unless defined $item->permanent_location;
90 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
91 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
92 sub _increment_barcode {
93 my ($record, $frameworkcode) = @_;
94 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
95 unless ($record->field($tagfield)->subfield($tagsubfield)) {
96 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
97 $sth_barcode->execute;
98 my ($newbarcode) = $sth_barcode->fetchrow;
100 # OK, we have the new barcode, now create the entry in MARC record
101 my $fieldItem = $record->field($tagfield);
102 $record->delete_field($fieldItem);
103 $fieldItem->add_subfields($tagsubfield => $newbarcode);
104 $record->insert_fields_ordered($fieldItem);
110 sub generate_subfield_form {
111 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
113 my $frameworkcode = &GetFrameworkCode($biblionumber);
116 my $dbh = C4::Context->dbh;
118 my $index_subfield = int(rand(1000000));
119 if ($subfieldtag eq '@'){
120 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
122 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
125 $subfield_data{tag} = $tag;
126 $subfield_data{subfield} = $subfieldtag;
127 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
128 $subfield_data{mandatory} = $subfieldlib->{mandatory};
129 $subfield_data{important} = $subfieldlib->{important};
130 $subfield_data{repeatable} = $subfieldlib->{repeatable};
131 $subfield_data{maxlength} = $subfieldlib->{maxlength};
133 if ( ! defined( $value ) || $value eq '') {
134 $value = $subfieldlib->{defaultvalue};
136 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
137 my $today_dt = dt_from_string;
138 my $year = $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/<<MM>>/$month/g;
143 $value =~ s/<<DD>>/$day/g;
144 # And <<USER>> with surname (?)
145 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
146 $value=~s/<<USER>>/$username/g;
150 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
152 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
153 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
154 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
155 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
156 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
157 my $temp2 = $temp->field($CNtag);
160 $value = $temp2->as_string( $CNsubfields, ' ' );
165 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
167 $value = $input->param('barcode');
170 if ( $subfieldlib->{authorised_value} ) {
171 my @authorised_values;
173 # builds list, depending on authorised value...
174 if ( $subfieldlib->{authorised_value} eq "branches" ) {
175 foreach my $thisbranch (@$branches) {
176 push @authorised_values, $thisbranch->{branchcode};
177 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
178 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
181 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
182 push @authorised_values, "";
183 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
186 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
188 $itemtypes = Koha::ItemTypes->search_with_localization;
190 while ( my $itemtype = $itemtypes->next ) {
191 push @authorised_values, $itemtype->itemtype;
192 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
196 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
197 $itype_sth->execute( $biblionumber );
198 ( $value ) = $itype_sth->fetchrow_array;
203 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
204 push @authorised_values, "";
206 my $class_sources = GetClassSources();
207 my $default_source = C4::Context->preference("DefaultClassificationSource");
209 foreach my $class_source (sort keys %$class_sources) {
210 next unless $class_sources->{$class_source}->{'used'} or
211 ($value and $class_source eq $value) or
212 ($class_source eq $default_source);
213 push @authorised_values, $class_source;
214 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
216 $value = $default_source unless ($value);
218 #---- "true" authorised value
221 push @authorised_values, qq{};
222 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
224 push @authorised_values, $r->{authorised_value};
225 $authorised_lib{$r->{authorised_value}} = $r->{lib};
229 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
230 $subfield_data{marc_value} = {
232 id => $subfield_data{id},
233 maxlength => $subfield_data{maxlength},
238 $subfield_data{marc_value} = {
240 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
241 values => \@authorised_values,
242 labels => \%authorised_lib,
247 # it's a thesaurus / authority field
248 elsif ( $subfieldlib->{authtypecode} ) {
249 $subfield_data{marc_value} = {
251 id => $subfield_data{id},
252 maxlength => $subfield_data{maxlength},
254 authtypecode => $subfieldlib->{authtypecode},
257 # it's a plugin field
258 elsif ( $subfieldlib->{value_builder} ) { # plugin
259 require Koha::FrameworkPlugin;
260 my $plugin = Koha::FrameworkPlugin->new({
261 name => $subfieldlib->{'value_builder'},
264 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
265 id => $subfield_data{id}, tabloop => $loop_data };
266 $plugin->build( $pars );
267 if( !$plugin->errstr ) {
268 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
269 $subfield_data{marc_value} = {
270 type => 'text_plugin',
271 id => $subfield_data{id},
272 maxlength => $subfield_data{maxlength},
275 nopopup => $plugin->noclick,
276 javascript => $plugin->javascript,
279 warn $plugin->errstr;
280 $subfield_data{marc_value} = {
282 id => $subfield_data{id},
283 maxlength => $subfield_data{maxlength},
285 }; # supply default input form
288 elsif ( $tag eq '' ) { # it's an hidden field
289 $subfield_data{marc_value} = {
291 id => $subfield_data{id},
292 maxlength => $subfield_data{maxlength},
296 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
297 $subfield_data{marc_value} = {
299 id => $subfield_data{id},
300 maxlength => $subfield_data{maxlength},
306 $value and length($value) > 100
309 C4::Context->preference("marcflavour") eq "UNIMARC"
310 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
313 C4::Context->preference("marcflavour") eq "MARC21"
314 and 500 <= $tag && $tag < 600
317 # oversize field (textarea)
318 $subfield_data{marc_value} = {
320 id => $subfield_data{id},
324 # it's a standard field
325 $subfield_data{marc_value} = {
327 id => $subfield_data{id},
328 maxlength => $subfield_data{maxlength},
333 # Getting list of subfields to keep when restricted editing is enabled
334 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
335 my $allowAllSubfields = (
336 not defined $subfieldsToAllowForRestrictedEditing
337 or $subfieldsToAllowForRestrictedEditing eq q||
339 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
341 # If we're on restricted editing, and our field is not in the list of subfields to allow,
342 # then it is read-only
343 $subfield_data{marc_value}->{readonly} = (
344 not $allowAllSubfields
345 and $restrictededition
346 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
349 return \%subfield_data;
352 # Removes some subfields when prefilling items
353 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
354 sub removeFieldsForPrefill {
359 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
361 # Getting list of subfields to keep
362 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
364 # Removing subfields that are not in the syspref
365 if ($tag && $subfieldsToUseWhenPrefill) {
366 my $field = $item->field($tag);
367 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
368 foreach my $subfield ($field->subfields()) {
369 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
370 $field->delete_subfield(code => $subfield->[0]);
381 my $error = $input->param('error');
382 my $biblionumber = $input->param('biblionumber');
383 my $itemnumber = $input->param('itemnumber');
384 my $op = $input->param('op') || q{};
385 my $hostitemnumber = $input->param('hostitemnumber');
386 my $marcflavour = C4::Context->preference("marcflavour");
387 my $searchid = $input->param('searchid');
388 # fast cataloguing datas
389 my $fa_circborrowernumber = $input->param('circborrowernumber');
390 my $fa_barcode = $input->param('barcode');
391 my $fa_branch = $input->param('branch');
392 my $fa_stickyduedate = $input->param('stickyduedate');
393 my $fa_duedatespec = $input->param('duedatespec');
395 my $frameworkcode = &GetFrameworkCode($biblionumber);
397 # Defining which userflag is needing according to the framework currently used
399 if (defined $input->param('frameworkcode')) {
400 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
403 if (not defined $userflags) {
404 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
407 my ($template, $loggedinuser, $cookie)
408 = get_template_and_user({template_name => "cataloguing/additem.tt",
411 flagsrequired => {editcatalogue => $userflags},
416 # Does the user have a restricted item editing permission?
417 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
418 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
419 # In case user is a superlibrarian, editing is not restricted
420 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
421 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
422 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
424 my $tagslib = &GetMarcStructure(1,$frameworkcode);
425 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
427 output_and_exit_if_error( $input, $cookie, $template,
428 { module => 'cataloguing', record => $record } );
430 my $oldrecord = TransformMarcToKoha($record);
432 my $nextop="additem";
433 my @errors; # store errors found while checking data BEFORE saving item.
435 # Getting last created item cookie
436 my $prefillitem = C4::Context->preference('PrefillItem');
438 my $cookieitemrecord;
440 my $lastitemcookie = $input->cookie('LastCreatedItem');
441 if ($lastitemcookie) {
442 $lastitemcookie = uri_unescape($lastitemcookie);
444 if ( thaw($lastitemcookie) ) {
445 $cookieitemrecord = thaw($lastitemcookie);
446 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
450 $lastitemcookie = 'undef' unless $lastitemcookie;
451 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
456 #-------------------------------------------------------------------------------
457 if ($op eq "additem") {
459 #-------------------------------------------------------------------------------
461 my @tags = $input->multi_param('tag');
462 my @subfields = $input->multi_param('subfield');
463 my @values = $input->multi_param('field_value');
464 # build indicator hash.
465 my @ind_tag = $input->multi_param('ind_tag');
466 my @indicator = $input->multi_param('indicator');
467 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
468 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
471 my $add_submit = $input->param('add_submit');
472 my $add_duplicate_submit = $input->param('add_duplicate_submit');
473 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
474 my $number_of_copies = $input->param('number_of_copies');
476 # This is a bit tricky : if there is a cookie for the last created item and
477 # we just added an item, the cookie value is not correct yet (it will be updated
478 # next page). To prevent the form from being filled with outdated values, we
479 # force the use of "add and duplicate" feature, so the form will be filled with
481 $add_duplicate_submit = 1 if ($prefillitem);
484 # if autoBarcode is set to 'incremental', calculate barcode...
485 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
486 $record = _increment_barcode($record, $frameworkcode);
489 my $addedolditem = TransformMarcToKoha( $record );
491 # If we have to add or add & duplicate, we add the item
492 if ( $add_submit || $add_duplicate_submit ) {
494 # check for item barcode # being unique
495 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
496 push @errors, "barcode_not_unique" if ($exist_itemnumber);
498 # if barcode exists, don't create, but report The problem.
499 unless ($exist_itemnumber) {
500 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
501 set_item_default_location($oldbibitemnum);
503 # Pushing the last created item cookie back
504 if ($prefillitem && defined $record) {
505 my $itemcookie = $input->cookie(
506 -name => 'LastCreatedItem',
507 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
508 -value => uri_escape_utf8( freeze( $record ) ),
513 $cookie = [ $cookie, $itemcookie ];
518 if ($exist_itemnumber) {
519 $itemrecord = $record;
523 # If we have to add & duplicate
524 if ($add_duplicate_submit) {
525 $itemrecord = $record;
526 if (C4::Context->preference('autoBarcode') eq 'incremental') {
527 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
530 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
531 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
532 my $fieldItem = $itemrecord->field($tagfield);
533 $itemrecord->delete_field($fieldItem);
534 $fieldItem->delete_subfields($tagsubfield);
535 $itemrecord->insert_fields_ordered($fieldItem);
537 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
540 # If we have to add multiple copies
541 if ($add_multiple_copies_submit) {
544 my $barcodeobj = C4::Barcodes->new;
545 my $copynumber = $addedolditem->{'copynumber'};
546 my $oldbarcode = $addedolditem->{'barcode'};
547 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
548 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
550 # If there is a barcode and we can't find their new values, we can't add multiple copies
552 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
553 if ($oldbarcode && !$testbarcode) {
555 push @errors, "no_next_barcode";
556 $itemrecord = $record;
561 # For the first iteration
562 my $barcodevalue = $oldbarcode;
563 my $exist_itemnumber;
566 for (my $i = 0; $i < $number_of_copies;) {
568 # If there is a barcode
571 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
572 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
574 # Putting it into the record
576 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
577 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
578 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
579 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
580 # But when adding multiple copies we need to prefix it here,
581 # so we retrieve the homebranch from the item and prefix the barcode with it.
582 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
583 my $homebranch = $record->subfield($hb_field, $hb_subfield);
584 $barcodevalue = $homebranch . $barcodevalue;
586 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
589 # Checking if the barcode already exists
590 $exist_itemnumber = get_item_from_barcode($barcodevalue);
592 # Updating record with the new copynumber
594 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
598 if (!$exist_itemnumber) {
599 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
600 AddItemFromMarc( $record, $biblionumber, { skip_record_index => 1 } );
601 set_item_default_location($oldbibitemnum);
603 # We count the item only if it was really added
604 # That way, all items are added, even if there was some already existing barcodes
605 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
607 # Only increment copynumber if item was really added
608 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
611 # Preparing the next iteration
612 $oldbarcode = $barcodevalue;
615 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
616 $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
621 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
622 print $input->redirect(
623 '/cgi-bin/koha/circ/circulation.pl?'
624 .'borrowernumber='.$fa_circborrowernumber
625 .'&barcode='.uri_escape_utf8($fa_barcode)
626 .'&duedatespec='.$fa_duedatespec
633 #-------------------------------------------------------------------------------
634 } elsif ($op eq "edititem") {
635 #-------------------------------------------------------------------------------
636 # retrieve item if exist => then, it's a modif
637 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
638 $nextop = "saveitem";
639 #-------------------------------------------------------------------------------
640 } elsif ($op eq "dupeitem") {
641 #-------------------------------------------------------------------------------
642 # retrieve item if exist => then, it's a modif
643 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
644 if (C4::Context->preference('autoBarcode') eq 'incremental') {
645 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
648 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
649 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
650 my $fieldItem = $itemrecord->field($tagfield);
651 $itemrecord->delete_field($fieldItem);
652 $fieldItem->delete_subfields($tagsubfield);
653 $itemrecord->insert_fields_ordered($fieldItem);
656 #check for hidden subfield and remove them for the duplicated item
657 foreach my $field ($itemrecord->fields()){
658 my $tag = $field->{_tag};
659 foreach my $subfield ($field->subfields()){
660 my $subfieldtag = $subfield->[0];
661 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
662 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
663 my $fieldItem = $itemrecord->field($tag);
664 $itemrecord->delete_field($fieldItem);
665 $fieldItem->delete_subfields($subfieldtag);
666 $itemrecord->insert_fields_ordered($fieldItem);
671 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
673 #-------------------------------------------------------------------------------
674 } elsif ($op eq "delitem") {
675 #-------------------------------------------------------------------------------
676 # check that there is no issue on this item before deletion.
677 my $item = Koha::Items->find($itemnumber);
678 $error = $item->safe_delete;
679 if(ref($error) eq 'Koha::Item'){
680 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
685 #-------------------------------------------------------------------------------
686 } elsif ($op eq "delallitems") {
687 #-------------------------------------------------------------------------------
688 my $items = Koha::Items->search({ biblionumber => $biblionumber });
689 while ( my $item = $items->next ) {
690 $error = $item->safe_delete({ skip_record_index => 1 });
691 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
694 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
695 $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
699 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
700 my $views = { C4::Search::enabled_staff_search_views };
701 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
702 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
703 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
704 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
705 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
706 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
708 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
712 #-------------------------------------------------------------------------------
713 } elsif ($op eq "saveitem") {
714 #-------------------------------------------------------------------------------
716 my @tags = $input->multi_param('tag');
717 my @subfields = $input->multi_param('subfield');
718 my @values = $input->multi_param('field_value');
719 # build indicator hash.
720 my @ind_tag = $input->multi_param('ind_tag');
721 my @indicator = $input->multi_param('indicator');
722 # my $itemnumber = $input->param('itemnumber');
723 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
724 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
725 # MARC::Record builded => now, record in DB
726 # warn "R: ".$record->as_formatted;
727 # check that the barcode don't exist already
728 my $addedolditem = TransformMarcToKoha($itemtosave);
729 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
730 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
731 push @errors,"barcode_not_unique";
733 my $item = Koha::Items->find($itemnumber );
734 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
736 my $olditemlost = $item->itemlost;
737 my $newitemlost = $newitem->{itemlost};
738 LostItem( $item->itemnumber, 'additem' )
739 if $newitemlost && $newitemlost ge '1' && !$olditemlost;
742 } elsif ($op eq "delinkitem"){
743 my $analyticfield = '773';
744 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
745 $analyticfield = '773';
746 } elsif ($marcflavour eq 'UNIMARC') {
747 $analyticfield = '461';
749 foreach my $field ($record->field($analyticfield)){
750 if ($field->subfield('9') eq $hostitemnumber){
751 $record->delete_field($field);
755 my $modbibresult = ModBiblio($record, $biblionumber,'');
759 #-------------------------------------------------------------------------------
760 # build screen with existing items. and "new" one
761 #-------------------------------------------------------------------------------
763 # now, build existiing item list
764 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
765 #my @fields = $record->fields();
768 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
770 #---- finds where items.itemnumber is stored
771 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
772 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
773 C4::Biblio::EmbedItemsInMarcBiblio({
774 marc_record => $temp,
775 biblionumber => $biblionumber });
776 my @fields = $temp->fields();
780 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
781 my $analyticfield = '773';
782 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
783 $analyticfield = '773';
784 } elsif ($marcflavour eq 'UNIMARC') {
785 $analyticfield = '461';
787 foreach my $hostfield ($temp->field($analyticfield)){
788 my $hostbiblionumber = $hostfield->subfield('0');
789 if ($hostbiblionumber){
790 my $hostrecord = GetMarcBiblio({
791 biblionumber => $hostbiblionumber,
794 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
795 foreach my $hostitem ($hostrecord->field($itemfield)){
796 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
797 push (@fields, $hostitem);
798 push (@hostitemnumbers, $hostfield->subfield('9'));
806 foreach my $field (@fields) {
807 next if ( $field->tag() < 10 );
809 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
811 # loop through each subfield
813 foreach my $subfield (@subf){
814 my $subfieldcode = $subfield->[0];
815 my $subfieldvalue= $subfield->[1];
817 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
818 && ($field->tag() ne $itemtagfield
819 && $subfieldcode ne $itemtagsubfield));
820 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
821 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
822 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
823 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
824 $subfieldcode, $subfieldvalue, '', $tagslib)
828 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
830 my $userenv = C4::Context->userenv();
831 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
832 $this_row{'nomod'} = 1;
835 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
837 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
838 foreach my $hostitemnumber (@hostitemnumbers) {
839 my $item = Koha::Items->find( $hostitemnumber );
840 if ($this_row{itemnumber} eq $hostitemnumber) {
841 $this_row{hostitemflag} = 1;
842 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
849 push(@big_array, \%this_row);
853 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
854 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
856 # now, construct template !
857 # First, the existing items for display
859 my @header_value_loop;
860 for my $row ( @big_array ) {
863 foreach my $key (sort keys %witness){
866 $item_field->{field} = $row->{$key};
868 $item_field->{field} = '';
872 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
875 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
876 next unless $key eq $subfield;
877 $item_field->{datatype} = 'date';
880 push @item_fields, $item_field;
882 $row_data{item_value} = [ @item_fields ];
883 $row_data{itemnumber} = $row->{itemnumber};
884 #reporting this_row values
885 $row_data{'nomod'} = $row->{'nomod'};
886 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
887 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
888 # $row_data{'countanalytics'} = $row->{'countanalytics'};
889 push(@item_value_loop,\%row_data);
891 foreach my $subfield_code (sort keys(%witness)) {
893 $header_value{header_value} = $witness{$subfield_code};
895 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
896 my $kohafield = $subfieldlib->{kohafield};
897 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
898 $header_value{column_name} = $1;
901 push(@header_value_loop, \%header_value);
904 # now, build the item form for entering a new item
908 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
909 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
910 for my $library ( @$libraries ) {
911 $library->{selected} = 1 if $library->{branchcode} eq $branch
914 # We generate form, from actuel record
917 foreach my $field ($itemrecord->fields()){
918 my $tag = $field->{_tag};
919 foreach my $subfield ( $field->subfields() ){
921 my $subfieldtag = $subfield->[0];
922 my $value = $subfield->[1];
923 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
925 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
927 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
928 push @fields, "$tag$subfieldtag";
929 push (@loop_data, $subfield_data);
935 # and now we add fields that are empty
937 # Using last created item if it exists
939 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
941 # We generate form, and fill with values if defined
942 foreach my $tag ( keys %{$tagslib}){
943 foreach my $subtag (keys %{$tagslib->{$tag}}){
944 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
945 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
946 next if any { /^$tag$subtag$/ } @fields;
948 my @values = (undef);
949 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
950 for my $value (@values){
951 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
952 push (@loop_data, $subfield_data);
957 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
959 my $item = Koha::Items->find($itemnumber); # We certainly want to fetch it earlier
961 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
963 biblionumber => $biblionumber,
964 title => $oldrecord->{title},
965 author => $oldrecord->{author},
966 item_loop => \@item_value_loop,
967 item_header_loop => \@header_value_loop,
969 itemnumber => $itemnumber,
970 barcode => $item ? $item->barcode : undef,
971 itemtagfield => $itemtagfield,
972 itemtagsubfield => $itemtagsubfield,
974 popup => scalar $input->param('popup') ? 1: 0,
975 C4::Search::enabled_staff_search_views,
977 $template->{'VARS'}->{'searchid'} = $searchid;
979 if ($frameworkcode eq 'FA'){
980 # fast cataloguing datas
982 'circborrowernumber' => $fa_circborrowernumber,
983 'barcode' => $fa_barcode,
984 'branch' => $fa_branch,
985 'stickyduedate' => $fa_stickyduedate,
986 'duedatespec' => $fa_duedatespec,
990 foreach my $error (@errors) {
991 $template->param($error => 1);
993 output_html_with_http_headers $input, $cookie, $template->output;