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>.
24 #use warnings; FIXME - Bug 2505
39 use List::MoreUtils qw/any/;
41 use Storable qw(thaw freeze);
48 our $dbh = C4::Context->dbh;
51 my ($tagfield,$insubfield,$record) = @_;
54 foreach my $field ($record->field($tagfield)) {
55 my @subfields = $field->subfields();
56 foreach my $subfield (@subfields) {
57 if (@$subfield[0] eq $insubfield) {
58 $result .= @$subfield[1];
59 $indicator = $field->indicator(1).$field->indicator(2);
63 return($indicator,$result);
66 sub get_item_from_barcode {
68 my $dbh=C4::Context->dbh;
70 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
71 $rq->execute($barcode);
72 ($result)=$rq->fetchrow;
76 sub set_item_default_location {
77 my $itemnumber = shift;
78 my $item = GetItem( $itemnumber );
79 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
80 $item->{'permanent_location'} = $item->{'location'};
81 $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
82 ModItem( $item, undef, $itemnumber);
85 $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
86 ModItem( $item, undef, $itemnumber);
90 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
91 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
92 sub _increment_barcode {
93 my ($record, $frameworkcode) = @_;
94 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
95 unless ($record->field($tagfield)->subfield($tagsubfield)) {
96 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
97 $sth_barcode->execute;
98 my ($newbarcode) = $sth_barcode->fetchrow;
100 # OK, we have the new barcode, now create the entry in MARC record
101 my $fieldItem = $record->field($tagfield);
102 $record->delete_field($fieldItem);
103 $fieldItem->add_subfields($tagsubfield => $newbarcode);
104 $record->insert_fields_ordered($fieldItem);
110 sub generate_subfield_form {
111 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
113 my $frameworkcode = &GetFrameworkCode($biblionumber);
116 my $dbh = C4::Context->dbh;
118 my $index_subfield = int(rand(1000000));
119 if ($subfieldtag eq '@'){
120 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
122 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
125 $subfield_data{tag} = $tag;
126 $subfield_data{subfield} = $subfieldtag;
127 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
128 $subfield_data{mandatory} = $subfieldlib->{mandatory};
129 $subfield_data{repeatable} = $subfieldlib->{repeatable};
130 $subfield_data{maxlength} = $subfieldlib->{maxlength};
132 $value =~ s/"/"/g;
133 if ( ! defined( $value ) || $value eq '') {
134 $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;
148 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
150 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
151 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
152 my $CNtag = substr($pref_itemcallnumber, 0, 3);
153 my $CNsubfield = substr($pref_itemcallnumber, 3, 1);
154 my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
155 my $temp2 = $temp->field($CNtag);
157 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
158 #remove any trailing space incase one subfield is used
159 $value =~ s/^\s+|\s+$//g;
163 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
165 $value = $input->param('barcode');
168 if ( $subfieldlib->{authorised_value} ) {
169 my @authorised_values;
171 # builds list, depending on authorised value...
172 if ( $subfieldlib->{authorised_value} eq "branches" ) {
173 foreach my $thisbranch (@$branches) {
174 push @authorised_values, $thisbranch->{branchcode};
175 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
176 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
179 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
180 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
181 my $itemtypes = Koha::ItemTypes->search_with_localization;
182 while ( my $itemtype = $itemtypes->next ) {
183 push @authorised_values, $itemtype->itemtype;
184 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
188 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
189 $itype_sth->execute( $biblionumber );
190 ( $value ) = $itype_sth->fetchrow_array;
195 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
196 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
198 my $class_sources = GetClassSources();
199 my $default_source = C4::Context->preference("DefaultClassificationSource");
201 foreach my $class_source (sort keys %$class_sources) {
202 next unless $class_sources->{$class_source}->{'used'} or
203 ($value and $class_source eq $value) or
204 ($class_source eq $default_source);
205 push @authorised_values, $class_source;
206 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
208 $value = $default_source unless ($value);
210 #---- "true" authorised value
213 push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
214 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
216 push @authorised_values, $r->{authorised_value};
217 $authorised_lib{$r->{authorised_value}} = $r->{lib};
221 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
222 $subfield_data{marc_value} = {
224 id => $subfield_data{id},
225 maxlength => $subfield_data{max_length},
230 $subfield_data{marc_value} = {
232 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
233 values => \@authorised_values,
234 labels => \%authorised_lib,
239 # it's a thesaurus / authority field
240 elsif ( $subfieldlib->{authtypecode} ) {
241 $subfield_data{marc_value} = {
243 id => $subfield_data{id},
244 maxlength => $subfield_data{max_length},
246 authtypecode => $subfieldlib->{authtypecode},
249 # it's a plugin field
250 elsif ( $subfieldlib->{value_builder} ) { # plugin
251 require Koha::FrameworkPlugin;
252 my $plugin = Koha::FrameworkPlugin->new({
253 name => $subfieldlib->{'value_builder'},
256 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
257 id => $subfield_data{id}, tabloop => $loop_data };
258 $plugin->build( $pars );
259 if( !$plugin->errstr ) {
260 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
261 $subfield_data{marc_value} = {
262 type => 'text_plugin',
263 id => $subfield_data{id},
264 maxlength => $subfield_data{max_length},
267 nopopup => $plugin->noclick,
268 javascript => $plugin->javascript,
271 warn $plugin->errstr;
272 $subfield_data{marc_value} = {
274 id => $subfield_data{id},
275 maxlength => $subfield_data{max_length},
277 }; # supply default input form
280 elsif ( $tag eq '' ) { # it's an hidden field
281 $subfield_data{marc_value} = {
283 id => $subfield_data{id},
284 maxlength => $subfield_data{max_length},
288 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
289 $subfield_data{marc_value} = {
291 id => $subfield_data{id},
292 maxlength => $subfield_data{max_length},
299 C4::Context->preference("marcflavour") eq "UNIMARC"
300 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
303 C4::Context->preference("marcflavour") eq "MARC21"
304 and 500 <= $tag && $tag < 600
307 # oversize field (textarea)
308 $subfield_data{marc_value} = {
310 id => $subfield_data{id},
314 # it's a standard field
315 $subfield_data{marc_value} = {
317 id => $subfield_data{id},
318 maxlength => $subfield_data{max_length},
323 # Getting list of subfields to keep when restricted editing is enabled
324 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
325 my $allowAllSubfields = (
326 not defined $subfieldsToAllowForRestrictedEditing
327 or $subfieldsToAllowForRestrictedEditing == q||
329 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
331 # If we're on restricted editing, and our field is not in the list of subfields to allow,
332 # then it is read-only
333 $subfield_data{marc_value}->{readonly} = (
334 not $allowAllSubfields
335 and $restrictededition
336 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
339 return \%subfield_data;
342 # Removes some subfields when prefilling items
343 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
344 sub removeFieldsForPrefill {
349 my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
351 # Getting list of subfields to keep
352 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
354 # Removing subfields that are not in the syspref
355 if ($tag && $subfieldsToUseWhenPrefill) {
356 my $field = $item->field($tag);
357 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
358 foreach my $subfield ($field->subfields()) {
359 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
360 $field->delete_subfield(code => $subfield->[0]);
371 my $error = $input->param('error');
372 my $biblionumber = $input->param('biblionumber');
373 my $itemnumber = $input->param('itemnumber');
374 my $op = $input->param('op');
375 my $hostitemnumber = $input->param('hostitemnumber');
376 my $marcflavour = C4::Context->preference("marcflavour");
377 my $searchid = $input->param('searchid');
378 # fast cataloguing datas
379 my $fa_circborrowernumber = $input->param('circborrowernumber');
380 my $fa_barcode = $input->param('barcode');
381 my $fa_branch = $input->param('branch');
382 my $fa_stickyduedate = $input->param('stickyduedate');
383 my $fa_duedatespec = $input->param('duedatespec');
385 my $frameworkcode = &GetFrameworkCode($biblionumber);
387 # Defining which userflag is needing according to the framework currently used
389 if (defined $input->param('frameworkcode')) {
390 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
393 if (not defined $userflags) {
394 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
397 my ($template, $loggedinuser, $cookie)
398 = get_template_and_user({template_name => "cataloguing/additem.tt",
401 authnotrequired => 0,
402 flagsrequired => {editcatalogue => $userflags},
407 # Does the user have a restricted item editing permission?
408 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
409 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
410 # In case user is a superlibrarian, editing is not restricted
411 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
412 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
413 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
415 my $tagslib = &GetMarcStructure(1,$frameworkcode);
416 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
417 my $oldrecord = TransformMarcToKoha($record);
419 my $nextop="additem";
420 my @errors; # store errors found while checking data BEFORE saving item.
422 # Getting last created item cookie
423 my $prefillitem = C4::Context->preference('PrefillItem');
425 my $cookieitemrecord;
427 my $lastitemcookie = $input->cookie('LastCreatedItem');
428 if ($lastitemcookie) {
429 $lastitemcookie = uri_unescape($lastitemcookie);
431 if ( thaw($lastitemcookie) ) {
432 $cookieitemrecord = thaw($lastitemcookie);
433 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
437 $lastitemcookie = 'undef' unless $lastitemcookie;
438 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
443 #-------------------------------------------------------------------------------
444 if ($op eq "additem") {
446 #-------------------------------------------------------------------------------
448 my @tags = $input->multi_param('tag');
449 my @subfields = $input->multi_param('subfield');
450 my @values = $input->multi_param('field_value');
451 # build indicator hash.
452 my @ind_tag = $input->multi_param('ind_tag');
453 my @indicator = $input->multi_param('indicator');
454 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
455 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
458 my $add_submit = $input->param('add_submit');
459 my $add_duplicate_submit = $input->param('add_duplicate_submit');
460 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
461 my $number_of_copies = $input->param('number_of_copies');
463 # This is a bit tricky : if there is a cookie for the last created item and
464 # we just added an item, the cookie value is not correct yet (it will be updated
465 # next page). To prevent the form from being filled with outdated values, we
466 # force the use of "add and duplicate" feature, so the form will be filled with
468 $add_duplicate_submit = 1 if ($prefillitem);
471 # if autoBarcode is set to 'incremental', calculate barcode...
472 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
473 $record = _increment_barcode($record, $frameworkcode);
476 my $addedolditem = TransformMarcToKoha( $record );
478 # If we have to add or add & duplicate, we add the item
479 if ( $add_submit || $add_duplicate_submit ) {
481 # check for item barcode # being unique
482 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
483 push @errors, "barcode_not_unique" if ($exist_itemnumber);
485 # if barcode exists, don't create, but report The problem.
486 unless ($exist_itemnumber) {
487 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
488 set_item_default_location($oldbibitemnum);
490 # Pushing the last created item cookie back
491 if ($prefillitem && defined $record) {
492 my $itemcookie = $input->cookie(
493 -name => 'LastCreatedItem',
494 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
495 -value => uri_escape_utf8( freeze( $record ) ),
500 $cookie = [ $cookie, $itemcookie ];
505 if ($exist_itemnumber) {
506 $itemrecord = $record;
510 # If we have to add & duplicate
511 if ($add_duplicate_submit) {
512 $itemrecord = $record;
513 if (C4::Context->preference('autoBarcode') eq 'incremental') {
514 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
517 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
518 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
519 my $fieldItem = $itemrecord->field($tagfield);
520 $itemrecord->delete_field($fieldItem);
521 $fieldItem->delete_subfields($tagsubfield);
522 $itemrecord->insert_fields_ordered($fieldItem);
524 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
527 # If we have to add multiple copies
528 if ($add_multiple_copies_submit) {
531 my $barcodeobj = C4::Barcodes->new;
532 my $oldbarcode = $addedolditem->{'barcode'};
533 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
535 # If there is a barcode and we can't find their new values, we can't add multiple copies
537 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
538 if ($oldbarcode && !$testbarcode) {
540 push @errors, "no_next_barcode";
541 $itemrecord = $record;
546 # For the first iteration
547 my $barcodevalue = $oldbarcode;
548 my $exist_itemnumber;
551 for (my $i = 0; $i < $number_of_copies;) {
553 # If there is a barcode
556 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
557 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
559 # Putting it into the record
561 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
564 # Checking if the barcode already exists
565 $exist_itemnumber = get_item_from_barcode($barcodevalue);
569 if (!$exist_itemnumber) {
570 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
571 set_item_default_location($oldbibitemnum);
573 # We count the item only if it was really added
574 # That way, all items are added, even if there was some already existing barcodes
575 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
579 # Preparing the next iteration
580 $oldbarcode = $barcodevalue;
585 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
586 print $input->redirect(
587 '/cgi-bin/koha/circ/circulation.pl?'
588 .'borrowernumber='.$fa_circborrowernumber
589 .'&barcode='.uri_escape_utf8($fa_barcode)
590 .'&duedatespec='.$fa_duedatespec
597 #-------------------------------------------------------------------------------
598 } elsif ($op eq "edititem") {
599 #-------------------------------------------------------------------------------
600 # retrieve item if exist => then, it's a modif
601 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
602 $nextop = "saveitem";
603 #-------------------------------------------------------------------------------
604 } elsif ($op eq "dupeitem") {
605 #-------------------------------------------------------------------------------
606 # retrieve item if exist => then, it's a modif
607 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
608 if (C4::Context->preference('autoBarcode') eq 'incremental') {
609 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
612 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
613 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
614 my $fieldItem = $itemrecord->field($tagfield);
615 $itemrecord->delete_field($fieldItem);
616 $fieldItem->delete_subfields($tagsubfield);
617 $itemrecord->insert_fields_ordered($fieldItem);
620 #check for hidden subfield and remove them for the duplicated item
621 foreach my $field ($itemrecord->fields()){
622 my $tag = $field->{_tag};
623 foreach my $subfield ($field->subfields()){
624 my $subfieldtag = $subfield->[0];
625 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
626 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
627 my $fieldItem = $itemrecord->field($tag);
628 $itemrecord->delete_field($fieldItem);
629 $fieldItem->delete_subfields($subfieldtag);
630 $itemrecord->insert_fields_ordered($fieldItem);
635 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
637 #-------------------------------------------------------------------------------
638 } elsif ($op eq "delitem") {
639 #-------------------------------------------------------------------------------
640 # check that there is no issue on this item before deletion.
641 $error = &DelItemCheck( $biblionumber,$itemnumber);
643 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
648 #-------------------------------------------------------------------------------
649 } elsif ($op eq "delallitems") {
650 #-------------------------------------------------------------------------------
651 my $itemnumbers = C4::Items::GetItemnumbersForBiblio( $biblionumber );
652 foreach my $itemnumber ( @$itemnumbers ) {
653 $error = C4::Items::DelItemCheck( $biblionumber, $itemnumber );
654 next if $error == 1; # Means ok
660 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
661 my $views = { C4::Search::enabled_staff_search_views };
662 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
663 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
664 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
665 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
666 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
667 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
669 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
673 #-------------------------------------------------------------------------------
674 } elsif ($op eq "saveitem") {
675 #-------------------------------------------------------------------------------
677 my @tags = $input->multi_param('tag');
678 my @subfields = $input->multi_param('subfield');
679 my @values = $input->multi_param('field_value');
680 # build indicator hash.
681 my @ind_tag = $input->multi_param('ind_tag');
682 my @indicator = $input->multi_param('indicator');
683 # my $itemnumber = $input->param('itemnumber');
684 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
685 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
686 # MARC::Record builded => now, record in DB
687 # warn "R: ".$record->as_formatted;
688 # check that the barcode don't exist already
689 my $addedolditem = TransformMarcToKoha($itemtosave);
690 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
691 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
692 push @errors,"barcode_not_unique";
694 ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
697 my $item = GetItem( $itemnumber );
698 my $olditemlost = $item->{'itemlost'};
700 my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
702 my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
703 if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
704 LostItem($itemnumber);
707 } elsif ($op eq "delinkitem"){
708 my $analyticfield = '773';
709 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
710 $analyticfield = '773';
711 } elsif ($marcflavour eq 'UNIMARC') {
712 $analyticfield = '461';
714 foreach my $field ($record->field($analyticfield)){
715 if ($field->subfield('9') eq $hostitemnumber){
716 $record->delete_field($field);
720 my $modbibresult = ModBiblio($record, $biblionumber,'');
724 #-------------------------------------------------------------------------------
725 # build screen with existing items. and "new" one
726 #-------------------------------------------------------------------------------
728 # now, build existiing item list
729 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
730 #my @fields = $record->fields();
733 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
735 #---- finds where items.itemnumber is stored
736 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
737 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
738 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
739 my @fields = $temp->fields();
743 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
744 my $analyticfield = '773';
745 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
746 $analyticfield = '773';
747 } elsif ($marcflavour eq 'UNIMARC') {
748 $analyticfield = '461';
750 foreach my $hostfield ($temp->field($analyticfield)){
751 my $hostbiblionumber = $hostfield->subfield('0');
752 if ($hostbiblionumber){
753 my $hostrecord = GetMarcBiblio({
754 biblionumber => $hostbiblionumber,
757 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
758 foreach my $hostitem ($hostrecord->field($itemfield)){
759 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
760 push (@fields, $hostitem);
761 push (@hostitemnumbers, $hostfield->subfield('9'));
770 foreach my $field (@fields) {
771 next if ( $field->tag() < 10 );
773 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
775 # loop through each subfield
777 foreach my $subfield (@subf){
778 my $subfieldcode = $subfield->[0];
779 my $subfieldvalue= $subfield->[1];
781 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
782 && ($field->tag() ne $itemtagfield
783 && $subfieldcode ne $itemtagsubfield));
784 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
785 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
786 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
787 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
788 $subfieldcode, $subfieldvalue, '', $tagslib)
792 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
794 my $userenv = C4::Context->userenv();
795 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
796 $this_row{'nomod'} = 1;
799 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
801 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
802 foreach my $hostitemnumber (@hostitemnumbers){
803 my $item = Koha::Items->find( $hostitemnumber );
804 if ($this_row{itemnumber} eq $hostitemnumber){
805 $this_row{hostitemflag} = 1;
806 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
811 # my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
812 # if ($countanalytics > 0){
813 # $this_row{countanalytics} = $countanalytics;
819 push(@big_array, \%this_row);
823 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
824 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
826 # now, construct template !
827 # First, the existing items for display
829 my @header_value_loop;
830 for my $row ( @big_array ) {
832 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
833 $row_data{item_value} = [ @item_fields ];
834 $row_data{itemnumber} = $row->{itemnumber};
835 #reporting this_row values
836 $row_data{'nomod'} = $row->{'nomod'};
837 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
838 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
839 # $row_data{'countanalytics'} = $row->{'countanalytics'};
840 push(@item_value_loop,\%row_data);
842 foreach my $subfield_code (sort keys(%witness)) {
844 $header_value{header_value} = $witness{$subfield_code};
846 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
847 my $kohafield = $subfieldlib->{kohafield};
848 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
849 $header_value{column_name} = $1;
852 push(@header_value_loop, \%header_value);
855 # now, build the item form for entering a new item
859 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
861 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
862 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
863 for my $library ( @$libraries ) {
864 $library->{selected} = 1 if $library->{branchcode} eq $branch
867 # We generate form, from actuel record
870 foreach my $field ($itemrecord->fields()){
871 my $tag = $field->{_tag};
872 foreach my $subfield ( $field->subfields() ){
874 my $subfieldtag = $subfield->[0];
875 my $value = $subfield->[1];
876 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
878 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
880 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
881 push @fields, "$tag$subfieldtag";
882 push (@loop_data, $subfield_data);
888 # and now we add fields that are empty
890 # Using last created item if it exists
892 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
894 # We generate form, and fill with values if defined
895 foreach my $tag ( keys %{$tagslib}){
896 foreach my $subtag (keys %{$tagslib->{$tag}}){
897 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
898 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
899 next if any { /^$tag$subtag$/ } @fields;
901 my @values = (undef);
902 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
903 for my $value (@values){
904 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
905 push (@loop_data, $subfield_data);
910 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
912 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
914 biblionumber => $biblionumber,
915 title => $oldrecord->{title},
916 author => $oldrecord->{author},
917 item_loop => \@item_value_loop,
918 item_header_loop => \@header_value_loop,
920 itemnumber => $itemnumber,
921 barcode => GetBarcodeFromItemnumber($itemnumber),
922 itemtagfield => $itemtagfield,
923 itemtagsubfield => $itemtagsubfield,
925 opisadd => ($nextop eq "saveitem") ? 0 : 1,
926 popup => scalar $input->param('popup') ? 1: 0,
927 C4::Search::enabled_staff_search_views,
929 $template->{'VARS'}->{'searchid'} = $searchid;
931 if ($frameworkcode eq 'FA'){
932 # fast cataloguing datas
934 'circborrowernumber' => $fa_circborrowernumber,
935 'barcode' => $fa_barcode,
936 'branch' => $fa_branch,
937 'stickyduedate' => $fa_stickyduedate,
938 'duedatespec' => $fa_duedatespec,
942 foreach my $error (@errors) {
943 $template->param($error => 1);
945 output_html_with_http_headers $input, $cookie, $template->output;