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) = @_;
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>>, <<MM>>, <<DD>> if provided in the default value
136 my $today_dt = dt_from_string;
137 my $year = $today_dt->strftime('%Y');
138 my $month = $today_dt->strftime('%m');
139 my $day = $today_dt->strftime('%d');
140 $value =~ s/<<YYYY>>/$year/g;
141 $value =~ s/<<MM>>/$month/g;
142 $value =~ s/<<DD>>/$day/g;
143 # And <<USER>> with surname (?)
144 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
145 $value=~s/<<USER>>/$username/g;
149 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
151 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
152 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
153 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
154 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
155 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
156 my $temp2 = $temp->field($CNtag);
159 $value = $temp2->as_string( $CNsubfields, ' ' );
164 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
166 $value = $input->param('barcode');
169 if ( $subfieldlib->{authorised_value} ) {
170 my @authorised_values;
172 # builds list, depending on authorised value...
173 if ( $subfieldlib->{authorised_value} eq "LOST" ) {
174 $subfield_data{IS_LOST_AV} = 1;
175 push @authorised_values, qq{};
176 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
178 push @authorised_values, $r->{authorised_value};
179 $authorised_lib{$r->{authorised_value}} = $r->{lib};
182 elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
183 foreach my $thisbranch (@$branches) {
184 push @authorised_values, $thisbranch->{branchcode};
185 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
186 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
189 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
190 push @authorised_values, "";
191 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
194 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
196 $itemtypes = Koha::ItemTypes->search_with_localization;
198 while ( my $itemtype = $itemtypes->next ) {
199 push @authorised_values, $itemtype->itemtype;
200 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
204 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
205 $itype_sth->execute( $biblionumber );
206 ( $value ) = $itype_sth->fetchrow_array;
211 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
212 push @authorised_values, "";
214 my $class_sources = GetClassSources();
215 my $default_source = C4::Context->preference("DefaultClassificationSource");
217 foreach my $class_source (sort keys %$class_sources) {
218 next unless $class_sources->{$class_source}->{'used'} or
219 ($value and $class_source eq $value) or
220 ($class_source eq $default_source);
221 push @authorised_values, $class_source;
222 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
224 $value = $default_source unless ($value);
226 #---- "true" authorised value
229 push @authorised_values, qq{};
230 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
232 push @authorised_values, $r->{authorised_value};
233 $authorised_lib{$r->{authorised_value}} = $r->{lib};
237 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
238 $subfield_data{marc_value} = {
240 id => $subfield_data{id},
241 maxlength => $subfield_data{maxlength},
246 $subfield_data{marc_value} = {
248 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
249 values => \@authorised_values,
250 labels => \%authorised_lib,
255 # it's a thesaurus / authority field
256 elsif ( $subfieldlib->{authtypecode} ) {
257 $subfield_data{marc_value} = {
259 id => $subfield_data{id},
260 maxlength => $subfield_data{maxlength},
262 authtypecode => $subfieldlib->{authtypecode},
265 # it's a plugin field
266 elsif ( $subfieldlib->{value_builder} ) { # plugin
267 require Koha::FrameworkPlugin;
268 my $plugin = Koha::FrameworkPlugin->new({
269 name => $subfieldlib->{'value_builder'},
272 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
273 id => $subfield_data{id}, tabloop => $loop_data };
274 $plugin->build( $pars );
275 if( !$plugin->errstr ) {
276 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
277 $subfield_data{marc_value} = {
278 type => 'text_plugin',
279 id => $subfield_data{id},
280 maxlength => $subfield_data{maxlength},
283 nopopup => $plugin->noclick,
284 javascript => $plugin->javascript,
287 warn $plugin->errstr;
288 $subfield_data{marc_value} = {
290 id => $subfield_data{id},
291 maxlength => $subfield_data{maxlength},
293 }; # supply default input form
296 elsif ( $tag eq '' ) { # it's an hidden field
297 $subfield_data{marc_value} = {
299 id => $subfield_data{id},
300 maxlength => $subfield_data{maxlength},
304 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
305 $subfield_data{marc_value} = {
307 id => $subfield_data{id},
308 maxlength => $subfield_data{maxlength},
314 $value and length($value) > 100
317 C4::Context->preference("marcflavour") eq "UNIMARC"
318 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
321 C4::Context->preference("marcflavour") eq "MARC21"
322 and 500 <= $tag && $tag < 600
325 # oversize field (textarea)
326 $subfield_data{marc_value} = {
328 id => $subfield_data{id},
332 # it's a standard field
333 $subfield_data{marc_value} = {
335 id => $subfield_data{id},
336 maxlength => $subfield_data{maxlength},
341 # Getting list of subfields to keep when restricted editing is enabled
342 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
343 my $allowAllSubfields = (
344 not defined $subfieldsToAllowForRestrictedEditing
345 or $subfieldsToAllowForRestrictedEditing eq q||
347 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
349 # If we're on restricted editing, and our field is not in the list of subfields to allow,
350 # then it is read-only
351 $subfield_data{marc_value}->{readonly} = (
352 not $allowAllSubfields
353 and $restrictededition
354 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
357 return \%subfield_data;
360 # Removes some subfields when prefilling items
361 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
362 sub removeFieldsForPrefill {
367 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
369 # Getting list of subfields to keep
370 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
372 # Removing subfields that are not in the syspref
373 if ($tag && $subfieldsToUseWhenPrefill) {
374 my $field = $item->field($tag);
375 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
376 foreach my $subfield ($field->subfields()) {
377 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
378 $field->delete_subfield(code => $subfield->[0]);
389 my $error = $input->param('error');
390 my $biblionumber = $input->param('biblionumber');
391 my $itemnumber = $input->param('itemnumber');
392 my $op = $input->param('op') || q{};
393 my $hostitemnumber = $input->param('hostitemnumber');
394 my $marcflavour = C4::Context->preference("marcflavour");
395 my $searchid = $input->param('searchid');
396 # fast cataloguing datas
397 my $fa_circborrowernumber = $input->param('circborrowernumber');
398 my $fa_barcode = $input->param('barcode');
399 my $fa_branch = $input->param('branch');
400 my $fa_stickyduedate = $input->param('stickyduedate');
401 my $fa_duedatespec = $input->param('duedatespec');
403 my $frameworkcode = &GetFrameworkCode($biblionumber);
405 # Defining which userflag is needing according to the framework currently used
407 if (defined $input->param('frameworkcode')) {
408 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
411 if (not defined $userflags) {
412 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
415 my ($template, $loggedinuser, $cookie)
416 = get_template_and_user({template_name => "cataloguing/additem.tt",
419 authnotrequired => 0,
420 flagsrequired => {editcatalogue => $userflags},
425 # Does the user have a restricted item editing permission?
426 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
427 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
428 # In case user is a superlibrarian, editing is not restricted
429 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
430 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
431 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
433 my $tagslib = &GetMarcStructure(1,$frameworkcode);
434 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
436 output_and_exit_if_error( $input, $cookie, $template,
437 { module => 'cataloguing', record => $record } );
439 my $oldrecord = TransformMarcToKoha($record);
441 my $nextop="additem";
442 my @errors; # store errors found while checking data BEFORE saving item.
444 # Getting last created item cookie
445 my $prefillitem = C4::Context->preference('PrefillItem');
447 my $cookieitemrecord;
449 my $lastitemcookie = $input->cookie('LastCreatedItem');
450 if ($lastitemcookie) {
451 $lastitemcookie = uri_unescape($lastitemcookie);
453 if ( thaw($lastitemcookie) ) {
454 $cookieitemrecord = thaw($lastitemcookie);
455 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
459 $lastitemcookie = 'undef' unless $lastitemcookie;
460 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
465 #-------------------------------------------------------------------------------
466 if ($op eq "additem") {
468 #-------------------------------------------------------------------------------
470 my @tags = $input->multi_param('tag');
471 my @subfields = $input->multi_param('subfield');
472 my @values = $input->multi_param('field_value');
473 # build indicator hash.
474 my @ind_tag = $input->multi_param('ind_tag');
475 my @indicator = $input->multi_param('indicator');
476 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
477 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
480 my $add_submit = $input->param('add_submit');
481 my $add_duplicate_submit = $input->param('add_duplicate_submit');
482 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
483 my $number_of_copies = $input->param('number_of_copies');
485 # This is a bit tricky : if there is a cookie for the last created item and
486 # we just added an item, the cookie value is not correct yet (it will be updated
487 # next page). To prevent the form from being filled with outdated values, we
488 # force the use of "add and duplicate" feature, so the form will be filled with
490 $add_duplicate_submit = 1 if ($prefillitem);
493 # if autoBarcode is set to 'incremental', calculate barcode...
494 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
495 $record = _increment_barcode($record, $frameworkcode);
498 my $addedolditem = TransformMarcToKoha( $record );
500 # If we have to add or add & duplicate, we add the item
501 if ( $add_submit || $add_duplicate_submit ) {
503 # check for item barcode # being unique
504 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
505 push @errors, "barcode_not_unique" if ($exist_itemnumber);
507 # if barcode exists, don't create, but report The problem.
508 unless ($exist_itemnumber) {
509 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
510 set_item_default_location($oldbibitemnum);
512 # Pushing the last created item cookie back
513 if ($prefillitem && defined $record) {
514 my $itemcookie = $input->cookie(
515 -name => 'LastCreatedItem',
516 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
517 -value => uri_escape_utf8( freeze( $record ) ),
522 $cookie = [ $cookie, $itemcookie ];
527 if ($exist_itemnumber) {
528 $itemrecord = $record;
532 # If we have to add & duplicate
533 if ($add_duplicate_submit) {
534 $itemrecord = $record;
535 if (C4::Context->preference('autoBarcode') eq 'incremental') {
536 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
539 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
540 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
541 my $fieldItem = $itemrecord->field($tagfield);
542 $itemrecord->delete_field($fieldItem);
543 $fieldItem->delete_subfields($tagsubfield);
544 $itemrecord->insert_fields_ordered($fieldItem);
546 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
549 # If we have to add multiple copies
550 if ($add_multiple_copies_submit) {
553 my $barcodeobj = C4::Barcodes->new;
554 my $copynumber = $addedolditem->{'copynumber'};
555 my $oldbarcode = $addedolditem->{'barcode'};
556 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
557 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
559 # If there is a barcode and we can't find their new values, we can't add multiple copies
561 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
562 if ($oldbarcode && !$testbarcode) {
564 push @errors, "no_next_barcode";
565 $itemrecord = $record;
570 # For the first iteration
571 my $barcodevalue = $oldbarcode;
572 my $exist_itemnumber;
575 for (my $i = 0; $i < $number_of_copies;) {
577 # If there is a barcode
580 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
581 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
583 # Putting it into the record
585 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
586 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
587 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
588 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
589 # But when adding multiple copies we need to prefix it here,
590 # so we retrieve the homebranch from the item and prefix the barcode with it.
591 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
592 my $homebranch = $record->subfield($hb_field, $hb_subfield);
593 $barcodevalue = $homebranch . $barcodevalue;
595 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
598 # Checking if the barcode already exists
599 $exist_itemnumber = get_item_from_barcode($barcodevalue);
601 # Updating record with the new copynumber
603 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
607 if (!$exist_itemnumber) {
608 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
609 AddItemFromMarc( $record, $biblionumber, { skip_modzebra_update => 1 } );
610 set_item_default_location($oldbibitemnum);
612 # We count the item only if it was really added
613 # That way, all items are added, even if there was some already existing barcodes
614 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
616 # Only increment copynumber if item was really added
617 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
620 # Preparing the next iteration
621 $oldbarcode = $barcodevalue;
624 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
629 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
630 print $input->redirect(
631 '/cgi-bin/koha/circ/circulation.pl?'
632 .'borrowernumber='.$fa_circborrowernumber
633 .'&barcode='.uri_escape_utf8($fa_barcode)
634 .'&duedatespec='.$fa_duedatespec
641 #-------------------------------------------------------------------------------
642 } elsif ($op eq "edititem") {
643 #-------------------------------------------------------------------------------
644 # retrieve item if exist => then, it's a modif
645 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
646 $nextop = "saveitem";
647 #-------------------------------------------------------------------------------
648 } elsif ($op eq "dupeitem") {
649 #-------------------------------------------------------------------------------
650 # retrieve item if exist => then, it's a modif
651 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
652 if (C4::Context->preference('autoBarcode') eq 'incremental') {
653 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
656 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
657 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
658 my $fieldItem = $itemrecord->field($tagfield);
659 $itemrecord->delete_field($fieldItem);
660 $fieldItem->delete_subfields($tagsubfield);
661 $itemrecord->insert_fields_ordered($fieldItem);
664 #check for hidden subfield and remove them for the duplicated item
665 foreach my $field ($itemrecord->fields()){
666 my $tag = $field->{_tag};
667 foreach my $subfield ($field->subfields()){
668 my $subfieldtag = $subfield->[0];
669 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
670 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
671 my $fieldItem = $itemrecord->field($tag);
672 $itemrecord->delete_field($fieldItem);
673 $fieldItem->delete_subfields($subfieldtag);
674 $itemrecord->insert_fields_ordered($fieldItem);
679 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
681 #-------------------------------------------------------------------------------
682 } elsif ($op eq "delitem") {
683 #-------------------------------------------------------------------------------
684 # check that there is no issue on this item before deletion.
685 my $item = Koha::Items->find($itemnumber);
686 $error = $item->safe_delete;
687 if(ref($error) eq 'Koha::Item'){
688 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
693 #-------------------------------------------------------------------------------
694 } elsif ($op eq "delallitems") {
695 #-------------------------------------------------------------------------------
696 my $items = Koha::Items->search({ biblionumber => $biblionumber });
697 while ( my $item = $items->next ) {
698 $error = $item->safe_delete({ skip_modzebra_update => 1 });
699 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
702 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
706 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
707 my $views = { C4::Search::enabled_staff_search_views };
708 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
709 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
710 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
711 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
712 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
713 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
715 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
719 #-------------------------------------------------------------------------------
720 } elsif ($op eq "saveitem") {
721 #-------------------------------------------------------------------------------
723 my @tags = $input->multi_param('tag');
724 my @subfields = $input->multi_param('subfield');
725 my @values = $input->multi_param('field_value');
726 # build indicator hash.
727 my @ind_tag = $input->multi_param('ind_tag');
728 my @indicator = $input->multi_param('indicator');
729 # my $itemnumber = $input->param('itemnumber');
730 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
731 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
732 # MARC::Record builded => now, record in DB
733 # warn "R: ".$record->as_formatted;
734 # check that the barcode don't exist already
735 my $addedolditem = TransformMarcToKoha($itemtosave);
736 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
737 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
738 push @errors,"barcode_not_unique";
740 my $item = Koha::Items->find($itemnumber );
741 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
743 my $olditemlost = $item->itemlost;
744 my $newitemlost = $newitem->{itemlost};
745 LostItem( $item->itemnumber, 'additem' )
746 if $newitemlost && $newitemlost ge '1' && !$olditemlost;
749 } elsif ($op eq "delinkitem"){
750 my $analyticfield = '773';
751 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
752 $analyticfield = '773';
753 } elsif ($marcflavour eq 'UNIMARC') {
754 $analyticfield = '461';
756 foreach my $field ($record->field($analyticfield)){
757 if ($field->subfield('9') eq $hostitemnumber){
758 $record->delete_field($field);
762 my $modbibresult = ModBiblio($record, $biblionumber,'');
766 #-------------------------------------------------------------------------------
767 # build screen with existing items. and "new" one
768 #-------------------------------------------------------------------------------
770 # now, build existiing item list
771 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
772 #my @fields = $record->fields();
775 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
777 #---- finds where items.itemnumber is stored
778 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
779 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
780 C4::Biblio::EmbedItemsInMarcBiblio({
781 marc_record => $temp,
782 biblionumber => $biblionumber });
783 my @fields = $temp->fields();
787 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
788 my $analyticfield = '773';
789 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
790 $analyticfield = '773';
791 } elsif ($marcflavour eq 'UNIMARC') {
792 $analyticfield = '461';
794 foreach my $hostfield ($temp->field($analyticfield)){
795 my $hostbiblionumber = $hostfield->subfield('0');
796 if ($hostbiblionumber){
797 my $hostrecord = GetMarcBiblio({
798 biblionumber => $hostbiblionumber,
801 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
802 foreach my $hostitem ($hostrecord->field($itemfield)){
803 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
804 push (@fields, $hostitem);
805 push (@hostitemnumbers, $hostfield->subfield('9'));
813 foreach my $field (@fields) {
814 next if ( $field->tag() < 10 );
816 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
818 # loop through each subfield
820 foreach my $subfield (@subf){
821 my $subfieldcode = $subfield->[0];
822 my $subfieldvalue= $subfield->[1];
824 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
825 && ($field->tag() ne $itemtagfield
826 && $subfieldcode ne $itemtagsubfield));
827 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
828 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
829 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
830 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
831 $subfieldcode, $subfieldvalue, '', $tagslib)
835 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
837 my $userenv = C4::Context->userenv();
838 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
839 $this_row{'nomod'} = 1;
842 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
844 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
845 foreach my $hostitemnumber (@hostitemnumbers) {
846 my $item = Koha::Items->find( $hostitemnumber );
847 if ($this_row{itemnumber} eq $hostitemnumber) {
848 $this_row{hostitemflag} = 1;
849 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
856 push(@big_array, \%this_row);
860 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
861 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
863 # now, construct template !
864 # First, the existing items for display
866 my @header_value_loop;
867 for my $row ( @big_array ) {
870 foreach my $key (sort keys %witness){
873 $item_field->{field} = $row->{$key};
875 $item_field->{field} = '';
879 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
882 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
883 next unless $key eq $subfield;
884 $item_field->{datatype} = 'date';
887 push @item_fields, $item_field;
889 $row_data{item_value} = [ @item_fields ];
890 $row_data{itemnumber} = $row->{itemnumber};
891 #reporting this_row values
892 $row_data{'nomod'} = $row->{'nomod'};
893 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
894 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
895 # $row_data{'countanalytics'} = $row->{'countanalytics'};
896 push(@item_value_loop,\%row_data);
898 foreach my $subfield_code (sort keys(%witness)) {
900 $header_value{header_value} = $witness{$subfield_code};
902 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
903 my $kohafield = $subfieldlib->{kohafield};
904 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
905 $header_value{column_name} = $1;
908 push(@header_value_loop, \%header_value);
911 # now, build the item form for entering a new item
915 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
916 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
917 for my $library ( @$libraries ) {
918 $library->{selected} = 1 if $library->{branchcode} eq $branch
921 # We generate form, from actuel record
924 foreach my $field ($itemrecord->fields()){
925 my $tag = $field->{_tag};
926 foreach my $subfield ( $field->subfields() ){
928 my $subfieldtag = $subfield->[0];
929 my $value = $subfield->[1];
930 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
932 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
934 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
935 push @fields, "$tag$subfieldtag";
936 push (@loop_data, $subfield_data);
942 # and now we add fields that are empty
944 # Using last created item if it exists
946 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
948 # We generate form, and fill with values if defined
949 foreach my $tag ( keys %{$tagslib}){
950 foreach my $subtag (keys %{$tagslib->{$tag}}){
951 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
952 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
953 next if any { /^$tag$subtag$/ } @fields;
955 my @values = (undef);
956 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
957 for my $value (@values){
958 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
959 push (@loop_data, $subfield_data);
964 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
966 my $item = Koha::Items->find($itemnumber); # We certainly want to fetch it earlier
968 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
970 biblionumber => $biblionumber,
971 title => $oldrecord->{title},
972 author => $oldrecord->{author},
973 item_loop => \@item_value_loop,
974 item_header_loop => \@header_value_loop,
976 itemnumber => $itemnumber,
977 barcode => $item ? $item->barcode : undef,
978 itemtagfield => $itemtagfield,
979 itemtagsubfield => $itemtagsubfield,
981 popup => scalar $input->param('popup') ? 1: 0,
982 C4::Search::enabled_staff_search_views,
984 $template->{'VARS'}->{'searchid'} = $searchid;
986 if ($frameworkcode eq 'FA'){
987 # fast cataloguing datas
989 'circborrowernumber' => $fa_circborrowernumber,
990 'barcode' => $fa_barcode,
991 'branch' => $fa_branch,
992 'stickyduedate' => $fa_stickyduedate,
993 'duedatespec' => $fa_duedatespec,
997 foreach my $error (@errors) {
998 $template->param($error => 1);
1000 output_html_with_http_headers $input, $cookie, $template->output;