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 List::MoreUtils qw/any/;
40 use Storable qw(thaw freeze);
47 our $dbh = C4::Context->dbh;
50 my ($tagfield,$insubfield,$record) = @_;
53 foreach my $field ($record->field($tagfield)) {
54 my @subfields = $field->subfields();
55 foreach my $subfield (@subfields) {
56 if (@$subfield[0] eq $insubfield) {
57 $result .= @$subfield[1];
58 $indicator = $field->indicator(1).$field->indicator(2);
62 return($indicator,$result);
65 sub get_item_from_barcode {
67 my $dbh=C4::Context->dbh;
69 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
70 $rq->execute($barcode);
71 ($result)=$rq->fetchrow;
75 sub set_item_default_location {
76 my $itemnumber = shift;
77 my $item = Koha::Items->find($itemnumber);
78 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
81 permanent_location => $item->location,
82 location => C4::Context->preference('NewItemsDefaultLocation')
89 ModItem( { permanent_location => $item->location }, undef, $itemnumber )
90 unless defined $item->permanent_location;
94 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
95 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
96 sub _increment_barcode {
97 my ($record, $frameworkcode) = @_;
98 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
99 unless ($record->field($tagfield)->subfield($tagsubfield)) {
100 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
101 $sth_barcode->execute;
102 my ($newbarcode) = $sth_barcode->fetchrow;
104 # OK, we have the new barcode, now create the entry in MARC record
105 my $fieldItem = $record->field($tagfield);
106 $record->delete_field($fieldItem);
107 $fieldItem->add_subfields($tagsubfield => $newbarcode);
108 $record->insert_fields_ordered($fieldItem);
114 sub generate_subfield_form {
115 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
117 my $frameworkcode = &GetFrameworkCode($biblionumber);
120 my $dbh = C4::Context->dbh;
122 my $index_subfield = int(rand(1000000));
123 if ($subfieldtag eq '@'){
124 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
126 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
129 $subfield_data{tag} = $tag;
130 $subfield_data{subfield} = $subfieldtag;
131 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
132 $subfield_data{mandatory} = $subfieldlib->{mandatory};
133 $subfield_data{important} = $subfieldlib->{important};
134 $subfield_data{repeatable} = $subfieldlib->{repeatable};
135 $subfield_data{maxlength} = $subfieldlib->{maxlength};
137 if ( ! defined( $value ) || $value eq '') {
138 $value = $subfieldlib->{defaultvalue};
140 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
141 my $today_dt = dt_from_string;
142 my $year = $today_dt->strftime('%Y');
143 my $month = $today_dt->strftime('%m');
144 my $day = $today_dt->strftime('%d');
145 $value =~ s/<<YYYY>>/$year/g;
146 $value =~ s/<<MM>>/$month/g;
147 $value =~ s/<<DD>>/$day/g;
148 # And <<USER>> with surname (?)
149 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
150 $value=~s/<<USER>>/$username/g;
154 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
156 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
157 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
158 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
159 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
160 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
161 my $temp2 = $temp->field($CNtag);
164 $value = $temp2->as_string( $CNsubfields, ' ' );
169 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
171 $value = $input->param('barcode');
174 if ( $subfieldlib->{authorised_value} ) {
175 my @authorised_values;
177 # builds list, depending on authorised value...
178 if ( $subfieldlib->{authorised_value} eq "branches" ) {
179 foreach my $thisbranch (@$branches) {
180 push @authorised_values, $thisbranch->{branchcode};
181 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
182 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
185 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
186 push @authorised_values, "";
187 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
190 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
192 $itemtypes = Koha::ItemTypes->search_with_localization;
194 while ( my $itemtype = $itemtypes->next ) {
195 push @authorised_values, $itemtype->itemtype;
196 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
200 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
201 $itype_sth->execute( $biblionumber );
202 ( $value ) = $itype_sth->fetchrow_array;
207 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
208 push @authorised_values, "";
210 my $class_sources = GetClassSources();
211 my $default_source = C4::Context->preference("DefaultClassificationSource");
213 foreach my $class_source (sort keys %$class_sources) {
214 next unless $class_sources->{$class_source}->{'used'} or
215 ($value and $class_source eq $value) or
216 ($class_source eq $default_source);
217 push @authorised_values, $class_source;
218 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
220 $value = $default_source unless ($value);
222 #---- "true" authorised value
225 push @authorised_values, qq{};
226 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
228 push @authorised_values, $r->{authorised_value};
229 $authorised_lib{$r->{authorised_value}} = $r->{lib};
233 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
234 $subfield_data{marc_value} = {
236 id => $subfield_data{id},
237 maxlength => $subfield_data{maxlength},
242 $subfield_data{marc_value} = {
244 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
245 values => \@authorised_values,
246 labels => \%authorised_lib,
251 # it's a thesaurus / authority field
252 elsif ( $subfieldlib->{authtypecode} ) {
253 $subfield_data{marc_value} = {
255 id => $subfield_data{id},
256 maxlength => $subfield_data{maxlength},
258 authtypecode => $subfieldlib->{authtypecode},
261 # it's a plugin field
262 elsif ( $subfieldlib->{value_builder} ) { # plugin
263 require Koha::FrameworkPlugin;
264 my $plugin = Koha::FrameworkPlugin->new({
265 name => $subfieldlib->{'value_builder'},
268 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
269 id => $subfield_data{id}, tabloop => $loop_data };
270 $plugin->build( $pars );
271 if( !$plugin->errstr ) {
272 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
273 $subfield_data{marc_value} = {
274 type => 'text_plugin',
275 id => $subfield_data{id},
276 maxlength => $subfield_data{maxlength},
279 nopopup => $plugin->noclick,
280 javascript => $plugin->javascript,
283 warn $plugin->errstr;
284 $subfield_data{marc_value} = {
286 id => $subfield_data{id},
287 maxlength => $subfield_data{maxlength},
289 }; # supply default input form
292 elsif ( $tag eq '' ) { # it's an hidden field
293 $subfield_data{marc_value} = {
295 id => $subfield_data{id},
296 maxlength => $subfield_data{maxlength},
300 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
301 $subfield_data{marc_value} = {
303 id => $subfield_data{id},
304 maxlength => $subfield_data{maxlength},
310 $value and length($value) > 100
313 C4::Context->preference("marcflavour") eq "UNIMARC"
314 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
317 C4::Context->preference("marcflavour") eq "MARC21"
318 and 500 <= $tag && $tag < 600
321 # oversize field (textarea)
322 $subfield_data{marc_value} = {
324 id => $subfield_data{id},
328 # it's a standard field
329 $subfield_data{marc_value} = {
331 id => $subfield_data{id},
332 maxlength => $subfield_data{maxlength},
337 # Getting list of subfields to keep when restricted editing is enabled
338 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
339 my $allowAllSubfields = (
340 not defined $subfieldsToAllowForRestrictedEditing
341 or $subfieldsToAllowForRestrictedEditing eq q||
343 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
345 # If we're on restricted editing, and our field is not in the list of subfields to allow,
346 # then it is read-only
347 $subfield_data{marc_value}->{readonly} = (
348 not $allowAllSubfields
349 and $restrictededition
350 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
353 return \%subfield_data;
356 # Removes some subfields when prefilling items
357 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
358 sub removeFieldsForPrefill {
363 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
365 # Getting list of subfields to keep
366 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
368 # Removing subfields that are not in the syspref
369 if ($tag && $subfieldsToUseWhenPrefill) {
370 my $field = $item->field($tag);
371 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
372 foreach my $subfield ($field->subfields()) {
373 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
374 $field->delete_subfield(code => $subfield->[0]);
385 my $error = $input->param('error');
386 my $biblionumber = $input->param('biblionumber');
387 my $itemnumber = $input->param('itemnumber');
388 my $op = $input->param('op') || q{};
389 my $hostitemnumber = $input->param('hostitemnumber');
390 my $marcflavour = C4::Context->preference("marcflavour");
391 my $searchid = $input->param('searchid');
392 # fast cataloguing datas
393 my $fa_circborrowernumber = $input->param('circborrowernumber');
394 my $fa_barcode = $input->param('barcode');
395 my $fa_branch = $input->param('branch');
396 my $fa_stickyduedate = $input->param('stickyduedate');
397 my $fa_duedatespec = $input->param('duedatespec');
399 my $frameworkcode = &GetFrameworkCode($biblionumber);
401 # Defining which userflag is needing according to the framework currently used
403 if (defined $input->param('frameworkcode')) {
404 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
407 if (not defined $userflags) {
408 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
411 my ($template, $loggedinuser, $cookie)
412 = get_template_and_user({template_name => "cataloguing/additem.tt",
415 authnotrequired => 0,
416 flagsrequired => {editcatalogue => $userflags},
421 # Does the user have a restricted item editing permission?
422 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
423 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
424 # In case user is a superlibrarian, editing is not restricted
425 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
426 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
427 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
429 my $tagslib = &GetMarcStructure(1,$frameworkcode);
430 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
432 output_and_exit_if_error( $input, $cookie, $template,
433 { module => 'cataloguing', record => $record } );
435 my $oldrecord = TransformMarcToKoha($record);
437 my $nextop="additem";
438 my @errors; # store errors found while checking data BEFORE saving item.
440 # Getting last created item cookie
441 my $prefillitem = C4::Context->preference('PrefillItem');
443 my $cookieitemrecord;
445 my $lastitemcookie = $input->cookie('LastCreatedItem');
446 if ($lastitemcookie) {
447 $lastitemcookie = uri_unescape($lastitemcookie);
449 if ( thaw($lastitemcookie) ) {
450 $cookieitemrecord = thaw($lastitemcookie);
451 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
455 $lastitemcookie = 'undef' unless $lastitemcookie;
456 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
461 #-------------------------------------------------------------------------------
462 if ($op eq "additem") {
464 #-------------------------------------------------------------------------------
466 my @tags = $input->multi_param('tag');
467 my @subfields = $input->multi_param('subfield');
468 my @values = $input->multi_param('field_value');
469 # build indicator hash.
470 my @ind_tag = $input->multi_param('ind_tag');
471 my @indicator = $input->multi_param('indicator');
472 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
473 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
476 my $add_submit = $input->param('add_submit');
477 my $add_duplicate_submit = $input->param('add_duplicate_submit');
478 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
479 my $number_of_copies = $input->param('number_of_copies');
481 # This is a bit tricky : if there is a cookie for the last created item and
482 # we just added an item, the cookie value is not correct yet (it will be updated
483 # next page). To prevent the form from being filled with outdated values, we
484 # force the use of "add and duplicate" feature, so the form will be filled with
486 $add_duplicate_submit = 1 if ($prefillitem);
489 # if autoBarcode is set to 'incremental', calculate barcode...
490 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
491 $record = _increment_barcode($record, $frameworkcode);
494 my $addedolditem = TransformMarcToKoha( $record );
496 # If we have to add or add & duplicate, we add the item
497 if ( $add_submit || $add_duplicate_submit ) {
499 # check for item barcode # being unique
500 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
501 push @errors, "barcode_not_unique" if ($exist_itemnumber);
503 # if barcode exists, don't create, but report The problem.
504 unless ($exist_itemnumber) {
505 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
506 set_item_default_location($oldbibitemnum);
508 # Pushing the last created item cookie back
509 if ($prefillitem && defined $record) {
510 my $itemcookie = $input->cookie(
511 -name => 'LastCreatedItem',
512 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
513 -value => uri_escape_utf8( freeze( $record ) ),
518 $cookie = [ $cookie, $itemcookie ];
523 if ($exist_itemnumber) {
524 $itemrecord = $record;
528 # If we have to add & duplicate
529 if ($add_duplicate_submit) {
530 $itemrecord = $record;
531 if (C4::Context->preference('autoBarcode') eq 'incremental') {
532 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
535 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
536 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
537 my $fieldItem = $itemrecord->field($tagfield);
538 $itemrecord->delete_field($fieldItem);
539 $fieldItem->delete_subfields($tagsubfield);
540 $itemrecord->insert_fields_ordered($fieldItem);
542 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
545 # If we have to add multiple copies
546 if ($add_multiple_copies_submit) {
549 my $barcodeobj = C4::Barcodes->new;
550 my $copynumber = $addedolditem->{'copynumber'};
551 my $oldbarcode = $addedolditem->{'barcode'};
552 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
553 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
555 # If there is a barcode and we can't find their new values, we can't add multiple copies
557 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
558 if ($oldbarcode && !$testbarcode) {
560 push @errors, "no_next_barcode";
561 $itemrecord = $record;
566 # For the first iteration
567 my $barcodevalue = $oldbarcode;
568 my $exist_itemnumber;
571 for (my $i = 0; $i < $number_of_copies;) {
573 # If there is a barcode
576 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
577 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
579 # Putting it into the record
581 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
582 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
583 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
584 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
585 # But when adding multiple copies we need to prefix it here,
586 # so we retrieve the homebranch from the item and prefix the barcode with it.
587 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
588 my $homebranch = $record->subfield($hb_field, $hb_subfield);
589 $barcodevalue = $homebranch . $barcodevalue;
591 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
594 # Checking if the barcode already exists
595 $exist_itemnumber = get_item_from_barcode($barcodevalue);
597 # Updating record with the new copynumber
599 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
603 if (!$exist_itemnumber) {
604 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
605 set_item_default_location($oldbibitemnum);
607 # We count the item only if it was really added
608 # That way, all items are added, even if there was some already existing barcodes
609 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
611 # Only increment copynumber if item was really added
612 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
615 # Preparing the next iteration
616 $oldbarcode = $barcodevalue;
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 $error = &DelItemCheck( $biblionumber,$itemnumber);
679 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
684 #-------------------------------------------------------------------------------
685 } elsif ($op eq "delallitems") {
686 #-------------------------------------------------------------------------------
687 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber })->get_column('itemnumber');
688 foreach my $itemnumber ( @itemnumbers ) {
689 $error = C4::Items::DelItemCheck( $biblionumber, $itemnumber );
690 next if $error == 1; # Means ok
696 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
697 my $views = { C4::Search::enabled_staff_search_views };
698 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
699 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
700 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
701 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
702 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
703 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
705 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
709 #-------------------------------------------------------------------------------
710 } elsif ($op eq "saveitem") {
711 #-------------------------------------------------------------------------------
713 my @tags = $input->multi_param('tag');
714 my @subfields = $input->multi_param('subfield');
715 my @values = $input->multi_param('field_value');
716 # build indicator hash.
717 my @ind_tag = $input->multi_param('ind_tag');
718 my @indicator = $input->multi_param('indicator');
719 # my $itemnumber = $input->param('itemnumber');
720 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
721 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
722 # MARC::Record builded => now, record in DB
723 # warn "R: ".$record->as_formatted;
724 # check that the barcode don't exist already
725 my $addedolditem = TransformMarcToKoha($itemtosave);
726 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
727 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
728 push @errors,"barcode_not_unique";
730 my $item = Koha::Items->find($itemnumber );
731 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
733 my $olditemlost = $item->itemlost;
734 my $newitemlost = $newitem->{itemlost};
735 LostItem( $item->itemnumber, 'additem' )
736 if $newitemlost && $newitemlost ge '1' && !$olditemlost;
739 } elsif ($op eq "delinkitem"){
740 my $analyticfield = '773';
741 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
742 $analyticfield = '773';
743 } elsif ($marcflavour eq 'UNIMARC') {
744 $analyticfield = '461';
746 foreach my $field ($record->field($analyticfield)){
747 if ($field->subfield('9') eq $hostitemnumber){
748 $record->delete_field($field);
752 my $modbibresult = ModBiblio($record, $biblionumber,'');
756 #-------------------------------------------------------------------------------
757 # build screen with existing items. and "new" one
758 #-------------------------------------------------------------------------------
760 # now, build existiing item list
761 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
762 #my @fields = $record->fields();
765 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
767 #---- finds where items.itemnumber is stored
768 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
769 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
770 C4::Biblio::EmbedItemsInMarcBiblio({
771 marc_record => $temp,
772 biblionumber => $biblionumber });
773 my @fields = $temp->fields();
777 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
778 my $analyticfield = '773';
779 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
780 $analyticfield = '773';
781 } elsif ($marcflavour eq 'UNIMARC') {
782 $analyticfield = '461';
784 foreach my $hostfield ($temp->field($analyticfield)){
785 my $hostbiblionumber = $hostfield->subfield('0');
786 if ($hostbiblionumber){
787 my $hostrecord = GetMarcBiblio({
788 biblionumber => $hostbiblionumber,
791 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
792 foreach my $hostitem ($hostrecord->field($itemfield)){
793 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
794 push (@fields, $hostitem);
795 push (@hostitemnumbers, $hostfield->subfield('9'));
803 foreach my $field (@fields) {
804 next if ( $field->tag() < 10 );
806 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
808 # loop through each subfield
810 foreach my $subfield (@subf){
811 my $subfieldcode = $subfield->[0];
812 my $subfieldvalue= $subfield->[1];
814 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
815 && ($field->tag() ne $itemtagfield
816 && $subfieldcode ne $itemtagsubfield));
817 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
818 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
819 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
820 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
821 $subfieldcode, $subfieldvalue, '', $tagslib)
825 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
827 my $userenv = C4::Context->userenv();
828 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
829 $this_row{'nomod'} = 1;
832 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
834 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
835 foreach my $hostitemnumber (@hostitemnumbers) {
836 my $item = Koha::Items->find( $hostitemnumber );
837 if ($this_row{itemnumber} eq $hostitemnumber) {
838 $this_row{hostitemflag} = 1;
839 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
846 push(@big_array, \%this_row);
850 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
851 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
853 # now, construct template !
854 # First, the existing items for display
856 my @header_value_loop;
857 for my $row ( @big_array ) {
860 foreach my $key (sort keys %witness){
863 $item_field->{field} = $row->{$key};
865 $item_field->{field} = '';
867 if ( $key eq 'd' || $key eq 'q' || $key eq 'r' || $key eq 's' || $key eq 'w' ){
868 # date accessioned || on loan || date last seen || date last borrowed || replacement price date
869 $item_field->{field} = output_pref({ dt => dt_from_string( $row->{$key} ), dateonly => 1 });
872 push @item_fields, $item_field;
874 $row_data{item_value} = [ @item_fields ];
875 $row_data{itemnumber} = $row->{itemnumber};
876 #reporting this_row values
877 $row_data{'nomod'} = $row->{'nomod'};
878 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
879 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
880 # $row_data{'countanalytics'} = $row->{'countanalytics'};
881 push(@item_value_loop,\%row_data);
883 foreach my $subfield_code (sort keys(%witness)) {
885 $header_value{header_value} = $witness{$subfield_code};
887 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
888 my $kohafield = $subfieldlib->{kohafield};
889 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
890 $header_value{column_name} = $1;
893 push(@header_value_loop, \%header_value);
896 # now, build the item form for entering a new item
900 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
901 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
902 for my $library ( @$libraries ) {
903 $library->{selected} = 1 if $library->{branchcode} eq $branch
906 # We generate form, from actuel record
909 foreach my $field ($itemrecord->fields()){
910 my $tag = $field->{_tag};
911 foreach my $subfield ( $field->subfields() ){
913 my $subfieldtag = $subfield->[0];
914 my $value = $subfield->[1];
915 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
917 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
919 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
920 push @fields, "$tag$subfieldtag";
921 push (@loop_data, $subfield_data);
927 # and now we add fields that are empty
929 # Using last created item if it exists
931 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
933 # We generate form, and fill with values if defined
934 foreach my $tag ( keys %{$tagslib}){
935 foreach my $subtag (keys %{$tagslib->{$tag}}){
936 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
937 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
938 next if any { /^$tag$subtag$/ } @fields;
940 my @values = (undef);
941 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
942 for my $value (@values){
943 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
944 push (@loop_data, $subfield_data);
949 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
951 my $item = Koha::Items->find($itemnumber); # We certainly want to fetch it earlier
953 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
955 biblionumber => $biblionumber,
956 title => $oldrecord->{title},
957 author => $oldrecord->{author},
958 item_loop => \@item_value_loop,
959 item_header_loop => \@header_value_loop,
961 itemnumber => $itemnumber,
962 barcode => $item ? $item->barcode : undef,
963 itemtagfield => $itemtagfield,
964 itemtagsubfield => $itemtagsubfield,
966 popup => scalar $input->param('popup') ? 1: 0,
967 C4::Search::enabled_staff_search_views,
969 $template->{'VARS'}->{'searchid'} = $searchid;
971 if ($frameworkcode eq 'FA'){
972 # fast cataloguing datas
974 'circborrowernumber' => $fa_circborrowernumber,
975 'barcode' => $fa_barcode,
976 'branch' => $fa_branch,
977 'stickyduedate' => $fa_stickyduedate,
978 'duedatespec' => $fa_duedatespec,
982 foreach my $error (@errors) {
983 $template->param($error => 1);
985 output_html_with_http_headers $input, $cookie, $template->output;