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},
250 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
254 $subfield_data{marc_value} = {
256 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
257 values => \@authorised_values,
258 labels => \%authorised_lib,
260 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
264 # it's a thesaurus / authority field
265 elsif ( $subfieldlib->{authtypecode} ) {
266 $subfield_data{marc_value} = {
268 id => $subfield_data{id},
269 maxlength => $subfield_data{maxlength},
271 authtypecode => $subfieldlib->{authtypecode},
274 # it's a plugin field
275 elsif ( $subfieldlib->{value_builder} ) { # plugin
276 require Koha::FrameworkPlugin;
277 my $plugin = Koha::FrameworkPlugin->new({
278 name => $subfieldlib->{'value_builder'},
281 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
282 id => $subfield_data{id}, tabloop => $loop_data };
283 $plugin->build( $pars );
284 if( !$plugin->errstr ) {
285 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
286 $subfield_data{marc_value} = {
287 type => 'text_plugin',
288 id => $subfield_data{id},
289 maxlength => $subfield_data{maxlength},
292 nopopup => $plugin->noclick,
293 javascript => $plugin->javascript,
296 warn $plugin->errstr;
297 $subfield_data{marc_value} = {
299 id => $subfield_data{id},
300 maxlength => $subfield_data{maxlength},
302 }; # supply default input form
305 elsif ( $tag eq '' ) { # it's an hidden field
306 $subfield_data{marc_value} = {
308 id => $subfield_data{id},
309 maxlength => $subfield_data{maxlength},
313 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
314 $subfield_data{marc_value} = {
316 id => $subfield_data{id},
317 maxlength => $subfield_data{maxlength},
323 $value and length($value) > 100
326 C4::Context->preference("marcflavour") eq "UNIMARC"
327 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
330 C4::Context->preference("marcflavour") eq "MARC21"
331 and 500 <= $tag && $tag < 600
334 # oversize field (textarea)
335 $subfield_data{marc_value} = {
337 id => $subfield_data{id},
341 # it's a standard field
342 $subfield_data{marc_value} = {
344 id => $subfield_data{id},
345 maxlength => $subfield_data{maxlength},
350 # Getting list of subfields to keep when restricted editing is enabled
351 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
352 my $allowAllSubfields = (
353 not defined $subfieldsToAllowForRestrictedEditing
354 or $subfieldsToAllowForRestrictedEditing eq q||
356 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
358 # If we're on restricted editing, and our field is not in the list of subfields to allow,
359 # then it is read-only
360 $subfield_data{marc_value}->{readonly} = (
361 not $allowAllSubfields
362 and $restrictededition
363 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
366 return \%subfield_data;
369 # Removes some subfields when prefilling items
370 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
371 sub removeFieldsForPrefill {
376 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
378 # Getting list of subfields to keep
379 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
381 # Removing subfields that are not in the syspref
382 if ($tag && $subfieldsToUseWhenPrefill) {
383 my $field = $item->field($tag);
384 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
385 foreach my $subfield ($field->subfields()) {
386 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
387 $field->delete_subfield(code => $subfield->[0]);
398 my $error = $input->param('error');
399 my $biblionumber = $input->param('biblionumber');
400 my $itemnumber = $input->param('itemnumber');
401 my $op = $input->param('op') || q{};
402 my $hostitemnumber = $input->param('hostitemnumber');
403 my $marcflavour = C4::Context->preference("marcflavour");
404 my $searchid = $input->param('searchid');
405 # fast cataloguing datas
406 my $fa_circborrowernumber = $input->param('circborrowernumber');
407 my $fa_barcode = $input->param('barcode');
408 my $fa_branch = $input->param('branch');
409 my $fa_stickyduedate = $input->param('stickyduedate');
410 my $fa_duedatespec = $input->param('duedatespec');
412 my $frameworkcode = &GetFrameworkCode($biblionumber);
414 # Defining which userflag is needing according to the framework currently used
416 if (defined $input->param('frameworkcode')) {
417 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
420 if (not defined $userflags) {
421 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
424 my ($template, $loggedinuser, $cookie)
425 = get_template_and_user({template_name => "cataloguing/additem.tt",
428 flagsrequired => {editcatalogue => $userflags},
433 # Does the user have a restricted item editing permission?
434 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
435 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
436 # In case user is a superlibrarian, editing is not restricted
437 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
438 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
439 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
441 my $tagslib = &GetMarcStructure(1,$frameworkcode);
442 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
444 output_and_exit_if_error( $input, $cookie, $template,
445 { module => 'cataloguing', record => $record } );
447 my $oldrecord = TransformMarcToKoha($record);
449 my $nextop="additem";
450 my @errors; # store errors found while checking data BEFORE saving item.
452 # Getting last created item cookie
453 my $prefillitem = C4::Context->preference('PrefillItem');
455 my $cookieitemrecord;
457 my $lastitemcookie = $input->cookie('LastCreatedItem');
458 if ($lastitemcookie) {
459 $lastitemcookie = uri_unescape($lastitemcookie);
461 if ( thaw($lastitemcookie) ) {
462 $cookieitemrecord = thaw($lastitemcookie);
463 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
467 $lastitemcookie = 'undef' unless $lastitemcookie;
468 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
473 #-------------------------------------------------------------------------------
474 if ($op eq "additem") {
476 #-------------------------------------------------------------------------------
478 my @tags = $input->multi_param('tag');
479 my @subfields = $input->multi_param('subfield');
480 my @values = $input->multi_param('field_value');
481 # build indicator hash.
482 my @ind_tag = $input->multi_param('ind_tag');
483 my @indicator = $input->multi_param('indicator');
484 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
485 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
488 my $add_submit = $input->param('add_submit');
489 my $add_duplicate_submit = $input->param('add_duplicate_submit');
490 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
491 my $number_of_copies = $input->param('number_of_copies');
493 # This is a bit tricky : if there is a cookie for the last created item and
494 # we just added an item, the cookie value is not correct yet (it will be updated
495 # next page). To prevent the form from being filled with outdated values, we
496 # force the use of "add and duplicate" feature, so the form will be filled with
498 $add_duplicate_submit = 1 if ($prefillitem);
501 # if autoBarcode is set to 'incremental', calculate barcode...
502 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
503 $record = _increment_barcode($record, $frameworkcode);
506 my $addedolditem = TransformMarcToKoha( $record );
508 # If we have to add or add & duplicate, we add the item
509 if ( $add_submit || $add_duplicate_submit ) {
511 # check for item barcode # being unique
512 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
513 push @errors, "barcode_not_unique" if ($exist_itemnumber);
515 # if barcode exists, don't create, but report The problem.
516 unless ($exist_itemnumber) {
517 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
518 set_item_default_location($oldbibitemnum);
520 # Pushing the last created item cookie back
521 if ($prefillitem && defined $record) {
522 my $itemcookie = $input->cookie(
523 -name => 'LastCreatedItem',
524 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
525 -value => uri_escape_utf8( freeze( $record ) ),
530 $cookie = [ $cookie, $itemcookie ];
535 if ($exist_itemnumber) {
536 $itemrecord = $record;
540 # If we have to add & duplicate
541 if ($add_duplicate_submit) {
542 $itemrecord = $record;
543 if (C4::Context->preference('autoBarcode') eq 'incremental') {
544 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
547 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
548 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
549 my $fieldItem = $itemrecord->field($tagfield);
550 $itemrecord->delete_field($fieldItem);
551 $fieldItem->delete_subfields($tagsubfield);
552 $itemrecord->insert_fields_ordered($fieldItem);
554 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
557 # If we have to add multiple copies
558 if ($add_multiple_copies_submit) {
561 my $barcodeobj = C4::Barcodes->new;
562 my $copynumber = $addedolditem->{'copynumber'};
563 my $oldbarcode = $addedolditem->{'barcode'};
564 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
565 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
567 # If there is a barcode and we can't find their new values, we can't add multiple copies
569 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
570 if ($oldbarcode && !$testbarcode) {
572 push @errors, "no_next_barcode";
573 $itemrecord = $record;
578 # For the first iteration
579 my $barcodevalue = $oldbarcode;
580 my $exist_itemnumber;
583 for (my $i = 0; $i < $number_of_copies;) {
585 # If there is a barcode
588 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
589 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
591 # Putting it into the record
593 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
594 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
595 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
596 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
597 # But when adding multiple copies we need to prefix it here,
598 # so we retrieve the homebranch from the item and prefix the barcode with it.
599 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
600 my $homebranch = $record->subfield($hb_field, $hb_subfield);
601 $barcodevalue = $homebranch . $barcodevalue;
603 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
606 # Checking if the barcode already exists
607 $exist_itemnumber = get_item_from_barcode($barcodevalue);
609 # Updating record with the new copynumber
611 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
615 if (!$exist_itemnumber) {
616 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
617 AddItemFromMarc( $record, $biblionumber, { skip_modzebra_update => 1 } );
618 set_item_default_location($oldbibitemnum);
620 # We count the item only if it was really added
621 # That way, all items are added, even if there was some already existing barcodes
622 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
624 # Only increment copynumber if item was really added
625 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
628 # Preparing the next iteration
629 $oldbarcode = $barcodevalue;
632 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
637 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
638 print $input->redirect(
639 '/cgi-bin/koha/circ/circulation.pl?'
640 .'borrowernumber='.$fa_circborrowernumber
641 .'&barcode='.uri_escape_utf8($fa_barcode)
642 .'&duedatespec='.$fa_duedatespec
649 #-------------------------------------------------------------------------------
650 } elsif ($op eq "edititem") {
651 #-------------------------------------------------------------------------------
652 # retrieve item if exist => then, it's a modif
653 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
654 $nextop = "saveitem";
655 #-------------------------------------------------------------------------------
656 } elsif ($op eq "dupeitem") {
657 #-------------------------------------------------------------------------------
658 # retrieve item if exist => then, it's a modif
659 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
660 if (C4::Context->preference('autoBarcode') eq 'incremental') {
661 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
664 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
665 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
666 my $fieldItem = $itemrecord->field($tagfield);
667 $itemrecord->delete_field($fieldItem);
668 $fieldItem->delete_subfields($tagsubfield);
669 $itemrecord->insert_fields_ordered($fieldItem);
672 #check for hidden subfield and remove them for the duplicated item
673 foreach my $field ($itemrecord->fields()){
674 my $tag = $field->{_tag};
675 foreach my $subfield ($field->subfields()){
676 my $subfieldtag = $subfield->[0];
677 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
678 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
679 my $fieldItem = $itemrecord->field($tag);
680 $itemrecord->delete_field($fieldItem);
681 $fieldItem->delete_subfields($subfieldtag);
682 $itemrecord->insert_fields_ordered($fieldItem);
687 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
689 #-------------------------------------------------------------------------------
690 } elsif ($op eq "delitem") {
691 #-------------------------------------------------------------------------------
692 # check that there is no issue on this item before deletion.
693 my $item = Koha::Items->find($itemnumber);
694 $error = $item->safe_delete;
695 if(ref($error) eq 'Koha::Item'){
696 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
701 #-------------------------------------------------------------------------------
702 } elsif ($op eq "delallitems") {
703 #-------------------------------------------------------------------------------
704 my $items = Koha::Items->search({ biblionumber => $biblionumber });
705 while ( my $item = $items->next ) {
706 $error = $item->safe_delete({ skip_modzebra_update => 1 });
707 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
710 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
714 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
715 my $views = { C4::Search::enabled_staff_search_views };
716 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
717 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
718 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
719 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
720 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
721 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
723 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
727 #-------------------------------------------------------------------------------
728 } elsif ($op eq "saveitem") {
729 #-------------------------------------------------------------------------------
731 my @tags = $input->multi_param('tag');
732 my @subfields = $input->multi_param('subfield');
733 my @values = $input->multi_param('field_value');
734 # build indicator hash.
735 my @ind_tag = $input->multi_param('ind_tag');
736 my @indicator = $input->multi_param('indicator');
737 # my $itemnumber = $input->param('itemnumber');
738 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
739 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
740 # MARC::Record builded => now, record in DB
741 # warn "R: ".$record->as_formatted;
742 # check that the barcode don't exist already
743 my $addedolditem = TransformMarcToKoha($itemtosave);
744 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
745 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
746 push @errors,"barcode_not_unique";
748 my $item = Koha::Items->find($itemnumber );
749 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
751 my $olditemlost = $item->itemlost;
752 my $newitemlost = $newitem->{itemlost};
753 if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
754 LostItem( $item->itemnumber, 'additem' )
758 } elsif ($op eq "delinkitem"){
759 my $analyticfield = '773';
760 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
761 $analyticfield = '773';
762 } elsif ($marcflavour eq 'UNIMARC') {
763 $analyticfield = '461';
765 foreach my $field ($record->field($analyticfield)){
766 if ($field->subfield('9') eq $hostitemnumber){
767 $record->delete_field($field);
771 my $modbibresult = ModBiblio($record, $biblionumber,'');
775 #-------------------------------------------------------------------------------
776 # build screen with existing items. and "new" one
777 #-------------------------------------------------------------------------------
779 # now, build existiing item list
780 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
781 #my @fields = $record->fields();
784 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
786 #---- finds where items.itemnumber is stored
787 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
788 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
789 C4::Biblio::EmbedItemsInMarcBiblio({
790 marc_record => $temp,
791 biblionumber => $biblionumber });
792 my @fields = $temp->fields();
796 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
797 my $analyticfield = '773';
798 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
799 $analyticfield = '773';
800 } elsif ($marcflavour eq 'UNIMARC') {
801 $analyticfield = '461';
803 foreach my $hostfield ($temp->field($analyticfield)){
804 my $hostbiblionumber = $hostfield->subfield('0');
805 if ($hostbiblionumber){
806 my $hostrecord = GetMarcBiblio({
807 biblionumber => $hostbiblionumber,
810 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
811 foreach my $hostitem ($hostrecord->field($itemfield)){
812 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
813 push (@fields, $hostitem);
814 push (@hostitemnumbers, $hostfield->subfield('9'));
822 foreach my $field (@fields) {
823 next if ( $field->tag() < 10 );
825 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
827 # loop through each subfield
829 foreach my $subfield (@subf){
830 my $subfieldcode = $subfield->[0];
831 my $subfieldvalue= $subfield->[1];
833 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
834 && ($field->tag() ne $itemtagfield
835 && $subfieldcode ne $itemtagsubfield));
836 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
837 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
838 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
839 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
840 $subfieldcode, $subfieldvalue, '', $tagslib)
844 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
846 my $userenv = C4::Context->userenv();
847 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
848 $this_row{'nomod'} = 1;
851 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
853 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
854 foreach my $hostitemnumber (@hostitemnumbers) {
855 my $item = Koha::Items->find( $hostitemnumber );
856 if ($this_row{itemnumber} eq $hostitemnumber) {
857 $this_row{hostitemflag} = 1;
858 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
865 push(@big_array, \%this_row);
869 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
870 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
872 # now, construct template !
873 # First, the existing items for display
875 my @header_value_loop;
876 for my $row ( @big_array ) {
879 foreach my $key (sort keys %witness){
882 $item_field->{field} = $row->{$key};
884 $item_field->{field} = '';
888 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
891 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
892 next unless $key eq $subfield;
893 $item_field->{datatype} = 'date';
896 push @item_fields, $item_field;
898 $row_data{item_value} = [ @item_fields ];
899 $row_data{itemnumber} = $row->{itemnumber};
900 #reporting this_row values
901 $row_data{'nomod'} = $row->{'nomod'};
902 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
903 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
904 # $row_data{'countanalytics'} = $row->{'countanalytics'};
905 push(@item_value_loop,\%row_data);
907 foreach my $subfield_code (sort keys(%witness)) {
909 $header_value{header_value} = $witness{$subfield_code};
911 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
912 my $kohafield = $subfieldlib->{kohafield};
913 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
914 $header_value{column_name} = $1;
917 push(@header_value_loop, \%header_value);
920 # now, build the item form for entering a new item
924 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
925 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
926 for my $library ( @$libraries ) {
927 $library->{selected} = 1 if $library->{branchcode} eq $branch
930 my $item = Koha::Items->find($itemnumber);
932 # We generate form, from actuel record
935 foreach my $field ($itemrecord->fields()){
936 my $tag = $field->{_tag};
937 foreach my $subfield ( $field->subfields() ){
939 my $subfieldtag = $subfield->[0];
940 my $value = $subfield->[1];
941 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
943 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
945 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
946 push @fields, "$tag$subfieldtag";
947 push (@loop_data, $subfield_data);
953 # and now we add fields that are empty
955 # Using last created item if it exists
957 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
959 # We generate form, and fill with values if defined
960 foreach my $tag ( keys %{$tagslib}){
961 foreach my $subtag (keys %{$tagslib->{$tag}}){
962 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
963 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
964 next if any { /^$tag$subtag$/ } @fields;
966 my @values = (undef);
967 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
968 for my $value (@values){
969 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
970 push (@loop_data, $subfield_data);
975 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
977 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
979 biblionumber => $biblionumber,
980 title => $oldrecord->{title},
981 author => $oldrecord->{author},
982 item_loop => \@item_value_loop,
983 item_header_loop => \@header_value_loop,
985 itemnumber => $itemnumber,
986 barcode => $item ? $item->barcode : undef,
987 itemtagfield => $itemtagfield,
988 itemtagsubfield => $itemtagsubfield,
990 popup => scalar $input->param('popup') ? 1: 0,
991 C4::Search::enabled_staff_search_views,
993 $template->{'VARS'}->{'searchid'} = $searchid;
995 if ($frameworkcode eq 'FA'){
996 # fast cataloguing datas
998 'circborrowernumber' => $fa_circborrowernumber,
999 'barcode' => $fa_barcode,
1000 'branch' => $fa_branch,
1001 'stickyduedate' => $fa_stickyduedate,
1002 'duedatespec' => $fa_duedatespec,
1006 foreach my $error (@errors) {
1007 $template->param($error => 1);
1009 output_html_with_http_headers $input, $cookie, $template->output;