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') ) {
79 $item->permanent_location($item->location);
80 $item->location(C4::Context->preference('NewItemsDefaultLocation'));
83 # It seems that we are dealing with that in too many places
84 $item->permanent_location($item->location) unless defined $item->permanent_location;
89 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
90 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
91 sub _increment_barcode {
92 my ($record, $frameworkcode) = @_;
93 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
94 unless ($record->field($tagfield)->subfield($tagsubfield)) {
95 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
96 $sth_barcode->execute;
97 my ($newbarcode) = $sth_barcode->fetchrow;
99 # OK, we have the new barcode, now create the entry in MARC record
100 my $fieldItem = $record->field($tagfield);
101 $record->delete_field($fieldItem);
102 $fieldItem->add_subfields($tagsubfield => $newbarcode);
103 $record->insert_fields_ordered($fieldItem);
109 sub generate_subfield_form {
110 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition, $item) = @_;
112 my $frameworkcode = &GetFrameworkCode($biblionumber);
115 my $dbh = C4::Context->dbh;
117 my $index_subfield = int(rand(1000000));
118 if ($subfieldtag eq '@'){
119 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
121 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
124 $subfield_data{tag} = $tag;
125 $subfield_data{subfield} = $subfieldtag;
126 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
127 $subfield_data{mandatory} = $subfieldlib->{mandatory};
128 $subfield_data{important} = $subfieldlib->{important};
129 $subfield_data{repeatable} = $subfieldlib->{repeatable};
130 $subfield_data{maxlength} = $subfieldlib->{maxlength};
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 my $temp2 = $temp->field($CNtag);
161 $value = $temp2->as_string( $CNsubfields, ' ' );
166 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
168 $value = $input->param('barcode');
171 if ( $subfieldlib->{authorised_value} ) {
172 my @authorised_values;
174 # builds list, depending on authorised value...
175 if ( $subfieldlib->{authorised_value} eq "LOST" ) {
176 my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue');
177 my $item_is_return_claim = $ClaimReturnedLostValue && $item && $item->itemlost && $ClaimReturnedLostValue eq $item->itemlost;
178 $subfield_data{IS_RETURN_CLAIM} = $item_is_return_claim;
180 $subfield_data{IS_LOST_AV} = 1;
182 push @authorised_values, qq{};
183 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
185 push @authorised_values, $r->{authorised_value};
186 $authorised_lib{$r->{authorised_value}} = $r->{lib};
189 elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
190 foreach my $thisbranch (@$branches) {
191 push @authorised_values, $thisbranch->{branchcode};
192 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
193 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
196 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
197 push @authorised_values, "";
198 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
201 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
203 $itemtypes = Koha::ItemTypes->search_with_localization;
205 while ( my $itemtype = $itemtypes->next ) {
206 push @authorised_values, $itemtype->itemtype;
207 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
211 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
212 $itype_sth->execute( $biblionumber );
213 ( $value ) = $itype_sth->fetchrow_array;
218 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
219 push @authorised_values, "";
221 my $class_sources = GetClassSources();
222 my $default_source = C4::Context->preference("DefaultClassificationSource");
224 foreach my $class_source (sort keys %$class_sources) {
225 next unless $class_sources->{$class_source}->{'used'} or
226 ($value and $class_source eq $value) or
227 ($class_source eq $default_source);
228 push @authorised_values, $class_source;
229 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
231 $value = $default_source unless ($value);
233 #---- "true" authorised value
236 push @authorised_values, qq{};
237 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
239 push @authorised_values, $r->{authorised_value};
240 $authorised_lib{$r->{authorised_value}} = $r->{lib};
244 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
245 $subfield_data{marc_value} = {
247 id => $subfield_data{id},
248 maxlength => $subfield_data{maxlength},
253 $subfield_data{marc_value} = {
255 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
256 values => \@authorised_values,
257 labels => \%authorised_lib,
262 # it's a thesaurus / authority field
263 elsif ( $subfieldlib->{authtypecode} ) {
264 $subfield_data{marc_value} = {
266 id => $subfield_data{id},
267 maxlength => $subfield_data{maxlength},
269 authtypecode => $subfieldlib->{authtypecode},
272 # it's a plugin field
273 elsif ( $subfieldlib->{value_builder} ) { # plugin
274 require Koha::FrameworkPlugin;
275 my $plugin = Koha::FrameworkPlugin->new({
276 name => $subfieldlib->{'value_builder'},
279 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
280 id => $subfield_data{id}, tabloop => $loop_data };
281 $plugin->build( $pars );
282 if( !$plugin->errstr ) {
283 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
284 $subfield_data{marc_value} = {
285 type => 'text_plugin',
286 id => $subfield_data{id},
287 maxlength => $subfield_data{maxlength},
290 nopopup => $plugin->noclick,
291 javascript => $plugin->javascript,
294 warn $plugin->errstr;
295 $subfield_data{marc_value} = {
297 id => $subfield_data{id},
298 maxlength => $subfield_data{maxlength},
300 }; # supply default input form
303 elsif ( $tag eq '' ) { # it's an hidden field
304 $subfield_data{marc_value} = {
306 id => $subfield_data{id},
307 maxlength => $subfield_data{maxlength},
311 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
312 $subfield_data{marc_value} = {
314 id => $subfield_data{id},
315 maxlength => $subfield_data{maxlength},
321 $value and length($value) > 100
324 C4::Context->preference("marcflavour") eq "UNIMARC"
325 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
328 C4::Context->preference("marcflavour") eq "MARC21"
329 and 500 <= $tag && $tag < 600
332 # oversize field (textarea)
333 $subfield_data{marc_value} = {
335 id => $subfield_data{id},
339 # it's a standard field
340 $subfield_data{marc_value} = {
342 id => $subfield_data{id},
343 maxlength => $subfield_data{maxlength},
348 # Getting list of subfields to keep when restricted editing is enabled
349 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
350 my $allowAllSubfields = (
351 not defined $subfieldsToAllowForRestrictedEditing
352 or $subfieldsToAllowForRestrictedEditing eq q||
354 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
356 # If we're on restricted editing, and our field is not in the list of subfields to allow,
357 # then it is read-only
358 $subfield_data{marc_value}->{readonly} = (
359 not $allowAllSubfields
360 and $restrictededition
361 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
364 return \%subfield_data;
367 # Removes some subfields when prefilling items
368 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
369 sub removeFieldsForPrefill {
374 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
376 # Getting list of subfields to keep
377 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
379 # Removing subfields that are not in the syspref
380 if ($tag && $subfieldsToUseWhenPrefill) {
381 my $field = $item->field($tag);
382 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
383 foreach my $subfield ($field->subfields()) {
384 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
385 $field->delete_subfield(code => $subfield->[0]);
396 my $error = $input->param('error');
397 my $biblionumber = $input->param('biblionumber');
398 my $itemnumber = $input->param('itemnumber');
399 my $op = $input->param('op') || q{};
400 my $hostitemnumber = $input->param('hostitemnumber');
401 my $marcflavour = C4::Context->preference("marcflavour");
402 my $searchid = $input->param('searchid');
403 # fast cataloguing datas
404 my $fa_circborrowernumber = $input->param('circborrowernumber');
405 my $fa_barcode = $input->param('barcode');
406 my $fa_branch = $input->param('branch');
407 my $fa_stickyduedate = $input->param('stickyduedate');
408 my $fa_duedatespec = $input->param('duedatespec');
410 my $frameworkcode = &GetFrameworkCode($biblionumber);
412 # Defining which userflag is needing according to the framework currently used
414 if (defined $input->param('frameworkcode')) {
415 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
418 if (not defined $userflags) {
419 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
422 my ($template, $loggedinuser, $cookie)
423 = get_template_and_user({template_name => "cataloguing/additem.tt",
426 authnotrequired => 0,
427 flagsrequired => {editcatalogue => $userflags},
432 # Does the user have a restricted item editing permission?
433 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
434 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
435 # In case user is a superlibrarian, editing is not restricted
436 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
437 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
438 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
440 my $tagslib = &GetMarcStructure(1,$frameworkcode);
441 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
443 output_and_exit_if_error( $input, $cookie, $template,
444 { module => 'cataloguing', record => $record } );
446 my $oldrecord = TransformMarcToKoha($record);
448 my $nextop="additem";
449 my @errors; # store errors found while checking data BEFORE saving item.
451 # Getting last created item cookie
452 my $prefillitem = C4::Context->preference('PrefillItem');
454 my $cookieitemrecord;
456 my $lastitemcookie = $input->cookie('LastCreatedItem');
457 if ($lastitemcookie) {
458 $lastitemcookie = uri_unescape($lastitemcookie);
460 if ( thaw($lastitemcookie) ) {
461 $cookieitemrecord = thaw($lastitemcookie);
462 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
466 $lastitemcookie = 'undef' unless $lastitemcookie;
467 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
472 #-------------------------------------------------------------------------------
473 if ($op eq "additem") {
475 #-------------------------------------------------------------------------------
477 my @tags = $input->multi_param('tag');
478 my @subfields = $input->multi_param('subfield');
479 my @values = $input->multi_param('field_value');
480 # build indicator hash.
481 my @ind_tag = $input->multi_param('ind_tag');
482 my @indicator = $input->multi_param('indicator');
483 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
484 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
487 my $add_submit = $input->param('add_submit');
488 my $add_duplicate_submit = $input->param('add_duplicate_submit');
489 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
490 my $number_of_copies = $input->param('number_of_copies');
492 # This is a bit tricky : if there is a cookie for the last created item and
493 # we just added an item, the cookie value is not correct yet (it will be updated
494 # next page). To prevent the form from being filled with outdated values, we
495 # force the use of "add and duplicate" feature, so the form will be filled with
497 $add_duplicate_submit = 1 if ($prefillitem);
500 # if autoBarcode is set to 'incremental', calculate barcode...
501 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
502 $record = _increment_barcode($record, $frameworkcode);
505 my $addedolditem = TransformMarcToKoha( $record );
507 # If we have to add or add & duplicate, we add the item
508 if ( $add_submit || $add_duplicate_submit ) {
510 # check for item barcode # being unique
511 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
512 push @errors, "barcode_not_unique" if ($exist_itemnumber);
514 # if barcode exists, don't create, but report The problem.
515 unless ($exist_itemnumber) {
516 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
517 set_item_default_location($oldbibitemnum);
519 # Pushing the last created item cookie back
520 if ($prefillitem && defined $record) {
521 my $itemcookie = $input->cookie(
522 -name => 'LastCreatedItem',
523 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
524 -value => uri_escape_utf8( freeze( $record ) ),
529 $cookie = [ $cookie, $itemcookie ];
534 if ($exist_itemnumber) {
535 $itemrecord = $record;
539 # If we have to add & duplicate
540 if ($add_duplicate_submit) {
541 $itemrecord = $record;
542 if (C4::Context->preference('autoBarcode') eq 'incremental') {
543 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
546 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
547 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
548 my $fieldItem = $itemrecord->field($tagfield);
549 $itemrecord->delete_field($fieldItem);
550 $fieldItem->delete_subfields($tagsubfield);
551 $itemrecord->insert_fields_ordered($fieldItem);
553 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
556 # If we have to add multiple copies
557 if ($add_multiple_copies_submit) {
560 my $barcodeobj = C4::Barcodes->new;
561 my $copynumber = $addedolditem->{'copynumber'};
562 my $oldbarcode = $addedolditem->{'barcode'};
563 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
564 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
566 # If there is a barcode and we can't find their new values, we can't add multiple copies
568 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
569 if ($oldbarcode && !$testbarcode) {
571 push @errors, "no_next_barcode";
572 $itemrecord = $record;
577 # For the first iteration
578 my $barcodevalue = $oldbarcode;
579 my $exist_itemnumber;
582 for (my $i = 0; $i < $number_of_copies;) {
584 # If there is a barcode
587 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
588 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
590 # Putting it into the record
592 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
593 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
594 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
595 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
596 # But when adding multiple copies we need to prefix it here,
597 # so we retrieve the homebranch from the item and prefix the barcode with it.
598 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
599 my $homebranch = $record->subfield($hb_field, $hb_subfield);
600 $barcodevalue = $homebranch . $barcodevalue;
602 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
605 # Checking if the barcode already exists
606 $exist_itemnumber = get_item_from_barcode($barcodevalue);
608 # Updating record with the new copynumber
610 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
614 if (!$exist_itemnumber) {
615 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
616 AddItemFromMarc( $record, $biblionumber, { skip_modzebra_update => 1 } );
617 set_item_default_location($oldbibitemnum);
619 # We count the item only if it was really added
620 # That way, all items are added, even if there was some already existing barcodes
621 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
623 # Only increment copynumber if item was really added
624 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
627 # Preparing the next iteration
628 $oldbarcode = $barcodevalue;
631 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
636 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
637 print $input->redirect(
638 '/cgi-bin/koha/circ/circulation.pl?'
639 .'borrowernumber='.$fa_circborrowernumber
640 .'&barcode='.uri_escape_utf8($fa_barcode)
641 .'&duedatespec='.$fa_duedatespec
648 #-------------------------------------------------------------------------------
649 } elsif ($op eq "edititem") {
650 #-------------------------------------------------------------------------------
651 # retrieve item if exist => then, it's a modif
652 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
653 $nextop = "saveitem";
654 #-------------------------------------------------------------------------------
655 } elsif ($op eq "dupeitem") {
656 #-------------------------------------------------------------------------------
657 # retrieve item if exist => then, it's a modif
658 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
659 if (C4::Context->preference('autoBarcode') eq 'incremental') {
660 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
663 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
664 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
665 my $fieldItem = $itemrecord->field($tagfield);
666 $itemrecord->delete_field($fieldItem);
667 $fieldItem->delete_subfields($tagsubfield);
668 $itemrecord->insert_fields_ordered($fieldItem);
671 #check for hidden subfield and remove them for the duplicated item
672 foreach my $field ($itemrecord->fields()){
673 my $tag = $field->{_tag};
674 foreach my $subfield ($field->subfields()){
675 my $subfieldtag = $subfield->[0];
676 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
677 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
678 my $fieldItem = $itemrecord->field($tag);
679 $itemrecord->delete_field($fieldItem);
680 $fieldItem->delete_subfields($subfieldtag);
681 $itemrecord->insert_fields_ordered($fieldItem);
686 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
688 #-------------------------------------------------------------------------------
689 } elsif ($op eq "delitem") {
690 #-------------------------------------------------------------------------------
691 # check that there is no issue on this item before deletion.
692 my $item = Koha::Items->find($itemnumber);
693 $error = $item->safe_delete;
694 if(ref($error) eq 'Koha::Item'){
695 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
700 #-------------------------------------------------------------------------------
701 } elsif ($op eq "delallitems") {
702 #-------------------------------------------------------------------------------
703 my $items = Koha::Items->search({ biblionumber => $biblionumber });
704 while ( my $item = $items->next ) {
705 $error = $item->safe_delete({ skip_modzebra_update => 1 });
706 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
709 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
713 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
714 my $views = { C4::Search::enabled_staff_search_views };
715 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
716 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
717 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
718 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
719 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
720 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
722 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
726 #-------------------------------------------------------------------------------
727 } elsif ($op eq "saveitem") {
728 #-------------------------------------------------------------------------------
730 my @tags = $input->multi_param('tag');
731 my @subfields = $input->multi_param('subfield');
732 my @values = $input->multi_param('field_value');
733 # build indicator hash.
734 my @ind_tag = $input->multi_param('ind_tag');
735 my @indicator = $input->multi_param('indicator');
736 # my $itemnumber = $input->param('itemnumber');
737 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
738 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
739 # MARC::Record builded => now, record in DB
740 # warn "R: ".$record->as_formatted;
741 # check that the barcode don't exist already
742 my $addedolditem = TransformMarcToKoha($itemtosave);
743 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
744 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
745 push @errors,"barcode_not_unique";
747 my $item = Koha::Items->find($itemnumber );
748 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
750 my $olditemlost = $item->itemlost;
751 my $newitemlost = $newitem->{itemlost};
752 if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
753 LostItem( $item->itemnumber, 'additem' )
754 } elsif ( !$newitemlost && $olditemlost && $olditemlost ge '1' ) {
759 } elsif ($op eq "delinkitem"){
760 my $analyticfield = '773';
761 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
762 $analyticfield = '773';
763 } elsif ($marcflavour eq 'UNIMARC') {
764 $analyticfield = '461';
766 foreach my $field ($record->field($analyticfield)){
767 if ($field->subfield('9') eq $hostitemnumber){
768 $record->delete_field($field);
772 my $modbibresult = ModBiblio($record, $biblionumber,'');
776 #-------------------------------------------------------------------------------
777 # build screen with existing items. and "new" one
778 #-------------------------------------------------------------------------------
780 # now, build existiing item list
781 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
782 #my @fields = $record->fields();
785 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
787 #---- finds where items.itemnumber is stored
788 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
789 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
790 C4::Biblio::EmbedItemsInMarcBiblio({
791 marc_record => $temp,
792 biblionumber => $biblionumber });
793 my @fields = $temp->fields();
797 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
798 my $analyticfield = '773';
799 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
800 $analyticfield = '773';
801 } elsif ($marcflavour eq 'UNIMARC') {
802 $analyticfield = '461';
804 foreach my $hostfield ($temp->field($analyticfield)){
805 my $hostbiblionumber = $hostfield->subfield('0');
806 if ($hostbiblionumber){
807 my $hostrecord = GetMarcBiblio({
808 biblionumber => $hostbiblionumber,
811 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
812 foreach my $hostitem ($hostrecord->field($itemfield)){
813 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
814 push (@fields, $hostitem);
815 push (@hostitemnumbers, $hostfield->subfield('9'));
823 foreach my $field (@fields) {
824 next if ( $field->tag() < 10 );
826 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
828 # loop through each subfield
830 foreach my $subfield (@subf){
831 my $subfieldcode = $subfield->[0];
832 my $subfieldvalue= $subfield->[1];
834 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
835 && ($field->tag() ne $itemtagfield
836 && $subfieldcode ne $itemtagsubfield));
837 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
838 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
839 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
840 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
841 $subfieldcode, $subfieldvalue, '', $tagslib)
845 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
847 my $userenv = C4::Context->userenv();
848 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
849 $this_row{'nomod'} = 1;
852 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
854 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
855 foreach my $hostitemnumber (@hostitemnumbers) {
856 my $item = Koha::Items->find( $hostitemnumber );
857 if ($this_row{itemnumber} eq $hostitemnumber) {
858 $this_row{hostitemflag} = 1;
859 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
866 push(@big_array, \%this_row);
870 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
871 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
873 # now, construct template !
874 # First, the existing items for display
876 my @header_value_loop;
877 for my $row ( @big_array ) {
880 foreach my $key (sort keys %witness){
883 $item_field->{field} = $row->{$key};
885 $item_field->{field} = '';
889 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
892 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
893 next unless $key eq $subfield;
894 $item_field->{datatype} = 'date';
897 push @item_fields, $item_field;
899 $row_data{item_value} = [ @item_fields ];
900 $row_data{itemnumber} = $row->{itemnumber};
901 #reporting this_row values
902 $row_data{'nomod'} = $row->{'nomod'};
903 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
904 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
905 # $row_data{'countanalytics'} = $row->{'countanalytics'};
906 push(@item_value_loop,\%row_data);
908 foreach my $subfield_code (sort keys(%witness)) {
910 $header_value{header_value} = $witness{$subfield_code};
912 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
913 my $kohafield = $subfieldlib->{kohafield};
914 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
915 $header_value{column_name} = $1;
918 push(@header_value_loop, \%header_value);
921 # now, build the item form for entering a new item
925 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
926 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
927 for my $library ( @$libraries ) {
928 $library->{selected} = 1 if $library->{branchcode} eq $branch
931 my $item = Koha::Items->find($itemnumber);
933 # We generate form, from actuel record
936 foreach my $field ($itemrecord->fields()){
937 my $tag = $field->{_tag};
938 foreach my $subfield ( $field->subfields() ){
940 my $subfieldtag = $subfield->[0];
941 my $value = $subfield->[1];
942 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
944 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
946 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
947 push @fields, "$tag$subfieldtag";
948 push (@loop_data, $subfield_data);
954 # and now we add fields that are empty
956 # Using last created item if it exists
958 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
960 # We generate form, and fill with values if defined
961 foreach my $tag ( keys %{$tagslib}){
962 foreach my $subtag (keys %{$tagslib->{$tag}}){
963 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
964 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
965 next if any { /^$tag$subtag$/ } @fields;
967 my @values = (undef);
968 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
969 for my $value (@values){
970 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
971 push (@loop_data, $subfield_data);
976 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
978 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
980 biblionumber => $biblionumber,
981 title => $oldrecord->{title},
982 author => $oldrecord->{author},
983 item_loop => \@item_value_loop,
984 item_header_loop => \@header_value_loop,
986 itemnumber => $itemnumber,
987 barcode => $item ? $item->barcode : undef,
988 itemtagfield => $itemtagfield,
989 itemtagsubfield => $itemtagsubfield,
991 popup => scalar $input->param('popup') ? 1: 0,
992 C4::Search::enabled_staff_search_views,
994 $template->{'VARS'}->{'searchid'} = $searchid;
996 if ($frameworkcode eq 'FA'){
997 # fast cataloguing datas
999 'circborrowernumber' => $fa_circborrowernumber,
1000 'barcode' => $fa_barcode,
1001 'branch' => $fa_branch,
1002 'stickyduedate' => $fa_stickyduedate,
1003 'duedatespec' => $fa_duedatespec,
1007 foreach my $error (@errors) {
1008 $template->param($error => 1);
1010 output_html_with_http_headers $input, $cookie, $template->output;